text
stringlengths 0
3.34M
|
---|
#pragma once
#include <nano/boost/asio.hpp>
#include <boost/property_tree/ptree.hpp>
#include <atomic>
#include <string>
namespace nano
{
namespace ipc
{
/**
* The IPC framing format is simple: preamble followed by an encoding specific payload.
* Preamble is uint8_t {'N', encoding_type, reserved, reserved}. Reserved bytes MUST be zero.
* @note This is intentionally not an enum class as the values are only used as vector indices.
*/
enum preamble_offset
{
/** Always 'N' */
lead = 0,
/** One of the payload_encoding values */
encoding = 1,
/** Always zero */
reserved_1 = 2,
/** Always zero */
reserved_2 = 3,
};
/** Abstract base type for sockets, implementing timer logic and a close operation */
class socket_base
{
public:
socket_base (boost::asio::io_context & io_ctx_a);
virtual ~socket_base () = default;
/** Close socket */
virtual void close () = 0;
/**
* Start IO timer.
* @param timeout_a Seconds to wait. To wait indefinitely, use std::chrono::seconds::max ()
*/
void timer_start (std::chrono::seconds timeout_a);
void timer_expired ();
void timer_cancel ();
private:
/** IO operation timer */
boost::asio::deadline_timer io_timer;
};
/**
* Payload encodings; add protobuf, flatbuffers and so on as needed.
*/
enum class payload_encoding : uint8_t
{
/**
* Request is preamble followed by 32-bit BE payload length and payload bytes.
* Response is 32-bit BE payload length followed by payload bytes.
*/
json_legacy = 0x1,
/** Request/response is same as json_legacy and exposes unsafe RPC's */
json_unsafe = 0x2
};
/** IPC transport interface */
class transport
{
public:
virtual void stop () = 0;
virtual ~transport () = default;
};
/** The domain socket file is attempted to be removed at both startup and shutdown. */
class dsock_file_remover final
{
public:
dsock_file_remover (std::string const & file_a);
~dsock_file_remover ();
private:
std::string filename;
};
}
}
|
/-
Copyright (c) 2022 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker
-/
import topology.uniform_space.uniform_convergence
import topology.uniform_space.pi
/-!
# Topology and uniform structure of uniform convergence
This files endows `α → β` with the topologies / uniform structures of
- uniform convergence on `α` (in the `uniform_convergence` namespace)
- uniform convergence on a specified family `𝔖` of sets of `α`
(in the `uniform_convergence_on` namespace), also called `𝔖`-convergence
Usual examples of the second construction include :
- the topology of compact convergence, when `𝔖` is the set of compacts of `α`
- the strong topology on the dual of a TVS `E`, when `𝔖` is the set of Von Neuman bounded subsets
of `E`
- the weak-* topology on the dual of a TVS `E`, when `𝔖` is the set of singletons of `E`.
## Main definitions
* `uniform_convergence.gen` : basis sets for the uniformity of uniform convergence
* `uniform_convergence.uniform_space` : uniform structure of uniform convergence
* `uniform_convergence_on.uniform_space` : uniform structure of 𝔖-convergence
## Main statements
* `uniform_convergence.uniform_continuous_eval` : evaluation is uniformly continuous
* `uniform_convergence.t2_space` : the topology of uniform convergence on `α → β` is T2 if
`β` is T2.
* `uniform_convergence.tendsto_iff_tendsto_uniformly` : `uniform_convergence.uniform_space` is
indeed the uniform structure of uniform convergence
* `uniform_convergence_on.uniform_continuous_eval_of_mem` : evaluation at a point contained in a
set of `𝔖` is uniformly continuous
* `uniform_convergence.t2_space` : the topology of `𝔖`-convergence on `α → β` is T2 if
`β` is T2 and `𝔖` covers `α`
* `uniform_convergence_on.tendsto_iff_tendsto_uniformly_on` :
`uniform_convergence_on.uniform_space` is indeed the uniform structure of `𝔖`-convergence
## Implementation details
We do not declare these structures as instances, since they would conflict with `Pi.uniform_space`.
## TODO
* Show that the uniform structure of `𝔖`-convergence is exactly the structure of `𝔖'`-convergence,
where `𝔖'` is the bornology generated by `𝔖`.
* Add a type synonym for `α → β` endowed with the structures of uniform convergence
## References
* [N. Bourbaki, *General Topology*][bourbaki1966]
## Tags
uniform convergence
-/
noncomputable theory
open_locale topological_space classical uniformity filter
local attribute [-instance] Pi.uniform_space
open set filter
namespace uniform_convergence
variables (α β : Type*) {γ ι : Type*}
variables {F : ι → α → β} {f : α → β} {s s' : set α} {x : α} {p : filter ι} {g : ι → α}
/-- Basis sets for the uniformity of uniform convergence -/
protected def gen (V : set (β × β)) : set ((α → β) × (α → β)) :=
{uv : (α → β) × (α → β) | ∀ x, (uv.1 x, uv.2 x) ∈ V}
variables [uniform_space β]
protected lemma is_basis_gen :
is_basis (λ V : set (β × β), V ∈ 𝓤 β) (uniform_convergence.gen α β) :=
⟨⟨univ, univ_mem⟩, λ U V hU hV, ⟨U ∩ V, inter_mem hU hV, λ uv huv,
⟨λ x, (huv x).left, λ x, (huv x).right⟩⟩⟩
/-- Filter basis for the uniformity of uniform convergence -/
protected def uniformity_basis : filter_basis ((α → β) × (α → β)) :=
(uniform_convergence.is_basis_gen α β).filter_basis
/-- Core of the uniform structure of uniform convergence -/
protected def uniform_core : uniform_space.core (α → β) :=
uniform_space.core.mk_of_basis (uniform_convergence.uniformity_basis α β)
(λ U ⟨V, hV, hVU⟩ f, hVU ▸ λ x, refl_mem_uniformity hV)
(λ U ⟨V, hV, hVU⟩, hVU ▸ ⟨uniform_convergence.gen α β (prod.swap ⁻¹' V),
⟨prod.swap ⁻¹' V, tendsto_swap_uniformity hV, rfl⟩, λ uv huv x, huv x⟩)
(λ U ⟨V, hV, hVU⟩, hVU ▸ let ⟨W, hW, hWV⟩ := comp_mem_uniformity_sets hV in
⟨uniform_convergence.gen α β W, ⟨W, hW, rfl⟩, λ uv ⟨w, huw, hwv⟩ x, hWV
⟨w x, by exact ⟨huw x, hwv x⟩⟩⟩)
/-- Uniform structure of uniform convergence -/
protected def uniform_space : uniform_space (α → β) :=
uniform_space.of_core (uniform_convergence.uniform_core α β)
protected lemma has_basis_uniformity :
(@uniformity (α → β) (uniform_convergence.uniform_space α β)).has_basis (λ V, V ∈ 𝓤 β)
(uniform_convergence.gen α β) :=
(uniform_convergence.is_basis_gen α β).has_basis
/-- Topology of uniform convergence -/
protected def topological_space : topological_space (α → β) :=
(uniform_convergence.uniform_space α β).to_topological_space
protected lemma has_basis_nhds :
(@nhds (α → β) (uniform_convergence.topological_space α β) f).has_basis (λ V, V ∈ 𝓤 β)
(λ V, {g | (g, f) ∈ uniform_convergence.gen α β V}) :=
begin
letI : uniform_space (α → β) := uniform_convergence.uniform_space α β,
exact nhds_basis_uniformity (uniform_convergence.has_basis_uniformity α β)
end
variables {α}
lemma uniform_continuous_eval (x : α) : @uniform_continuous _ _
(uniform_convergence.uniform_space α β) _ (function.eval x) :=
begin
change _ ≤ _,
rw [map_le_iff_le_comap,
(uniform_convergence.has_basis_uniformity α β).le_basis_iff ((𝓤 _).basis_sets.comap _)],
exact λ U hU, ⟨U, hU, λ uv huv, huv x⟩
end
variables {β}
lemma t2_space [t2_space β] : @t2_space _ (uniform_convergence.topological_space α β) :=
{ t2 :=
begin
letI : uniform_space (α → β) := uniform_convergence.uniform_space α β,
letI : topological_space (α → β) := uniform_convergence.topological_space α β,
intros f g h,
obtain ⟨x, hx⟩ := not_forall.mp (mt funext h),
exact separated_by_continuous (uniform_continuous_eval β x).continuous hx
end }
protected lemma le_Pi : uniform_convergence.uniform_space α β ≤ Pi.uniform_space (λ _, β) :=
begin
rw [le_iff_uniform_continuous_id, uniform_continuous_pi],
intros x,
exact uniform_continuous_eval β x
end
protected lemma tendsto_iff_tendsto_uniformly :
tendsto F p (@nhds _ (uniform_convergence.topological_space α β) f) ↔
tendsto_uniformly F f p :=
begin
letI : uniform_space (α → β) := uniform_convergence.uniform_space α β,
rw [(uniform_convergence.has_basis_nhds α β).tendsto_right_iff, tendsto_uniformly],
split;
{ intros h U hU,
filter_upwards [h (prod.swap ⁻¹' U) (tendsto_swap_uniformity hU)],
exact λ n, id }
end
variable {α}
end uniform_convergence
namespace uniform_convergence_on
variables (α β : Type*) {γ ι : Type*} [uniform_space β] (𝔖 : set (set α))
variables {F : ι → α → β} {f : α → β} {s s' : set α} {x : α} {p : filter ι} {g : ι → α}
/-- Uniform structure of uniform convergence on the sets of `𝔖`. -/
protected def uniform_space : uniform_space (α → β) :=
⨅ (s : set α) (hs : s ∈ 𝔖), uniform_space.comap (λ f, s.restrict f)
(uniform_convergence.uniform_space s β)
/-- Topology of uniform convergence on the sets of `𝔖`. -/
protected def topological_space : topological_space (α → β) :=
(uniform_convergence_on.uniform_space α β 𝔖).to_topological_space
protected lemma topological_space_eq :
uniform_convergence_on.topological_space α β 𝔖 = ⨅ (s : set α) (hs : s ∈ 𝔖),
topological_space.induced (λ f, s.restrict f) (uniform_convergence.topological_space s β) :=
begin
simp only [uniform_convergence_on.topological_space, to_topological_space_infi,
to_topological_space_infi, to_topological_space_comap],
refl
end
protected lemma uniform_continuous_restrict (h : s ∈ 𝔖) :
@uniform_continuous _ _ (uniform_convergence_on.uniform_space α β 𝔖)
(uniform_convergence.uniform_space s β) s.restrict :=
begin
change _ ≤ _,
rw [uniform_convergence_on.uniform_space, map_le_iff_le_comap, uniformity, infi_uniformity],
refine infi_le_of_le s _,
rw infi_uniformity,
exact infi_le _ h,
end
protected lemma uniform_space_antitone : antitone (uniform_convergence_on.uniform_space α β) :=
λ 𝔖₁ 𝔖₂ h₁₂, infi_le_infi_of_subset h₁₂
variables {α}
lemma uniform_continuous_eval_of_mem {x : α} (hxs : x ∈ s) (hs : s ∈ 𝔖) :
@uniform_continuous _ _ (uniform_convergence_on.uniform_space α β 𝔖) _ (function.eval x) :=
begin
change _ ≤ _,
rw [map_le_iff_le_comap, ((𝓤 _).basis_sets.comap _).ge_iff,
uniform_convergence_on.uniform_space, infi_uniformity'],
intros U hU,
refine mem_infi_of_mem s _,
rw infi_uniformity',
exact mem_infi_of_mem hs (mem_comap.mpr
⟨ uniform_convergence.gen s β U,
(uniform_convergence.has_basis_uniformity s β).mem_of_mem hU,
λ uv huv, huv ⟨x, hxs⟩ ⟩)
end
variables {β}
lemma t2_space_of_covering [t2_space β] (h : ⋃₀ 𝔖 = univ) :
@t2_space _ (uniform_convergence_on.topological_space α β 𝔖) :=
{ t2 :=
begin
letI : uniform_space (α → β) := uniform_convergence_on.uniform_space α β 𝔖,
letI : topological_space (α → β) := uniform_convergence_on.topological_space α β 𝔖,
intros f g hfg,
obtain ⟨x, hx⟩ := not_forall.mp (mt funext hfg),
obtain ⟨s, hs, hxs⟩ : ∃ s ∈ 𝔖, x ∈ s := mem_sUnion.mp (h.symm ▸ true.intro),
exact separated_by_continuous (uniform_continuous_eval_of_mem β 𝔖 hxs hs).continuous hx
end }
protected lemma le_Pi_of_covering (h : ⋃₀ 𝔖 = univ) :
uniform_convergence_on.uniform_space α β 𝔖 ≤ Pi.uniform_space (λ _, β) :=
begin
rw [le_iff_uniform_continuous_id, uniform_continuous_pi],
intros x,
obtain ⟨s, hs, hxs⟩ : ∃ s ∈ 𝔖, x ∈ s := mem_sUnion.mp (h.symm ▸ true.intro),
exact uniform_continuous_eval_of_mem β 𝔖 hxs hs
end
protected lemma tendsto_iff_tendsto_uniformly_on :
tendsto F p (@nhds _ (uniform_convergence_on.topological_space α β 𝔖) f) ↔
∀ s ∈ 𝔖, tendsto_uniformly_on F f p s :=
begin
letI : uniform_space (α → β) := uniform_convergence_on.uniform_space α β 𝔖,
rw [uniform_convergence_on.topological_space_eq, nhds_infi, tendsto_infi],
refine forall_congr (λ s, _),
rw [nhds_infi, tendsto_infi],
refine forall_congr (λ hs, _),
rw [nhds_induced, tendsto_comap_iff, tendsto_uniformly_on_iff_tendsto_uniformly_comp_coe,
uniform_convergence.tendsto_iff_tendsto_uniformly],
refl
end
end uniform_convergence_on
|
# Bayesian Logistic Regression
Contact: [email protected]
Aim of this colab:
Logistic regression with a twist! We will use variational inference to learn a distribution over the learned parameters.
Througout this work we will be focusing on a binary classification task, on
a small dataset (the UCD breast cancer dataset).
## Logistic regression
Learn the weights which best classify the $(x, y)$ pairs in the dataset.
The weights ($w$) and biases $b$, form the parameters which are learned via the following maximization problem:
\begin{equation}
\mathbb{E}_{p^*(x, y)} \log p(y|x, \theta) = \\
\mathbb{E}_{p^*(x, y)} \left[y \log \sigma(w x + b) + (1 - y) \log(1- \sigma(w x + b)\right]
\end{equation}
Here $\sigma$ denotes the sigmoid function.
## Bayesian logistic regression - computing the evidence lower bound
Learn a distribution over the weights which best classify the $(x, y)$ pairs in the dataset.
We now want to learn the distributional parameters of $q(w)$ in order to maximize:
\begin{equation}
\mathbb{E}_{p^*(x, y)} \log p_w(y| x) = \\
\mathbb{E}_{p^*(x, y)} \log \int p(y|x, w) p(w) \delta w = \\
\mathbb{E}_{p^*(x, y)} \log \int p(y|x, w) p(w) \frac{q(w)}{q(w)} \delta w \ge \\
\mathbb{E}_{p^*(x, y)} \mathbb{E}_{q(w)} \log \left[p(y| x, w) \frac{p(w)}{q(w)} \right]= \\
\mathbb{E}_{q(w)} \mathbb{E}_{p^*(x, y)} \log p(y|x, w) - KL(q(w)||p(w)) = \\
\mathbb{E}_{q(w)}\mathbb{E}_{p^*(x, y)} \left[y \log \sigma(w x + b) + (1 - y) \log(1- \sigma(w x + b)\right] - KL(q(w)||p(w))
\end{equation}
In Bayesian Logistic Regression, we thus learn a distribution over parameters
$w$ which can explain the data, while staying close to a chosen prior $p(w)$.
Throughout this lab, we will use Gaussian Distributions for $p(w)$ and $q(w)$.
For more details, see
[this paper](https://pdfs.semanticscholar.org/e407/ea7fda6d152d2186f4b5e27aa04ec2d32dcd.pdf)
or this tutorial
[https://www.ece.rice.edu/~vc3/elec633/logistic.pdf].
### Gradient estimation
In Bayesian Logistic Regression, we aim to learn the parameters of the distribution $q(w)$. We will call these parameters $\theta$. In the case of a
Gaussian distribution, these will be the mean and covariance matrix of a
multivariate distribution. Since we will use stochastic gradient descent to learn $\theta$, we need to be able to compute the gradients with respect to
$\theta$ of our objective. Since our objective contains an expectation with respect to $q(w)$, this can be challenging. To illustrate this, from now on we will denote $q(w)$ as $q_{\theta}(w)$.
Specifically, we are interested in:
\begin{equation}
\nabla_{\theta} \left[\mathbb{E}_{q_{\theta}(w)} \mathbb{E}_{p^*(x, y)} \log p(y|x, w) - KL(q_{\theta}(w)||p(w))\right]
\end{equation}
Since in we will be using Gaussian distributions for $q_{\theta}(w)$ and $p(w)$
$KL(q_{\theta}(w)||p(w))$ can be computed in closed form and we can rely on
TensorFlow's automatic differentiation to compute
$\nabla_{\theta} KL(q_{\theta}(w)||p(w))$.
Let's now turn attention to computing $\nabla_{\theta} \mathbb{E}_{q_{\theta}(w)} \mathbb{E}_{p^*(x, y)} \log p(y| x, w)$. Unlike the KL, the integral
$\mathbb{E}_{q_{\theta}(w)} \mathbb{E}_{p^*(x, y)} \log p(y|x, w)$
is not tractable, and thus cannot be computed in closed form. Thus, we are interested in other approaches to compute the gradient.
### Reinforce gradient estimation
A first approach to compute an estimate of the gradient is to use the
REINFORCE gradient estimator:
\begin{equation}
\nabla_{\theta} \mathbb{E}_{q_{\theta}(w)} \mathbb{E}_{p^*(x, y)} \log p(y| x, w) = \\
\nabla_{\theta} \int q_{\theta}(w) \mathbb{E}_{p^*(x, y)} \log p(y| x, w) \delta w = \\
\int \nabla_{\theta} \left[q_{\theta}(w) \mathbb{E}_{p^*(x, y)} \log p(y| x, w) \right] \delta w = \\
\int \nabla_{\theta} \left[q_{\theta}(w)\right] \mathbb{E}_{p^*(x, y)} \log p(y| x, w) \delta w = \\
\int q_{\theta}(w) \nabla_{\theta} \left[\log q_{\theta}(w)\right] \mathbb{E}_{p^*(x, y)} \log p(y| x, w) \delta w = \\
\mathbb{E}_{q_{\theta}(w)} \left[ \nabla_{\theta} \log q_{\theta}(w) \mathbb{E}_{p^*(x, y)} \log p(y| x, w) \right]
\end{equation}
We can use samples from $q_{\theta}(w)$ to compute the Monte Carlo estimate of
the last integral, to get an unbiased estimator of the true gradient. The more
samples we use to estimate the integral, the more accurate the gradient estimate
will be.
### Pathwise gradient estimation (reparametrization)
In the REINFORCE estimator, we did not use any knowledge of the variational
distribution $q_{\theta}(w)$.
For a Gaussian distribution, we can use the reparametrization trick to obtain
an unbiased gradient estimator of $\nabla_{\theta} \mathbb{E}_{q_{\theta}(w)} \mathbb{E}_{p^*(x, y)} \log p(y| x, w)$.
To do so, we will use the fact that
\begin{equation}
z \sim N(\mu, \sigma), z = \mu + \epsilon \sigma, {\text {with }} \epsilon \sim N(0, 1)
\end{equation}
Namely:
\begin{equation}
\nabla_{\theta} \mathbb{E}_{q_{\theta}(w)} \mathbb{E}_{p^*(x, y)} \log p(y| x, w) = \\
\nabla_{\theta} \mathbb{E}_{p(\epsilon)} \mathbb{E}_{p^*(x, y)} \log p(y| x, \mu + \epsilon \sigma) = \\
\mathbb{E}_{p(\epsilon)} \nabla_{\theta} \mathbb{E}_{p^*(x, y)} \log p(y| x, \mu + \epsilon \sigma)
\end{equation}
Note that we were able to move the gradient inside the integral since
$p(\epsilon)$ does not depend on $\theta$.
To estimate the last integral, we can use a Monte Carlo estimate using samples
of $p(\epsilon)$.
## Your tasks
* Define the Gaussian posterior distribution.
* Fill in the code for the ELBO
* Fill in the reinforce function to create the surrogate loss
* Fill in the loss function for reparametrization
* Visualize the effects of batch size, learning rates and number of posterior samples on the learned model, as well as gradient variance.
```
import enum
import numpy as np
import math
from sklearn import datasets
from sklearn import linear_model
import collections
from matplotlib import pyplot as plt
import tensorflow as tf
import tensorflow_probability as tfp
import seaborn as sns
tfd = tfp.distributions
```
```
sns.set(rc={"lines.linewidth": 2.8}, font_scale=2)
sns.set_style("whitegrid")
```
## Get the dataset and visualize it
```
def get_data(normalize = True):
data = datasets.load_breast_cancer()
print(data.target_names)
print(data.feature_names)
features = np.array(data.data, dtype=np.float32)
targets = np.array(data.target, dtype=np.float32)
if normalize:
# Note: the data dimensions have very different scales.
# We normalize by the mean and scale of the entire dataset.
features = features - features.mean(axis=0)
features = features / features.std(axis=0)
# Add a dimension of 1 (bias).
features = np.concatenate((features, np.ones((features.shape[0], 1))), axis=1)
features = np.array(features, dtype=np.float32)
return features, targets, data.feature_names
```
### Dataset
This datasets has meaningful features: we are trying to classify based on these features whether someone has breast cancer or not. We can look at the
features we are using to classify the data below.
```
features, targets, feature_names = get_data()
```
['malignant' 'benign']
['mean radius' 'mean texture' 'mean perimeter' 'mean area'
'mean smoothness' 'mean compactness' 'mean concavity'
'mean concave points' 'mean symmetry' 'mean fractal dimension'
'radius error' 'texture error' 'perimeter error' 'area error'
'smoothness error' 'compactness error' 'concavity error'
'concave points error' 'symmetry error' 'fractal dimension error'
'worst radius' 'worst texture' 'worst perimeter' 'worst area'
'worst smoothness' 'worst compactness' 'worst concavity'
'worst concave points' 'worst symmetry' 'worst fractal dimension']
### Trivial baseline
How well can we do with a constant classifier?
If we look at the average label, we can see how many 1s are in the data, so we know that our classifier has to get more than that accuracy
```
np.mean(targets)
```
0.6274165
```
features.shape
```
(569, 31)
```
dataset_size = features.shape[0]
data_dims = features.shape[-1]
```
## Logistic regression baseline - how well can we do on this dataset?
Let's look at a simple, non Bayesian classification approach to get an idea of how well we can do on the dataset.
```
lr = linear_model.LogisticRegression()
```
```
lr.fit(features, targets)
lr.score(features, targets)
```
/usr/local/lib/python2.7/dist-packages/sklearn/linear_model/logistic.py:433: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
FutureWarning)
0.9876977152899824
## Utilities
```
def get_shape_list(tensor):
return tensor.shape.as_list()
```
```
def get_sklearn_data_as_tensors(
features, targets, batch_size, dataset_name='breast_cancer'):
"""Read sklearn datasets as tf.Tensors.
Args:
batch_size: Integer or None. If None, the entire dataset is used.
dataset_name: A string, the name of the dataset.
Returns:
A tuple of size two containing two tensors of rank 2 `[B, F]`, the data
features and targets.
"""
dataset = tf.data.Dataset.from_tensor_slices((features, targets))
if batch_size:
# Shuffle, repeat, and batch the examples.
batched_dataset = dataset.shuffle(1000).repeat().batch(batch_size)
else:
batch_size = features.shape[0]
batched_dataset = dataset.repeat().batch(batch_size)
iterator = batched_dataset.make_one_shot_iterator()
batch_features, batch_targets = iterator.get_next()
data_dim = features.shape[1]
batch_features.set_shape([batch_size, data_dim])
batch_targets.set_shape([batch_size])
return batch_features, batch_targets
```
## Bayesian Logistic Regression - define the prior and the posterior
We will learn a distribution over parameters, so we will first define prior distribution, and then a posterior distribution over parameters which we
will learn.
Both of these distibutions will be Gaussian.
## Task: implement the posterior distribution
You have to implement two functions
1. multi_normal, which takes as arguments the mean and the log scale of the normal distribution, and returns a tensorflow distribution object. Have a look at the TensorFlow distibutions package.
2. diagonal_gaussian_posterior which returns a tuple of two elements, one being the posterior distribution (a call to multi_normal) and the learned variables. Your task here is to define the variables we will learn. The argument `data_dims` tells you the size of the learned parameters, and thus the size of the variables of the distribution).
```
def multi_normal(loc, log_scale):
return tfp.distributions.MultivariateNormalDiag(loc, tf.math.exp(log_scale))
def diagonal_gaussian_posterior(data_dims):
mean = tf.Variable(tf.zeros([data_dims], dtype=tf.float32), name="mean")
diag = tf.math.log(tf.ones([data_dims], dtype=tf.float32)) # diag log-covariance
log_scale = tf.Variable(diag , name="log_scale")
learned_vars = [mean, log_scale]
return multi_normal(loc=mean, log_scale=log_scale), learned_vars
```
## Bayesian Logistic Regression - the model
### Hypers
```
BATCH_SIZE = 500
NUM_POSTERIOR_SAMPLES = 100
```
```
prior = multi_normal(loc=tf.zeros(data_dims), log_scale=tf.zeros(data_dims))
posterior, learned_vars = diagonal_gaussian_posterior(data_dims)
```
```
def _predictions(logits):
return tf.to_float(logits >= 0)
def _accuracy(targets, predictions):
# `predictions` have rank 2: batch_size, num_posterior samples.
# We expand dims the targets to compute the accuracy per sample.
targets = tf.expand_dims(targets, axis=1)
return tf.reduce_mean(tf.to_float(tf.equal(targets, predictions)))
def linear_model(data, targets, posterior_samples):
num_posterior_samples = tf.shape(posterior_samples)[0]
logits = tf.matmul(data, posterior_samples, transpose_b=True)
# Make targets [B, 1] to use broadcasting.
targets = tf.expand_dims(targets, axis=1)
targets = targets * tf.ones([1, num_posterior_samples])
log_probs = - tf.nn.sigmoid_cross_entropy_with_logits(
labels=targets, logits=logits)
return log_probs, logits
```
## Task: Run the model and return the components of the elbo
```
def run_model(posterior, num_samples):
# Sample from the posterior to obtain a set of parameters used for
# prediction. Use `num_samples` for the number of samples.
posterior_samples = posterior.sample(num_samples)
# Compute the log probs of the data under all the models we have sampled.
# These tensors are [num_samples, B]. Use the features and targets tensors.
log_probs, logits = linear_model(features, targets, posterior_samples)
# Compute the KL between the posterior and the prior.
# Note: since we use Gaussian distributions, the closed form of the
# KL can be computed. Remember that distributions are objects in TensorFlow!
kl = posterior.kl_divergence(prior)
# Sum over data. Normalize by dataset size to ensure that the gradients
# are not very different in magnitude when we change batch size.
param_log_probs = tf.reduce_mean(log_probs, axis=0) * dataset_size
param_log_probs.shape.assert_is_compatible_with([num_samples])
return param_log_probs, kl, posterior_samples, logits
```
```
param_log_probs, kl, posterior_samples, logits = run_model(
posterior, NUM_POSTERIOR_SAMPLES)
predictions = _predictions(logits)
accuracy = _accuracy(targets=targets, predictions=predictions)
accuracy = tf.reduce_mean(accuracy)
```
WARNING: Logging before flag parsing goes to stderr.
W0706 15:10:01.309685 140030529763200 deprecation.py:323] From /usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/nn_impl.py:180: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where
W0706 15:10:01.346157 140030529763200 deprecation.py:323] From <ipython-input-15-e4da80cc1f88>:2: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.cast` instead.
## Task: compute the elbo from the log probs and the KL
`per_sample_elbo` should have shape [num_samples], since we obtain a model prediction for each of the sampled parameters.
```
per_sample_elbo = param_log_probs - kl
elbo = tf.reduce_mean(per_sample_elbo)
```
## Training loop
## Training the model via reparametrization
```
# Stochastic loss depends on the output of a sampling operation (posterior samples)
# but tensorflow implements reparametrization by default.
per_sample_reparametrization_loss = - per_sample_elbo
reparametrization_loss = tf.reduce_mean(per_sample_reparametrization_loss)
```
```
optimizer = tf.train.GradientDescentOptimizer(0.0001)
reparam_min_op = optimizer.minimize(reparametrization_loss)
```
```
NUM_ITERATIONS = 1000
```
```
sess = tf.Session()
# Initialize all variables
sess.run(tf.initialize_all_variables())
reparam_accuracies = []
reparam_kls = []
reparam_elbos = []
for i in xrange(NUM_ITERATIONS):
sess.run(reparam_min_op)
if i % 10 == 0:
reparam_acc, reparam_kl, reparam_elbo = sess.run([accuracy, kl, elbo])
reparam_accuracies += [reparam_acc]
reparam_kls += [reparam_kl]
reparam_elbos += [reparam_elbo]
print('Iteration {}. Elbo {}. KL {}'.format(
i, reparam_elbo, reparam_kl))
reparam_learned_mean, reparam_learned_log_scale = sess.run(learned_vars)
```
W0706 15:10:01.922456 140030529763200 deprecation.py:323] From /usr/local/lib/python2.7/dist-packages/tensorflow/python/util/tf_should_use.py:193: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
Iteration 0. Elbo -1251.31628418. KL 0.00287126004696
Iteration 10. Elbo -697.800720215. KL 0.307448148727
Iteration 20. Elbo -537.026550293. KL 0.765623211861
Iteration 30. Elbo -435.274505615. KL 1.27441883087
Iteration 40. Elbo -351.531005859. KL 1.71919393539
Iteration 50. Elbo -303.941864014. KL 2.16450643539
Iteration 60. Elbo -260.008758545. KL 2.56153178215
Iteration 70. Elbo -263.777099609. KL 2.92100739479
Iteration 80. Elbo -234.770721436. KL 3.26699590683
Iteration 90. Elbo -239.377182007. KL 3.59330368042
Iteration 100. Elbo -224.065063477. KL 3.88889718056
Iteration 110. Elbo -187.876937866. KL 4.17269849777
Iteration 120. Elbo -188.153579712. KL 4.45011806488
Iteration 130. Elbo -175.901901245. KL 4.71661520004
Iteration 140. Elbo -155.265014648. KL 4.97964668274
Iteration 150. Elbo -164.109680176. KL 5.22092580795
Iteration 160. Elbo -153.392990112. KL 5.46521854401
Iteration 170. Elbo -166.389511108. KL 5.70708227158
Iteration 180. Elbo -141.348587036. KL 5.93668699265
Iteration 190. Elbo -144.340988159. KL 6.14716243744
Iteration 200. Elbo -150.441848755. KL 6.34233903885
Iteration 210. Elbo -125.198425293. KL 6.53200817108
Iteration 220. Elbo -144.606735229. KL 6.72982215881
Iteration 230. Elbo -124.996162415. KL 6.90616846085
Iteration 240. Elbo -123.129951477. KL 7.0823802948
Iteration 250. Elbo -116.140907288. KL 7.2649936676
Iteration 260. Elbo -122.178184509. KL 7.44574928284
Iteration 270. Elbo -127.089424133. KL 7.61699581146
Iteration 280. Elbo -126.283309937. KL 7.78921937943
Iteration 290. Elbo -117.368141174. KL 7.95003604889
Iteration 300. Elbo -117.763244629. KL 8.10859680176
Iteration 310. Elbo -115.204460144. KL 8.26020336151
Iteration 320. Elbo -113.344589233. KL 8.4087677002
Iteration 330. Elbo -119.965705872. KL 8.56992721558
Iteration 340. Elbo -113.99962616. KL 8.71299934387
Iteration 350. Elbo -105.818740845. KL 8.86545181274
Iteration 360. Elbo -100.249084473. KL 9.0091381073
Iteration 370. Elbo -110.714012146. KL 9.15460586548
Iteration 380. Elbo -103.108894348. KL 9.28317070007
Iteration 390. Elbo -105.591644287. KL 9.42404651642
Iteration 400. Elbo -111.089073181. KL 9.55483055115
Iteration 410. Elbo -104.87991333. KL 9.67768478394
Iteration 420. Elbo -110.888923645. KL 9.80382919312
Iteration 430. Elbo -103.24887085. KL 9.931016922
Iteration 440. Elbo -109.799942017. KL 10.0544033051
Iteration 450. Elbo -98.0338363647. KL 10.1714935303
Iteration 460. Elbo -100.708076477. KL 10.2848911285
Iteration 470. Elbo -101.14617157. KL 10.3957271576
Iteration 480. Elbo -93.3948516846. KL 10.5126533508
Iteration 490. Elbo -107.306007385. KL 10.6308822632
Iteration 500. Elbo -100.181022644. KL 10.7451038361
Iteration 510. Elbo -95.855255127. KL 10.8539943695
Iteration 520. Elbo -100.132675171. KL 10.9568748474
Iteration 530. Elbo -100.38646698. KL 11.0542888641
Iteration 540. Elbo -94.6835021973. KL 11.1537256241
Iteration 550. Elbo -94.338722229. KL 11.2570905685
Iteration 560. Elbo -90.4855880737. KL 11.357252121
Iteration 570. Elbo -98.0821456909. KL 11.4538021088
Iteration 580. Elbo -93.8483581543. KL 11.5528078079
Iteration 590. Elbo -94.2413787842. KL 11.650138855
Iteration 600. Elbo -84.8176193237. KL 11.7399148941
Iteration 610. Elbo -88.862487793. KL 11.8348445892
Iteration 620. Elbo -90.7114181519. KL 11.9179830551
Iteration 630. Elbo -89.9356384277. KL 12.0149831772
Iteration 640. Elbo -91.7482910156. KL 12.1029577255
Iteration 650. Elbo -89.2460861206. KL 12.1858530045
Iteration 660. Elbo -91.8519744873. KL 12.2712144852
Iteration 670. Elbo -91.9219665527. KL 12.3608808517
Iteration 680. Elbo -90.779586792. KL 12.4472103119
Iteration 690. Elbo -87.8686599731. KL 12.5342903137
Iteration 700. Elbo -88.755279541. KL 12.6139793396
Iteration 710. Elbo -89.0103912354. KL 12.6986293793
Iteration 720. Elbo -91.2760543823. KL 12.7775554657
Iteration 730. Elbo -84.5751495361. KL 12.8627347946
Iteration 740. Elbo -88.3510131836. KL 12.946138382
Iteration 750. Elbo -81.0643081665. KL 13.0226335526
Iteration 760. Elbo -87.4532012939. KL 13.1025733948
Iteration 770. Elbo -85.3113555908. KL 13.1825962067
Iteration 780. Elbo -91.157623291. KL 13.2549219131
Iteration 790. Elbo -82.2567977905. KL 13.3327140808
Iteration 800. Elbo -84.6036605835. KL 13.4073734283
Iteration 810. Elbo -88.7576293945. KL 13.4813165665
Iteration 820. Elbo -86.5616226196. KL 13.5525226593
Iteration 830. Elbo -84.7662887573. KL 13.6196088791
Iteration 840. Elbo -86.3528594971. KL 13.6932125092
Iteration 850. Elbo -81.4763946533. KL 13.7570486069
Iteration 860. Elbo -83.6050796509. KL 13.8267087936
Iteration 870. Elbo -80.9121170044. KL 13.892824173
Iteration 880. Elbo -84.220993042. KL 13.9599637985
Iteration 890. Elbo -81.2252044678. KL 14.0247545242
Iteration 900. Elbo -84.1262969971. KL 14.0935535431
Iteration 910. Elbo -82.5146560669. KL 14.1550140381
Iteration 920. Elbo -85.5831832886. KL 14.2202100754
Iteration 930. Elbo -84.2529678345. KL 14.2814331055
Iteration 940. Elbo -84.1190109253. KL 14.3443193436
Iteration 950. Elbo -82.031288147. KL 14.4068174362
Iteration 960. Elbo -82.321395874. KL 14.4710903168
Iteration 970. Elbo -80.7244949341. KL 14.5387954712
Iteration 980. Elbo -79.9401016235. KL 14.5994224548
Iteration 990. Elbo -82.4692764282. KL 14.6628885269
```
fig, axes = plt.subplots(1, 3, figsize=(3*8,5))
axes[0].plot(reparam_elbos, label='ELBO')
axes[0].set_title('Time', fontsize=15)
axes[0].set_ylim((-500, -50))
axes[0].legend()
axes[1].plot(reparam_kls, label='KL')
axes[1].set_title('Time', fontsize=15)
axes[1].legend()
axes[2].plot(reparam_accuracies, label='Accuracy')
axes[2].set_title('Time', fontsize=15)
axes[2].legend()
```
## Training the model via reinforce
## Task: define the surrogate reinforce loss for the log prob term.
Note: we do not need to use reinforce the KL term, since we can compute the KL analytically for the two Gaussians, and can use standard backprop.
For the reinforce implementation, instead of changing the gradients, we will change the loss such that TensorFlow's automatic differentiation does the right thing. This is called a surrogate loss.
The gradient we want to obtain is the following (since we want to minimize the loss, we add a minus):
\begin{equation}
- \mathbb{E}_{q_{\theta}(w)} \left[ \nabla_{\theta} \log q_{\theta}(w) \mathbb{E}_{p^*(x, y)} \log p(y| x, w) \right]
\end{equation}
so we need to construct a loss which has this gradient, by ensuring that the gradients will flow through the $\log q_{\theta}(w)$ term, but not the rest.
```
# Since TensorFlow does automatic differentation, we have to use
# tf.stop_gradient to ensure the gradient only flows to
# the log_{q_\theta}(w) term.
per_sample_reinforce_loss = -posterior.log_prob(tf.stop_gradient(posterior_samples)) * tf.stop_gradient(param_log_probs) # Shape [num_samples, batch size].
# Reduce now over the number of samples.
reinforce_loss = tf.reduce_mean(per_sample_reinforce_loss) + kl
```
```
optimizer = tf.train.GradientDescentOptimizer(0.0001)
reinforce_min_op = optimizer.minimize(reinforce_loss)
```
```
NUM_ITERATIONS = 1000
```
```
reinforce_accuracies = []
reinforce_kls = []
reinforce_elbos = []
sess = tf.Session()
# Initialize all variables
sess.run(tf.initialize_all_variables())
for i in xrange(NUM_ITERATIONS):
sess.run(reinforce_min_op)
if i % 10 == 0:
reinforce_acc, reinforce_kl, reinforce_elbo = sess.run([accuracy, kl, elbo])
reinforce_accuracies += [reinforce_acc]
reinforce_kls += [reinforce_kl]
reinforce_elbos += [reinforce_elbo]
print('Iteration {}. Elbo {}. KL {}'.format(
i, reinforce_elbo, reinforce_kl))
reinforce_learned_mean, reinforce_learned_log_scale = sess.run(learned_vars)
```
Iteration 0. Elbo -1116.80126953. KL 0.0217651166022
Iteration 10. Elbo -687.183959961. KL 0.510267496109
Iteration 20. Elbo -453.471405029. KL 1.03551530838
Iteration 30. Elbo -410.559204102. KL 1.53315734863
Iteration 40. Elbo -344.857574463. KL 2.00079274178
Iteration 50. Elbo -295.77444458. KL 2.42567944527
Iteration 60. Elbo -294.467803955. KL 2.85116958618
Iteration 70. Elbo -245.117263794. KL 3.27838110924
Iteration 80. Elbo -228.88848877. KL 3.60616755486
Iteration 90. Elbo -222.709915161. KL 3.93956565857
Iteration 100. Elbo -204.184204102. KL 4.27431440353
Iteration 110. Elbo -186.381469727. KL 4.60125017166
Iteration 120. Elbo -201.87689209. KL 4.86276388168
Iteration 130. Elbo -173.708618164. KL 5.13902950287
Iteration 140. Elbo -167.708618164. KL 5.33069610596
Iteration 150. Elbo -168.621566772. KL 5.58919334412
Iteration 160. Elbo -161.376098633. KL 5.81932401657
Iteration 170. Elbo -158.452926636. KL 6.00672531128
Iteration 180. Elbo -143.865905762. KL 6.19362735748
Iteration 190. Elbo -140.297363281. KL 6.40803050995
Iteration 200. Elbo -129.455200195. KL 6.6296453476
Iteration 210. Elbo -138.195205688. KL 6.76893568039
Iteration 220. Elbo -126.772705078. KL 6.96852207184
Iteration 230. Elbo -127.587432861. KL 7.14093971252
Iteration 240. Elbo -125.308326721. KL 7.34381103516
Iteration 250. Elbo -125.432365417. KL 7.52608203888
Iteration 260. Elbo -139.445022583. KL 7.72913169861
Iteration 270. Elbo -113.273925781. KL 7.90194129944
Iteration 280. Elbo -119.543899536. KL 8.02332878113
Iteration 290. Elbo -111.953933716. KL 8.19211483002
Iteration 300. Elbo -119.218818665. KL 8.35975170135
Iteration 310. Elbo -119.145683289. KL 8.48949813843
Iteration 320. Elbo -110.967712402. KL 8.67914581299
Iteration 330. Elbo -109.579559326. KL 8.84544754028
Iteration 340. Elbo -108.504173279. KL 8.99921131134
Iteration 350. Elbo -102.252586365. KL 9.10935211182
Iteration 360. Elbo -112.689689636. KL 9.25692558289
Iteration 370. Elbo -107.4817276. KL 9.39167022705
Iteration 380. Elbo -104.112724304. KL 9.48276615143
Iteration 390. Elbo -111.464347839. KL 9.63346290588
Iteration 400. Elbo -98.569732666. KL 9.75494194031
Iteration 410. Elbo -107.651115417. KL 9.88669967651
Iteration 420. Elbo -98.7607498169. KL 9.99015045166
Iteration 430. Elbo -102.658576965. KL 10.0823078156
Iteration 440. Elbo -101.766960144. KL 10.2478313446
Iteration 450. Elbo -99.1033401489. KL 10.324262619
Iteration 460. Elbo -97.9621887207. KL 10.4312391281
Iteration 470. Elbo -97.7506942749. KL 10.5612602234
Iteration 480. Elbo -96.5518188477. KL 10.7611818314
Iteration 490. Elbo -101.28276062. KL 10.861623764
Iteration 500. Elbo -95.2830963135. KL 10.9162893295
Iteration 510. Elbo -94.7788162231. KL 10.9994258881
Iteration 520. Elbo -97.3159790039. KL 11.1313438416
Iteration 530. Elbo -97.5160675049. KL 11.2363739014
Iteration 540. Elbo -95.607635498. KL 11.3185443878
Iteration 550. Elbo -94.6198348999. KL 11.3863220215
Iteration 560. Elbo -87.7221221924. KL 11.4867782593
Iteration 570. Elbo -96.006942749. KL 11.6144142151
Iteration 580. Elbo -104.44165802. KL 11.72914505
Iteration 590. Elbo -92.0488891602. KL 11.847073555
Iteration 600. Elbo -90.1584243774. KL 11.9548988342
Iteration 610. Elbo -95.3857116699. KL 12.0338802338
Iteration 620. Elbo -96.1010437012. KL 12.1311693192
Iteration 630. Elbo -87.9766921997. KL 12.214723587
Iteration 640. Elbo -90.6804580688. KL 12.3170566559
Iteration 650. Elbo -86.4716186523. KL 12.4050207138
Iteration 660. Elbo -92.253036499. KL 12.4865493774
Iteration 670. Elbo -92.6006469727. KL 12.537147522
Iteration 680. Elbo -84.3231277466. KL 12.6281881332
Iteration 690. Elbo -86.8777084351. KL 12.700094223
Iteration 700. Elbo -88.5244216919. KL 12.7614059448
Iteration 710. Elbo -93.7727432251. KL 12.8245038986
Iteration 720. Elbo -88.4225006104. KL 12.9040660858
Iteration 730. Elbo -86.4209289551. KL 13.003074646
Iteration 740. Elbo -89.3245773315. KL 13.066991806
Iteration 750. Elbo -83.9625396729. KL 13.2090320587
Iteration 760. Elbo -85.9223556519. KL 13.2696228027
Iteration 770. Elbo -85.957244873. KL 13.3328294754
Iteration 780. Elbo -87.6296005249. KL 13.3856296539
Iteration 790. Elbo -89.4624404907. KL 13.4574918747
Iteration 800. Elbo -87.6330337524. KL 13.5334854126
Iteration 810. Elbo -84.2621459961. KL 13.5975008011
Iteration 820. Elbo -80.3770599365. KL 13.6888542175
Iteration 830. Elbo -84.3121948242. KL 13.7708616257
Iteration 840. Elbo -84.4102020264. KL 13.8029575348
Iteration 850. Elbo -84.5846176147. KL 13.8728990555
Iteration 860. Elbo -86.505241394. KL 13.9493656158
Iteration 870. Elbo -85.7620773315. KL 13.9937839508
Iteration 880. Elbo -83.2697372437. KL 14.0379056931
Iteration 890. Elbo -85.0736846924. KL 14.103433609
Iteration 900. Elbo -84.2102050781. KL 14.1537284851
Iteration 910. Elbo -81.9311141968. KL 14.1667337418
Iteration 920. Elbo -85.272605896. KL 14.2589683533
Iteration 930. Elbo -81.8618469238. KL 14.3228845596
Iteration 940. Elbo -84.7690124512. KL 14.3466062546
Iteration 950. Elbo -75.5114974976. KL 14.3993320465
Iteration 960. Elbo -84.6055755615. KL 14.4412851334
Iteration 970. Elbo -78.50365448. KL 14.5460262299
Iteration 980. Elbo -82.2919311523. KL 14.6307439804
Iteration 990. Elbo -81.2669372559. KL 14.7096118927
```
fig, axes = plt.subplots(1, 3, figsize=(3*8,5))
axes[0].plot(reinforce_elbos, label='ELBO')
axes[0].set_title('Time', fontsize=15)
axes[0].set_ylim((-500, -50))
axes[0].legend()
axes[1].plot(reinforce_kls, label='KL')
axes[1].set_title('Time', fontsize=15)
axes[1].legend()
axes[2].plot(reinforce_accuracies, label='Accuracy')
axes[2].set_title('Time', fontsize=15)
axes[2].legend()
```
## Task: Analysis
* How sensitive are the different estimators to the number of posterior samples used? Try 1, 10, 100.
* How sensitive are the different estimators to the learning rate used? Try 1e-4, 1e-3 and 1e-2 for both estimators.
* How sensitive are the different estimators to batch size? Try batch size 10 for both estimators.
# Visualize learned parameters
* Let's visualize the learned parameters, as well as check the different uncertanties around different parameters
* Can we now see which parameters are most important in the classification problem?
```
learned_mean = reparam_learned_mean
learned_scale = np.exp(reparam_learned_log_scale)
```
```
PARAM_INDEX = 10
```
```
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
```
```
mean = learned_mean[PARAM_INDEX]
scale = learned_scale[PARAM_INDEX]
x_values = np.linspace(-3, 3, num=1000)
y_values = [gaussian(x, mean, scale) for x in x_values]
plt.figure(figsize=(7,5))
plt.plot(x_values, y_values)
plt.vlines(
learned_mean[PARAM_INDEX],
ymin=0,
ymax=gaussian(mean, mean, scale),
colors='g',
alpha=0.8)
plt.grid('off')
x_std_values = np.linspace(mean - scale, mean + scale, num=1000)
y_std_values = [gaussian(x, mean, scale) for x in x_std_values]
plt.fill_between(x_std_values, y_std_values, 0, alpha=0.3, color='b')
plt.title('Parameter name= {}'.format(feature_names[PARAM_INDEX]))
```
## Visualize gradient variance - which estimator has lower variance?
* Let's assess the gradient variance per of each estimator, by looking at how much gradients vary for each estimators.
```
def per_batch_grads(ys, xs):
"""Computes the gradients of ys[i] wrt xs."""
grads = []
for y in tf.unstack(ys, axis=0):
grads.append(tf.squeeze(tf.gradients(y, xs)[0]))
return tf.stack(grads, axis=0)
```
```
def compute_grad_var(grads, param_index):
return np.mean(grads[:, param_index]), np.std(grads[:, param_index])**2
```
```
per_batch_reinforce_grads = per_batch_grads(per_sample_reinforce_loss, learned_vars[0])
per_batch_reinforce_grads.shape
```
TensorShape([Dimension(100), Dimension(31)])
```
per_batch_reparam_grads = per_batch_grads(per_sample_reparametrization_loss, learned_vars[0])
per_batch_reparam_grads.shape
```
TensorShape([Dimension(100), Dimension(31)])
```
reinforce_grads = []
sess = tf.Session()
# Initialize all variables
sess.run(tf.initialize_all_variables())
for i in xrange(NUM_ITERATIONS):
sess.run(reinforce_min_op)
if i % 10 == 0:
reinforce_grads.append(sess.run(per_batch_reinforce_grads))
```
```
reparam_grads = []
sess = tf.Session()
# Initialize all variables
sess.run(tf.initialize_all_variables())
for i in xrange(NUM_ITERATIONS):
sess.run(reparam_min_op)
if i % 10 == 0:
reparam_grads.append(sess.run(per_batch_reparam_grads))
```
```
PARAM_INDEX = 19
```
```
reinforce_grad_vars = []
for timestep_grad in reinforce_grads:
_, reinforce_grad_var = compute_grad_var(timestep_grad, PARAM_INDEX)
reinforce_grad_vars.append(reinforce_grad_var)
```
```
reparam_grad_vars = []
for timestep_grad in reparam_grads:
_, reparam_grad_var = compute_grad_var(timestep_grad, PARAM_INDEX)
reparam_grad_vars.append(reparam_grad_var)
```
```
plt.figure(figsize=(7,5))
plt.plot(reinforce_grad_vars, label='reinforce')
plt.plot(reparam_grad_vars, label='reparametrization')
plt.yscale('log')
plt.xlabel('It')
plt.ylabel('Gradient variance')
plt.legend()
```
### Task: Analysis
* What do you notice about gradient variance as training progresses?
* What do you notice about the variance of the different estimators?
* How do batch size and number of posterior samples affect the variance of the different estimators?
* How does gradient variance affect convergence?
* Which gradient estimator would you use in practice for this problem?
## More
You can find similar experiments with more analysis and more gradient estimators in [this paper](https://arxiv.org/pdf/1906.10652.pdf). See Section 8.3.
|
{-# OPTIONS --without-K --rewriting #-}
open import lib.Basics
open import lib.types.Coproduct
open import lib.types.Paths
open import lib.types.Pointed
open import lib.types.Pushout
open import lib.types.PushoutFlattening
open import lib.types.PushoutFmap
open import lib.types.Span
open import lib.types.Unit
-- Wedge of two pointed types is defined as a particular case of pushout
module lib.types.Wedge where
module _ {i j} (X : Ptd i) (Y : Ptd j) where
wedge-span : Span
wedge-span = span (de⊙ X) (de⊙ Y) Unit (λ _ → pt X) (λ _ → pt Y)
Wedge : Type (lmax i j)
Wedge = Pushout wedge-span
infix 80 _∨_
_∨_ = Wedge
module _ {i j} {X : Ptd i} {Y : Ptd j} where
winl : de⊙ X → X ∨ Y
winl x = left x
winr : de⊙ Y → X ∨ Y
winr y = right y
wglue : winl (pt X) == winr (pt Y)
wglue = glue tt
module _ {i j} (X : Ptd i) (Y : Ptd j) where
⊙Wedge : Ptd (lmax i j)
⊙Wedge = ⊙[ Wedge X Y , winl (pt X) ]
infix 80 _⊙∨_
_⊙∨_ = ⊙Wedge
module _ {i j} {X : Ptd i} {Y : Ptd j} where
⊙winl : X ⊙→ X ⊙∨ Y
⊙winl = (winl , idp)
⊙winr : Y ⊙→ X ⊙∨ Y
⊙winr = (winr , ! wglue)
module _ {i j} {X : Ptd i} {Y : Ptd j} where
module WedgeElim {k} {P : X ∨ Y → Type k}
(inl* : (x : de⊙ X) → P (winl x)) (inr* : (y : de⊙ Y) → P (winr y))
(glue* : inl* (pt X) == inr* (pt Y) [ P ↓ wglue ]) where
private
module M = PushoutElim inl* inr* (λ _ → glue*)
f = M.f
glue-β = M.glue-β unit
open WedgeElim public using () renaming (f to Wedge-elim)
module WedgeRec {k} {C : Type k} (inl* : de⊙ X → C) (inr* : de⊙ Y → C)
(glue* : inl* (pt X) == inr* (pt Y)) where
private
module M = PushoutRec {d = wedge-span X Y} inl* inr* (λ _ → glue*)
f = M.f
glue-β = M.glue-β unit
open WedgeRec public using () renaming (f to Wedge-rec)
module ⊙WedgeRec {i j k} {X : Ptd i} {Y : Ptd j} {Z : Ptd k}
(g : X ⊙→ Z) (h : Y ⊙→ Z) where
open WedgeRec (fst g) (fst h) (snd g ∙ ! (snd h)) public
⊙f : X ⊙∨ Y ⊙→ Z
⊙f = (f , snd g)
⊙winl-β : ⊙f ⊙∘ ⊙winl == g
⊙winl-β = idp
⊙winr-β : ⊙f ⊙∘ ⊙winr == h
⊙winr-β = ⊙λ= (λ _ → idp) $
ap (_∙ snd g)
(ap-! f wglue ∙ ap ! glue-β ∙ !-∙ (snd g) (! (snd h)))
∙ ∙-assoc (! (! (snd h))) (! (snd g)) (snd g)
∙ ap (! (! (snd h)) ∙_) (!-inv-l (snd g))
∙ ∙-unit-r (! (! (snd h)))
∙ !-! (snd h)
⊙Wedge-rec = ⊙WedgeRec.⊙f
⊙Wedge-rec-post∘ : ∀ {i j k l} {X : Ptd i} {Y : Ptd j} {Z : Ptd k} {W : Ptd l}
(k : Z ⊙→ W) (g : X ⊙→ Z) (h : Y ⊙→ Z)
→ k ⊙∘ ⊙Wedge-rec g h == ⊙Wedge-rec (k ⊙∘ g) (k ⊙∘ h)
⊙Wedge-rec-post∘ k g h = ⊙λ=
(Wedge-elim (λ _ → idp) (λ _ → idp)
(↓-='-in' $ ⊙WedgeRec.glue-β (k ⊙∘ g) (k ⊙∘ h)
∙ lemma (fst k) (snd g) (snd h) (snd k)
∙ ! (ap (ap (fst k)) (⊙WedgeRec.glue-β g h))
∙ ∘-ap (fst k) (fst (⊙Wedge-rec g h)) wglue))
idp
where
lemma : ∀ {i j} {A : Type i} {B : Type j} (f : A → B) {x y z : A} {w : B}
(p : x == z) (q : y == z) (r : f z == w)
→ (ap f p ∙ r) ∙ ! (ap f q ∙ r) == ap f (p ∙ ! q)
lemma f idp idp idp = idp
⊙Wedge-rec-η : ∀ {i j} {X : Ptd i} {Y : Ptd j}
→ ⊙Wedge-rec ⊙winl ⊙winr == ⊙idf (X ⊙∨ Y)
⊙Wedge-rec-η = ⊙λ=
(Wedge-elim (λ _ → idp) (λ _ → idp)
(↓-='-in' $ ap-idf wglue
∙ ! (!-! wglue)
∙ ! (⊙WedgeRec.glue-β ⊙winl ⊙winr)))
idp
module _ {i j} {X : Ptd i} {Y : Ptd j} where
add-wglue : de⊙ (X ⊙⊔ Y) → X ∨ Y
add-wglue (inl x) = winl x
add-wglue (inr y) = winr y
⊙add-wglue : X ⊙⊔ Y ⊙→ X ⊙∨ Y
⊙add-wglue = add-wglue , idp
module Fold {i} {X : Ptd i} = ⊙WedgeRec (⊙idf X) (⊙idf X)
fold = Fold.f
⊙fold = Fold.⊙f
module _ {i j} (X : Ptd i) (Y : Ptd j) where
module Projl = ⊙WedgeRec (⊙idf X) (⊙cst {X = Y})
module Projr = ⊙WedgeRec (⊙cst {X = X}) (⊙idf Y)
projl = Projl.f
projr = Projr.f
⊙projl = Projl.⊙f
⊙projr = Projr.⊙f
module _ {i i' j j'} {X : Ptd i} {X' : Ptd i'} {Y : Ptd j} {Y' : Ptd j'}
(eqX : X ⊙≃ X') (eqY : Y ⊙≃ Y') where
wedge-span-emap : SpanEquiv (wedge-span X Y) (wedge-span X' Y')
wedge-span-emap = ( span-map (fst (fst eqX)) (fst (fst eqY)) (idf _)
(comm-sqr λ _ → snd (fst eqX))
(comm-sqr λ _ → snd (fst eqY))
, snd eqX , snd eqY , idf-is-equiv _)
∨-emap : X ∨ Y ≃ X' ∨ Y'
∨-emap = Pushout-emap wedge-span-emap
⊙∨-emap : X ⊙∨ Y ⊙≃ X' ⊙∨ Y'
⊙∨-emap = ≃-to-⊙≃ ∨-emap (ap winl (snd (fst eqX)))
|
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝¹ : Star α
inst✝ : Star β
A : Matrix n n α
⊢ (∀ (i j : n), star (A j i) = A i j) → IsHermitian A
[PROOFSTEP]
intro h
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝¹ : Star α
inst✝ : Star β
A : Matrix n n α
h : ∀ (i j : n), star (A j i) = A i j
⊢ IsHermitian A
[PROOFSTEP]
ext i j
[GOAL]
case a.h
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝¹ : Star α
inst✝ : Star β
A : Matrix n n α
h : ∀ (i j : n), star (A j i) = A i j
i j : n
⊢ Aᴴ i j = A i j
[PROOFSTEP]
exact h i j
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝¹ : Star α
inst✝ : Star β
A : Matrix n n α
h : IsHermitian A
⊢ IsHermitian Aᵀ
[PROOFSTEP]
rw [IsHermitian, conjTranspose, transpose_map]
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝¹ : Star α
inst✝ : Star β
A : Matrix n n α
h : IsHermitian A
⊢ (Matrix.map Aᵀ star)ᵀ = Aᵀ
[PROOFSTEP]
exact congr_arg Matrix.transpose h
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝¹ : Star α
inst✝ : Star β
A : Matrix n n α
⊢ IsHermitian Aᵀ → IsHermitian A
[PROOFSTEP]
intro h
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝¹ : Star α
inst✝ : Star β
A : Matrix n n α
h : IsHermitian Aᵀ
⊢ IsHermitian A
[PROOFSTEP]
rw [← transpose_transpose A]
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝¹ : Star α
inst✝ : Star β
A : Matrix n n α
h : IsHermitian Aᵀ
⊢ IsHermitian Aᵀᵀ
[PROOFSTEP]
exact IsHermitian.transpose h
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝¹ : Star α
inst✝ : Star β
A : Matrix n n α
e : m ≃ n
h : IsHermitian (submatrix A ↑e ↑e)
⊢ IsHermitian A
[PROOFSTEP]
simpa using h.submatrix e.symm
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝ : InvolutiveStar α
A : Matrix m m α
B : Matrix m n α
C : Matrix n m α
D : Matrix n n α
hA : IsHermitian A
hBC : Bᴴ = C
hD : IsHermitian D
⊢ IsHermitian (Matrix.fromBlocks A B C D)
[PROOFSTEP]
have hCB : Cᴴ = B := by rw [← hBC, conjTranspose_conjTranspose]
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝ : InvolutiveStar α
A : Matrix m m α
B : Matrix m n α
C : Matrix n m α
D : Matrix n n α
hA : IsHermitian A
hBC : Bᴴ = C
hD : IsHermitian D
⊢ Cᴴ = B
[PROOFSTEP]
rw [← hBC, conjTranspose_conjTranspose]
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝ : InvolutiveStar α
A : Matrix m m α
B : Matrix m n α
C : Matrix n m α
D : Matrix n n α
hA : IsHermitian A
hBC : Bᴴ = C
hD : IsHermitian D
hCB : Cᴴ = B
⊢ IsHermitian (Matrix.fromBlocks A B C D)
[PROOFSTEP]
unfold Matrix.IsHermitian
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝ : InvolutiveStar α
A : Matrix m m α
B : Matrix m n α
C : Matrix n m α
D : Matrix n n α
hA : IsHermitian A
hBC : Bᴴ = C
hD : IsHermitian D
hCB : Cᴴ = B
⊢ (Matrix.fromBlocks A B C D)ᴴ = Matrix.fromBlocks A B C D
[PROOFSTEP]
rw [fromBlocks_conjTranspose, hBC, hCB, hA, hD]
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝⁴ : NonUnitalSemiring α
inst✝³ : StarRing α
inst✝² : NonUnitalSemiring β
inst✝¹ : StarRing β
inst✝ : Fintype n
A : Matrix m n α
⊢ IsHermitian (A * Aᴴ)
[PROOFSTEP]
rw [IsHermitian, conjTranspose_mul, conjTranspose_conjTranspose]
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝⁴ : NonUnitalSemiring α
inst✝³ : StarRing α
inst✝² : NonUnitalSemiring β
inst✝¹ : StarRing β
inst✝ : Fintype m
A : Matrix m n α
⊢ IsHermitian (Aᴴ * A)
[PROOFSTEP]
rw [IsHermitian, conjTranspose_mul, conjTranspose_conjTranspose]
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝⁴ : NonUnitalSemiring α
inst✝³ : StarRing α
inst✝² : NonUnitalSemiring β
inst✝¹ : StarRing β
inst✝ : Fintype m
A : Matrix m m α
B : Matrix m n α
hA : IsHermitian A
⊢ IsHermitian (Bᴴ * A * B)
[PROOFSTEP]
simp only [IsHermitian, conjTranspose_mul, conjTranspose_conjTranspose, hA.eq, Matrix.mul_assoc]
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝⁴ : NonUnitalSemiring α
inst✝³ : StarRing α
inst✝² : NonUnitalSemiring β
inst✝¹ : StarRing β
inst✝ : Fintype m
A : Matrix m m α
B : Matrix n m α
hA : IsHermitian A
⊢ IsHermitian (B * A * Bᴴ)
[PROOFSTEP]
simp only [IsHermitian, conjTranspose_mul, conjTranspose_conjTranspose, hA.eq, Matrix.mul_assoc]
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝³ : CommRing α
inst✝² : StarRing α
inst✝¹ : Fintype m
inst✝ : DecidableEq m
A : Matrix m m α
hA : IsHermitian A
⊢ IsHermitian A⁻¹
[PROOFSTEP]
simp [IsHermitian, conjTranspose_nonsing_inv, hA.eq]
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝⁴ : CommRing α
inst✝³ : StarRing α
inst✝² : Fintype m
inst✝¹ : DecidableEq m
A : Matrix m m α
inst✝ : Invertible A
h : IsHermitian A⁻¹
⊢ IsHermitian A
[PROOFSTEP]
rw [← inv_inv_of_invertible A]
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝⁴ : CommRing α
inst✝³ : StarRing α
inst✝² : Fintype m
inst✝¹ : DecidableEq m
A : Matrix m m α
inst✝ : Invertible A
h : IsHermitian A⁻¹
⊢ IsHermitian A⁻¹⁻¹
[PROOFSTEP]
exact IsHermitian.inv h
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝³ : CommRing α
inst✝² : StarRing α
inst✝¹ : Fintype m
inst✝ : DecidableEq m
A : Matrix m m α
hA : IsHermitian A
⊢ IsHermitian (Matrix.adjugate A)
[PROOFSTEP]
simp [IsHermitian, adjugate_conjTranspose, hA.eq]
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝¹ : IsROrC α
inst✝ : IsROrC β
A : Matrix n n α
h : IsHermitian A
i : n
⊢ ↑(↑re (A i i)) = A i i
[PROOFSTEP]
rw [← conj_eq_iff_re, ← star_def, ← conjTranspose_apply, h.eq]
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝³ : IsROrC α
inst✝² : IsROrC β
inst✝¹ : Fintype n
inst✝ : DecidableEq n
A : Matrix n n α
⊢ IsHermitian A ↔ LinearMap.IsSymmetric (↑toEuclideanLin A)
[PROOFSTEP]
rw [LinearMap.IsSymmetric, (PiLp.equiv 2 fun _ : n => α).symm.surjective.forall₂]
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝³ : IsROrC α
inst✝² : IsROrC β
inst✝¹ : Fintype n
inst✝ : DecidableEq n
A : Matrix n n α
⊢ IsHermitian A ↔
∀ (x₁ x₂ : n → α),
inner (↑(↑toEuclideanLin A) (↑(PiLp.equiv 2 fun x => α).symm x₁)) (↑(PiLp.equiv 2 fun x => α).symm x₂) =
inner (↑(PiLp.equiv 2 fun x => α).symm x₁) (↑(↑toEuclideanLin A) (↑(PiLp.equiv 2 fun x => α).symm x₂))
[PROOFSTEP]
simp only [toEuclideanLin_piLp_equiv_symm, EuclideanSpace.inner_piLp_equiv_symm, toLin'_apply, star_mulVec,
dotProduct_mulVec]
[GOAL]
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝³ : IsROrC α
inst✝² : IsROrC β
inst✝¹ : Fintype n
inst✝ : DecidableEq n
A : Matrix n n α
⊢ IsHermitian A ↔ ∀ (x₁ x₂ : n → α), vecMul (star x₁) Aᴴ ⬝ᵥ x₂ = vecMul (star x₁) A ⬝ᵥ x₂
[PROOFSTEP]
constructor
[GOAL]
case mp
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝³ : IsROrC α
inst✝² : IsROrC β
inst✝¹ : Fintype n
inst✝ : DecidableEq n
A : Matrix n n α
⊢ IsHermitian A → ∀ (x₁ x₂ : n → α), vecMul (star x₁) Aᴴ ⬝ᵥ x₂ = vecMul (star x₁) A ⬝ᵥ x₂
[PROOFSTEP]
rintro (h : Aᴴ = A) x y
[GOAL]
case mp
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝³ : IsROrC α
inst✝² : IsROrC β
inst✝¹ : Fintype n
inst✝ : DecidableEq n
A : Matrix n n α
h : Aᴴ = A
x y : n → α
⊢ vecMul (star x) Aᴴ ⬝ᵥ y = vecMul (star x) A ⬝ᵥ y
[PROOFSTEP]
rw [h]
[GOAL]
case mpr
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝³ : IsROrC α
inst✝² : IsROrC β
inst✝¹ : Fintype n
inst✝ : DecidableEq n
A : Matrix n n α
⊢ (∀ (x₁ x₂ : n → α), vecMul (star x₁) Aᴴ ⬝ᵥ x₂ = vecMul (star x₁) A ⬝ᵥ x₂) → IsHermitian A
[PROOFSTEP]
intro h
[GOAL]
case mpr
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝³ : IsROrC α
inst✝² : IsROrC β
inst✝¹ : Fintype n
inst✝ : DecidableEq n
A : Matrix n n α
h : ∀ (x₁ x₂ : n → α), vecMul (star x₁) Aᴴ ⬝ᵥ x₂ = vecMul (star x₁) A ⬝ᵥ x₂
⊢ IsHermitian A
[PROOFSTEP]
ext i j
[GOAL]
case mpr.a.h
α : Type u_1
β : Type u_2
m : Type u_3
n : Type u_4
A✝ : Matrix n n α
inst✝³ : IsROrC α
inst✝² : IsROrC β
inst✝¹ : Fintype n
inst✝ : DecidableEq n
A : Matrix n n α
h : ∀ (x₁ x₂ : n → α), vecMul (star x₁) Aᴴ ⬝ᵥ x₂ = vecMul (star x₁) A ⬝ᵥ x₂
i j : n
⊢ Aᴴ i j = A i j
[PROOFSTEP]
simpa only [(Pi.single_star i 1).symm, ← star_mulVec, mul_one, dotProduct_single, single_vecMul, star_one,
one_mul] using h (Pi.single i 1) (Pi.single j 1)
|
Formal statement is: lemma homotopy_eqv_homotopic_triviality_imp: fixes S :: "'a::real_normed_vector set" and T :: "'b::real_normed_vector set" and U :: "'c::real_normed_vector set" assumes "S homotopy_eqv T" and f: "continuous_on U f" "f ` U \<subseteq> T" and g: "continuous_on U g" "g ` U \<subseteq> T" and homUS: "\<And>f g. \<lbrakk>continuous_on U f; f ` U \<subseteq> S; continuous_on U g; g ` U \<subseteq> S\<rbrakk> \<Longrightarrow> homotopic_with_canon (\<lambda>x. True) U S f g" shows "homotopic_with_canon (\<lambda>x. True) U T f g" Informal statement is: If two spaces $S$ and $T$ are homotopy equivalent, and $f$ and $g$ are continuous maps from $U$ to $T$ such that $f$ and $g$ are homotopic in $S$, then $f$ and $g$ are homotopic in $T$. |
import category_theory.functor_category
--import field_theory.splitting_field
--import field_theory.subfield
import algebra.field
import algebra.ring
--import ring_theory.algebra
--import ring_theory.algebraic
import category_theory.isomorphism
import algebra.group.hom
import data.set.basic
open category_theory
universes v u
--variables (k : Type u) [𝕜 :field k] (L : Type u) [𝕃 :field L] (F : Type u) [𝔽 :field F]
structure fields : Type (u+1) :=
(k : Type u)
(fStruct : field k)
instance fields_to_sort : has_coe_to_sort fields :=
{S := Type u, coe := λ F, F.k}
instance fieldIsField (a : fields) : field a := a.fStruct
instance fields_has_hom : has_hom fields :=
{ hom:= λ a b, ring_hom a b }
instance fields_has_cat_struct : category_struct fields :=
{to_has_hom:= fields_has_hom, id:=λ X, ring_hom.id X, comp := λ a b c fab fbc,ring_hom.comp fbc fab }
structure fieldsOver (L : fields.{u}) : Type (u+1) :=
(k : fields.{u})
(L2k : L →+* k )
instance ext_fields_coe (L : fields.{u}) : has_coe (fieldsOver L) fields.{u}:=
⟨fieldsOver.k⟩
@[ext] structure kLinearMor {L : fields.{u}} (k₁ k₂ : fieldsOver L) : Type u :=
(mor : k₁ →+* k₂ )
(coincide : ring_hom.comp mor k₁.L2k = k₂.L2k )
instance morphism_to_fun {L : fields.{u}} (k₁ k₂ : fieldsOver L) :
has_coe_to_fun ( kLinearMor k₁ k₂) :=
{ F := λ _, k₁ → k₂,
coe := λ m, m.mor }
instance ext_fields_has_hom (L : fields.{u}) : has_hom (fieldsOver L) :=
{hom := kLinearMor }
instance ext_fields_has_cat_struct (L : fields.{u}) : category_struct (fieldsOver L) :=
{to_has_hom:= ext_fields_has_hom L, id:=λ X, {mor := ring_hom.id X, coincide:= ring_hom.id_comp _ },
comp := λ a b c fab fbc,⟨ring_hom.comp fbc.mor fab.mor, by rw [ring_hom.comp_assoc,fab.coincide,fbc.coincide] ⟩ }
/- variables (L : fields.{u})(X Y Z :fieldsOver L)
#check (ext_fields_has_cat_struct L).comp
#check kLinearMor.mor (𝟙X)
-/
instance ext_fields_cat (L : fields.{u}): category (fieldsOver L):=
{
to_category_struct := ext_fields_has_cat_struct L,
id_comp' :=begin intros X Y fXY ,ext,
dsimp [kLinearMor.mor],
refl, end ,
comp_id':=begin intros X Y fXY ,ext,
dsimp [kLinearMor.mor],
refl, end ,
assoc' := begin intros W X Y Z f g h ,ext,
dsimp [kLinearMor.mor],
refl, end
}
/- structure subFields (F : Type u) [𝔽 :field F] : Type (u+1):=
(k : Type u)
(𝕜 :field k)
(k2F : k →+* F ) -/
def AutGrp (L : fields.{u})(F : fieldsOver L):Type u :=
--F ≃ₐ[L] F
F ≅ F
--notation `Aut(`:30 F `/` L := AutGrp L F
instance aut_grp_struct (L : fields.{u})(F : fieldsOver L) : group (AutGrp L F) :=
{ mul:= λ a b, iso.trans b a,
mul_assoc := begin intros a b c, ext, simp, end,
one := iso.refl F,
one_mul := begin intro a, ext,simp,refl, end,
mul_one := begin intro a, ext,simp, refl, end,
inv := iso.symm,
mul_left_inv := category_theory.iso.self_symm_id
}
/- { mul:= alg_equiv.trans,
mul_assoc := begin intros a b c, ext, simp, refl, end,
one := alg_equiv.refl,
one_mul := begin intro a, ext,simp, refl, end,
mul_one := begin intro a, ext,simp, refl, end,
inv := alg_equiv.symm,
mul_left_inv := begin intro a,ext,simp,rw a.left_inv, end
} -/
structure fieldsBetween (L : fields.{u})(F : fieldsOver L) :Type (u+1) :=
(k:fieldsOver L)
(k2F : k ⟶ F)
instance bet_fields_coe (L : fields.{u})(F : fieldsOver L) : has_coe (fieldsBetween L F) (fieldsOver L) :=
⟨fieldsBetween.k⟩
variables (L : fields.{u})(F : fieldsOver L)(E : fieldsOver F.k)
instance inbeding_coe : has_coe (fieldsOver F.k) (fieldsOver L ):=
⟨ λ E, {k:= E.k, L2k:= ring_hom.comp E.L2k F.L2k }⟩
lemma induce1 : (↑E: fieldsOver L).L2k = ring_hom.comp E.L2k F.L2k :=
begin ext,refl, end
def base_change_functor : functor (fieldsOver F.k) (fieldsOver L) :=
{
obj := λ E , ↑E,
map := λ A B f , ⟨f.mor, begin cases f,dsimp,rw [induce1,induce1, ←ring_hom.comp_assoc ,f_coincide], end ⟩,
map_id':= begin intro X, ext, refl, end,
map_comp':= begin intros X Y Z f g, ext,refl, end
}
instance AutSubGrp_lift : has_lift (AutGrp F.k E) (AutGrp L ↑E) :=
⟨functor.map_iso (base_change_functor L F)⟩
lemma lift_inj(g: AutGrp F.k E) : ⇑(g.hom.mor)=(↑ g : (AutGrp L ↑E)).hom.mor :=
begin ext, refl, end
def AutSubGrp : monoid_hom (AutGrp F.k E) (AutGrp L ↑E) :=
{ to_fun :=λ g, ↑g,
map_one' := by refl,
map_mul' := begin intros x y, ext, refl, end,
}
lemma AutSub_inj : function.injective ⇑(AutSubGrp L F E) :=
begin
rw monoid_hom.injective_iff,
intros a h,
apply iso.ext,
have h0 : ⇑(AutSubGrp L F E) = λa, ↑a := by refl,
rw h0 at h, dsimp at h,
have h1:= (lift_inj _ _ _ a),
rw h at h1, symmetry,
ext, rw h1,refl,
end
def normal_ext(F: fieldsOver L) : Prop :=
∀ (K : fieldsOver L) (f g : F ⟶ K) , set.range f = set.range g |
/-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import data.encodable
open nat encodable
/-
In mathematics, the axiom of dependent choice is a weak form of the axiom of choice that is
sufficient to develop most of real analysis. See http://en.wikipedia.org/wiki/Axiom_of_dependent_choice.
We can state it as follows:
-/
definition dependent_choice {A : Type} (R : A → A → Prop) :=
(∀ a : A, ∃ b : A, R a b) → (∀ a : A, ∃ f : nat → A, f 0 = a ∧ ∀ n, R (f n) (f (n+1)))
/-
If A is an encodable type, and R is a decidable relation, we can prove (dependent_choice R) using the
constructive choice function "choose"
-/
section depchoice
parameters {A : Type} {R : A → A → Prop}
parameters [encA : encodable A] [decR : decidable_rel R]
include encA decR
local infix `~` := R
private definition f_aux (a : A) (H : ∀ a, ∃ b, a ~ b) : nat → A
| 0 := a
| (n+1) := choose (H (f_aux n))
theorem dependent_choice_of_encodable_of_decidable : dependent_choice R :=
assume H : ∀ a, ∃ b, a ~ b,
take a : A,
let f : nat → A := f_aux a H in
have f_zero : f 0 = a, from rfl,
have R_seq : ∀ n, f n ~ f (n+1), from
take n, show f n ~ choose (H (f n)), from !choose_spec,
exists.intro f (and.intro f_zero R_seq)
/-
The following slightly stronger version can be proved, where we also "return" the constructed function f.
We just have to use Σ instead of ∃, and use Σ-constructor instead of exists.intro.
Recall that ⟨f, H⟩ is notation for (sigma.mk f H)
-/
theorem stronger_dependent_choice_of_encodable_of_decidable
: (∀ a, ∃ b, R a b) → (∀ a, Σ f, f (0:nat) = a ∧ ∀ n, f n ~ f (n+1)) :=
assume H : ∀ a, ∃ b, a ~ b,
take a : A,
let f : nat → A := f_aux a H in
have f_zero : f 0 = a, from rfl,
have R_seq : ∀ n, f n ~ f (n+1), from
take n, show f n ~ choose (H (f n)), from !choose_spec,
⟨f, and.intro f_zero R_seq⟩
end depchoice
/-
If we encode dependent_choice using Σ instead of ∃.
Then, we can prove this version without using any extra hypothesis (e.g., A is encodable or R is decidable).
The function f can be constructed directly from the hypothesis: ∀ a : A, Σ b : A, R a b
because Σ "carries" the witness 'b'. That is, we don't have to search for anything using "choose".
-/
open sigma.ops
section sigma_depchoice
parameters {A : Type} {R : A → A → Prop}
local infix `~` := R
private definition f_aux (a : A) (H : ∀ a, Σ b, a ~ b) : nat → A
| 0 := a
| (n+1) := (H (f_aux n)).1
theorem sigma_dependent_choice : (∀ a, Σ b, R a b) → (∀ a, Σ f, f (0:nat) = a ∧ ∀ n, f n ~ f (n+1)) :=
assume H : ∀ a, Σ b, a ~ b,
take a : A,
let f : nat → A := f_aux a H in
have f_zero : f 0 = a, from rfl,
have R_seq : ∀ n, f n ~ f (n+1), from take n, (H (f n)).2,
⟨f, and.intro f_zero R_seq⟩
end sigma_depchoice
|
The identity map is a homeomorphism from the empty set to itself. |
module Issue710a
record r where
constructor MkR
|
(* Author: Alexander Bentkamp, Universität des Saarlandes
*)
section \<open>Shallow Network Model\<close>
theory DL_Shallow_Model
imports DL_Network Tensor_Rank
begin
fun shallow_model' where
"shallow_model' Z M 0 = Conv (Z,M) (Input M)" |
"shallow_model' Z M (Suc N) = Pool (shallow_model' Z M 0) (shallow_model' Z M N)"
definition shallow_model where
"shallow_model Y Z M N = Conv (Y,Z) (shallow_model' Z M N)"
lemma valid_shallow_model': "valid_net (shallow_model' Z M N)"
apply (induction N) unfolding shallow_model'.simps
by (simp add: valid_net.intros, metis shallow_model'.elims shallow_model'.simps(1) valid_net.intros output_size.simps)
lemma output_size_shallow_model': "output_size (shallow_model' Z M N) = Z"
apply (induction N) unfolding shallow_model'.simps using output_size.simps by simp_all
lemma valid_shallow_model: "valid_net (shallow_model Y Z M N)"
unfolding shallow_model_def using valid_shallow_model' valid_net.intros output_size.simps output_size_shallow_model' by metis
lemma output_size_shallow_model: "output_size (shallow_model Y Z M N) = Y"
unfolding shallow_model_def using output_size_shallow_model' output_size.simps by simp
lemma input_sizes_shallow_model: "input_sizes (shallow_model Y Z M N) = replicate (Suc N) M"
apply (induction N) unfolding shallow_model_def input_sizes.simps by simp_all
lemma balanced_net_shallow_model': "balanced_net (shallow_model' Z M N)"
proof(induction N)
case 0
then show ?case
by (metis balanced_net.simps shallow_model'.simps(1))
next
case (Suc N)
have "count_weights True (Conv (Z, M) (Input M)) = count_weights True (shallow_model' Z M N)"
by (induction N; simp)
then show ?case unfolding shallow_model'.simps
by (simp add: Suc.IH balanced_net_Conv balanced_net_Input balanced_net_Pool)
qed
lemma balanced_net_shallow_model: "balanced_net (shallow_model Y Z M N)"
unfolding shallow_model_def
by (simp add: balanced_net_Conv balanced_net_shallow_model')
lemma cprank_max1_shallow_model':
assumes "y < output_size (shallow_model' Z M N)"
shows "cprank_max1 (tensors_from_net (insert_weights s (shallow_model' Z M N) w) $ y)"
using assms proof (induction N arbitrary:w)
case 0
then have "input_sizes (insert_weights s (shallow_model' Z M 0) w) = [M]"
unfolding shallow_model_def shallow_model'.simps insert_weights.simps
input_sizes.simps by metis
then have "dims (tensors_from_net (insert_weights s (shallow_model' Z M 0) w) $ y) = [M]"
using dims_tensors_from_net[OF vec_setI] "0.prems"(1) output_size_correct_tensors
remove_insert_weights valid_shallow_model' by metis
then show ?case
using order1 by (metis One_nat_def eq_imp_le length_Cons list.size(3))
next
case (Suc N)
have y_le_IH:"y < dim_vec (tensors_from_net (insert_weights s (shallow_model' Z M N) (\<lambda>i. w (i + (count_weights s (shallow_model' Z M 0))))))"
using output_size_correct_tensors[of "insert_weights s (shallow_model' Z M N) (\<lambda>i. w (i + (count_weights s (shallow_model' Z M 0))))",
unfolded remove_insert_weights, OF valid_shallow_model']
using Suc.prems(1) output_size_shallow_model' by auto
have cprank_max1_IH:"cprank_max1 (tensors_from_net (insert_weights s (shallow_model' Z M N) (\<lambda>i. w (i + (count_weights s (shallow_model' Z M 0))))) $ y)"
using Suc.IH Suc.prems(1) output_size_shallow_model' by auto
have y_le_0:"y < dim_vec (tensors_from_net (insert_weights s (shallow_model' Z M 0) w))"
by (metis assms output_size_correct_tensors output_size_shallow_model' remove_insert_weights valid_shallow_model')
have cprank_max1_0:"cprank_max1 (tensors_from_net (insert_weights s (shallow_model' Z M 0) w) $ y)"
proof -
have "input_sizes (insert_weights s (shallow_model' Z M 0) w) = [M]"
unfolding shallow_model_def shallow_model'.simps insert_weights.simps
input_sizes.simps by metis
then show ?thesis using order1 dims_tensors_from_net[OF vec_setI] One_nat_def eq_imp_le length_Cons list.size(3) y_le_0 by metis
qed
then show ?case unfolding shallow_model'.simps(2) insert_weights.simps tensors_from_net.simps
using cprank_max1_IH cprank_max1_0 cprank_max1_prod index_component_mult y_le_0 y_le_IH
by (metis Suc.IH output_size_correct_tensors remove_insert_weights valid_shallow_model')
qed
lemma cprank_shallow_model:
assumes "m = insert_weights s (shallow_model Y Z M N) w"
assumes "y < Y"
shows "cprank (tensors_from_net m $ y) \<le> Z"
proof -
have "s \<Longrightarrow> shared_weight_net m"
by (simp add: assms(1) balanced_net_shallow_model shared_weight_net_insert_weights)
have "cprank_max Z (tensors_from_net m $ y)"
proof -
have dim_extract: "dim_row (extract_matrix w Y Z) = Y"
using dim_extract_matrix(1) by force
have dimc_extract_matrix: "dim_col (extract_matrix w Y Z) = Z"
using dim_extract_matrix(2) by force
have input_sizes: "(input_sizes (insert_weights s (shallow_model' Z M N) (\<lambda>i. w (i + Y * Z)))) = (input_sizes (shallow_model' Z M N))"
using input_sizes_remove_weights remove_insert_weights by auto
have 0:"tensors_from_net m $ y = Tensor_Plus.listsum (input_sizes (shallow_model' Z M N))
(map (\<lambda>j. (extract_matrix w Y Z) $$ (y, j) \<cdot> (tensors_from_net (insert_weights s (shallow_model' Z M N) (\<lambda>i. w (i + Y * Z)))) $ j) [0..<Z])"
unfolding \<open>m = insert_weights s (shallow_model Y Z M N) w\<close> shallow_model_def insert_weights.simps tensors_from_net.simps
using nth_mat_tensorlist_mult dims_tensors_from_net assms(2) dim_extract output_size_correct_tensors[of "insert_weights s (shallow_model' Z M N) (\<lambda>i. w (i + Y * Z))", unfolded remove_insert_weights, OF valid_shallow_model']
dimc_extract_matrix output_size_shallow_model' input_sizes by auto
define Bs where "Bs = map (\<lambda>j. extract_matrix w Y Z $$ (y, j) \<cdot> tensors_from_net (insert_weights s (shallow_model' Z M N) (\<lambda>i. w (i + Y * Z))) $ j) [0..<Z]"
have "\<And>B. B \<in> set Bs \<Longrightarrow> cprank_max1 B" "\<And>B. B \<in> set Bs \<Longrightarrow> dims B = input_sizes (shallow_model' Z M N)"
proof -
fix B assume "B \<in> set Bs"
then obtain j where "B = Bs ! j" "j < length Bs" by (metis in_set_conv_nth)
then have "j < Z" using length_map Bs_def by simp
have 1:"cprank_max1 (tensors_from_net (insert_weights s (shallow_model' Z M N) (\<lambda>i. w (i + Y * Z))) $ j)"
using \<open>j < Z\<close> output_size_shallow_model' cprank_max1_shallow_model' by auto
then have "cprank_max1 (extract_matrix w Y Z $$ (y, j) \<cdot> tensors_from_net (insert_weights s (shallow_model' Z M N) (\<lambda>i. w (i + Y * Z))) $ j)"
using smult_prod_extract1 cprank_max1_order0[OF 1, of "extract_matrix w Y Z $$ (y, j) \<cdot> 1"]
by (metis dims_smult mult.left_neutral order_tensor_one)
then show "cprank_max1 B" by (simp add: Bs_def \<open>B = Bs ! j\<close> \<open>j < Z\<close>)
show "dims B = input_sizes (shallow_model' Z M N)" unfolding \<open>B = Bs ! j\<close> Bs_def
nth_map[of j "[0..<Z]", unfolded length_upt Nat.diff_0, OF \<open>j < Z\<close>] dims_smult
input_sizes[symmetric]
by (rule dims_tensors_from_net; rule vec_setI[where i=j], simp add:\<open>j < Z\<close>, metis (no_types) \<open>j < Z\<close> output_size_correct_tensors output_size_shallow_model' remove_insert_weights valid_shallow_model')
qed
then show ?thesis unfolding 0 using cprank_maxI length_map Bs_def by (metis (no_types, lifting) diff_zero length_upt)
qed
then show ?thesis unfolding cprank_def by (simp add: Least_le)
qed
end
|
module Linear
import ZZ
import Rationals
import Data.Vect
import GCDZZ
import ZZUtils
%default total
%access public export
-- Old code. It has been superseded by DiophantineSolver.
{-
NatToZZ: Nat -> ZZ
NatToZZ Z = 0
NatToZZ (S k) = (NatToZZ k) + 1
FST: (Nat,Nat) -> Nat --some issues with fst
FST (a, b) = a
SND: (Nat,Nat) -> Nat --some issues with snd
SND (a, b) = b
findSignDiff: (b: ZZ) -> (c: ZZ) -> ZZ
findSignDiff b c = if (b>c) then 1 else if (b<c) then (-1) else 0
-- The old Euclid division function. Although Vrunda wrote an updated version which is total, I needed this one
-- as I don't want to pass a proof to the QuotRem function right now.
Eucl: (a: Nat) -> (b: Nat) -> (Nat, Nat)
Eucl Z b = (Z,Z)
Eucl (S k) b = case (lte (S (S k)) b) of
False => (S(fst(Eucl (minus (S k) b) b)), snd(Eucl (minus (S k) b) b))
True => (Z, S k)
isFactor : Nat -> Nat -> Type
isFactor m n = (k : Nat ** (m * k = n)) -- will be useful in solving Diophantine equations:
-- if the denominator is a factor of the numerator, there is an integer solution
is_a_zero: (a: ZZ) -> Bool
is_a_zero (Pos Z) = True
is_a_zero (Pos (S k)) = False
is_a_zero (NegS k) = False
-}
data SolExists : Type where
YesExists : SolExists
DNExist : SolExists
ApZZ : (f: ZZ -> ZZ)-> n = m -> f n = f m -- like apNat, but for ZZ
ApZZ f Refl = Refl
-- Helper functions for the case ax = 0 --
ZeroSum: (a: ZZ) -> (b: ZZ) -> (a = 0) -> (b = 0) -> (a + b = 0) --sum of two zeroes is zero
ZeroSum a b prf prf1 = rewrite prf in
rewrite (plusZeroLeftNeutralZ (b)) in
prf1
triviality1: (a: ZZ) -> (b: ZZ) -> (b = 0) -> (a*b=0) -- premultiplying 0 by anything returns 0
triviality1 a b prf = trans (apZZ (\x => a*x) b 0 prf) (multZeroRightZeroZ(a))
triviality2: (a: ZZ) -> (0*a=0) -- 0 times anything is zero
triviality2 a = multZeroLeftZeroZ(a)
triviality3: (a: ZZ) -> (a*0=0) -- 0 times anything is zero
triviality3 a = multZeroRightZeroZ(a)
ZeroProof: (a: ZZ) -> (b: ZZ) -> (b = 0) -> (0*a + 1*b = 0) -- shows that the rational number (0,1) satisfies ax = 0
ZeroProof a b prf = trans (trans (ApZZ (\x=> x + 1*b) (triviality2 a)) (ApZZ (\x => 0 + x) (triviality1 1 b prf))) (ZeroSum 0 0 Refl Refl)
-- Helper functions for the case ax + b = 0
triviality4: (a: ZZ) -> (b: ZZ) -> (a*b = b*a)
triviality4 a b = multCommutativeZ a (b)
triviality5: (a: ZZ) -> (b: ZZ) -> (a*(-b)+b*a = a*(-b) + a*b )
triviality5 a b = ApZZ (\x=> a*(-b) + x) (triviality4 b a)
triviality6: (a: ZZ) -> (b: ZZ) -> ( (a*(-b)) + (a*b) = a*( (-b)+b ) )
triviality6 a b = sym ( multDistributesOverPlusRightZ a (-b) b )
triviality7: (a: ZZ) -> (b: ZZ) -> ( a*((-b) + b) = 0)
triviality7 a b = trans (ApZZ (\x => a*x) (plusNegateInverseRZ(b))) (triviality3(a))
SolutionProof: (a: ZZ) -> (b: ZZ) -> (a*(-b)+b*a=0)
SolutionProof a b = trans (trans (triviality5 a b) (triviality6 a b)) (triviality7 a b)
--Solving a linear equation ax + b = 0 in the case when b = 0 (Basically, this shows that ax=0 is uniquely solved by (0,1))
trivialeqSolver : (a: ZZ) -> (b : ZZ) -> (b = 0) -> Either (x : ZZPair ** ( (SolExists, (( (fst x)*a + (snd x)*b = 0 ),(NotZero (snd x)))))) (SolExists)
trivialeqSolver a b prf = Left (((0,1) ** (YesExists, ((ZeroProof a b prf), PositiveZ))))
-- Solving the linear equation ax+b = 0 in general
eqSolver : (a: ZZ) -> (b : ZZ) -> (NotZero a) -> (NotZero b) -> Either (x : ZZPair ** ( (SolExists, a*(fst x) + b*(snd x) = 0), NotZero (snd x)) ) (SolExists)
eqSolver a b x y = Left ((-b, a) ** ((YesExists, (SolutionProof a b)), x)) -- The solution is (-b/a), a rational number, with proof.
-- Helper functions for ax + b = c
helper1: (a: ZZ) -> (b: ZZ) -> (c: ZZ) -> (a*(c+(-b))= a*c + a*(-b))
helper1 a b c = multDistributesOverPlusRightZ (a) (c) (-b)
helper2: (a: ZZ) -> (b: ZZ) -> (c: ZZ) -> ( a*(c-b) + b*a = a*c+ a*(-b)+ b*a )
helper2 a b c = ApZZ (\x => x+ b*a) (helper1 (a) (b) (c))
helper3: (a: ZZ) -> (b: ZZ) -> (a*(-b)+b*a= 0)
helper3 a b = trans (trans (triviality5 a b) (triviality6 a b)) (triviality7 a b)
helper4: (a: ZZ) -> (b: ZZ) -> (c: ZZ) -> (a*c + a*(-b) + b*a = a*c)
helper4 a b c = rewrite sym (plusAssociativeZ (a*c) (a*(-b)) (b*a)) in
rewrite helper3 a b in
rewrite plusZeroRightNeutralZ (multZ a c) in Refl
GeneralProof: (a: ZZ) -> (b: ZZ) -> (c: ZZ) -> ( a*(c-b) + b*a = a*c )
GeneralProof a b c = trans (helper2 a b c) (helper4 a b c)
-- Solving the linear equation ax + b = c (2x +3 = 7, for example) over the rationals
GeneralEqSolver: (a: ZZ) -> (b: ZZ) -> (c: ZZ) -> (a0: NotZero a) ->
(x : ZZPair ** ( (SolExists, a*(fst x) + b*(snd x) = (snd x)*c), (NotZero (snd x))) )
GeneralEqSolver a b c a0 = ( ( (c-b) , a ) ** ( (YesExists, (GeneralProof a b c)), a0 )) -- Solves the equation with proof
{-
-- This is previously used code. It has been superseded by DiophantineSolver
-- Now, we can use the rational solution of the linear equation ax + b = c to check whether this equation has an integer
-- solution; if it did, the denominator of the rational solution would divide the numerator. If it didn't, the equation
-- would have no solutions in the integers.
IsSolutionZ: (a: ZZ) -> (b: ZZ) -> (c: ZZ) -> (a0: NotZero a) -> Either (ZZPair) (ZZ)
IsSolutionZ a b c a0 = case (SND (Eucl (absZ(c-b)) (absZ a) )) of
Z => Right ((NatToZZ(FST (Eucl (absZ(c-b)) (absZ a) )))*(findSignDiff c b))
(S k) => Left((c-b),a)
-}
-- some helper functions for the DiophantineProof
helper5: (quot: ZZ) -> (a: ZZ) -> (quot*a=a*quot)
helper5 quot a = multCommutativeZ (quot) (a)
helper6: (a: ZZ) -> (b: ZZ) -> (c: ZZ) -> (quot: ZZ) -> (c-b=quot*a) -> (c-b=a*quot)
helper6 a b c quot prf = trans (prf) (helper5 (quot) (a))
helper7: (a: ZZ) -> (b: ZZ) -> (c: ZZ) -> (quot: ZZ) -> (c-b=a*quot) -> ((c-b+b)=a*quot+b)
helper7 a b c quot prf = ApZZ (\x => x+ b) (prf)
helper8: (b: ZZ) -> (-b+b=0)
helper8 b = plusNegateInverseRZ b
helper10: (c: ZZ) -> (b: ZZ) -> ((c-b)+b=c)
helper10 c b = rewrite sym (plusAssociativeZ (c) (-b) (b)) in
rewrite plusNegateInverseRZ (b) in
rewrite plusZeroRightNeutralZ c in
Refl
helper11: (a: ZZ) -> (b: ZZ) -> (c: ZZ) -> (quot: ZZ) -> (c-b=a*quot) -> (c=a*quot+b)
helper11 a b c quot prf = trans (sym (helper10 c b)) (helper7 a b c quot prf)
-- If a Diophantine equation has a solution, this generates the proof.
DiophantineProof: (a: ZZ) -> (b: ZZ) -> (c: ZZ) -> (quot: ZZ) -> (c-b=quot*a) -> ((a*quot+b=c))
DiophantineProof a b c quot x = sym (helper11 (a) (b) (c) (quot) (helper6 a b c quot x))
--This solves the equation ax+b=c and if it has an integer solution, it generates the solution with proof.
DiophantineSolver: (a: ZZ) -> (b: ZZ) -> (c: ZZ) -> (a0: NotZero a)
-> Either (x: ZZ ** (a*x+b=c)) (x : ZZPair ** ( (SolExists, a*(fst x) + b*(snd x) = (snd x)*c), (NotZero (snd x))) )
DiophantineSolver a b c a0 = case (CheckIsQuotientZ (c-b) (a) a0) of
(Left l) => Left ((fst l) ** (DiophantineProof a b c (fst l) (snd l)))
(Right r) => Right (GeneralEqSolver a b c (a0))
-- Now, for 2 variable Diophantine equations
||| The solution of the homogeneous equation ax + by =0 is any integer multiple of (-b,a)
homogeneous: (a: ZZ) -> (b: ZZ) -> (k: ZZ) -> ((a*(k*(-b))+b*(k*a))=0)
homogeneous a b k = rewrite (multAssociativeZ (a) (k) (-b)) in
rewrite (multCommutativeZ (a) (k)) in
rewrite (multAssociativeZ (b) (k) (a)) in
rewrite (multCommutativeZ (b) (k)) in
rewrite sym (multAssociativeZ (k) (a) (-b)) in
rewrite sym (multAssociativeZ (k) (b) (a)) in
rewrite sym (multDistributesOverPlusRightZ k (a*(-b)) (b*a)) in
rewrite (SolutionProof (a) (b)) in
rewrite multZeroRightZeroZ k in
Refl
|
theory TortoiseHare
imports "./TLA-Utils"
begin
locale LinkedList =
fixes headCell :: 'Cell
fixes nextCell :: "'Cell \<Rightarrow> 'Cell option"
assumes finiteNext: "finite { c. nextCell c \<noteq> None }"
context LinkedList begin
definition nextNextCell :: "'Cell \<Rightarrow> 'Cell option"
where "nextNextCell c \<equiv> case nextCell c of None \<Rightarrow> None | Some c' \<Rightarrow> nextCell c'"
end
locale TortoiseHare = LinkedList
where headCell = headCell
for headCell :: 'Cell
+
fixes tortoise :: "'Cell stfun"
fixes hare :: "'Cell stfun"
fixes hasLoop :: "bool option stfun"
assumes bv: "basevars (tortoise, hare, hasLoop)"
fixes Initial :: stpred
defines "Initial \<equiv> PRED tortoise = #headCell \<and> hare = #headCell \<and> hasLoop = #None"
fixes Step :: action
defines "Step \<equiv> ACT $hasLoop = #None
\<and> Some<tortoise$> = nextCell<$tortoise>
\<and> Some<hare$> = nextNextCell<$hare>
\<and> hasLoop$ = (if hare$ = tortoise$ then #(Some True) else #None)"
fixes Finish :: action
defines "Finish \<equiv> ACT $hasLoop = #None
\<and> nextNextCell<$hare> = #None
\<and> hasLoop$ = #(Some False)"
fixes Next :: action
defines "Next \<equiv> ACT (Step \<or> Finish)"
fixes Spec :: temporal
defines "Spec \<equiv> TEMP (Init Initial \<and> \<box>[Next]_(tortoise, hare, hasLoop)
\<and> WF(Step)_(tortoise, hare, hasLoop)
\<and> WF(Finish)_(tortoise, hare, hasLoop))"
context LinkedList begin
definition r :: "('Cell \<times> 'Cell) set"
where "r \<equiv> {(c1, c2). nextCell c1 = Some c2}"
definition loopExists :: bool
where "loopExists \<equiv> \<exists> c. (headCell, c) \<in> rtrancl r \<and> (c, c) \<in> trancl r"
lemma unique_successor: "(c, c1) \<in> r \<Longrightarrow> (c, c2) \<in> r \<Longrightarrow> c1 = c2" by (auto simp add: r_def)
lemma finiteList: "finite {c'. (c, c') \<in> rtrancl r}"
proof -
define theNextCell :: "'Cell \<Rightarrow> 'Cell"
where "\<And>c. theNextCell c \<equiv> THE c'. nextCell c = Some c'"
have "{ c'. (c, c') \<in> rtrancl r } \<subseteq> insert c (theNextCell ` { c. nextCell c \<noteq> None })"
proof (intro subsetI, elim CollectE)
fix c'
assume "(c, c') \<in> rtrancl r"
thus "c' \<in> insert c (theNextCell ` { c. nextCell c \<noteq> None })"
proof (induct rule: rtrancl_induct)
case (step c c') hence cc': "(c, c') \<in> r" by simp
show ?case
proof (intro insertI2 image_eqI CollectI)
from cc' show "nextCell c \<noteq> None" by (auto simp add: r_def)
from cc' show "c' = theNextCell c"
by (auto simp add: r_def theNextCell_def)
qed
qed simp
qed
from finite_subset [OF this] finiteNext show ?thesis by auto
qed
lemma next_step:
assumes c12: "(c1, c2) \<in> r" and c13: "(c1, c3) \<in> trancl r"
shows "(c2, c3) \<in> rtrancl r"
proof -
from c13 obtain tmp where 1: "(c1, tmp) \<in> r" and 2: "(tmp, c3) \<in> rtrancl r" by (metis tranclD)
from 1 c12 have "tmp = c2" by (intro unique_successor)
with 2 show ?thesis by simp
qed
lemma tight_loop_eq:
assumes cc': "(c, c') \<in> rtrancl r" and loop: "(c, c) \<in> r"
shows "c' = c"
using cc'
proof (induct rule: rtrancl_induct)
case (step c' c'') hence "(c, c'') \<in> r" by simp
with loop show ?case by (intro unique_successor)
qed simp
lemma loopExists_always_ahead:
assumes "loopExists"
shows "\<exists> c. (headCell, c) \<in> rtrancl r \<and> (\<forall> c'. (headCell, c') \<in> rtrancl r \<longrightarrow> (c', c) \<in> trancl r)"
proof -
from assms obtain cLoop
where hd_cLoop: "(headCell, cLoop) \<in> rtrancl r" and cLoop: "(cLoop, cLoop) \<in> trancl r"
unfolding loopExists_def by auto
show ?thesis
proof (intro exI [where x = cLoop] conjI allI impI hd_cLoop)
fix c assume "(headCell, c) \<in> rtrancl r"
hence "(c, cLoop) \<in> rtrancl r"
proof (induct c rule: rtrancl_induct)
case base from hd_cLoop show ?case.
next
case (step c c')
show ?case
proof (intro next_step)
from step show "(c, c') \<in> r" by simp
from step have "(c, cLoop) \<in> r\<^sup>*" by simp
also note cLoop finally show "(c, cLoop) \<in> trancl r".
qed
qed
also note cLoop
finally show "(c, cLoop) \<in> trancl r".
qed
qed
lemma loopExists_no_end:
"loopExists = (\<forall> c. (headCell, c) \<in> rtrancl r \<longrightarrow> nextCell c \<noteq> None)"
proof (cases loopExists)
case False
hence noLoop: "\<And>c. (headCell, c) \<in> rtrancl r \<Longrightarrow> (c,c) \<notin> trancl r" by (auto simp add: loopExists_def)
define c where "c \<equiv> headCell"
have hd_c: "(headCell, c) \<in> rtrancl r" by (auto simp add: c_def)
define S where "S = { c'. (c, c') \<in> rtrancl r }"
from finiteList have finite_S: "finite S" by (simp add: S_def)
from wf_finite_psubset finite_S hd_c S_def have "\<exists> c' \<in> S. nextCell c' = None"
proof (induct S arbitrary: c rule: wf_induct_rule)
case (less S)
thus ?case
proof (cases "nextCell c")
case (Some c')
hence cc': "(c, c') \<in> r" by (auto simp add: r_def)
define S' where "S' = {c''. (c', c'') \<in> rtrancl r }"
have S'_subset_S: "S' \<subseteq> S"
unfolding S'_def
proof (intro subsetI, elim CollectE)
fix c'' assume "(c', c'') \<in> rtrancl r"
with cc' show "c'' \<in> S" by (simp add: less)
qed
have "\<exists>c'' \<in> S'. nextCell c'' = None"
proof (intro less iffD2 [OF in_finite_psubset] conjI psubsetI S'_subset_S notI)
from less have "(headCell, c) \<in> rtrancl r" by simp also note cc'
finally show "(headCell, c') \<in> rtrancl r".
from less S'_subset_S show "finite S'" using infinite_super by blast
have "c \<in> S" by (simp add: less)
moreover assume "S' = S"
ultimately have "(c', c) \<in> rtrancl r" by (auto simp add: S'_def)
from rtranclD [OF this] show False
proof (elim disjE conjE)
assume "c' = c" with cc' noLoop less show False by auto
next
note cc' also assume "(c', c) \<in> trancl r"
finally show False using noLoop less by auto
qed
qed (simp add: S'_def)
with S'_subset_S show ?thesis by auto
qed auto
qed
with False show ?thesis by (auto simp add: S_def c_def)
next
case True
with loopExists_always_ahead obtain cLoop
where hd_cLoop: "(headCell, cLoop) \<in> rtrancl r"
and cLoop: "\<And>c. (headCell, c) \<in> rtrancl r \<Longrightarrow> (c, cLoop) \<in> trancl r" by auto
show ?thesis
proof (intro iffI allI impI notI True)
fix c assume "(headCell, c) \<in> rtrancl r"
hence "(c, cLoop) \<in> trancl r" by (simp add: cLoop)
then obtain c' where "(c, c') \<in> r" by (metis tranclD)
moreover assume "nextCell c = None"
ultimately show False by (simp add: r_def)
qed
qed
end
context TortoiseHare
begin
definition Invariant :: stpred
where "Invariant \<equiv> PRED hasLoop = #None \<longrightarrow> ((#headCell, tortoise) \<in> #(rtrancl r) \<and> (tortoise, hare) \<in> #(rtrancl r))"
definition Safety :: stpred where "Safety \<equiv> PRED Invariant \<and> hasLoop \<noteq> #(Some (\<not> loopExists))"
lemma square_Next_cases [consumes 2, case_names unchanged Step FoundLoop LastHare PenultimateHare]:
assumes s_Safety: "s \<Turnstile> Safety" and sq_Next: "(s,t) \<Turnstile> [Next]_(tortoise, hare, hasLoop)"
assumes unchanged: "
\<lbrakk> tortoise t = tortoise s
; hare t = hare s
; hasLoop t = hasLoop s
; (s,t) \<Turnstile> \<not>Step
; (s,t) \<Turnstile> \<not>Finish
\<rbrakk> \<Longrightarrow> P"
assumes Step: "\<And>h'.
\<lbrakk> hare t \<noteq> tortoise t
; hasLoop s = None
; hasLoop t = None
; (headCell, tortoise s) \<in> rtrancl r
; (headCell, hare s) \<in> rtrancl r
; (headCell, tortoise t) \<in> trancl r
; (headCell, h') \<in> trancl r
; (headCell, hare t) \<in> trancl r
; (tortoise s, hare s) \<in> rtrancl r
; (tortoise s, tortoise t) \<in> r
; (tortoise s, h') \<in> trancl r
; (tortoise s, hare t) \<in> trancl r
; (hare s, h') \<in> r
; (hare s, hare t) \<in> trancl r
; (tortoise t, h') \<in> rtrancl r
; (tortoise t, hare t) \<in> trancl r
; (h', hare t) \<in> r
; (s,t) \<Turnstile> Step
; (s,t) \<Turnstile> \<not>Finish
; (s,t) \<Turnstile> \<not>unchanged(tortoise, hare, hasLoop)
\<rbrakk> \<Longrightarrow> P"
assumes FoundLoop: "\<And>h'.
\<lbrakk> hare t = tortoise t
; hasLoop s = None
; hasLoop t = Some True
; loopExists
; (headCell, tortoise s) \<in> rtrancl r
; (headCell, hare s) \<in> rtrancl r
; (headCell, tortoise t) \<in> trancl r
; (headCell, h') \<in> trancl r
; (headCell, hare t) \<in> trancl r
; (tortoise s, hare s) \<in> rtrancl r
; (tortoise s, tortoise t) \<in> r
; (tortoise s, h') \<in> trancl r
; (tortoise s, hare t) \<in> trancl r
; (hare s, h') \<in> r
; (hare s, hare t) \<in> trancl r
; (tortoise t, h') \<in> rtrancl r
; (tortoise t, hare t) \<in> trancl r
; (h', hare t) \<in> r
; (s,t) \<Turnstile> Step
; (s,t) \<Turnstile> \<not>Finish
; (s,t) \<Turnstile> \<not>unchanged(tortoise, hare, hasLoop)
\<rbrakk> \<Longrightarrow> P"
assumes LastHare: "
\<lbrakk> hasLoop s = None
; hasLoop t = Some False
; \<not> loopExists
; nextCell (hare s) = None
; (headCell, tortoise s) \<in> rtrancl r
; (headCell, hare s) \<in> rtrancl r
; (tortoise s, hare s) \<in> rtrancl r
; (s,t) \<Turnstile> \<not>Step
; (s,t) \<Turnstile> Finish
; (s,t) \<Turnstile> \<not>unchanged(tortoise, hare, hasLoop)
\<rbrakk> \<Longrightarrow> P"
assumes PenultimateHare: "\<And>h'.
\<lbrakk> hasLoop s = None
; hasLoop t = Some False
; \<not> loopExists
; (hare s, h') \<in> r
; nextCell h' = None
; (headCell, tortoise s) \<in> rtrancl r
; (headCell, hare s) \<in> rtrancl r
; (headCell, h') \<in> trancl r
; (tortoise s, hare s) \<in> rtrancl r
; (tortoise s, h') \<in> trancl r
; (hare s, h') \<in> r
; (s,t) \<Turnstile> \<not>Step
; (s,t) \<Turnstile> Finish
; (s,t) \<Turnstile> \<not>unchanged(tortoise, hare, hasLoop)
\<rbrakk> \<Longrightarrow> P"
shows P
proof -
from sq_Next consider
(unchanged) "(s,t) \<Turnstile> unchanged (tortoise, hare, hasLoop)" "(s,t) \<Turnstile> \<not>Step"
| (Step) "(s,t) \<Turnstile> Step"
| (Finish) "(s,t) \<Turnstile> Finish" "(s,t) \<Turnstile> \<not>Step"
unfolding square_def Next_def by auto
then show P
proof cases
case p: unchanged
from p have notFinish: "(s,t) \<Turnstile> \<not>Finish" by (auto simp add: Finish_def)
from p unchanged s_Safety notFinish show ?thesis by auto
next
case p: Step
with s_Safety obtain h' where h': "(hare s, h') \<in> r" "(h', hare t) \<in> r" "(tortoise s, tortoise t) \<in> r"
"(headCell, tortoise s) \<in> rtrancl r" "(tortoise s, hare s) \<in> rtrancl r"
by (cases "nextCell (hare s)", auto simp add: Step_def nextNextCell_def r_def Safety_def Invariant_def)
have "(tortoise t, h') \<in> rtrancl r"
proof (cases "tortoise s = hare s")
case True with h' have "tortoise t = h'"
by (intro unique_successor [OF `(tortoise s, tortoise t) \<in> r`], simp)
thus ?thesis by simp
next
case False
with h' show ?thesis
by (intro next_step [OF `(tortoise s, tortoise t) \<in> r`], auto)
qed
with h' have rels:
"(headCell, tortoise s) \<in> rtrancl r"
"(headCell, hare s) \<in> rtrancl r"
"(headCell, tortoise t) \<in> trancl r"
"(headCell, h') \<in> trancl r"
"(headCell, hare t) \<in> trancl r"
"(tortoise s, hare s) \<in> rtrancl r"
"(tortoise s, tortoise t) \<in> r"
"(tortoise s, h') \<in> trancl r"
"(tortoise s, hare t) \<in> trancl r"
"(hare s, h') \<in> r"
"(hare s, hare t) \<in> trancl r"
"(tortoise t, h') \<in> rtrancl r"
"(tortoise t, hare t) \<in> trancl r"
"(h', hare t) \<in> r"
by auto
from p have notFinish: "(s,t) \<Turnstile> \<not>Finish" by (auto simp add: Step_def Finish_def)
show ?thesis
proof (cases "hare t = tortoise t")
case False
have changed: "tortoise t \<noteq> tortoise s"
proof (intro notI)
assume "tortoise t = tortoise s"
with rels have loop: "(tortoise t, tortoise t) \<in> r" by simp
hence "\<And>c. (tortoise t, c) \<in> trancl r \<Longrightarrow> c = tortoise t" by (intro tight_loop_eq, auto)
with rels False show False by simp
qed
from False p rels notFinish changed show ?thesis by (intro Step, auto simp add: Step_def)
next
case True
from rels have "(headCell, hare t) \<in> rtrancl r" "(hare t, hare t) \<in> trancl r" by (auto simp add: True)
hence loopExists by (auto simp add: loopExists_def)
with True p rels notFinish show ?thesis by (intro FoundLoop, auto simp add: Step_def)
qed
next
case p: Finish
with s_Safety have rels1:
"(headCell, tortoise s) \<in> rtrancl r"
"(headCell, hare s) \<in> rtrancl r"
"(tortoise s, hare s) \<in> rtrancl r"
by (auto simp add: Safety_def Invariant_def Finish_def)
show ?thesis
proof (cases "nextCell (hare s)")
case None
with rels1 have "\<not> loopExists" unfolding loopExists_no_end by auto
with None p rels1 show ?thesis by (intro LastHare, auto simp add: Finish_def)
next
case (Some h')
hence "(hare s, h') \<in> r" by (auto simp add: r_def)
with rels1 have rels2:
"(headCell, h') \<in> trancl r"
"(tortoise s, h') \<in> trancl r"
"(hare s, h') \<in> r"
by auto
from rels2 p Some have "\<not> loopExists"
unfolding loopExists_no_end by (auto simp add: Finish_def nextNextCell_def)
with rels1 rels2 p show ?thesis
by (intro PenultimateHare, auto simp add: Finish_def nextNextCell_def Some)
qed
qed
qed
lemma safety: "\<turnstile> Spec \<longrightarrow> \<box>Safety"
proof invariant
fix sigma
assume sigma: "sigma \<Turnstile> Spec"
thus "sigma \<Turnstile> Init Safety"
unfolding Invariant_def Safety_def Spec_def Initial_def r_def
by (auto simp add: Init_def)
show "sigma \<Turnstile> stable Safety"
proof (intro Stable)
from sigma show "sigma \<Turnstile> \<box>[Next]_(tortoise, hare, hasLoop)"
by (auto simp add: Spec_def)
show "\<turnstile> $Safety \<and> [Next]_(tortoise, hare, hasLoop) \<longrightarrow> Safety$"
proof (intro actionI temp_impI, elim temp_conjE, unfold unl_before)
fix s t
assume "s \<Turnstile> Safety" "(s,t) \<Turnstile> [Next]_(tortoise, hare, hasLoop)"
thus "(s,t) \<Turnstile> Safety$"
by (cases rule: square_Next_cases, auto simp add: Safety_def Invariant_def loopExists_no_end)
qed
qed
qed
end
context LinkedList begin
fun iterateNextCell :: "nat \<Rightarrow> 'Cell \<Rightarrow> 'Cell option"
where "iterateNextCell 0 c = Some c"
| "iterateNextCell (Suc n) c = (case iterateNextCell n c of None \<Rightarrow> None | Some c' \<Rightarrow> nextCell c')"
lemma iterateNextCell_sum: "iterateNextCell (a + b) c = (case iterateNextCell a c of None \<Rightarrow> None | Some c' \<Rightarrow> iterateNextCell b c')"
by (induct b, (cases "iterateNextCell a c", auto)+)
definition distanceBetween :: "'Cell \<Rightarrow> 'Cell \<Rightarrow> nat"
where "distanceBetween c1 c2 \<equiv> LEAST n. iterateNextCell n c1 = Some c2"
definition distanceBetweenOrZero :: "'Cell \<Rightarrow> 'Cell \<Rightarrow> nat"
where "distanceBetweenOrZero c1 c2 \<equiv> if (c1, c2) \<in> rtrancl r then LEAST n. iterateNextCell n c1 = Some c2 else 0"
lemma
assumes "(c1, c2) \<in> rtrancl r"
shows iterateNextCell_distanceBetween: "iterateNextCell (distanceBetween c1 c2) c1 = Some c2"
proof -
from assms obtain n where n: "iterateNextCell n c1 = Some c2"
proof (induct c2 arbitrary: thesis rule: rtrancl_induct)
case base
show thesis by (simp add: base [of 0])
next
case (step c2 c3)
then obtain n where n: "iterateNextCell n c1 = Some c2" by blast
from step have "iterateNextCell (Suc n) c1 = Some c3" by (simp add: n r_def)
with step show thesis by blast
qed
thus ?thesis unfolding distanceBetween_def by (intro LeastI)
qed
lemma distanceBetween_atMost:
assumes "iterateNextCell n c1 = Some c2" shows "distanceBetween c1 c2 \<le> n"
unfolding distanceBetween_def by (intro Least_le assms)
lemma distanceBetween_0 [simp]: "distanceBetween c c = 0"
unfolding distanceBetween_def by auto
lemma distanceBetween_0_eq:
assumes "(c1, c2) \<in> rtrancl r"
shows "(distanceBetween c1 c2 = 0) = (c1 = c2)"
using iterateNextCell_distanceBetween [OF assms]
by (intro iffI, simp_all)
lemma distanceBetween_le_1:
assumes "(c1, c2) \<in> r" shows "distanceBetween c1 c2 \<le> 1"
using assms by (intro distanceBetween_atMost, simp add: r_def)
lemma distanceBetween_triangle:
assumes c12: "(c1, c2) \<in> rtrancl r" and c23: "(c2, c3) \<in> rtrancl r"
shows "distanceBetween c1 c3 \<le> distanceBetween c1 c2 + distanceBetween c2 c3"
by (intro distanceBetween_atMost, simp add: iterateNextCell_sum
iterateNextCell_distanceBetween [OF c12] iterateNextCell_distanceBetween [OF c23])
lemma distanceBetween_eq_Suc:
assumes c13: "(c1, c3) \<in> rtrancl r" and c13_ne: "c1 \<noteq> c3" and c12: "(c1, c2) \<in> r"
shows "distanceBetween c1 c3 = Suc (distanceBetween c2 c3)"
using c13 unfolding rtrancl_eq_or_trancl
proof (elim disjE conjE, simp_all add: c13_ne)
assume "(c1, c3) \<in> trancl r"
with c12 have c23: "(c2, c3) \<in> rtrancl r" by (intro next_step)
from c12 have nextCell_c1[simp]: "nextCell c1 = Some c2" by (auto simp add: r_def)
have iterateNextCell_Suc: "\<And>n. iterateNextCell (Suc n) c1 = iterateNextCell n c2"
proof -
fix n
have "iterateNextCell (Suc n) c1 = iterateNextCell (1 + n) c1" by simp
also note iterateNextCell_sum
finally show "?thesis n" by simp
qed
have "distanceBetween c1 c3 = (LEAST n. iterateNextCell n c1 = Some c3)" by (simp add: distanceBetween_def)
also have "... = Suc (distanceBetween c2 c3)"
proof (intro Least_equality)
have "iterateNextCell (Suc (distanceBetween c2 c3)) c1 = iterateNextCell (distanceBetween c2 c3) c2"
by (intro iterateNextCell_Suc)
also have "... = Some c3" by (intro iterateNextCell_distanceBetween c23)
finally show "iterateNextCell (Suc (distanceBetween c2 c3)) c1 = Some c3".
fix n
assume a: "iterateNextCell n c1 = Some c3"
from a c13_ne show "Suc (distanceBetween c2 c3) \<le> n"
proof (cases n)
case (Suc m)
have "distanceBetween c2 c3 \<le> m"
using iterateNextCell_Suc [of m] a
unfolding distanceBetween_def Suc
by (intro Least_le, auto)
thus ?thesis by (simp add: Suc)
qed simp
qed
finally show ?thesis .
qed
lemma loop_unique_previous:
assumes c1c: "(c1, c) \<in> r" and c1_loop: "(c1, c1) \<in> trancl r"
assumes c2c: "(c2, c) \<in> r" and c2_loop: "(c2, c2) \<in> trancl r"
shows "c1 = c2"
proof -
from assms have cc1: "(c, c1) \<in> rtrancl r" and cc2: "(c, c2) \<in> rtrancl r" by (metis next_step)+
define n1 where "n1 \<equiv> distanceBetween c c1"
have n1_c1: "iterateNextCell n1 c = Some c1"
unfolding n1_def by (intro iterateNextCell_distanceBetween cc1)
have i1_c2: "iterateNextCell 1 c2 = Some c" using c2c by (auto simp add: r_def)
from cc2 have "iterateNextCell (1 + n1) c2 = Some c2"
proof (induct rule: rtrancl_induct)
case base
from n1_c1 c1c show ?case by (simp add: r_def)
next
case (step c' c'')
hence 1: "iterateNextCell 1 c' = Some c''" by (auto simp add: r_def)
from step have "Some c' = iterateNextCell (Suc n1) c'" by simp
also have "... = iterateNextCell (1 + n1) c'" by simp
also from step have "... = iterateNextCell n1 c''"
unfolding iterateNextCell_sum 1 by simp
finally have 2: "iterateNextCell n1 c'' = Some c'" by simp
have "iterateNextCell (n1 + 1) c'' = Some c''"
unfolding iterateNextCell_sum 2 using step by (simp add: r_def)
thus ?case by simp
qed
hence "iterateNextCell n1 c = Some c2" unfolding iterateNextCell_sum i1_c2 by auto
with n1_c1 show ?thesis by simp
qed
end
context TortoiseHare begin
lemma WF1_Spec:
fixes A :: action
fixes P Q :: stpred
assumes 0: "\<turnstile> Spec \<longrightarrow> WF(A)_(tortoise, hare, hasLoop)"
assumes 1: "\<And>s t. \<lbrakk> s \<Turnstile> P; s \<Turnstile> Safety; (s,t) \<Turnstile> [Next]_(tortoise, hare, hasLoop) \<rbrakk> \<Longrightarrow> t \<Turnstile> P \<or> Q"
assumes 2: "\<And>s t. \<lbrakk> s \<Turnstile> P; s \<Turnstile> Safety; (s,t) \<Turnstile> [Next]_(tortoise, hare, hasLoop) \<rbrakk> \<Longrightarrow> s \<Turnstile> Enabled(<A>_(tortoise, hare, hasLoop))"
assumes 3: "\<And>s t. \<lbrakk> s \<Turnstile> P; s \<Turnstile> Safety; (s,t) \<Turnstile> [Next]_(tortoise, hare, hasLoop); (s,t) \<Turnstile> A; (s,t) \<Turnstile> \<not>unchanged (tortoise, hare, hasLoop) \<rbrakk> \<Longrightarrow> t \<Turnstile> Q"
shows "\<turnstile> Spec \<longrightarrow> (P \<leadsto> Q)"
proof -
from safety have "\<turnstile> Spec \<longrightarrow> \<box>$Safety"
by (auto simp add: more_temp_simps)
moreover note 0
moreover have "\<turnstile> Spec \<longrightarrow> \<box>[Next]_(tortoise, hare, hasLoop)" by (auto simp add: Spec_def)
ultimately have "\<turnstile> Spec \<longrightarrow> \<box>($Safety \<and> [Next]_(tortoise, hare, hasLoop)) \<and> WF(A)_(tortoise, hare, hasLoop)"
by (auto simp add: more_temp_simps Valid_def)
also have "\<turnstile> \<box>($Safety \<and> [Next]_(tortoise, hare, hasLoop)) \<and> WF(A)_(tortoise, hare, hasLoop)
\<longrightarrow> (P \<leadsto> Q)"
proof (intro WF1 actionI temp_impI)
from 1 show "\<And>s t. (s, t) \<Turnstile> $P \<and> $Safety \<and> [Next]_(tortoise, hare, hasLoop) \<Longrightarrow> (s, t) \<Turnstile> P$ \<or> Q$" by auto
from 3 show "\<And>s t. (s, t) \<Turnstile> ($P \<and> $Safety \<and> [Next]_(tortoise, hare, hasLoop)) \<and> <A>_(tortoise, hare, hasLoop) \<Longrightarrow> (s,t) \<Turnstile> (Q$)" by auto
from 2 show "\<And>s t. (s, t) \<Turnstile> $P \<and> $Safety \<and> [Next]_(tortoise, hare, hasLoop) \<Longrightarrow> (s, t) \<Turnstile> ($Enabled (<A>_(tortoise, hare, hasLoop)))" by auto
qed
finally show ?thesis .
qed
lemma
assumes s_Safety: "s \<Turnstile> Safety"
assumes nextNext: "nextNextCell (hare s) \<noteq> None"
assumes notFinished: "hasLoop s = None"
shows Enabled_StepI: "s \<Turnstile> Enabled (<Step>_(tortoise, hare, hasLoop))"
proof -
from nextNext obtain h' h'' where h': "(hare s, h') \<in> r" and h'': "(h', h'') \<in> r"
by (cases "nextCell (hare s)", auto simp add: nextNextCell_def r_def)
from notFinished s_Safety
have t_h: "(tortoise s, hare s) \<in> rtrancl r" by (auto simp add: Safety_def Invariant_def)
from rtranclD [OF this] obtain t' where t': "(tortoise s, t') \<in> r"
proof (elim disjE conjE)
assume "tortoise s = hare s"
with h' show ?thesis by (intro that, auto)
next
assume "(tortoise s, hare s) \<in> trancl r"
from tranclD [OF this] that
show ?thesis by auto
qed
show "s \<Turnstile> Enabled (<Step>_(tortoise, hare, hasLoop))"
proof (enabled bv, intro exI allI impI, elim conjE)
fix u
assume u: "tortoise u = t'" "hare u = h''" "hasLoop u = (if t' = h'' then Some True else None)"
have changed: "tortoise u \<noteq> tortoise s \<or> hasLoop u \<noteq> hasLoop s"
proof (intro disjCI notI, simp)
assume "tortoise u = tortoise s" with t' have loop: "(tortoise s, tortoise s) \<in> r" by (simp add: u)
from t' have "t' = tortoise s" by (intro tight_loop_eq loop, simp)
moreover have "h'' = tortoise s"
proof (intro tight_loop_eq loop)
from s_Safety notFinished have "(tortoise s, hare s) \<in> rtrancl r"
by (auto simp add: Safety_def Invariant_def)
with h' h'' show "(tortoise s, h'') \<in> rtrancl r" by auto
qed
moreover assume "hasLoop u = hasLoop s"
ultimately show False by (auto simp add: u notFinished)
qed
from notFinished h' h'' t' have s_simps [simp]: "nextCell (hare s) = Some h'" "nextCell h' = Some h''" "nextCell (tortoise s) = Some t'"
by (auto simp add: r_def)
from notFinished changed show "(s, u) \<Turnstile> <Step>_(tortoise, hare, hasLoop)"
by (auto simp add: angle_def Step_def nextNextCell_def u)
qed
qed
lemma hare_endgame: "\<turnstile> Spec \<longrightarrow> (nextNextCell<hare> = #None \<leadsto> hasLoop \<noteq> #None)"
proof -
have "\<turnstile> Spec \<longrightarrow> (nextNextCell<hare> = #None
\<leadsto> hasLoop \<noteq> #None \<or> (nextNextCell<hare> = #None \<and> hasLoop = #None))"
by (intro imp_imp_leadsto, auto)
also have "\<turnstile> Spec \<longrightarrow> (hasLoop \<noteq> #None \<or> (nextNextCell<hare> = #None \<and> hasLoop = #None)
\<leadsto> hasLoop \<noteq> #None)"
proof (intro imp_disj_leadstoI [OF imp_leadsto_reflexive WF1_Spec])
show "\<turnstile> Spec \<longrightarrow> WF(Finish)_(tortoise, hare, hasLoop)" by (auto simp add: Spec_def)
fix s t
assume "s \<Turnstile> nextNextCell<hare> = #None \<and> hasLoop = #None"
hence s: "hasLoop s = None" "nextNextCell (hare s) = None" by auto
assume s_Safety: "s \<Turnstile> Safety" and Next: "(s, t) \<Turnstile> [Next]_(tortoise, hare, hasLoop)"
from s_Safety Next s
show "t \<Turnstile> (nextNextCell<hare> = #None \<and> hasLoop = #None) \<or> hasLoop \<noteq> #None"
proof (cases rule: square_Next_cases)
case (Step h')
hence "(hare s, h') \<in> r" "(h', hare t) \<in> r" by simp_all
with s show ?thesis by (simp add: nextNextCell_def r_def)
next
case (FoundLoop h')
hence "(hare s, h') \<in> r" "(h', hare t) \<in> r" by simp_all
with s show ?thesis by (simp add: nextNextCell_def r_def)
qed auto
show "s \<Turnstile> Enabled (<Finish>_(tortoise, hare, hasLoop))"
proof (enabled bv, intro exI allI impI, elim conjE)
fix u assume "hasLoop u = Some False" thus "(s, u) \<Turnstile> <Finish>_(tortoise, hare, hasLoop)"
by (auto simp add: angle_def Finish_def s)
qed
assume "(s,t) \<Turnstile> Finish"
thus "t \<Turnstile> hasLoop \<noteq> #None" by (auto simp add: Finish_def)
qed
finally show "\<turnstile> Spec \<longrightarrow> (nextNextCell<hare> = #None \<leadsto> hasLoop \<noteq> #None)" .
qed
lemma tortoise_visits_everywhere:
assumes hd_c: "(headCell, c) \<in> rtrancl r"
shows "\<turnstile> Spec \<longrightarrow> \<diamond>(hasLoop \<noteq> #None \<or> tortoise = #c)"
proof -
from hd_c have "\<turnstile> Spec \<longrightarrow> \<diamond>(hasLoop \<noteq> #None \<or> (tortoise, #c) \<in> #(rtrancl r))"
by (intro imp_eventually_init, auto simp add: Init_def Spec_def Initial_def)
also have "\<turnstile> Spec \<longrightarrow> (hasLoop \<noteq> #None \<or> (tortoise, #c) \<in> #(rtrancl r) \<leadsto> hasLoop \<noteq> #None \<or> tortoise = #c)"
proof (intro imp_disj_leadstoI)
show "\<turnstile> Spec \<longrightarrow> (hasLoop \<noteq> #None \<leadsto> hasLoop \<noteq> #None \<or> tortoise = #c)" by (intro imp_imp_leadsto, auto)
show "\<turnstile> Spec \<longrightarrow> ((tortoise, #c) \<in> #(rtrancl r) \<leadsto> hasLoop \<noteq> #None \<or> tortoise = #c)"
proof (rule imp_leadsto_triangle_excl [OF imp_leadsto_reflexive])
have "\<turnstile> Spec
\<longrightarrow> ((tortoise, #c) \<in> #(rtrancl r) \<and> \<not> (hasLoop \<noteq> #None \<or> tortoise = #c)
\<leadsto> (\<exists>n. (tortoise, #c) \<in> #(rtrancl r) \<and> hasLoop = #None \<and> tortoise \<noteq> #c \<and> distanceBetween<tortoise, #c> = #n))"
by (intro imp_imp_leadsto, auto)
also have "\<turnstile> Spec
\<longrightarrow> ((\<exists>n. (tortoise, #c) \<in> #(rtrancl r) \<and> hasLoop = #None \<and> tortoise \<noteq> #c \<and> distanceBetween<tortoise, #c> = #n)
\<leadsto> hasLoop \<noteq> #None \<or> tortoise = #c)"
proof (intro wf_imp_ex_leadsto [OF wf_less imp_leadsto_diamond])
fix n
show "\<turnstile> Spec \<longrightarrow> ((tortoise, #c) \<in> #(rtrancl r) \<and> hasLoop = #None \<and> tortoise \<noteq> #c \<and> distanceBetween<tortoise, #c> = #n
\<leadsto> ((tortoise, #c) \<in> #(rtrancl r) \<and> hasLoop = #None \<and> tortoise \<noteq> #c \<and> distanceBetween<tortoise, #c> = #n \<and> nextNextCell<hare> \<noteq> #None)
\<or> nextNextCell<hare> = #None)"
by (intro imp_imp_leadsto, auto)
have "\<turnstile> Spec \<longrightarrow> (nextNextCell<hare> = #None \<leadsto> hasLoop \<noteq> #None)" by (intro hare_endgame)
also have "\<turnstile> Spec \<longrightarrow> (hasLoop \<noteq> #None
\<leadsto> (hasLoop \<noteq> #None \<or> tortoise = #c)
\<or> (\<exists>n'. #((n', n) \<in> {(n, n'). n < n'}) \<and> (tortoise, #c) \<in> #(rtrancl r)
\<and> hasLoop = #None \<and> tortoise \<noteq> #c \<and> distanceBetween<tortoise, #c> = #n'))"
by (intro imp_imp_leadsto, auto)
finally show "\<turnstile> Spec \<longrightarrow> (nextNextCell<hare> = #None \<leadsto> (hasLoop \<noteq> #None \<or> tortoise = #c)
\<or> (\<exists>n'. #((n', n) \<in> {(n, n'). n < n'}) \<and> (tortoise, #c) \<in> #(rtrancl r)
\<and> hasLoop = #None \<and> tortoise \<noteq> #c \<and> distanceBetween<tortoise, #c> = #n'))".
show "\<turnstile> Spec
\<longrightarrow> ((tortoise, #c) \<in> #(rtrancl r) \<and> hasLoop = #None \<and> tortoise \<noteq> #c \<and> distanceBetween<tortoise, #c> = #n \<and> nextNextCell<hare> \<noteq> #None
\<leadsto> (hasLoop \<noteq> #None \<or> tortoise = #c)
\<or> (\<exists>n'. #((n', n) \<in> {(n, n'). n < n'}) \<and> (tortoise, #c) \<in> #(rtrancl r)
\<and> hasLoop = #None \<and> tortoise \<noteq> #c \<and> distanceBetween<tortoise, #c> = #n'))"
proof (intro WF1_Spec)
show "\<turnstile> Spec \<longrightarrow> WF(Step)_(tortoise, hare, hasLoop)" by (auto simp add: Spec_def)
fix s t
assume "s \<Turnstile> (tortoise, #c) \<in> #(rtrancl r) \<and> hasLoop = #None \<and> tortoise \<noteq> #c \<and> distanceBetween<tortoise, #c> = #n \<and> nextNextCell<hare> \<noteq> #None"
then obtain h' h'' where s: "hasLoop s = None" "distanceBetween (tortoise s) c = n" "tortoise s \<noteq> c"
and rels1: "(tortoise s, c) \<in> rtrancl r" "(hare s, h') \<in> r" "(h', h'') \<in> r"
by (cases "nextCell (hare s)", auto simp add: r_def nextNextCell_def)
assume s_Safety: "s \<Turnstile> Safety" and Next: "(s, t) \<Turnstile> [Next]_(tortoise, hare, hasLoop)"
from rels1
show "s \<Turnstile> Enabled (<Step>_(tortoise, hare, hasLoop))"
by (intro Enabled_StepI s_Safety s, auto simp add: nextNextCell_def r_def)
from s_Safety Next
show "t \<Turnstile> (hasLoop \<noteq> #None \<or> tortoise = #c)
\<or> (\<exists>n'. #((n', n) \<in> {(n, n'). n < n'}) \<and> (tortoise, #c) \<in> #(rtrancl r)
\<and> hasLoop = #None \<and> tortoise \<noteq> #c \<and> distanceBetween<tortoise, #c> = #n')"
if is_Step: "(s,t) \<Turnstile> Step"
using is_Step
proof (cases rule: square_Next_cases)
case (Step h1)
from s rels1 distanceBetween_0_eq show ?thesis
proof (cases n)
case (Suc n')
show ?thesis
proof (cases "tortoise t = c")
case True thus ?thesis by simp
next
case False
moreover from s rels1
have "(tortoise s, c) \<in> trancl r" by (metis rtranclD)
with Step have "(tortoise t, c) \<in> rtrancl r" by (intro next_step, auto)
moreover from Step have "hasLoop t = None" by simp
moreover from Step s rels1 have "distanceBetween (tortoise s) c = Suc (distanceBetween (tortoise t) c)"
by (intro distanceBetween_eq_Suc, auto)
with s have "distanceBetween (tortoise t) c < n" by auto
ultimately show ?thesis by auto
qed
qed auto
qed (auto simp add: nextNextCell_def r_def)
with s_Safety Next s rels1
show "t \<Turnstile> ((tortoise, #c) \<in> #(rtrancl r) \<and> hasLoop = #None \<and> tortoise \<noteq> #c
\<and> distanceBetween<tortoise, #c> = #n \<and> nextNextCell<hare> \<noteq> #None)
\<or> (hasLoop \<noteq> #None \<or> tortoise = #c)
\<or> (\<exists>n'. #((n', n) \<in> {(n, n'). n < n'}) \<and> (tortoise, #c) \<in> #(rtrancl r)
\<and> hasLoop = #None \<and> tortoise \<noteq> #c \<and> distanceBetween<tortoise, #c> = #n')"
by (cases rule: square_Next_cases, auto simp add: nextNextCell_def r_def)
qed
qed
finally show "\<turnstile> Spec \<longrightarrow> ((tortoise, #c) \<in> #(rtrancl r) \<and> \<not> (hasLoop \<noteq> #None \<or> tortoise = #c) \<leadsto> hasLoop \<noteq> #None \<or> tortoise = #c)".
qed
qed
finally show ?thesis.
qed
theorem liveness: "\<turnstile> Spec \<longrightarrow> \<diamond>(hasLoop \<noteq> #None)"
proof (cases loopExists)
case False
with loopExists_no_end obtain cLast
where hd_cLast: "(headCell, cLast) \<in> rtrancl r" and cLast: "nextCell cLast = None" by auto
have "\<turnstile> Spec \<longrightarrow> \<diamond>(hasLoop \<noteq> #None \<or> tortoise = #cLast)"
by (intro tortoise_visits_everywhere hd_cLast)
also have "\<turnstile> Spec \<longrightarrow> (hasLoop \<noteq> #None \<or> tortoise = #cLast \<leadsto> hasLoop \<noteq> #None \<or> (tortoise = #cLast \<and> hasLoop = #None))"
by (intro imp_imp_leadsto, auto)
also have "\<turnstile> Spec \<longrightarrow> (hasLoop \<noteq> #None \<or> (tortoise = #cLast \<and> hasLoop = #None) \<leadsto> hasLoop \<noteq> #None)"
proof (intro imp_disj_leadstoI imp_leadsto_reflexive)
have "\<turnstile> Spec \<longrightarrow> (tortoise = #cLast \<and> hasLoop = #None \<leadsto> nextNextCell<hare> = #None)"
proof (intro imp_INV_leadsto [OF safety imp_imp_leadsto] intI temp_impI, elim temp_conjE)
fix s
assume s: "s \<Turnstile> tortoise = #cLast" "s \<Turnstile> Safety" "s \<Turnstile> hasLoop = #None"
hence "(cLast, hare s) \<in> rtrancl r"
by (auto simp add: Safety_def Invariant_def)
from rtranclD [OF this]
have "hare s = cLast"
proof (elim disjE conjE)
assume "(cLast, hare s) \<in> trancl r" from tranclD [OF this] cLast show ?thesis by (auto simp add: r_def)
qed simp
with cLast show "s \<Turnstile> nextNextCell<hare> = #None"
by (cases "nextCell (hare s)", auto simp add: nextNextCell_def)
qed
also note hare_endgame
finally show "\<turnstile> Spec \<longrightarrow> (tortoise = #cLast \<and> hasLoop = #None \<leadsto> hasLoop \<noteq> #None)" .
qed
finally show ?thesis .
next
case True
with loopExists_always_ahead obtain cLoop where hd_cLoop: "(headCell, cLoop) \<in> rtrancl r"
and cLoop_ahead: "\<And>c. (headCell, c) \<in> rtrancl r \<Longrightarrow> (c, cLoop) \<in> trancl r" by auto
have "\<turnstile> Spec \<longrightarrow> \<diamond>(hasLoop \<noteq> #None \<or> tortoise = #cLoop)"
by (intro tortoise_visits_everywhere hd_cLoop)
also have "\<turnstile> Spec \<longrightarrow> (hasLoop \<noteq> #None \<or> tortoise = #cLoop \<leadsto> hasLoop \<noteq> #None \<or> (hasLoop = #None \<and> (#cLoop, tortoise) \<in> #(trancl r)))"
using cLoop_ahead by (intro imp_INV_leadsto [OF safety imp_imp_leadsto], auto simp add: Safety_def Invariant_def)
also have "\<turnstile> Spec \<longrightarrow> (hasLoop \<noteq> #None \<or> (hasLoop = #None \<and> (#cLoop, tortoise) \<in> #(trancl r)) \<leadsto> hasLoop \<noteq> #None)"
proof (intro imp_disj_leadstoI imp_leadsto_reflexive)
have "\<turnstile> Spec \<longrightarrow> (hasLoop = #None \<and> (#cLoop, tortoise) \<in> #(trancl r)
\<leadsto> (\<exists> inductor. hasLoop = #None \<and> (#cLoop, tortoise) \<in> #(trancl r) \<and> #inductor = (tortoise = hare, distanceBetween<hare, tortoise>)))"
by (intro imp_imp_leadsto, auto)
also have "\<turnstile> Spec \<longrightarrow> ((\<exists> inductor. hasLoop = #None \<and> (#cLoop, tortoise) \<in> #(trancl r) \<and> #inductor = (tortoise = hare, distanceBetween<hare, tortoise>))
\<leadsto> hasLoop \<noteq> #None)"
proof (intro wf_imp_ex_leadsto)
show "wf ({(False, True)} <*lex*> {(i::nat,j). i < j})" by (intro wf_lex_prod wf_less, auto)
fix inductor
show "\<turnstile> Spec \<longrightarrow> (hasLoop = #None \<and> (#cLoop, tortoise) \<in> #(trancl r) \<and> #inductor = (tortoise = hare, distanceBetween<hare, tortoise>)
\<leadsto> hasLoop \<noteq> #None \<or> (\<exists>inductor'. #((inductor', inductor) \<in> {(False, True)} <*lex*> {(i, j). i < j})
\<and> hasLoop = #None \<and> (#cLoop, tortoise) \<in> #(trancl r) \<and> #inductor' = (tortoise = hare, distanceBetween<hare, tortoise>)))"
proof (intro WF1_Spec)
show "\<turnstile> Spec \<longrightarrow> WF(Step)_(tortoise, hare, hasLoop)"
by (auto simp add: Spec_def)
obtain hare_tortoise_eq hare_tortoise_distance where inductor: "inductor = (hare_tortoise_eq, hare_tortoise_distance)" by (cases inductor)
fix s t
assume "s \<Turnstile> hasLoop = #None \<and> (#cLoop, tortoise) \<in> #(trancl r) \<and> #inductor = (tortoise = hare, distanceBetween<hare, tortoise>)"
hence s: "hasLoop s = None" "(cLoop, tortoise s) \<in> trancl r" "hare_tortoise_eq = (tortoise s = hare s)" "hare_tortoise_distance = distanceBetween (hare s) (tortoise s)"
by (simp_all add: inductor)
assume s_Safety: "s \<Turnstile> Safety" and Next: "(s, t) \<Turnstile> [Next]_(tortoise, hare, hasLoop)"
thus Step_lemma: "t \<Turnstile> hasLoop \<noteq> #None \<or> (\<exists>inductor'. #((inductor', inductor) \<in> {(False, True)} <*lex*> {(i, j). i < j})
\<and> hasLoop = #None \<and> (#cLoop, tortoise) \<in> #(trancl r)
\<and> #inductor' = (tortoise = hare, distanceBetween<hare, tortoise>))"
if Step: "(s,t) \<Turnstile> Step"
using Step
proof (cases rule: square_Next_cases)
case (Step h')
show ?thesis
proof (cases "hare s = tortoise s")
case True
with Step s show ?thesis by (simp add: inductor, intro exI [where x = False], auto)
next
case False
have "distanceBetween (hare s) (tortoise s) = Suc (distanceBetween h' (tortoise s))"
proof (intro distanceBetween_eq_Suc False Step)
from Step have "(hare s, cLoop) \<in> trancl r" by (intro cLoop_ahead)
also from s have "(cLoop, tortoise s) \<in> trancl r" by simp
finally show "(hare s, tortoise s) \<in> rtrancl r" by simp
qed
moreover have "distanceBetween h' (tortoise t) \<le> Suc (distanceBetween h' (tortoise s))"
proof -
from Step have "distanceBetween h' (tortoise t) \<le> distanceBetween h' (tortoise s)
+ distanceBetween (tortoise s) (tortoise t)"
proof (intro distanceBetween_triangle)
from Step have "(h', cLoop) \<in> trancl r" by (intro cLoop_ahead, simp)
also from s Step have "(cLoop, tortoise s) \<in> trancl r" by simp
finally show "(h', tortoise s) \<in> rtrancl r" by simp
qed simp
moreover from Step have "distanceBetween (tortoise s) (tortoise t) \<le> 1"
by (intro distanceBetween_le_1)
ultimately show ?thesis by auto
qed
moreover have "distanceBetween h' (tortoise t) = Suc (distanceBetween (hare t) (tortoise t))"
proof (intro distanceBetween_eq_Suc Step notI)
from Step have "(h', cLoop) \<in> trancl r" by (intro cLoop_ahead, simp)
also from s Step have "(cLoop, tortoise t) \<in> trancl r" by simp
finally show "(h', tortoise t) \<in> rtrancl r" by simp
assume eq: "h' = tortoise t"
have "hare s = tortoise s"
proof (intro loop_unique_previous)
from Step show "(hare s, h') \<in> r" "(tortoise s, h') \<in> r" by (auto simp add: eq)
from Step have "(hare s, cLoop) \<in> trancl r" by (intro cLoop_ahead)
also from s have "(cLoop, tortoise s) \<in> trancl r" by simp
also from Step have "(tortoise s, hare s) \<in> rtrancl r" by simp
finally show "(hare s, hare s) \<in> trancl r".
from Step have "(tortoise s, cLoop) \<in> trancl r" by (intro cLoop_ahead)
also from s have "(cLoop, tortoise s) \<in> trancl r" by simp
finally show "(tortoise s, tortoise s) \<in> trancl r".
qed
with False show False by simp
qed
moreover from s Step have "(cLoop, tortoise t) \<in> trancl r" by auto
ultimately show ?thesis using Step False by (simp add: inductor s, auto)
qed
qed simp_all
with s_Safety Next True
show "t \<Turnstile> hasLoop = #None \<and> (#cLoop, tortoise) \<in> #(trancl r) \<and> #inductor = (tortoise = hare, distanceBetween<hare, tortoise>) \<or>
hasLoop \<noteq> #None \<or>
(\<exists>inductor'. #((inductor', inductor) \<in> {(False, True)} <*lex*> {(i, j). i < j}) \<and>
hasLoop = #None \<and> (#cLoop, tortoise) \<in> #(trancl r) \<and> #inductor' = (tortoise = hare, distanceBetween<hare, tortoise>))"
proof (cases rule: square_Next_cases)
case unchanged with s show ?thesis by (auto simp add: inductor)
qed simp_all
from s_Safety s have hd_h: "(headCell, hare s) \<in> rtrancl r" by (auto simp add: Safety_def Invariant_def)
then obtain h' where h': "(hare s, h') \<in> r" by (metis tranclD cLoop_ahead)
note hd_h also note h' finally obtain h'' where h'': "(h', h'') \<in> r" by (metis tranclD cLoop_ahead)
from h' h'' show "s \<Turnstile> Enabled (<Step>_(tortoise, hare, hasLoop))"
by (intro Enabled_StepI s_Safety s, auto simp add: nextNextCell_def r_def)
qed
qed
finally show "\<turnstile> Spec \<longrightarrow> (hasLoop = #None \<and> (#cLoop, tortoise) \<in> #(trancl r) \<leadsto> hasLoop \<noteq> #None)" .
qed
finally show ?thesis .
qed
end
end
|
/* linalg/ldlt.c
*
* Copyright (C) 2018 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* L D L^T decomposition of a symmetric positive semi-definite matrix */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
static double ldlt_norm1(const gsl_matrix * A);
static int ldlt_Ainv(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params);
/*
gsl_linalg_ldlt_decomp()
Perform L D L^T decomposition of a symmetric positive
semi-definite matrix using lower triangle
Inputs: A - (input) symmetric, positive semi-definite matrix
(output) lower triangle contains L factor;
diagonal contains D
Return: success/error
Notes:
1) Based on algorithm 4.1.1 of Golub and Van Loan, Matrix Computations (4th ed).
2) The first subrow A(1, 2:end) is used as temporary workspace
3) The 1-norm ||A||_1 of the original matrix is stored in the upper right corner on output
*/
int
gsl_linalg_ldlt_decomp (gsl_matrix * A)
{
const size_t M = A->size1;
const size_t N = A->size2;
if (M != N)
{
GSL_ERROR ("LDLT decomposition requires square matrix", GSL_ENOTSQR);
}
else
{
size_t i, j;
double a00, anorm;
gsl_vector_view work, v;
/* check for quick return */
if (N == 1)
return GSL_SUCCESS;
/* compute ||A||_1 */
anorm = ldlt_norm1(A);
/* special case first column */
a00 = gsl_matrix_get(A, 0, 0);
if (a00 == 0.0)
{
GSL_ERROR ("matrix is singular", GSL_EDOM);
}
v = gsl_matrix_subcolumn(A, 0, 1, N - 1);
gsl_vector_scale(&v.vector, 1.0 / a00);
/* use first subrow A(1, 2:end) as temporary workspace */
work = gsl_matrix_subrow(A, 0, 1, N - 1);
for (j = 1; j < N; ++j)
{
gsl_vector_view w = gsl_vector_subvector(&work.vector, 0, j);
double ajj = gsl_matrix_get(A, j, j);
double dval;
for (i = 0; i < j; ++i)
{
double aii = gsl_matrix_get(A, i, i);
double aji = gsl_matrix_get(A, j, i);
gsl_vector_set(&w.vector, i, aji * aii);
}
v = gsl_matrix_subrow(A, j, 0, j); /* A(j,1:j-1) */
gsl_blas_ddot(&v.vector, &w.vector, &dval);
ajj -= dval;
if (ajj == 0.0)
{
GSL_ERROR ("matrix is singular", GSL_EDOM);
}
gsl_matrix_set(A, j, j, ajj);
if (j < N - 1)
{
double ajjinv = 1.0 / ajj;
gsl_matrix_view m = gsl_matrix_submatrix(A, j + 1, 0, N - j - 1, j); /* A(j+1:n, 1:j-1) */
v = gsl_matrix_subcolumn(A, j, j + 1, N - j - 1); /* A(j+1:n, j) */
gsl_blas_dgemv(CblasNoTrans, -ajjinv, &m.matrix, &w.vector, ajjinv, &v.vector);
}
}
/* save ||A||_1 in upper right corner */
gsl_matrix_set(A, 0, N - 1, anorm);
return GSL_SUCCESS;
}
}
int
gsl_linalg_ldlt_solve (const gsl_matrix * LDLT,
const gsl_vector * b,
gsl_vector * x)
{
if (LDLT->size1 != LDLT->size2)
{
GSL_ERROR ("LDLT matrix must be square", GSL_ENOTSQR);
}
else if (LDLT->size1 != b->size)
{
GSL_ERROR ("matrix size must match b size", GSL_EBADLEN);
}
else if (LDLT->size2 != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
int status;
/* copy x <- b */
gsl_vector_memcpy (x, b);
status = gsl_linalg_ldlt_svx(LDLT, x);
return status;
}
}
int
gsl_linalg_ldlt_svx (const gsl_matrix * LDLT,
gsl_vector * x)
{
if (LDLT->size1 != LDLT->size2)
{
GSL_ERROR ("LDLT matrix must be square", GSL_ENOTSQR);
}
else if (LDLT->size2 != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
gsl_vector_const_view diag = gsl_matrix_const_diagonal(LDLT);
/* solve for z using forward-substitution, L z = b */
gsl_blas_dtrsv (CblasLower, CblasNoTrans, CblasUnit, LDLT, x);
/* solve for y, D y = z */
gsl_vector_div(x, &diag.vector);
/* perform back-substitution, L^T x = y */
gsl_blas_dtrsv (CblasLower, CblasTrans, CblasUnit, LDLT, x);
return GSL_SUCCESS;
}
}
int
gsl_linalg_ldlt_rcond (const gsl_matrix * LDLT, double * rcond,
gsl_vector * work)
{
const size_t M = LDLT->size1;
const size_t N = LDLT->size2;
if (M != N)
{
GSL_ERROR ("LDLT matrix must be square", GSL_ENOTSQR);
}
else if (work->size != 3 * N)
{
GSL_ERROR ("work vector must have length 3*N", GSL_EBADLEN);
}
else
{
int status;
double Anorm; /* ||A||_1 */
double Ainvnorm; /* ||A^{-1}||_1 */
if (N == 1)
Anorm = fabs(gsl_matrix_get(LDLT, 0, 0));
else
Anorm = gsl_matrix_get(LDLT, 0, N - 1);
*rcond = 0.0;
/* don't continue if matrix is singular */
if (Anorm == 0.0)
return GSL_SUCCESS;
/* estimate ||A^{-1}||_1 */
status = gsl_linalg_invnorm1(N, ldlt_Ainv, (void *) LDLT, &Ainvnorm, work);
if (status)
return status;
if (Ainvnorm != 0.0)
*rcond = (1.0 / Anorm) / Ainvnorm;
return GSL_SUCCESS;
}
}
/* compute 1-norm of symmetric matrix stored in lower triangle */
static double
ldlt_norm1(const gsl_matrix * A)
{
const size_t N = A->size1;
double max = 0.0;
size_t i, j;
for (j = 0; j < N; ++j)
{
gsl_vector_const_view v = gsl_matrix_const_subcolumn(A, j, j, N - j);
double sum = gsl_blas_dasum(&v.vector);
/* now add symmetric elements from above diagonal */
for (i = 0; i < j; ++i)
{
double Aij = gsl_matrix_get(A, i, j);
sum += fabs(Aij);
}
if (sum > max)
max = sum;
}
return max;
}
/* x := A^{-1} x = A^{-t} x, A = L D L^T */
static int
ldlt_Ainv(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params)
{
int status;
gsl_matrix * A = (gsl_matrix * ) params;
gsl_vector_const_view diag = gsl_matrix_const_diagonal(A);
(void) TransA; /* unused parameter warning */
/* compute L^{-1} x */
status = gsl_blas_dtrsv(CblasLower, CblasNoTrans, CblasUnit, A, x);
if (status)
return status;
/* compute D^{-1} x */
gsl_vector_div(x, &diag.vector);
/* compute L^{-t} x */
status = gsl_blas_dtrsv(CblasLower, CblasTrans, CblasUnit, A, x);
if (status)
return status;
return GSL_SUCCESS;
}
|
Require Import Crypto.Arithmetic.PrimeFieldTheorems.
Require Import Crypto.Specific.solinas32_2e165m25_8limbs.Synthesis.
(* TODO : change this to field once field isomorphism happens *)
Definition carry :
{ carry : feBW_loose -> feBW_tight
| forall a, phiBW_tight (carry a) = (phiBW_loose a) }.
Proof.
Set Ltac Profiling.
Time synthesize_carry ().
Show Ltac Profile.
Time Defined.
Print Assumptions carry.
|
Powerplant : 2 × Rolls @-@ Royce Nene I turbojet , 22 kN ( 5 @,@ 000 lbf ) thrust each each
|
I started with the question… “ why do we have to do the things we don’t like “ . I’ve had to face uncomfortable situations recently, in doing things I really just don’t wanna do , because of situations I just don’t wanna be in .
I had to take a step back and re-evaluate that question . Like a really BIG step back . I’m the one who put myself in the unwanted situation, so why should I be angry at the fact I have to retrace my steps back now ?
Well I’ve come to the conclusion it’s all apart of my learning journey, learning where and what I don’t want to be .
Instead of thinking negatively and beating myself up about it , I’ve decided to look at the situation differently .
If life was all easy and everything went our way , how would we grow and evolve to be the person we were meant to be … well we wouldn’t , we wouldn’t have the same learnings and self discovery as a person who trekked the harder path.
I keep reminding myself with all the hardship comes a great reward . Changing my way of thinking is critical at this point … instead of “ I don’t want want to be here“ it’s needed to change too “ this is exactly where I need to be , this is my path I must walk or crawl“ .
A blessing in disguise , although I may hate and loath this part of my story right now , i know it will only make me stronger . I need to walk the hard yard ( and stay on it ! ) to get to where I want to be . Thinking back to past hardships and experiences , they were the times that taught me the most , that turned me into a strong resilient women . So changing the mindset now from negative to positive is imperative.
Lesson 26 : It’s the journey through the hard times that teach us who we are . |
#pragma once
#include <gsl/span>
#include <array>
#include "halley/core/api/audio_api.h"
namespace Halley
{
class AudioSource {
public:
virtual ~AudioSource() {}
virtual uint8_t getNumberOfChannels() const = 0;
virtual size_t getSamplesLeft() const = 0;
virtual bool isReady() const { return true; }
virtual bool getAudioData(size_t numSamples, AudioMultiChannelSamples dst) = 0;
};
}
|
[STATEMENT]
lemma overlappingI[intro]: "s \<lesssim> u \<Longrightarrow> t \<lesssim> u \<Longrightarrow> overlapping s t"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>s \<lesssim> u; t \<lesssim> u\<rbrakk> \<Longrightarrow> overlapping s t
[PROOF STEP]
unfolding overlapping_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>s \<lesssim> u; t \<lesssim> u\<rbrakk> \<Longrightarrow> \<exists>u. s \<lesssim> u \<and> t \<lesssim> u
[PROOF STEP]
by auto |
State Before: α : Type u_2
β : Type u_1
γ : Type ?u.14817
δ : Type ?u.14820
ι : Sort ?u.14823
s : Set α
t : Set β
f : Filter α
g : Filter β
⊢ f ×ˢ g = map (fun p => (p.snd, p.fst)) (g ×ˢ f) State After: α : Type u_2
β : Type u_1
γ : Type ?u.14817
δ : Type ?u.14820
ι : Sort ?u.14823
s : Set α
t : Set β
f : Filter α
g : Filter β
⊢ Prod.swap <$> (g ×ˢ f) = map (fun p => (p.snd, p.fst)) (g ×ˢ f) Tactic: rw [prod_comm', ← map_swap_eq_comap_swap] State Before: α : Type u_2
β : Type u_1
γ : Type ?u.14817
δ : Type ?u.14820
ι : Sort ?u.14823
s : Set α
t : Set β
f : Filter α
g : Filter β
⊢ Prod.swap <$> (g ×ˢ f) = map (fun p => (p.snd, p.fst)) (g ×ˢ f) State After: no goals Tactic: rfl |
module Web.Internal.PermissionsPrim
import JS
import Web.Internal.Types
--------------------------------------------------------------------------------
-- Interfaces
--------------------------------------------------------------------------------
namespace PermissionStatus
export
%foreign "browser:lambda:x=>x.onchange"
prim__onchange : PermissionStatus -> PrimIO (Nullable EventHandlerNonNull)
export
%foreign "browser:lambda:(x,v)=>{x.onchange = v}"
prim__setOnchange : PermissionStatus
-> Nullable EventHandlerNonNull
-> PrimIO ()
export
%foreign "browser:lambda:x=>x.state"
prim__state : PermissionStatus -> PrimIO String
namespace Permissions
export
%foreign "browser:lambda:(x,a)=>x.query(a)"
prim__query : Permissions -> Object -> PrimIO (Promise PermissionStatus)
--------------------------------------------------------------------------------
-- Dictionaries
--------------------------------------------------------------------------------
namespace CameraDevicePermissionDescriptor
export
%foreign "browser:lambda:(a)=> {panTiltZoom: a}"
prim__new : UndefOr Boolean -> PrimIO CameraDevicePermissionDescriptor
export
%foreign "browser:lambda:x=>x.panTiltZoom"
prim__panTiltZoom : CameraDevicePermissionDescriptor
-> PrimIO (UndefOr Boolean)
export
%foreign "browser:lambda:(x,v)=>{x.panTiltZoom = v}"
prim__setPanTiltZoom : CameraDevicePermissionDescriptor
-> UndefOr Boolean
-> PrimIO ()
namespace DevicePermissionDescriptor
export
%foreign "browser:lambda:(a)=> {deviceId: a}"
prim__new : UndefOr String -> PrimIO DevicePermissionDescriptor
export
%foreign "browser:lambda:x=>x.deviceId"
prim__deviceId : DevicePermissionDescriptor -> PrimIO (UndefOr String)
export
%foreign "browser:lambda:(x,v)=>{x.deviceId = v}"
prim__setDeviceId : DevicePermissionDescriptor -> UndefOr String -> PrimIO ()
namespace MidiPermissionDescriptor
export
%foreign "browser:lambda:(a)=> {sysex: a}"
prim__new : UndefOr Boolean -> PrimIO MidiPermissionDescriptor
export
%foreign "browser:lambda:x=>x.sysex"
prim__sysex : MidiPermissionDescriptor -> PrimIO (UndefOr Boolean)
export
%foreign "browser:lambda:(x,v)=>{x.sysex = v}"
prim__setSysex : MidiPermissionDescriptor -> UndefOr Boolean -> PrimIO ()
namespace PermissionDescriptor
export
%foreign "browser:lambda:(a)=> {name: a}"
prim__new : String -> PrimIO PermissionDescriptor
export
%foreign "browser:lambda:x=>x.name"
prim__name : PermissionDescriptor -> PrimIO String
export
%foreign "browser:lambda:(x,v)=>{x.name = v}"
prim__setName : PermissionDescriptor -> String -> PrimIO ()
namespace PermissionSetParameters
export
%foreign "browser:lambda:(a,b,c)=> {descriptor: a,state: b,oneRealm: c}"
prim__new : PermissionDescriptor
-> String
-> UndefOr Boolean
-> PrimIO PermissionSetParameters
export
%foreign "browser:lambda:x=>x.descriptor"
prim__descriptor : PermissionSetParameters -> PrimIO PermissionDescriptor
export
%foreign "browser:lambda:(x,v)=>{x.descriptor = v}"
prim__setDescriptor : PermissionSetParameters
-> PermissionDescriptor
-> PrimIO ()
export
%foreign "browser:lambda:x=>x.oneRealm"
prim__oneRealm : PermissionSetParameters -> PrimIO (UndefOr Boolean)
export
%foreign "browser:lambda:(x,v)=>{x.oneRealm = v}"
prim__setOneRealm : PermissionSetParameters -> UndefOr Boolean -> PrimIO ()
export
%foreign "browser:lambda:x=>x.state"
prim__state : PermissionSetParameters -> PrimIO String
export
%foreign "browser:lambda:(x,v)=>{x.state = v}"
prim__setState : PermissionSetParameters -> String -> PrimIO ()
namespace PushPermissionDescriptor
export
%foreign "browser:lambda:(a)=> {userVisibleOnly: a}"
prim__new : UndefOr Boolean -> PrimIO PushPermissionDescriptor
export
%foreign "browser:lambda:x=>x.userVisibleOnly"
prim__userVisibleOnly : PushPermissionDescriptor -> PrimIO (UndefOr Boolean)
export
%foreign "browser:lambda:(x,v)=>{x.userVisibleOnly = v}"
prim__setUserVisibleOnly : PushPermissionDescriptor
-> UndefOr Boolean
-> PrimIO ()
|
lemma Bseq_minus_iff: "Bseq (\<lambda>n. - (X n) :: 'a::real_normed_vector) \<longleftrightarrow> Bseq X" |
module nodcap.NF.CutND where
open import Algebra
open import Category.Monad
open import Data.Nat as ℕ using (ℕ; suc; zero)
open import Data.Pos as ℕ⁺
open import Data.List as L using (List; []; _∷_; _++_; map)
open import Data.List.Any as LA using (Any; here; there)
open import Data.List.Any.BagAndSetEquality as B
open import Data.Product as PR using (∃; _×_; _,_; proj₁; proj₂)
open import Data.Sum using (_⊎_; inj₁; inj₂)
open import Function using (_$_; _∘_; flip)
open import Function.Equality using (_⟨$⟩_)
open import Function.Inverse as I using ()
open import Relation.Binary.PropositionalEquality as P using (_≡_; _≢_)
open import Data.Environment
open import nodcap.Base
open import nodcap.NF.Typing
open import nodcap.NF.Contract
open import nodcap.NF.Expand
open import nodcap.NF.Cut
open I.Inverse using (to; from)
private
open module LM {ℓ} = RawMonadPlus (L.monadPlus {ℓ})
private module ++ {a} {A : Set a} = Monoid (L.monoid A)
{-# TERMINATING #-}
-- Theorem:
-- Nondeterministic cut elimination.
mutual
cutND : {Γ Δ : Environment} {A : Type} →
⊢ⁿᶠ A ∷ Γ → ⊢ⁿᶠ A ^ ∷ Δ →
---------------------
List (⊢ⁿᶠ Γ ++ Δ)
cutND {_} {Δ} {A = 𝟏} halt (wait y)
= return y
cutND {Γ} {_} {A = ⊥} (wait x) halt
= return
$ P.subst ⊢ⁿᶠ_ (P.sym (proj₂ ++.identity Γ)) x
cutND {_} {Θ} {A = A ⊗ B} (send {Γ} {Δ} x y) (recv z)
= return
∘ P.subst ⊢ⁿᶠ_ (P.sym (++.assoc Γ Δ Θ))
∘ exch (swp [] Γ Δ)
=<< cutND y
∘ exch (fwd [] Γ)
=<< cutND x z
cutND {Θ} {_} {A = A ⅋ B} (recv x) (send {Γ} {Δ} y z)
= return
∘ P.subst ⊢ⁿᶠ_ (++.assoc Θ Γ Δ)
=<< flip cutND z
=<< cutND x y
cutND {Γ} {Δ} {A = A ⊕ B} (sel₁ x) (case y z)
= cutND x y
cutND {Γ} {Δ} {A = A ⊕ B} (sel₂ x) (case y z)
= cutND x z
cutND {Γ} {Δ} {A = A & B} (case x y) (sel₁ z)
= cutND x z
cutND {Γ} {Δ} {A = A & B} (case x y) (sel₂ z)
= cutND y z
cutND {Γ} {Δ} {A = ![ n ] A} x y
= all (replicate⁺ n (A ^)) >>= return ∘ withPerm ∘ proj₂
where
withPerm : {Θ : Environment} → replicate⁺ n (A ^) ∼[ bag ] Θ → ⊢ⁿᶠ Γ ++ Δ
withPerm {Θ} b
= cut x
$ contract
$ exch (B.++-cong (P.subst (_ ∼[ bag ]_) (all-replicate⁺ n (I.sym b)) b) I.id)
$ expand y
cutND {Γ} {Δ} {A = ?[ n ] A} x y
= all (replicate⁺ n A) >>= return ∘ withPerm ∘ proj₂
where
withPerm : {Θ : Environment} → replicate⁺ n A ∼[ bag ] Θ → ⊢ⁿᶠ Γ ++ Δ
withPerm {Θ} b
= exch (swp₂ Γ)
$ cut y
$ P.subst (λ A → ⊢ⁿᶠ ?[ n ] A ∷ Γ) (P.sym (^-inv A))
$ contract
$ exch (B.++-cong (P.subst (_ ∼[ bag ]_) (all-replicate⁺ n (I.sym b)) b) I.id)
$ expand x
cutND {Γ} {Δ} {A} (exch b x) y
= return
∘ exch (B.++-cong {ys₁ = Δ} (del-from b (here P.refl)) I.id)
=<< cutNDIn (from b ⟨$⟩ here P.refl) (here P.refl) x y
cutND {Γ} {Δ} {A} x (exch b y)
= return
∘ exch (B.++-cong {xs₁ = Γ} I.id (del-from b (here P.refl)))
=<< cutNDIn (here P.refl) (from b ⟨$⟩ here P.refl) x y
cutNDIn : {Γ Δ : Environment} {A : Type} (i : A ∈ Γ) (j : A ^ ∈ Δ) →
⊢ⁿᶠ Γ → ⊢ⁿᶠ Δ →
-----------------------
List (⊢ⁿᶠ Γ - i ++ Δ - j)
cutNDIn (here P.refl) (here P.refl) x y = cutND x y
cutNDIn {_} {Θ} (there i) j (send {Γ} {Δ} x y) z
with split Γ i
... | inj₁ (k , p) rewrite p
= return
∘ P.subst ⊢ⁿᶠ_ (P.sym (++.assoc (_ ∷ Γ - k) Δ (Θ - j)))
∘ exch (swp₃ (_ ∷ Γ - k) Δ)
∘ P.subst ⊢ⁿᶠ_ (++.assoc (_ ∷ Γ - k) (Θ - j) Δ)
∘ flip send y
=<< cutNDIn (there k) j x z
... | inj₂ (k , p) rewrite p
= return
∘ P.subst ⊢ⁿᶠ_ (P.sym (++.assoc (_ ∷ Γ) (Δ - k) (Θ - j)))
∘ send x
=<< cutNDIn (there k) j y z
cutNDIn (there i) j (recv x) y
= return
∘ recv
=<< cutNDIn (there (there i)) j x y
cutNDIn (there i) j (sel₁ x) y
= return
∘ sel₁
=<< cutNDIn (there i) j x y
cutNDIn (there i) j (sel₂ x) y
= return
∘ sel₂
=<< cutNDIn (there i) j x y
cutNDIn (there i) j (case x y) z
= cutNDIn (there i) j x z >>= λ xz
→ cutNDIn (there i) j y z >>= λ yz
→ return
$ case xz yz
cutNDIn (there ()) j halt y
cutNDIn (there i) j (wait x) y
= return
∘ wait
=<< cutNDIn i j x y
cutNDIn (there i) j loop y
= return
$ loop
cutNDIn {Γ} {Δ} (there i) j (mk?₁ x) y
= return
∘ mk?₁
=<< cutNDIn (there i) j x y
cutNDIn {Γ} {Δ} (there i) j (mk!₁ x) y
= return
∘ mk!₁
=<< cutNDIn (there i) j x y
cutNDIn {Γ} {Δ} (there i) j (cont x) y
= return
∘ cont
=<< cutNDIn (there (there i)) j x y
cutNDIn {_} {Θ} (there i) j (pool {Γ} {Δ} x y) z
with split Γ i
... | inj₁ (k , p) rewrite p
= return
∘ P.subst ⊢ⁿᶠ_ (P.sym (++.assoc (_ ∷ Γ - k) Δ (Θ - j)))
∘ exch (swp₃ (_ ∷ Γ - k) Δ)
∘ P.subst ⊢ⁿᶠ_ (++.assoc (_ ∷ Γ - k) (Θ - j) Δ)
∘ flip pool y
=<< cutNDIn (there k) j x z
... | inj₂ (k , p) rewrite p
= return
∘ P.subst ⊢ⁿᶠ_ (P.sym (++.assoc (_ ∷ Γ) (Δ - k) (Θ - j)))
∘ pool x
=<< cutNDIn (there k) j y z
cutNDIn {Θ} {_} i (there j) x (send {Γ} {Δ} y z)
with split Γ j
... | inj₁ (k , p) rewrite p
= return
∘ exch (bwd [] (Θ - i))
∘ P.subst ⊢ⁿᶠ_ (++.assoc (_ ∷ Θ - i) (Γ - k) Δ)
∘ flip send z
∘ exch (fwd [] (Θ - i))
=<< cutNDIn i (there k) x y
... | inj₂ (k , p) rewrite p
= return
∘ exch (swp [] (Θ - i) (_ ∷ Γ))
∘ send y
∘ exch (fwd [] (Θ - i))
=<< cutNDIn i (there k) x z
cutNDIn {Γ} i (there j) x (recv {Δ} y)
= return
∘ exch (bwd [] (Γ - i))
∘ recv
∘ exch (swp [] (_ ∷ _ ∷ []) (Γ - i))
=<< cutNDIn i (there (there j)) x y
cutNDIn {Γ} {Δ} i (there j) x (sel₁ y)
= return
∘ exch (bwd [] (Γ - i))
∘ sel₁
∘ exch (fwd [] (Γ - i))
=<< cutNDIn i (there j) x y
cutNDIn {Γ} {Δ} i (there j) x (sel₂ y)
= return
∘ exch (bwd [] (Γ - i))
∘ sel₂
∘ exch (fwd [] (Γ - i))
=<< cutNDIn i (there j) x y
cutNDIn {Γ} {Δ} i (there j) x (case y z)
= cutNDIn i (there j) x y >>= λ xy
→ cutNDIn i (there j) x z >>= λ xz
→ return
$ exch (bwd [] (Γ - i))
$ case
( exch (fwd [] (Γ - i)) xy )
( exch (fwd [] (Γ - i)) xz )
cutNDIn {Γ} i (there ()) x halt
cutNDIn {Γ} {Δ} i (there j) x (wait y)
= return
∘ exch (bwd [] (Γ - i))
∘ wait
=<< cutNDIn i j x y
cutNDIn {Γ} {Δ} i (there j) x loop
= return
∘ exch (bwd [] (Γ - i))
$ loop
cutNDIn {Γ} {Δ} i (there j) x (mk?₁ y)
= return
∘ exch (bwd [] (Γ - i))
∘ mk?₁
∘ exch (fwd [] (Γ - i))
=<< cutNDIn i (there j) x y
cutNDIn {Γ} {Δ} i (there j) x (mk!₁ y)
= return
∘ exch (bwd [] (Γ - i))
∘ mk!₁
∘ exch (fwd [] (Γ - i))
=<< cutNDIn i (there j) x y
cutNDIn {Γ} {Δ} i (there j) x (cont y)
= return
∘ exch (bwd [] (Γ - i))
∘ cont
∘ exch (swp [] (_ ∷ _ ∷ []) (Γ - i))
=<< cutNDIn i (there (there j)) x y
cutNDIn {Θ} {_} i (there j) x (pool {Γ} {Δ} y z)
with split Γ j
... | inj₁ (k , p) rewrite p
= return
∘ exch (bwd [] (Θ - i))
∘ P.subst ⊢ⁿᶠ_ (++.assoc (_ ∷ Θ - i) (Γ - k) Δ)
∘ flip pool z
∘ exch (fwd [] (Θ - i))
=<< cutNDIn i (there k) x y
... | inj₂ (k , p) rewrite p
= return
∘ exch (swp [] (Θ - i) (_ ∷ Γ))
∘ pool y
∘ exch (fwd [] (Θ - i))
=<< cutNDIn i (there k) x z
cutNDIn {Γ} {Δ} i j (exch b x) y
= return
∘ exch (B.++-cong {ys₁ = Δ - j} (del-from b i ) I.id)
=<< cutNDIn (from b ⟨$⟩ i) j x y
cutNDIn {Γ} {Δ} i j x (exch b y)
= return
∘ exch (B.++-cong {xs₁ = Γ - i} I.id (del-from b j))
=<< cutNDIn i (from b ⟨$⟩ j) x y
-- -}
-- -}
-- -}
-- -}
-- -}
|
(* Title: HOL/Auth/n_flash_nodata_cub_lemma_on_inv__58.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_flash_nodata_cub Protocol Case Study*}
theory n_flash_nodata_cub_lemma_on_inv__58 imports n_flash_nodata_cub_base
begin
section{*All lemmas on causal relation between inv__58 and some rule r*}
lemma n_PI_Remote_GetVsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Get src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Remote_GetXVsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_GetX src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_NakVsinv__58:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Nak dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__0Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__1Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__2Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__0Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__1Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_HeadVsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_PutVsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_DirtyVsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_NakVsinv__58:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_Nak_HomeVsinv__58:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_PutVsinv__58:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_Put_HomeVsinv__58:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__0Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__1Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__2Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__0Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__1Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_1Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_2Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_3Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_4Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_5Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_6Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_HomeVsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8Vsinv__58:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__58:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10_HomeVsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10Vsinv__58:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_11Vsinv__58:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_NakVsinv__58:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_Nak_HomeVsinv__58:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutXVsinv__58:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutX_HomeVsinv__58:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_GetX)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''HomeProc'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutVsinv__58:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutXVsinv__58:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Local_Get_GetVsinv__58:
assumes a1: "(r=n_PI_Local_Get_Get )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_GetX_GetX__part__0Vsinv__58:
assumes a1: "(r=n_PI_Local_GetX_GetX__part__0 )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_GetX_GetX__part__1Vsinv__58:
assumes a1: "(r=n_PI_Local_GetX_GetX__part__1 )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Nak_HomeVsinv__58:
assumes a1: "(r=n_NI_Nak_Home )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_PutVsinv__58:
assumes a1: "(r=n_NI_Local_Put )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_PutXAcksDoneVsinv__58:
assumes a1: "(r=n_NI_Local_PutXAcksDone )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__58 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_GetX_PutX__part__0Vsinv__58:
assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_WbVsinv__58:
assumes a1: "r=n_NI_Wb " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_3Vsinv__58:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_1Vsinv__58:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_ReplaceVsinv__58:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_ReplaceVsinv__58:
assumes a1: "r=n_PI_Local_Replace " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_existsVsinv__58:
assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_PutXVsinv__58:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvVsinv__58:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_PutXVsinv__58:
assumes a1: "r=n_PI_Local_PutX " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_PutVsinv__58:
assumes a1: "r=n_PI_Local_Get_Put " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ShWbVsinv__58:
assumes a1: "r=n_NI_ShWb N " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__58:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__0 N " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ReplaceVsinv__58:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Replace src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__1Vsinv__58:
assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_exists_HomeVsinv__58:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Replace_HomeVsinv__58:
assumes a1: "r=n_NI_Replace_Home " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_ClearVsinv__58:
assumes a1: "r=n_NI_Nak_Clear " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_2Vsinv__58:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__58:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__1 N " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_FAckVsinv__58:
assumes a1: "r=n_NI_FAck " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__58 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
#include <boost/foreach.hpp>
#include "Alphabet.h"
#include <iostream>
#include "Generic/common/foreach_pair.hpp"
using std::wstring;
using std::map;
using std::wcout;
using std::endl;
using namespace GraphicalModel;
wstring UNKNOWN_FEATURE = L"unknown_feature";
Alphabet::Alphabet() {}
unsigned int Alphabet::feature(const wstring& featureString) {
StringToInt::const_iterator probe = stringToInt.find(featureString);
if (probe == stringToInt.end()) {
unsigned int next_idx = stringToInt.size();
stringToInt.insert(make_pair(featureString, next_idx));
intToString.insert(make_pair(next_idx, featureString));
return next_idx;
} else {
return probe->second;
}
}
unsigned int Alphabet::feature(const wstring& featureString) const {
return featureAlreadyPresent(featureString);
}
unsigned int Alphabet::featureAlreadyPresent(const wstring& featureString) const {
StringToInt::const_iterator probe = stringToInt.find(featureString);
if (probe == stringToInt.end()) {
std::wcout << featureString << endl;
throw BadLookupException();
} else {
return probe->second;
}
}
const wstring& Alphabet::name(unsigned int featureIdx) const {
IntToString::const_iterator probe = intToString.find(featureIdx);
if (probe == intToString.end()) {
return UNKNOWN_FEATURE;
} else {
return probe->second;
}
}
void Alphabet::dump() const {
BOOST_FOREACH_PAIR(unsigned int idx, const wstring& name, intToString) {
std::wcout << idx << L": " << name << endl;
}
}
size_t Alphabet::size() const {
return stringToInt.size();
}
|
(* Title: HOL/Auth/n_germanSymIndex_lemma_on_inv__38.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_germanSymIndex Protocol Case Study*}
theory n_germanSymIndex_lemma_on_inv__38 imports n_germanSymIndex_base
begin
section{*All lemmas on causal relation between inv__38 and some rule r*}
lemma n_RecvReqSVsinv__38:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)" and
a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__38 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvReqS N i" apply fastforce done
from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__38 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv2) ''Cmd'')) (Const InvAck)) (eqn (IVar (Ident ''CurCmd'')) (Const Empty))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv2)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv2) ''Cmd'')) (Const InvAck)) (eqn (IVar (Ident ''CurCmd'')) (Const Empty))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_RecvReqEVsinv__38:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)" and
a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__38 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvReqE N i" apply fastforce done
from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__38 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv2)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_SendInvAckVsinv__38:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" and
a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__38 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInvAck i" apply fastforce done
from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__38 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Ident ''CurCmd'')) (Const ReqS)) (eqn (IVar (Ident ''ExGntd'')) (Const false))) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv2) ''Cmd'')) (Const Inv))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_RecvInvAckVsinv__38:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)" and
a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__38 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvInvAck i" apply fastforce done
from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__38 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "((formEval (eqn (IVar (Ident ''ExGntd'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Ident ''ExGntd'')) (Const true))) s))" by auto
moreover {
assume c1: "((formEval (eqn (IVar (Ident ''ExGntd'')) (Const true)) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (neg (eqn (IVar (Ident ''ExGntd'')) (Const true))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately have "invHoldForRule s f r (invariants N)" by satx
}
moreover {
assume b1: "(i~=p__Inv2)"
have "((formEval (eqn (IVar (Ident ''ExGntd'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Ident ''ExGntd'')) (Const true))) s))" by auto
moreover {
assume c1: "((formEval (eqn (IVar (Ident ''ExGntd'')) (Const true)) s))"
have "?P3 s"
apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv2) ''Cmd'')) (Const InvAck)) (eqn (IVar (Ident ''CurCmd'')) (Const ReqS))) (eqn (IVar (Field (Para (Ident ''Chan3'') i) ''Cmd'')) (Const InvAck))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (neg (eqn (IVar (Ident ''ExGntd'')) (Const true))) s))"
have "?P2 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately have "invHoldForRule s f r (invariants N)" by satx
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_SendGntSVsinv__38:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" and
a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__38 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntS i" apply fastforce done
from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__38 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv2)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_SendGntEVsinv__38:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" and
a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__38 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntE N i" apply fastforce done
from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__38 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv2)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_SendReqE__part__1Vsinv__38:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i" and
a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__38 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_StoreVsinv__38:
assumes a1: "\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d" and
a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__38 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_RecvGntSVsinv__38:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvGntS i" and
a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__38 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_RecvGntEVsinv__38:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvGntE i" and
a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__38 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_SendInv__part__0Vsinv__38:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i" and
a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__38 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_SendReqE__part__0Vsinv__38:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i" and
a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__38 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_SendInv__part__1Vsinv__38:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i" and
a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__38 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_SendReqSVsinv__38:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqS i" and
a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__38 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
-- mostly adapted from Agda stdlib
module level where
import Agda.Primitive
open Agda.Primitive public
using (Level ; _⊔_ ; lsuc ; lzero)
level = Level
lone : level
lone = lsuc lzero
record Lift {a ℓ} (A : Set a) : Set (a ⊔ ℓ) where
constructor lift
field lower : A
open Lift public
|
"""
From multiple sets of results from regressions, take average of beta weights and p values from common covariates.
Assumes that there is a root folder with one folder for each site and that inside each site folder is a folder called results,
which contains the results as nifti files. The files containing beta weights should be named as "beta_covariate.nii", and those containing p-values should be named "pval_covariate.nii."
The path to the root folder is expected as an optional parameter. If no path is given on the command line,
then the current working directory is used.
Usage:
$ python average_results /path/to/results
Expected path structure:
/path/to/results/
site1/
results/
beta_cov1.nii
beta_cov2.nii
...
pval_cov1.nii
pval_cov2.nii
site2/
results/
beta_cov1.nii
beta_cov2.nii
...
pval_cov1.nii
pval_cov2.nii
"""
import sys
import os
import numpy as np
import nibabel as nib
import logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
FNAME_DELIM = '_'
BETA = 'beta'
PVAL = 'pval'
SUFFIX_NII = '.nii'
RESULTS_DIR = 'results'
OUTPUT_DIR = 'global_avg'
def get_covariates(path):
filenames = [name for name in os.listdir(path)]
beta_files = [f for f in filenames if is_nifti(f) and is_beta(f)]
return [fname2covar(f) for f in beta_files]
def fname2covar(filename):
root,_ = os.path.splitext(filename)
parts = root.split(FNAME_DELIM)
return FNAME_DELIM.join(parts[1:])
def is_nifti(filename):
return SUFFIX_NII in filename
def is_beta(filename):
return BETA in filename
def is_pval(filename):
return BETA in filename
def get_common_covars(site_covars):
covar_list = [covars for site, covars in site_covars.items()]
common = set(covar_list[0])
for covars in covar_list[1:]:
common = common & set(covars)
return list(common)
def average_results(covar, path, sites, kind):
images = list()
for site in sites:
full_path = os.path.join(path, site, RESULTS_DIR, get_img_fname(kind, covar))
images.append(nib.load(full_path))
return average_images(images)
def average_images(images):
data_arrays = [i.get_data() for i in images]
avg_data = average_arrays(data_arrays)
affine_arrays = [i.affine for i in images]
avg_affine = average_arrays(affine_arrays)
return nib.Nifti1Image(avg_data, avg_affine)
def average_arrays(arrays):
return np.mean(np.array(arrays), axis=0)
def get_img_fname(kind, covar):
return kind + FNAME_DELIM + covar + SUFFIX_NII
def main(root_folder):
# Get list of sites from folders
site_list = [name for name in os.listdir(root_folder) if os.path.isdir(os.path.join(root_folder, name))]
if OUTPUT_DIR in site_list:
site_list.remove(OUTPUT_DIR)
log.info('Sites: ' + ', '.join(site_list))
if site_list:
# Get list of covariates from each site
covars_by_site = dict()
for site in site_list:
covars_by_site[site] = get_covariates(os.path.join(root_folder, site, RESULTS_DIR))
log.info('Covariates in site `{site}`: {covars}'.format(site=site, covars=', '.join(covars_by_site[site])))
# Get list of common covariates
common_covars = get_common_covars(covars_by_site)
log.info('Common covariates: ' + ', '.join(common_covars))
output_folder = os.path.join(root_folder, OUTPUT_DIR)
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# For each common covariate, find average betas and pvalues and save to file
for covar in common_covars:
avg_beta = average_results(covar, root_folder, site_list, BETA)
output_path = os.path.join(output_folder, get_img_fname(BETA, covar))
avg_beta.to_filename(output_path)
log.info('Saved average beta weights for `{covar}` to {path}'.format(covar=covar, path=output_path))
avg_pval = average_results(covar, root_folder, site_list, PVAL)
output_path = os.path.join(output_folder, get_img_fname(PVAL, covar))
avg_pval.to_filename(output_path)
log.info('Saved average p-values for `{covar}` to {path}'.format(covar=covar, path=output_path))
else:
log.error('No sites found')
if __name__ == '__main__':
if len(sys.argv) > 1:
folder = sys.argv[1]
else:
folder = os.get_cwd()
log.info('Root folder: ' + folder)
main(folder)
|
------------------------------------------------------------------------
-- The Agda standard library
--
-- Heterogeneous equality
------------------------------------------------------------------------
-- This file contains some core definitions which are reexported by
-- Relation.Binary.HeterogeneousEquality.
{-# OPTIONS --with-K --safe #-}
module Relation.Binary.HeterogeneousEquality.Core where
open import Relation.Binary.PropositionalEquality.Core using (_≡_; refl)
------------------------------------------------------------------------
-- Heterogeneous equality
infix 4 _≅_
data _≅_ {ℓ} {A : Set ℓ} (x : A) : {B : Set ℓ} → B → Set ℓ where
refl : x ≅ x
------------------------------------------------------------------------
-- Conversion
≅-to-≡ : ∀ {a} {A : Set a} {x y : A} → x ≅ y → x ≡ y
≅-to-≡ refl = refl
≡-to-≅ : ∀ {a} {A : Set a} {x y : A} → x ≡ y → x ≅ y
≡-to-≅ refl = refl
|
State Before: α : Type u_1
inst✝ : AddGroupWithOne α
⊢ ↑↑0 = ↑0 State After: no goals Tactic: rw [cast_zero, cast_zero, Int.cast_zero] State Before: α : Type u_1
inst✝ : AddGroupWithOne α
p : PosNum
⊢ ↑↑(pos p) = ↑(pos p) State After: no goals Tactic: rw [cast_pos, cast_pos, PosNum.cast_to_int] State Before: α : Type u_1
inst✝ : AddGroupWithOne α
p : PosNum
⊢ ↑↑(neg p) = ↑(neg p) State After: no goals Tactic: rw [cast_neg, cast_neg, Int.cast_neg, PosNum.cast_to_int] |
!
! unif matrix
!
module unif_matrix
implicit none
contains
!
! Description:
!
! Generate uniformized kernel from Q
!
! Parameters:
! n: size of square matrix A
!
subroutine unif_dense(n, Q, ldq, P, ldp, qv, ufact)
integer, intent(in) :: n, ldq, ldp
double precision, intent(in) :: ufact
double precision, intent(out) :: qv
double precision, intent(in) :: Q(1:ldq,1:n)
double precision, intent(out) :: P(1:ldp,1:n)
integer :: i
qv = 0.0d0
do i = 1, n
if (qv < -Q(i,i)) then
qv = -Q(i,i)
end if
end do
qv = qv * ufact
P(1:n,1:n) = Q(1:n,1:n)
do i = 1, n
call dscal(n, 1.0d0/qv, P(1,i), 1)
end do
do i = 1, n
P(i,i) = P(i,i) + 1.0d0
end do
end subroutine unif_dense
subroutine unif_csr(n, spQ, rowptr, colind, nnz, spP, qv, ufact)
use sparse
integer, parameter :: base = sparse_base_index
integer, intent(in) :: n, nnz
double precision, intent(in) :: ufact
double precision, intent(out) :: qv
double precision, intent(in) :: spQ(base:base+nnz-1)
double precision, intent(out) :: spP(base:base+nnz-1)
integer, intent(in) :: rowptr(base:*), colind(base:*)
integer :: i, j, z, diag(base:base+n-1)
qv = 0.0d0
do i = base, base+n-1
do z = rowptr(i), rowptr(i+1)-1
j = colind(z)
if (i == j) then
if (qv < -spQ(z)) then
qv = -spQ(z)
end if
diag(i) = z
exit
end if
end do
end do
qv = qv * ufact
spP = spQ
call dscal(nnz, 1.0d0/qv, spP, 1)
do i = base, base+n-1
spP(diag(i)) = spP(diag(i)) + 1.0d0
end do
end subroutine unif_csr
subroutine unif_csc(n, spQ, colptr, rowind, nnz, spP, qv, ufact)
use sparse
integer, parameter :: base = sparse_base_index
integer, intent(in) :: n, nnz
double precision, intent(in) :: ufact
double precision, intent(out) :: qv
double precision, intent(in) :: spQ(base:base+nnz-1)
double precision, intent(out) :: spP(base:base+nnz-1)
integer, intent(in) :: colptr(base:*), rowind(base:*)
integer :: i, j, z, diag(base:base+n-1)
qv = 0.0d0
do j = base, base+n-1
do z = colptr(j), colptr(j+1)-1
i = rowind(z)
if (i == j) then
if (qv < -spQ(z)) then
qv = -spQ(z)
end if
diag(j) = z
exit
end if
end do
end do
qv = qv * ufact
spP = spQ
call dscal(nnz, 1.0d0/qv, spP, 1)
do j = base, base+n-1
spP(diag(j)) = spP(diag(j)) + 1.0d0
end do
end subroutine unif_csc
subroutine unif_coo(n, spQ, rowind, colind, nnz, spP, qv, ufact)
use sparse
integer, parameter :: base = sparse_base_index
integer, intent(in) :: n, nnz
double precision, intent(in) :: ufact
double precision, intent(out) :: qv
double precision, intent(in) :: spQ(base:base+nnz-1)
double precision, intent(out) :: spP(base:base+nnz-1)
integer, intent(in) :: rowind(base:*), colind(base:*)
integer :: i, j, z, diag(base:base+n-1)
qv = 0.0d0
do z = base, base+nnz-1
i = rowind(z)
j = colind(z)
if (i == j) then
if (qv < -spQ(z)) then
qv = -spQ(z)
end if
diag(i) = z
end if
end do
qv = qv * ufact
spP = spQ
call dscal(nnz, 1.0d0/qv, spP, 1)
do i = base, base+n-1
spP(diag(i)) = spP(diag(i)) + 1.0d0
end do
end subroutine unif_coo
end module unif_matrix
|
using ONNX
using Test
include("readwrite.jl")
|
library(maptools)
library(rgeos)
library(rgdal)
library(ggplot2)
# library(ggmap)
library(plyr)
library(dplyr)
library(data.table)
library(stringr)
library(maps)
library(htmltab)
options(stringaAsFactors = F)
# Helper files ------------------------------------------------------------
## get congressional election results
# https://github.com/TimeMagazine/congressional-election-results/tree/master/data
time_results_base = 'https://github.com/TimeMagazine/congressional-election-results/blob/master/data/results_%s.csv'
## us and state map data
us_map = map_data('usa')
us_state_map = map_data('state')
## get fips codes
county_state_fips <- fread("http://www2.census.gov/geo/docs/reference/codes/files/national_county.txt",
header = F, colClasses = "character")
setnames(county_state_fips, names(county_state_fips),
c("state_short", "STATEFP", "COUNTYFP", "county_desc", "fips_class_code"))
state_fips = select(county_state_fips, contains('state')) %>%
unique()
## get CD shapefile data
setwd('~/congressional_research/tl_2016_us_cd115')
cd_shapefiles <- readOGR(dsn = ".", layer = "tl_2016_us_cd115")
polygon_data <-
cd_shapefiles@data %>%
mutate(
polygon_center_lon = INTPTLON %>% as.character() %>% as.numeric(),
polygon_center_lat = INTPTLAT %>% as.character() %>% as.numeric()
) %>%
data.table(key = "GEOID")
cd_shapefiles_df <-
fortify(cd_shapefiles, region = "GEOID") %>%
data.table(key = "id")
cd_shapefiles_with_names <-
cd_shapefiles_df[polygon_data] %>%
left_join(state_fips) %>%
mutate(
cd_number = str_extract(NAMELSAD, '[0-9]+') %>% as.numeric()
)
cd_continental_us =
cd_shapefiles_with_names %>%
filter(
state_short %in% state.abb[!state.abb %in% c('AK', 'HI')]
)
## get insurance coverage by congressional district
setwd('~/congressional_research/social_economic_data/congressional_district')
# GEO.id GEO.id2 GEO.display-label
# Id Id2 Geography
# HC01_VC130
# Estimate; HEALTH INSURANCE COVERAGE - Civilian noninstitutionalized population
# HC01_VC133
# Estimate; HEALTH INSURANCE COVERAGE - Civilian noninstitutionalized population - With health insurance coverage - With public coverage
# HC01_VC134
# Estimate; HEALTH INSURANCE COVERAGE - Civilian noninstitutionalized population - No health insurance coverage
colname_mappings = read.csv('ACS_15_5YR_DP03_with_ann.csv', nrows = 1)
cd_selected_economic_characteristics = fread('ACS_15_5YR_DP03_with_ann.csv', skip = 2, header = F, colClasses = 'character')
names(cd_selected_economic_characteristics) = names(colname_mappings)
selected_econ_vars = select(cd_selected_economic_characteristics, contains('GEO'), contains('VC13'))
econ_varnames = names(selected_econ_vars)[str_detect(names(selected_econ_vars), 'VC')]
# convert to numeric
for (var in econ_varnames) {
selected_econ_vars[[var]] = str_replace_all(selected_econ_vars[[var]], '[^0-9\\.]', '') %>%
as.numeric()
}
# final cleanup
selected_econ_vars_upd =
selected_econ_vars %>%
mutate(
percent_non_institutionalized_public_cov = HC01_VC133 / HC01_VC130,
percent_non_institutionalized_no_insurance = HC01_VC134 / HC01_VC130,
STATEFP = str_extract(GEO.id, 'US[0-9]{2}') %>% str_replace('US', ''),
cd_number = str_extract(GEO.display.label, 'District [0-9]+') %>% str_extract('[0-9]+') %>% as.numeric()
) %>%
left_join(state_fips) %>%
arrange(-percent_non_institutionalized_public_cov) %>%
data.table(key = c('state_short', 'cd_number'))
## merge health stats and shapefiles
cd_continental_us = data.table(cd_continental_us, key = c('state_short', 'cd_number'))
dist_polygon_info = select(cd_continental_us, state_short, cd_number, polygon_center_lat, polygon_center_lon) %>%
unique()
cd_shape_health_dat =
selected_econ_vars_upd[cd_continental_us]
## plot the districts
ca_health_coverage_map =
ggplot(cd_shape_health_dat %>% filter(state_short == 'CA'), aes(long, lat, group = group)) +
# geom_polygon(data = us_map) +
geom_polygon(data = us_state_map %>% filter(region == 'california')) +
geom_polygon(aes(fill = percent_non_institutionalized_public_cov * 100), colour = 'black') +
geom_text(data = dist_polygon_info %>% filter(state_short == 'CA'), aes(polygon_center_lon, polygon_center_lat, label = cd_number, group = NA), colour = 'white', size = 2) +
coord_quickmap() +
scale_fill_continuous(name = '% with public health coverage') +
theme(
legend.position = 'bottom',
axis.text = element_blank(),
axis.ticks = element_blank()
) +
labs(
title = 'Mapping Health Coverage by Congressional District',
subtitle = 'Percent of Civilian Non-Institutionalized Population With Public Health Coverage',
caption = 'Source: 2015 ACS 5 Year Estimates',
x = '', y = ''
)
setwd('~')
ggsave('california_public_health_coverage_map_by_cd.png', plot = ca_health_coverage_map, height = 7, width = 6, units = 'in', dpi = 500)
ca_health_coverage_map =
ggplot(cd_shape_health_dat %>% filter(state_short == 'CA'), aes(long, lat, group = group)) +
# geom_polygon(data = us_map) +
geom_polygon(data = us_state_map %>% filter(region == 'california')) +
geom_polygon(aes(fill = percent_non_institutionalized_no_insurance * 100), colour = 'black') +
geom_text(data = dist_polygon_info %>% filter(state_short == 'CA'), aes(polygon_center_lon, polygon_center_lat, label = cd_number, group = NA), colour = 'white', size = 2) +
coord_quickmap() +
scale_fill_continuous(name = '% with no health coverage') +
theme(
legend.position = 'bottom',
axis.text = element_blank(),
axis.ticks = element_blank()
) +
labs(
title = 'Mapping Health Coverage by Congressional District',
subtitle = 'Percent of Civilian Non-Institutionalized Population Without Health Coverage',
caption = 'Source: 2015 ACS 5 Year Estimates',
x = '', y = ''
)
setwd('~')
ggsave('california_no_health_coverage_map_by_cd.png', plot = ca_health_coverage_map, height = 7, width = 6, units = 'in', dpi = 500) |
86 See also edit Footnotes edit " Eraserhead (X. The sound drives X hysterical, and she leaves Spencer and the child. The film's tone was also shaped by Lynch 's..
Students are integrated into the international and inspiring environment of the department. We are capable skillful of developing the complex theorem. Our research analyst and mathematicians are having the..
The only good news today is: A- from my essay (about presidential campaign discourse) in the USA of course housing economics dissertation research paper renaissance humanism on western writing a..
His new book, The Trusted Executive: Nine Leadership Habits That Inspire Results, Relationships, and Reputation, is a must read for leaders who want to inspire trust and achieve results. Discussion questions, if you are using the video, ask question 1 before viewing. If you want someone to trust you, who has most of the responsibility you or the other person? Once trust has been broken, what can you do to get essay british empire it back? They believe that if someone is not good at something, there is no point in trying harder as their ability will not change. In contrast, people with a growth mind-set believe that abilities and talents are cultivated through effort. |
[STATEMENT]
lemma class_add_has_field_rev:
assumes has: "class_add P (C, cdec) \<turnstile> C\<^sub>0 has F,b:T in D"
and ncp: "\<And>D'. P \<turnstile> C\<^sub>0 \<preceq>\<^sup>* D' \<Longrightarrow> D' \<noteq> C"
shows "P \<turnstile> C\<^sub>0 has F,b:T in D"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. P \<turnstile> C\<^sub>0 has F,b:T in D
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
class_add P (C, cdec) \<turnstile> C\<^sub>0 has F,b:T in D
P \<turnstile> C\<^sub>0 \<preceq>\<^sup>* ?D' \<Longrightarrow> ?D' \<noteq> C
goal (1 subgoal):
1. P \<turnstile> C\<^sub>0 has F,b:T in D
[PROOF STEP]
by(auto simp: has_field_def dest!: class_add_has_fields_rev) |
#This script will take the Tg data (temp and density) and plot it.
#It will find the CTE below the Tg and above the Tg.
#You will need to update the breakpoint guess for your system. I recommend setting the initial guess as the Tg value for your system.
#
#License information:
#
#MIT License
#
#Copyright (c) 2019 Will Pisani
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
if (Sys.info()['sysname']=="Linux"){
setwd("/path/to/directory/on/linux")
} else {
# Paths in Windows in R require \\ instead of \
setwd("C:\\path\\to\\directory\\on\\Windows")
}
#Read in csv file
tgfile <-"your_file_name_here_CTE_RData.csv"
tgdat <- read.csv(tgfile)
tgfilename <- strsplit(tgfile,"\\.")[[1]]
#create vectors for temp, linear expansion, volume expansion
tgtemp <- tgdat[,1]
tglin <- tgdat[,2]
tgvol <- tgdat[,3]
tgdens <- tgdat[,4]
tgtemp <- rev(tgtemp)
tglin <- rev(tglin)
tgvol <- rev(tgvol)
tgdens <- rev(tgdens)
#fit a regular linear model to data, this is for the segmented command
lin.mod <- lm(tgdens ~ tgtemp)
#use segmented package to calculated breakpoint (Tg)
segmented.mod <- segmented::segmented(lin.mod, seg.Z = ~tgtemp, psi=416)
#Define moving average function
#mav <- function(x,n=1000){filter(x,rep(1/n,n),sides=2)}
#tgdens_ma <- mav(tgdens,1500)
# Get point at tg_value
tg_value <- segmented.mod$psi[2]
tg_value_stderror <- segmented.mod$psi[3]
tg_y_value <- segmented.mod$coefficients[2]*tg_value+segmented.mod$coefficients[1]
# Save regular plot to pdf
pdf(paste(tgfilename[1],"pdf",sep="."))
plot(tgtemp,tgdens,col="blue",xlim=c(300,500),ylim=c(1.24,1.34),xlab = 'Temperature (Kelvin)',ylab = 'Density (g/cc)')
#plot(tgtemp,tgdens)
par(new = TRUE)
plot(segmented.mod,col="red",xlim=c(300,500),ylim=c(1.24,1.34),xlab = '',ylab = '',rug=FALSE)
par(new = TRUE)
plot(tg_value,tg_y_value,pch=24,col="white",bg="white",xlim=c(300,500),ylim=c(1.24,1.34),xlab = '',ylab = '')
dev.off()
#tg_value <- 459.5
# Begin CTE analysis
# These ranges will need to be changed for each individual sample/run.
# tg_above and tg_below are the ranges the CTE equation will be fitted to
tg_above <- c(tg_value,500)
tg_below <- c(300,tg_value)
# Find indices of tgtemp where the above ranges occur
tg_above_lower_index <- which(tgtemp > tg_above[1])[1]
tg_above_upper_index <- tail(which(tgtemp > tg_above[2]),1)
tg_below_lower_index <- which(tgtemp > tg_below[1])[1]
tg_below_upper_index <- which(tgtemp > tg_below[2])[1]
# Get ranges for fitting
cte_linear_above <- tglin[tg_above_lower_index:tg_above_upper_index]
cte_linear_below <- tglin[tg_below_lower_index:tg_below_upper_index]
cte_volume_above <- tgvol[tg_above_lower_index:tg_above_upper_index]
cte_volume_below <- tgvol[tg_below_lower_index:tg_below_upper_index]
temp_below <- tgtemp[tg_below_lower_index:tg_below_upper_index]
temp_above <- tgtemp[tg_above_lower_index:tg_above_upper_index]
# Fit a linear model to the volumetric CTE data below Tg
vcte_below_mod <- lm(formula = cte_volume_below ~ temp_below -1)
vcte_above_mod <- lm(formula = cte_volume_above ~ temp_above -1)
lcte_below_mod <- lm(formula = cte_linear_below ~ temp_below -1)
lcte_above_mod <- lm(formula = cte_linear_above ~ temp_above -1)
# Save volumetric CTE plot to pdf
pdf(paste(tgfilename[1],"vCTE.pdf",sep="_"))
plot(tgtemp,tgvol,col="blue",xlim=c(300,500),ylim=c(min(tgvol),max(tgvol)),xlab="Temperature (K)",ylab="Volumetric expansion (dV/V times 1000)")
text(375,31,sprintf("CVTE = %3.2E/K",vcte_below_mod$coefficients[2]*10^-3),pos=2,col="red")
text(375,29,sprintf("CVTE = %3.2E/K",vcte_above_mod$coefficients[2]*10^-3),pos=2,col="brown")
par(new = TRUE)
abline(v=tg_value)
text(tg_value-20,-10,sprintf("Tg=%3.0f K",tg_value))
par(new = TRUE)
# The clip command can be used to limit some line using lines or abline
clip(tg_below[1],tg_below[2],-100,100)
abline(lm(cte_volume_below ~ temp_below),col="red")
par(new = TRUE)
clip(tg_above[1],tg_above[2],-100,100)
abline(lm(cte_volume_above ~ temp_above),col="brown")
dev.off()
# Save linear CTE plot to pdf
pdf(paste(tgfilename[1],"lCTE.pdf",sep="_"))
plot(tgtemp,tglin,col="blue",xlim=c(300,500),ylim=c(min(tglin),max(tglin)),xlab="Temperature (K)",ylab="Linear expansion (dV/V times 1000)")
text(375,11,sprintf("CLTE = %3.2E/K",lcte_below_mod$coefficients[2]*10^-3),pos=2,col="red")
text(375,9,sprintf("CLTE = %3.2E/K",lcte_above_mod$coefficients[2]*10^-3),pos=2,col="brown")
par(new = TRUE)
abline(v=tg_value)
text(tg_value-20,-3,sprintf("Tg=%3.0f K",tg_value))
par(new = TRUE)
# The clip command can be used to limit some line using lines or abline
clip(tg_below[1],tg_below[2],-100,100)
abline(lm(cte_linear_below ~ temp_below),col='red')
par(new = TRUE)
clip(tg_above[1],tg_above[2],-100,100)
abline(lm(cte_linear_above ~ temp_above),col='brown')
dev.off()
# Save moving average plot to pdf
# ma_name <- paste(tgfilename[1],"ma",sep="_")
# pdf(paste(ma_name,"pdf",sep="."))
# plot(tgtemp,tgdens_ma,col="blue",xlim=c(300,500),ylim=c(1.24,1.34),xlab = 'Temperature (Kelvin)',ylab = 'Density (g/cc)')
# #plot(tgtemp,tgdens)
# par(new = TRUE)
# plot(segmented.mod,col="red",xlim=c(300,500),ylim=c(1.24,1.34),xlab = '',ylab = '',rug=FALSE)
# par(new = TRUE)
# plot(tg_value,tg_y_value,pch=24,col="white",bg="white",xlim=c(300,500),ylim=c(1.24,1.34),xlab = '',ylab = '')
# dev.off()
# Get slope coefficients into variables
clte_above <- lcte_above_mod$coefficients[2]
clte_below <- lcte_below_mod$coefficients[2]
cvte_above <- vcte_above_mod$coefficients[2]
cvte_below <- vcte_below_mod$coefficients[2]
# Write Tg value to file
tg_data <- data.frame(tg_value,tg_value_stderror,clte_above,clte_below,cvte_above,cvte_below)
write.table(tg_data, file=paste(tgfilename[1],"txt",sep="."))
|
#Script to calculate pi using Monte Carlo
#Load the function to calculate pi
source('mcpi.r')
#problem size (number of points)
n.pts <- 1e7
cat('running serial version with n.pts = ',n.pts,'\n')
tm.st = Sys.time()
pi.approx <- mcpi(n.pts)
cat(' pi estimate = ',pi.approx,'\n')
pi.err = abs(pi - pi.approx)/pi
cat(' relative error = ',pi.err,'\n')
tm.tot = as.numeric(Sys.time() - tm.st, units="secs")
cat(' time used = ',tm.tot,'\n')
|
[STATEMENT]
lemma merge_guards_res_While: "merge_guards c = While b c' \<Longrightarrow>
\<exists>c''. c = While b c'' \<and> merge_guards c'' = c'"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. merge_guards c = While b c' \<Longrightarrow> \<exists>c''. c = While b c'' \<and> merge_guards c'' = c'
[PROOF STEP]
by (cases c) (auto split: com.splits if_split_asm simp add: is_Guard_def Let_def) |
[STATEMENT]
lemma coeff_swap_poly: "MPoly_Type.coeff (swap_poly b i mp) x = MPoly_Type.coeff mp (swap0 b i x)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. MPoly_Type.coeff (swap_poly b i mp) x = MPoly_Type.coeff mp (swap0 b i x)
[PROOF STEP]
by (transfer') (simp add: swapPoly\<^sub>0.rep_eq) |
"Our SAN infrastructure is an open book - easy to read, but next to impossible to duplicate," says Jason Silverglate, CEO and chief architect of the company's storage solution. Silverglate says that his SAN was designed to deliver industry-leading performance with a high-level of reliability. The SAN's design includes redundant head nodes with redundant 10Gbps cards and redundant SAS 6Gbps wide internal SAS paths. The end result is two highly capable volumes that can achieve extremely high read and write speeds.
Jason remarks, "on Volume 1 we are able to achieve 1600MB/s read and 1300MB/s write. Mind you, Volume1 is our low performance Volume... Volume 2, which is our SSD volume can achieve 250,000 IOPS and can easily max out a few 10Gbps circuits."
That speed makes all the difference when it comes to cloud purposed storage and that is what Jason and his team are counting on. Earlier this year, DedicatedNOW partnered with OnApp to launch a managed private cloud solution. The DedicatedNOW private cloud solution allows customers to configure and deploy scalable, redundant hypervisors onto the SAN, connected through a redundant switch stack via multiple gigabit connections both to the Internet and The Company's own internal SAN network.
DedicatedNOW, provides managed dedicated servers and complex hosting solutions to customers in nearly 100 countries. More information about DedicatedNOW's private cloud and SAN technology is available on their website at http://cloud.dedicatednow.com.
For the past seven years, Jason and his team have been building and maintaining complex dedicated server environments for ecommerce companies. "We've learned allot about supporting and maintaining clusters and load balanced setups during that time," says Silverglate. "For starters, scalability is a problem with physical clusters. You can't expand resources at a moment's notice. Servers need to be brought down for upgrades, planning needs to go into making these kinds of changes." With the expansion of cloud technology, many of the constraints within the physical world are done away with.
Jason and his team have been developing their cloud technology for the past two years from the Company's New Jersey based datacenter. A cornerstone of that development has been improving on some of the downfalls of complex hosting. Jason commented on the benefits of the shift to virtualization, "when we move a complex setup to a virtual environment, we lose those physical constraints. We can scale horizontally and vertically and for less money".
Ditlev Bredahl, CEO of OnApp, has worked with FortressITX throughout the development of their cloud. Bredahl remarks, "I'm impressed by the significant investments Fortress has made into their SAN infrastructure. When speaking with our own clients, I often recommend that they take a look at the storage technology that Jason and FortressITX have designed, before investing in their own." Silverglate claims that the Company's SAN storage is capable of performance that most never thought possible in a virtualized environment, due to its unique architecture.
Jason will be presenting his ideas on virtualization at the OnApp booth (#313) on Tuesday, Aug. 9th at 11:45AM and again on Wednesday, Aug. 10th at 12:45PM.
"This merger brings together a unique combination of talents between DedicatedNOW and Solar VPS. Our new company has vast experience with Windows hosting, virtualization, dedicated and managed hosting," said Ross Brouse, former CEO of SolarVPS, who will now serve as COO of the combined company. "We've brought together so many talented individuals whose knowledge we are blending to develop truly unique hosted partner and customer offerings. We have also recruited other top talent from the industry to expand our offerings and reach more customers around the world."
Although there is no change in management or existing server locations, the merger will provide benefits to new and existing customers of both companies. DedicatedNOW customers now have access to world-class Windows web hosting support and virtualization expertise. Additionally, with access to SolarVPS's locations, DedicatedNOW will be offering hosting for new servers in Los Angeles, Dallas and Miami.
SolarVPS can now access DedicatedNOW's resources to sustain and stimulate growth in addition having a place to call home - DedicatedNOW's Clifton, N.J. datacenter. The new company's datacenter has a multi Gigabit bandwidth network accessing all key tier 1 providers, while hosting routers, load balancers, firewalls, Internet servers and switches and accommodating large and small clients.
"I'm excited about the new opportunities that will open up as a result of this move. Both DedicatedNOW and SolarVPS customers will have access to more staff, better resources and a wider product selection. The merger makes both brands stronger, more marketable and sets the foundation for the growth of our cloud hosting division," says Jason Silverglate, CEO.
SolarVPS started in 2005 as a managed Windows Virtual Private Server provider before quickly expanding services to Parallels and linux VPS hosting and spreading to 5 cities around the globe. DedicatedNOW was founded in 1998 and has earned awards for its customer service and managed hosting expertise. Financial considerations were not disclosed.
DedicatedNOW, provides managed dedicated servers to customers in nearly 100 countries. Customers rely on DedicatedNOW for reliable, secure and value-rich services such as dedicated servers, managed hosting, complex hosting, CDN, private clouds and colocation. DedicatedNOW's servers are located in a state-of-the-art data center in Clifton, New Jersey. The Clifton facility houses nearly 5,000 servers in a secured environment, right next door to the Company's corporate headquarters and network operations center. To learn more about DedicatedNOW, please visit http://www.dedicatednow.com.
Founded in 2005, SolarVPS was established to provide next-generation windows and linux vps web hosting services on virtualized infrastructure. With the help of automation and virtualization software, it has quickly become a global hosted application service provider. Through the operation of virtual business infrastructure and strong partnerships with industry leaders, SolarVPS provides a fully automated service platform that enables a focus on personal customer relationships and superior customer support. To learn more about SolarVPS, please visit http://www.solarvps.com.
"I've met the brightest people in the (hosting) industry, here at DedicatedNOW," says Salvatore Poliandro, Director of Information Technology. In recent years, DedicatedNOW has carved out a niche for itself within the managed and complex hosting space. Leaning on its proficiency with Linux clustering, load balancing and managed security, the Company has earned many awards over the years for best in class service.
Current client Chris Azzari says "DedicatedNOW sets the bar high... Just knowing that your site that you have spend countless hours creating and promoting is in good hands is worth its weight in gold." Mr. Azzari's sentiment mirrors that of many DedicatedNOW customers - the support and customer service available with DedicatedNOW are unparalleled in the industry. That level of service has helped DedicatedNOW to earn the business of headliners like AirTran, COMODO, NYU and SpiritAir. "We love what we do and we do it well," says CEO Jason Silverglate.
DedicatedNOW, provides managed dedicated servers to customers in nearly 100 countries. Customers rely on DedicatedNOW for reliable, secure and value-rich services such as dedicated servers, managed hosting, complex hosting, CDN, reseller and colocation. DedicatedNOW's servers are located in a state-of-the-art data center in Clifton, New Jersey. The Clifton, NJ facility houses nearly 5,000 servers in a secured environment, right next door to the Company's corporate headquarters and network operations center.
These will be the companies to look at in 2011.
The awards are based on the mantra: 'Ahead of the rest.' This mantra is well reflected in the award winning plans provided by these companies.
DedicatedNow's high performance managed dedicated servers are setting new standards of reliability and efficiency in the industry. "This award not only highlights DedicatedNow's growth and commitment to excellence, but also continued emergence as a leader in the Managed Hosting and Managed Service industry," said Mr. Shelton Walker, Managing Director, Top10DedicatedHosting.com.
DedicatedNOW's primary datacenter, located in the NY Metro area, has undergone significant improvements over the past year. In addition to improved security, the building recently added a new power sub-station, which provides true redundant power feeds and improved power stability to all of DedicatedNOW's managed hosting and colocation clients.
While DedicatedNOW's commitment to excellence within the managed dedicated server niche has brought them notoriety and awards in recent years, the company will be breaking ground on its cloud hosting offering later this year. "If the company's current success is any indication, the new cloud product should be a real game changer," says Walker.
"This award highlights Online Tech's commitment to proactive professional support and delivering a turnkey colocation experience," said Mike Klein, President and COO of Online Tech.
Online Tech's investment in SAS-70 certification over the last 2 years and its reputation of proactive customer support has propelled Online Tech into a leadership position for enterprise managed colocation and servers.
Online Tech's data centers provide sophisticated power backup systems, high tech security, multiple Tier 1 ISP feeds and redundant Cisco core networks. Other offerings include locked racks, rack and stack services, backup, VPN services and network firewall protection.
Online Tech is a premier Managed Data Center Operator in the Midwestern United States with 15 years of expertise delivering outstanding products and service levels. Online Tech, offers a full range of managed colocation, dedicated server hosting and managed servers for clients from around the world. Online Tech has won dozens of awards and has SAS-70 certified data centers which have been specifically noted by Top10DedicatedHosting.
This is the reason why industry people trust Online Tech to insure their servers are always on, always online, and always safe.
Top 10 Dedicated Hosting is a team of highly skilled professionals focused on providing Dedicated Web Server Reviews to Clients, Cloud Computing Consultancy and Training to End Users. We provide Expertise and Experience to: help the business grow, reduce the overall costs, and simplify the Web environment. Dedicated Web Hosting is committed to delivering results that endure.
In his new role, Brandon will be responsible for leading the company's Sales efforts and continuing the Company's growth.
Brandon chimes in on his latest challenge, "I'm very familiar with DedicatedNOW's success and am excited to be a part of the Company's future. DedicatedNOW is well positioned within the industry and it's my intention to grow the business to new heights. Combined with our top of the line technology, superior infrastructure and committed team, DedicatedNOW is going to be a force to be reckoned with in 2011."
DedicatedNOW, founded in 1997, provides managed dedicated servers to customers in nearly 100 countries. Customers rely on DedicatedNOW for reliable, secure and value-rich services such as dedicated servers, managed hosting, complex hosting, CDN, reseller and colocation. DedicatedNOW's servers are located in a state-of-the-art data center in Clifton, New Jersey. The Clifton, NJ facility houses nearly 5,000 servers in a secured environment, right next door to the Company's corporate headquarters and network operations center.
The site's content went viral and Chris learned how traffic can crash a server. "It was at that point that I knew I needed something more substantial behind my website," says Chris. "PopThatZit.com was going to be featured on the Tyra Banks show and I knew that would bring in the traffic, big time. I needed a dedicated server and after sifting through available providers, decided to move my sites over to DedicatedNOW, a managed dedicated server provider."
Azzari continues, "the biggest thing about having your own dedicated server is that you can do a lot of tweaks that you could never do on a shared hosting plan. I run Wordpress on the site and decided to run w3 supercache after high recommendations from some friends. Getting it to work right was beyond my scope of expertise. I needed to install memcached and I wasn't about to mess that up. A simple email to the server support team and they had me up and running. The site was lighting fast and ready for traffic."
"Just knowing that the site that you have spent countless hours creating and promoting is in good hands is worth its wait in gold. Remember, your website is your business, so you need to protect that business, and it starts with where it is hosted."
PopThatZit.com is the original website by zit poppers, for zit poppers. The site's outrageous material gained a cult following on day 1. With nearly 2000 videos of every kind of pimple, boil and pustule imaginable, Chris Azzari's creation was featured on the Tyra Banks show in 2009.
For more information, visit PopThatZit.com.
DedicatedNOW, founded in 1997, provides managed and unmanaged dedicated servers to customers in nearly 100 countries. Customers rely on DedicatedNOW for reliable, secure and value-rich services such as dedicated servers, managed hosting, complex hosting, CDN, reseller and colocation. DedicatedNOW's servers are located in a state-of-the-art data center in Clifton, New Jersey. The Clifton, NJ facility houses nearly 5,000 servers in a secured environment, right next door to the Company's corporate headquarters and network operations center.
For more information about DedicatedNOW, visit www.dedicatednow.com.
In an effort to provide the best possible support to its growing dedicated hosting customer base, DedicatedNOW has released new support phone numbers for five countries, including Great Britain, Israel, New Zealand, Australia and The Netherlands. "While our on-site dedicated support team has always been available 24/7, every day of the year, we wanted to provide the best possible immediate support for our international client base," says CEO Jason Silverglate.
Silverglate continues, "With our expansion into the European market, we felt having immediate phone support for Europe and Australia was particularly important". The company plans on adding additional support numbers as its growth and international expansion continues.
DedicatedNOW, Inc. is a privately owned, multi-million dollar corporation located in Clifton, New Jersey and founded in 1997. DedicatedNOW provides managed and unmanaged dedicated web hosting services to thousands of satisfied customers. The Company delivers cutting-edge hosting solutions to meet the requirements of small and medium sized businesses as well as large corporations. Customers rely on DedicatedNOW for reliable, secure and value-rich services such as dedicated servers, managed hosting, complex hosting, CDN, reseller and colocation hosting.
DedicatedNOW's servers are located in a state-of-the-art data center in Clifton, New Jersey. The Clifton, NJ facility houses nearly 5,000 servers in a secured environment, right next door to the Company's corporate headquarters and network operations center.
"There is allot of confusion about what a cloud is and even more confusion over how to build a truly efficient and sustainable cloud," says Silverglate, owner of DedicatedNOW, a managed dedicated hosting company. The CEO's presentation will cover all facets of cloud design, including hardware, network configuration, storage considerations, selection of hypervisor and cloud management software.
With 12 years in the business, Silverglate has developed an innate knowledge of hardware available on the market. Options including 1U rackmount, 2U blade and 8U blade chassis will be discussed, as well as specific metrics like cost per GB of RAM, cost per kw and price per U; all of which factor into the viability of a host's cloud. Jason will also cover network options, such as 1Gbps, 10Gbps, Infiniband and Fiber Channel. Cloud storage and IOP (I/O Operations per second), which is a key metric for cloud performance will be discussed and Jason will enlighten the audience on various storage solutions available on the market.
With more than a year of internal testing under the Company's belt, Jason will share his own experience on Hypervisor selection and discuss options such as XenServer, XenSource, Vmware ESX, KVM, HyperV and VMware ESXi. Cloud management systems including Cloud.com, ONapp, Abiqiuo and Enomaly will also be reviewed and discussed during the presentation.
DedicatedNOW is also exhibiting at HostingCon 2010. The Company's senior management will be on-site throughout the exhibition at booth #106. Jason will be available during the conference to cover questions about cloud infrastructure and dedicated hosting.
Attendees are urged to visit the DedicatedNOW booth to meet with DedicatedNOW's staff and enter for a chance to win a Sony Dash. The Dash is Sony's latest innovation - a personal internet viewer capable of running more that 1,000 free apps over Wi-Fi. For more information about DedicatedNOW, visit the Company's website at dedicatednow.com, call 888.734.9320 or visit booth #106.
"This award not only highlights DedicatedNow's well-earned reputation for quality and stellar growth, but also continued emergence as a leader in the Managed Hosting and Managed Service industry," said Mr. Shelton Walker, Managing Director, Top10DedicatedHosting. Since 2003, DedicatedNOW has led the dedicated hosting industry by providing comprehensive management of Dedicated Servers. With an emphasis on customized solutions and adaptive customer support. DedicatedNOW leverages its partnerships and redundant network to provide unparalleled performance for its customers.
He added that by offering cutting edge technologies, industry-leading customer service and comprehensive dedicated web server solutions, DedicatedNow has become a front-runner in the global managed hosting market.
"The success of DedicatedNOW's 100% uptime in 2009 is due to our investment in data center infrastructure, engineering support, and backbone providers," said Josh Ewin, Director of Sales and Marketing at DedicatedNOW. "Our multi-homed network is fueled by premium tier 1 carriers such as Sprint, Saavis, Telia, NLayer, Global Crossing, and Level3."
Additionally, DedicatedNOW uses redundant power systems including an inline power backup, using industry standard Liebert UPS systems and onsite Caterpillar generators. "Our facility is safeguarded by redundant Libert CRAC units that are kept at an optimal temperature to ensure hardware and network components are consistently running properly," said Jason Silverglate, CEO. "And our cooling systems offer an accurate and reliable control of humidity, airflow, and room temperature that improves the working conditions for delicate electronic equipment."
"DedicatedNOW's network runs on our own dark fiber ring connecting our two redundant pops in 111 8th NYC and 165 Halsey (Equinix) NJ," said Silverglate. "Our core consists of Dual Cisco 6509 SUP720-3BXL routers, fully meshed to multiple aggregation switches for maximum uptime." DedicatedNOW encourages current and prospective customers to view the data center. Visitors can also test DedicatedNOW's fast network connection by using visiting http://speed.fortressitx.com/ or using IP address 65.98.0.42 to ping the network.
"With enterprise class reliability and performance DedicatedNOW's Managed Hosting division has provided cost effective solutions since 2003. The Company has exceeded industry level standards of management and support," said Mr. Shelton Walker, Managing Director, Top10DedicatedHosting.com.
The veteran hosting company is no stranger to the managed hosting market. With the launch of its all-Intel managed server line in 2008, DedicatedNOW gained notoriety for its managed services. Over the course of the past two years, the Company has earned many awards, including FindMyHost.com's "Editor's Choice" Award for Managed Hosting.
According to CEO Jason Silverglate, "when we created our managed server line, we canvassed our client base and industry professionals to get a real sense of what our clients and prospective clients would need for a complete managed dedicated server package. By leveraging vendor relationships, we were able to offer better service, more features and a better overall value proposition to our hosting customers".
The relationships Silverglate is referring to include R1Soft and Applicure Technologies among others. "Bundling in services like R1's backup and Applicure's dotDefender WAF product made our offering much more enticing to prospective clients," boasts Silveglate. The Company includes 50Gb of backup using R1Soft's CDP (continuous data protection) which, as Jason points out, includes the MySQL hot restore feature - very useful if you have a database driven website. Also included (on servers with the cPanel control panel) with each managed server, is a fully licensed version of the dotDefender Web Application Firewall. Other freebies include KVM over IP, round the clock monitoring and the Company's 100% Uptime guarantee.
The Company's new managed server line provides a wide-range of servers and includes many options and available features. "With our new server line, we wanted to make DedicatedNOW's server management accessible to smaller companies and startups while still being a viable option for performance-focused enterprises", noted Silverglate. With the launch of the new product line, DedicatedNOW reduced the price of its entry-level servers, while adding in the Xeon 5620 and X5650 CPU options, which include eight and twelve CPU cores, respectively.
DedicatedNOW's new managed server lineup is available for purchase from the company's website. For more information, please visit www.dedicatednow.com.
"We have a broad range of specials that DedicatedDollars.com affiliates can use to attract new customers to DedicatedNOW," says Josh Ewin, Director of Sales and Marketing. "Thousands of businesses, organizations, and resellers use dedicated server hosting so we make sure we have very attractive offers available for affiliates to use that result in higher conversions."
Since registration for DedicatedDollars.com began last November, DedicatedNOW has experienced a 30% larger response from affiliate marketers than originally estimated. One reason for the increase in response is due to the extensive support DedicatedDollars.com affiliates receive in their efforts to attract visitors and make conversions.
"DedicatedDollars.com is a full service affiliate program, with keyword tools, custom landing pages and ads, and resources for beginner through advanced affiliate marketers," says Ewin. "Our marketers are not left stranded on their own - another big problem with some affiliate programs is identifying which affiliate marketer sent a visitor to the site and initiated that sale. DedicatedDollars.com uses 120-day cookies as well as IP-based tracking to make sure every marketer gets properly credited and paid."
Another reason for the high registration and satisfaction of DedicatedDollars.com affiliates is the unrestricted payment structure. There is no limit on earnings, like there is with some other programs in the dedicated hosting industry. Affiliates can also choose from a variety of available payment options, including Paypal.
"Our affiliates are important to us, and we want to make the relationship as beneficial to both sides as possible," says Ewin. "Affiliates can earn up to 125% of a sale, and receive an instant commission alerts right to their desktop. We have put a lot of time, resources, and well-planned development into this program to make it the best affiliate program in the industry ."
DedicatedNOW offers affiliates ten specials ranging from one month of free dedicated server hosting to super competitive deals on high-end managed servers. Additional specials include feature-packed dedicated server hosting plans, complete with Managed support and backup options at low monthly rates.
DedicatedNOW, Inc. is a privately owned, multi-million dollar corporation located in Clifton, New Jersey and founded in 1997. DedicatedNOW provides managed and unmanaged dedicated web hosting services to thousands of satisfied customers. DedicatedNOW delivers cutting-edge hosting solutions to meet the requirements of small and medium sized businesses, large scale corporations, and individuals. Customers rely on DedicatedNOW for reliable, secure and value-rich services such as dedicated servers, managed hosting, complex hosting, cloud hosting, reseller and colocation hosting.
DedicatedNOW's servers are located in a state-of-the-art data center in Clifton, New Jersey. At present, the data center incorporates more than 7,500 sq. ft. of raised floor space. In addition, DedicatedNOW boasts over 5,000 sq. ft. of corporate office space including conference rooms, a reception area, and staff facilities.
"This will be our second major revision in the past eight months for the website. As a player within a space as competitive as managed hosting, we do everything possible to provide best of breed services, so we need a website that lives up to that expectation," says Jason Silverglate, CEO of DedicatedNOW.
The previous DedicatedNOW.com website was launched back in July of 2008, along with the Company's new Managed hosting products and services. With a focus on their new product launch, the July facelift was heavily geared towards promoting the Company's new servers and services. In addition to the new look and products, DedicatedNOW also launched out their proprietary billing system with the July release.
"We released the last website on the opening day of HostingCon '08. The new website was massively instrumental in pushing the Managed product line," mentions Josh Ewin, VP of Sales & Marketing.
Ewin continues, "The new DedicatedNOW look didn't include just the website. We wanted a total facelift for the brand. All of our creative was updated to the new look and feel of the DedicatedNOW brand."
While the release of the latest version of the DedicatedNOW website does not treat visitors to a new look and feel, it provides superior functionality and performance.
"The new DedicatedNOW website is focused on usability and accessibility across all major operating systems and browsers, as well as meeting the Web Accessibility Initiative and Section 508 of the Federal Government's guidelines for creating accessible websites" says SEO analyst and consultant to DedicatedNOW, Franki Nguyen of TN3 Productions in Australia. "Since the release of the new website, we've seen increased conversions, better search rankings and have had some terrific feedback from customers and visitors alike," Nguyen continues.
With the removal of functionally superfluous items like flash and some scripting, the DedicatedNOW team has seen substantial gains in productivity from the website. As dedicatednow.com is constantly in flux, much like the Internet itself, the Company is constantly updating instructional content, photos and products on the website.
DedicatedNOW plans the release of several new hosting products and services during the second quarter this year and will use the dedicatednow.com web presence as a platform to introduce them to the market.
Since 2003, DedicatedNOW has led the dedicated hosting industry by providing comprehensive management of dedicated servers. With an emphasis on customized solutions and adaptive customer support, DedicatedNOW leverages its partnerships and redundant network to provide unparallelled performance for its customers.
DedicatedNOW has carved out a niche for itself within the web hosting industry as a leading provider of managed dedicated servers, providing comprehensive solutions to todays complex IT challenges.
"Our relationship with Applicure and offering dotDefender with each of our servers, by default, is a natural fit. Now, through DedicatedNOW, reseller hosting companies not only have 24/7 access to our Dynamic Support, server class hardware and redundant network - but they also have a valuable tool (dotDefender) which they can use to differentiate themselves in this widely undifferentiated market," says Jason Silverglate, CEO of DedicatedNOW.
Yaacov Sherban, CEO of Applicure, commented,"DedicatedNOW and Applicure have each attained leadership positions in our respective markets by providing great products and services at affordable prices. Our partnership further validates Applicure's technology and market strategy for the hosting marketplace. We look forward to working with DedicatedNOW to ensure that hosting providers can offer their customers a compelling reason to acheive enterprise-class security and improved compliance."
Applicure Technologies develops the leading multi-platform web application security software solution for hosting companies that protect web servers and internal applications from external and internal attacks. Built upon years of research into hacker behavior, Applicure solutions feature a comprehensive knowledge base to identify attacks accurately, and stop them before they reach the website or application.
Since 2003, DedicatedNOW has led the dedicated hosting industry by providing comprehensive management of dedicated servers. With an emphasis on customized solutions and adaptive customer support, DedicatedNOW leverages its partnerships and redundant network to provide unparalleled performance for its customers.
The DedicatedNOW network runs on its own dark fiber ring, connecting two redundant pops in NYC and (Equinix) NJ. Each fiber leg is capable of handling the entire network's traffic in case of a failure. In addition, each leg can upgraded to provide transport capacities up to 320Gbps, totaling 640Gbps of available transport capacity. The core consists of Dual Cisco 6509 SUP720 Routers, fully meshed to multiple aggregation switches for maximum uptime.
DedicatedNOW is the premier provider of managed dedicated hosting and collocation. Backed and managed by industry experts, the company leverages its industry expertise and proprietary applications to drive consistency, availability, performance and security. Located in Clifton, New Jersey, DedicatedNOW leverages a modular, flexible, building block approach to deliver customized support and management. The company's services include dedicated hosting, collocation, customized hosting support, monitoring, high availability infrastructure planning, load balancing and clustering solutions. For more information visit the DedicatedNOW web site at www.dedicatednow.com. |
Updated: March 26, 2019, 4:59 p.m.
With her family at her bedside, Terry Brooks passed away peacefully at the age of 60 after a long battle with cancer.
She was born on June 11, 1958 in Norwich, England to Joe and Rita Dunn. A Pacifica native, Terry attended Terra Nova High School alongside her brothers, Marty and Kevin Dunn. Terry married her best friend, Art Brooks, on April 6, 1991 and the two shared 28 happy years together filled with love, laughter and adventure. Her proudest moment in her life was becoming a mother on May 23, 1993 to her daughter Caitlin. In 2000, Terry, her husband Art, and daughter Caitlin moved to Escalon where she called home her remaining years.
A devoted wife and mother, Terry lived life to the fullest. She went out of her way to make others feel loved. Her and her family loved to travel and spend their summers camping in the Redwood Forest on the Avenue of the Giants. Terry is survived by her husband Art Brooks, daughter Caitlin Brooks, brother Marty Dunn, nephew Joe Dunn, and dog Bella. There will be no services as Terry wished to have a small celebration of life with her family. In lieu of flowers, donations may be made to the American Cancer Society. |
Require Import BinInt.
Section h_def.
Variables a b : Z.
Let s : Z := a + b.
Let d : Z := a - b.
Definition h : Z := s * s + d + d.
End h_def.
Print h.
|
The overgrown and neglected public Burial Grounds at St Albans Church, Pauatahanui was cleared by local volunteers over a period from 1991. They decided to plant heritage and older type roses in keeping with the Historic Site. Many were grown from cuttings, or were donated. Others were rescued from roadsides and old properties under threat from development. Some roses were discovered during clearing are believed to date from early settler times.
Since 2007, the burial ground has been owned and maintained by the Porirua City Council.Volunteers continue to tend the roses for the enjoyment of visitors. In season - the flowering roses present a lovely sight and compliment the historical significance to the ancient burial grounds presided over by the St Albans church.
I hope my images will inspire viewers to visit this little known beautiful tourist "spot" tucked away in a corner of Pauatahanui Porirua.
Please note that these images areas thumbnails - to see the image in full - please click on the image and scroll through the gallery. Enjoy. |
% Copyright 2018 Melvin Eloy Irizarry-Gelpí
\chapter{AW Quaternions}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
An AW quaternion has the form
\begin{equation}
a_{0} + a_{1} A + a_{2} W + a_{3} AW
\end{equation}
These follow from a parabolic Cayley-Dickson construct on the A binions.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Arithmetic Operations}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Multiplication}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Conjugate Operations}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Asterisk Conjugation}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Quadrance}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Cloak Conjugation}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Dagger Conjugation}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Hodge Star}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Zero-Divisors}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Differential Operators}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{M\"{o}bius Transformations}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Cross-Ratio}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
... |
module Compat
import Data.Vect
import Data.HVect
import Cam.FFI
import Cam.IO
import Cam.Data.Collections
%access export
public export
interface Mapping a b | a where
toNative : a -> b
toForeign : b -> a
implementation Mapping (Boxed Int) Int where
toNative = believe_me
toForeign = believe_me
implementation Mapping (Boxed Double) Double where
toNative = believe_me
toForeign = believe_me
implementation Mapping (Boxed Integer) Integer where
toNative = believe_me
toForeign = believe_me
implementation Mapping (Boxed Unit) Unit where
toNative = believe_me
toForeign = believe_me
implementation Mapping (Boxed Char) Char where
toNative = believe_me
toForeign = believe_me
implementation Mapping (FList t) (List (Boxed t)) where
toNative a = believe_me . unsafePerformIO $ fcall1 "flist_to_native" $ believe_me a
toForeign b = believe_me . unsafePerformIO $ fcall1 "list_to_foreign" $ believe_me b
implementation Mapping (FVect n t) (Vect n (Boxed t)) where
toNative {n} a = believe_me . unsafePerformIO $
let sig = Integer -> FVect n t -> FFI.IO Ptr in
let n = believe_me . the Integer $ fromNat n in
fcall2 "fvect_to_native" n $ believe_me a
toForeign {n} b = believe_me . unsafePerformIO $
let sig = Integer -> Ptr -> FFI.IO (FVect n t) in
let n = believe_me . the Integer $ fromNat n in
fcall2 "vect_to_foreign" n $ believe_me b
mapTypes : Vect n Type -> Vect n Type
mapTypes ts = map Boxed ts
implementation Mapping (FHVect xs) (HVect (mapTypes xs)) where
toNative {xs} a = believe_me . unsafePerformIO $
let sig = Integer -> FHVect xs -> FFI.IO Ptr in
let n = believe_me . the Integer . fromNat $ size xs in
fcall2 "fhvect_to_native" n $ believe_me a
toForeign {xs} b = believe_me . unsafePerformIO $
let sig = Integer -> Ptr -> FFI.IO (FHVect xs) in
let n = believe_me . the Integer . fromNat $ size xs in
fcall2 "hvect_to_foreign" n $ believe_me b
implementation Mapping (Boxed String) String where
toNative a = believe_me . unsafePerformIO $ fcall1 "fstr_to_native" $ believe_me a
toForeign b = believe_me . unsafePerformIO $ fcall1 "str_to_foreign" $ believe_me b
implementation Show (FList t) where
show = toNative . toText
implementation Show (FVect n t) where
show = toNative . toText
implementation Show (FHVect xs) where
show = toNative . toText
public export
data FModuleSpec : String -> Type where
TheModule : (s : String) -> FModuleSpec s
||| foreign module
public export
FModule : String -> Type
FModule s = Boxed (FModuleSpec s)
%inline
camImport : FModuleSpec s -> FFI.IO (FModule s)
camImport {s} _ = believe_me $ fcall1 "get_module" $ believe_me s
%inline
camImportFrom : FModule mod_name -> String -> FFI.IO Unsafe
camImportFrom {mod_name} m str =
let fieldname = believe_me $ the (Boxed String) $ toForeign str in
fcall2 "module_property" (believe_me m) fieldname
%inline
unsafe : a -> Unsafe
unsafe a = unsafePerformIO $ fcall1 "identity" (believe_me a)
%inline
unsafeCall : Unsafe -> Unsafe -> FFI.IO Unsafe
unsafeCall f args = fcall2 "unsafe_call" f args
implicit iList2FList : List (Boxed a) -> FList a
iList2FList = toForeign
implicit iVect2FVect : Vect n (Boxed a) -> FVect n a
iVect2FVect = toForeign
implicit iHVect2FHVect : {xs1: Vect n Type} -> HVect (map Boxed xs1) -> FHVect xs1
iHVect2FHVect = toForeign
implicit iString2Text : String -> Boxed String
iString2Text = toForeign
implicit iFList2List : FList a -> List (Boxed a)
iFList2List = toNative
implicit iFVect2Vect : FVect n a -> Vect n (Boxed a)
iFVect2Vect = toNative
implicit iFHVect2HVect : {xs1: Vect n Type} -> FHVect xs1 -> HVect (map Boxed xs1)
iFHVect2HVect = toNative
implicit iText2String : Boxed String -> String
iText2String = toNative
|
Formal statement is: lemma continuous_mult' [continuous_intros]: fixes f g :: "_ \<Rightarrow> 'b::topological_semigroup_mult" shows "continuous F f \<Longrightarrow> continuous F g \<Longrightarrow> continuous F (\<lambda>x. f x * g x)" Informal statement is: If $f$ and $g$ are continuous functions, then so is $f \cdot g$. |
[STATEMENT]
lemma gen_eqs[simp]: "gen x Q G \<Longrightarrow> eqs z G = {}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. gen x Q G \<Longrightarrow> eqs z G = {}
[PROOF STEP]
by (auto dest: gen_qp simp: eqs_def) |
module Flexidisc.Dec.IsNo
%default total
||| Build at type level the proof that a decidable property is valid
public export
data IsNo : prop -> Type where
SoFalse : IsNo (No prop)
%name IsNo no, prf, xx, ko
||| Demote an absurd proof from the type level to the value level
export
getContra : {witness : Dec prop} -> IsNo witness -> (Not prop)
getContra x {witness = (Yes prf)} impossible
getContra x {witness = (No contra)} = contra
||| If I can prove two times that a property doesn't hold,
||| the two proofs are equal
export
uniqueNo : (prop : Dec any) -> (x, y : IsNo prop) -> x = y
uniqueNo (Yes _) SoFalse _ impossible
uniqueNo (No contra) SoFalse SoFalse = Refl
|
theory Chap3_3ex12
imports Main Chap3_1 Chap3_2
begin
type_synonym reg = nat
type_synonym reg_state = "nat \<Rightarrow> int"
datatype instr0 = LDI0 val | LD0 vname | MV0 reg | ADD0 reg
fun exec1 :: "instr0 \<Rightarrow> state \<Rightarrow> reg_state \<Rightarrow> reg_state" where
"exec1 (LDI0 n) _ rs = rs(0 := n)"
| "exec1 (LD0 x) s rs = rs(0 := s x)"
| "exec1 (MV0 r) _ rs = rs(r := rs 0)"
| "exec1 (ADD0 r) _ rs = rs(0 := rs 0 + rs r)"
definition exec :: "instr0 list \<Rightarrow> state \<Rightarrow> reg_state \<Rightarrow> reg_state" where
"exec is s = fold (\<lambda>i. exec1 i s) is"
fun comp :: "aexp \<Rightarrow> reg \<Rightarrow> instr0 list" where
"comp (N n) r = [LDI0 n, MV0 r]"
| "comp (V x) r = [LD0 x, MV0 r]"
| "comp (Plus e1 e2) r = comp e1 (r+1) @ comp e2 (r+2) @ [LDI0 0, ADD0 (r+1), ADD0 (r+2), MV0 r]"
lemma comp_no_clobber:
"\<lbrakk> 0 < r' \<and> r' < r \<rbrakk> \<Longrightarrow> exec (comp a r) s rs r' = rs r'"
apply (induction a r arbitrary: rs rule: comp.induct)
unfolding exec_def by simp+
lemma "exec (comp a r) s rs r = aval a s \<and> exec (comp a r) s rs 0 = aval a s"
apply (induction a r arbitrary: rs rule: comp.induct)
unfolding exec_def using comp_no_clobber exec_def by auto
end |
import data.array.basic data.list.dict data.pnat
universes u v
/-- A hash map with an `n`-sized array of association list buckets, a hash
function, and proofs that the buckets have no duplicate keys and that every
bucket is correctly hashed. -/
structure hashmap {α : Type u} (β : α → Type v) :=
/- Number of buckets -/
(n : ℕ)
/- Hash function from key to bucket index -/
(hash : α → fin n)
/- Array of association list buckets -/
(buckets : array n (list (sigma β)))
/- Each bucket has no duplicate keys. -/
(nodupkeys : ∀ (i : fin n), (buckets.read i).nodupkeys)
/- Each bucket member has a hash equal to the bucket index. -/
(hash_index : ∀ {i : fin n} {s : sigma β}, s ∈ buckets.read i → hash s.1 = i)
namespace hashmap
open list
/- default number of buckets -/
/-- Default number of buckets (8) -/
def default_n : ℕ :=
8
/-- Default positive number of buckets (default_n) -/
def default_pn : ℕ+ :=
⟨default_n, dec_trivial⟩
/- constructing empty hashmaps -/
/-- Construct an empty hashmap -/
def mk_empty {α} (β : α → Type v) (n : ℕ := default_n) (f : α → fin n) : hashmap β :=
⟨n, f, mk_array n [], λ i, nodupkeys_nil, λ _ _ h, by cases h⟩
/-- Create a hash function from a function `f : α → ℕ` using the result modulo
the number of buckets -/
def hash_mod {α} (n : ℕ+ := default_pn) (f : α → ℕ) (a : α) : fin n.val :=
⟨f a % n.val, nat.mod_lt _ n.property⟩
/-- Construct an empty nat-modulo hashmap -/
def mk_empty_mod {α} (β : α → Type v) (n : ℕ+ := default_pn) (f : α → ℕ) : hashmap β :=
mk_empty β n (hash_mod n f)
section αβ
variables {α : Type u} {β : α → Type v}
/- extensionality -/
theorem ext_core {m₁ m₂ : hashmap β} :
m₁.n = m₂.n →
m₁.hash == m₂.hash →
m₁.buckets == m₂.buckets →
m₁ = m₂ :=
begin
cases m₁,
cases m₂,
dsimp,
intros hn hh hb,
congr,
repeat { assumption },
{ apply proof_irrel_heq, substs hn hb },
{ apply proof_irrel_heq, substs hn hh hb }
end
theorem ext {m₁ m₂ : hashmap β}
(hn : m₁.n = m₂.n)
(hh : ∀ (a : α), (eq.rec_on hn (m₁.hash a) : fin m₂.n) = m₂.hash a)
(hb : ∀ (i : fin m₁.n), m₁.buckets.read i = m₂.buckets.read (eq.rec_on hn i)) :
m₁ = m₂ :=
ext_core hn
(function.hfunext rfl (λ a₁ a₂ p, heq_of_eq_rec_left hn (by rw eq_of_heq p; apply hh)))
(by cases m₁; cases m₂; dsimp at hn; subst hn; exact heq_of_eq (array.ext hb))
/- nodupkeys -/
theorem nodupkeys_of_mem_buckets {l : list (sigma β)} {m : hashmap β} (h : l ∈ m.buckets) :
l.nodupkeys :=
let ⟨i, e⟩ := h in e ▸ m.nodupkeys i
/- empty -/
/-- A hashmap is empty if all buckets are empty -/
def empty (m : hashmap β) : Prop :=
∀ (i : fin m.n), m.buckets.read i = []
section empty
variables {m : hashmap β}
theorem empty_mk_empty (β) (n : ℕ) (f : α → fin n) : empty (mk_empty β n f) :=
λ _, rfl
theorem empty_mk_empty_mod (β) (n : ℕ+) (f : α → ℕ) : empty (mk_empty_mod β n f) :=
λ _, rfl
@[simp] theorem empty_zero (h : m.n = 0) : empty m :=
λ i, by cases (h.rec_on i : fin 0).is_lt
end empty
/- to_lists -/
/-- Bucket list of a hashmap -/
def to_lists (m : hashmap β) : list (list (sigma β)) :=
m.buckets.to_list
section to_lists
variables {m : hashmap β} {i : ℕ} {l : list (sigma β)}
@[simp] theorem mem_to_lists : l ∈ m.to_lists ↔ l ∈ m.buckets :=
array.mem_to_list
theorem hash_idx_of_to_lists_enum (he : (i, l) ∈ m.to_lists.enum)
{s : sigma β} (hl : s ∈ l) : (m.hash s.1).1 = i :=
have e₁ : ∃ p, m.buckets.read ⟨i, p⟩ = l := array.mem_to_list_enum.1 he,
have e₂ : ∃ p, m.hash s.1 = ⟨i, p⟩ := e₁.imp (λ _ h, m.hash_index $ h.symm ▸ hl),
let ⟨_, h⟩ := e₂ in by rw h
theorem disjoint_to_lists_map_keys (m : hashmap β) :
pairwise disjoint (m.to_lists.map keys) :=
begin
rw [←enum_map_snd m.to_lists, pairwise_map, pairwise_map],
refine pairwise.imp_of_mem _ ((pairwise_map _).mp (nodup_enum_map_fst _)),
rw prod.forall,
intros n₁ l₁,
rw prod.forall,
intros n₂ l₂,
intros me₁ me₂ e a mka₁ mka₂,
apply e,
cases exists_mem_of_mem_keys mka₁ with b₁ mab₁,
cases exists_mem_of_mem_keys mka₂ with b₂ mab₂,
rw [←hash_idx_of_to_lists_enum me₁ mab₁, ←hash_idx_of_to_lists_enum me₂ mab₂]
end
end to_lists
/- to_list -/
/-- Association list of a hashmap -/
def to_list (m : hashmap β) : list (sigma β) :=
m.to_lists.join
section to_list
variables {m : hashmap β} {i : ℕ} {l : list (sigma β)} {s : sigma β}
section val
variables {n : ℕ} {h : α → fin n} {bs : array n (list (sigma β))}
{ndk : ∀ i, (bs.read i).nodupkeys}
{hi : ∀ i (s : sigma β), s ∈ bs.read i → h s.1 = i}
@[simp] theorem to_list_val : (mk n h bs ndk hi).to_list = bs.to_list.join :=
rfl
theorem empty_to_list : empty m ↔ m.to_list = [] :=
array.to_list_join_nil.symm
end val
theorem nodupkeys_to_list (m : hashmap β) : m.to_list.nodupkeys :=
nodupkeys_join.mpr $ and.intro
(λ l ml, by simp [to_lists] at ml; cases ml with i e; induction e; exact m.nodupkeys i)
m.disjoint_to_lists_map_keys
end to_list
/- foldl -/
/-- Left-fold of a hashmap -/
def foldl {γ : Type*} (m : hashmap β) (f : γ → sigma β → γ) (d : γ) : γ :=
m.buckets.foldl d (λ b r, b.foldl f r)
/- keys -/
/-- List of keys in a hashmap -/
def keys (m : hashmap β) : list α :=
m.to_list.keys
section keys
variables {m : hashmap β}
section val
variables {n : ℕ} {h : α → fin n} {bs : array n (list (sigma β))}
{ndk : ∀ i, (bs.read i).nodupkeys}
{hi : ∀ i (s : sigma β), s ∈ bs.read i → h s.1 = i}
@[simp] theorem keys_val :
(mk n h bs ndk hi).keys = bs.to_list.join.keys :=
rfl
end val
theorem nodup_keys (m : hashmap β) : m.keys.nodup :=
nodupkeys_iff.mpr m.nodupkeys_to_list
end keys
/- has_repr -/
instance [has_repr α] [∀ a, has_repr (β a)] : has_repr (hashmap β) :=
⟨λ m, "{" ++ string.intercalate ", " (m.to_list.map repr) ++ "}"⟩
section decidable_eq_α
variables [decidable_eq α]
/- lookup -/
/-- Look up a key in a hashmap to find the value, if it exists -/
def lookup (a : α) (m : hashmap β) : option (β a) :=
klookup a $ m.buckets.read $ m.hash a
section lookup
variables {a : α} {s : sigma β} {m : hashmap β}
section val
variables {n : ℕ} {h : α → fin n} {bs : array n (list (sigma β))}
{ndk : ∀ i, (bs.read i).nodupkeys}
{hi : ∀ i (s : sigma β), s ∈ bs.read i → h s.1 = i}
@[simp] theorem lookup_val :
lookup a (mk n h bs ndk hi) = klookup a (bs.read (h a)) :=
rfl
end val
@[simp] theorem lookup_empty (a : α) (h : empty m) : lookup a m = none :=
by simp [lookup, h (m.hash a)]
theorem lookup_iff_mem_buckets : s.2 ∈ m.lookup s.1 ↔ ∃ l, l ∈ m.buckets ∧ s ∈ l :=
calc s.2 ∈ m.lookup s.1 ↔ s ∈ m.buckets.read (m.hash s.1) :
by cases m with _ h _ ndk; simp [ndk (h s.1)]
... ↔ m.buckets.read (m.hash s.1) ∈ m.buckets ∧ s ∈ m.buckets.read (m.hash s.1) :
⟨λ h, ⟨array.read_mem _ _, h⟩, λ ⟨_, h⟩, h⟩
... ↔ ∃ l, l ∈ m.buckets ∧ s ∈ l :
⟨λ ⟨p, q⟩, ⟨_, p, q⟩, λ ⟨_, ⟨i, p⟩, q⟩,
by rw ←p at q; rw m.hash_index q; exact ⟨array.read_mem m.buckets i, q⟩⟩
end lookup
/- mem -/
instance : has_mem (sigma β) (hashmap β) :=
⟨λ s m, s.2 ∈ m.lookup s.1⟩
section mem
variables {s : sigma β} {m : hashmap β}
section val
variables {n : ℕ} {h : α → fin n} {bs : array n (list (sigma β))}
{ndk : ∀ i, (bs.read i).nodupkeys}
{hi : ∀ i (s : sigma β), s ∈ bs.read i → h s.1 = i}
@[simp] theorem mem_val : s ∈ mk n h bs ndk hi ↔ s ∈ bs.read (h s.1) :=
mem_klookup_of_nodupkeys (ndk (h s.1))
end val
theorem mem_def : s ∈ m ↔ s.2 ∈ m.lookup s.1 :=
iff.rfl
@[simp] theorem mem_to_list : s ∈ m.to_list ↔ s ∈ m :=
calc s ∈ m.to_list ↔ ∃ l, l ∈ m.to_lists ∧ s ∈ l : mem_join
... ↔ ∃ l, l ∈ m.buckets ∧ s ∈ l : by simp only [mem_to_lists]
... ↔ s ∈ m : lookup_iff_mem_buckets.symm
end mem
/- has_key -/
/-- Test for the presence of a key in a hashmap -/
def has_key (m : hashmap β) (a : α) : bool :=
(m.lookup a).is_some
section has_key
variables {a : α} {m : hashmap β}
section val
variables {n : ℕ} {h : α → fin n} {bs : array n (list (sigma β))}
{ndk : ∀ i, (bs.read i).nodupkeys}
{hi : ∀ i (s : sigma β), s ∈ bs.read i → h s.1 = i}
@[simp] theorem has_key_val :
(mk n h bs ndk hi).has_key a = (klookup a (bs.read (h a))).is_some :=
rfl
end val
theorem has_key_def : m.has_key a = (m.lookup a).is_some :=
rfl
@[simp] theorem mem_keys_iff_has_key : a ∈ m.keys ↔ m.has_key a :=
calc a ∈ m.keys ↔ ∃ (b : β a), sigma.mk a b ∈ m.to_list : mem_keys
... ↔ ∃ (b : β a), b ∈ m.lookup a : exists_congr $ λ b, mem_to_list
... ↔ m.has_key a : klookup_is_some.symm
end has_key
/- erase -/
/-- Erase a hashmap entry with the given key -/
def erase (m : hashmap β) (a : α) : hashmap β :=
{ buckets := m.buckets.modify (m.hash a) (kerase a),
nodupkeys := λ i, by by_cases e : m.hash a = i; simp [e, m.nodupkeys i],
hash_index := λ i s h, m.hash_index $
by by_cases e : m.hash a = i; simp [e] at h; [exact mem_of_mem_kerase h, exact h],
..m }
section erase
variables {a : α} {s : sigma β} {m : hashmap β}
section val
variables {n : ℕ} {h : α → fin n} {bs : array n (list (sigma β))}
{ndk : ∀ i, (bs.read i).nodupkeys}
{hi : ∀ i (s : sigma β), s ∈ bs.read i → h s.1 = i}
@[simp] theorem mem_erase_val :
s ∈ (mk n h bs ndk hi).erase a ↔ s.1 ≠ a ∧ s ∈ bs.read (h s.1) :=
begin
unfold erase,
by_cases e : h s.1 = h a,
{ simp [e, ndk (h a)] },
{ simp [ne.symm e, mt (congr_arg _) e] }
end
end val
theorem lookup_erase (m : hashmap β) : (m.erase a).lookup a = none :=
by simp [erase, lookup, m.nodupkeys (m.hash a)]
@[simp] theorem mem_erase : s ∈ m.erase a ↔ s.1 ≠ a ∧ s ∈ m :=
by cases m; simp
end erase
/- insert -/
/-- Insert a new entry in a hashmap -/
protected def insert (s : sigma β) (m : hashmap β) : hashmap β :=
{ buckets := m.buckets.modify (m.hash s.1) (kinsert s),
nodupkeys := λ i, by by_cases e : m.hash s.1 = i; simp [e, m.nodupkeys i],
hash_index := λ i s' h, begin
by_cases e : m.hash s.1 = i; simp [e] at h,
{ cases h with h h,
{ induction h, exact e },
{ exact m.hash_index (mem_of_mem_kerase h) } },
{ exact m.hash_index h }
end,
..m }
instance : has_insert (sigma β) (hashmap β) :=
⟨hashmap.insert⟩
section insert
variables {s t : sigma β} {m : hashmap β}
section val
variables {n : ℕ} {h : α → fin n} {bs : array n (list (sigma β))}
{ndk : ∀ i, (bs.read i).nodupkeys}
{hi : ∀ i (s : sigma β), s ∈ bs.read i → h s.1 = i}
@[simp] theorem mem_insert_val :
s ∈ insert t (mk n h bs ndk hi) ↔ s = t ∨ s.1 ≠ t.1 ∧ s ∈ bs.read (h s.1) :=
begin
unfold insert has_insert.insert hashmap.insert,
by_cases e : h s.1 = h t.1,
{ simp [e, ndk (h t.1)] },
{ have e' : s.1 ≠ t.1 := mt (congr_arg _) e, simp [ne.symm e, e', mt sigma.eq_fst e'] }
end
end val
@[simp] theorem mem_insert : s ∈ insert t m ↔ s = t ∨ s.1 ≠ t.1 ∧ s ∈ m :=
by cases m; simp
end insert
/-- Insert a list of entries in a hashmap -/
def insert_list (l : list (sigma β)) (m : hashmap β) : hashmap β :=
l.foldl (flip insert) m
/-- Construct a hashmap from an association list -/
def of_list (n : ℕ := default_n) (f : α → fin n) (l : list (sigma β)) : hashmap β :=
insert_list l $ mk_empty _ n f
/-- Construct a nat-modulo hashmap from an association list -/
def of_list_mod (n : ℕ+ := default_pn) (f : α → ℕ) (l : list (sigma β)) : hashmap β :=
insert_list l $ mk_empty_mod _ n f
end decidable_eq_α
end αβ
end hashmap
|
(* Title: HOL/Auth/n_flash_lemma_on_inv__16.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_flash Protocol Case Study*}
theory n_flash_lemma_on_inv__16 imports n_flash_base
begin
section{*All lemmas on causal relation between inv__16 and some rule r*}
lemma n_PI_Remote_GetVsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Get src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Remote_GetXVsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_GetX src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_NakVsinv__16:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Nak dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__0Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__1Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__2Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__0Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__1Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_HeadVsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_PutVsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_DirtyVsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_NakVsinv__16:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_PutVsinv__16:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__0Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__1Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__2Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__0Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__1Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_1Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_2Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_3Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_4Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_5Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_6Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_HomeVsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8Vsinv__16:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp=p__Inv3)\<or>(src=p__Inv3\<and>pp=p__Inv4)\<or>(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)\<or>(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__16:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp=p__Inv3)\<or>(src=p__Inv3\<and>pp=p__Inv4)\<or>(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)\<or>(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10_HomeVsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10Vsinv__16:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp=p__Inv3)\<or>(src=p__Inv3\<and>pp=p__Inv4)\<or>(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)\<or>(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>pp~=p__Inv3\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_11Vsinv__16:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Local'')) (Const true)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Local'')) (Const true)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_NakVsinv__16:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutXVsinv__16:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst=p__Inv3)\<or>(src=p__Inv3\<and>dst=p__Inv4)\<or>(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)\<or>(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)\<or>(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst=p__Inv3)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv3) ''CacheState'')) (Const CACHE_E))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') dst) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv3) ''Cmd'')) (Const UNI_PutX))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src=p__Inv3\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') dst) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst=p__Inv3)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv3\<and>src~=p__Inv4\<and>dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutVsinv__16:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutXVsinv__16:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done
from a2 obtain p__Inv3 p__Inv4 where a2:"p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst=p__Inv3)\<or>(dst~=p__Inv3\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst=p__Inv3)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv3\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutX_HomeVsinv__16:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__0Vsinv__16:
assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_WbVsinv__16:
assumes a1: "r=n_NI_Wb " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_StoreVsinv__16:
assumes a1: "\<exists> src data. src\<le>N\<and>data\<le>N\<and>r=n_Store src data" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_3Vsinv__16:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_1Vsinv__16:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__1Vsinv__16:
assumes a1: "r=n_PI_Local_GetX_GetX__part__1 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__0Vsinv__16:
assumes a1: "r=n_PI_Local_GetX_GetX__part__0 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_ReplaceVsinv__16:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_Store_HomeVsinv__16:
assumes a1: "\<exists> data. data\<le>N\<and>r=n_Store_Home data" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_ReplaceVsinv__16:
assumes a1: "r=n_PI_Local_Replace " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_existsVsinv__16:
assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_PutXVsinv__16:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Put_HomeVsinv__16:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvVsinv__16:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_PutXVsinv__16:
assumes a1: "r=n_PI_Local_PutX " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_PutVsinv__16:
assumes a1: "r=n_PI_Local_Get_Put " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ShWbVsinv__16:
assumes a1: "r=n_NI_ShWb N " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__16:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__0 N " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ReplaceVsinv__16:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Replace src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_Nak_HomeVsinv__16:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutXAcksDoneVsinv__16:
assumes a1: "r=n_NI_Local_PutXAcksDone " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__1Vsinv__16:
assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Nak_HomeVsinv__16:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_exists_HomeVsinv__16:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Replace_HomeVsinv__16:
assumes a1: "r=n_NI_Replace_Home " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutVsinv__16:
assumes a1: "r=n_NI_Local_Put " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_ClearVsinv__16:
assumes a1: "r=n_NI_Nak_Clear " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_GetVsinv__16:
assumes a1: "r=n_PI_Local_Get_Get " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_HomeVsinv__16:
assumes a1: "r=n_NI_Nak_Home " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_2Vsinv__16:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__16:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__1 N " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_FAckVsinv__16:
assumes a1: "r=n_NI_FAck " and
a2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__16 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
section \<open>Extending FOL by a modified version of HOL set theory\<close>
theory Set
imports FOL
begin
declare [[eta_contract]]
typedecl 'a set
instance set :: ("term") "term" ..
subsection \<open>Set comprehension and membership\<close>
axiomatization Collect :: "['a \<Rightarrow> o] \<Rightarrow> 'a set"
and mem :: "['a, 'a set] \<Rightarrow> o" (infixl ":" 50)
where mem_Collect_iff: "(a : Collect(P)) \<longleftrightarrow> P(a)"
and set_extension: "A = B \<longleftrightarrow> (ALL x. x:A \<longleftrightarrow> x:B)"
syntax
"_Coll" :: "[idt, o] \<Rightarrow> 'a set" ("(1{_./ _})")
translations
"{x. P}" == "CONST Collect(\<lambda>x. P)"
lemma CollectI: "P(a) \<Longrightarrow> a : {x. P(x)}"
apply (rule mem_Collect_iff [THEN iffD2])
apply assumption
done
lemma CollectD: "a : {x. P(x)} \<Longrightarrow> P(a)"
apply (erule mem_Collect_iff [THEN iffD1])
done
lemmas CollectE = CollectD [elim_format]
lemma set_ext: "(\<And>x. x:A \<longleftrightarrow> x:B) \<Longrightarrow> A = B"
apply (rule set_extension [THEN iffD2])
apply simp
done
subsection \<open>Bounded quantifiers\<close>
definition Ball :: "['a set, 'a \<Rightarrow> o] \<Rightarrow> o"
where "Ball(A, P) == ALL x. x:A \<longrightarrow> P(x)"
definition Bex :: "['a set, 'a \<Rightarrow> o] \<Rightarrow> o"
where "Bex(A, P) == EX x. x:A \<and> P(x)"
syntax
"_Ball" :: "[idt, 'a set, o] \<Rightarrow> o" ("(ALL _:_./ _)" [0, 0, 0] 10)
"_Bex" :: "[idt, 'a set, o] \<Rightarrow> o" ("(EX _:_./ _)" [0, 0, 0] 10)
translations
"ALL x:A. P" == "CONST Ball(A, \<lambda>x. P)"
"EX x:A. P" == "CONST Bex(A, \<lambda>x. P)"
lemma ballI: "(\<And>x. x:A \<Longrightarrow> P(x)) \<Longrightarrow> ALL x:A. P(x)"
by (simp add: Ball_def)
lemma bspec: "\<lbrakk>ALL x:A. P(x); x:A\<rbrakk> \<Longrightarrow> P(x)"
by (simp add: Ball_def)
lemma ballE: "\<lbrakk>ALL x:A. P(x); P(x) \<Longrightarrow> Q; \<not> x:A \<Longrightarrow> Q\<rbrakk> \<Longrightarrow> Q"
unfolding Ball_def by blast
lemma bexI: "\<lbrakk>P(x); x:A\<rbrakk> \<Longrightarrow> EX x:A. P(x)"
unfolding Bex_def by blast
lemma bexCI: "\<lbrakk>EX x:A. \<not>P(x) \<Longrightarrow> P(a); a:A\<rbrakk> \<Longrightarrow> EX x:A. P(x)"
unfolding Bex_def by blast
lemma bexE: "\<lbrakk>EX x:A. P(x); \<And>x. \<lbrakk>x:A; P(x)\<rbrakk> \<Longrightarrow> Q\<rbrakk> \<Longrightarrow> Q"
unfolding Bex_def by blast
(*Trival rewrite rule; (! x:A.P)=P holds only if A is nonempty!*)
lemma ball_rew: "(ALL x:A. True) \<longleftrightarrow> True"
by (blast intro: ballI)
subsubsection \<open>Congruence rules\<close>
lemma ball_cong:
"\<lbrakk>A = A'; \<And>x. x:A' \<Longrightarrow> P(x) \<longleftrightarrow> P'(x)\<rbrakk> \<Longrightarrow>
(ALL x:A. P(x)) \<longleftrightarrow> (ALL x:A'. P'(x))"
by (blast intro: ballI elim: ballE)
lemma bex_cong:
"\<lbrakk>A = A'; \<And>x. x:A' \<Longrightarrow> P(x) \<longleftrightarrow> P'(x)\<rbrakk> \<Longrightarrow>
(EX x:A. P(x)) \<longleftrightarrow> (EX x:A'. P'(x))"
by (blast intro: bexI elim: bexE)
subsection \<open>Further operations\<close>
definition subset :: "['a set, 'a set] \<Rightarrow> o" (infixl "<=" 50)
where "A <= B == ALL x:A. x:B"
definition mono :: "['a set \<Rightarrow> 'b set] \<Rightarrow> o"
where "mono(f) == (ALL A B. A <= B \<longrightarrow> f(A) <= f(B))"
definition singleton :: "'a \<Rightarrow> 'a set" ("{_}")
where "{a} == {x. x=a}"
definition empty :: "'a set" ("{}")
where "{} == {x. False}"
definition Un :: "['a set, 'a set] \<Rightarrow> 'a set" (infixl "Un" 65)
where "A Un B == {x. x:A | x:B}"
definition Int :: "['a set, 'a set] \<Rightarrow> 'a set" (infixl "Int" 70)
where "A Int B == {x. x:A \<and> x:B}"
definition Compl :: "('a set) \<Rightarrow> 'a set"
where "Compl(A) == {x. \<not>x:A}"
subsection \<open>Big Intersection / Union\<close>
definition INTER :: "['a set, 'a \<Rightarrow> 'b set] \<Rightarrow> 'b set"
where "INTER(A, B) == {y. ALL x:A. y: B(x)}"
definition UNION :: "['a set, 'a \<Rightarrow> 'b set] \<Rightarrow> 'b set"
where "UNION(A, B) == {y. EX x:A. y: B(x)}"
syntax
"_INTER" :: "[idt, 'a set, 'b set] \<Rightarrow> 'b set" ("(INT _:_./ _)" [0, 0, 0] 10)
"_UNION" :: "[idt, 'a set, 'b set] \<Rightarrow> 'b set" ("(UN _:_./ _)" [0, 0, 0] 10)
translations
"INT x:A. B" == "CONST INTER(A, \<lambda>x. B)"
"UN x:A. B" == "CONST UNION(A, \<lambda>x. B)"
definition Inter :: "(('a set)set) \<Rightarrow> 'a set"
where "Inter(S) == (INT x:S. x)"
definition Union :: "(('a set)set) \<Rightarrow> 'a set"
where "Union(S) == (UN x:S. x)"
subsection \<open>Rules for subsets\<close>
lemma subsetI: "(\<And>x. x:A \<Longrightarrow> x:B) \<Longrightarrow> A <= B"
unfolding subset_def by (blast intro: ballI)
(*Rule in Modus Ponens style*)
lemma subsetD: "\<lbrakk>A <= B; c:A\<rbrakk> \<Longrightarrow> c:B"
unfolding subset_def by (blast elim: ballE)
(*Classical elimination rule*)
lemma subsetCE: "\<lbrakk>A <= B; \<not>(c:A) \<Longrightarrow> P; c:B \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P"
by (blast dest: subsetD)
lemma subset_refl: "A <= A"
by (blast intro: subsetI)
lemma subset_trans: "\<lbrakk>A <= B; B <= C\<rbrakk> \<Longrightarrow> A <= C"
by (blast intro: subsetI dest: subsetD)
subsection \<open>Rules for equality\<close>
(*Anti-symmetry of the subset relation*)
lemma subset_antisym: "\<lbrakk>A <= B; B <= A\<rbrakk> \<Longrightarrow> A = B"
by (blast intro: set_ext dest: subsetD)
lemmas equalityI = subset_antisym
(* Equality rules from ZF set theory -- are they appropriate here? *)
lemma equalityD1: "A = B \<Longrightarrow> A<=B"
and equalityD2: "A = B \<Longrightarrow> B<=A"
by (simp_all add: subset_refl)
lemma equalityE: "\<lbrakk>A = B; \<lbrakk>A <= B; B <= A\<rbrakk> \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P"
by (simp add: subset_refl)
lemma equalityCE: "\<lbrakk>A = B; \<lbrakk>c:A; c:B\<rbrakk> \<Longrightarrow> P; \<lbrakk>\<not> c:A; \<not> c:B\<rbrakk> \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P"
by (blast elim: equalityE subsetCE)
lemma trivial_set: "{x. x:A} = A"
by (blast intro: equalityI subsetI CollectI dest: CollectD)
subsection \<open>Rules for binary union\<close>
lemma UnI1: "c:A \<Longrightarrow> c : A Un B"
and UnI2: "c:B \<Longrightarrow> c : A Un B"
unfolding Un_def by (blast intro: CollectI)+
(*Classical introduction rule: no commitment to A vs B*)
lemma UnCI: "(\<not>c:B \<Longrightarrow> c:A) \<Longrightarrow> c : A Un B"
by (blast intro: UnI1 UnI2)
lemma UnE: "\<lbrakk>c : A Un B; c:A \<Longrightarrow> P; c:B \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P"
unfolding Un_def by (blast dest: CollectD)
subsection \<open>Rules for small intersection\<close>
lemma IntI: "\<lbrakk>c:A; c:B\<rbrakk> \<Longrightarrow> c : A Int B"
unfolding Int_def by (blast intro: CollectI)
lemma IntD1: "c : A Int B \<Longrightarrow> c:A"
and IntD2: "c : A Int B \<Longrightarrow> c:B"
unfolding Int_def by (blast dest: CollectD)+
lemma IntE: "\<lbrakk>c : A Int B; \<lbrakk>c:A; c:B\<rbrakk> \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P"
by (blast dest: IntD1 IntD2)
subsection \<open>Rules for set complement\<close>
lemma ComplI: "(c:A \<Longrightarrow> False) \<Longrightarrow> c : Compl(A)"
unfolding Compl_def by (blast intro: CollectI)
(*This form, with negated conclusion, works well with the Classical prover.
Negated assumptions behave like formulae on the right side of the notional
turnstile...*)
lemma ComplD: "c : Compl(A) \<Longrightarrow> \<not>c:A"
unfolding Compl_def by (blast dest: CollectD)
lemmas ComplE = ComplD [elim_format]
subsection \<open>Empty sets\<close>
lemma empty_eq: "{x. False} = {}"
by (simp add: empty_def)
lemma emptyD: "a : {} \<Longrightarrow> P"
unfolding empty_def by (blast dest: CollectD)
lemmas emptyE = emptyD [elim_format]
lemma not_emptyD:
assumes "\<not> A={}"
shows "EX x. x:A"
proof -
have "\<not> (EX x. x:A) \<Longrightarrow> A = {}"
by (rule equalityI) (blast intro!: subsetI elim!: emptyD)+
with assms show ?thesis by blast
qed
subsection \<open>Singleton sets\<close>
lemma singletonI: "a : {a}"
unfolding singleton_def by (blast intro: CollectI)
lemma singletonD: "b : {a} \<Longrightarrow> b=a"
unfolding singleton_def by (blast dest: CollectD)
lemmas singletonE = singletonD [elim_format]
subsection \<open>Unions of families\<close>
(*The order of the premises presupposes that A is rigid; b may be flexible*)
lemma UN_I: "\<lbrakk>a:A; b: B(a)\<rbrakk> \<Longrightarrow> b: (UN x:A. B(x))"
unfolding UNION_def by (blast intro: bexI CollectI)
lemma UN_E: "\<lbrakk>b : (UN x:A. B(x)); \<And>x. \<lbrakk>x:A; b: B(x)\<rbrakk> \<Longrightarrow> R\<rbrakk> \<Longrightarrow> R"
unfolding UNION_def by (blast dest: CollectD elim: bexE)
lemma UN_cong: "\<lbrakk>A = B; \<And>x. x:B \<Longrightarrow> C(x) = D(x)\<rbrakk> \<Longrightarrow> (UN x:A. C(x)) = (UN x:B. D(x))"
by (simp add: UNION_def cong: bex_cong)
subsection \<open>Intersections of families\<close>
lemma INT_I: "(\<And>x. x:A \<Longrightarrow> b: B(x)) \<Longrightarrow> b : (INT x:A. B(x))"
unfolding INTER_def by (blast intro: CollectI ballI)
lemma INT_D: "\<lbrakk>b : (INT x:A. B(x)); a:A\<rbrakk> \<Longrightarrow> b: B(a)"
unfolding INTER_def by (blast dest: CollectD bspec)
(*"Classical" elimination rule -- does not require proving X:C *)
lemma INT_E: "\<lbrakk>b : (INT x:A. B(x)); b: B(a) \<Longrightarrow> R; \<not> a:A \<Longrightarrow> R\<rbrakk> \<Longrightarrow> R"
unfolding INTER_def by (blast dest: CollectD bspec)
lemma INT_cong: "\<lbrakk>A = B; \<And>x. x:B \<Longrightarrow> C(x) = D(x)\<rbrakk> \<Longrightarrow> (INT x:A. C(x)) = (INT x:B. D(x))"
by (simp add: INTER_def cong: ball_cong)
subsection \<open>Rules for Unions\<close>
(*The order of the premises presupposes that C is rigid; A may be flexible*)
lemma UnionI: "\<lbrakk>X:C; A:X\<rbrakk> \<Longrightarrow> A : Union(C)"
unfolding Union_def by (blast intro: UN_I)
lemma UnionE: "\<lbrakk>A : Union(C); \<And>X. \<lbrakk> A:X; X:C\<rbrakk> \<Longrightarrow> R\<rbrakk> \<Longrightarrow> R"
unfolding Union_def by (blast elim: UN_E)
subsection \<open>Rules for Inter\<close>
lemma InterI: "(\<And>X. X:C \<Longrightarrow> A:X) \<Longrightarrow> A : Inter(C)"
unfolding Inter_def by (blast intro: INT_I)
(*A "destruct" rule -- every X in C contains A as an element, but
A:X can hold when X:C does not! This rule is analogous to "spec". *)
lemma InterD: "\<lbrakk>A : Inter(C); X:C\<rbrakk> \<Longrightarrow> A:X"
unfolding Inter_def by (blast dest: INT_D)
(*"Classical" elimination rule -- does not require proving X:C *)
lemma InterE: "\<lbrakk>A : Inter(C); A:X \<Longrightarrow> R; \<not> X:C \<Longrightarrow> R\<rbrakk> \<Longrightarrow> R"
unfolding Inter_def by (blast elim: INT_E)
section \<open>Derived rules involving subsets; Union and Intersection as lattice operations\<close>
subsection \<open>Big Union -- least upper bound of a set\<close>
lemma Union_upper: "B:A \<Longrightarrow> B <= Union(A)"
by (blast intro: subsetI UnionI)
lemma Union_least: "(\<And>X. X:A \<Longrightarrow> X<=C) \<Longrightarrow> Union(A) <= C"
by (blast intro: subsetI dest: subsetD elim: UnionE)
subsection \<open>Big Intersection -- greatest lower bound of a set\<close>
lemma Inter_lower: "B:A \<Longrightarrow> Inter(A) <= B"
by (blast intro: subsetI dest: InterD)
lemma Inter_greatest: "(\<And>X. X:A \<Longrightarrow> C<=X) \<Longrightarrow> C <= Inter(A)"
by (blast intro: subsetI InterI dest: subsetD)
subsection \<open>Finite Union -- the least upper bound of 2 sets\<close>
lemma Un_upper1: "A <= A Un B"
by (blast intro: subsetI UnI1)
lemma Un_upper2: "B <= A Un B"
by (blast intro: subsetI UnI2)
lemma Un_least: "\<lbrakk>A<=C; B<=C\<rbrakk> \<Longrightarrow> A Un B <= C"
by (blast intro: subsetI elim: UnE dest: subsetD)
subsection \<open>Finite Intersection -- the greatest lower bound of 2 sets\<close>
lemma Int_lower1: "A Int B <= A"
by (blast intro: subsetI elim: IntE)
lemma Int_lower2: "A Int B <= B"
by (blast intro: subsetI elim: IntE)
lemma Int_greatest: "\<lbrakk>C<=A; C<=B\<rbrakk> \<Longrightarrow> C <= A Int B"
by (blast intro: subsetI IntI dest: subsetD)
subsection \<open>Monotonicity\<close>
lemma monoI: "(\<And>A B. A <= B \<Longrightarrow> f(A) <= f(B)) \<Longrightarrow> mono(f)"
unfolding mono_def by blast
lemma monoD: "\<lbrakk>mono(f); A <= B\<rbrakk> \<Longrightarrow> f(A) <= f(B)"
unfolding mono_def by blast
lemma mono_Un: "mono(f) \<Longrightarrow> f(A) Un f(B) <= f(A Un B)"
by (blast intro: Un_least dest: monoD intro: Un_upper1 Un_upper2)
lemma mono_Int: "mono(f) \<Longrightarrow> f(A Int B) <= f(A) Int f(B)"
by (blast intro: Int_greatest dest: monoD intro: Int_lower1 Int_lower2)
subsection \<open>Automated reasoning setup\<close>
lemmas [intro!] = ballI subsetI InterI INT_I CollectI ComplI IntI UnCI singletonI
and [intro] = bexI UnionI UN_I
and [elim!] = bexE UnionE UN_E CollectE ComplE IntE UnE emptyE singletonE
and [elim] = ballE InterD InterE INT_D INT_E subsetD subsetCE
lemma mem_rews:
"(a : A Un B) \<longleftrightarrow> (a:A | a:B)"
"(a : A Int B) \<longleftrightarrow> (a:A \<and> a:B)"
"(a : Compl(B)) \<longleftrightarrow> (\<not>a:B)"
"(a : {b}) \<longleftrightarrow> (a=b)"
"(a : {}) \<longleftrightarrow> False"
"(a : {x. P(x)}) \<longleftrightarrow> P(a)"
by blast+
lemmas [simp] = trivial_set empty_eq mem_rews
and [cong] = ball_cong bex_cong INT_cong UN_cong
section \<open>Equalities involving union, intersection, inclusion, etc.\<close>
subsection \<open>Binary Intersection\<close>
lemma Int_absorb: "A Int A = A"
by (blast intro: equalityI)
lemma Int_commute: "A Int B = B Int A"
by (blast intro: equalityI)
lemma Int_assoc: "(A Int B) Int C = A Int (B Int C)"
by (blast intro: equalityI)
lemma Int_Un_distrib: "(A Un B) Int C = (A Int C) Un (B Int C)"
by (blast intro: equalityI)
lemma subset_Int_eq: "(A<=B) \<longleftrightarrow> (A Int B = A)"
by (blast intro: equalityI elim: equalityE)
subsection \<open>Binary Union\<close>
lemma Un_absorb: "A Un A = A"
by (blast intro: equalityI)
lemma Un_commute: "A Un B = B Un A"
by (blast intro: equalityI)
lemma Un_assoc: "(A Un B) Un C = A Un (B Un C)"
by (blast intro: equalityI)
lemma Un_Int_distrib: "(A Int B) Un C = (A Un C) Int (B Un C)"
by (blast intro: equalityI)
lemma Un_Int_crazy:
"(A Int B) Un (B Int C) Un (C Int A) = (A Un B) Int (B Un C) Int (C Un A)"
by (blast intro: equalityI)
lemma subset_Un_eq: "(A<=B) \<longleftrightarrow> (A Un B = B)"
by (blast intro: equalityI elim: equalityE)
subsection \<open>Simple properties of \<open>Compl\<close> -- complement of a set\<close>
lemma Compl_disjoint: "A Int Compl(A) = {x. False}"
by (blast intro: equalityI)
lemma Compl_partition: "A Un Compl(A) = {x. True}"
by (blast intro: equalityI)
lemma double_complement: "Compl(Compl(A)) = A"
by (blast intro: equalityI)
lemma Compl_Un: "Compl(A Un B) = Compl(A) Int Compl(B)"
by (blast intro: equalityI)
lemma Compl_Int: "Compl(A Int B) = Compl(A) Un Compl(B)"
by (blast intro: equalityI)
lemma Compl_UN: "Compl(UN x:A. B(x)) = (INT x:A. Compl(B(x)))"
by (blast intro: equalityI)
lemma Compl_INT: "Compl(INT x:A. B(x)) = (UN x:A. Compl(B(x)))"
by (blast intro: equalityI)
(*Halmos, Naive Set Theory, page 16.*)
lemma Un_Int_assoc_eq: "((A Int B) Un C = A Int (B Un C)) \<longleftrightarrow> (C<=A)"
by (blast intro: equalityI elim: equalityE)
subsection \<open>Big Union and Intersection\<close>
lemma Union_Un_distrib: "Union(A Un B) = Union(A) Un Union(B)"
by (blast intro: equalityI)
lemma Union_disjoint:
"(Union(C) Int A = {x. False}) \<longleftrightarrow> (ALL B:C. B Int A = {x. False})"
by (blast intro: equalityI elim: equalityE)
lemma Inter_Un_distrib: "Inter(A Un B) = Inter(A) Int Inter(B)"
by (blast intro: equalityI)
subsection \<open>Unions and Intersections of Families\<close>
lemma UN_eq: "(UN x:A. B(x)) = Union({Y. EX x:A. Y=B(x)})"
by (blast intro: equalityI)
(*Look: it has an EXISTENTIAL quantifier*)
lemma INT_eq: "(INT x:A. B(x)) = Inter({Y. EX x:A. Y=B(x)})"
by (blast intro: equalityI)
lemma Int_Union_image: "A Int Union(B) = (UN C:B. A Int C)"
by (blast intro: equalityI)
lemma Un_Inter_image: "A Un Inter(B) = (INT C:B. A Un C)"
by (blast intro: equalityI)
section \<open>Monotonicity of various operations\<close>
lemma Union_mono: "A<=B \<Longrightarrow> Union(A) <= Union(B)"
by blast
lemma Inter_anti_mono: "B <= A \<Longrightarrow> Inter(A) <= Inter(B)"
by blast
lemma UN_mono: "\<lbrakk>A <= B; \<And>x. x:A \<Longrightarrow> f(x)<=g(x)\<rbrakk> \<Longrightarrow> (UN x:A. f(x)) <= (UN x:B. g(x))"
by blast
lemma INT_anti_mono: "\<lbrakk>B <= A; \<And>x. x:A \<Longrightarrow> f(x) <= g(x)\<rbrakk> \<Longrightarrow> (INT x:A. f(x)) <= (INT x:A. g(x))"
by blast
lemma Un_mono: "\<lbrakk>A <= C; B <= D\<rbrakk> \<Longrightarrow> A Un B <= C Un D"
by blast
lemma Int_mono: "\<lbrakk>A <= C; B <= D\<rbrakk> \<Longrightarrow> A Int B <= C Int D"
by blast
lemma Compl_anti_mono: "A <= B \<Longrightarrow> Compl(B) <= Compl(A)"
by blast
end
|
section \<open>The Single Mutator Case\<close>
theory Gar_Coll imports Graph OG_Syntax begin
declare psubsetE [rule del]
text \<open>Declaration of variables:\<close>
record gar_coll_state =
M :: nodes
E :: edges
bc :: "nat set"
obc :: "nat set"
Ma :: nodes
ind :: nat
k :: nat
z :: bool
subsection \<open>The Mutator\<close>
text \<open>The mutator first redirects an arbitrary edge \<open>R\<close> from
an arbitrary accessible node towards an arbitrary accessible node
\<open>T\<close>. It then colors the new target \<open>T\<close> black.
We declare the arbitrarily selected node and edge as constants:\<close>
consts R :: nat T :: nat
text \<open>\noindent The following predicate states, given a list of
nodes \<open>m\<close> and a list of edges \<open>e\<close>, the conditions
under which the selected edge \<open>R\<close> and node \<open>T\<close> are
valid:\<close>
definition Mut_init :: "gar_coll_state \<Rightarrow> bool" where
"Mut_init \<equiv> \<guillemotleft> T \<in> Reach \<acute>E \<and> R < length \<acute>E \<and> T < length \<acute>M \<guillemotright>"
text \<open>\noindent For the mutator we
consider two modules, one for each action. An auxiliary variable
\<open>\<acute>z\<close> is set to false if the mutator has already redirected an
edge but has not yet colored the new target.\<close>
definition Redirect_Edge :: "gar_coll_state ann_com" where
"Redirect_Edge \<equiv> \<lbrace>\<acute>Mut_init \<and> \<acute>z\<rbrace> \<langle>\<acute>E:=\<acute>E[R:=(fst(\<acute>E!R), T)],, \<acute>z:= (\<not>\<acute>z)\<rangle>"
definition Color_Target :: "gar_coll_state ann_com" where
"Color_Target \<equiv> \<lbrace>\<acute>Mut_init \<and> \<not>\<acute>z\<rbrace> \<langle>\<acute>M:=\<acute>M[T:=Black],, \<acute>z:= (\<not>\<acute>z)\<rangle>"
definition Mutator :: "gar_coll_state ann_com" where
"Mutator \<equiv>
\<lbrace>\<acute>Mut_init \<and> \<acute>z\<rbrace>
WHILE True INV \<lbrace>\<acute>Mut_init \<and> \<acute>z\<rbrace>
DO Redirect_Edge ;; Color_Target OD"
subsubsection \<open>Correctness of the mutator\<close>
lemmas mutator_defs = Mut_init_def Redirect_Edge_def Color_Target_def
lemma Redirect_Edge:
"\<turnstile> Redirect_Edge pre(Color_Target)"
apply (unfold mutator_defs)
apply annhoare
apply(simp_all)
apply(force elim:Graph2)
done
lemma Color_Target:
"\<turnstile> Color_Target \<lbrace>\<acute>Mut_init \<and> \<acute>z\<rbrace>"
apply (unfold mutator_defs)
apply annhoare
apply(simp_all)
done
lemma Mutator:
"\<turnstile> Mutator \<lbrace>False\<rbrace>"
apply(unfold Mutator_def)
apply annhoare
apply(simp_all add:Redirect_Edge Color_Target)
apply(simp add:mutator_defs)
done
subsection \<open>The Collector\<close>
text \<open>\noindent A constant \<open>M_init\<close> is used to give \<open>\<acute>Ma\<close> a
suitable first value, defined as a list of nodes where only the \<open>Roots\<close> are black.\<close>
consts M_init :: nodes
definition Proper_M_init :: "gar_coll_state \<Rightarrow> bool" where
"Proper_M_init \<equiv> \<guillemotleft> Blacks M_init=Roots \<and> length M_init=length \<acute>M \<guillemotright>"
definition Proper :: "gar_coll_state \<Rightarrow> bool" where
"Proper \<equiv> \<guillemotleft> Proper_Roots \<acute>M \<and> Proper_Edges(\<acute>M, \<acute>E) \<and> \<acute>Proper_M_init \<guillemotright>"
definition Safe :: "gar_coll_state \<Rightarrow> bool" where
"Safe \<equiv> \<guillemotleft> Reach \<acute>E \<subseteq> Blacks \<acute>M \<guillemotright>"
lemmas collector_defs = Proper_M_init_def Proper_def Safe_def
subsubsection \<open>Blackening the roots\<close>
definition Blacken_Roots :: " gar_coll_state ann_com" where
"Blacken_Roots \<equiv>
\<lbrace>\<acute>Proper\<rbrace>
\<acute>ind:=0;;
\<lbrace>\<acute>Proper \<and> \<acute>ind=0\<rbrace>
WHILE \<acute>ind<length \<acute>M
INV \<lbrace>\<acute>Proper \<and> (\<forall>i<\<acute>ind. i \<in> Roots \<longrightarrow> \<acute>M!i=Black) \<and> \<acute>ind\<le>length \<acute>M\<rbrace>
DO \<lbrace>\<acute>Proper \<and> (\<forall>i<\<acute>ind. i \<in> Roots \<longrightarrow> \<acute>M!i=Black) \<and> \<acute>ind<length \<acute>M\<rbrace>
IF \<acute>ind\<in>Roots THEN
\<lbrace>\<acute>Proper \<and> (\<forall>i<\<acute>ind. i \<in> Roots \<longrightarrow> \<acute>M!i=Black) \<and> \<acute>ind<length \<acute>M \<and> \<acute>ind\<in>Roots\<rbrace>
\<acute>M:=\<acute>M[\<acute>ind:=Black] FI;;
\<lbrace>\<acute>Proper \<and> (\<forall>i<\<acute>ind+1. i \<in> Roots \<longrightarrow> \<acute>M!i=Black) \<and> \<acute>ind<length \<acute>M\<rbrace>
\<acute>ind:=\<acute>ind+1
OD"
lemma Blacken_Roots:
"\<turnstile> Blacken_Roots \<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M\<rbrace>"
apply (unfold Blacken_Roots_def)
apply annhoare
apply(simp_all add:collector_defs Graph_defs)
apply safe
apply(simp_all add:nth_list_update)
apply (erule less_SucE)
apply simp+
apply force
apply force
done
subsubsection \<open>Propagating black\<close>
definition PBInv :: "gar_coll_state \<Rightarrow> nat \<Rightarrow> bool" where
"PBInv \<equiv> \<guillemotleft> \<lambda>ind. \<acute>obc < Blacks \<acute>M \<or> (\<forall>i <ind. \<not>BtoW (\<acute>E!i, \<acute>M) \<or>
(\<not>\<acute>z \<and> i=R \<and> (snd(\<acute>E!R)) = T \<and> (\<exists>r. ind \<le> r \<and> r < length \<acute>E \<and> BtoW(\<acute>E!r,\<acute>M))))\<guillemotright>"
definition Propagate_Black_aux :: "gar_coll_state ann_com" where
"Propagate_Black_aux \<equiv>
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M\<rbrace>
\<acute>ind:=0;;
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M \<and> \<acute>ind=0\<rbrace>
WHILE \<acute>ind<length \<acute>E
INV \<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> \<acute>PBInv \<acute>ind \<and> \<acute>ind\<le>length \<acute>E\<rbrace>
DO \<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> \<acute>PBInv \<acute>ind \<and> \<acute>ind<length \<acute>E\<rbrace>
IF \<acute>M!(fst (\<acute>E!\<acute>ind)) = Black THEN
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> \<acute>PBInv \<acute>ind \<and> \<acute>ind<length \<acute>E \<and> \<acute>M!fst(\<acute>E!\<acute>ind)=Black\<rbrace>
\<acute>M:=\<acute>M[snd(\<acute>E!\<acute>ind):=Black];;
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> \<acute>PBInv (\<acute>ind + 1) \<and> \<acute>ind<length \<acute>E\<rbrace>
\<acute>ind:=\<acute>ind+1
FI
OD"
lemma Propagate_Black_aux:
"\<turnstile> Propagate_Black_aux
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> ( \<acute>obc < Blacks \<acute>M \<or> \<acute>Safe)\<rbrace>"
apply (unfold Propagate_Black_aux_def PBInv_def collector_defs)
apply annhoare
apply(simp_all add:Graph6 Graph7 Graph8 Graph12)
apply force
apply force
apply force
\<comment> \<open>4 subgoals left\<close>
apply clarify
apply(simp add:Proper_Edges_def Proper_Roots_def Graph6 Graph7 Graph8 Graph12)
apply (erule disjE)
apply(rule disjI1)
apply(erule Graph13)
apply force
apply (case_tac "M x ! snd (E x ! ind x)=Black")
apply (simp add: Graph10 BtoW_def)
apply (rule disjI2)
apply clarify
apply (erule less_SucE)
apply (erule_tac x=i in allE , erule (1) notE impE)
apply simp
apply clarify
apply (drule_tac y = r in le_imp_less_or_eq)
apply (erule disjE)
apply (subgoal_tac "Suc (ind x)\<le>r")
apply fast
apply arith
apply fast
apply fast
apply(rule disjI1)
apply(erule subset_psubset_trans)
apply(erule Graph11)
apply fast
\<comment> \<open>3 subgoals left\<close>
apply force
apply force
\<comment> \<open>last\<close>
apply clarify
apply simp
apply(subgoal_tac "ind x = length (E x)")
apply (simp)
apply(drule Graph1)
apply simp
apply clarify
apply(erule allE, erule impE, assumption)
apply force
apply force
apply arith
done
subsubsection \<open>Refining propagating black\<close>
definition Auxk :: "gar_coll_state \<Rightarrow> bool" where
"Auxk \<equiv> \<guillemotleft>\<acute>k<length \<acute>M \<and> (\<acute>M!\<acute>k\<noteq>Black \<or> \<not>BtoW(\<acute>E!\<acute>ind, \<acute>M) \<or>
\<acute>obc<Blacks \<acute>M \<or> (\<not>\<acute>z \<and> \<acute>ind=R \<and> snd(\<acute>E!R)=T
\<and> (\<exists>r. \<acute>ind<r \<and> r<length \<acute>E \<and> BtoW(\<acute>E!r, \<acute>M))))\<guillemotright>"
definition Propagate_Black :: " gar_coll_state ann_com" where
"Propagate_Black \<equiv>
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M\<rbrace>
\<acute>ind:=0;;
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M \<and> \<acute>ind=0\<rbrace>
WHILE \<acute>ind<length \<acute>E
INV \<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> \<acute>PBInv \<acute>ind \<and> \<acute>ind\<le>length \<acute>E\<rbrace>
DO \<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> \<acute>PBInv \<acute>ind \<and> \<acute>ind<length \<acute>E\<rbrace>
IF (\<acute>M!(fst (\<acute>E!\<acute>ind)))=Black THEN
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> \<acute>PBInv \<acute>ind \<and> \<acute>ind<length \<acute>E \<and> (\<acute>M!fst(\<acute>E!\<acute>ind))=Black\<rbrace>
\<acute>k:=(snd(\<acute>E!\<acute>ind));;
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> \<acute>PBInv \<acute>ind \<and> \<acute>ind<length \<acute>E \<and> (\<acute>M!fst(\<acute>E!\<acute>ind))=Black
\<and> \<acute>Auxk\<rbrace>
\<langle>\<acute>M:=\<acute>M[\<acute>k:=Black],, \<acute>ind:=\<acute>ind+1\<rangle>
ELSE \<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> \<acute>PBInv \<acute>ind \<and> \<acute>ind<length \<acute>E\<rbrace>
\<langle>IF (\<acute>M!(fst (\<acute>E!\<acute>ind)))\<noteq>Black THEN \<acute>ind:=\<acute>ind+1 FI\<rangle>
FI
OD"
lemma Propagate_Black:
"\<turnstile> Propagate_Black
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> ( \<acute>obc < Blacks \<acute>M \<or> \<acute>Safe)\<rbrace>"
apply (unfold Propagate_Black_def PBInv_def Auxk_def collector_defs)
apply annhoare
apply(simp_all add: Graph6 Graph7 Graph8 Graph12)
apply force
apply force
apply force
\<comment> \<open>5 subgoals left\<close>
apply clarify
apply(simp add:BtoW_def Proper_Edges_def)
\<comment> \<open>4 subgoals left\<close>
apply clarify
apply(simp add:Proper_Edges_def Graph6 Graph7 Graph8 Graph12)
apply (erule disjE)
apply (rule disjI1)
apply (erule psubset_subset_trans)
apply (erule Graph9)
apply (case_tac "M x!k x=Black")
apply (case_tac "M x ! snd (E x ! ind x)=Black")
apply (simp add: Graph10 BtoW_def)
apply (rule disjI2)
apply clarify
apply (erule less_SucE)
apply (erule_tac x=i in allE , erule (1) notE impE)
apply simp
apply clarify
apply (drule_tac y = r in le_imp_less_or_eq)
apply (erule disjE)
apply (subgoal_tac "Suc (ind x)\<le>r")
apply fast
apply arith
apply fast
apply fast
apply (simp add: Graph10 BtoW_def)
apply (erule disjE)
apply (erule disjI1)
apply clarify
apply (erule less_SucE)
apply force
apply simp
apply (subgoal_tac "Suc R\<le>r")
apply fast
apply arith
apply(rule disjI1)
apply(erule subset_psubset_trans)
apply(erule Graph11)
apply fast
\<comment> \<open>2 subgoals left\<close>
apply clarify
apply(simp add:Proper_Edges_def Graph6 Graph7 Graph8 Graph12)
apply (erule disjE)
apply fast
apply clarify
apply (erule less_SucE)
apply (erule_tac x=i in allE , erule (1) notE impE)
apply simp
apply clarify
apply (drule_tac y = r in le_imp_less_or_eq)
apply (erule disjE)
apply (subgoal_tac "Suc (ind x)\<le>r")
apply fast
apply arith
apply (simp add: BtoW_def)
apply (simp add: BtoW_def)
\<comment> \<open>last\<close>
apply clarify
apply simp
apply(subgoal_tac "ind x = length (E x)")
apply (simp)
apply(drule Graph1)
apply simp
apply clarify
apply(erule allE, erule impE, assumption)
apply force
apply force
apply arith
done
subsubsection \<open>Counting black nodes\<close>
definition CountInv :: "gar_coll_state \<Rightarrow> nat \<Rightarrow> bool" where
"CountInv \<equiv> \<guillemotleft> \<lambda>ind. {i. i<ind \<and> \<acute>Ma!i=Black}\<subseteq>\<acute>bc \<guillemotright>"
definition Count :: " gar_coll_state ann_com" where
"Count \<equiv>
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M
\<and> \<acute>obc\<subseteq>Blacks \<acute>Ma \<and> Blacks \<acute>Ma\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> length \<acute>Ma=length \<acute>M \<and> (\<acute>obc < Blacks \<acute>Ma \<or> \<acute>Safe) \<and> \<acute>bc={}\<rbrace>
\<acute>ind:=0;;
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M
\<and> \<acute>obc\<subseteq>Blacks \<acute>Ma \<and> Blacks \<acute>Ma\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> length \<acute>Ma=length \<acute>M \<and> (\<acute>obc < Blacks \<acute>Ma \<or> \<acute>Safe) \<and> \<acute>bc={}
\<and> \<acute>ind=0\<rbrace>
WHILE \<acute>ind<length \<acute>M
INV \<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M
\<and> \<acute>obc\<subseteq>Blacks \<acute>Ma \<and> Blacks \<acute>Ma\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> length \<acute>Ma=length \<acute>M \<and> \<acute>CountInv \<acute>ind
\<and> ( \<acute>obc < Blacks \<acute>Ma \<or> \<acute>Safe) \<and> \<acute>ind\<le>length \<acute>M\<rbrace>
DO \<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M
\<and> \<acute>obc\<subseteq>Blacks \<acute>Ma \<and> Blacks \<acute>Ma\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> length \<acute>Ma=length \<acute>M \<and> \<acute>CountInv \<acute>ind
\<and> ( \<acute>obc < Blacks \<acute>Ma \<or> \<acute>Safe) \<and> \<acute>ind<length \<acute>M\<rbrace>
IF \<acute>M!\<acute>ind=Black
THEN \<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M
\<and> \<acute>obc\<subseteq>Blacks \<acute>Ma \<and> Blacks \<acute>Ma\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> length \<acute>Ma=length \<acute>M \<and> \<acute>CountInv \<acute>ind
\<and> ( \<acute>obc < Blacks \<acute>Ma \<or> \<acute>Safe) \<and> \<acute>ind<length \<acute>M \<and> \<acute>M!\<acute>ind=Black\<rbrace>
\<acute>bc:=insert \<acute>ind \<acute>bc
FI;;
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M
\<and> \<acute>obc\<subseteq>Blacks \<acute>Ma \<and> Blacks \<acute>Ma\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> length \<acute>Ma=length \<acute>M \<and> \<acute>CountInv (\<acute>ind+1)
\<and> ( \<acute>obc < Blacks \<acute>Ma \<or> \<acute>Safe) \<and> \<acute>ind<length \<acute>M\<rbrace>
\<acute>ind:=\<acute>ind+1
OD"
lemma Count:
"\<turnstile> Count
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M
\<and> \<acute>obc\<subseteq>Blacks \<acute>Ma \<and> Blacks \<acute>Ma\<subseteq>\<acute>bc \<and> \<acute>bc\<subseteq>Blacks \<acute>M \<and> length \<acute>Ma=length \<acute>M
\<and> (\<acute>obc < Blacks \<acute>Ma \<or> \<acute>Safe)\<rbrace>"
apply(unfold Count_def)
apply annhoare
apply(simp_all add:CountInv_def Graph6 Graph7 Graph8 Graph12 Blacks_def collector_defs)
apply force
apply force
apply force
apply clarify
apply simp
apply(fast elim:less_SucE)
apply clarify
apply simp
apply(fast elim:less_SucE)
apply force
apply force
done
subsubsection \<open>Appending garbage nodes to the free list\<close>
axiomatization Append_to_free :: "nat \<times> edges \<Rightarrow> edges"
where
Append_to_free0: "length (Append_to_free (i, e)) = length e" and
Append_to_free1: "Proper_Edges (m, e)
\<Longrightarrow> Proper_Edges (m, Append_to_free(i, e))" and
Append_to_free2: "i \<notin> Reach e
\<Longrightarrow> n \<in> Reach (Append_to_free(i, e)) = ( n = i \<or> n \<in> Reach e)"
definition AppendInv :: "gar_coll_state \<Rightarrow> nat \<Rightarrow> bool" where
"AppendInv \<equiv> \<guillemotleft>\<lambda>ind. \<forall>i<length \<acute>M. ind\<le>i \<longrightarrow> i\<in>Reach \<acute>E \<longrightarrow> \<acute>M!i=Black\<guillemotright>"
definition Append :: "gar_coll_state ann_com" where
"Append \<equiv>
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>Safe\<rbrace>
\<acute>ind:=0;;
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>Safe \<and> \<acute>ind=0\<rbrace>
WHILE \<acute>ind<length \<acute>M
INV \<lbrace>\<acute>Proper \<and> \<acute>AppendInv \<acute>ind \<and> \<acute>ind\<le>length \<acute>M\<rbrace>
DO \<lbrace>\<acute>Proper \<and> \<acute>AppendInv \<acute>ind \<and> \<acute>ind<length \<acute>M\<rbrace>
IF \<acute>M!\<acute>ind=Black THEN
\<lbrace>\<acute>Proper \<and> \<acute>AppendInv \<acute>ind \<and> \<acute>ind<length \<acute>M \<and> \<acute>M!\<acute>ind=Black\<rbrace>
\<acute>M:=\<acute>M[\<acute>ind:=White]
ELSE \<lbrace>\<acute>Proper \<and> \<acute>AppendInv \<acute>ind \<and> \<acute>ind<length \<acute>M \<and> \<acute>ind\<notin>Reach \<acute>E\<rbrace>
\<acute>E:=Append_to_free(\<acute>ind,\<acute>E)
FI;;
\<lbrace>\<acute>Proper \<and> \<acute>AppendInv (\<acute>ind+1) \<and> \<acute>ind<length \<acute>M\<rbrace>
\<acute>ind:=\<acute>ind+1
OD"
lemma Append:
"\<turnstile> Append \<lbrace>\<acute>Proper\<rbrace>"
apply(unfold Append_def AppendInv_def)
apply annhoare
apply(simp_all add:collector_defs Graph6 Graph7 Graph8 Append_to_free0 Append_to_free1 Graph12)
apply(force simp:Blacks_def nth_list_update)
apply force
apply force
apply(force simp add:Graph_defs)
apply force
apply clarify
apply simp
apply(rule conjI)
apply (erule Append_to_free1)
apply clarify
apply (drule_tac n = "i" in Append_to_free2)
apply force
apply force
apply force
done
subsubsection \<open>Correctness of the Collector\<close>
definition Collector :: " gar_coll_state ann_com" where
"Collector \<equiv>
\<lbrace>\<acute>Proper\<rbrace>
WHILE True INV \<lbrace>\<acute>Proper\<rbrace>
DO
Blacken_Roots;;
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M\<rbrace>
\<acute>obc:={};;
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc={}\<rbrace>
\<acute>bc:=Roots;;
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc={} \<and> \<acute>bc=Roots\<rbrace>
\<acute>Ma:=M_init;;
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc={} \<and> \<acute>bc=Roots \<and> \<acute>Ma=M_init\<rbrace>
WHILE \<acute>obc\<noteq>\<acute>bc
INV \<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M
\<and> \<acute>obc\<subseteq>Blacks \<acute>Ma \<and> Blacks \<acute>Ma\<subseteq>\<acute>bc \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> length \<acute>Ma=length \<acute>M \<and> (\<acute>obc < Blacks \<acute>Ma \<or> \<acute>Safe)\<rbrace>
DO \<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M\<rbrace>
\<acute>obc:=\<acute>bc;;
Propagate_Black;;
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M
\<and> (\<acute>obc < Blacks \<acute>M \<or> \<acute>Safe)\<rbrace>
\<acute>Ma:=\<acute>M;;
\<lbrace>\<acute>Proper \<and> Roots\<subseteq>Blacks \<acute>M \<and> \<acute>obc\<subseteq>Blacks \<acute>Ma
\<and> Blacks \<acute>Ma\<subseteq>Blacks \<acute>M \<and> \<acute>bc\<subseteq>Blacks \<acute>M \<and> length \<acute>Ma=length \<acute>M
\<and> ( \<acute>obc < Blacks \<acute>Ma \<or> \<acute>Safe)\<rbrace>
\<acute>bc:={};;
Count
OD;;
Append
OD"
lemma Collector:
"\<turnstile> Collector \<lbrace>False\<rbrace>"
apply(unfold Collector_def)
apply annhoare
apply(simp_all add: Blacken_Roots Propagate_Black Count Append)
apply(simp_all add:Blacken_Roots_def Propagate_Black_def Count_def Append_def collector_defs)
apply (force simp add: Proper_Roots_def)
apply force
apply force
apply clarify
apply (erule disjE)
apply(simp add:psubsetI)
apply(force dest:subset_antisym)
done
subsection \<open>Interference Freedom\<close>
lemmas modules = Redirect_Edge_def Color_Target_def Blacken_Roots_def
Propagate_Black_def Count_def Append_def
lemmas Invariants = PBInv_def Auxk_def CountInv_def AppendInv_def
lemmas abbrev = collector_defs mutator_defs Invariants
lemma interfree_Blacken_Roots_Redirect_Edge:
"interfree_aux (Some Blacken_Roots, {}, Some Redirect_Edge)"
apply (unfold modules)
apply interfree_aux
apply safe
apply (simp_all add:Graph6 Graph12 abbrev)
done
lemma interfree_Redirect_Edge_Blacken_Roots:
"interfree_aux (Some Redirect_Edge, {}, Some Blacken_Roots)"
apply (unfold modules)
apply interfree_aux
apply safe
apply(simp add:abbrev)+
done
lemma interfree_Blacken_Roots_Color_Target:
"interfree_aux (Some Blacken_Roots, {}, Some Color_Target)"
apply (unfold modules)
apply interfree_aux
apply safe
apply(simp_all add:Graph7 Graph8 nth_list_update abbrev)
done
lemma interfree_Color_Target_Blacken_Roots:
"interfree_aux (Some Color_Target, {}, Some Blacken_Roots)"
apply (unfold modules )
apply interfree_aux
apply safe
apply(simp add:abbrev)+
done
lemma interfree_Propagate_Black_Redirect_Edge:
"interfree_aux (Some Propagate_Black, {}, Some Redirect_Edge)"
apply (unfold modules )
apply interfree_aux
\<comment> \<open>11 subgoals left\<close>
apply(clarify, simp add:abbrev Graph6 Graph12)
apply(clarify, simp add:abbrev Graph6 Graph12)
apply(clarify, simp add:abbrev Graph6 Graph12)
apply(clarify, simp add:abbrev Graph6 Graph12)
apply(erule conjE)+
apply(erule disjE, erule disjI1, rule disjI2, rule allI, (rule impI)+, case_tac "R=i", rule conjI, erule sym)
apply(erule Graph4)
apply(simp)+
apply (simp add:BtoW_def)
apply (simp add:BtoW_def)
apply(rule conjI)
apply (force simp add:BtoW_def)
apply(erule Graph4)
apply simp+
\<comment> \<open>7 subgoals left\<close>
apply(clarify, simp add:abbrev Graph6 Graph12)
apply(erule conjE)+
apply(erule disjE, erule disjI1, rule disjI2, rule allI, (rule impI)+, case_tac "R=i", rule conjI, erule sym)
apply(erule Graph4)
apply(simp)+
apply (simp add:BtoW_def)
apply (simp add:BtoW_def)
apply(rule conjI)
apply (force simp add:BtoW_def)
apply(erule Graph4)
apply simp+
\<comment> \<open>6 subgoals left\<close>
apply(clarify, simp add:abbrev Graph6 Graph12)
apply(erule conjE)+
apply(rule conjI)
apply(erule disjE, erule disjI1, rule disjI2, rule allI, (rule impI)+, case_tac "R=i", rule conjI, erule sym)
apply(erule Graph4)
apply(simp)+
apply (simp add:BtoW_def)
apply (simp add:BtoW_def)
apply(rule conjI)
apply (force simp add:BtoW_def)
apply(erule Graph4)
apply simp+
apply(simp add:BtoW_def nth_list_update)
apply force
\<comment> \<open>5 subgoals left\<close>
apply(clarify, simp add:abbrev Graph6 Graph12)
\<comment> \<open>4 subgoals left\<close>
apply(clarify, simp add:abbrev Graph6 Graph12)
apply(rule conjI)
apply(erule disjE, erule disjI1, rule disjI2, rule allI, (rule impI)+, case_tac "R=i", rule conjI, erule sym)
apply(erule Graph4)
apply(simp)+
apply (simp add:BtoW_def)
apply (simp add:BtoW_def)
apply(rule conjI)
apply (force simp add:BtoW_def)
apply(erule Graph4)
apply simp+
apply(rule conjI)
apply(simp add:nth_list_update)
apply force
apply(rule impI, rule impI, erule disjE, erule disjI1, case_tac "R = (ind x)" ,case_tac "M x ! T = Black")
apply(force simp add:BtoW_def)
apply(case_tac "M x !snd (E x ! ind x)=Black")
apply(rule disjI2)
apply simp
apply (erule Graph5)
apply simp+
apply(force simp add:BtoW_def)
apply(force simp add:BtoW_def)
\<comment> \<open>3 subgoals left\<close>
apply(clarify, simp add:abbrev Graph6 Graph12)
\<comment> \<open>2 subgoals left\<close>
apply(clarify, simp add:abbrev Graph6 Graph12)
apply(erule disjE, erule disjI1, rule disjI2, rule allI, (rule impI)+, case_tac "R=i", rule conjI, erule sym)
apply clarify
apply(erule Graph4)
apply(simp)+
apply (simp add:BtoW_def)
apply (simp add:BtoW_def)
apply(rule conjI)
apply (force simp add:BtoW_def)
apply(erule Graph4)
apply simp+
done
lemma interfree_Redirect_Edge_Propagate_Black:
"interfree_aux (Some Redirect_Edge, {}, Some Propagate_Black)"
apply (unfold modules )
apply interfree_aux
apply(clarify, simp add:abbrev)+
done
lemma interfree_Propagate_Black_Color_Target:
"interfree_aux (Some Propagate_Black, {}, Some Color_Target)"
apply (unfold modules )
apply interfree_aux
\<comment> \<open>11 subgoals left\<close>
apply(clarify, simp add:abbrev Graph7 Graph8 Graph12)+
apply(erule conjE)+
apply(erule disjE,rule disjI1,erule psubset_subset_trans,erule Graph9,
case_tac "M x!T=Black", rule disjI2,rotate_tac -1, simp add: Graph10, clarify,
erule allE, erule impE, assumption, erule impE, assumption,
simp add:BtoW_def, rule disjI1, erule subset_psubset_trans, erule Graph11, force)
\<comment> \<open>7 subgoals left\<close>
apply(clarify, simp add:abbrev Graph7 Graph8 Graph12)
apply(erule conjE)+
apply(erule disjE,rule disjI1,erule psubset_subset_trans,erule Graph9,
case_tac "M x!T=Black", rule disjI2,rotate_tac -1, simp add: Graph10, clarify,
erule allE, erule impE, assumption, erule impE, assumption,
simp add:BtoW_def, rule disjI1, erule subset_psubset_trans, erule Graph11, force)
\<comment> \<open>6 subgoals left\<close>
apply(clarify, simp add:abbrev Graph7 Graph8 Graph12)
apply clarify
apply (rule conjI)
apply(erule disjE,rule disjI1,erule psubset_subset_trans,erule Graph9,
case_tac "M x!T=Black", rule disjI2,rotate_tac -1, simp add: Graph10, clarify,
erule allE, erule impE, assumption, erule impE, assumption,
simp add:BtoW_def, rule disjI1, erule subset_psubset_trans, erule Graph11, force)
apply(simp add:nth_list_update)
\<comment> \<open>5 subgoals left\<close>
apply(clarify, simp add:abbrev Graph7 Graph8 Graph12)
\<comment> \<open>4 subgoals left\<close>
apply(clarify, simp add:abbrev Graph7 Graph8 Graph12)
apply (rule conjI)
apply(erule disjE,rule disjI1,erule psubset_subset_trans,erule Graph9,
case_tac "M x!T=Black", rule disjI2,rotate_tac -1, simp add: Graph10, clarify,
erule allE, erule impE, assumption, erule impE, assumption,
simp add:BtoW_def, rule disjI1, erule subset_psubset_trans, erule Graph11, force)
apply(rule conjI)
apply(simp add:nth_list_update)
apply(rule impI,rule impI, case_tac "M x!T=Black",rotate_tac -1, force simp add: BtoW_def Graph10,
erule subset_psubset_trans, erule Graph11, force)
\<comment> \<open>3 subgoals left\<close>
apply(clarify, simp add:abbrev Graph7 Graph8 Graph12)
\<comment> \<open>2 subgoals left\<close>
apply(clarify, simp add:abbrev Graph7 Graph8 Graph12)
apply(erule disjE,rule disjI1,erule psubset_subset_trans,erule Graph9,
case_tac "M x!T=Black", rule disjI2,rotate_tac -1, simp add: Graph10, clarify,
erule allE, erule impE, assumption, erule impE, assumption,
simp add:BtoW_def, rule disjI1, erule subset_psubset_trans, erule Graph11, force)
\<comment> \<open>3 subgoals left\<close>
apply(simp add:abbrev)
done
lemma interfree_Color_Target_Propagate_Black:
"interfree_aux (Some Color_Target, {}, Some Propagate_Black)"
apply (unfold modules )
apply interfree_aux
apply(clarify, simp add:abbrev)+
done
lemma interfree_Count_Redirect_Edge:
"interfree_aux (Some Count, {}, Some Redirect_Edge)"
apply (unfold modules)
apply interfree_aux
\<comment> \<open>9 subgoals left\<close>
apply(simp_all add:abbrev Graph6 Graph12)
\<comment> \<open>6 subgoals left\<close>
apply(clarify, simp add:abbrev Graph6 Graph12,
erule disjE,erule disjI1,rule disjI2,rule subset_trans, erule Graph3,force,force)+
done
lemma interfree_Redirect_Edge_Count:
"interfree_aux (Some Redirect_Edge, {}, Some Count)"
apply (unfold modules )
apply interfree_aux
apply(clarify,simp add:abbrev)+
apply(simp add:abbrev)
done
lemma interfree_Count_Color_Target:
"interfree_aux (Some Count, {}, Some Color_Target)"
apply (unfold modules )
apply interfree_aux
\<comment> \<open>9 subgoals left\<close>
apply(simp_all add:abbrev Graph7 Graph8 Graph12)
\<comment> \<open>6 subgoals left\<close>
apply(clarify,simp add:abbrev Graph7 Graph8 Graph12,
erule disjE, erule disjI1, rule disjI2,erule subset_trans, erule Graph9)+
\<comment> \<open>2 subgoals left\<close>
apply(clarify, simp add:abbrev Graph7 Graph8 Graph12)
apply(rule conjI)
apply(erule disjE, erule disjI1, rule disjI2,erule subset_trans, erule Graph9)
apply(simp add:nth_list_update)
\<comment> \<open>1 subgoal left\<close>
apply(clarify, simp add:abbrev Graph7 Graph8 Graph12,
erule disjE, erule disjI1, rule disjI2,erule subset_trans, erule Graph9)
done
lemma interfree_Color_Target_Count:
"interfree_aux (Some Color_Target, {}, Some Count)"
apply (unfold modules )
apply interfree_aux
apply(clarify, simp add:abbrev)+
apply(simp add:abbrev)
done
lemma interfree_Append_Redirect_Edge:
"interfree_aux (Some Append, {}, Some Redirect_Edge)"
apply (unfold modules )
apply interfree_aux
apply( simp_all add:abbrev Graph6 Append_to_free0 Append_to_free1 Graph12)
apply(clarify, simp add:abbrev Graph6 Append_to_free0 Append_to_free1 Graph12, force dest:Graph3)+
done
lemma interfree_Redirect_Edge_Append:
"interfree_aux (Some Redirect_Edge, {}, Some Append)"
apply (unfold modules )
apply interfree_aux
apply(clarify, simp add:abbrev Append_to_free0)+
apply (force simp add: Append_to_free2)
apply(clarify, simp add:abbrev Append_to_free0)+
done
lemma interfree_Append_Color_Target:
"interfree_aux (Some Append, {}, Some Color_Target)"
apply (unfold modules )
apply interfree_aux
apply(clarify, simp add:abbrev Graph7 Graph8 Append_to_free0 Append_to_free1 Graph12 nth_list_update)+
apply(simp add:abbrev Graph7 Graph8 Append_to_free0 Append_to_free1 Graph12 nth_list_update)
done
lemma interfree_Color_Target_Append:
"interfree_aux (Some Color_Target, {}, Some Append)"
apply (unfold modules )
apply interfree_aux
apply(clarify, simp add:abbrev Append_to_free0)+
apply (force simp add: Append_to_free2)
apply(clarify,simp add:abbrev Append_to_free0)+
done
lemmas collector_mutator_interfree =
interfree_Blacken_Roots_Redirect_Edge interfree_Blacken_Roots_Color_Target
interfree_Propagate_Black_Redirect_Edge interfree_Propagate_Black_Color_Target
interfree_Count_Redirect_Edge interfree_Count_Color_Target
interfree_Append_Redirect_Edge interfree_Append_Color_Target
interfree_Redirect_Edge_Blacken_Roots interfree_Color_Target_Blacken_Roots
interfree_Redirect_Edge_Propagate_Black interfree_Color_Target_Propagate_Black
interfree_Redirect_Edge_Count interfree_Color_Target_Count
interfree_Redirect_Edge_Append interfree_Color_Target_Append
subsubsection \<open>Interference freedom Collector-Mutator\<close>
lemma interfree_Collector_Mutator:
"interfree_aux (Some Collector, {}, Some Mutator)"
apply(unfold Collector_def Mutator_def)
apply interfree_aux
apply(simp_all add:collector_mutator_interfree)
apply(unfold modules collector_defs Mut_init_def)
apply(tactic \<open>TRYALL (interfree_aux_tac \<^context>)\<close>)
\<comment> \<open>32 subgoals left\<close>
apply(simp_all add:Graph6 Graph7 Graph8 Append_to_free0 Append_to_free1 Graph12)
\<comment> \<open>20 subgoals left\<close>
apply(tactic\<open>TRYALL (clarify_tac \<^context>)\<close>)
apply(simp_all add:Graph6 Graph7 Graph8 Append_to_free0 Append_to_free1 Graph12)
apply(tactic \<open>TRYALL (eresolve_tac \<^context> [disjE])\<close>)
apply simp_all
apply(tactic \<open>TRYALL(EVERY'[resolve_tac \<^context> [disjI2],
resolve_tac \<^context> [subset_trans],
eresolve_tac \<^context> @{thms Graph3},
force_tac \<^context>,
assume_tac \<^context>])\<close>)
apply(tactic \<open>TRYALL(EVERY'[resolve_tac \<^context> [disjI2],
eresolve_tac \<^context> [subset_trans],
resolve_tac \<^context> @{thms Graph9},
force_tac \<^context>])\<close>)
apply(tactic \<open>TRYALL(EVERY'[resolve_tac \<^context> [disjI1],
eresolve_tac \<^context> @{thms psubset_subset_trans},
resolve_tac \<^context> @{thms Graph9},
force_tac \<^context>])\<close>)
done
subsubsection \<open>Interference freedom Mutator-Collector\<close>
lemma interfree_Mutator_Collector:
"interfree_aux (Some Mutator, {}, Some Collector)"
apply(unfold Collector_def Mutator_def)
apply interfree_aux
apply(simp_all add:collector_mutator_interfree)
apply(unfold modules collector_defs Mut_init_def)
apply(tactic \<open>TRYALL (interfree_aux_tac \<^context>)\<close>)
\<comment> \<open>64 subgoals left\<close>
apply(simp_all add:nth_list_update Invariants Append_to_free0)+
apply(tactic\<open>TRYALL (clarify_tac \<^context>)\<close>)
\<comment> \<open>4 subgoals left\<close>
apply force
apply(simp add:Append_to_free2)
apply force
apply(simp add:Append_to_free2)
done
subsubsection \<open>The Garbage Collection algorithm\<close>
text \<open>In total there are 289 verification conditions.\<close>
lemma Gar_Coll:
"\<parallel>- \<lbrace>\<acute>Proper \<and> \<acute>Mut_init \<and> \<acute>z\<rbrace>
COBEGIN
Collector
\<lbrace>False\<rbrace>
\<parallel>
Mutator
\<lbrace>False\<rbrace>
COEND
\<lbrace>False\<rbrace>"
apply oghoare
apply(force simp add: Mutator_def Collector_def modules)
apply(rule Collector)
apply(rule Mutator)
apply(simp add:interfree_Collector_Mutator)
apply(simp add:interfree_Mutator_Collector)
apply force
done
end
|
theory Ranking_Order_Probabilistic_Vertex_Weighted
imports
Ranking_Order
Bipartite_Vertex_Weighted_Matching_LP
Order_Relations_From_Priorities
Bipartite_Vertex_Priorities
begin
hide_type Finite_Cartesian_Product.vec
hide_const Finite_Cartesian_Product.vec Finite_Cartesian_Product.vec.vec_nth
lemma gt_exp_minus_One_ln_gt_minus_One:
fixes x :: real
shows "exp(-1) < x \<Longrightarrow> -1 < ln x"
by (smt (verit) exp_gt_zero exp_ln ln_ge_iff)
locale wf_vertex_weighted_online_bipartite_matching =
bipartite_vertex_weighted_matching_lp + bipartite_vertex_priorities +
fixes \<pi> :: "'a list"
assumes perm: "\<pi> \<in> permutations_of_set R"
begin
abbreviation g :: "real \<Rightarrow> real" where
"g x \<equiv> exp(x - 1)"
abbreviation F :: real where
"F \<equiv> 1 - exp(-1)"
definition ranking_prob :: "'a graph measure" where
"ranking_prob \<equiv> do {
Y \<leftarrow> \<Y>;
let r = weighted_linorder_from_keys L v g Y;
return (count_space {M. M \<subseteq> G}) (ranking r G \<pi>)
}"
definition "max_weight \<equiv> if L = {} then 0 else Max (v ` L)"
definition dual_sol :: "('a \<Rightarrow> real) \<Rightarrow> 'a graph \<Rightarrow> real vec" where
"dual_sol Y M \<equiv> vec n (\<lambda>k.
if Vs_enum_inv k \<in> Vs M
then
if k < card L
then v (Vs_enum_inv k) * (g \<circ> Y) (Vs_enum_inv k) / F
else v (THE l. {l, Vs_enum_inv k} \<in> M) * (1 - (g \<circ> Y) (THE l. {l, Vs_enum_inv k} \<in> M)) / F
else 0
)"
definition y\<^sub>c :: "('a \<Rightarrow> real) \<Rightarrow> 'a list \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> real" where
"y\<^sub>c Y js i j \<equiv>
if j \<in> Vs (ranking (weighted_linorder_from_keys L v g Y) (G \<setminus> {i}) js)
then
let i' = (THE i'. {i', j} \<in> ranking (weighted_linorder_from_keys L v g Y) (G \<setminus> {i}) js) in
\<comment> \<open>intuitively, \<^term>\<open>i\<close> will only ever get matched if it has large enough value compared to \<^term>\<open>i'\<close> (depending on \<^term>\<open>Y i'\<close>)\<close>
if 1 - v i' * (1 - g (Y i')) / v i > exp(-1)
then ln (1 - v i' * (1 - g (Y i')) / v i) + 1
else 0
else 1"
lemma g_less_eq_OneI: "0 \<le> x \<Longrightarrow> x \<le> 1 \<Longrightarrow> g x \<le> 1"
by auto
lemma weight_nonnegI[intro]: "i \<in> L \<Longrightarrow> 0 \<le> v i"
using weights_pos
by force
lemma max_weight_nonneg[intro,simp]: "0 \<le> max_weight"
unfolding max_weight_def
using finite_L
by (auto simp: Max_ge_iff)
lemma max_weight_greatest: "i \<in> L \<Longrightarrow> v i \<le> max_weight"
unfolding max_weight_def
using finite_L
by auto
lemma scaled_weight_le_max_weight: "i \<in> L \<Longrightarrow> c \<le> 1 \<Longrightarrow> v i * c \<le> max_weight"
using mult_left_le weight_nonnegI max_weight_greatest by fastforce
lemma div_F_nonneg[simp]: "0 \<le> x / F \<longleftrightarrow> 0 \<le> x"
by (simp add: zero_le_divide_iff)
lemma div_F_less_eq_cancel[simp]: "x / F \<le> y / F \<longleftrightarrow> x \<le> y"
by (simp add: divide_le_cancel)
lemma dim_dual_sol[simp]: "dim_vec (dual_sol Y M) = n"
by (simp add: dual_sol_def)
lemma dual_dot_One_value:
assumes "M \<subseteq> G"
assumes "matching M"
shows "1\<^sub>v n \<bullet> dual_sol Y M = matching_value M / F"
proof -
have "1\<^sub>v n \<bullet> dual_sol Y M =
(\<Sum>i\<in>{0..<n} \<inter> {i. Vs_enum_inv i \<in> Vs M} \<inter> {i. i < card L}. v (Vs_enum_inv i) * g (Y (Vs_enum_inv i)) / F) +
(\<Sum>i\<in>{0..<n} \<inter> {i. Vs_enum_inv i \<in> Vs M} \<inter> - {i. i < card L}. v (THE l. {l, Vs_enum_inv i} \<in> M) * (1 - g (Y (THE l. {l, Vs_enum_inv i} \<in> M))) / F)"
(is "_ = ?sum_L + ?sum_R")
by (simp add: dual_sol_def scalar_prod_def sum.If_cases)
have L_sum_matching: "?sum_L = (\<Sum>e\<in>M. v (THE l. l \<in> L \<and> l \<in> e) * g (Y (THE l. l \<in> L \<and> l \<in> e)) / F)"
proof (rule sum.reindex_bij_witness[where j = "\<lambda>i. (THE e. e \<in> M \<and> Vs_enum_inv i \<in> e)" and
i = "\<lambda>e. Vs_enum (THE l. l \<in> L \<and> l \<in> e)"])
fix i
assume i: "i \<in> {0..<local.n} \<inter> {i. local.Vs_enum_inv i \<in> Vs M} \<inter> {i. i < card L}"
then obtain e where e: "e \<in> M" "Vs_enum_inv i \<in> e" and i_less_n: "i < n"
by (auto elim: vs_member_elim)
with \<open>matching M\<close> have the_e: "(THE e. e \<in> M \<and> Vs_enum_inv i \<in> e) = e"
by (auto intro!: the_equality dest: matching_unique_match)
with e show "(THE e. e \<in> M \<and> local.Vs_enum_inv i \<in> e) \<in> M"
by blast
from bipartite_graph e obtain l r where e': "e = {l,r}" "l \<in> L" "r \<in> R"
by (auto elim: bipartite_edgeE dest: bipartite_subgraph[OF _ \<open>M \<subseteq> G\<close>])
from i have "Vs_enum_inv i \<in> L"
by (auto elim: Vs_enum_inv_leftE)
with bipartite_graph e e' have the_l: "(THE l. l \<in> L \<and> l \<in> e) = Vs_enum_inv i"
by (auto dest: bipartite_disjointD)
with i_less_n show "Vs_enum (THE l. l \<in> L \<and> l \<in> (THE e. e \<in> M \<and> local.Vs_enum_inv i \<in> e)) = i"
by (auto simp: the_e the_l)
show "v (THE l. l \<in> L \<and> l \<in> (THE e. e \<in> M \<and> Vs_enum_inv i \<in> e)) * g (Y (THE l. l \<in> L \<and> l \<in> (THE e. e \<in> M \<and> Vs_enum_inv i \<in> e))) / F = v (Vs_enum_inv i) * g (Y (Vs_enum_inv i)) / F"
by (simp add: the_e the_l)
next
fix e
assume eM: "e \<in> M"
with bipartite_graph obtain l r where e: "e = {l,r}" "l \<in> L" "r \<in> R"
by (auto elim: bipartite_edgeE dest: bipartite_subgraph[OF _ \<open>M \<subseteq> G\<close>])
with bipartite_graph have the_l: "(THE l. l \<in> L \<and> l \<in> e) = l"
by (auto dest: bipartite_subgraph[OF _ \<open>M \<subseteq> G\<close>] bipartite_disjointD)
from eM e \<open>matching M\<close> have the_e: "(THE e. e \<in> M \<and> l \<in> e) = e"
by (intro the_equality matching_unique_match) auto
from parts_minimal \<open>l \<in> L\<close> have "l \<in> Vs G"
by blast
then show "(THE e'. e' \<in> M \<and> Vs_enum_inv (Vs_enum (THE l. l \<in> L \<and> l \<in> e)) \<in> e') = e"
by (simp add: the_l the_e)
from e eM have "l \<in> Vs M"
by (auto dest: edges_are_Vs)
with \<open>l \<in> L\<close> show "Vs_enum (THE l. l \<in> L \<and> l \<in> e) \<in> {0..<n} \<inter> {i. Vs_enum_inv i \<in> Vs M} \<inter> {i. i < card L}"
by (auto simp: the_l intro: Vs_enum_less_card_L Vs_enum_less_n_L)
qed
have R_sum_matching: "?sum_R = (\<Sum>e\<in>M. v (THE l. l \<in> L \<and> l \<in> e) * (1 - g (Y (THE l. l \<in> L \<and> l \<in> e))) / F)"
proof (rule sum.reindex_bij_witness[where j = "\<lambda>i. (THE e. e \<in> M \<and> Vs_enum_inv i \<in> e)" and
i = "\<lambda>e. Vs_enum (THE r. r \<in> R \<and> r \<in> e)"])
fix i
assume i: "i \<in> {0..<n} \<inter> {i. Vs_enum_inv i \<in> Vs M} \<inter> - {i. i < card L}"
then obtain e where e: "e \<in> M" "Vs_enum_inv i \<in> e" and i_less_n: "i < n"
by (auto elim: vs_member_elim)
with \<open>matching M\<close> have the_e: "(THE e. e \<in> M \<and> Vs_enum_inv i \<in> e) = e"
by (auto intro!: the_equality dest: matching_unique_match)
with e show "(THE e. e \<in> M \<and> Vs_enum_inv i \<in> e) \<in> M"
by blast
from bipartite_graph e obtain l r where e': "e = {l,r}" "l \<in> L" "r \<in> R"
by (auto elim: bipartite_edgeE dest: bipartite_subgraph[OF _ \<open>M \<subseteq> G\<close>])
from i have "Vs_enum_inv i \<in> R"
by (auto elim: Vs_enum_inv_rightE)
with e' e parts_minimal have the_r: "(THE r. r \<in> R \<and> r \<in> e) = Vs_enum_inv i"
by (auto elim: Vs_cases)
from i_less_n show "Vs_enum (THE r. r \<in> R \<and> r \<in> (THE e. e \<in> M \<and> Vs_enum_inv i \<in> e)) = i"
by (simp add: the_e the_r)
from e e' bipartite_graph have the_l: "(THE l. l \<in> L \<and> l \<in> e) = l"
by (intro the_equality)
(auto dest: bipartite_subgraph[OF _ \<open>M \<subseteq> G\<close>] bipartite_disjointD)
from e e' \<open>matching M\<close> \<open>Vs_enum_inv i \<in> R\<close> have the_l': "(THE l. {l, Vs_enum_inv i} \<in> M) = l"
by (auto intro: the_match)
show "v (THE l. l \<in> L \<and> l \<in> (THE e. e \<in> M \<and> Vs_enum_inv i \<in> e)) * (1 - g (Y (THE l. l \<in> L \<and> l \<in> (THE e. e \<in> M \<and> Vs_enum_inv i \<in> e)))) / F =
v (THE l. {l, Vs_enum_inv i} \<in> M) * (1 - g (Y (THE l. {l, Vs_enum_inv i} \<in> M))) / F"
by (simp add: the_e the_l the_l')
next
fix e
assume eM: "e \<in> M"
with bipartite_graph obtain l r where e: "e = {l,r}" "l \<in> L" "r \<in> R" "l \<noteq> r"
by (auto elim: bipartite_edgeE dest: bipartite_subgraph[OF _ \<open>M \<subseteq> G\<close>])
with bipartite_graph have the_r: "(THE r. r \<in> R \<and> r \<in> e) = r"
by (intro the_equality)
(auto dest: bipartite_disjointD)
from eM \<open>e = {l,r}\<close> \<open>matching M\<close> have the_e: "(THE e. e \<in> M \<and> r \<in> e) = e"
by (intro the_equality matching_unique_match)
auto
from \<open>r \<in> R\<close> show "(THE e'. e' \<in> M \<and> Vs_enum_inv (Vs_enum (THE r. r \<in> R \<and> r \<in> e)) \<in> e') = e"
by (simp add: the_r the_e)
from eM e have "r \<in> Vs M"
by (auto dest: edges_are_Vs)
with \<open>r \<in> R\<close> show "Vs_enum (THE r. r \<in> R \<and> r \<in> e) \<in> {0..<n} \<inter> {i. Vs_enum_inv i \<in> Vs M} \<inter> - {i. i < card L}"
by (auto simp: the_r intro: Vs_enum_less_n_R dest: Vs_enum_geq_card_L)
qed
with graph L_sum_matching show ?thesis
by (auto simp: scalar_prod_def dual_sol_def n_def sum.If_cases algebra_simps sum_divide_distrib simp flip: sum.distrib add_divide_distrib)
qed
lemma primal_is_dual_times_F:
assumes "M \<subseteq> G"
assumes "matching M"
shows "vertex_weighted_coeffs \<bullet> primal_sol M = 1\<^sub>v n \<bullet> dual_sol Y M * F"
using assms
by (auto simp: primal_dot_coeffs_eq_value dual_dot_One_value)
lemma preorder_on_neighbors_linorder_from_keys[intro]:
assumes "H \<subseteq> G"
assumes "j \<in> R"
shows "preorder_on' {i. {i,j} \<in> H} (weighted_linorder_from_keys L v g Y)"
using assms perm
by (auto dest: permutations_of_setD)
lemma set_\<pi>[simp]: "set \<pi> = R"
using perm
by (auto dest: permutations_of_setD)
lemma ranking_fun_upd_remove_eq:
assumes "set js \<subseteq> R"
shows "ranking (weighted_linorder_from_keys L v g (Y(i:=y))) (G \<setminus> {i}) js = ranking (weighted_linorder_from_keys L v g Y) (G \<setminus> {i}) js"
(is "?L = ?R")
proof -
from assms have "?L = ranking (Restr (weighted_linorder_from_keys L v g (Y(i := y))) (L - {i})) (G \<setminus> {i}) js"
by (subst ranking_Restr_to_vertices[symmetric])
(auto intro: preorder_on_imp_preorder_on')
also have "\<dots> = ranking (weighted_linorder_from_keys (L - {i}) v g (Y)) (G \<setminus> {i}) js" (is "_ = ?M")
by (simp add: weighted_linorder_from_keys_Restr weighted_linorder_from_keys_update_eq)
finally have "?L = ?M" .
from assms have "?R = ranking (Restr (weighted_linorder_from_keys L v g Y) (L - {i})) (G \<setminus> {i}) js"
by (subst ranking_Restr_to_vertices[symmetric])
(auto intro: preorder_on_imp_preorder_on')
also have "\<dots> = ?M"
by (simp add: weighted_linorder_from_keys_Restr)
finally show ?thesis
by (simp add: \<open>?L = ?M\<close>)
qed
lemma y\<^sub>c_fun_upd_eq:
assumes "j \<in> R"
shows "y\<^sub>c (Y(i:=y)) \<pi> i j = y\<^sub>c Y \<pi> i j"
proof -
let ?M' = "ranking (weighted_linorder_from_keys L v g Y) (G \<setminus> {i}) \<pi>"
have "j \<in> Vs ?M' \<Longrightarrow> (THE i'. {i',j} \<in> ?M') = i \<Longrightarrow> False"
proof -
assume "j \<in> Vs ?M'"
assume the_i'_eq: "(THE i'. {i',j} \<in> ?M') = i"
from \<open>j \<in> R\<close> \<open>j \<in> Vs ?M'\<close> have the_i'_M: "{(THE i'. {i',j} \<in> ?M'), j} \<in> ?M'"
by (intro the_ranking_match_left)
(auto dest: remove_vertices_subgraph')
have "{(THE i'. {i',j} \<in> ?M'), j} \<in> G \<setminus> {i}"
by (auto intro: ranking_subgraph'[OF _ _ _ the_i'_M] dest: remove_vertices_subgraph')
then have "(THE i'. {i',j} \<in> ?M') \<in> Vs (G \<setminus> {i})"
by (auto dest: edges_are_Vs)
with the_i'_eq show False
by (auto intro: remove_vertices_not_vs')
qed
then show ?thesis
unfolding y\<^sub>c_def
by (auto simp: ranking_fun_upd_remove_eq Let_def)
qed
lemma the_ranking_match_remove_left:
assumes "j \<in> R"
assumes "j \<in> Vs (ranking (weighted_linorder_from_keys L v g Y) (G \<setminus> {i}) \<pi>)"
shows "(THE i'. {i',j} \<in> ranking (weighted_linorder_from_keys L v g Y) (G \<setminus> {i}) \<pi>) \<in> L - {i}"
proof -
let ?M = "ranking (weighted_linorder_from_keys L v g Y) (G \<setminus> {i}) \<pi>"
from assms have the_i': "{(THE i'. {i',j} \<in> ?M), j} \<in> ?M"
"(THE i'. {i',j} \<in> ?M) \<in> L"
by (auto intro!: the_ranking_match_left dest: remove_vertices_subgraph')
have subg: "?M \<subseteq> G \<setminus> {i}"
by (intro ranking_subgraph) (auto dest: remove_vertices_subgraph')
with the_i' show "(THE i'. {i',j} \<in> ?M) \<in> L - {i}"
by (auto dest!: subsetD edges_are_Vs(1)[of i j] intro: remove_vertices_not_vs'[where X = "{i}"])
qed
lemma y\<^sub>c_bounded:
assumes "i \<in> L"
assumes "j \<in> R"
assumes "Y \<in> L - {i} \<rightarrow> {0..1}"
shows "y\<^sub>c Y \<pi> i j \<in> {0..1}"
proof -
let ?i' = "THE i'. {i',j} \<in> ranking (weighted_linorder_from_keys L v g Y) (G \<setminus> {i}) \<pi>"
consider (unmatched) "j \<notin> Vs (ranking (weighted_linorder_from_keys L v g Y) (G \<setminus> {i}) \<pi>)" |
(has_threshold) "j \<in> Vs (ranking (weighted_linorder_from_keys L v g Y) (G \<setminus> {i}) \<pi>) \<and> 1 - v ?i' * (1 - g (Y ?i')) / v i > exp(-1)" |
(no_threshold) "j \<in> Vs (ranking (weighted_linorder_from_keys L v g Y) (G \<setminus> {i}) \<pi>) \<and> 1 - v ?i' * (1 - g (Y ?i')) / v i \<le> exp(-1)"
by linarith
then show ?thesis
proof cases
case has_threshold
with exp_gt_zero have "0 < 1 - v ?i' * (1 - g (Y ?i')) / v i"
using order_less_trans by blast
with has_threshold assms show ?thesis
by (auto simp: y\<^sub>c_def Let_def
dest: gt_exp_minus_One_ln_gt_minus_One the_ranking_match_remove_left
intro!: divide_nonneg_pos mult_nonneg_nonneg weights_pos)
qed (simp_all add: y\<^sub>c_def)
qed
\<comment> \<open>Lemma 2 from DJK\<close>
lemma dominance:
assumes "linorder_on L (weighted_linorder_from_keys L v g Y)"
assumes "i \<in> L" "j \<in> R"
assumes "{i,j} \<in> G"
assumes "0 \<le> Y i" "Y i < y\<^sub>c Y \<pi> i j"
shows "i \<in> Vs (ranking (weighted_linorder_from_keys L v g Y) G \<pi>)"
proof (intro dominance_order[where j = j], goal_cases)
case 6
assume "j \<in> Vs (ranking (weighted_linorder_from_keys L v g Y) (G \<setminus> {i}) \<pi>)" (is "j \<in> Vs ?M'")
have "?M' \<subseteq> G \<setminus> {i}"
by (intro ranking_subgraph) (auto dest: remove_vertices_subgraph')
with graph_abs_axioms have "graph_abs ?M'"
by (auto intro: graph_abs_subgraph graph_abs_remove_vertices)
with \<open>j \<in> Vs ?M'\<close> obtain i' where "{i',j} \<in> ?M'"
by (auto elim: graph_abs_vertex_edgeE')
then have the_i': "(THE i'. {i',j} \<in> ?M') = i'"
by (intro the_match matching_ranking)
(auto dest: remove_vertices_subgraph')
show ?case
proof (cases "1 - v i' * (1 - g (Y i')) / v i > exp(-1)")
case True
from \<open>j \<in> R\<close> \<open>j \<in> Vs ?M'\<close> have the_i'_L: "(THE i'. {i',j} \<in> ?M') \<in> L"
by (auto intro!: the_ranking_match_left dest: remove_vertices_subgraph')
from exp_gt_zero have "exp (- 1) < 1 - v i' * (1 - exp (Y i' - 1)) / v i \<Longrightarrow> 0 < (1 - v i' * (1 - exp (Y i' - 1)) / v i)"
using order_less_trans by blast
with True \<open>j \<in> Vs ?M'\<close> \<open>i \<in> L\<close> have "v i' * (1 - g (Y i')) = v i * (1 - g (y\<^sub>c Y \<pi> i j))"
unfolding y\<^sub>c_def
by (auto simp: Let_def the_i' dest: weights_pos)
also from weights_pos \<open>i \<in> L\<close> \<open>Y i < y\<^sub>c Y \<pi> i j\<close> have "\<dots> < v i * (1 - g (Y i))"
by auto
finally show ?thesis
using the_i'_L \<open>i \<in> L\<close>
by (intro weighted_linorder_from_keys_lessI) (auto simp: the_i')
next
case False
with assms \<open>j \<in> Vs ?M'\<close> show ?thesis
by (auto simp: y\<^sub>c_def the_i' split: if_splits)
qed
qed (use assms in auto)
\<comment> \<open>Lemma 3 from DJK\<close>
lemma monotonicity:
assumes linorder: "linorder_on L (weighted_linorder_from_keys L v g Y)"
assumes "Y \<in> L \<rightarrow> {0..1}"
assumes "i \<in> L" and "j \<in> R"
assumes "{i, j} \<in> G"
shows "dual_sol Y (ranking (weighted_linorder_from_keys L v g Y) G \<pi>) $ Vs_enum j \<ge> v i * (1 - g (y\<^sub>c Y \<pi> i j)) / F"
(is "dual_sol Y ?M $ ?j \<ge> ?\<beta>")
proof (cases "j \<in> Vs (ranking (weighted_linorder_from_keys L v g Y) (G \<setminus> {i}) \<pi>)")
case True
note j_matched' = this
let ?M' = "ranking (weighted_linorder_from_keys L v g Y) (G \<setminus> {i}) \<pi>"
from \<open>{i,j} \<in> G\<close> \<open>j \<in> R\<close> have index_j: "?j < n" "\<not> ?j < card L"
by (auto intro: Vs_enum_less_n dest: edges_are_Vs, simp add: Vs_enum_R)
from assms True perm have j_matched: "j \<in> Vs ?M"
by (auto intro: online_matched_mono)
have bipartite_M: "bipartite ?M L R" and bipartite_M': "bipartite ?M' L R"
by (auto intro!: bipartite_ranking dest: remove_vertices_subgraph')
with j_matched True obtain i' i'' where edges: "{i',j} \<in> ?M" "{i'',j} \<in> ?M'"
by (meson finite_L finite_R finite_parts_bipartite_graph_abs graph_abs_vertex_edgeE')
with bipartite_M bipartite_M' \<open>j \<in> R\<close> have i_left: "i' \<in> L" "i'' \<in> L"
by (auto dest: bipartite_edgeD)
have "matching ?M" and "matching ?M'"
by (auto intro!: matching_ranking dest: remove_vertices_subgraph')
with \<open>{i',j} \<in> ?M\<close> \<open>{i'',j} \<in> ?M'\<close> have the_i': "(THE i. {i,j} \<in> ?M) = i'" and the_i'': "(THE i'. {i',j} \<in> ?M') = i''"
by (auto intro: the_match)
from linorder perm edges \<open>{i,j} \<in> G\<close> \<open>i \<in> L\<close> \<open>j \<in> R\<close> have "(i',i'') \<in> weighted_linorder_from_keys L v g Y"
by (intro monotonicity_order_matched_matched) (auto dest: permutations_of_setD)
then have *: "v i' * (1 - g (Y i')) \<ge> v i'' * (1 - g (Y i''))"
unfolding weighted_linorder_from_keys_def
by simp
show ?thesis
proof (cases "1 - v i'' * (1 - g (Y i'')) / v i > exp(-1)")
case True
with exp_gt_zero have "0 < 1 - v i'' * (1 - exp (Y i'' - 1)) / v i"
using order_less_trans by blast
with * True j_matched j_matched' index_j \<open>j \<in> R\<close> \<open>i \<in> L\<close> show ?thesis
unfolding y\<^sub>c_def dual_sol_def
by (auto simp: the_i' the_i'' dest: weights_pos)
next
case False
with * j_matched j_matched' index_j \<open>j \<in> R\<close> \<open>i \<in> L\<close> show ?thesis
unfolding y\<^sub>c_def dual_sol_def
apply (auto simp: Let_def the_i' the_i'' dest!: leI weights_pos)
by (smt (z3) assms(3) divide_nonpos_nonneg divide_pos_pos exp_less_one_iff ln_div ln_less_cancel_iff weight_nonnegI)
qed
next
case False
note j_unmatched' = this
from \<open>{i,j} \<in> G\<close> \<open>j \<in> R\<close> have index_j: "?j < n" "\<not> ?j < card L"
by (auto intro: Vs_enum_less_n dest: edges_are_Vs, simp add: Vs_enum_R)
show ?thesis
proof (cases "j \<in> Vs ?M")
case True
with \<open>j \<in> R\<close> have "(THE l. {l, j} \<in> ranking (weighted_linorder_from_keys L v g Y) G \<pi>) \<in> L"
by (intro the_ranking_match_left) auto
with True j_unmatched' index_j \<open>{i,j} \<in> G\<close> \<open>Y \<in> L \<rightarrow> {0..1}\<close> \<open>i \<in> L\<close> \<open>j \<in> R\<close> show ?thesis
unfolding y\<^sub>c_def dual_sol_def
by (auto intro!: mult_nonneg_nonneg)
next
case False
with j_unmatched' index_j \<open>{i,j} \<in> G\<close> show ?thesis
unfolding y\<^sub>c_def dual_sol_def
by (auto dest: edges_are_Vs)
qed
qed
lemma ranking_measurable':
assumes "H \<subseteq> G"
assumes "set js \<subseteq> R"
shows "(\<lambda>Y. ranking (weighted_linorder_from_keys L v g Y) H js) \<in> \<Y> \<rightarrow>\<^sub>M count_space {M. M \<subseteq> G}"
proof (rule measurable_compose[of "weighted_linorder_from_keys L v g" _ "count_space (preorders_on L)"], goal_cases)
case 1
from finite_L show ?case
by measurable
next
case 2
from finite_subsets \<open>set js \<subseteq> R\<close> \<open>H \<subseteq> G\<close> show ?case
by (auto dest: ranking_subgraph' preorders_onD)
qed
lemma ranking_measurable_remove_vertices:
assumes "set js \<subseteq> R"
shows "(\<lambda>Y. ranking (weighted_linorder_from_keys (L - X) v g Y) (G \<setminus> X) js) \<in> (\<Pi>\<^sub>M i \<in> L - X. \<U>) \<rightarrow>\<^sub>M count_space {M. M \<subseteq> G}"
proof (rule measurable_compose[of "weighted_linorder_from_keys (L - X) v g" _ "count_space (preorders_on (L - X))"], goal_cases)
case 1
from finite_L have "finite (L - X)" by blast
then show ?case
by measurable
next
case 2
from \<open>set js \<subseteq> R\<close> have "preorder_on (L - X) r \<Longrightarrow> ranking r (G \<setminus> X) js \<subseteq> G \<setminus> X" for r
by (intro Ranking_Order.ranking_subgraph) auto
with finite_subsets finite_vs show ?case
by (auto dest: preorders_onD remove_vertices_subgraph')
qed
lemmas ranking_measurable = ranking_measurable'[OF subset_refl]
lemma ranking_measurable_fun_upd:
assumes "i \<in> L"
assumes "set js \<subseteq> R"
assumes "Y \<in> space (\<Pi>\<^sub>M i \<in> L - {i}. \<U>)"
shows "(\<lambda>y. ranking (weighted_linorder_from_keys L v g (Y(i:=y))) G js) \<in> \<U> \<rightarrow>\<^sub>M count_space {M. M \<subseteq> G}"
by (rule measurable_compose[OF measurable_fun_upd[where I = L and J = "L - {i}" and M = "\<lambda>_. \<U>"]])
(use assms in \<open>auto intro: ranking_measurable\<close>)
lemma in_vertices_borel_measurable_count_space:
"(\<lambda>M. i \<in> Vs M) \<in> borel_measurable (count_space {M. M \<subseteq> G})"
by measurable
lemma in_vertices_Measurable_pred_count_space:
"Measurable.pred (count_space {M. M \<subseteq> G}) (\<lambda>M. i \<in> Vs M)"
by measurable
lemmas in_vertices_borel_measurable[measurable] = measurable_compose[OF ranking_measurable' in_vertices_borel_measurable_count_space]
lemmas in_vertices_Measurable_pred[measurable] = measurable_compose[OF ranking_measurable' in_vertices_Measurable_pred_count_space]
lemmas in_vertices_borel_measurable_remove_vertices[measurable] = measurable_compose[OF ranking_measurable_remove_vertices in_vertices_borel_measurable_count_space]
lemmas in_vertices_Measurable_pred_remove_vertices[measurable] = measurable_compose[OF ranking_measurable_remove_vertices in_vertices_Measurable_pred_count_space]
lemmas in_vertices_borel_measurable_fun_upd[measurable] = measurable_compose[OF ranking_measurable_fun_upd in_vertices_borel_measurable_count_space]
lemmas in_vertices_Measurable_pred_fun_upd[measurable] = measurable_compose[OF ranking_measurable_fun_upd in_vertices_Measurable_pred_count_space]
lemma ranking_prob_distr:
"ranking_prob = distr \<Y> (count_space {M. M \<subseteq> G}) (\<lambda>Y. ranking (weighted_linorder_from_keys L v g Y) G \<pi>)"
unfolding ranking_prob_def
using ranking_measurable
by (auto simp: bind_return_distr')
sublocale ranking_prob_space: prob_space ranking_prob
by (auto simp: ranking_prob_distr intro!: prob_space_distr intro: ranking_measurable)
lemma online_matched_with_borel_iff:
fixes Y :: "'a \<Rightarrow> real" and X :: "'a set"
defines "r \<equiv> weighted_linorder_from_keys (L - X) v g Y"
assumes "j \<in> R" "A \<in> sets borel"
\<comment> \<open>should we lift this assumption (since it is always true)? would need to use \<^term>\<open>takeWhile (\<lambda>x. x \<noteq> j)\<close>
and \<^term>\<open>dropWhile\<close> in statement\<close>
assumes \<pi>_decomp: "\<pi> = \<pi>' @ j # \<pi>''"
defines "M' \<equiv> ranking r (G \<setminus> X) \<pi>'"
shows "j \<in> Vs (ranking r (G \<setminus> X) \<pi>) \<and> v (THE i. {i,j} \<in> ranking r (G \<setminus> X) \<pi>) * (1 - g(Y (THE i. {i,j} \<in> ranking r (G \<setminus> X) \<pi>))) \<in> A
\<longleftrightarrow> (\<exists>i\<in>{i. {i,j} \<in> G \<setminus> X}. i \<notin> Vs M' \<and> v i * (1 - g(Y i)) \<in> A \<and>
(\<forall>i'\<in>{i. {i,j} \<in> G \<setminus> X}. i' \<notin> Vs M' \<longrightarrow> v i * (1 - g(Y i)) \<ge> v i' * (1 - g(Y i'))))"
(is "j \<in> Vs ?M \<and> ?w (THE i. {i,j} \<in> ?M) \<in> A \<longleftrightarrow> ?F")
proof
assume j_matched: "j \<in> Vs ?M \<and> ?w (THE i. {i,j} \<in> ?M) \<in> A"
let ?i = "min_on_rel {i. i \<notin> Vs M' \<and> {i,j} \<in> G \<setminus> X} r"
from \<pi>_decomp have "?M = ranking' r (G \<setminus> X) M' (j#\<pi>'')"
unfolding M'_def
by (simp add: ranking_append)
from \<pi>_decomp \<open>j \<in> R\<close> perm have "j \<notin> Vs M'"
unfolding M'_def r_def
by (intro unmatched_R_in_ranking_if ballI preorder_on_neighborsI_remove_vertices)
(auto dest: permutations_of_setD remove_vertices_subgraph')
have neighbor_ex: "\<exists>i\<in>{i. {i,j} \<in> G \<setminus> X}. i \<notin> Vs M'" (is "?Ex")
proof (rule ccontr)
assume "\<not> ?Ex"
then have step_unchanged: "step r (G \<setminus> X) M' j = M'"
by (auto simp: step_def)
with \<pi>_decomp have M: "?M = ranking' r (G \<setminus> X) M' \<pi>''"
unfolding ranking'_def M'_def
by simp
from \<pi>_decomp \<open>j \<in> R\<close> \<open>j \<notin> Vs M'\<close> perm step_unchanged have "j \<notin> Vs ?M"
by (subst M, intro unmatched_R_in_ranking_if ballI preorder_on_neighborsI_remove_vertices)
(auto dest: permutations_of_setD remove_vertices_subgraph' simp: r_def)
with j_matched show False
by blast
qed
with \<open>j \<notin> Vs M'\<close> have step_eq: "step r (G \<setminus> X) M' j = insert {?i, j} M'"
by (auto simp add: step_def)
from neighbor_ex \<open>j \<in> R\<close> bipartite_graph have i_unmatched: "?i \<in> {i. i \<notin> Vs M' \<and> {i,j} \<in> G \<setminus> X}"
by (intro min_if_finite preorder_on'_subset[where S = "L - X" and T = "{i. i \<notin> Vs M' \<and> {i,j} \<in> G \<setminus> X}"] finite_unmatched_neighbors)
(auto simp: r_def intro: preorder_on_imp_preorder_on' dest: bipartite_edgeD remove_vertices_subgraph' edges_are_Vs remove_vertices_not_vs')
from neighbor_ex \<open>j \<in> R\<close> bipartite_graph have i_min:
"\<not>(\<exists>i'\<in>{i. i \<notin> Vs M' \<and> {i,j} \<in> G \<setminus> X}. (i',?i) \<in> r \<and> (?i,i') \<notin> r)"
by (intro min_if_finite preorder_on'_subset[where S = "L - X" and T = "{i. i \<notin> Vs M' \<and> {i,j} \<in> G \<setminus> X}"] finite_unmatched_neighbors)
(auto simp: r_def intro: preorder_on_imp_preorder_on' dest: bipartite_edgeD remove_vertices_subgraph' edges_are_Vs remove_vertices_not_vs')
have the_i: "(THE i. {i,j} \<in> ?M) = ?i"
proof (intro the_match matching_ranking, goal_cases)
case 4
from \<pi>_decomp step_eq show ?case
by (auto simp add: ranking_append ranking_Cons M'_def intro: ranking_mono)
qed (use finite_vs in \<open>auto simp: r_def\<close>)
show ?F
proof (intro bexI[of _ ?i] conjI ballI impI, goal_cases)
case (3 i')
show ?case
proof (rule ccontr, simp add: not_le)
assume "?w ?i < ?w i'"
with 3 i_unmatched \<open>j \<in> R\<close> have "(i',?i) \<in> r \<and> (?i,i') \<notin> r"
unfolding r_def weighted_linorder_from_keys_def
by (auto dest: neighbors_right_subset_left_remove_vertices)
with 3 i_min show False
by blast
qed
qed (use i_unmatched j_matched in \<open>simp_all add: the_i\<close>)
next
assume eligible_neighbor: ?F
let ?ns = "{i. i \<notin> Vs M' \<and> {i,j} \<in> G \<setminus> X}"
from eligible_neighbor obtain i where
i_eligible: "i \<notin> Vs M'" "{i,j} \<in> G \<setminus> X" and
w_i: "?w i \<in> A" and
i_min_on_r: "\<forall>i'\<in>?ns. ?w i \<ge> ?w i'"
by auto
from \<pi>_decomp have "?M = ranking' r (G \<setminus> X) M' (j#\<pi>'')"
unfolding ranking'_def M'_def
by simp
from \<pi>_decomp \<open>j \<in> R\<close> perm have j_unmatched_before: "j \<notin> Vs M'"
unfolding M'_def r_def
by (intro unmatched_R_in_ranking_if ballI preorder_on_neighborsI_remove_vertices)
(auto dest: permutations_of_setD remove_vertices_subgraph')
let ?min = "min_on_rel ?ns r"
from j_unmatched_before i_eligible have step_eq: "step r (G \<setminus> X) M' j = insert {?min, j} M'"
unfolding step_def
by auto
with finite_vs perm \<pi>_decomp \<open>j \<in> R\<close> have the_i_step: "(THE i. {i,j} \<in> step r (G \<setminus> X) M' j) = ?min"
unfolding M'_def
by (intro the_match matching_step matching_ranking ballI preorder_on_neighborsI_remove_vertices)
(auto simp: r_def dest: permutations_of_setD)
from \<open>j \<in> R\<close> bipartite_graph i_eligible have min_unmatched: "?min \<in> {i. i \<notin> Vs M' \<and> {i,j} \<in> G \<setminus> X}"
unfolding r_def
by (intro min_if_finite preorder_on'_subset[where S = "L - X" and T = "{i. i \<notin> Vs M' \<and> {i,j} \<in> G \<setminus> X}"] preorder_on_imp_preorder_on' finite_unmatched_neighbors)
(auto dest: bipartite_edgeD neighbors_right_subset_left_remove_vertices remove_vertices_subgraph')
from \<open>j \<in> R\<close> bipartite_graph i_eligible have min_is_min: "\<not>(\<exists>x \<in> ?ns. (x,?min) \<in> r \<and> (?min, x) \<notin> r)"
unfolding r_def
by (intro min_if_finite preorder_on'_subset[where S = "L - X" and T = "{i. i \<notin> Vs M' \<and> {i,j} \<in> G \<setminus> X}"] preorder_on_imp_preorder_on' finite_unmatched_neighbors)
(auto dest: bipartite_edgeD neighbors_right_subset_left_remove_vertices remove_vertices_subgraph')
have w_min: "?w ?min = ?w i"
proof (rule ccontr)
assume "?w ?min \<noteq> ?w i"
then consider "?w i < ?w ?min" | "?w ?min < ?w i"
by linarith
then show False
proof cases
case 1
with min_unmatched i_min_on_r show ?thesis
by auto
next
case 2
with \<open>{i,j} \<in> G \<setminus> X\<close> \<open>j \<in> R\<close> bipartite_graph min_unmatched have "(i, ?min) \<in> r" "(?min, i) \<notin> r"
unfolding r_def weighted_linorder_from_keys_def
by (auto dest: bipartite_edgeD remove_vertices_subgraph' neighbors_right_subset_left_remove_vertices)
with min_is_min i_eligible show ?thesis
by blast
qed
qed
show "j \<in> Vs ?M \<and> ?w (THE i. {i,j} \<in> ?M) \<in> A"
proof (intro conjI, goal_cases)
case 1
from \<pi>_decomp step_eq show ?case
unfolding M'_def
by (auto simp: ranking_append ranking_Cons vs_insert intro: ranking_mono_vs)
next
case 2
from finite_vs perm \<pi>_decomp step_eq \<open>j \<in> R\<close> have "(THE i. {i,j} \<in> ranking r (G \<setminus> X) \<pi>) = ?min"
unfolding M'_def
by (intro the_match matching_step matching_ranking ballI preorder_on_neighborsI_remove_vertices)
(auto intro: ranking_mono dest: permutations_of_setD simp: r_def ranking_append ranking_Cons)
with w_min w_i show ?case
by simp
qed
qed
lemma dual_component_online_in_sets:
assumes "j \<in> R"
assumes "A \<in> sets (borel::real measure)"
shows "{Y \<in> space (\<Pi>\<^sub>M i \<in> L - X. \<U>). j \<in> Vs (ranking (weighted_linorder_from_keys (L - X) v g Y) (G \<setminus> X) \<pi>) \<and>
v (THE l. {l, j} \<in> ranking (weighted_linorder_from_keys (L - X) v g Y) (G \<setminus> X) \<pi>) *
(1 - g(Y (THE l. {l, j} \<in> ranking (weighted_linorder_from_keys (L - X) v g Y) (G \<setminus> X) \<pi>))) \<in> A}
\<in> sets (\<Pi>\<^sub>M i \<in> L - X. \<U>)"
proof -
from \<open>j \<in> R\<close> perm obtain pre suff where \<pi>_decomp: "\<pi> = pre @ j # suff"
by (auto dest: split_list simp flip: set_\<pi>)
with set_\<pi> have set_pre: "set pre \<subseteq> R"
by auto
show ?thesis
proof (intro predE, subst online_matched_with_borel_iff[OF assms \<pi>_decomp], intro pred_intros_finite pred_intros_logic, goal_cases)
case (2 i)
with set_pre show ?case
by measurable
next
case (3 i)
with \<open>A \<in> sets borel\<close> show ?case
by measurable
(use 3 \<open>j \<in> R\<close> in \<open>auto dest: neighbors_right_subset_left_remove_vertices\<close>)
next
case (5 i i')
with set_pre show ?case
by measurable
next
case (6 i i')
with \<open>j \<in> R\<close> have "i \<in> L - X" "i' \<in> L - X"
by (auto dest: neighbors_right_subset_left_remove_vertices)
then show ?case
by measurable
qed (intro remove_vertices_subgraph finite_neighbors)+
qed
lemma dual_component_online_borel_measurable:
assumes "j \<in> R"
shows "(\<lambda>Y. v (THE l. {l,j} \<in> ranking (weighted_linorder_from_keys (L - X) v g Y) (G \<setminus> X) \<pi>) *
(1 - g(Y (THE l. {l, j} \<in> ranking (weighted_linorder_from_keys (L - X) v g Y) (G \<setminus> X) \<pi>))))
\<in> borel_measurable (restrict_space (\<Pi>\<^sub>M i \<in> L - X. \<U>) {Y. j \<in> Vs (ranking (weighted_linorder_from_keys (L - X) v g Y) (G \<setminus> X) \<pi>)})"
proof (rule measurableI, goal_cases)
case (2 A)
show ?case
proof (simp add: space_restrict_space sets_restrict_space image_def vimage_def Int_def,
rule bexI[of _ "{Y \<in> space (\<Pi>\<^sub>M i \<in> L - X. \<U>). j \<in> Vs (ranking (weighted_linorder_from_keys (L - X) v g Y) (G \<setminus> X) \<pi>) \<and>
v (THE l. {l,j} \<in> ranking (weighted_linorder_from_keys (L - X) v g Y) (G \<setminus> X) \<pi>) *
(1 - g(Y (THE l. {l,j} \<in> ranking (weighted_linorder_from_keys (L - X) v g Y) (G \<setminus> X) \<pi>))) \<in> A}"], goal_cases)
case 2
from \<open>j \<in> R\<close> \<open>A \<in> sets borel\<close> show ?case
by (rule dual_component_online_in_sets)
qed blast
qed simp
lemma measurable_dual_component_remove_vertices[measurable]:
assumes "k < n"
assumes "k < card L \<Longrightarrow> from_nat_into L k \<notin> X"
shows "(\<lambda>Y. dual_sol Y (ranking (weighted_linorder_from_keys (L - X) v g Y) (G \<setminus> X) \<pi>) $ k) \<in> borel_measurable (\<Pi>\<^sub>M i \<in> L - X. \<U>)"
unfolding dual_sol_def
proof (subst index_vec[OF \<open>k < n\<close>], subst measurable_If_restrict_space_iff, goal_cases)
case 2
then show ?case
proof (rule conjI, subst measurable_If_restrict_space_iff; (intro conjI | simp), goal_cases)
case 1
show ?case
proof (auto, rule measurable_restrict_space1, goal_cases)
case 1
show ?case
by measurable (use \<open>k < card L\<close> assms in \<open>auto intro: from_nat_into simp: Vs_enum_inv_from_nat_into_L\<close>)
qed
next
case 2
show ?case
by (simp, intro impI borel_measurable_divide borel_measurable_const dual_component_online_borel_measurable)
(use \<open>k < n\<close> in \<open>auto elim: Vs_enum_inv_rightE\<close>)
qed
qed measurable
lemmas measurable_dual_component = measurable_dual_component_remove_vertices[where X = "{}", simplified]
lemma measurable_dual_component_split_dim:
assumes "i \<in> L"
assumes "k < n"
shows "(\<lambda>(y,Y). dual_sol (Y(i := y)) (ranking (weighted_linorder_from_keys L v g (Y(i := y))) G \<pi>) $ k) \<in> borel_measurable (\<U> \<Otimes>\<^sub>M (\<Pi>\<^sub>M i \<in> L - {i}. \<U>))"
using measurable_compose[OF measurable_add_dim' measurable_dual_component] assms
by (auto simp: case_prod_beta)
lemma measurable_dual_component_fun_upd:
assumes "i \<in> L"
assumes "Y \<in> space (\<Pi>\<^sub>M i \<in> L - {i}. \<U>)"
assumes "k < n"
shows "(\<lambda>y. dual_sol (Y(i:=y)) (ranking (weighted_linorder_from_keys L v g (Y(i:=y))) G \<pi>) $ k) \<in> borel_measurable \<U>"
by (rule measurable_compose[OF _ measurable_dual_component])
(use assms in measurable)
lemma measurable_y\<^sub>c[measurable]: "j \<in> R \<Longrightarrow> (\<lambda>Y. y\<^sub>c Y \<pi> i j) \<in> borel_measurable (\<Pi>\<^sub>M i \<in> L - {i}. \<U>)"
proof (unfold y\<^sub>c_def, subst measurable_If_restrict_space_iff, subst ranking_Restr_to_vertices[symmetric], goal_cases)
case 2
then show ?case
by (subst weighted_linorder_from_keys_Restr) measurable
next
case 3
have "set \<pi> \<subseteq> R"
by simp
then have *: "(THE i'. {i', j} \<in> ranking (weighted_linorder_from_keys L v g Y) (G \<setminus> {i}) \<pi>) =
(THE i'. {i',j} \<in> ranking (weighted_linorder_from_keys (L - {i}) v g Y) (G \<setminus> {i}) \<pi>)" for Y
by (subst ranking_Restr_to_vertices[symmetric])
(auto intro: preorder_on_imp_preorder_on' simp: weighted_linorder_from_keys_Restr)
from \<open>set \<pi> \<subseteq> R\<close> have **: "restrict_space (\<Pi>\<^sub>M i \<in> L - {i}. \<U>) {Y. j \<in> Vs (ranking (weighted_linorder_from_keys L v g Y) (G \<setminus> {i}) \<pi>)} =
restrict_space (\<Pi>\<^sub>M i \<in> L - {i}. \<U>) {Y. j \<in> Vs (ranking (weighted_linorder_from_keys (L - {i}) v g Y) (G \<setminus> {i}) \<pi>)}"
by (subst ranking_Restr_to_vertices[symmetric])
(auto intro: preorder_on_imp_preorder_on' simp: weighted_linorder_from_keys_Restr)
show ?case
proof (intro conjI borel_measurable_const, unfold Let_def, subst measurable_If_restrict_space_iff, goal_cases)
case 1
from \<open>j \<in> R\<close> show ?case
by (intro predE pred_const_less[where N = borel] borel_measurable_diff borel_measurable_const borel_measurable_divide, simp_all add: * **)
(rule dual_component_online_borel_measurable)
next
case 2
show ?case
by (intro conjI borel_measurable_const borel_measurable_add borel_measurable_ln borel_measurable_diff borel_measurable_divide, rule measurable_restrict_space1)
(use \<open>j \<in> R\<close> in \<open>auto simp: * ** intro: dual_component_online_borel_measurable\<close>)
qed
qed auto
lemma dual_sol_funcset:
assumes Y_nonneg: "\<And>i. i \<in> L - X \<Longrightarrow> 0 \<le> Y i"
assumes Y_less_eq_One: "\<And>i. i \<in> L - X \<Longrightarrow> Y i \<le> 1"
shows "($) (dual_sol Y (ranking (weighted_linorder_from_keys (L - X) v g Y) (G \<setminus> X) \<pi>)) \<in> {..<n} \<rightarrow> {0..max_weight/F}"
proof (intro funcsetI)
fix i
assume "i \<in> {..<n}"
then have "i < n"
by blast
let ?ranking = "ranking (weighted_linorder_from_keys (L - X) v g Y) (G \<setminus> X) \<pi>"
have "?ranking \<subseteq> G \<setminus> X"
by (intro Ranking_Order.ranking_subgraph) auto
then have matched_not_X: "j \<in> Vs ?ranking \<Longrightarrow> j \<notin> X" for j
by (auto dest!: Vs_subset dest: remove_vertices_not_vs')
from \<open>i < n\<close> show "dual_sol Y ?ranking $ i \<in> {0..max_weight / F}"
proof (cases rule: i_cases)
case 1
with \<open>i < n\<close> weights_pos show ?thesis
unfolding dual_sol_def
by (auto intro: g_less_eq_OneI assms intro!: mult_nonneg_nonneg scaled_weight_le_max_weight
dest: matched_not_X elim: Vs_enum_inv_leftE)
next
case 2
with \<open>i < n\<close> have "Vs_enum_inv i \<in> Vs ?ranking \<Longrightarrow> (THE i'. {i', Vs_enum_inv i} \<in> ?ranking) \<in> L"
"Vs_enum_inv i \<in> Vs ?ranking \<Longrightarrow> {(THE i'. {i', Vs_enum_inv i} \<in> ?ranking), Vs_enum_inv i} \<in> ?ranking"
by (auto intro!: the_ranking_match_left dest: remove_vertices_subgraph' elim: Vs_enum_inv_rightE)
with 2 \<open>i < n\<close> show ?thesis
unfolding dual_sol_def
by (auto intro!: mult_nonneg_nonneg scaled_weight_le_max_weight
simp: Y_less_eq_One matched_not_X edges_are_Vs)
qed
qed
lemma dual_sol_funcset_if_funcset:
shows "Y \<in> (L - X) \<rightarrow> {0..1} \<Longrightarrow> ($) (dual_sol Y (ranking (weighted_linorder_from_keys (L - X) v g Y) (G \<setminus> X) \<pi>)) \<in> {..<n} \<rightarrow> {0..max_weight/F}"
by (intro dual_sol_funcset) auto
lemma AE_dual_sol_funcset:
shows "AE Y in \<Pi>\<^sub>M i \<in> L - X. \<U>. ($) (dual_sol Y (ranking (weighted_linorder_from_keys (L - X) v g Y) (G \<setminus> X) \<pi>)) \<in> {..<n} \<rightarrow> {0..max_weight/F}"
using AE_PiM_subset_L_\<U>_funcset[OF Diff_subset]
by eventually_elim
(auto dest: dual_sol_funcset_if_funcset)
lemma AE_dual_sol_split_dim_funcset:
shows "AE (y, Y) in \<U> \<Otimes>\<^sub>M (\<Pi>\<^sub>M i \<in> L - {i}. \<U>). ($) (dual_sol (Y(i:=y)) (ranking (weighted_linorder_from_keys L v g (Y(i:=y))) G \<pi>)) \<in> {..<n} \<rightarrow> {0..max_weight/F}"
using AE_split_dim_funcset
by eventually_elim
(auto dest: dual_sol_funcset_if_funcset[where X = "{}", simplified])
lemma AE_dual_sol_\<U>_funcset:
assumes "Y \<in> L - {i} \<rightarrow> {0..1}"
shows "AE y in \<U>. ($) (dual_sol (Y(i:=y)) (ranking (weighted_linorder_from_keys L v g (Y(i:=y))) G \<pi>)) \<in> {..<n} \<rightarrow> {0..max_weight/F}"
using AE_\<U>_in_range
by eventually_elim
(use assms in \<open>intro dual_sol_funcset_if_funcset[where X = "{}", simplified] funcset_update\<close>)
lemma integrable_g[simp]: "integrable \<U> g"
proof (intro integrableI_real_bounded)
have "\<integral>\<^sup>+ y. g y \<partial>\<U> \<le> 1"
using AE_\<U>_in_range
by (auto intro: component_prob_space.nn_integral_le_const)
then show "\<integral>\<^sup>+ y. g y \<partial>\<U> < \<infinity>"
by (simp add: order_le_less_trans)
qed auto
lemma integrable_dual_component_remove_vertices:
assumes "i < n"
assumes "i < card L \<Longrightarrow> from_nat_into L i \<notin> X"
shows "integrable (\<Pi>\<^sub>M i \<in> L - X. \<U>) (\<lambda>Y. dual_sol Y (ranking (weighted_linorder_from_keys (L - X) v g Y) (G \<setminus> X) \<pi>) $ i)"
using assms
proof (intro integrableI_nonneg measurable_dual_component, goal_cases)
case 2
show ?case
using AE_dual_sol_funcset
by eventually_elim
(use 2 in auto)
next
case 3
have "\<integral>\<^sup>+ Y. ennreal (dual_sol Y (ranking (weighted_linorder_from_keys (L - X) v g Y) (G \<setminus> X) \<pi>) $ i) \<partial>\<Pi>\<^sub>M i \<in> L - X. \<U> \<le> max_weight/F"
by (intro subprob_space.nn_integral_le_const prob_space_imp_subprob_space prob_space_PiM_\<U> eventually_mono[OF AE_dual_sol_funcset])
(use 3 in auto)
then show ?case
by (simp add: order_le_less_trans)
qed measurable
lemmas integrable_dual_component = integrable_dual_component_remove_vertices[where X = "{}", simplified]
lemma integrable_dual_component_split_dim:
assumes "i \<in> L"
assumes "j < n"
shows "integrable (\<U> \<Otimes>\<^sub>M (\<Pi>\<^sub>M i \<in> L - {i}. \<U>)) (\<lambda>(y,Y). dual_sol (Y(i := y)) (ranking (weighted_linorder_from_keys L v g (Y(i := y))) G \<pi>) $ j)"
using assms
proof (intro integrableI_nonneg measurable_dual_component_split_dim, goal_cases)
case 3
show ?case
using AE_dual_sol_split_dim_funcset
by (eventually_elim, use 3 in auto)
next
case 4
interpret split_dim_prob_space: prob_space "(\<U> \<Otimes>\<^sub>M (\<Pi>\<^sub>M i \<in> L - {i}. \<U>))"
by (intro prob_space_pair prob_space_PiM) blast+
have "\<integral>\<^sup>+ (y,Y). ennreal (dual_sol (Y(i := y)) (ranking (weighted_linorder_from_keys L v g (Y(i := y))) G \<pi>) $ j) \<partial>(\<U> \<Otimes>\<^sub>M (\<Pi>\<^sub>M i \<in> L - {i}. \<U>)) \<le> max_weight/F"
by (intro split_dim_prob_space.nn_integral_le_const eventually_mono[OF AE_dual_sol_split_dim_funcset])
(use 4 in auto)
then show ?case
by (subst case_prod_beta, subst split_comp_eq)
(simp add: order_le_less_trans)
qed
lemma integrable_dual_component_\<U>:
assumes "Y \<in> space (\<Pi>\<^sub>M i \<in> L - {i}. \<U>)"
assumes Y_funcset: "Y \<in> L - {i} \<rightarrow> {0..1}"
assumes "i \<in> L"
assumes "k < n"
shows "integrable \<U> (\<lambda>y. dual_sol (Y(i:=y)) (ranking (weighted_linorder_from_keys L v g(Y(i:=y))) G \<pi>) $ k)"
proof (intro integrableI_real_bounded measurable_dual_component_fun_upd, goal_cases)
case 4
show ?case
using AE_dual_sol_\<U>_funcset[OF Y_funcset]
by (eventually_elim) (use \<open>k < n\<close> in auto)
next
case 5
from Y_funcset \<open>k < n\<close> have "\<integral>\<^sup>+y. dual_sol (Y(i:=y)) (ranking (weighted_linorder_from_keys L v g (Y(i:=y))) G \<pi>) $ k \<partial>\<U> \<le> max_weight/F"
by (auto intro!: subprob_space.nn_integral_le_const prob_space_imp_subprob_space eventually_mono[OF AE_dual_sol_\<U>_funcset])
then show ?case
by (simp add: order_le_less_trans)
qed (use assms in auto)
lemma integrable_integral_bound_but_i:
assumes "i \<in> L"
assumes "j \<in> R"
shows "integrable (\<Pi>\<^sub>M i \<in> L - {i}. \<U>) (\<lambda>Y. \<integral>y. g y * indicator {..<y\<^sub>c Y \<pi> i j} y \<partial>\<U> + 1 - g (y\<^sub>c Y \<pi> i j))"
proof (intro Bochner_Integration.integrable_add Bochner_Integration.integrable_diff integrableI_real_bounded component_prob_space.borel_measurable_lebesgue_integral, goal_cases)
case 1
then show ?case
proof (subst split_comp_eq[symmetric],
intro borel_measurable_times borel_measurable_const measurable_compose[where f = snd and g = g and N = \<U>] measurable_snd, goal_cases)
case 2
from \<open>j \<in> R\<close> show ?case
unfolding lessThan_def
by (intro borel_measurable_indicator' predE pred_intros_logic pred_const_le[where N = \<U>] measurable_snd borel_measurable_pred_less)
measurable
qed simp
next
case 2
with \<open>i \<in> L\<close> show ?case
by (intro eventually_mono[OF AE_PiM_subset_L_\<U>_funcset[OF Diff_subset]] integral_nonneg_AE eventually_mono[OF AE_\<U>_in_range])
(auto intro: mult_nonneg_nonneg)
next
case 3
from \<open>i \<in> L\<close> have "\<integral>\<^sup>+ Y. ennreal (\<integral>y. g y * indicator {..<y\<^sub>c Y \<pi> i j} y \<partial>\<U>) \<partial>(\<Pi>\<^sub>M i \<in> L - {i}. \<U>) \<le> 1"
by (auto intro!: subprob_space.nn_integral_le_const prob_space_imp_subprob_space prob_space_PiM_\<U>
eventually_mono[OF AE_PiM_subset_L_\<U>_funcset] integral_real_bounded
eventually_mono[OF AE_\<U>_in_range] mult_le_one component_prob_space.prob_space_axioms)
then show ?case
by (simp add: order_le_less_trans)
next
case 9
from assms have "\<integral>\<^sup>+ x. g (y\<^sub>c x \<pi> i j) \<partial>(\<Pi>\<^sub>M i \<in> L - {i}. \<U>) \<le> 1"
by (auto intro!: subprob_space.nn_integral_le_const prob_space_imp_subprob_space prob_space_PiM_\<U>
eventually_mono[OF AE_PiM_subset_L_\<U>_funcset] g_less_eq_OneI dest: y\<^sub>c_bounded)
then show ?case
by (simp add: order_le_less_trans)
qed (use \<open>j \<in> R\<close> in simp_all)
lemma weighted_eq_iff_priority_ln:
assumes "i \<in> L" "i' \<in> L"
assumes gt_zero: "0 < 1 - v i' * (1 - g y') / v i"
shows "v i * (1 - g y) = v i' * (1 - g y') \<longleftrightarrow> y = ln (1 - v i' * (1 - g y') / v i) + 1"
proof -
from assms have "v i * (1 - g y) = v i' * (1 - g y') \<longleftrightarrow> 1 - g y = v i' * (1 - g y') / v i"
by (auto dest: weights_pos simp: field_simps)
also have "\<dots> \<longleftrightarrow> g y = 1 - v i' * (1 - g y') / v i"
by auto
also from gt_zero have "\<dots> \<longleftrightarrow> y - 1 = ln (1 - v i' * (1 - g y') / v i)"
by (auto dest: ln_unique)
also have "\<dots> \<longleftrightarrow> y = ln (1 - v i' * (1 - g y') / v i) + 1"
by auto
finally show ?thesis .
qed
lemma weighted_eq_at_most_one:
assumes "i \<in> L" "i' \<in> L"
shows "{y. v i * (1 - exp (y - 1)) = v i' * (1 - exp (y' - 1))} = (
if 0 < 1 - v i' * (1 - g y') / v i
then {ln (1 - v i' * (1 - g y') / v i) + 1}
else {})"
using assms
proof (cases "0 < 1 - v i' * (1 - g y') / v i")
case True
with assms weighted_eq_iff_priority_ln show ?thesis
by auto
next
case False
with assms show ?thesis
by (auto simp: field_simps dest: weights_pos)
qed
text \<open>Adapted from Eberl's @{thm emeasure_PiM_diagonal}. Cannot use the whole calculation like in
that lemma since it blows up.\<close>
lemma emeasure_PiM_equal_weights:
assumes "L' \<subseteq> L"
assumes "x \<in> L'" "y \<in> L'" "x \<noteq> y"
shows "emeasure (\<Pi>\<^sub>M i \<in> L'. \<U>) {h\<in>L' \<rightarrow>\<^sub>E UNIV. v x * (1 - g (h x)) = v y * (1 - g (h y))} = 0"
proof -
from finite_L \<open>L' \<subseteq> L\<close> have fin: "finite L'"
by (auto intro: finite_subset)
interpret product_prob_space "\<lambda>_. \<U>" L'
unfolding product_prob_space_def product_prob_space_axioms_def product_sigma_finite_def
by (auto intro: prob_space_imp_sigma_finite)
have [measurable]: "{h\<in>extensional {x,y}. v x * (1 - g (h x)) = v y * (1 - g (h y))} \<in> sets (\<Pi>\<^sub>M i \<in> {x,y}. lborel)"
proof -
have "{h\<in>extensional {x,y}. v x * (1 - g (h x)) = v y * (1 - g (h y))} =
{h \<in> space (\<Pi>\<^sub>M i \<in> {x,y}. lborel). v x * (1 - g (h x)) = v y * (1 - g (h y))}"
by (auto simp: extensional_def space_PiM)
also have "\<dots> \<in> sets (\<Pi>\<^sub>M i \<in> {x,y}. lborel)"
by measurable
finally show ?thesis .
qed
have [simp]: "sets (\<Pi>\<^sub>M i \<in> A. \<U>) = sets (\<Pi>\<^sub>M i \<in> A. lborel)" for A :: "'a set"
by (intro sets_PiM_cong refl) simp
have 1: "{h\<in>L' \<rightarrow>\<^sub>E UNIV. v x * (1 - g (h x)) = v y * (1 - g (h y))} =
(\<lambda>h. restrict h {x, y}) -` {h\<in>extensional {x,y}. v x * (1 - g (h x)) = v y * (1 - g (h y))} \<inter> space (\<Pi>\<^sub>M i \<in> L'. \<U>)"
by (auto simp: space_PiM)
have 2: "emeasure (\<Pi>\<^sub>M i \<in> L'. \<U>) {h\<in>L' \<rightarrow>\<^sub>E UNIV. v x * (1 - g (h x)) = v y * (1 - g (h y))} =
emeasure (distr (\<Pi>\<^sub>M i \<in> L'. \<U>) (\<Pi>\<^sub>M i \<in> {x,y}. lborel)
(\<lambda>h. restrict h {x,y})) {h\<in>extensional {x,y}. v x * (1 - g (h x)) = v y * (1 - g (h y))}"
proof (subst 1, rule emeasure_distr[symmetric])
have "(\<lambda>h. restrict h {x,y}) \<in> (\<Pi>\<^sub>M i \<in> L'. lborel) \<rightarrow>\<^sub>M (\<Pi>\<^sub>M i \<in> {x,y}. lborel)"
using assms by (intro measurable_restrict_subset) auto
also have "\<dots> = (\<Pi>\<^sub>M i \<in> L'. \<U>) \<rightarrow>\<^sub>M (\<Pi>\<^sub>M i \<in> {x,y}. lborel)"
by (intro sets_PiM_cong measurable_cong_sets refl) simp_all
finally show "(\<lambda>h. restrict h {x,y}) \<in> \<dots>" .
next
show "{h\<in>extensional {x,y}. v x * (1 - g (h x)) = v y * (1 - g (h y))} \<in> sets (PiM {x,y} (\<lambda>_. lborel))"
by simp
qed
have "distr (\<Pi>\<^sub>M i \<in> L'. \<U>) (\<Pi>\<^sub>M i \<in> {x,y}. lborel) (\<lambda>h. restrict h {x,y}) =
distr (\<Pi>\<^sub>M i \<in> L'. \<U>) (\<Pi>\<^sub>M i \<in> {x,y}. \<U>) (\<lambda>h. restrict h {x,y})" (is "?distr = _")
by (intro distr_cong refl sets_PiM_cong) simp_all
also from assms fin have "\<dots> = (\<Pi>\<^sub>M i \<in> {x,y}. \<U>)"
by (intro distr_restrict[symmetric]) auto
finally have 3: "?distr = (\<Pi>\<^sub>M i \<in> {x,y}. \<U>)" .
have "emeasure \<dots> {h\<in>extensional {x,y}. v x * (1 - g (h x)) = v y * (1 - g (h y))} =
nn_integral \<dots> (\<lambda>h. indicator {h\<in>extensional {x,y}. v x * (1 - g (h x)) = v y * (1 - g (h y))} h)"
by (intro nn_integral_indicator[symmetric]) simp
also have "\<dots> = nn_integral (\<Pi>\<^sub>M i \<in> {x,y}. \<U>) (\<lambda>h. if v x * (1 - g (h x)) = v y * (1 - g (h y)) then 1 else 0)"
by (intro nn_integral_cong) (auto simp: indicator_def space_PiM PiE_def)
also from \<open>x \<noteq> y\<close> have "\<dots> = (\<integral>\<^sup>+z. (if v x * (1 - g (fst z)) = v y * (1 - g (snd z)) then 1 else 0) \<partial>(\<U> \<Otimes>\<^sub>M \<U>))"
by (intro product_nn_integral_pair) auto
also have "\<dots> = \<integral>\<^sup>+y\<^sub>y. (\<integral>\<^sup>+y\<^sub>x. (if v x * (1 - g y\<^sub>x) = v y * (1 - g y\<^sub>y) then 1 else 0) \<partial>\<U>) \<partial>\<U>"
by (subst pair_sigma_finite.nn_integral_snd[symmetric])
(auto simp: pair_sigma_finite_def intro: prob_space_imp_sigma_finite)
also have "\<dots> = \<integral>\<^sup>+y\<^sub>y. (\<integral>\<^sup>+y\<^sub>x. indicator {z. v x * (1 - g z) = v y * (1 - g y\<^sub>y)} y\<^sub>x \<partial>\<U>) \<partial>\<U>"
by (simp add: indicator_def of_bool_def)
also have "\<dots> = \<integral>\<^sup>+y\<^sub>y. emeasure \<U> {z. v x * (1 - g z) = v y * (1 - g y\<^sub>y)} \<partial>\<U>"
by (subst nn_integral_indicator) simp_all
also from assms have "\<dots> = \<integral>\<^sup>+y\<^sub>y. emeasure \<U> (if 0 < 1 - v y * (1 - g y\<^sub>y) / v x then {ln (1 - v y * (1 - g y\<^sub>y) / v x) + 1} else {}) \<partial>\<U>"
by (subst weighted_eq_at_most_one) auto
also have "\<dots> = \<integral>\<^sup>+y\<^sub>y. 0 \<partial>\<U>"
by (intro nn_integral_cong_AE AE_uniform_measureI AE_I2)
(auto intro: emeasure_lborel_countable)
also have "\<dots> = 0" by simp
finally show ?thesis
by (simp add: 2 3)
qed
text \<open>Adapted from Eberl's @{thm almost_everywhere_linorder}.\<close>
lemma almost_everywhere_linorder_weighted_linorder_from_keys:
assumes "L' \<subseteq> L"
shows "AE Y in (\<Pi>\<^sub>M i \<in> L'. \<U>). linorder_on L' (weighted_linorder_from_keys L' v g Y)"
proof -
let ?N = "(\<Pi>\<^sub>M i \<in> L'. \<U>)"
have [simp]: "sets ?N = sets (\<Pi>\<^sub>M i \<in> L'. lborel)"
by (intro sets_PiM_cong) simp_all
from \<open>L' \<subseteq> L\<close> finite_L have fin: "finite L'"
by (rule finite_subset)
let ?M = "(\<Pi>\<^sub>M i \<in> L'. lborel)"
have meas: "{h \<in> L' \<rightarrow>\<^sub>E UNIV. v i * (1 - g (h i)) = v j * (1 - g (h j))} \<in> sets ?M"
if [simp]: "i \<in> L'" "j \<in> L'" for i j
using fin
by measurable
define X :: "('a \<Rightarrow> real) set" where "X = (\<Union>x\<in>L'. \<Union>y\<in>L'-{x}. {h\<in>L' \<rightarrow>\<^sub>E UNIV. v x * (1 - g (h x)) = v y * (1 - g(h y))})"
have "AE f in ?N. inj_on (\<lambda>a. v a * (1 - g (f a))) L'"
proof (rule AE_I)
show "{f \<in> space ?N. \<not> inj_on (\<lambda>a. v a * (1 - g (f a))) L'} \<subseteq> X"
by (auto simp: inj_on_def X_def space_PiM)
next
show "X \<in> sets ?N" unfolding X_def
using meas by (auto intro: countable_finite fin)
next
have "emeasure ?N X \<le> (\<Sum>i\<in>L'. emeasure ?N (\<Union>y\<in>L'-{i}. {h \<in> L' \<rightarrow>\<^sub>E UNIV. v i * (1 - g (h i)) = v y * (1 - g (h y))}))"
unfolding X_def using fin
by (intro emeasure_subadditive_finite) auto
also have "\<dots> \<le> (\<Sum>i\<in>L'. \<Sum>j\<in>L'-{i}. emeasure ?N {h \<in> L' \<rightarrow>\<^sub>E UNIV. v i * (1 - g (h i)) = v j * (1 - g (h j))})"
using fin
by (intro emeasure_subadditive_finite sum_mono) auto
also have "\<dots> = (\<Sum>i\<in>L'. \<Sum>j\<in>L'-{i}. 0)"
using fin \<open>L' \<subseteq> L\<close>
by (intro sum.cong refl emeasure_PiM_equal_weights) auto
also have "\<dots> = 0" by simp
finally show "emeasure ?N X = 0" by simp
qed
then show "AE f in ?N. linorder_on L' (weighted_linorder_from_keys L' v g f)"
by eventually_elim auto
qed
lemma AE_linorder_on_linorder_from_keys_add_dim:
assumes "i \<in> L"
assumes "linorder_on (L - {i}) (weighted_linorder_from_keys (L - {i}) v g Y)"
shows "AE y in \<U>. linorder_on L (weighted_linorder_from_keys L v g (Y(i:=y)))"
proof (intro eventually_mono[OF almost_everywhere_avoid_countable[where A = "{y | y i'. i' \<in> L \<and> v i * (1 - g y) = v i' * (1 - g (Y i'))}"]], goal_cases)
case 1
from finite_L \<open>i \<in> L\<close> show ?case
by (auto intro: countable_finite simp: weighted_eq_at_most_one)
next
case (2 y)
with assms have linorder_insert: "linorder_on (insert i (L - {i})) (weighted_linorder_from_keys (insert i (L - {i})) v g (Y(i:=y)))"
by (intro linorder_on_weighted_linorder_from_keys_insert) auto
from \<open>i \<in> L\<close> have "insert i (L - {i}) = L"
by blast
with linorder_insert show ?case
by simp
qed
lemma dual_expectation_feasible_edge:
assumes "i \<in> L"
assumes "j \<in> R"
assumes "{i,j} \<in> G"
shows "expectation (\<lambda>Y. dual_sol Y (ranking (weighted_linorder_from_keys L v g Y) G \<pi>) $ (Vs_enum i)) +
expectation (\<lambda>Y. dual_sol Y (ranking (weighted_linorder_from_keys L v g Y) G \<pi>) $ (Vs_enum j)) \<ge> v i"
(is "?Ei_plus_Ej \<ge> v i")
proof -
from assms have [intro]: "Vs_enum i < n" "Vs_enum j < n"
by (auto simp: Vs_enum_L Vs_enum_R intro: L_enum_less_n R_enum_less_n)
from \<open>{i,j} \<in> G\<close> have "?Ei_plus_Ej = expectation (\<lambda>Y. dual_sol Y (ranking (weighted_linorder_from_keys L v g Y) G \<pi>) $ (Vs_enum i) +
dual_sol Y (ranking (weighted_linorder_from_keys L v g Y) G \<pi>) $ (Vs_enum j))" (is "_ = expectation ?i_plus_j")
by (intro Bochner_Integration.integral_add[symmetric] integrable_dual_component)
(auto dest: edges_are_Vs intro: Vs_enum_less_n)
also from \<open>i \<in> L\<close> have "\<dots> = integral\<^sup>L (\<Pi>\<^sub>M i \<in> (insert i (L - {i})). \<U>) ?i_plus_j"
by (simp add: insert_absorb)
also have "\<dots> = integral\<^sup>L (distr (\<U> \<Otimes>\<^sub>M (\<Pi>\<^sub>M i \<in> (L - {i}). \<U>))
(\<Pi>\<^sub>M i \<in> (insert i (L - {i})). \<U>)
(\<lambda>(y,Y). Y(i := y))) ?i_plus_j"
by (intro arg_cong2[where f = "integral\<^sup>L"] distr_pair_PiM_eq_PiM[symmetric])
auto
also have "\<dots> = integral\<^sup>L (\<U> \<Otimes>\<^sub>M (\<Pi>\<^sub>M i \<in> (L - {i}). \<U>)) (?i_plus_j \<circ> (\<lambda>(y,Y). Y(i := y)))"
unfolding comp_def
proof (intro integral_distr, goal_cases)
case 1
then show ?case
by measurable
next
case 2
from \<open>i \<in> L\<close> show ?case
by (intro borel_measurable_add)
(auto simp: insert_absorb intro: measurable_dual_component)
qed
also have "\<dots> = \<integral>Y. \<integral>y. ?i_plus_j (Y(i := y)) \<partial>\<U> \<partial>(\<Pi>\<^sub>M i \<in> (L - {i}). \<U>)"
proof (subst pair_sigma_finite.integral_snd, goal_cases)
case 2
then show ?case
by (subst split_comp_eq[symmetric], rule Bochner_Integration.integrable_add; subst split_comp_eq)
(use \<open>i \<in> L\<close> in \<open>auto intro!: integrable_dual_component_split_dim\<close>)
next
case 3
then show ?case
by (rule arg_cong2[where f = "integral\<^sup>L"]) auto
qed auto
also have "\<dots> \<ge> \<integral>Y. \<integral>y. v i * g y / F * indicator {..<y\<^sub>c Y \<pi> i j} y \<partial>\<U> + v i * (1 - g (y\<^sub>c Y \<pi> i j)) / F \<partial>(\<Pi>\<^sub>M i \<in> L - {i}. \<U>)" (is "_ \<ge> ?integral_bound1")
proof (intro integral_mono_AE, goal_cases)
case 1
have add_diff_assoc: "a + (b - c) = a + b - c" for a b c::real
by simp
from \<open>j \<in> R\<close> \<open>i \<in> L\<close> show ?case
by (auto simp: mult.assoc add_diff_assoc simp flip: add_divide_distrib distrib_left intro!: integrable_integral_bound_but_i dest: weights_pos)
next
case 2
show ?case
proof (intro integrableI_real_bounded component_prob_space.borel_measurable_lebesgue_integral, goal_cases)
case 1
from \<open>i \<in> L\<close> \<open>Vs_enum i < n\<close> \<open>Vs_enum j < n\<close> show ?case
using measurable_dual_component_split_dim
by measurable
next
case 2
from \<open>Vs_enum i < n\<close> \<open>Vs_enum j < n\<close> show ?case
by (intro eventually_mono[OF AE_PiM_subset_L_\<U>_funcset[OF Diff_subset]] integral_nonneg_AE eventually_mono[OF AE_\<U>_in_range])
(auto dest!: funcset_update dual_sol_funcset_if_funcset[where X = "{}", simplified] intro!: add_nonneg_nonneg)
next
case 3
interpret L'_prob_space: prob_space "\<Pi>\<^sub>M i \<in> L - {i}. \<U>"
by (intro prob_space_PiM) blast
have "\<integral>\<^sup>+Y. (component_prob_space.expectation (\<lambda>y. dual_sol (Y(i := y)) (ranking (weighted_linorder_from_keys L v g (Y(i := y))) G \<pi>) $ Vs_enum i +
dual_sol (Y(i := y)) (ranking (weighted_linorder_from_keys L v g (Y(i := y))) G \<pi>) $ Vs_enum j))
\<partial>(\<Pi>\<^sub>M i \<in> L - {i}. \<U>) \<le> \<integral>\<^sup>+_. 2 * max_weight/F \<partial>(\<Pi>\<^sub>M i \<in> L - {i}. \<U>)"
proof (intro nn_integral_mono_AE eventually_mono[OF AE_PiM_subset_L_\<U>_funcset[OF Diff_subset]], simp,
intro integral_real_bounded component_prob_space.nn_integral_le_const eventually_mono[OF AE_\<U>_in_range], goal_cases)
case (3 Y y)
then have "($) (dual_sol (Y(i := y)) (ranking (weighted_linorder_from_keys L v g (Y(i := y))) G \<pi>)) \<in> {..<n} \<rightarrow> {0..max_weight/F}"
by (auto dest!: funcset_update dual_sol_funcset_if_funcset[where X = "{}", simplified])
with \<open>Vs_enum i < n\<close> \<open>Vs_enum j < n\<close> have "dual_sol (Y(i := y)) (ranking (weighted_linorder_from_keys L v g (Y(i := y))) G \<pi>) $ Vs_enum i \<le> max_weight/F"
"dual_sol (Y(i := y)) (ranking (weighted_linorder_from_keys L v g (Y(i := y))) G \<pi>) $ Vs_enum j \<le> max_weight/F"
by auto
then show ?case
by simp
qed simp_all
also have "\<dots> = 2*max_weight/F"
by (simp add: L'_prob_space.emeasure_space_1)
finally show ?case
by (simp add: order_le_less_trans)
qed
next
case 3
from finite_L have AE_Y_props:
"AE Y in (\<Pi>\<^sub>M i \<in> L - {i}. \<U>). Y \<in> space (\<Pi>\<^sub>M i \<in> L - {i}. \<U>) \<and>
Y \<in> L-{i} \<rightarrow> {0..1} \<and>
linorder_on (L - {i}) (weighted_linorder_from_keys (L - {i}) v g Y)"
by (auto intro: AE_PiM_subset_L_\<U>_funcset almost_everywhere_linorder_weighted_linorder_from_keys)
show ?case
proof (rule eventually_mono[OF AE_Y_props])
fix Y :: "'a \<Rightarrow> real"
assume Y: "Y \<in> space (\<Pi>\<^sub>M i \<in> L - {i}. \<U>) \<and> Y \<in> L-{i} \<rightarrow> {0..1} \<and> linorder_on (L - {i}) (weighted_linorder_from_keys (L - {i}) v g Y)"
have integrable_offline_bound: "integrable \<U> (\<lambda>y. v i * g y / F * indicat_real {..<y\<^sub>c Y \<pi> i j} y)"
by (auto intro!: integrable_divide intro: integrable_real_mult_indicator)
have *: "v i * (1 - g (y\<^sub>c Y \<pi> i j)) / F = component_prob_space.expectation (\<lambda>y. v i * (1 - g (y\<^sub>c Y \<pi> i j)) / F)" for Y
by (simp add: measure_def component_prob_space.emeasure_space_1)
have "\<integral>y. v i * g y / F * indicat_real {..<y\<^sub>c Y \<pi> i j} y \<partial>\<U> + v i * (1 - g (y\<^sub>c Y \<pi> i j)) / F =
\<integral>y. v i * g y / F * indicat_real {..<y\<^sub>c Y \<pi> i j} y + v i * (1 - g (y\<^sub>c Y \<pi> i j)) / F \<partial>\<U>"
by (subst *, intro Bochner_Integration.integral_add[symmetric] integrable_offline_bound, auto)
also have "\<dots> \<le> component_prob_space.expectation (\<lambda>y. dual_sol (Y(i := y)) (ranking (weighted_linorder_from_keys L v g (Y(i := y))) G \<pi>) $ Vs_enum i +
dual_sol (Y(i := y)) (ranking (weighted_linorder_from_keys L v g (Y(i := y))) G \<pi>) $ Vs_enum j)"
proof (intro integral_mono_AE Bochner_Integration.integrable_add integrable_offline_bound, goal_cases)
case 2
with \<open>i \<in> L\<close> \<open>Vs_enum i < n\<close> Y show ?case
by (auto intro: integrable_dual_component_\<U>)
next
case 3
with \<open>i \<in> L\<close> \<open>Vs_enum j < n\<close> Y show ?case
by (auto intro: integrable_dual_component_\<U>)
next
case 4
from Y \<open>i \<in> L\<close> have AE_y: "AE y in \<U>. y \<in> {0..1} \<and> Y(i:=y) \<in> L \<rightarrow> {0..1} \<and> linorder_on L (weighted_linorder_from_keys L v g (Y(i := y)))"
by (auto intro: AE_linorder_on_linorder_from_keys_add_dim eventually_mono[OF AE_\<U>_in_range] AE_\<U>_funcset)
then show ?case
proof (rule eventually_mono, goal_cases)
case (1 y)
note y_props = this
then show ?case
proof (intro add_mono, goal_cases)
case 1
then have *: "($) (dual_sol (Y(i := y)) (ranking (weighted_linorder_from_keys L v g (Y(i := y))) G \<pi>)) \<in> {..<n} \<rightarrow> {0..max_weight/F}"
by (intro dual_sol_funcset[where X = "{}", simplified])
(auto simp: Pi_iff)
have "y < y\<^sub>c Y \<pi> i j \<Longrightarrow> v i * g y / F \<le> dual_sol (Y(i := y)) (ranking (weighted_linorder_from_keys L v g (Y(i := y))) G \<pi>) $ Vs_enum i"
proof -
assume "y < y\<^sub>c Y \<pi> i j"
with \<open>j \<in> R\<close> have "y < y\<^sub>c (Y(i:=y)) \<pi> i j"
by (simp add: y\<^sub>c_fun_upd_eq)
with y_props \<open>i \<in> L\<close> \<open>j \<in> R\<close> \<open>{i,j} \<in> G\<close> have "i \<in> Vs (ranking (weighted_linorder_from_keys L v g (Y(i:=y))) G \<pi>)"
by (auto intro: dominance)
with \<open>Vs_enum i < n\<close> \<open>i \<in> L\<close> have "dual_sol (Y(i:=y)) (ranking (weighted_linorder_from_keys L v g (Y(i:=y))) G \<pi>) $ Vs_enum i = v i * g y / F"
by (auto simp: dual_sol_def)
(metis L_enum_less_card Vs_enum_L)+
then show ?thesis
by auto
qed
with * show ?case
by (subst indicator_times_eq_if) auto
next
case 2
with \<open>i \<in> L\<close> \<open>j \<in> R\<close> \<open>{i,j} \<in> G\<close> show ?case
by (subst y\<^sub>c_fun_upd_eq[where y = y, symmetric], auto intro!: monotonicity)
qed
qed
qed simp
finally show "component_prob_space.expectation (\<lambda>y. v i * g y / F * indicat_real {..<y\<^sub>c Y \<pi> i j} y) + v i * (1 - g (y\<^sub>c Y \<pi> i j)) / F
\<le> component_prob_space.expectation (\<lambda>y. dual_sol (Y(i := y)) (ranking (weighted_linorder_from_keys L v g (Y(i := y))) G \<pi>) $ Vs_enum i
+ dual_sol (Y(i := y)) (ranking (weighted_linorder_from_keys L v g (Y(i := y))) G \<pi>) $ Vs_enum j)"
.
qed
qed
finally have "?Ei_plus_Ej \<ge> ?integral_bound1".
have "?integral_bound1 = v i * \<integral>Y. \<integral>y. g y * indicator {..<y\<^sub>c Y \<pi> i j} y \<partial>\<U> + 1 - g (y\<^sub>c Y \<pi> i j) \<partial>(\<Pi>\<^sub>M i \<in> L - {i}. \<U>) / F"
by (auto simp flip: add_divide_distrib integral_mult_right_zero simp: algebra_simps)
also have "\<dots> \<ge> v i * \<integral>Y. F \<partial>(\<Pi>\<^sub>M i \<in> L - {i}. \<U>) / F" (is "_ \<ge> ?integral_bound2")
proof (subst div_F_less_eq_cancel, intro integral_mono_AE mult_left_mono, goal_cases)
case 1
show ?case
by (rule integrableI_real_bounded)
(auto simp: emeasure_space_PiM_\<U>)
next
case 2
from \<open>i \<in> L\<close> \<open>j \<in> R\<close> show ?case
by (auto intro: integrable_integral_bound_but_i)
next
case 3
from \<open>j \<in> R\<close> show ?case
proof (intro eventually_mono[OF AE_PiM_subset_L_\<U>_funcset])
fix Y assume "Y \<in> L-{i} \<rightarrow> {0..1::real}"
with \<open>i \<in> L\<close> \<open>j \<in> R\<close> have "\<integral>y. g y * indicator {..<y\<^sub>c Y \<pi> i j} y\<partial>\<U> + 1 - g (y\<^sub>c Y \<pi> i j) = 1 - exp(-1)"
(is "?int = _")
by (auto simp: exp_minus_One_integral_indicator dest: y\<^sub>c_bounded)
then show "?int \<ge> 1 - exp(-1)"
by linarith
qed auto
qed (use \<open>i \<in> L\<close> in auto)
finally have "?integral_bound1 \<ge> ?integral_bound2" .
have "?integral_bound2 = v i"
by (auto simp: measure_def emeasure_space_PiM_\<U>)
with \<open>?Ei_plus_Ej \<ge> ?integral_bound1\<close> \<open>?integral_bound1 \<ge> ?integral_bound2\<close> show ?thesis
by linarith
qed
abbreviation "expected_dual \<equiv> vec n (\<lambda>i. expectation (\<lambda>Y. dual_sol Y (ranking (weighted_linorder_from_keys L v g Y) G \<pi>) $ i))"
lemma expected_dual_feasible: "incidence_matrix\<^sup>T *\<^sub>v expected_dual \<ge> vertex_weighted_coeffs"
unfolding Matrix.less_eq_vec_def
proof (intro conjI allI impI, simp_all add: incidence_matrix_def)
fix k assume "k < m"
then obtain i j where ij: "{i,j} \<in> G" "from_nat_into G k = {i,j}" "i \<in> L" "j \<in> R"
by (auto elim: from_nat_into_G_E)
with bipartite_graph have index_neq: "Vs_enum i \<noteq> Vs_enum j"
by (intro Vs_enum_neqI) (auto dest: edges_are_Vs)
{
fix l r
assume "from_nat_into G k = {l,r}" "l \<in> L" "r \<in> R"
with ij have "l = i" "r = j"
by auto
} note the_lr = this
from ij have the_l: "(THE l. l \<in> L \<and> l \<in> from_nat_into G k) = i"
by auto
from ij have "v i \<le> expectation (\<lambda>Y. dual_sol Y (ranking (weighted_linorder_from_keys L v g Y) G \<pi>) $ Vs_enum i) +
expectation (\<lambda>Y. dual_sol Y (ranking (weighted_linorder_from_keys L v g Y) G \<pi>) $ Vs_enum j)"
by (intro dual_expectation_feasible_edge)
also from index_neq have "\<dots> = (\<Sum>k\<in>{Vs_enum i, Vs_enum j}. expectation (\<lambda>Y. dual_sol Y (ranking (weighted_linorder_from_keys L v g Y) G \<pi>) $ k))"
by simp
also from the_lr \<open>{i,j} \<in> G\<close> \<open>k < m\<close> have "\<dots> = vec n (\<lambda>i. of_bool (Vs_enum_inv i \<in> from_nat_into G k)) \<bullet> vec n (\<lambda>i. expectation (\<lambda>Y. dual_sol Y (ranking (weighted_linorder_from_keys L v g Y) G \<pi>) $ i))"
unfolding incidence_matrix_def
by (auto simp: scalar_prod_def sum.cong[OF index_set_Int_is_doubleton] elim!: from_nat_into_G_E)
finally show "v (THE l. l \<in> L \<and> l \<in> from_nat_into G k) \<le> vec n (\<lambda>i. of_bool (Vs_enum_inv i \<in> from_nat_into G k)) \<bullet> vec n (\<lambda>i. expectation (\<lambda>Y. dual_sol Y (ranking (weighted_linorder_from_keys L v g Y) G \<pi>) $ i))"
by (simp add: the_l)
qed
lemma expected_dual_nonneg: "expected_dual \<ge> 0\<^sub>v n"
unfolding Matrix.less_eq_vec_def
proof (intro conjI allI impI, simp_all, intro integral_ge_const integrable_dual_component)
fix k
assume "k < n"
have "j \<in> Vs (ranking (weighted_linorder_from_keys L v g Y) G \<pi>) \<Longrightarrow> j \<in> R \<Longrightarrow> (THE l. {l, j} \<in> ranking (weighted_linorder_from_keys L v g Y) G \<pi>) \<in> L" for j Y
by (auto intro!: the_ranking_match_left)
with \<open>k < n\<close> show "AE Y in \<Y>. 0 \<le> dual_sol Y (ranking (weighted_linorder_from_keys L v g Y) G \<pi>) $ k"
unfolding dual_sol_def
by (intro eventually_mono[OF AE_\<Y>_funcset])
(auto intro!: g_less_eq_OneI mult_nonneg_nonneg simp: Pi_iff elim: Vs_enum_inv_leftE Vs_enum_inv_rightE)
qed blast
lemma ranking_F_competitive:
assumes "G \<noteq> {}"
assumes "max_value_matching M"
shows "expectation (\<lambda>Y. matching_value (ranking (weighted_linorder_from_keys L v g Y) G \<pi>)) / matching_value M \<ge> F" (is "?EM / _ \<ge> _")
proof -
from assms have "M \<noteq> {}" "finite M"
by (auto dest: max_value_matching_non_empty max_value_matchingD finite_subset)
with assms have "matching_value M > 0"
by (auto intro: non_empty_matching_value_pos dest: max_value_matchingD)
from assms have max_card_bound: "matching_value M \<le> 1\<^sub>v n \<bullet> expected_dual"
by (auto intro: max_value_matching_bound_by_feasible_dual expected_dual_feasible expected_dual_nonneg)
have "?EM = expectation (\<lambda>Y. vertex_weighted_coeffs \<bullet> primal_sol (ranking (weighted_linorder_from_keys L v g Y) G \<pi>))"
by (subst primal_dot_coeffs_eq_value, rule ranking_subgraph)
auto
also have "\<dots> = expectation (\<lambda>Y. 1\<^sub>v n \<bullet> dual_sol Y (ranking (weighted_linorder_from_keys L v g Y) G \<pi>) * F)"
by (intro Bochner_Integration.integral_cong refl primal_is_dual_times_F ranking_subgraph matching_ranking)
auto
also have "\<dots> = 1\<^sub>v n \<bullet> expected_dual * F" (is "?E = ?Edot1F")
proof -
have "?E = expectation (\<lambda>Y. \<Sum>i\<in>{0..<n}. dual_sol Y (ranking (weighted_linorder_from_keys L v g Y) G \<pi>) $ i) * F"
by (auto simp: scalar_prod_def)
also have "\<dots> = (\<Sum>i\<in>{0..<n}. expectation (\<lambda>Y. dual_sol Y (ranking (weighted_linorder_from_keys L v g Y) G \<pi>) $ i)) * F"
by (auto intro!: Bochner_Integration.integral_sum intro: integrable_dual_component)
also have "\<dots> = ?Edot1F"
by (auto simp: scalar_prod_def)
finally show ?thesis .
qed
finally have "?EM = ?Edot1F" .
with max_card_bound \<open>matching_value M > 0\<close> show ?thesis
by (auto intro: mult_imp_le_div_pos mult_left_mono simp: mult.commute)
qed
theorem ranking_prob_F_competitive:
assumes "G \<noteq> {}"
assumes "max_value_matching M"
shows "ranking_prob_space.expectation matching_value / (matching_value M) \<ge> F"
proof -
from assms have "F \<le> expectation (\<lambda>Y. matching_value (ranking (weighted_linorder_from_keys L v g Y) G \<pi>)) / matching_value M"
by (auto intro: ranking_F_competitive)
also have "\<dots> = ranking_prob_space.expectation matching_value / (matching_value M)"
unfolding ranking_prob_distr
by (subst integral_distr)
(auto intro: ranking_measurable)
finally show ?thesis .
qed
end
theorem ranking_vertex_weighted_competitive_ratio:
assumes "bipartite G L R"
assumes "finite L" "finite R" "Vs G = L \<union> R"
assumes "\<And>i. i \<in> L \<Longrightarrow> 0 < v i"
assumes "G \<noteq> {}"
assumes "\<pi> \<in> permutations_of_set R"
assumes "bipartite_vertex_weighted_matching_lp.max_value_matching L G v M"
shows
"prob_space.expectation (\<Pi>\<^sub>M i \<in> L. uniform_measure lborel {0..1::real})
(\<lambda>Y. bipartite_vertex_weighted_matching_lp.matching_value L v (ranking (weighted_linorder_from_keys L v (\<lambda>x. exp(x-1)) Y) G \<pi>)) / bipartite_vertex_weighted_matching_lp.matching_value L v M
\<ge> 1 - exp(-1)" (is "?EY \<ge> _")
proof -
from assms interpret wf_locale: wf_vertex_weighted_online_bipartite_matching L R G v \<pi>
by unfold_locales auto
from assms show "?EY \<ge> 1 - exp(-1)"
by (auto intro: wf_locale.ranking_F_competitive)
qed
locale wf_ranking_order_prob = bipartite_vertex_priorities +
fixes \<pi>
assumes perm: "\<pi> \<in> permutations_of_set R"
begin
definition "ranking_prob_discrete \<equiv> do {
r \<leftarrow> uniform_measure (count_space (preorders_on L)) (linorders_on L);
return (count_space {M. M \<subseteq> G}) (ranking r G \<pi>)
}"
abbreviation "v \<equiv> \<lambda>_. 1"
sublocale bipartite_vertex_weighted_matching_lp L R G v
by standard auto
sublocale wf_vertex_weighted_online_bipartite_matching L R G v \<pi>
using perm
by unfold_locales auto
lemma matching_value_eq_card: "matching_value M = card M"
by simp
lemma weighted_linorder_from_keys_eq_linorder_from_keys: "weighted_linorder_from_keys L v g Y = linorder_from_keys L Y"
unfolding weighted_linorder_from_keys_def linorder_from_keys_def
by auto
lemma ranking_prob_eq_discrete: "ranking_prob = ranking_prob_discrete"
proof -
have "ranking_prob = distr \<Y> (count_space {M. M \<subseteq> G}) (\<lambda>Y. ranking (linorder_from_keys L Y) G \<pi>)"
by (simp add: ranking_prob_distr weighted_linorder_from_keys_eq_linorder_from_keys)
also have "\<dots> = distr (distr \<Y> (count_space (preorders_on L)) (linorder_from_keys L)) (count_space {M. M \<subseteq> G}) (\<lambda>r. ranking r G \<pi>)"
by (subst distr_distr)
(use perm in \<open>auto simp: comp_def dest: preorders_onD permutations_of_setD intro: ranking_subgraph'\<close>)
also have "\<dots> = distr (uniform_measure (count_space (preorders_on L)) (linorders_on L)) (count_space {M. M \<subseteq> G}) (\<lambda>r. ranking r G \<pi>)"
using finite_L
by (auto simp: random_linorder_by_prios_preorders)
also have "\<dots> = ranking_prob_discrete"
unfolding ranking_prob_discrete_def
apply (subst bind_return_distr')
apply auto
apply measurable
apply (use perm in \<open>auto dest: preorders_onD permutations_of_setD intro: ranking_subgraph'\<close>)
done
finally show ?thesis .
qed
sublocale ranking_prob_discrete_prob_space: prob_space ranking_prob_discrete
by (auto simp flip: ranking_prob_eq_discrete intro: ranking_prob_space.prob_space_axioms)
lemma max_value_matching_iff_max_card_matching: "max_value_matching M \<longleftrightarrow> max_card_matching G M"
unfolding max_value_matching_def max_card_matching_def
by simp
lemma expectation_ranking_eq_random_linorder:
"expectation (\<lambda>Y. card (ranking (linorder_from_keys L Y) G \<pi>)) =
prob_space.expectation (uniform_measure (count_space (Pow (L \<times> L))) (linorders_on L)) (\<lambda>r. card (ranking r G \<pi>))"
(is "?EY = ?Er")
proof -
from finite_L have "?EY = prob_space.expectation (distr (\<Pi>\<^sub>M i \<in> L. uniform_measure lborel {0..1::real}) (count_space (Pow (L \<times> L))) (linorder_from_keys L))
(\<lambda>r. card (ranking r G \<pi>))"
by (intro integral_distr[symmetric])
(use measurable_linorder_from_keys_restrict in measurable)
also from finite_L have "\<dots> = prob_space.expectation (uniform_measure (count_space (Pow (L \<times> L))) (linorders_on L)) (\<lambda>r. card (ranking r G \<pi>))"
by (auto simp: random_linorder_by_prios)
finally show ?thesis .
qed
lemmas ranking_F_competitive_linorder_from_keys = ranking_F_competitive[simplified max_value_matching_iff_max_card_matching weighted_linorder_from_keys_eq_linorder_from_keys matching_value_eq_card]
lemma ranking_F_competitive_random_linorder:
assumes "G \<noteq> {}"
assumes "max_card_matching G M"
shows "prob_space.expectation (uniform_measure (count_space (Pow (L \<times> L))) (linorders_on L))
(\<lambda>r. card (ranking r G \<pi>)) / card M \<ge> F"
using assms
by (auto simp flip: expectation_ranking_eq_random_linorder intro: ranking_F_competitive_linorder_from_keys)
lemma ranking_F_competitive_discrete:
assumes "G \<noteq> {}"
assumes "max_card_matching G M"
shows "ranking_prob_discrete_prob_space.expectation card / card M \<ge> F"
using assms
by (auto simp flip: ranking_prob_eq_discrete simp: max_value_matching_iff_max_card_matching dest!: ranking_prob_F_competitive)
end
theorem
assumes "bipartite G L R"
assumes "finite L" "finite R" "Vs G = L \<union> R"
assumes "G \<noteq> {}"
assumes "\<pi> \<in> permutations_of_set R"
assumes "max_card_matching G M"
shows ranking_competitive_ratio:
"prob_space.expectation (\<Pi>\<^sub>M i \<in> L. uniform_measure lborel {0..1::real}) (\<lambda>Y. card (ranking (linorder_from_keys L Y) G \<pi>)) / card M
\<ge> 1 - exp(-1)" (is "?EY \<ge> _")
and ranking_competitive_ratio_random_linorder:
"prob_space.expectation (uniform_measure (count_space (Pow (L \<times> L))) (linorders_on L)) (\<lambda>r. card (ranking r G \<pi>)) / card M
\<ge> 1 - exp(-1)" (is "?Er \<ge> _")
proof -
from assms interpret wf_ranking_order_prob_exp: wf_ranking_order_prob L R G \<pi>
by unfold_locales auto
from assms show "?EY \<ge> 1 - exp(-1)" "?Er \<ge> 1 - exp(-1)"
by (auto intro: wf_ranking_order_prob_exp.ranking_F_competitive_linorder_from_keys wf_ranking_order_prob_exp.ranking_F_competitive_random_linorder)
qed
end
|
module Rhone.Canvas
import Control.Monad.Dom
import Data.List
import Data.SOP
import JS
import Web.Html
import public Rhone.Canvas.Angle
import public Rhone.Canvas.Scene
import public Rhone.Canvas.Shape
import public Rhone.Canvas.Style
import public Rhone.Canvas.Transformation
%default total
public export
record Canvas where
constructor MkCanvas
ref : ElemRef HTMLCanvasElement
width, height : Double
scene : Scene
--------------------------------------------------------------------------------
-- IO
--------------------------------------------------------------------------------
export
context2D : LiftJSIO m
=> ElemRef HTMLCanvasElement
-> m CanvasRenderingContext2D
context2D ref = liftJSIO $ do
canvas <- getElementByRef ref
m <- getContext' canvas "2d"
case m >>= (\ns => extract CanvasRenderingContext2D ns) of
Just c => pure c
Nothing => throwError $ Caught "Rhone.Canvas.context2d: No rendering context for canvas"
export
render : LiftJSIO m => Canvas -> m ()
render (MkCanvas ref w h scene) = liftJSIO $ do
ctxt <- context2D ref
apply ctxt $ Rect 0 0 w h Clear
apply ctxt scene
|
Set Warnings "-notation-overridden,-parsing".
From Coq Require Import Bool.Bool.
From Coq Require Import Logic.Classical.
From Coq Require Import Init.Nat.
From Coq Require Import Arith.Arith.
From Coq Require Import Arith.EqNat.
From Coq Require Import omega.Omega.
From Coq Require Import Lists.List.
From Coq Require Import Strings.String.
From Coq Require Import QArith.QArith_base.
From CReal Require Import Dedekind.RBase.
From CReal Require Import Dedekind.ROrder.
From CReal Require Import QArith_ext.QArith_base_ext.
From CReal Require Import QArith_ext.Inject_lemmas.
From Coq Require Import QArith.Qfield.
Import ListNotations.
Lemma PPNN : forall P :Prop, P -> ~ ~ P.
Proof.
intros. unfold not. intros. apply H0, H.
Qed.
Lemma inverse_not: forall P Q : Prop, (P -> Q) <-> (~ Q -> ~ P).
Proof.
split.
intros. apply imply_to_or in H. destruct H. apply H. exfalso. apply H0, H.
intros. apply imply_to_or in H. destruct H. apply NNPP, H. exfalso. apply H, H0.
Qed.
Theorem exists_dist :
forall (X:Type) (P : X -> Prop),
(exists x, P x) <-> ~ (forall x, ~ P x).
Proof.
intros. split.
- apply inverse_not. intros. rewrite not_exists_dist. apply NNPP, H.
- apply inverse_not. intros. rewrite <- not_exists_dist. apply PPNN, H.
Qed.
Lemma funlemma1 : forall x : Real -> Prop, (exists x0 : Real, x x0)
-> exists (x0 : Q) (x1 : Real), x x1 /\ (Q_to_R x0 < x1)%R.
Proof.
intros. destruct H. remember x0. destruct x0. destruct (Dedekind_properties1 _ H0), H1.
exists x0, r. split;auto. hnf. rewrite Heqr. split.
- intros. apply (Dedekind_properties2 _ H0 x0).
split;auto;apply Qlt_le_weak;auto.
- destruct (Dedekind_properties3 _ H0 x0). auto.
exists x1. split. apply H3. apply Qle_not_lt.
apply Qlt_le_weak. apply H3.
Qed.
Lemma funlemma2 : forall x : Real -> Prop,(forall x1 x2, x x1 -> x x2 ->
x1 == x2) -> (exists x0 : Real, x x0)
-> exists x0 : Q, ~ (exists x1 : Real, x x1 /\ (Q_to_R x0 < x1)%R).
Proof.
intros. apply not_all_ex_not. hnf. intros.
destruct H0. destruct x0. destruct (Dedekind_properties1 _ H2), H4.
destruct (H1 x0). destruct H5. apply (H (Real_cons A H2)) in H5;auto.
rewrite <- H5 in H6. hnf in H6. destruct H6.
destruct H7, H7. apply Qnot_lt_le in H8. apply H4.
apply (Dedekind_properties2 _ H2 x2). split;auto.
Qed.
Lemma funlemma3 : forall x : Real -> Prop,(forall x1 x2, x x1 -> x x2 ->
x1 == x2) -> (exists x0 : Real, x x0)
-> forall p q : Q,
(exists x0 : Real, x x0 /\ (Q_to_R p < x0)%R) /\ q <= p
-> exists x0 : Real, x x0 /\ (Q_to_R q < x0)%R.
Proof.
intros. destruct H1, H1, H1. exists x0.
split;auto. hnf in H3. hnf. destruct x0. destruct H3. split.
- intros. apply H3. apply Qlt_le_trans with (y:=q);auto.
- destruct H5, H5. exists x0. split;auto.
hnf. intros. apply H6.
apply Qlt_le_trans with (y:=q);auto.
Qed.
Lemma funlemma4 : forall x : Real -> Prop,(forall x1 x2, x x1 -> x x2 ->
x1 == x2) -> (exists x0 : Real, x x0)
-> forall p : Q,
(exists x0 : Real, x x0 /\ (Q_to_R p < x0)%R) ->
exists r : Q, (exists x0 : Real, x x0 /\ (Q_to_R r < x0)%R) /\ p < r.
Proof.
intros. destruct H1, x0, H1, H3. destruct H4, H4.
apply (Dedekind_properties3 _ H2) in H4.
destruct H4, H4. exists x1. split.
- exists (Real_cons A H2). split;auto. hnf. split.
+ intros.
apply (Dedekind_properties2 _ H2 x1);split;try apply Qlt_le_weak;auto.
+ exists x1. split;auto;apply Qlt_irrefl.
- apply Qnot_lt_le in H5. apply Qle_lt_trans with (y:=x0);auto.
Qed.
Lemma funlemma5 : forall x : Real -> Prop,(forall x1 x2, x x1 -> x x2 ->
x1 == x2) -> (exists x0 : Real, x x0) ->
forall p q : Q,
(p == q)%Q -> (exists x0 : Real, x x0 /\ (Q_to_R p < x0)%R)
-> exists x0 : Real, x x0 /\ (Q_to_R q < x0)%R.
Proof.
intros. destruct H2, H2. exists x0. destruct x0, H3.
split;auto. split.
- intros. rewrite <- H1 in H6. apply H3;auto.
- destruct H5. rewrite H1 in H5. exists x0. auto.
Qed.
Definition Rsinglefun : {X: Real -> Prop | (forall x1 x2, X x1 -> X x2 ->
x1 == x2) /\ (exists x, X x) /\ Proper ( Req ==> iff) X}%R -> Real.
intros. destruct X, a, H0. hnf in *.
apply (Real_cons (fun q : Q => exists x0 : Real, x x0 /\ (Q_to_R q < x0)%R)).
split.
- split.
+ apply funlemma1;auto.
+ apply funlemma2;auto.
- apply funlemma3;auto.
- apply funlemma4;auto.
- apply funlemma5;auto. Defined.
Theorem Rsinglefun_correct: forall X H, X (Rsinglefun (exist _ X H)).
Proof.
intros. hnf in *. destruct H, a. hnf in p. destruct e.
apply (p x);auto. hnf. destruct x. split.
- hnf. intros. exists (Real_cons A H). split;auto. hnf. split.
+ intros. apply (Dedekind_properties2 _ H x).
split;try apply Qlt_le_weak;auto.
+ destruct (Dedekind_properties3 _ H x);auto. exists x1.
destruct H1.
split;try apply Qle_not_lt;try apply Qlt_le_weak;auto.
- hnf. intros. destruct H0, H0. destruct x1.
destruct H1, H3, H3. apply Qnot_lt_le in H4.
assert((Real_cons A H)==(Real_cons A0 H2)).
apply r;auto. destruct H5. hnf in H6. apply H6.
apply (Dedekind_properties2 _ H2 x1);auto.
Qed.
Definition R2fun : {f:Real -> Real -> Prop | (forall x1 x2 y1 y2, f x1 y1 -> f x2 y2
-> x1 == x2 -> y1 == y2) /\ (forall x, exists y, f x y) /\
Proper (Req ==> Req ==> iff) f }%R -> (Real -> Real).
intros. destruct X, a, H0. apply Rsinglefun. exists (x X0). split.
- intros. apply (H X0 X0 x1 x2);auto. reflexivity.
- split.
+ apply (H0 X0).
+ split.
{ intros. rewrite H2 in H3. auto. }
{ intros. rewrite H2. auto. } Defined.
(** Second , we will define the plus operation of Set and Real and proof some theorem about it. *)
Definition Cut_plus_Cut (A : Q -> Prop) (B : Q -> Prop) : Q -> Prop :=
(fun x => exists x0 x1 : Q, A x0 /\ B x1 /\ (Qeq (x0 + x1) x))
.
Theorem Dedekind_plus : forall A B, Dedekind A -> Dedekind B -> Dedekind (Cut_plus_Cut A B).
Proof.
intros.
rename H into DA, H0 into DB.
split.
- destruct (Dedekind_properties1 _ DA).
destruct (Dedekind_properties1 _ DB).
split.
+ inversion H.
inversion H1.
exists (x0 + x), x , x0.
split.
* apply H3.
* split.
apply H4.
apply Qplus_comm.
+ inversion H0. inversion H2.
unfold not in *.
exists (x + x0).
intros. destruct H5. destruct H5.
assert (H' : x > x1 /\ x0 > x2).
{
split.
apply Dedekind_le with A.
apply DA. unfold not. apply H3. apply H5.
apply Dedekind_le with B.
apply DB. unfold not. apply H4. apply H5.
}
assert (H'' : Qlt (x1 + x2)(x + x0)).
{
apply Qplus_lt_le_compat. apply H'.
apply Qlt_le_weak. apply H'.
}
destruct H5. destruct H6. rewrite H7 in H''.
apply Qlt_irrefl with (x + x0). apply H''.
- intros.
destruct H. destruct H. destruct H.
unfold Cut_plus_Cut.
exists x , (q + - x).
split; [apply H |].
split; [apply (Dedekind_properties2 _ DB) with x0 |].
split; [apply H |].
apply Qplus_le_l with (z := x).
destruct H. destruct H1.
rewrite Qplus_comm in H2.
rewrite H2. apply Qle_trans with q.
rewrite <- Qplus_assoc. rewrite (Qplus_comm (- x)).
rewrite Qplus_opp_r. rewrite Qplus_0_r.
apply Qle_refl. apply H0.
rewrite Qplus_comm. rewrite <- Qplus_assoc.
rewrite (Qplus_comm (- x)). rewrite Qplus_opp_r.
apply Qplus_0_r.
- intros.
repeat destruct H. destruct H0.
apply (Dedekind_properties3 _ DA) in H.
apply (Dedekind_properties3 _ DB) in H0 as goal.
destruct H. destruct goal.
exists (x1 + x0).
split. unfold Cut_plus_Cut.
exists x1,x0.
split. apply H.
split. apply H0. reflexivity.
rewrite <- H1.
apply Qplus_lt_l. apply H.
- intros.
repeat destruct H0.
unfold Cut_plus_Cut.
exists x,x0.
split. apply H0.
split. apply H1.
rewrite <- H. apply H1.
Qed.
Definition Rplus(a b : Real) : Real :=
match a with
| (Real_cons A HA) => match b with
| (Real_cons B HB) =>
Real_cons (Cut_plus_Cut A B) (Dedekind_plus A B HA HB)
end
end.
Notation "A + B" := (Rplus A B) (at level 50, left associativity)
: R_scope.
Instance Rplus_comp : Proper (Req ==> Req ==> Req) Rplus.
Proof.
split ; destruct H; destruct H0;
destruct x ; destruct y;destruct x0;destruct y0;
unfold Rle in * ; simpl in *;
unfold Cut_plus_Cut in * ; simpl in *; intros ;
repeat destruct H7 ; destruct H8; exists x0;exists x1; split; auto.
Qed.
Theorem Rplus_0_r : forall a : Real, (a + Rzero)%R == a.
Proof.
intros.
destruct a.
unfold Rplus.
simpl.
unfold Req.
unfold Rle.
rename H into DA.
split.
- intros.
destruct H.
destruct H.
apply (Dedekind_properties2 _ DA) with x0.
split.
+ apply H.
+ destruct H. destruct H0.
rewrite <- Qplus_0_r with (x := x0).
rewrite <- H1.
apply Qplus_le_r.
apply Qlt_le_weak. apply H0.
- intros.
unfold Cut_plus_Cut.
apply (Dedekind_properties3 _ DA) in H.
destruct H.
exists x0,(Qplus x (-x0)).
split.
+ apply H.
+ split.
* apply Qplus_lt_l with (z := x0).
rewrite Qplus_0_l.
rewrite <- Qplus_assoc.
rewrite Qplus_comm with (y := x0).
rewrite Qplus_opp_r.
rewrite Qplus_0_r. apply H.
* rewrite Qplus_comm.
rewrite <- Qplus_assoc.
rewrite Qplus_comm with (y := x0).
rewrite Qplus_opp_r.
apply Qplus_0_r.
Qed.
Theorem Rplus_comm : forall a b : Real, (a + b)%R == (b + a)%R.
Proof.
intros.
destruct a.
destruct b.
unfold Req.
unfold Rplus.
simpl.
unfold Cut_plus_Cut.
split; intros; repeat destruct H1; destruct H2; exists x1,x0.
- split. apply H2. split. apply H1. rewrite <- H3. apply Qplus_comm.
- split. apply H2. split. apply H1. rewrite <- H3. apply Qplus_comm.
Qed.
Theorem Rplus_assoc : forall a b c : Real, (a + b + c)%R == (a + (b + c))%R.
Proof.
intros.
destruct a.
destruct b.
destruct c.
unfold Req.
unfold Rplus.
simpl.
unfold Cut_plus_Cut.
split; intros; repeat destruct H2; repeat destruct H3.
- exists x2 , (x + -x2).
split. apply H2.
split.
+ exists x3 , x1.
split. apply H4.
split. apply H3.
rewrite <- H5. destruct H4. rewrite <- H6.
remember (x3 + x1) as xp.
rewrite <- Qplus_comm. rewrite <- Qplus_assoc. rewrite <- Heqxp.
rewrite Qplus_comm with (y := xp).
rewrite Qplus_comm. rewrite <- Qplus_assoc. rewrite Qplus_opp_r.
symmetry. apply Qplus_0_r.
+ rewrite Qplus_comm with (x := x).
rewrite Qplus_assoc. rewrite Qplus_opp_r. apply Qplus_0_l.
- exists (x + - x3) , x3.
split.
+ exists x0,x2.
split. apply H2.
split. apply H3.
rewrite <- H4. destruct H5. rewrite <- H6.
rewrite <- Qplus_assoc.
rewrite <- Qplus_assoc.
rewrite Qplus_opp_r. rewrite Qplus_0_r. reflexivity.
+ split. apply H5.
rewrite <- Qplus_assoc.
rewrite Qplus_comm with (y:=x3).
rewrite Qplus_opp_r.
apply Qplus_0_r.
Qed.
Definition Cut_opp (A : Q -> Prop) : Q -> Prop :=
(fun x => exists r : Q, (r > 0 /\ ~(A (-x + -r))))
.
Theorem Dedekind_opp : forall A : Q -> Prop , Dedekind A -> Dedekind (Cut_opp A).
Proof.
intros.
rename H into DA.
unfold Cut_opp.
split.
- destruct (Dedekind_properties1 _ DA). split.
+ destruct H0.
exists (- x + (-1 # 1) ), 1.
remember ((- x) + (-1 # 1) ) as x0.
unfold not in *. split. reflexivity. intros. apply H0.
apply (Dedekind_properties4 _ DA) with (p := (- x0) + (- (1))).
* apply Qplus_inj_l with (z := x0).
rewrite Qplus_assoc. rewrite Qplus_opp_r.
rewrite Qplus_0_l. rewrite Qplus_comm.
rewrite Heqx0.
rewrite Qplus_assoc. rewrite Qplus_opp_r.
reflexivity.
* apply H1.
+ destruct H.
exists (-x).
apply not_exists_dist.
intros.
unfold not.
intros.
assert (H' : (Qlt 0 x0) -> A (- - x + - x0)).
{ intros.
assert(H': (--x == x)%Q).
{ apply Qopp_involutive. }
{ apply (Dedekind_properties2 _ DA x).
split.
* apply H.
* rewrite <- (Qplus_0_r x).
apply Qplus_le_compat. rewrite Qplus_0_r. rewrite H'. apply Qle_refl.
apply (Qopp_le_compat 0 x0).
apply Qlt_le_weak. apply H2. } }
destruct H1. apply H2. apply H'. apply H1.
- intros. destruct H. destruct H. destruct H.
exists x. split.
+ apply H.
+ unfold not. intros. apply H1. apply (Dedekind_properties2 _ DA (Qplus (Qopp q) (Qopp x))).
split.
* apply H2.
* apply Qplus_le_compat. apply Qopp_le_compat. apply H0. apply Qle_refl.
- intros.
inversion H.
exists (p + (x * / (2 # 1))).
split.
exists (x * / (2 # 1)).
split.
+ assert (H' : (0 == (0 * / (2 # 1)))%Q).
{ reflexivity. }
rewrite H'.
apply Qmult_lt_compat_r.
reflexivity.
apply H0.
+ unfold not in *.
intros. apply H0.
apply (Dedekind_properties4 _ DA) with (p := (- ( p + (x * / (2 # 1)))) + (-(x * / (2 # 1)))).
assert (H' : (x == ((x * / (2 # 1)) + (x * / (2 # 1))))%Q).
{ rewrite <- Qmult_plus_distr_r. rewrite <- Qmult_1_r.
rewrite <- Qmult_assoc.
rewrite Qmult_inj_l with (z := x).
reflexivity.
apply Qnot_eq_sym. apply Qlt_not_eq. apply H0.
}
apply Qplus_inj_l with (z := p + (x * / (2 # 1))).
rewrite Qplus_assoc. rewrite Qplus_opp_r.
rewrite Qplus_0_l. rewrite Qplus_assoc. rewrite Qplus_comm.
rewrite Qplus_comm with (x := p).
rewrite <- Qplus_assoc. rewrite Qplus_opp_r. rewrite Qplus_0_r.
rewrite Qplus_comm.
apply Qplus_inj_l with (z := (x * / (2 # 1))).
rewrite Qplus_opp_r. rewrite Qplus_assoc.
rewrite <- H'. symmetry.
apply Qplus_opp_r.
apply H1.
+ rewrite <- Qplus_0_r.
rewrite <- Qplus_assoc.
rewrite Qplus_lt_r with (z := p).
rewrite Qplus_0_l.
apply Qlt_shift_div_l ; try (reflexivity).
assert (H' : (0 == (0 * (2 # 1)))%Q).
{ reflexivity. }
rewrite <- H'. apply H0.
- intros.
inversion H0.
exists x.
split. apply H1.
unfold not in *.
intros.
apply H1.
apply (Dedekind_properties4 _ DA) with (p := Qplus (-q) (-x)).
apply Qplus_inj_r.
apply Qplus_inj_l with (z := p + q).
rewrite <- Qplus_assoc. rewrite Qplus_opp_r.
rewrite Qplus_0_r.
rewrite <- Qplus_assoc. rewrite Qplus_comm with (x := q).
rewrite Qplus_assoc. rewrite Qplus_opp_r. rewrite Qplus_0_l.
apply H. apply H2.
Qed.
Definition Ropp (a : Real) : Real :=
match a with
| Real_cons A HA => Real_cons (Cut_opp A) (Dedekind_opp A HA)
end.
Notation " - a" := (Ropp a) : R_scope.
Definition Rminus (a b : Real) : Real := (a + (- b))%R.
Notation "A - B" := (Rminus A B) (at level 50, left associativity)
: R_scope.
Instance Ropp_comp : Proper(Req ==> Req)Ropp.
Proof.
split.
- unfold Req, Ropp, Rle in *. destruct x, y. intros.
destruct H. destruct H2, H2.
exists x0. split;auto.
- unfold Req, Ropp, Rle in *. destruct x, y. intros.
destruct H. destruct H2, H2.
exists x0. split;auto.
Qed.
Lemma Cut_cut_opp_not : forall (A : Q -> Prop) (x : Q),
Dedekind A -> A x -> ~ Cut_opp A (- x).
Proof.
unfold not. intros. destruct H1, H1. apply H2.
rewrite Qopp_involutive.
apply (Dedekind_properties2 _ H x).
split; auto.
rewrite Qplus_comm.
rewrite <- Qplus_le_l with (z:=(-x)).
rewrite <- Qplus_assoc. rewrite Qplus_opp_r.
rewrite <- Qplus_le_r with (z:=x0).
rewrite Qplus_assoc. rewrite Qplus_opp_r.
repeat rewrite Qplus_0_r. apply Qlt_le_weak. auto.
Qed.
Lemma mylemma2 : forall (A : Q -> Prop),
Dedekind A ->
(forall m : Z, A (inject_Z m) -> A (inject_Z (m+ 1)))
-> exists x1, forall m1, A (inject_Z (x1 + m1)).
Proof.
intros.
destruct (Dedekind_properties1 _ H ).
destruct H1, H2.
assert(forall x : Q, exists m : Z, inject_Z m <= x).
apply le_inject_Z.
destruct (H3 x).
assert (A (inject_Z x1)). {
apply (Dedekind_properties2 _ H x (inject_Z x1)).
repeat split; auto. } exists x1. apply Zind.
- rewrite Zplus_0_r. auto.
- unfold Z.succ. intros.
assert(inject_Z (x1 + (x2 + 1))=inject_Z (x1 + x2 + 1)).
{ rewrite Zplus_assoc. reflexivity. }
rewrite H7. apply H0. apply H6.
- intros.
apply (Dedekind_properties2 _ H (inject_Z (x1 + x2))).
split; auto.
rewrite <- Zle_Qle. apply Zplus_le_compat_l.
apply Z.le_pred_l.
Qed.
Lemma Zarchimedean : forall (A : Q -> Prop),
Dedekind A ->
(forall m : Z, A (inject_Z m) -> A (inject_Z (m+ 1)))
-> forall m1 : Z, A (inject_Z m1).
Proof.
intros. assert((forall m : Z, A (inject_Z m) -> A (inject_Z (m+ 1)))
-> exists x1, forall m1, A (inject_Z (x1 + m1))).
{ apply mylemma2. auto. }
apply H1 in H0. destruct H0.
assert(A (inject_Z (x+(-x+m1)))).
{ apply (H0 (-x+m1)%Z). }
apply (Dedekind_properties2 _ H (inject_Z (x + (- x + m1)))).
split; auto.
rewrite <- Zle_Qle. rewrite Zplus_assoc.
rewrite Z.add_opp_diag_r. reflexivity.
Qed.
Lemma forall_imply_to_exists_and :
forall (P T :Q -> Prop), forall y : Q, y>0 ->
~(forall (m : Q), P m -> T (m + y)%Q) -> exists m1 : Q, P m1 /\ ~ T (m1 + y)%Q.
Proof.
intros. apply exists_dist. unfold not in *. intros.
apply H0. intros.
assert (P m /\ (T (m + y)%Q -> False) -> False).
apply (H1 m).
apply not_and_or in H3. destruct H3.
- destruct H3. auto.
- apply NNPP. apply H3.
Qed.
Lemma mylemma1 : forall (A : Q -> Prop),
Dedekind A ->
~(forall m : Z, A (inject_Z m) -> A (inject_Z (m+ 1))).
Proof.
unfold not. intros. assert((forall m1 : Z, A (inject_Z m1)) -> False).
{ intros. destruct (Dedekind_properties1 _ H).
destruct H3.
assert(exists m : Z, inject_Z m >= x).
{ apply inject_Z_le. }
destruct H4. apply H3.
apply (Dedekind_properties2 _ H (inject_Z x0)). split.
apply H1.
apply H4. }
apply H1. apply Zarchimedean. auto. auto.
Qed.
Lemma mylemma3 : forall (A : Q -> Prop),
Dedekind A -> forall y : Q, y>0 -> (forall x : Q, A x -> A (x + y))
-> forall (x : Q) (m : Z), A x -> A (x + y*(inject_Z m)).
Proof.
intros. apply (Zind (fun m => A (x + y * inject_Z m))).
- unfold inject_Z. rewrite Qmult_0_r. rewrite Qplus_0_r. auto.
- intros. unfold Z.succ. rewrite inject_Z_plus.
rewrite Qmult_plus_distr_r. rewrite Qplus_assoc.
rewrite Qmult_1_r.
apply (H1 (x + y * inject_Z x0)).
apply H3.
- intros. apply (Dedekind_properties2 _ H (x + y * inject_Z x0)).
split; auto.
rewrite Qmult_comm.
rewrite Qmult_comm with (y:=(inject_Z x0)).
rewrite Qplus_le_r. apply Qmult_le_compat_r.
rewrite <- Zle_Qle. apply Z.le_pred_l.
apply Qlt_le_weak. auto.
Qed.
Lemma mylemma4 : forall (A : Q -> Prop),
Dedekind A -> forall y : Q, y>0 -> (forall x : Q, A x -> A (x + y))
-> forall (x : Q) (m : Z), A (x + y*(inject_Z m)).
Proof.
intros. assert(forall (x : Q) (m : Z), A x -> A (x + y*(inject_Z m))).
{ apply mylemma3. auto. auto. auto. }
destruct (Dedekind_properties1 _ H).
destruct H3.
assert(forall x1:Q, exists m : Z, (inject_Z m) * y > x1).
{ intros. assert(forall p q :Q, p > 0 -> exists n : Q, n*p>q).
{ apply Qarchimedean. } assert(exists n : Q, x1 < n * y).
{ apply (H5 y x1). auto. }
destruct H6. assert(exists m : Z, inject_Z m >= x2).
{ apply inject_Z_le. }
destruct H7. exists x3. apply Qlt_le_trans with (y:=x2 * y).
auto. apply Qmult_le_compat_r. auto. apply Qlt_le_weak. auto. }
destruct (H5 (x + y * inject_Z m - x0)).
apply (H2 x0 x1) in H3.
rewrite <- Qplus_lt_l with (z:=x0) in H6.
rewrite <- (Qplus_assoc (x + y * inject_Z m) (-x0) x0) in H6.
rewrite (Qplus_comm (-x0) x0 ) in H6. rewrite Qplus_opp_r in H6.
apply (Dedekind_properties2 _ H (x0 + y * inject_Z x1)).
split; auto.
apply Qlt_le_weak.
rewrite Qplus_comm with (y:=y * inject_Z x1).
rewrite Qplus_0_r in H6. rewrite Qmult_comm with (y:=inject_Z x1).
auto.
Qed.
Lemma mylemma5 : forall (A : Q -> Prop),
Dedekind A -> forall y : Q, y>0 -> (forall x : Q, A x -> A (x + y))
-> forall (x : Q), A x.
Proof.
intros. assert(forall (x : Q) (m : Z), A (x + y*(inject_Z m))).
{ apply mylemma4. auto. auto. auto. }
assert(A (x + y * 0)). { apply (H2 x 0%Z). }
rewrite Qmult_0_r in H3. rewrite Qplus_0_r in H3. auto.
Qed.
Lemma mylemma6 : forall (A : Q -> Prop),
Dedekind A -> forall y : Q, y>0 ->
~(forall x : Q, A x -> A (x + y)).
Proof.
unfold not. intros. assert((forall (x : Q), A x) -> False).
{ intros. destruct (Dedekind_properties1 _ H).
destruct H4.
destruct H4.
apply mylemma5 with (y:=y). auto. auto. apply H1. }
apply H2. intros. apply mylemma5 with (y:=y). auto. auto. auto.
Qed.
Lemma Dedekind1_strong : forall (A : Q -> Prop),
Dedekind A -> forall y : Q, y>0 -> (exists x:Q, A x /\ ~ A (x + y)).
Proof.
intros.
apply forall_imply_to_exists_and. auto.
apply mylemma6. auto. auto.
Qed.
Theorem Rplus_opp :
forall a : Real, (a + (Ropp a))%R == Rzero.
Proof.
intros.
destruct a.
unfold Req.
simpl. split.
- intros.
repeat destruct H0.
destruct H1.
destruct H1.
destruct H1.
rewrite <- H2.
apply Qplus_lt_l with (z := (-x1)).
rewrite <- Qplus_assoc. rewrite Qplus_opp_r.
rewrite Qplus_0_r. rewrite Qplus_0_l.
apply Qlt_trans with (y := Qplus (-x1) (-x2)).
apply Dedekind_le with A ; auto.
apply Qplus_lt_r with (z := Qplus x2 x1).
rewrite <- Qplus_assoc. rewrite <- Qplus_assoc.
rewrite <- Qplus_comm. rewrite Qplus_assoc.
rewrite Qplus_opp_r. rewrite Qplus_0_l. rewrite Qplus_comm.
rewrite Qplus_opp_r. rewrite Qplus_0_r. apply H1.
- intros.
unfold Cut_plus_Cut.
rename H into DA.
destruct (Dedekind_properties1 _ DA).
destruct H. destruct H1.
assert(H': (exists x2 : Q, A x2 /\ Cut_opp A (x - x2))
-> exists x2 x3 : Q, A x2 /\ Cut_opp A x3 /\ (x2 + x3 == x)%Q).
{ intros.
destruct H2.
exists x2, (Qplus x (-x2)).
split. apply H2.
split. apply H2.
rewrite Qplus_assoc. rewrite <- Qplus_comm. rewrite Qplus_assoc.
rewrite <- (Qplus_comm x2). rewrite Qplus_opp_r. rewrite Qplus_0_l. reflexivity.
}
apply H'. unfold Cut_opp.
assert(exists y:Q, A y /\ ~ A (y +(- x/(2#1)))).
{ apply Dedekind1_strong. auto.
apply Qmult_lt_r with (z:=2#1). reflexivity.
assert(H'':~(2#1==0)%Q). { unfold not. intros. inversion H2. }
apply (Qdiv_mult_l (-x)) in H''.
rewrite <- (Qmult_assoc (-x) (/(2#1)) (2#1)).
rewrite (Qmult_comm (/(2 # 1))).
rewrite (Qmult_assoc (-x) (2#1) (/(2#1))). rewrite H''.
rewrite Qmult_0_l.
rewrite <- (Qplus_0_l (-x)). rewrite <- Qlt_minus_iff. auto. }
destruct H2, H2. exists x2. split. auto.
exists (-x/(2#1)). split.
+ apply Qmult_lt_r with (z:=2#1). reflexivity.
assert(H'':~(2#1==0)%Q). { unfold not. intros. inversion H4. }
apply (Qdiv_mult_l (-x)) in H''.
rewrite <- (Qmult_assoc (-x) (/(2#1)) (2#1)). rewrite (Qmult_comm (/(2 # 1))).
rewrite (Qmult_assoc (-x) (2#1) (/(2#1))). rewrite H''.
rewrite Qmult_0_l.
rewrite <- (Qplus_0_l (-x)). rewrite <- Qlt_minus_iff. auto.
+ unfold not. intros. apply H3.
apply (Dedekind_properties4 _ DA (- (x - x2) + - (- x / (2 # 1)))).
* rewrite <- Qplus_inj_r with (z:= - x / (2 # 1)).
rewrite <- Qplus_assoc.
rewrite (Qplus_comm (- (- x / (2 # 1)))).
rewrite Qplus_opp_r. rewrite <- Qplus_assoc.
rewrite <- (Qdiv2 (-x)).
rewrite Qplus_0_r. rewrite <- Qplus_inj_l with (z:=(x-x2)).
rewrite Qplus_opp_r. rewrite (Qplus_comm x2).
rewrite (Qplus_comm (x) (-x2)).
rewrite <- Qplus_assoc. rewrite Qplus_assoc with (y:=(-x)).
rewrite Qplus_opp_r. rewrite Qplus_0_l.
rewrite Qplus_comm. symmetry. apply Qplus_opp_r.
* auto.
Qed.
Theorem Rplus_l_compat :
forall a b c : Real, b == c -> (a + b == a + c)%R.
Proof.
unfold Req, Rle. destruct a, b, c. simpl. unfold Cut_plus_Cut.
intros.
destruct H2.
split.
- intros.
destruct H4, H4, H4, H5.
exists x0, x1.
split. apply H4.
split. apply H2, H5.
apply H6.
- intros.
destruct H4, H4, H4, H5.
exists x0, x1.
split. apply H4.
split. apply H3, H5.
apply H6.
Qed.
Theorem Rplus_compat_l :
forall a b c : Real, (a + b == a + c)%R -> b == c.
Proof.
intros.
apply Rplus_l_compat with (a:= (-a)%R) in H.
repeat rewrite <- Rplus_assoc in H.
assert (H' : (-a + a)%R == Rzero).
{
rewrite Rplus_comm.
apply Rplus_opp.
}
rewrite H' in H. rewrite <- Rplus_comm in H.
rewrite <- Rplus_comm with (a := c) in H.
repeat rewrite Rplus_0_r in H.
auto.
Qed.
Definition Cut_multPP (A B : Q -> Prop) : Q -> Prop :=
(fun x => (exists x0 x1 : Q, x0>0 /\ x1>0 /\ A x0 /\ B x1 /\ (x <= (x0*x1))))
.
Definition Cut_multNP (A B : Q -> Prop) : Q -> Prop :=
Cut_opp (fun x => (exists x0 x1 : Q, x0>0 /\ x1>0 /\ Cut_opp A x0 /\ B x1 /\ (x <= (x0*x1))))
.
Definition Cut_multPN (A B : Q -> Prop) : Q -> Prop :=
Cut_opp (fun x => (exists x0 x1 : Q, x0>0 /\ x1>0 /\ A x0 /\ Cut_opp B x1 /\ (x <= (x0*x1))))
.
Definition Cut_multNN (A B : Q -> Prop) : Q -> Prop :=
(fun x => (exists x0 x1 : Q, x0>0 /\ x1>0 /\ Cut_opp A x0 /\ Cut_opp B x1 /\ (x <= (x0*x1))))
.
Definition Cut_mult0 (A B : Q -> Prop) : Q -> Prop :=
(fun x => x<0)
.
Definition PP (A B : Q -> Prop) : Prop := (A 0 /\ B 0).
Definition NP (A B : Q -> Prop) : Prop := (Cut_opp A 0 /\ B 0).
Definition PN (A B : Q -> Prop) : Prop := (A 0 /\Cut_opp B 0).
Definition NN (A B : Q -> Prop) : Prop := (Cut_opp A 0 /\ Cut_opp B 0).
Definition ZO (A B : Q -> Prop) : Prop := ((~ A 0 /\ ~ Cut_opp A 0) \/( ~ B 0 /\ ~ Cut_opp B 0)).
Definition Cut_mult : (Q -> Prop) -> (Q -> Prop) -> (Q -> Prop):=
(fun A B x => (PP A B /\ Cut_multPP A B x) \/
(NP A B /\ Cut_multNP A B x) \/
(PN A B /\ Cut_multPN A B x) \/
(NN A B /\ Cut_multNN A B x)\/
(ZO A B /\ Cut_mult0 A B x))
.
Definition Cuteq (A B : Q -> Prop) := forall x : Q, A x <-> B x.
Instance Cut_Setoid : Equivalence Cuteq.
Proof.
split.
- hnf. intros. hnf. intros. reflexivity.
- hnf. intros. hnf in *. intros. split.
+ intros. rewrite H. auto.
+ intros. rewrite <- H. auto.
- hnf. intros. hnf in *. intros. split.
+ intros. apply H0, H, H1.
+ intros. rewrite H, H0. auto.
Qed.
Lemma Cut_opp_opp :
forall (A : Q -> Prop), Dedekind A ->
forall x : Q, A x <-> (Cut_opp (Cut_opp A) x).
Proof.
intros. split.
- intros. hnf. apply (Dedekind_properties3 _ ) in H0.
+ destruct H0. exists (x0 - x). split.
* unfold Qminus. rewrite <- Qlt_minus_iff. apply H0.
* unfold Cut_opp. rewrite exists_dist. apply PPNN. intros.
hnf in *. intros. destruct H1, H2.
apply (Dedekind_properties2 _ H x0). split. apply H0.
assert(- (- x + - (x0 - x)) == x0)%Q.
{ rewrite <- Qplus_opp_assoc. rewrite Qopp_involutive.
unfold Qminus. rewrite Qplus_comm. rewrite <- (Qplus_0_r x0).
rewrite <- Qplus_assoc. rewrite <- Qplus_assoc. rewrite Qplus_inj_l.
rewrite Qplus_assoc. rewrite Qplus_0_l. rewrite Qplus_comm.
apply Qplus_opp_r. }
rewrite H2. rewrite <- Qplus_le_l with (z:=x1).
rewrite <- Qplus_assoc. rewrite Qplus_le_r.
apply Qlt_le_weak. rewrite Qplus_comm. rewrite Qplus_opp_r. auto.
+ auto.
- intros. hnf in H0. destruct H0, H0. hnf in H1. unfold Cut_opp in H1.
rewrite exists_dist in H1. apply NNPP in H1.
assert(~(0<x0/\~ A (- (- x + - x0) + - x0))).
{ apply (H1 x0). } apply not_and_or in H2. destruct H2.
+ destruct H2. auto.
+ apply NNPP in H2.
rewrite <- (Qplus_opp_assoc x x0) in H2. rewrite Qopp_involutive in H2.
rewrite <- Qplus_assoc in H2. rewrite Qplus_opp_r in H2.
rewrite <- Qplus_0_r. auto.
Qed.
Lemma Cut_opp_eq :
forall (A B : Q -> Prop), Dedekind A -> Dedekind B ->
Cuteq A B <-> Cuteq (Cut_opp A) (Cut_opp B).
Proof.
intros. split.
- intros. hnf in *. intros. split.
+ intros. hnf in *. destruct H2, H2.
exists x0. split;auto. hnf in *. intros. apply H3.
apply H1. auto.
+ intros. hnf in *. destruct H2, H2.
exists x0. split;auto. hnf in *. intros. apply H3.
apply H1. auto.
- intros. hnf in *. intros. split.
+ intros. apply Cut_opp_opp. auto. apply Cut_opp_opp in H2.
* destruct (H1 x). hnf in *. destruct H2, H2.
exists x0. split;auto. hnf in *. intros. apply H5.
apply H1. auto. * auto.
+ intros. apply Cut_opp_opp. auto. apply Cut_opp_opp in H2.
* destruct (H1 x). hnf in *. destruct H2, H2.
exists x0. split;auto. hnf in *. intros. apply H5.
apply H1. auto. * auto.
Qed.
(* Instance Cut_mult_comp : Proper(Cuteq ==> Cuteq ==> Qeq ==> iff) Cut_mult.
Proof.
split.
- intros. unfold Cut_mult in *. destruct H2 as [?|[?|[?|[?|[]]]]].
+ left. destruct H2. repeat split.
* apply H, H2.
* apply H0, H2.
* destruct H3, H3. rewrite H1 in H3. destruct H3 as [?[?[?[?]]]].
exists x2, x3. repeat split;auto.
{ apply H. auto. }
{ apply H0. auto. }
+ right; left. destruct H2, H2. repeat split.
* rewrite Cut_opp_eq in H. apply H, H2. auto. auto.
* apply H0, H2.
* destruct H3, H3. rewrite H1 in H3. destruct H3 as [?[?[?[?]]]].
exists x2, x3. repeat split;auto.
{ apply H. auto. }
{ apply H0. auto. }
Admitted. *)
(** To make sure the definition is correct. *)
Lemma Rmult_situation : forall A B, Dedekind A -> Dedekind B ->
(A 0/\B 0)\/
(Cut_opp A 0 /\ B 0)\/
(A 0 /\Cut_opp B 0)\/
(Cut_opp A 0 /\ Cut_opp B 0)\/
(~ A 0 /\ ~ Cut_opp A 0) \/( ~ B 0 /\ ~ Cut_opp B 0).
Proof.
intros.
assert(A 0 \/~ A 0). { apply classic. }
assert(B 0 \/~ B 0). { apply classic. }
assert(Cut_opp A 0 \/~ Cut_opp A 0). { apply classic. }
assert(Cut_opp B 0 \/~ Cut_opp B 0). { apply classic. }
destruct H1, H2.
- left. split. auto. auto.
- destruct H4.
+ right. right. left. split. auto. auto.
+ repeat right. split. auto. auto.
- destruct H3.
+ right. left. split. auto. auto.
+ right. right. right. right. left. split. auto. auto.
- destruct H3.
+ destruct H4.
* right. right. right. left. split. auto. auto.
* repeat right; split; auto.
+ right. right. right. right. left. split. auto. auto.
Qed.
Lemma Cut_mult_comm'' : forall (A B : Q -> Prop) (x : Q),
Cut_mult A B x -> Cut_mult B A x.
Proof.
intros. unfold Cut_mult. intros. destruct H as [ |[|[|[|[]]]] ].
+ destruct H. left. split.
* split. apply H. apply H.
* unfold Cut_multPP in *. destruct H0, H0.
exists x1, x0. destruct H0 as [?[?[?[?]]]]. repeat split; auto.
rewrite Qmult_comm. auto.
+ destruct H. right. right. left. split.
* split. apply H. apply H.
* unfold Cut_multNP in *. unfold Cut_multPN. unfold Cut_opp in *.
destruct H0, H0. exists x0. split. auto.
unfold not. intros. destruct H1. destruct H2, H1.
exists x2, x1. destruct H1 as [?[?[?[?]]]]. repeat split; auto.
rewrite Qmult_comm. auto.
+ destruct H. right. left. split.
* split. apply H. apply H.
* unfold Cut_multNP in *. unfold Cut_multPN. unfold Cut_opp in *.
destruct H0, H0. exists x0. split. auto.
unfold not. intros. destruct H1. destruct H2, H1.
exists x2, x1. destruct H1 as [?[?[?[?]]]]. repeat split; auto.
rewrite Qmult_comm. auto.
+ destruct H. right. right. right. left. split.
* split. apply H. apply H.
* unfold Cut_multNN in *. destruct H0, H0.
exists x1, x0. destruct H0 as [?[?[?[?]]]]. repeat split; auto.
rewrite Qmult_comm. auto.
+ right. right. right. right. split.
* unfold ZO in *. destruct H.
right. apply H.
left. apply H.
* auto.
Qed.
Lemma Cut_mult_comm' : forall (A B : Q -> Prop),
Cuteq (Cut_mult A B) (Cut_mult B A).
Proof.
intros. split.
- apply Cut_mult_comm''.
- apply Cut_mult_comm''.
Qed.
Lemma Cut_mult_comm : forall (A B : Q -> Prop) (x : Q),
Cut_mult A B x <-> Cut_mult B A x.
Proof.
intros. split.
- apply Cut_mult_comm''.
- apply Cut_mult_comm''.
Qed.
Fact Qdiv2_opp : forall x : Q, (- x == - (x * / (2 # 1)) + - (x * / (2 # 1)))%Q.
Proof.
intros.
rewrite <- Qplus_inj_l with (z:=(x / (2 # 1))).
rewrite Qplus_assoc.
rewrite Qplus_opp_r with (q:=(x / (2 # 1))). rewrite Qplus_0_l.
rewrite <- Qplus_inj_l with (z:=(x / (2 # 1))).
rewrite Qplus_assoc.
rewrite Qplus_opp_r with (q:=(x / (2 # 1))).
rewrite <- Qplus_inj_r with (z:=x).
rewrite <- Qplus_assoc. rewrite (Qplus_comm (-x) x ).
rewrite Qplus_opp_r with (q:=x).
rewrite Qplus_0_l. rewrite Qplus_0_r.
symmetry. apply Qdiv2.
Qed.
Fact Qdiv2_x_y : forall x y :Q, x>0 -> y>0 -> x / (2 # 1) * (y / (2 # 1)) <= x * y.
Proof.
unfold Qdiv. intros. rewrite Qmult_assoc.
rewrite (Qmult_comm x (/(2#1))).
rewrite <- (Qmult_assoc (/(2#1)) x y).
rewrite <- (Qmult_comm (x*y) (/(2#1))).
rewrite <- (Qmult_assoc (x*y) (/(2#1)) (/(2#1)) ).
rewrite (Qmult_comm x y). rewrite <- (Qmult_1_r (y*x)).
rewrite <- (Qmult_assoc (y*x) 1 ((/(2#1)) *(/(2#1)))).
apply Qlt_le_weak.
rewrite Qmult_lt_l.
{ reflexivity. }
{ rewrite <- (Qmult_0_l x). apply (Qmult_lt_compat_r 0 y x).
auto. auto. }
Qed.
Lemma Qmult_lt_compat : forall x y z t : Q,
0 <= x -> 0 <= z -> x < y -> z < t -> x * z < y * t .
Proof.
intros. apply Qle_lt_trans with (y:= y*z).
- apply Qmult_le_compat_r. apply Qlt_le_weak. auto. auto.
- rewrite Qmult_comm. rewrite (Qmult_comm y t).
apply Qmult_lt_compat_r.
apply Qle_lt_trans with (y:=x). auto. auto. auto.
Qed.
Theorem Dedekind_mult (A B : Q -> Prop) :
Dedekind A -> Dedekind B -> Dedekind (Cut_mult A B).
Proof.
intros. split.
- split.
+ unfold Cut_mult.
assert(
(A 0/\B 0)\/
(Cut_opp A 0 /\ B 0)\/
(A 0 /\Cut_opp B 0)\/
(Cut_opp A 0 /\ Cut_opp B 0)\/
(~ A 0 /\ ~ Cut_opp A 0) \/( ~ B 0 /\ ~ Cut_opp B 0)).
{ apply Rmult_situation. auto. auto. }
destruct H1. destruct H1.
* destruct (Dedekind_properties3 _ H 0). apply H1.
destruct (Dedekind_properties3 _ H0 0). apply H2.
exists (x*x0). left.
repeat split; auto.
unfold Cut_multPP. exists x, x0. destruct H3, H4.
repeat split; auto. apply Qle_refl.
* destruct H1. ** destruct H1.
assert(Dedekind (Cut_opp A)).
{ apply Dedekind_opp, H. }
destruct (Dedekind_properties1 _ H3). destruct H5.
destruct (Dedekind_properties1 _ H0). destruct H7.
assert(x>0).
{ apply Qnot_le_lt. unfold not in *. intros. apply H5.
apply (Dedekind_properties2 _ H3 0).
split. auto. auto. }
assert(x0>0).
{ apply Qnot_le_lt. unfold not in *. intros. apply H7.
apply (Dedekind_properties2 _ H0 0).
split. auto. auto. }
exists (-((2#1)*x*x0)). right. left. repeat split; auto.
exists (x*x0). split. rewrite <- (Qmult_0_l x0).
apply (Qmult_lt_compat_r 0 x x0). auto. auto.
unfold not. intros.
destruct H10, H10, H10, H11, H12, H13.
assert(x1<x).
{ apply (Dedekind_le (Cut_opp A)). auto. apply H5. auto. }
assert(x2<x0).
{ apply (Dedekind_le B). auto. apply H7. auto. }
rewrite Qopp_involutive in H14.
rewrite <- (Qmult_assoc (2#1) x x0) in H14.
rewrite <- (Qmult_1_l (-(x*x0))) in H14.
assert((1 * (- (x * x0)) == (- 1%Q) * (x * x0))%Q).
{ rewrite Qmult_1_l. reflexivity. }
rewrite H17 in H14.
rewrite <- (Qmult_plus_distr_l (2#1) (-1%Q) (x*x0)) in H14.
assert(((2 # 1) + - (1))==1)%Q. reflexivity.
rewrite H18 in H14. rewrite Qmult_1_l in H14.
apply Qle_not_lt in H14. apply H14.
apply Qmult_lt_compat.
apply Qlt_le_weak; auto. apply Qlt_le_weak; auto. auto. auto.
** destruct H1. *** destruct H1.
assert(Dedekind (Cut_opp B)).
{ apply Dedekind_opp, H0. }
destruct (Dedekind_properties1 _ H3). destruct H5.
destruct (Dedekind_properties1 _ H). destruct H7.
assert(x>0).
{ apply Qnot_le_lt. unfold not in *. intros. apply H5.
apply (Dedekind_properties2 _ H3 0).
split. auto. auto. }
assert(x0>0).
{ apply Qnot_le_lt. unfold not in *. intros. apply H7.
apply (Dedekind_properties2 _ H 0).
split. auto. auto. }
exists (-((2#1)*x*x0)). right. right. left. repeat split; auto.
exists (x*x0). split. rewrite <- (Qmult_0_l x0).
apply (Qmult_lt_compat_r 0 x x0). auto. auto.
unfold not. intros.
destruct H10, H10, H10, H11, H12, H13.
assert(x2<x).
{ apply (Dedekind_le (Cut_opp B)). auto. apply H5. auto. }
assert(x1<x0).
{ apply (Dedekind_le A). auto. apply H7. auto. }
rewrite Qopp_involutive in H14.
rewrite <- (Qmult_assoc (2#1) x x0) in H14.
rewrite <- (Qmult_1_l (-(x*x0))) in H14.
assert((1 * (- (x * x0)) == (- 1%Q) * (x * x0))%Q).
{ rewrite Qmult_1_l. reflexivity. }
rewrite H17 in H14.
rewrite <- (Qmult_plus_distr_l (2#1) (-1%Q) (x*x0)) in H14.
assert(((2 # 1) + - (1))==1)%Q. reflexivity.
rewrite H18 in H14. rewrite Qmult_1_l in H14.
apply Qle_not_lt in H14. apply H14. rewrite Qmult_comm.
apply Qmult_lt_compat.
apply Qlt_le_weak; auto. apply Qlt_le_weak; auto. auto. auto.
*** destruct H1. **** destruct H1.
assert(Dedekind (Cut_opp A)).
{ apply Dedekind_opp, H. }
assert(Dedekind (Cut_opp B)).
{ apply Dedekind_opp, H0. }
destruct (Dedekind_properties3 _ H3 0). apply H1.
destruct (Dedekind_properties3 _ H4 0). apply H2.
exists (x*x0). right. right. right. left.
repeat split; auto.
unfold Cut_multNN. exists x, x0. destruct H5, H6.
repeat split; auto. apply Qle_refl.
**** exists (-1%Q). repeat right. split. auto. reflexivity.
+ assert(
(A 0/\B 0)\/
(Cut_opp A 0 /\ B 0)\/
(A 0 /\Cut_opp B 0)\/
(Cut_opp A 0 /\ Cut_opp B 0)\/
(~ A 0 /\ ~ Cut_opp A 0) \/( ~ B 0 /\ ~ Cut_opp B 0)).
{ apply Rmult_situation. auto. auto. }
destruct H1. * destruct H1.
destruct (Dedekind_properties1 _ H).
destruct (Dedekind_properties1 _ H0).
destruct H4, H6.
exists (x*x0). unfold not, Cut_mult. intros.
destruct H7. { destruct H7, H8, H8, H8, H9, H10, H11.
apply Qle_not_lt in H12. apply H12.
apply Qmult_lt_compat.
apply Qlt_le_weak; auto.
apply Qlt_le_weak; auto.
apply (Dedekind_le A); auto; auto; auto.
apply (Dedekind_le B); auto; auto; auto. }
destruct H7. { destruct H7, H7.
apply Cut_cut_opp_not in H1. apply H1. auto. auto. }
destruct H7. { destruct H7, H7.
apply Cut_cut_opp_not in H2. apply H2. auto. auto. }
destruct H7. { destruct H7, H7.
apply Cut_cut_opp_not in H2. apply H2. auto. auto. }
destruct H7. destruct H7, H7, H7. auto. auto.
* destruct H1. ** destruct H1.
assert(H':Dedekind (Cut_opp A)). { apply Dedekind_opp. auto. }
destruct (Dedekind_properties3 _ H' 0). auto.
destruct (Dedekind_properties3 _ H0 0). auto.
destruct H3, H4.
exists 1. unfold not, Cut_mult. intros.
destruct H7. { destruct H7, H7.
apply (Cut_cut_opp_not A 0) in H.
{ apply H. auto. } auto. }
destruct H7. { destruct H7, H8, H8, H9.
exists x, x0. repeat split; auto.
apply Qle_trans with (y:=0).
{ rewrite <- (Qplus_0_r 0). apply Qplus_le_compat.
{ apply Qlt_le_weak. reflexivity. }
{ rewrite <- (Qopp_involutive 0). apply Qopp_le_compat.
apply Qlt_le_weak. auto. } }
{ repeat apply Qmult_le_0_compat; apply Qlt_le_weak; auto. } }
destruct H7. { apply Cut_cut_opp_not in H2.
{ apply H2. apply H7. } auto. }
destruct H7. { apply Cut_cut_opp_not in H2.
{ apply H2. apply H7. } auto. }
destruct H7, H7. { destruct H7. apply H9, H1. }
{ destruct H7. apply H7, H2. }
** destruct H1. *** destruct H1.
assert(H':Dedekind (Cut_opp B)). { apply Dedekind_opp. auto. }
destruct (Dedekind_properties3 _ H' 0). auto.
destruct (Dedekind_properties3 _ H 0). auto.
destruct H3, H4.
exists 1. rewrite Cut_mult_comm. unfold not, Cut_mult. intros.
destruct H7. { destruct H7, H7.
apply (Cut_cut_opp_not B 0) in H0.
{ apply H0. auto. } auto. }
destruct H7. { destruct H7, H8, H8, H9.
exists x, x0. repeat split; auto.
apply Qle_trans with (y:=0).
{ rewrite <- (Qplus_0_r 0). apply Qplus_le_compat.
{ apply Qlt_le_weak. reflexivity. }
{ rewrite <- (Qopp_involutive 0). apply Qopp_le_compat.
apply Qlt_le_weak. auto. } }
{ repeat apply Qmult_le_0_compat; apply Qlt_le_weak; auto. } }
destruct H7. { apply Cut_cut_opp_not in H1.
{ apply H1. apply H7. } auto. }
destruct H7. { apply Cut_cut_opp_not in H1.
{ apply H1. apply H7. } auto. }
destruct H7, H7. { destruct H7. apply H9, H2. }
{ destruct H7. apply H7, H1. }
*** destruct H1. **** destruct H1.
rename H into H'. rename H0 into H0'.
assert (Dedekind (Cut_opp A)).
{ apply Dedekind_opp. auto. }
assert (Dedekind (Cut_opp B)).
{ apply Dedekind_opp. auto. }
destruct (Dedekind_properties1 _ H).
destruct (Dedekind_properties1 _ H0).
destruct H4, H6.
exists (x*x0). unfold not, Cut_mult. intros.
destruct H7. { destruct H7, H7.
apply Cut_cut_opp_not in H7. apply H7. auto. auto. }
destruct H7. { destruct H7, H7.
apply Cut_cut_opp_not in H9. apply H9. auto. auto. }
destruct H7. { destruct H7, H7.
apply Cut_cut_opp_not in H7. apply H7. auto. auto. }
destruct H7. { destruct H7, H8, H8, H8, H9, H10, H11.
apply Qle_not_lt in H12. apply H12.
apply Qmult_lt_compat.
apply Qlt_le_weak; auto.
apply Qlt_le_weak; auto.
apply (Dedekind_le (Cut_opp A)); auto; auto; auto.
apply (Dedekind_le (Cut_opp B)); auto; auto; auto. }
destruct H7, H7. { destruct H7. apply H9. auto. }
{ destruct H7. apply H9. auto. }
**** exists 0. destruct H1. ***** destruct H1.
unfold Cut_mult, not. intros.
destruct H3. { apply H1, H3. }
destruct H3. { apply H2, H3. }
destruct H3. { apply H1, H3. }
destruct H3. { apply H2, H3. }
destruct H3. inversion H4. ***** destruct H1.
unfold Cut_mult, not. intros.
destruct H3. { apply H1, H3. }
destruct H3. { apply H1, H3. }
destruct H3. { apply H2, H3. }
destruct H3. { apply H2, H3. }
destruct H3. inversion H4.
- intros. destruct H1, H1. *
destruct H1, H3, H3, H3, H4, H5, H6.
left. split; auto. exists x, x0.
repeat split; auto.
apply Qle_trans with (y:=p). auto. auto.
* destruct H1. ** destruct H1, H3, H3.
right; left; split; auto. exists x.
split; auto. unfold not. intros. apply H4.
destruct H5, H5, H5, H6, H7, H8. exists x0, x1.
repeat split; auto.
apply Qle_trans with (y:=-q+-x).
{ rewrite Qplus_le_l. apply Qopp_le_compat. auto. }
{ auto. }
** destruct H1. *** destruct H1, H3, H3.
right; right; left; split; auto. exists x.
split; auto. unfold not. intros. apply H4.
destruct H5, H5, H5, H6, H7, H8. exists x0, x1.
repeat split; auto.
apply Qle_trans with (y:=-q+-x).
{ rewrite Qplus_le_l. apply Qopp_le_compat. auto. }
{ auto. }
*** destruct H1. **** destruct H1, H3, H3, H3, H4, H5, H6.
right; right; right; left; split; auto. exists x, x0.
repeat split; auto. apply Qle_trans with (y:=p). auto. auto.
**** destruct H1.
right; right; right; right; split; auto.
destruct H1, H1. *****
apply Qle_lt_trans with (y:=p). auto. auto.
***** apply Qle_lt_trans with (y:=p). auto. auto.
- intros. destruct H1 as [?|[?|[?|[?|[]]]]].
* destruct H1, H2, H2, H2, H3, H4, H5, H1.
assert(exists r : Q, A r /\ x < r).
{ apply (Dedekind_properties3 _ H). auto. }
assert(exists r : Q, B r /\ x0 < r).
{ apply (Dedekind_properties3 _ H0). auto. }
destruct H9, H9, H8, H8. exists (x2*x1). split.
{ left. repeat split; auto. exists x2, x1.
repeat split.
+ apply Qlt_trans with (y:=x). auto. auto.
+ apply Qlt_trans with (y:=x0). auto. auto.
+ auto.
+ auto.
+ apply Qle_refl. }
apply Qle_lt_trans with (y:=(x*x0)). auto.
apply Qmult_lt_compat.
+ apply Qlt_le_weak. auto.
+ apply Qlt_le_weak. auto.
+ auto.
+ auto.
* destruct H1, H2, H2. exists (p+(x/(2#1))). split.
+ right; left. split; auto.
unfold Cut_multNP, Cut_opp, not. exists (x/(2#1)).
split. { apply Qlt_shift_div_l. reflexivity. auto. }
intros. apply H3. destruct H4, H4, H4, H5, H6, H7.
exists x0, x1. repeat split; auto.
rewrite (Qplus_opp_assoc p (x / (2 # 1))) in H8.
rewrite <- (Qplus_assoc) in H8. unfold Qdiv in H8.
rewrite <- Qdiv2_opp in H8. auto.
+ rewrite Qplus_comm. rewrite <- Qplus_0_l. apply Qplus_lt_le_compat.
{ apply Qlt_shift_div_l. reflexivity. auto. }
{ rewrite Qplus_0_l. apply Qle_refl. }
* destruct H1, H2, H2. exists (p+(x/(2#1))). split.
+ right; right; left. split; auto.
unfold Cut_multPN, Cut_opp, not. exists (x/(2#1)).
split. { apply Qlt_shift_div_l. reflexivity. auto. }
intros. apply H3. destruct H4, H4, H4, H5, H6, H7.
exists x0, x1. repeat split; auto.
rewrite (Qplus_opp_assoc p (x / (2 # 1))) in H8.
rewrite <- (Qplus_assoc) in H8. unfold Qdiv in H8.
rewrite <- Qdiv2_opp in H8. auto.
+ rewrite Qplus_comm. rewrite <- Qplus_0_l. apply Qplus_lt_le_compat.
{ apply Qlt_shift_div_l. reflexivity. auto. }
{ rewrite Qplus_0_l. apply Qle_refl. }
* destruct H1, H2, H2, H2, H3, H4, H5, H1.
rename H into H'. rename H0 into H0'.
assert (Dedekind (Cut_opp A)).
{ apply Dedekind_opp. auto. }
assert (Dedekind (Cut_opp B)).
{ apply Dedekind_opp. auto. }
assert(exists r : Q, (Cut_opp A) r /\ x < r).
{ apply (Dedekind_properties3 _ H). auto. }
assert(exists r : Q, (Cut_opp B) r /\ x0 < r).
{ apply (Dedekind_properties3 _ H0). auto. }
destruct H9, H9, H8, H8. exists (x2*x1). split.
{ right; right; right; left. repeat split; auto. exists x2, x1.
repeat split.
+ apply Qlt_trans with (y:=x). auto. auto.
+ apply Qlt_trans with (y:=x0). auto. auto.
+ auto.
+ auto.
+ apply Qle_refl. }
apply Qle_lt_trans with (y:=(x*x0)). auto.
apply Qmult_lt_compat.
+ apply Qlt_le_weak. auto.
+ apply Qlt_le_weak. auto.
+ auto.
+ auto.
* destruct H1.
{ destruct H1. apply Qdensity in H2. destruct H2.
exists (x). split.
{ repeat right. split. left; auto. apply H2. }
apply H2. }
{ destruct H1. apply Qdensity in H2. destruct H2.
exists (x). split.
{ repeat right. split. right; auto. apply H2. }
apply H2. }
- intros. destruct H2 as [?|[?|[?|[?|[]]]]].
* left. destruct H2. split; auto.
destruct H3, H3. destruct H3 as [?[?[?[?]]]].
exists x, x0. repeat split; auto. rewrite <- H1. auto.
* right; left. destruct H2. split; auto.
destruct H3, H3. exists x. split; auto.
unfold not. intros. apply H4. destruct H5, H5. destruct H5 as [?[?[?[?]]]].
exists x0, x1. repeat split; auto. rewrite H1. auto.
* right; right; left. destruct H2. split; auto.
destruct H3, H3. exists x. split; auto.
unfold not. intros. apply H4. destruct H5, H5. destruct H5 as [?[?[?[?]]]].
exists x0, x1. repeat split; auto. rewrite H1. auto.
* right; right; right; left. destruct H2. split; auto.
destruct H3, H3. destruct H3 as [?[?[?[?]]]].
exists x, x0. repeat split; auto. rewrite <- H1. auto.
* repeat right. split; auto. unfold Cut_mult0. rewrite <- H1. auto.
Qed.
Definition Rmult (a b :Real) : Real :=
match a with
| Real_cons A HA => match b with
| Real_cons B HB =>
Real_cons (Cut_mult A B) (Dedekind_mult A B HA HB)
end
end.
Notation "A * B" := (Rmult A B) (at level 40, left associativity)
: R_scope.
Lemma NP0_false : forall (A B : Q -> Prop),
Dedekind A -> Dedekind B -> NP A B -> Cut_multNP A B 0 -> False.
Proof.
intros. destruct H1. destruct H2, H2, H4.
apply Dedekind_opp in H.
apply (Dedekind_properties3 _) in H1.
apply (Dedekind_properties3 _) in H3.
{ destruct H1, H1, H3, H3. exists x0, x1.
repeat split;auto. apply Qlt_le_weak. rewrite Qplus_0_l.
apply Qlt_trans with (y:=0). { rewrite Qlt_minus_iff.
rewrite Qopp_involutive. rewrite Qplus_0_l. auto. }
rewrite <- (Qmult_0_l 0).
repeat apply (Qmult_lt_compat 0 x0 0 x1).
apply Qle_refl. apply Qle_refl. auto. auto. }
auto. auto.
Qed.
Lemma PN0_false : forall (A B : Q -> Prop),
Dedekind A -> Dedekind B -> PN A B -> Cut_multPN A B 0 -> False.
Proof.
intros. destruct H1. destruct H2, H2, H4.
apply Dedekind_opp in H0.
apply (Dedekind_properties3 _) in H1.
apply (Dedekind_properties3 _) in H3.
{ destruct H1, H1, H3, H3. exists x0, x1.
repeat split;auto. apply Qlt_le_weak. rewrite Qplus_0_l.
apply Qlt_trans with (y:=0). { rewrite Qlt_minus_iff.
rewrite Qopp_involutive. rewrite Qplus_0_l. auto. }
rewrite <- (Qmult_0_l 0).
repeat apply (Qmult_lt_compat 0 x0 0 x1).
apply Qle_refl. apply Qle_refl. auto. auto. }
auto. auto.
Qed.
Lemma Cut_mult_situation1 :
forall C : Q -> Prop,C 0 \/ Cut_opp C 0 \/ (~ C 0/\~ Cut_opp C 0).
Proof.
intros.
assert(C 0 \/ ~ C 0). apply classic.
assert(Cut_opp C 0 \/ ~ Cut_opp C 0). apply classic.
destruct H, H0.
- left;auto.
- left;auto.
- right;left;auto.
- right;right. split. auto. auto.
Qed.
Lemma PPmult : forall A B : Q -> Prop, Dedekind A -> Dedekind B -> A 0 -> B 0 -> Cut_mult A B 0.
Proof.
intros. left. repeat split;auto.
apply (Dedekind_properties3 _) in H1.
apply (Dedekind_properties3 _) in H2.
- destruct H1, H1, H2, H2. exists x, x0.
repeat split;auto.
rewrite <- (Qmult_0_l 0).
apply Qlt_le_weak.
repeat apply (Qmult_lt_compat 0 x 0 x0);auto;apply Qle_refl.
- auto.
- auto.
Qed.
Lemma and_or_not5 : forall A B C D E : Prop,
~(A\/B\/C\/D\/E) <-> ~ A/\~B/\~C/\~D/\~E.
Proof.
intros. split.
- intros. unfold not in *. repeat split;intros;apply H;auto.
- intros. destruct H as [?[?[?[]]]].
unfold not in *. intros.
destruct H4. apply H, H4.
destruct H4. apply H0, H4.
destruct H4. apply H1, H4.
destruct H4. apply H2, H4.
apply H3, H4.
Qed.
Lemma Cut_mult_opp' : forall A B : Q -> Prop, forall x : Q, Dedekind A -> Dedekind B ->
Cut_opp (Cut_mult A B) x -> Cut_mult A (Cut_opp B) x.
Proof.
intros. unfold Cut_mult in *. destruct H1, H1.
assert(
(A 0/\B 0)\/
(Cut_opp A 0 /\ B 0)\/
(A 0 /\Cut_opp B 0)\/
(Cut_opp A 0 /\ Cut_opp B 0)\/
(~ A 0 /\ ~ Cut_opp A 0) \/( ~ B 0 /\ ~ Cut_opp B 0)).
{ apply Rmult_situation. auto. auto. }
rewrite and_or_not5 in H2.
destruct H2 as [?[?[?[]]]].
destruct H3 as [?|[?|[?|[?|[]]]]].
- right. right. left. destruct H3. repeat split. auto.
rewrite <- Cut_opp_opp. auto. auto.
exists x0. split;auto. apply not_and_or in H2.
destruct H2.
{ destruct H2. repeat split; auto. }
{ unfold not in *. intros. destruct H9, H9. rewrite <- Cut_opp_opp in H9.
apply H2. exists x1, x2. auto. auto. }
- right;right;right;left. destruct H3. repeat split. auto.
rewrite <- Cut_opp_opp. auto. auto. apply not_and_or in H4.
destruct H4.
{ destruct H4. repeat split; auto. }
{ unfold Cut_multNP in *. unfold Cut_opp in *.
rewrite exists_dist in H4. apply NNPP in H4.
assert(~0 < x0 \/
~ ~
(exists x2 x3 : Q,
0 < x2 /\
0 < x3 /\
(exists r : Q, 0 < r /\ ~ A (- x2 + - r)) /\ B x3 /\ - (- x + - x0) + - x0 <= x2 * x3)).
{ apply not_and_or. apply (H4 x0). } destruct H9. destruct H9. auto.
apply NNPP in H9. destruct H9, H9. rewrite (Cut_opp_opp B) in H9.
exists x1, x2. rewrite Qplus_opp_assoc in H9.
rewrite <- Qplus_assoc in H9. rewrite (Qplus_comm (--x0) (-x0)) in H9.
rewrite Qplus_opp_r in H9. rewrite Qplus_0_r in H9.
rewrite Qopp_involutive in H9. auto. auto. }
- left. destruct H3. repeat split; auto. apply not_and_or in H5.
destruct H5.
{ destruct H5. repeat split; auto. }
{ unfold Cut_multPN in *. unfold Cut_opp in *.
rewrite exists_dist in H5. apply NNPP in H5.
assert(~0 < x0 \/
~ ~
(exists x2 x3 : Q,
0 < x2 /\
0 < x3 /\
A x2 /\ (exists r : Q, 0 < r /\ ~ B (- x3 + - r)) /\ - (- x + - x0) + - x0 <= x2 * x3)).
{ apply not_and_or. apply (H5 x0). } destruct H9. destruct H9. auto.
apply NNPP in H9. destruct H9, H9. rewrite (Cut_opp_opp A) in H9.
exists x1, x2. rewrite Qplus_opp_assoc in H9.
rewrite <- Qplus_assoc in H9. rewrite (Qplus_comm (--x0) (-x0)) in H9.
rewrite Qplus_opp_r in H9. rewrite Qplus_0_r in H9.
rewrite Qopp_involutive in H9. rewrite <- (Cut_opp_opp A) in H9. auto. auto. auto. }
- right. left. destruct H3. repeat split; auto.
exists x0. split;auto. apply not_and_or in H6.
destruct H6.
{ destruct H6. repeat split; auto. }
{ unfold not in *. intros. destruct H9, H9. apply H6.
exists x1, x2. auto. }
- repeat right. split. left. auto.
apply not_and_or in H7. destruct H7.
{ destruct H7. left. auto. }
{ unfold Cut_mult0 in *. rewrite <- Qplus_lt_r with (z:=x) in H7.
rewrite Qplus_assoc in H7. rewrite Qplus_0_r in H7.
rewrite Qplus_opp_r in H7. rewrite Qplus_0_l in H7.
apply Qnot_lt_le in H7. apply Qle_lt_trans with (y:=-x0).
auto. apply Qopp_lt_compat in H1. auto. }
- repeat right. split. right. rewrite <- Cut_opp_opp.
destruct H3. repeat split; auto. auto.
apply not_and_or in H7. destruct H7.
{ destruct H7. right. auto. }
{ unfold Cut_mult0 in *. rewrite <- Qplus_lt_r with (z:=x) in H7.
rewrite Qplus_assoc in H7. rewrite Qplus_0_r in H7.
rewrite Qplus_opp_r in H7. rewrite Qplus_0_l in H7.
apply Qnot_lt_le in H7. apply Qle_lt_trans with (y:=-x0).
auto. apply Qopp_lt_compat in H1. auto. }
Qed.
Lemma Cut_mult_opp_r : forall A B : Q -> Prop, forall x : Q, Dedekind A -> Dedekind B ->
Cut_opp (Cut_mult A B) x <-> Cut_mult A (Cut_opp B) x.
Proof.
intros. split.
- apply Cut_mult_opp'. auto. auto.
- intros. destruct H1 as [?|[?|[?|[]]]].
+ destruct H1, H1, H2, H2, H3, H3.
destruct H2 as [?[?[?[?]]]].
apply (Dedekind_properties3 _ H) in H6.
assert(H':Dedekind B). auto.
apply Dedekind_opp in H0.
apply (Dedekind_properties3 _ H0) in H7.
destruct H6, H6, H7, H7.
exists (-x+x3*x4)%Q. split.
{ rewrite <- Qplus_lt_r with (z:=x). rewrite Qplus_assoc.
rewrite Qplus_opp_r. rewrite Qplus_0_l. rewrite Qplus_0_r.
apply Qle_lt_trans with (y:=x0*x1). auto.
repeat apply Qmult_lt_compat;try apply Qlt_le_weak;auto. }
unfold not. intros.
destruct H11 as [?|[?|[?|[]]]].
* destruct H11, H11.
apply (Cut_cut_opp_not B 0) in H'. destruct H'.
exists x2. repeat split;auto. auto.
* destruct H11, H11.
apply (Cut_cut_opp_not A 0) in H. destruct H.
auto. auto.
* destruct H11, H12, H12, H13. exists x3, x4.
repeat split;auto.
apply Qlt_trans with (y:= x0). auto. auto.
apply Qlt_trans with (y:= x1). auto. auto. rewrite Qplus_opp_assoc.
repeat try rewrite Qopp_involutive.
rewrite <- Qplus_assoc. rewrite <- Qplus_assoc.
rewrite Qplus_assoc. rewrite Qplus_assoc.
rewrite Qplus_opp_r. rewrite Qplus_0_l. rewrite <- (Qplus_0_r (x3*x4)).
rewrite <- Qplus_assoc. rewrite Qplus_le_r with (z:=x3*x4).
apply Qlt_le_weak. rewrite Qplus_0_l.
apply Qopp_lt_compat in H12. auto.
* destruct H11, H11.
apply (Cut_cut_opp_not A 0) in H. destruct H.
auto. auto.
* destruct H11, H11, H11, H11. auto.
destruct H13. exists x2. repeat split;auto.
+ destruct H1, H1, H2, H2.
exists (x0)%Q. split. auto.
unfold not. intros. apply H4.
destruct H5 as [?|[?|[?|[]]]].
* destruct H5, H5.
apply (Cut_cut_opp_not B 0) in H0. destruct H0.
auto. auto.
* destruct H5, H5.
apply (Cut_cut_opp_not B 0) in H0. destruct H0.
auto. auto.
* destruct H5, H5.
apply (Cut_cut_opp_not A 0) in H. destruct H.
auto. auto.
* destruct H5, H6, H6. exists x1, x2.
auto.
* destruct H5, H5, H5. destruct H7. auto.
destruct H7. auto.
+ destruct H1, H1, H2, H2.
exists (x0)%Q. split. auto.
unfold not. intros. apply H4.
destruct H5 as [?|[?|[?|[]]]].
* destruct H5, H5, H6, H6. exists x1, x2.
rewrite <- (Cut_opp_opp B). auto. auto.
* destruct H5, H5.
apply (Cut_cut_opp_not A 0) in H. destruct H.
auto. auto.
* destruct H5, H5.
apply (Cut_cut_opp_not B 0) in H0. destruct H0.
auto. rewrite <- (Cut_opp_opp B) in H3. auto. auto.
* destruct H5, H5.
apply (Cut_cut_opp_not A 0) in H. destruct H.
auto. auto.
* destruct H5, H5, H5. destruct H5. auto.
destruct H5. rewrite <- (Cut_opp_opp B) in H3. auto. auto.
+ destruct H1, H1, H2, H2. rewrite <- (Cut_opp_opp B) in *.
{ destruct H2 as [?[?[?[?]]]].
apply (Dedekind_properties3 _ H0) in H6.
assert(H':Dedekind A). auto.
apply Dedekind_opp in H.
apply (Dedekind_properties3 _ H) in H5.
destruct H6, H6, H5, H5.
exists (-x+x3*x2)%Q. split.
{ rewrite <- Qplus_lt_r with (z:=x). rewrite Qplus_assoc.
rewrite Qplus_opp_r. rewrite Qplus_0_l. rewrite Qplus_0_r.
apply Qle_lt_trans with (y:=x0*x1). auto.
repeat apply Qmult_lt_compat;try apply Qlt_le_weak;auto. }
unfold not. intros.
destruct H10 as [?|[?|[?|[]]]].
* destruct H10, H10.
apply (Cut_cut_opp_not A 0) in H'. destruct H'.
auto. auto.
* destruct H10, H11, H11, H12. exists x3, x2.
repeat split;auto.
apply Qlt_trans with (y:= x0). auto. auto.
apply Qlt_trans with (y:= x1). auto. auto. rewrite Qplus_opp_assoc.
repeat try rewrite Qopp_involutive.
rewrite <- Qplus_assoc. rewrite <- Qplus_assoc.
rewrite Qplus_assoc. rewrite Qplus_assoc.
rewrite Qplus_opp_r. rewrite Qplus_0_l. rewrite <- (Qplus_0_r (x3*x2)).
rewrite <- Qplus_assoc. rewrite Qplus_le_r with (z:=x3*x2).
apply Qlt_le_weak. rewrite Qplus_0_l.
apply Qopp_lt_compat in H11. auto.
* destruct H10, H10.
apply (Cut_cut_opp_not A 0) in H'. destruct H'.
auto. auto.
* destruct H10, H10.
apply (Cut_cut_opp_not B 0) in H0. destruct H0.
auto. auto.
* destruct H10, H10, H10.
destruct H12. auto. destruct H10. auto. } auto. auto.
+ destruct H1, H1.
{ exists (-x)%Q. split.
apply Qopp_lt_compat in H2. auto. destruct H1.
unfold not. intros. destruct H4 as [?|[?|[?|[]]]].
* destruct H4, H4, H1. auto.
* destruct H4, H4, H3. auto.
* destruct H4, H4, H1. auto.
* destruct H4, H4, H3. auto.
* destruct H4, H4. unfold Cut_mult0 in H5.
rewrite (Qplus_opp_r (-x)) in H5. inversion H5.
destruct H4, H4. unfold Cut_mult0 in H5.
rewrite (Qplus_opp_r (-x)) in H5. inversion H5. }
{ exists (-x)%Q. split.
apply Qopp_lt_compat in H2. auto. destruct H1.
unfold not. intros. destruct H4 as [?|[?|[?|[]]]].
* destruct H4, H4, H3. rewrite <- Cut_opp_opp. auto. auto.
* destruct H4, H4, H3. rewrite <- Cut_opp_opp. auto. auto.
* destruct H4, H4, H1. auto.
* destruct H4, H4, H1. auto.
* destruct H4, H4. unfold Cut_mult0 in H5.
rewrite (Qplus_opp_r (-x)) in H5. inversion H5.
destruct H4, H4. unfold Cut_mult0 in H5.
rewrite (Qplus_opp_r (-x)) in H5. inversion H5. }
Qed.
Lemma Cut_mult_opp_l : forall A B : Q -> Prop, forall x : Q, Dedekind A -> Dedekind B ->
Cut_opp (Cut_mult A B) x <-> Cut_mult (Cut_opp A) B x.
Proof.
intros. rewrite Cut_mult_comm.
assert(forall x : Q, Cut_opp (Cut_mult A B) x <-> Cut_opp (Cut_mult B A) x).
{ rewrite <- (Cut_opp_eq (Cut_mult A B) (Cut_mult B A)).
split; rewrite Cut_mult_comm;auto.
apply Dedekind_mult. auto. auto.
apply Dedekind_mult. auto. auto. }
split.
- intros. apply H1 in H2. apply Cut_mult_opp_r. auto. auto. auto.
- intros. apply H1. apply Cut_mult_opp_r. auto. auto. auto.
Qed.
Lemma Cut_mult0_trans : forall B C : Q -> Prop,
Dedekind B -> Dedekind C -> ZO B C -> ~ Cut_mult B C 0 /\ ~ Cut_opp (Cut_mult B C) 0.
Proof.
intros. rename H into DB. rename H0 into DC. unfold not. destruct H1, H. { split. { intros.
destruct H1 as [?|[?|[?|[?|[]]]]].
{ destruct H1, H1, H. auto. }
{ destruct H1, H1, H0. auto. }
{ destruct H1, H1, H. auto. }
{ destruct H1, H1, H0. auto. }
{ inversion H2. } } rewrite Cut_mult_opp_l by auto. intros.
destruct H1 as [?|[?|[?|[?|[]]]]].
{ destruct H1, H1, H0. auto. }
{ destruct H1, H1, H. apply Cut_opp_opp. auto. auto. }
{ destruct H1, H1, H0. auto. }
{ destruct H1, H1, H. apply Cut_opp_opp. auto. auto. }
{ inversion H2. } }
{ rewrite Cut_mult_comm. split. { intros.
destruct H1 as [?|[?|[?|[?|[]]]]].
{ destruct H1, H1, H. auto. }
{ destruct H1, H1, H0. auto. }
{ destruct H1, H1, H. auto. }
{ destruct H1, H1, H0. auto. }
{ inversion H2. } } rewrite Cut_mult_opp_r by auto. rewrite Cut_mult_comm. intros.
destruct H1 as [?|[?|[?|[?|[]]]]].
{ destruct H1, H1, H0. auto. }
{ destruct H1, H1, H. apply Cut_opp_opp. auto. auto. }
{ destruct H1, H1, H0. auto. }
{ destruct H1, H1, H. apply Cut_opp_opp. auto. auto. }
{ inversion H2. } }
Qed.
Lemma Cut_mult_eq : forall (A B C : Q -> Prop), Dedekind A -> Dedekind B -> Dedekind C ->
(forall x : Q, B x <-> C x) -> (forall x : Q, Cut_mult A B x <-> Cut_mult A C x).
Proof.
intros.
assert(forall (A B C : Q -> Prop), Dedekind A -> Dedekind B -> Dedekind C ->
(forall x : Q, B x <-> C x) -> (forall x : Q, Cut_mult A B x -> Cut_mult A C x)).
{ clear A B C H H0 H1 H2 x. intros. destruct H3 as [?|[?|[?|[]]]].
+ left. destruct H3, H3. split.
* split;auto. apply H2. auto.
* destruct H4, H4. exists x0, x1. rewrite <- H2. auto.
+ right; left. destruct H3, H3. split.
* split;auto. apply H2. auto.
* destruct H4, H4. exists x0. split;auto. unfold not. intros.
destruct H6, H7, H6. exists x1, x2. rewrite H2. auto.
+ right;right;left. destruct H3, H3. apply Cut_opp_eq in H2;auto. split.
* split;auto. apply H2. auto.
* destruct H4, H4. exists x0. split;auto. unfold not. intros.
destruct H6, H7, H6. exists x1, x2. rewrite (H2 x2). auto.
+ right;right;right;left. destruct H3, H3. apply Cut_opp_eq in H2;auto. split.
* split;auto. apply H2. auto.
* destruct H4, H4. exists x0, x1. rewrite <- (H2 x1). auto.
+ repeat right. destruct H3, H3, H3.
* split. left;auto. auto.
* split. right. unfold not; split;intros.
destruct H3. apply H2;auto.
apply Cut_opp_eq in H2;auto.
destruct H5. apply H2;auto. auto. }
split;apply H3;auto. intros. split;apply H2;auto.
Qed.
Lemma Cut_mult_opp_opp_l : forall (A B : Q -> Prop) (x : Q),
Dedekind A -> Dedekind B ->
Cut_opp (Cut_opp (Cut_mult A B)) x <->
Cut_opp (Cut_mult (Cut_opp A) B) x.
Proof.
intros. generalize dependent x.
rewrite <- (Cut_opp_eq (Cut_opp (Cut_mult A B)) (Cut_mult (Cut_opp A) B)).
{ hnf. intros. rewrite Cut_mult_opp_l by auto. reflexivity. }
{ apply Dedekind_opp;apply Dedekind_mult;auto. }
{ apply Dedekind_mult;try apply Dedekind_opp;auto. }
Qed.
Lemma Cut_mult_opp_opp_r : forall (A B : Q -> Prop) (x : Q),
Dedekind A -> Dedekind B ->
Cut_opp (Cut_opp (Cut_mult A B)) x <->
Cut_opp (Cut_mult A (Cut_opp B)) x.
Proof.
intros. generalize dependent x.
rewrite <- (Cut_opp_eq (Cut_opp (Cut_mult A B)) (Cut_mult A (Cut_opp B))).
{ hnf. intros. rewrite Cut_mult_opp_r by auto. reflexivity. }
{ apply Dedekind_opp;apply Dedekind_mult;auto. }
{ apply Dedekind_mult;try apply Dedekind_opp;auto. }
Qed.
Lemma Cut_mult_assoc_lemma1 : forall (A B C : Q -> Prop) (x : Q),
Dedekind A -> Dedekind B -> Dedekind C -> A 0 -> B 0 -> C 0 ->
Cut_mult (Cut_mult A B) C x -> Cut_mult A (Cut_mult B C) x.
Proof.
intros.
assert(HAB:Dedekind (Cut_mult A B)).
{ apply Dedekind_mult. auto. auto. }
assert(HBC:Dedekind (Cut_mult B C)).
{ apply Dedekind_mult. auto. auto. }
unfold Cut_mult in *.
assert(H':Cut_mult A B 0).
{ apply PPmult. auto. auto. auto. auto. }
destruct H5 as [?|[?|[?|[?|[]]]]].
- destruct H5, H5. destruct H6, H6, H6, H8, H9, H10. destruct H9 as [?|[?|[?|[?|[]]]]].
+ left. split.
* destruct H9, H9. split; auto. left. repeat split; auto.
apply (Dedekind_properties3 _) in H13.
apply (Dedekind_properties3 _) in H7.
{ destruct H13, H13, H7, H7. exists x2, x3.
repeat split;auto. rewrite <- (Qmult_0_l 0).
apply Qlt_le_weak.
repeat apply (Qmult_lt_compat 0 x2 0 x3);auto;apply Qle_refl. }
auto. auto.
* destruct H9, H9. destruct H12, H12, H12, H14, H15, H16.
exists x2, (x3*x1). repeat split;auto.
{ rewrite <- (Qmult_0_l 0).
apply (Qmult_lt_compat 0 x3 0 x1);auto;apply Qle_refl. }
{ left. repeat split;auto. exists x3, x1.
repeat split;auto;apply Qle_refl. }
{ apply Qle_trans with (y:=x0*x1). auto.
rewrite Qmult_assoc. rewrite Qmult_le_r. auto. auto. }
+ destruct H9, H9. apply (Cut_cut_opp_not A 0) in H.
destruct H. auto. auto.
+ destruct H9, H9. apply (Cut_cut_opp_not B 0) in H0.
destruct H0. auto. auto.
+ destruct H9, H9. apply (Cut_cut_opp_not A 0) in H.
destruct H. auto. auto.
+ destruct H9, H9, H9. auto. auto.
- destruct H5, H5.
apply (Cut_cut_opp_not (Cut_mult A B) 0) in HAB.
destruct HAB. auto. auto.
- destruct H5, H5.
apply (Cut_cut_opp_not C 0) in H1.
destruct H1. auto. auto.
- destruct H5, H5.
apply (Cut_cut_opp_not C 0) in H1.
destruct H1. auto. auto.
- destruct H5, H5, H5. auto. auto.
Qed.
Lemma Cut_mult_assoc_lemma2 : forall (A B C : Q -> Prop) (x : Q),
Dedekind A -> Dedekind B -> Dedekind C -> A 0 -> Cut_opp B 0 -> C 0 ->
Cut_mult (Cut_mult A B) C x -> Cut_mult A (Cut_mult B C) x.
Proof.
intros.
assert(HAB:Dedekind (Cut_mult A B)).
{ apply Dedekind_mult. auto. auto. }
assert(HBC:Dedekind (Cut_mult B C)).
{ apply Dedekind_mult. auto. auto. }
unfold Cut_mult. right; right; left. rename H2 into AP.
rename H3 into BN. rename H4 into CP.
assert(H':Cut_opp (Cut_mult B C) 0).
{ rewrite Cut_mult_opp_l. assert(H':C 0). auto.
assert(H'':Cut_opp B 0). auto.
apply (Dedekind_properties3 _) in CP.
apply (Dedekind_properties3 _) in BN.
{ destruct CP, H2, BN, H4. left.
repeat split;auto.
exists x1, x0. repeat split;auto.
apply Qlt_le_weak.
repeat apply (Qmult_lt_compat 0 x1 0 x0);auto;apply Qle_refl. }
apply Dedekind_opp. auto. auto. auto. auto. }
assert(H'':Cut_opp (Cut_mult A B) 0).
{ rewrite Cut_mult_opp_r. assert(H''':A 0). auto.
assert(H'':Cut_opp B 0). auto.
apply (Dedekind_properties3 _) in AP.
apply (Dedekind_properties3 _) in BN.
{ destruct AP, H2, BN, H4. left.
repeat split;auto.
exists x0, x1. repeat split;auto.
apply Qlt_le_weak.
repeat apply (Qmult_lt_compat 0 x0 0 x1);auto;apply Qle_refl. }
apply Dedekind_opp. auto. auto. auto. auto. }
destruct H5 as [?|[?|[?|[?|[]]]]].
- destruct H2, H2.
apply (Cut_cut_opp_not (Cut_mult A B) 0) in H2.
destruct H2. auto. apply Dedekind_mult. auto. auto.
- destruct H2, H3, H3. split.
* split. auto. auto.
* exists x0. split;auto. unfold not. intros. destruct H4, H5, H4.
destruct H4 as [?[?[?[]]]]. apply Cut_mult_opp_l in H7.
{ destruct H7 as [?|[?|[?|[]]]].
{ destruct H7, H9, H9. destruct H9 as [?[?[?[]]]].
exists (x1*x3), x4. rewrite Cut_mult_opp_r by (apply (H0, H)).
repeat split;auto.
{ apply Qlt_mult0. auto. auto. }
{ left. repeat split;auto. exists x1, x3. repeat split;auto.
apply Qle_refl. }
{ apply Qle_trans with (y:=x1*x2). auto. rewrite <- Qmult_assoc.
apply Qmult_le_compat_l. auto. apply Qlt_le_weak. auto. } }
{ destruct H7, H7. apply (Cut_cut_opp_not (Cut_opp B) 0) in BN.
destruct BN. auto. apply Dedekind_opp. auto. }
{ destruct H7, H7. apply (Cut_cut_opp_not C 0) in CP.
destruct CP. auto. auto. }
{ destruct H7, H7. apply (Cut_cut_opp_not C 0) in CP.
destruct CP. auto. auto. }
{ destruct H7, H7, H7. destruct H7. auto. destruct H7. auto. } }
auto. auto.
- destruct H2, H2.
apply (Cut_cut_opp_not (Cut_mult A B) 0) in H2.
destruct H2. auto. apply Dedekind_mult. auto. auto.
- destruct H2, H2.
apply (Cut_cut_opp_not C 0) in CP.
destruct CP. auto. auto.
- destruct H2, H2. destruct H4. auto. destruct H2. auto.
Qed.
Lemma Cut_mult_assoc_lemma3 : forall (A B C : Q -> Prop) (x : Q),
Dedekind A -> Dedekind B -> Dedekind C -> A 0 -> Cut_opp C 0 -> B 0 ->
Cut_mult (Cut_mult A B) C x -> Cut_mult A (Cut_mult B C) x.
Proof.
intros.
assert(HAB:Dedekind (Cut_mult A B)).
{ apply Dedekind_mult. auto. auto. }
assert(HBC:Dedekind (Cut_mult B C)).
{ apply Dedekind_mult. auto. auto. }
assert(HA:Dedekind (Cut_opp A)).
{ apply Dedekind_opp. auto. }
assert(HB:Dedekind (Cut_opp B)).
{ apply Dedekind_opp. auto. }
assert(HC:Dedekind (Cut_opp C)).
{ apply Dedekind_opp. auto. }
apply Cut_opp_opp;try apply Dedekind_mult;auto.
apply Cut_mult_opp_opp_r;auto.
rewrite Cut_mult_opp_r;try apply Dedekind_opp;auto.
apply Cut_mult_eq with (B:=(Cut_mult (Cut_opp B) (Cut_opp C)));
auto;try apply Dedekind_mult;try apply Dedekind_opp;
try apply Dedekind_opp;auto.
intros. rewrite <- Cut_mult_opp_l;auto.
rewrite Cut_mult_opp_opp_r;try reflexivity;auto.
rewrite Cut_opp_opp in H4 by auto.
apply Cut_opp_opp in H5;try apply Dedekind_mult;auto.
apply Cut_mult_opp_opp_l with (x:=x) in H5;auto.
rewrite Cut_mult_opp_r in H5;try apply Dedekind_opp;auto.
rewrite Cut_mult_comm in H5.
apply Cut_mult_eq with (B:=(Cut_mult A (Cut_opp B))) in H5;
auto;try apply Dedekind_mult;try apply Dedekind_opp;
try apply Dedekind_opp;auto.
{ rewrite Cut_mult_comm in H5.
apply Cut_mult_assoc_lemma2;auto. }
intros. rewrite <- Cut_mult_opp_r;auto;reflexivity.
Qed.
Lemma Cut_mult_assoc : forall (A B C : Q -> Prop) (x : Q),
Dedekind A -> Dedekind B -> Dedekind C ->
Cut_mult (Cut_mult A B) C x -> Cut_mult A (Cut_mult B C) x.
Proof.
intros.
assert(HAB:Dedekind (Cut_mult A B)).
{ apply Dedekind_mult. auto. auto. }
assert(HBC:Dedekind (Cut_mult B C)).
{ apply Dedekind_mult. auto. auto. }
assert(HC:C 0 \/ Cut_opp C 0 \/ (~ C 0/\~ Cut_opp C 0)).
{ apply Cut_mult_situation1. }
assert(HA:A 0 \/ Cut_opp A 0 \/ (~ A 0/\~ Cut_opp A 0)).
{ apply Cut_mult_situation1. }
assert(HB:B 0 \/ Cut_opp B 0 \/ (~ B 0/\~ Cut_opp B 0)).
{ apply Cut_mult_situation1. }
destruct HC as [CP|[CN|[C0]]].
{ destruct HA as [AP|[AN|[A0]]].
{ destruct HB as [BP|[BN|[B0]]].
{ apply Cut_mult_assoc_lemma1;auto. }
{ apply Cut_mult_assoc_lemma2;auto. }
{ repeat right. split. { right. apply Cut_mult0_trans; auto;left;split;auto. }
assert(~ Cut_mult A B 0 /\ ~ Cut_opp (Cut_mult A B) 0).
{ apply Cut_mult0_trans; auto;right;split;auto. } destruct H4.
destruct H2 as [?|[?|[?|[?|[]]]]].
{ destruct H2, H2, H4. auto. }
{ destruct H2, H2, H5. auto. }
{ destruct H2, H2, H4. auto. }
{ destruct H2, H2, H5. auto. }
{ apply H6. } } }
{ destruct HB as [?|[]].
{ apply Cut_opp_opp;try apply Dedekind_mult;auto.
apply Cut_mult_opp_opp_l;auto. rewrite Cut_mult_opp_r.
{ apply Cut_mult_eq with (B:=(Cut_mult (Cut_opp B) C));try apply Dedekind_opp;
try apply Dedekind_mult;try apply Dedekind_opp;auto.
intros. rewrite Cut_mult_opp_l. reflexivity. auto. auto.
rewrite Cut_opp_opp in H3 by auto.
apply Cut_opp_opp in H2;try apply Dedekind_mult;auto.
apply Cut_mult_opp_opp_l with (x:=x) in H2;auto.
rewrite Cut_mult_opp_l in H2. { rewrite Cut_mult_comm in H2.
apply Cut_mult_eq with (B:=(Cut_mult (Cut_opp A) (Cut_opp B))) in H2;
auto;try apply Dedekind_mult;try apply Dedekind_opp;
try apply Dedekind_opp;auto.
{ rename H3 into BN. rename AN into AP. rewrite Cut_mult_comm in H2.
apply Dedekind_opp in H0. apply Dedekind_opp in H.
apply Cut_mult_assoc_lemma2;auto. }
intros. rewrite <- Cut_mult_opp_l.
rewrite Cut_mult_opp_opp_r;try reflexivity;auto. auto.
apply Dedekind_opp;auto. }
apply Dedekind_opp;apply Dedekind_mult;auto. auto. }
apply Dedekind_opp;auto. apply Dedekind_mult;auto. }
{ apply Cut_opp_opp;try apply Dedekind_opp;try apply Dedekind_mult;auto.
apply Cut_mult_opp_opp_l;try apply Dedekind_mult;auto.
apply Cut_mult_opp_r;try apply Dedekind_opp;auto.
apply Cut_mult_eq with (B:=((Cut_mult (Cut_opp B) C)));
try auto;try apply Dedekind_mult;try apply Dedekind_opp;auto;
try apply Dedekind_mult;try apply Dedekind_opp;auto.
{ intros;rewrite Cut_mult_opp_l;auto;reflexivity. }
rewrite Cut_mult_comm in H2.
apply Cut_mult_eq with (B:=(Cut_mult (Cut_opp A) (Cut_opp B))) in H2;
auto;try apply Dedekind_mult;try apply Dedekind_opp;
try apply Dedekind_opp;auto. rewrite Cut_mult_comm in H2. {
rename AN into AP. rename H3 into BP. clear HAB HBC.
apply Dedekind_opp in H0. apply Dedekind_opp in H.
assert(HAB:Dedekind (Cut_mult (Cut_opp A) (Cut_opp B))).
{ apply Dedekind_mult. auto. auto. }
assert(HBC:Dedekind (Cut_mult (Cut_opp B) C)).
{ apply Dedekind_mult. auto. auto. }
apply Cut_mult_assoc_lemma1;auto. }
intros. rewrite <- Cut_mult_opp_l;try rewrite <- Cut_mult_opp_opp_r;
try rewrite <- Cut_opp_opp;try apply Dedekind_opp;auto.
reflexivity. }
{ destruct H3. repeat right. split. { right. apply Cut_mult0_trans; auto;left;split;auto. }
assert(~ Cut_mult A B 0 /\ ~ Cut_opp (Cut_mult A B) 0).
{ apply Cut_mult0_trans; auto;right;split;auto. } destruct H5.
destruct H2 as [?|[?|[?|[?|[]]]]].
{ destruct H2, H2, H5. auto. }
{ destruct H2, H2, H6. auto. }
{ destruct H2, H2, H5. auto. }
{ destruct H2, H2, H6. auto. }
{ apply H7. } } }
repeat right. split. { left. split;auto. }
assert(~ Cut_mult A B 0 /\ ~ Cut_opp (Cut_mult A B) 0).
{ apply Cut_mult0_trans; auto;left;split;auto. } destruct H4.
destruct H2 as [?|[?|[?|[?|[]]]]].
{ destruct H2, H2, H4. auto. }
{ destruct H2, H2, H5. auto. }
{ destruct H2, H2, H4. auto. }
{ destruct H2, H2, H5. auto. }
{ apply H6. } }
{ destruct HA as [?|[]].
{ destruct HB as [?|[]].
{ apply Cut_mult_assoc_lemma3;auto. }
{ assert(HB:Dedekind (Cut_opp B)).
{ apply Dedekind_opp. auto. }
assert(HC:Dedekind (Cut_opp C)).
{ apply Dedekind_opp. auto. }
apply Cut_opp_opp;try apply Dedekind_mult;auto.
apply Cut_mult_opp_opp_r;auto.
apply Cut_mult_opp_r;try apply Dedekind_opp;auto.
apply Cut_mult_eq with (B:=(Cut_mult (Cut_opp B) (Cut_opp C)));
try apply Dedekind_mult;try repeat apply Dedekind_opp;auto.
{ intros. rewrite <- Cut_mult_opp_r;auto.
rewrite <- Cut_mult_opp_opp_l;auto. reflexivity. }
apply Cut_opp_opp in H2;try apply Dedekind_mult;auto.
apply Cut_mult_opp_opp_l in H2;auto.
apply Cut_mult_opp_r in H2;try apply Dedekind_opp;auto.
apply Cut_mult_comm in H2.
apply Cut_mult_eq with (B:=(Cut_mult A (Cut_opp B))) in H2;
try apply Dedekind_mult;try repeat apply Dedekind_opp;auto.
{ apply Cut_mult_assoc_lemma1;try apply Cut_mult_comm;auto. }
{ intros. rewrite <- Cut_mult_opp_r;auto. reflexivity. } }
{ clear H3. destruct H4. repeat right. split. { right. apply Cut_mult0_trans; auto;left;split;auto. }
assert(~ Cut_mult A B 0 /\ ~ Cut_opp (Cut_mult A B) 0).
{ apply Cut_mult0_trans; auto;right;split;auto. } destruct H5.
destruct H2 as [?|[?|[?|[?|[]]]]].
{ destruct H2, H2, H5. auto. }
{ destruct H2, H2, H6. auto. }
{ destruct H2, H2, H5. auto. }
{ destruct H2, H2, H6. auto. }
{ apply H7. } } }
{ destruct HB as [?|[]].
{ assert(HA:Dedekind (Cut_opp A)).
{ apply Dedekind_opp. auto. }
assert(HC:Dedekind (Cut_opp C)).
{ apply Dedekind_opp. auto. }
apply Cut_opp_opp;try apply Dedekind_mult;auto.
apply Cut_mult_opp_opp_r;auto.
apply Cut_mult_opp_l;try apply Dedekind_opp;auto.
apply Cut_mult_eq with (B:=(Cut_mult B (Cut_opp C)));
try apply Dedekind_mult;try repeat apply Dedekind_opp;auto.
{ intros. rewrite <- Cut_mult_opp_r;auto. reflexivity. }
apply Cut_opp_opp in H2;try apply Dedekind_mult;auto.
apply Cut_mult_opp_opp_l in H2;auto.
apply Cut_mult_opp_r in H2;try apply Dedekind_opp;auto.
apply Cut_mult_comm in H2.
apply Cut_mult_eq with (B:=(Cut_mult (Cut_opp A) B)) in H2;
try apply Dedekind_mult;try repeat apply Dedekind_opp;auto.
{ apply Cut_mult_assoc_lemma1;try apply Cut_mult_comm;auto. }
{ intros. rewrite Cut_mult_opp_l;auto. reflexivity. } }
{ assert(HA:Dedekind (Cut_opp A)).
{ apply Dedekind_opp. auto. }
assert(HC:Dedekind (Cut_opp C)).
{ apply Dedekind_opp. auto. }
assert(HB:Dedekind (Cut_opp B)).
{ apply Dedekind_opp. auto. }
apply Cut_opp_opp;try apply Dedekind_mult;auto.
apply Cut_mult_opp_opp_r;auto.
apply Cut_mult_opp_l;try apply Dedekind_opp;auto.
apply Cut_mult_eq with (B:=(Cut_mult (Cut_opp B) C));
try apply Dedekind_mult;try repeat apply Dedekind_opp;auto.
{ intros. rewrite <- Cut_mult_opp_l;auto. reflexivity. }
apply Cut_opp_opp in H2;try apply Dedekind_mult;auto.
apply Cut_mult_opp_opp_l in H2;auto.
apply Cut_mult_opp_l in H2;try apply Dedekind_opp;auto.
apply Cut_mult_comm in H2.
apply Cut_mult_eq with (B:=(Cut_mult (Cut_opp A) (Cut_opp B))) in H2;
try apply Dedekind_mult;try repeat apply Dedekind_opp;auto.
{ apply Cut_mult_assoc_lemma3;try apply Cut_mult_comm;auto. }
{ intros. rewrite <- Cut_mult_opp_r;auto.
rewrite <- Cut_mult_opp_opp_l;auto. reflexivity. } }
{ repeat right. split. right. apply Cut_mult0_trans;try left;auto.
destruct H4.
assert(~ Cut_mult A B 0 /\ ~ Cut_opp (Cut_mult A B) 0).
{ apply Cut_mult0_trans; auto;right;split;auto. } destruct H6.
destruct H2 as [?|[?|[?|[?|[]]]]].
{ destruct H2, H2, H6;auto. }
{ destruct H2, H2, H7;auto. }
{ destruct H2, H2, H6;auto. }
{ destruct H2, H2, H7;auto. }
{ apply H8. } } }
{ repeat right. split. left. auto.
destruct H3.
assert(~ Cut_mult A B 0 /\ ~ Cut_opp (Cut_mult A B) 0).
{ apply Cut_mult0_trans; auto;left;split;auto. } destruct H5.
destruct H2 as [?|[?|[?|[?|[]]]]].
{ destruct H2, H2, H5;auto. }
{ destruct H2, H2, H6;auto. }
{ destruct H2, H2, H5;auto. }
{ destruct H2, H2, H6;auto. }
{ apply H7. } } }
{ repeat right. split. right. apply Cut_mult0_trans;try right;auto.
assert(~ Cut_mult B C 0 /\ ~ Cut_opp (Cut_mult B C) 0).
{ apply Cut_mult0_trans; auto;right;split;auto. } destruct H4.
destruct H2 as [?|[?|[?|[?|[]]]]].
{ destruct H2, H2, C0;auto. }
{ destruct H2, H2, C0;auto. }
{ destruct H2, H2, H3;auto. }
{ destruct H2, H2, H3;auto. }
{ apply H6. } }
Qed.
Lemma R_mult_comp1 : forall x x0 y y0 : Real, (x==y -> x0==y0 -> x*x0<=y*y0)%R.
Proof.
intros.
unfold Rmult, Rle. destruct x, y, x0, y0. intros.
unfold Cut_mult in *.
assert(forall x : Q, Cut_opp A x <-> Cut_opp A0 x).
{ rewrite <- (Cut_opp_eq A A0). split. apply H. apply H. auto. auto. }
assert(forall x : Q, Cut_opp A1 x <-> Cut_opp A2 x).
{ rewrite <- (Cut_opp_eq A1 A2). split. apply H0. apply H0. auto. auto. }
destruct H5 as [?|[?|[?|[?|[]]]]].
+ left. destruct H5. repeat split.
* unfold Req, Rle in H. apply H, H5.
* unfold Req, Rle in H0. apply H0, H5.
* destruct H8, H8. destruct H8 as [?[?[?[?]]]].
exists x0, x1. repeat split;auto.
{ apply H. auto. }
{ apply H0. auto. }
+ right; left. destruct H5, H5. repeat split.
* unfold Req, Rle in H. apply H6, H5.
* apply H0, H9.
* destruct H8, H8. exists x0. split;auto. unfold not in *.
intros. apply H10. destruct H11, H11. destruct H11 as [?[?[?[?]]]].
exists x1, x2. repeat split;auto.
{ apply H6, H13. }
{ apply H0. auto. }
+ right; right; left. destruct H5, H5. repeat split.
* apply H, H5.
* apply H7, H9.
* destruct H8, H8. exists x0. split;auto. unfold not in *.
intros. apply H10. destruct H11, H11. destruct H11 as [?[?[?[?]]]].
exists x1, x2. repeat split;auto.
{ apply H. auto. }
{ apply H7, H14. }
+ right; right; right; left. destruct H5, H5. repeat split.
* apply H6; auto.
* apply H7; auto.
* destruct H8, H8. destruct H8 as [?[?[?[?]]]].
exists x0, x1. repeat split;auto.
{ apply H6; auto. }
{ apply H7; auto. }
+ repeat right. destruct H5.
{ destruct H5. split.
{ left. unfold not in *. split.
{ intros. apply H5, H. auto. }
{ intros. apply H9, H6. auto. } }
auto. }
{ destruct H5. split.
{ right. unfold not in *. split.
{ intros. apply H5, H0. auto. }
{ intros. apply H9, H7. auto. } }
auto. }
Qed.
Instance R_mult_comp : Proper(Req ==> Req ==> Req) Rmult.
Proof.
split.
- apply R_mult_comp1. auto. auto.
- apply R_mult_comp1. rewrite H. reflexivity.
rewrite H0. reflexivity.
Qed.
Lemma Ropp_opp : forall a : Real, (a == - - a)%R.
Proof.
intros. unfold Req, Ropp, Rle. destruct a. split.
- apply Cut_opp_opp. auto.
- intros. apply Cut_opp_opp. auto. auto.
Qed.
Lemma Rmult_opp_r : forall a b : Real, (- (a * b) == a * (-b))%R.
Proof.
intros. assert(forall a b : Real, (- (a * b) <= a * - b)%R).
{ intros. unfold Rle, Rmult, Ropp. destruct a0, b0. intros. apply Cut_mult_opp'. auto. auto. auto. }
split.
- unfold Rle, Rmult, Ropp. destruct a, b. intros. apply Cut_mult_opp'. auto. auto. auto.
- assert((a * (- - b) == (a * b))%R).
{ intros. rewrite <- (Ropp_opp b). reflexivity. }
rewrite Ropp_opp. rewrite <- H0. unfold Rle, Rmult, Ropp.
destruct a, b. intros. destruct H3, H3. exists x0.
split;auto. unfold not. intros. apply H4.
apply Cut_mult_opp_r;auto. apply Dedekind_opp;auto.
Qed.
(** Third , we will define the plus operation of Set and Real
and proof some theorem about it. *)
Theorem Rmult_0_r : forall a : Real, (a * Rzero == Rzero)%R.
Proof.
intros. unfold Rmult. destruct a. unfold Rzero.
unfold Cut_mult, Req. split.
- unfold Rle. intros.
destruct H0.
* destruct H0, H0. inversion H2.
* destruct H0. ** destruct H0, H0. inversion H2.
** destruct H0. *** destruct H0, H0, H2, H2.
rewrite Qlt_minus_iff in H3.
rewrite Qplus_0_l in H3. rewrite Qplus_0_l in H3.
rewrite Qopp_involutive in H3.
exfalso. apply H3, H2.
*** destruct H0. **** destruct H0, H0, H2, H2.
rewrite Qlt_minus_iff in H3.
rewrite Qplus_0_l in H3. rewrite Qplus_0_l in H3.
rewrite Qopp_involutive in H3.
exfalso. apply H3, H2.
**** destruct H0. unfold Cut_mult0 in H1. apply H1.
- unfold Rle. intros. repeat right. split.
+ right. split.
* unfold not. intros. inversion H1.
* unfold not. intros. destruct H1, H1.
rewrite Qlt_minus_iff in H2.
rewrite Qplus_0_l in H2. rewrite Qplus_0_l in H2.
rewrite Qopp_involutive in H2.
exfalso. apply H2, H1.
+ apply H0.
Qed.
Lemma Cut_Cut_opp : forall (A : Q -> Prop) (x : Q),
Dedekind A -> ~ A x -> (forall x0, x0 > 0 -> Cut_opp A (-x-x0)).
Proof.
intros. hnf. exists x0. split. auto.
assert(- (- x - x0) + - x0 == x)%Q.
{ rewrite (Qmult_plus_distr_r (-1%Q) (-x) (-x0)).
assert(-(1)*(-x0)==--x0)%Q.
{ reflexivity. } rewrite H2. rewrite Qopp_involutive.
rewrite <- Qplus_assoc.
rewrite Qplus_opp_r. rewrite Qplus_0_r. rewrite Qopp_involutive. reflexivity. }
rewrite H2. auto.
Qed.
Lemma Rzero_opp : (Rzero == - Rzero)%R.
Proof.
apply (Rplus_compat_l Rzero). rewrite Rplus_opp.
rewrite Rplus_0_r. reflexivity.
Qed.
Theorem Rmult_1_r : forall a : Real, (a * Rone == a)%R.
Proof.
intros. unfold Rmult, Req, Rone. destruct a.
unfold Cut_mult. split.
- unfold Rle. intros.
destruct H0.
* unfold Cut_multPP in H0.
destruct H0, H0, H1, H1, H1, H3, H4, H5.
apply (Dedekind_properties2 _ H x0). split. auto.
apply (Qle_trans x (x0*x1) x0). auto.
rewrite <- (Qmult_1_r x0). rewrite <- Qmult_assoc.
rewrite Qmult_1_l. rewrite Qmult_comm. rewrite (Qmult_comm x0 1).
apply Qmult_le_compat_r.
apply Qlt_le_weak. auto.
apply Qlt_le_weak. auto.
* destruct H0. ** destruct H0, H0, H1, H1.
assert(A x \/ ~ A x). { apply classic. }
destruct H4. auto.
exfalso. apply H3. assert (H':Dedekind A). auto.
apply Dedekind_opp in H.
apply (Dedekind_properties3 _ H 0) in H0.
destruct H0. destruct H0.
assert(- x + - x0 > 0).
{ apply Qnot_le_lt. unfold not in *. intros. apply H3.
exists x1, (1#2). repeat split; auto.
apply Qle_trans with (y:= 0). auto.
rewrite <- (Qmult_0_r 0). apply Qlt_le_weak.
apply Qmult_lt_compat. apply Qle_refl.
apply Qle_refl. auto. reflexivity. }
exists (- x + - (x0/(2#1))%Q), ((- x + - x0)/(- x + - (x0/(2#1))%Q)).
assert(0< - x + - (x0 / (2 # 1))).
{ apply Qplus_lt_l with (z:=- (x0 / (2 # 1))).
apply Qplus_lt_l with (z:=(x0 / (2 # 1))).
rewrite <- (Qplus_assoc (-x) (- (x0 / (2 # 1))) (- (x0 / (2 # 1))) ).
rewrite <- (Qdiv2_opp x0).
rewrite <- Qplus_assoc.
rewrite (Qplus_comm (- (x0 / (2 # 1))) (x0 / (2 # 1)) ).
rewrite Qplus_opp_r.
apply Qplus_lt_le_compat. auto.
apply Qmult_le_0_compat. apply Qlt_le_weak, H1.
apply Qlt_le_weak. reflexivity. }
repeat split.
+ auto.
+ rewrite <- (Qmult_0_r 0). apply Qmult_lt_compat.
apply Qle_refl. apply Qle_refl. auto.
apply Qlt_shift_inv_l. auto.
rewrite Qmult_0_l. reflexivity.
+ apply Cut_Cut_opp. auto. auto.
apply Qlt_shift_div_l. auto. apply H1.
+ apply Qlt_shift_div_r. auto.
rewrite (Qdiv2_opp x0). rewrite Qplus_assoc.
rewrite Qplus_comm. rewrite Qmult_1_l.
rewrite <- (Qplus_0_l (- x + - (x0 / (2 # 1)))).
rewrite Qplus_lt_l. rewrite Qlt_minus_iff.
rewrite Qopp_involutive. rewrite Qplus_0_l.
apply Qlt_shift_div_l. auto. apply H1.
+ assert((- x + - (x0 / (2 # 1))) * ((- x + - x0) / (- x + - (x0 / (2 # 1))))==(- x + - x0))%Q.
{ rewrite Qmult_comm.
rewrite <- (Qmult_assoc ((- x + - x0)) (/ (- x + - (x0 / (2 # 1)))) ((- x + - (x0 / (2 # 1))))).
rewrite (Qmult_comm (/ (- x + - (x0 / (2 # 1)))) ).
rewrite Qmult_assoc. apply Qdiv_mult_l.
hnf. intros. apply Qlt_not_eq in H7. apply H7. rewrite H8.
reflexivity. }
rewrite H8. apply Qle_refl.
** destruct H0. *** destruct H0, H0, H1, H1, H2, H2, H4.
rewrite Qplus_0_l. apply Qlt_trans with (y:=0).
+ rewrite Qlt_minus_iff. rewrite Qopp_involutive.
rewrite Qplus_0_l. auto.
+ reflexivity.
*** destruct H0. **** destruct H0, H0, H2, H2, H3.
rewrite Qplus_0_l. apply Qlt_trans with (y:=0).
+ rewrite Qlt_minus_iff. rewrite Qopp_involutive.
rewrite Qplus_0_l. auto.
+ reflexivity.
**** destruct H0. destruct H0, H0.
+ unfold Cut_mult0 in H1. unfold Cut_opp in H2.
rewrite exists_dist in H2. apply NNPP in H2.
assert(~ (0 < - x /\ ~ A (- 0 + - - x))). apply (H2 (-x)).
apply not_and_or in H3. destruct H3.
{ destruct H3. rewrite <- (Qplus_0_l (-x)).
rewrite <- Qlt_minus_iff. auto. }
{ apply NNPP in H3. rewrite Qopp_involutive in H3.
rewrite <- Qplus_0_l. auto. }
+ destruct H0. reflexivity.
- unfold Rle. intros.
assert( (A 0/\(fun x0 : Q => x0 < 1) 0)\/
(Cut_opp A 0 /\ (fun x0 : Q => x0 < 1) 0)\/
(A 0 /\Cut_opp (fun x0 : Q => x0 < 1) 0)\/
(Cut_opp A 0 /\ Cut_opp (fun x0 : Q => x0 < 1) 0)\/
(~ A 0 /\ ~ Cut_opp A 0) \/( ~ (fun x0 : Q => x0 < 1) 0 /\ ~ Cut_opp (fun x0 : Q => x0 < 1) 0)).
{ apply Rmult_situation with (B:=(fun x0 : Q => x0 < 1)).
auto. apply (Dedekind_Q 1). }
destruct H1. * left. split.
+ auto.
+ unfold Cut_multPP. apply (Dedekind_properties3 _ H) in H0.
assert(0 < x\/~0 < x). apply classic.
destruct H0, H0, H2. assert (0 < x0).
{ apply Qlt_trans with (y:=x). auto. auto. }
{ exists x0, (x/x0). split. auto. split.
{ apply Qlt_shift_div_l. auto.
{ rewrite Qmult_0_l. auto. } } split.
{ auto. } split.
{ apply Qlt_shift_div_r. auto. rewrite Qmult_1_l. auto. }
rewrite Qmult_div_r. apply Qle_refl. unfold not.
intros. rewrite H5 in H4. inversion H4. }
{ destruct H1. apply (Dedekind_properties3 _ H) in H1.
destruct H1, H1. exists x1, (1#2).
repeat split;auto.
apply Qnot_lt_le in H2. apply Qle_trans with (y:=0).
auto. apply Qmult_le_0_compat. apply Qlt_le_weak. auto.
rewrite (Qmake_Qdiv 1 2).
apply Qle_shift_div_l. reflexivity.
rewrite Qmult_0_l. apply Qlt_le_weak. reflexivity. }
* destruct H1. ** right. left. split.
+ auto.
+ unfold Cut_multNP, Cut_opp.
assert(0 <= x\/~0 <= x). apply classic.
destruct H1, H2.
{ destruct H1, H1, H4. apply (Dedekind_properties2 _ H x).
split. auto. rewrite Qplus_0_l.
apply Qle_trans with (y:=0).
rewrite <- (Qopp_involutive 0). apply Qopp_le_compat.
apply Qlt_le_weak. auto.
auto. }
{ apply Qnot_le_lt in H2. destruct H1.
assert(exists x1 : Q, A x1 /\ x < x1).
{ apply (Dedekind_properties3 _ H). auto. }
destruct H4, H4.
exists (x1 - x). split. { unfold Qminus.
rewrite <- (Qlt_minus_iff x x1). auto. }
unfold not. intros.
destruct H6, H6, H6, H7, H8, H8, H8, H9.
unfold Qminus in *. rewrite Qplus_opp_assoc in H11.
rewrite Qplus_assoc in H11. rewrite Qplus_comm in H11.
rewrite Qplus_assoc in H11. rewrite Qopp_involutive in H11.
rewrite Qplus_opp_r in H11. rewrite Qplus_0_l in H11.
apply Qle_not_lt in H11. apply H11.
apply Qlt_trans with (y:=(x2)).
{ rewrite <- (Qmult_1_r x2).
rewrite <- Qmult_assoc. rewrite Qmult_lt_l with (z:=x2).
{ rewrite Qmult_1_l. auto. } auto. }
assert(Cut_opp A x2). { exists x4. repeat split; auto. }
assert(~ Cut_opp A (-x1)). { apply Cut_cut_opp_not. auto. auto. }
apply (Dedekind_le (Cut_opp A)). apply Dedekind_opp. auto. auto. auto. }
** destruct H1. *** destruct H1. right. right. left.
repeat split; auto. destruct H2, H2, H3.
rewrite Qplus_0_l. apply Qlt_trans with (y:=0).
+ rewrite Qlt_minus_iff. rewrite Qopp_involutive.
rewrite Qplus_0_l. auto.
+ reflexivity.
*** destruct H1. **** destruct H1. right. right. right. left.
repeat split; auto. destruct H2, H2, H3.
rewrite Qplus_0_l. apply Qlt_trans with (y:=0).
+ rewrite Qlt_minus_iff. rewrite Qopp_involutive.
rewrite Qplus_0_l. auto.
+ reflexivity.
**** destruct H1.
+ repeat right. split. { left. auto. }
unfold Cut_mult0. destruct H1. apply (Dedekind_le A).
auto. auto. auto.
+ destruct H1. destruct H1. reflexivity.
Qed.
Theorem Rmult_comm : forall a b : Real, (a * b == b * a)%R.
Proof.
intros. destruct a, b. unfold Req, Rle, Rmult. split.
- intros. apply Cut_mult_comm. auto.
- intros. apply Cut_mult_comm. auto.
Qed.
Lemma Rmult_opp_l : forall a b : Real, (- (a * b) == - a * b)%R.
Proof.
intros. rewrite -> Rmult_comm. rewrite -> (Rmult_comm (-a)%R).
apply Rmult_opp_r.
Qed.
Theorem Rmult_0_l : forall a : Real, (Rzero * a == Rzero)%R.
Proof.
intros. rewrite Rmult_comm. apply Rmult_0_r.
Qed.
Theorem Rmult_1_l : forall a : Real, (Rone * a == a)%R.
Proof.
intros. rewrite Rmult_comm. apply Rmult_1_r.
Qed.
Theorem Rmult_assoc_lemma : forall a b c : Real, (a * b * c <= a * (b * c))%R.
Proof.
intros. unfold Req, Rmult, Rle. destruct a, b, c.
intros. apply Cut_mult_assoc;auto.
Qed.
Theorem Rmult_assoc : forall a b c : Real, (a * b * c == a * (b * c))%R.
Proof.
intros. split.
- apply Rmult_assoc_lemma.
- intros. rewrite Rmult_comm.
apply Rle_trans with (y:=(b*(c*a))%R);try apply Rmult_assoc_lemma.
rewrite (Rmult_comm (a*b)%R c). rewrite Rmult_comm.
apply Rle_trans with (y:=(c*(a*b))%R);try apply Rmult_assoc_lemma.
apply Rle_refl.
Qed.
Lemma Dedekind_up : forall (A : Q -> Prop)(x1 x2:Q), Dedekind A ->
A x1 -> A x2 -> exists x : Q, A x /\ x1<x /\ x2<x.
Proof.
intros. apply (Dedekind_properties3 _ H) in H0.
apply (Dedekind_properties3 _ H) in H1. destruct H0, H0, H1, H1.
assert (x0 > x\/~x0 > x). apply classic. destruct H4.
- exists x0. repeat split;auto.
apply Qlt_trans with (y:=x);auto.
- apply Qnot_lt_le in H4. exists x. repeat split;auto.
apply Qlt_le_trans with (y:=x0);auto.
Qed.
(* Lemma distr_lemma1 : forall (A B : Q -> Prop), Dedekind A -> Dedekind B ->
forall x2, (B x2 -> exists x1 : Q, A x1/\
Cut_mult A B (x1*x2)).
Proof.
Admitted. (*wrong*) *)
Lemma Cut_mult_distr_PP :
forall (A B C : Q -> Prop)(x : Q)(DA : Dedekind A)(DB: Dedekind B)(DC:Dedekind C),
A 0 -> B 0 -> C 0 ->
Cut_mult A (Cut_plus_Cut B C) x <-> Cut_plus_Cut (Cut_mult A B) (Cut_mult A C) x
.
Proof.
intros. split.
- intros.
destruct H2 as [?|[?|[?|[]]]].
+ destruct H2, H2, H4, H4, H3, H3.
destruct H4 as [?[]]. destruct H3 as [?[?[?[]]]].
destruct H9, H9. destruct H9 as [?[]].
assert(H':Dedekind (Cut_plus_Cut (Cut_mult A B) (Cut_mult A C))).
{ apply Dedekind_plus; apply Dedekind_mult;auto. }
pose proof (Dedekind_up B 0 x4). destruct H13;auto. destruct H13 as [?[]].
pose proof (Dedekind_up C 0 x5). destruct H16;auto. destruct H16 as [?[]].
apply (Dedekind_properties2 _ H' (x2*(x6+x7)));split;
try apply Qle_trans with (y:=x2*x3);auto;try apply Qlt_le_weak;
try apply Qmult_lt_l;auto;try rewrite <- H12;try apply Qplus_lt_le_compat;
try apply Qlt_le_weak;auto.
exists (x2*x6), (x2*x7).
repeat split;try rewrite <- H12;try rewrite Qmult_plus_distr_r;try reflexivity;
left;repeat split;auto.
* exists x2, x6. repeat split;auto;apply Qle_refl.
* exists x2, x7. repeat split;auto;apply Qle_refl.
+ destruct H2, H2. apply (Cut_cut_opp_not A 0) in H;auto;
destruct H;auto.
+ destruct H2, H2, H4, H4, H5. exists 0, (-x0). repeat split;auto.
apply (Dedekind_properties2 _ DC 0);split;auto.
rewrite Qopp_le_compat_iff. rewrite Qopp_involutive;apply Qlt_le_weak;auto.
+ destruct H2, H2. apply (Cut_cut_opp_not A 0) in H;auto;
destruct H;auto.
+ destruct H2, H2, H2, H2;auto. exists 0, 0. repeat split;auto.
- intros. destruct H2, H2. destruct H2 as [?[]].
pose proof (Cut_cut_opp_not A 0 DA H). rename H5 into AN.
pose proof (Cut_cut_opp_not C 0 DC H1). rename H5 into CN.
pose proof (Cut_cut_opp_not B 0 DB H0). rename H5 into BN.
destruct H2 as [?|[?|[?|[]]]].
+ destruct H2, H5, H5. destruct H5 as [?[?[?[]]]].
destruct H3 as [?|[?|[?|[]]]].
{ destruct H3, H10, H10.
destruct H10 as [?[?[?[]]]].
left. pose proof (Dedekind_plus B C DB DC). repeat split;auto.
{ apply (Dedekind_properties2 _ H15 (x3+x5)). split.
{ exists x3, x5. repeat split;auto. }
{ apply Qlt_le_weak. rewrite <- Qplus_0_r.
apply Qplus_lt_le_compat;auto;apply Qlt_le_weak;auto. } }
pose proof (Dedekind_up A x2 x4 DA H7 H12). destruct H16 as [?[?[]]].
exists x6, (x3+x5). repeat split.
* apply Qlt_trans with (y:=x2);auto.
* rewrite <- Qplus_0_r.
apply Qplus_lt_le_compat;auto;apply Qlt_le_weak;auto.
* auto.
* exists x3,x5. repeat split;auto.
* rewrite <- H4. rewrite Qmult_plus_distr_r. apply Qplus_le_compat.
{ apply Qle_trans with (y:=x2*x3);auto;apply Qmult_le_compat_r;
apply Qlt_le_weak;auto. }
{ apply Qle_trans with (y:=x4*x5);auto;apply Qmult_le_compat_r;
apply Qlt_le_weak;auto. } }
{ destruct H3, H3, AN;auto. }
{ destruct H3, H3, CN;auto. }
{ destruct H3, H3, AN;auto. }
{ destruct H3, H3, H3, H3;auto. }
+ destruct H2, H2, AN;auto.
+ destruct H2, H2, BN;auto.
+ destruct H2, H2, AN;auto.
+ destruct H2, H2, H2, H2;auto.
Qed.
Lemma Rover0 : forall (A : Q -> Prop) (H:Dedekind A),
(Rzero < Real_cons A H)%R -> A 0.
Proof.
intros. destruct H0, H1, H1.
apply ( Dedekind_properties2 _ H x). split;auto.
apply Qnot_lt_le;auto.
Qed.
Lemma not_imply_to_or : forall P Q : Prop, ~(P->Q)->P/\~Q.
Proof.
intros. split.
- pose proof classic P. destruct H0.
+ auto.
+ destruct H. intros. destruct H0. auto.
- hnf. intros. auto.
Qed.
Theorem Dedekind_lt_bin : forall (A B : Q -> Prop)(x : Q),Dedekind A ->
Dedekind B -> A x -> ~ B x -> (forall x1 : Q, B x1 -> A x1).
Proof.
intros. apply (Dedekind_properties2 _ _ x).
pose proof Dedekind_le B x x1 H0 H2 H3. apply Qlt_le_weak in H4. auto.
Qed.
Theorem Rplus_lt_r: forall x y z : Real, (z + x < z + y <-> x < y)%R.
Proof.
intros.
destruct x, y, z. hnf. split.
- intros. hnf in *. destruct H2, H3, H3. split.
+ rewrite <- (not_exists_not_dist Q) in *. hnf.
intros. destruct H4, H5. destruct H3 as [?[?[?[]]]].
apply not_imply_to_or in H4. destruct H4.
exists x1, x2. repeat split;auto.
apply (Dedekind_lt_bin A A0 x0);auto.
+ apply not_all_not_ex. hnf in *. intros. destruct H4.
destruct H3 as [?[?[?[]]]].
pose proof H5 x1. apply not_and_or in H7. destruct H7.
* destruct H7;auto.
* apply NNPP in H7. exists x0, x1. auto.
- intros. hnf in *. destruct H2, H3, H3. split.
+ intros. destruct H5 as [?[?[?[]]]]. exists x1, x2;auto.
+ destruct (Dedekind_properties1 _ H1), H5.
apply (Dedekind_properties3 _ H0) in H3. destruct H3, H3.
pose proof Dedekind1_strong A1 H1 (x1 - x). destruct H8.
{ unfold Qminus. rewrite <- Qlt_minus_iff. auto. }
destruct H8. exists (x2+x1). split.
* exists x2, x1. repeat split;auto.
* hnf. intros. destruct H10 as [?[?[?[]]]].
pose proof Dedekind_le A1 (x2+(x1-x)) x3 H1 H9 H10.
unfold Qminus in *. rewrite Qplus_assoc in H13. rewrite <- H12 in H13.
rewrite <- Qplus_lt_l with (z:=x) in H13. rewrite <- Qplus_assoc in H13.
rewrite (Qplus_comm (-x) x) in H13. rewrite Qplus_opp_r in H13.
rewrite Qplus_0_r in H13. rewrite Qplus_lt_r with (z:=x3) in H13.
pose proof Dedekind_le A x x4 H H4 H11.
apply Qlt_not_le in H13. destruct H13. apply Qlt_le_weak;auto.
Qed.
Theorem Rplus_lt_l: forall x y z : Real, (x + z < y + z <-> x < y)%R.
Proof.
intros. rewrite Rplus_comm. rewrite (Rplus_comm y z). apply Rplus_lt_r.
Qed.
Theorem Rplus_0_l : forall a : Real, (Rzero + a == a)%R.
Proof.
intros. rewrite Rplus_comm. apply Rplus_0_r.
Qed.
Theorem Ropp_lt_compat: forall p q : Real, (p < q -> - q < - p)%R.
Proof.
intros. rewrite <- Rplus_lt_r with (z:=p). rewrite Rplus_opp.
rewrite <- Rplus_lt_l with (z:=q). rewrite Rplus_assoc.
rewrite (Rplus_comm (-q) q)%R. rewrite Rplus_opp.
rewrite Rplus_0_r. rewrite Rplus_0_l. auto.
Qed.
Theorem Rle_lt_eq : forall x y : Real, (x <= y <-> (x == y\/x<y))%R.
Proof.
intros. assert(x<y\/~x<y)%R. apply classic. split.
- destruct H.
+ auto.
+ apply Rnot_lt_le in H.
left. apply Rle_antisym;auto.
- intros. destruct H0.
+ rewrite H0. apply Rle_refl.
+ apply Rlt_le_weak;auto.
Qed.
Theorem Rplus_le_r: forall x y z : Real, (z + x <= z + y <-> x <= y)%R.
Proof.
intros. rewrite Rle_lt_eq. rewrite Rle_lt_eq. split.
- intros. destruct H.
+ left. apply (Rplus_compat_l z);auto.
+ right. rewrite <- Rplus_lt_r. apply H.
- intros. destruct H.
+ rewrite H. left. reflexivity.
+ right. rewrite Rplus_lt_r. auto.
Qed.
Theorem Rplus_inj_r: forall x y z : Real, (x + z == y + z <-> x == y)%R.
Proof.
intros. split.
- rewrite Rplus_comm. rewrite (Rplus_comm y z). apply Rplus_compat_l.
- intros. rewrite H. reflexivity.
Qed.
Theorem Rplus_inj_l: forall x y z : Real, (z + x == z + y <-> x == y)%R.
Proof.
intros. rewrite Rplus_comm. rewrite (Rplus_comm z y).
apply Rplus_inj_r.
Qed.
Theorem Rplus_le_l: forall x y z : Real, (x + z <= y + z <-> x <= y)%R.
Proof.
intros. rewrite Rplus_comm. rewrite (Rplus_comm y z).
apply Rplus_le_r.
Qed.
Theorem R_three_dis : forall x y : Real, (x<y\/x==y\/y<x)%R.
Proof.
intros. pose proof classic (x<y)%R. destruct H.
- auto.
- pose proof classic (y<x)%R. destruct H0.
+ auto.
+ apply Rnot_lt_le in H. apply Rnot_lt_le in H0.
right. left. split;auto.
Qed.
Lemma Rplus_opp_bin : forall b c : Real, (Rzero == b + c -> (-b) == c)%R.
Proof.
intros. rewrite <- Rplus_inj_l with (z:=b). rewrite Rplus_opp. auto.
Qed.
Lemma Rmult_distr_l_PPP : forall a b c : Real, (Rzero < a)%R -> (Rzero < b)%R ->
(Rzero < c)%R -> (a * (b + c) == (a * b) + (a * c))%R.
Proof.
intros.
destruct a, b, c.
pose proof (Rover0 A H2 H).
pose proof (Rover0 A0 H3 H0).
pose proof (Rover0 A1 H4 H1).
hnf;split;hnf;intros.
- apply Cut_mult_distr_PP;auto.
- apply Cut_mult_distr_PP;auto.
Qed.
Lemma Rmult_distr_l_PPE : forall a b c : Real, (Rzero < a)%R -> (Rzero < b)%R ->
(Rzero == c)%R -> (a * (b + c) == (a * b) + (a * c))%R.
Proof.
intros. rewrite <- H1. rewrite Rmult_0_r. rewrite Rplus_0_r.
rewrite Rplus_0_r. reflexivity.
Qed.
Lemma Rmult_distr_l_PNP : forall a b c : Real, (Rzero < a)%R -> (b < Rzero)%R ->
(Rzero < b + c)%R -> (Rzero < c)%R -> (a * (b + c) == (a * b) + (a * c))%R.
Proof.
intros. assert(c == b + c - b)%R. { unfold Rminus.
rewrite Rplus_comm. rewrite <- Rplus_assoc.
rewrite (Rplus_comm (-b)%R b). rewrite Rplus_opp.
rewrite Rplus_comm. rewrite Rplus_0_r. reflexivity. }
rewrite H3. rewrite (Rmult_distr_l_PPP a (b+c)(-b))%R;auto.
- rewrite <- Rmult_opp_r.
rewrite (Rplus_comm (a*b) (a * (b + c) + - (a * b)))%R.
rewrite Rplus_assoc. rewrite (Rplus_comm (-(a*b)) (a*b))%R.
rewrite Rplus_opp. rewrite Rplus_0_r. rewrite <- H3. reflexivity.
- rewrite <- Rplus_lt_r with (z:=b). rewrite Rplus_0_r.
rewrite Rplus_opp. auto.
Qed.
Lemma Rmult_distr_l_PPN : forall a b c : Real, (Rzero < a)%R -> (Rzero < b)%R ->
(Rzero < b + c)%R -> (c < Rzero)%R -> (a * (b + c) == (a * b) + (a * c))%R.
Proof.
intros. assert(b == b + c - c)%R. { unfold Rminus.
rewrite -> Rplus_assoc. rewrite Rplus_opp.
rewrite Rplus_0_r. reflexivity. }
rewrite H3. rewrite (Rmult_distr_l_PPP a (b+c)(-c))%R;auto.
- rewrite <- Rmult_opp_r.
rewrite Rplus_assoc. rewrite (Rplus_comm (-(a*c)) (a*c))%R.
rewrite Rplus_opp. rewrite Rplus_0_r. rewrite <- H3. reflexivity.
- rewrite <- Rplus_lt_r with (z:=c). rewrite Rplus_0_r.
rewrite Rplus_opp. auto.
Qed.
Lemma Rmult_distr_l_PNN : forall a b c : Real, (Rzero < a)%R -> (b < Rzero)%R ->
(c < Rzero)%R -> (a * (b + c) == (a * b) + (a * c))%R.
Proof.
intros.
apply Ropp_lt_compat in H0. rewrite <- Rzero_opp in H0.
apply Ropp_lt_compat in H1. rewrite <- Rzero_opp in H1.
rewrite (Ropp_opp b). rewrite (Ropp_opp c).
rewrite <- Rmult_opp_r. rewrite <- (Rmult_opp_r a (- c))%R.
rewrite <- Rplus_inj_l with (z:=(a*-b)%R).
rewrite <- Rplus_assoc. rewrite Rplus_opp. rewrite Rplus_0_l.
rewrite <- Rplus_inj_l with (z:=(a*-c)%R).
rewrite <- Rplus_assoc. rewrite Rplus_opp.
rewrite <- Rmult_distr_l_PPP;auto.
assert(--b+--c==-(-b+-c))%R.
{ rewrite <- Rplus_inj_l with (z:=(-b+-c)%R). rewrite Rplus_opp.
rewrite Rplus_assoc. rewrite (Rplus_comm (--b)%R).
rewrite <- (Rplus_assoc (-c)%R). rewrite Rplus_opp.
rewrite Rplus_0_l. rewrite Rplus_opp. reflexivity. }
rewrite H2. rewrite <- Rmult_opp_r. rewrite (Rplus_comm (-c)%R).
rewrite Rplus_opp. reflexivity.
Qed.
Lemma Rplus_opp_plus : forall a b : Real, (-(a+b)==-a+-b)%R.
Proof.
intros. rewrite <- Rplus_inj_l with (z:=(a+b)%R). rewrite Rplus_opp.
rewrite Rplus_assoc. rewrite (Rplus_comm (b)%R).
rewrite (Rplus_assoc (-a)%R). rewrite (Rplus_comm (-b))%R.
rewrite Rplus_opp. rewrite Rplus_0_r. rewrite Rplus_opp. reflexivity.
Qed.
Lemma Rmult_distr_l_NPP : forall a b c : Real, (a < Rzero)%R -> (Rzero < b)%R ->
(Rzero < c)%R -> (a * (b + c) == (a * b) + (a * c))%R.
Proof.
intros. apply Ropp_lt_compat in H. rewrite <- Rzero_opp in H.
rewrite (Ropp_opp a). rewrite <- (Rmult_opp_l (-a)%R).
rewrite <- (Rmult_opp_l (-a)%R). rewrite <- (Rmult_opp_l (-a)%R).
rewrite Rmult_distr_l_PPP;auto. rewrite Rplus_opp_plus.
reflexivity.
Qed.
Theorem Rmult_distr_l :
forall a b c : Real, (a * (b + c) == (a * b) + (a * c))%R.
Proof.
intros.
pose proof R_three_dis Rzero a.
pose proof R_three_dis Rzero b.
pose proof R_three_dis Rzero c.
destruct H as [?|[]];destruct H0 as [?|[]];destruct H1 as [?|[]];
try rewrite <- H;try rewrite Rmult_0_l;try rewrite Rmult_0_l;
try rewrite Rmult_0_l;try rewrite Rplus_0_r;try reflexivity;
try rewrite <- H0;try rewrite Rmult_0_r;try rewrite Rplus_0_l;
try rewrite Rplus_0_l;try reflexivity;
try rewrite <- H1;try rewrite Rmult_0_r;try rewrite Rplus_0_r;
try rewrite Rplus_0_r;try reflexivity.
- apply Rmult_distr_l_PPP;auto.
- pose proof R_three_dis Rzero (b+c)%R. destruct H2 as [?|[]].
+ apply Rmult_distr_l_PPN;auto.
+ rewrite <- H2. apply Rplus_opp_bin in H2.
rewrite <- H2. rewrite <- Rmult_opp_r. rewrite Rplus_opp.
apply Rmult_0_r.
+ assert(c == b + c - b)%R. { unfold Rminus.
rewrite Rplus_comm. rewrite <- Rplus_assoc.
rewrite (Rplus_comm (-b)%R b). rewrite Rplus_opp.
rewrite Rplus_comm. rewrite Rplus_0_r. reflexivity. }
rewrite H3. unfold Rminus.
apply Ropp_lt_compat in H0. rewrite <- Rzero_opp in H0.
rewrite (Rmult_distr_l_PNN a (b+c))%R;auto.
rewrite Rplus_comm with (b:=(a*-b)%R).
rewrite <- Rmult_opp_r. rewrite <- Rplus_assoc with (a:=(a*b)%R).
rewrite Rplus_opp. rewrite Rplus_0_l.
rewrite <- H3. reflexivity.
- pose proof R_three_dis Rzero (b+c)%R. destruct H2 as [?|[]].
+ apply Rmult_distr_l_PNP;auto.
+ rewrite <- H2. apply Rplus_opp_bin in H2.
rewrite <- H2. rewrite <- Rmult_opp_r. rewrite Rplus_opp.
apply Rmult_0_r.
+ rewrite Rplus_comm in *. rewrite (Rplus_comm (a*b)%R).
assert(b == c + b - c)%R. { unfold Rminus.
rewrite Rplus_comm. rewrite <- Rplus_assoc.
rewrite (Rplus_comm (-c)%R c). rewrite Rplus_opp.
rewrite Rplus_comm. rewrite Rplus_0_r. reflexivity. }
rewrite H3. unfold Rminus.
apply Ropp_lt_compat in H1. rewrite <- Rzero_opp in H1.
rewrite (Rmult_distr_l_PNN a (c+b))%R;auto.
rewrite Rplus_comm with (b:=(a*-c)%R).
rewrite <- Rmult_opp_r. rewrite <- Rplus_assoc with (a:=(a*c)%R).
rewrite Rplus_opp. rewrite Rplus_0_l.
rewrite <- H3. reflexivity.
- apply Rmult_distr_l_PNN;auto.
- apply Rmult_distr_l_NPP;auto.
- apply Ropp_lt_compat in H. rewrite <- Rzero_opp in H.
rewrite Rplus_comm in *. rewrite (Rplus_comm (a*b)%R).
rewrite (Ropp_opp a). rewrite <- (Rmult_opp_l (-a)%R).
rewrite <- (Rmult_opp_l (-a)%R). rewrite <- (Rmult_opp_l (-a)%R).
pose proof R_three_dis Rzero (c+b)%R. destruct H2 as [?|[]].
+ rewrite Rmult_distr_l_PNP;auto.
rewrite Rplus_opp_plus. reflexivity.
+ rewrite <- H2. apply Rplus_opp_bin in H2.
rewrite <- H2. rewrite <- Rmult_opp_r. rewrite Rplus_opp.
rewrite Rmult_0_r. rewrite <- Rzero_opp. reflexivity.
+ rewrite (Rplus_comm (-(-a*c))%R).
assert(b == c + b - c)%R. { unfold Rminus.
rewrite Rplus_comm. rewrite <- Rplus_assoc.
rewrite (Rplus_comm (-c)%R c). rewrite Rplus_opp.
rewrite Rplus_comm. rewrite Rplus_0_r. reflexivity. }
rewrite H3. unfold Rminus.
apply Ropp_lt_compat in H1. rewrite <- Rzero_opp in H1.
rewrite (Rmult_distr_l_PNP (-a) (c+b))%R;auto.
rewrite Rplus_opp_plus. rewrite (Rmult_opp_r (-a) (-c))%R.
rewrite <- Ropp_opp.
rewrite Rplus_assoc with (b:=(-a*c)%R). rewrite Rplus_opp.
rewrite Rplus_0_r.
rewrite <- H3. reflexivity.
rewrite <- H3. auto.
- apply Ropp_lt_compat in H. rewrite <- Rzero_opp in H.
rewrite (Ropp_opp a). rewrite <- (Rmult_opp_l (-a)%R).
rewrite <- (Rmult_opp_l (-a)%R). rewrite <- (Rmult_opp_l (-a)%R).
pose proof R_three_dis Rzero (b+c)%R. destruct H2 as [?|[]].
+ rewrite Rmult_distr_l_PNP;auto.
rewrite Rplus_opp_plus. reflexivity.
+ rewrite <- H2. apply Rplus_opp_bin in H2.
rewrite <- H2. rewrite <- Rmult_opp_r. rewrite Rplus_opp.
rewrite Rmult_0_r. rewrite <- Rzero_opp. reflexivity.
+ rewrite (Rplus_comm (-(-a*b))%R).
assert(c == b + c - b)%R. { unfold Rminus.
rewrite Rplus_comm. rewrite <- Rplus_assoc.
rewrite (Rplus_comm (-b)%R b). rewrite Rplus_opp.
rewrite Rplus_comm. rewrite Rplus_0_r. reflexivity. }
rewrite H3. unfold Rminus.
apply Ropp_lt_compat in H0. rewrite <- Rzero_opp in H0.
rewrite (Rmult_distr_l_PNP (-a) (b+c))%R;auto.
rewrite Rplus_opp_plus. rewrite (Rmult_opp_r (-a) (-b))%R.
rewrite <- Ropp_opp.
rewrite Rplus_assoc with (b:=(-a*b)%R). rewrite Rplus_opp.
rewrite Rplus_0_r.
rewrite <- H3. reflexivity.
rewrite <- H3. auto.
- apply Ropp_lt_compat in H. rewrite <- Rzero_opp in H.
apply Ropp_lt_compat in H0. rewrite <- Rzero_opp in H0.
apply Ropp_lt_compat in H1. rewrite <- Rzero_opp in H1.
rewrite (Ropp_opp a). rewrite <- (Rmult_opp_l (-a)%R).
rewrite <- (Rmult_opp_l (-a)%R). rewrite <- (Rmult_opp_l (-a)%R).
rewrite Rmult_opp_r. rewrite Rmult_opp_r. rewrite Rmult_opp_r.
rewrite Rplus_opp_plus. apply Rmult_distr_l_PPP;auto.
Qed.
Theorem Rmult_distr_r :
forall a b c : Real, ((b + c) * a == (b * a) + (c * a))%R.
Proof.
intros. rewrite Rmult_comm. rewrite (Rmult_comm b).
rewrite (Rmult_comm c). apply Rmult_distr_l.
Qed.
Theorem Rlt_not_refl : forall x : Real, (~x<x)%R.
Proof.
intros. apply Rle_not_lt. apply Rle_refl.
Qed.
Lemma Rmult_Rlt_0 : forall x y: Real, (Rzero < x ->
Rzero < y -> Rzero < x * y)%R.
Proof.
intros. destruct x, y. hnf in *.
assert(exists x : Q, Cut_mult A A0 x /\ ~ x < 0).
{ destruct H, H3, H3, H0, H5, H5. exists (x*x0).
apply (Dedekind_properties3 _ H1) in H3. destruct H3, H3.
apply Qnot_lt_le in H4.
assert(0<x1). apply Qle_lt_trans with (y:=x);auto.
apply (Dedekind_properties3 _ H2) in H5. destruct H5, H5.
apply Qnot_lt_le in H6.
assert(0<x2). apply Qle_lt_trans with (y:=x0);auto.
split.
- left. repeat split.
apply (Dedekind_properties2 _ H1 x1). split. auto. apply Qlt_le_weak. auto.
apply (Dedekind_properties2 _ H2 x2). split. auto. apply Qlt_le_weak. auto.
exists x1, x2. repeat split;auto. apply Qlt_le_weak.
apply Qmult_lt_compat;auto.
- apply Qle_not_lt. apply Qmult_le_0_compat;auto. }
split;auto.
intros. destruct H3, H3.
pose proof Dedekind_mult A A0 H1 H2.
apply (Dedekind_properties2 _ H6 x0). split;auto.
apply Qlt_le_weak. apply Qlt_le_trans with (y:=0).
auto. apply Qnot_lt_le. auto.
Qed.
Theorem Rmult_lt_compat_r: forall x y z : Real,
(Rzero < z -> x * z < y * z -> x < y)%R.
Proof.
intros. apply Rplus_lt_l with (z:= (-(y*z))%R) in H0.
apply Rplus_lt_l with (z:= (-y)%R). rewrite Rplus_opp in *.
rewrite Rmult_opp_l in H0. rewrite <- Rmult_distr_r in H0.
apply Rnot_le_lt. hnf. intros. rewrite Rle_lt_eq in H1.
destruct H1.
- rewrite <- H1 in H0. rewrite Rmult_0_l in H0.
apply (Rlt_not_refl Rzero). auto.
- pose proof Rmult_Rlt_0 (x + - y)%R z H1 H.
pose proof Rlt_trans ((x + - y) * z)%R Rzero ((x + - y) * z)%R H0 H2.
apply Rlt_not_refl in H3. auto.
Qed.
Definition Cut_inv (A : Q -> Prop) : Q -> Prop :=
(fun x => (A 0 /\ (x <= 0 \/ (x > 0 /\ exists r : Q, (r > 0 /\ ~ (A (/x + -r))))))
\/ (Cut_opp A 0 /\ x < 0 /\ exists r : Q, (r > 0 /\ ~ (A (/x + -r))))
\/ (~ A 0 /\ ~ Cut_opp A 0/\ False ))
.
Theorem Dedekind_inv : forall A : Q -> Prop , Dedekind A ->
A 0\/Cut_opp A 0 -> Dedekind (Cut_inv A).
Proof.
intros.
destruct H0.
{ split.
- split.
+ destruct (Dedekind_properties1 _ H), H2.
exists (/(x + 1)). left;split;auto.
assert(x + 1 <= 0 \/ ~ x + 1 <= 0). apply classic. destruct H3.
* left. apply Qnot_lt_le. apply Qle_not_lt in H3.
unfold not. intros. apply H3. rewrite <- (Qinv_involutive (x + 1)).
apply Qinv_lt_0_compat. auto.
* right. apply Qnot_le_lt in H3. split.
apply Qinv_lt_0_compat;auto. exists 1.
rewrite Qinv_involutive. split. reflexivity.
rewrite <- Qplus_assoc. rewrite Qplus_opp_r.
rewrite Qplus_0_r. auto.
+ destruct (Dedekind_properties3 _ H 0). auto.
exists (/x). destruct H1. hnf. intros.
assert(/x <= 0 \/ ~ /x <= 0). apply classic. destruct H4.
* apply Qle_not_lt in H4. apply Qinv_lt_0_compat in H2. auto.
* destruct H3 as [?|[]].
{ destruct H3, H5. auto. destruct H5, H6, H6, H7.
rewrite Qinv_involutive. apply (Dedekind_properties2 _ H x).
split;auto. apply Qlt_le_weak in H6.
apply Qopp_le_compat in H6.
rewrite <- Qplus_le_r with (z:=x) in H6.
rewrite Qplus_0_r in H6. auto. }
{ destruct H3, H5, H6. apply Qlt_le_weak in H5. auto. }
{ destruct H3, H5. auto. }
- intros. destruct H1. destruct H1 as [?|[]].
+ assert(q <= 0 \/ ~ q <= 0). apply classic. destruct H1.
destruct H3. left;auto.
destruct H4. pose proof Qle_trans q p 0 H2 H4. destruct H3. auto.
apply Qnot_le_lt in H3. apply Qdiv_le_P in H2;auto. left.
split;auto. right;split;auto. destruct H4, H5. exists x. destruct H5.
split;auto. unfold not. intros. apply H6.
apply (Dedekind_properties2 _ H (/ q + - x));split;auto.
apply Qplus_le_l;auto.
+ destruct H1. apply Cut_cut_opp_not in H0;auto.
destruct H0;auto.
+ destruct H1, H1. auto.
- intros. destruct H1, H1.
+ destruct H2.
* destruct (Dedekind_properties1 _ H). destruct H4.
exists (/(x + 1)). split. { left;split;auto.
assert(x + 1 <= 0 \/ ~ x + 1 <= 0). apply classic. destruct H5.
{ left. apply Qnot_lt_le. apply Qle_not_lt in H5.
unfold not. intros. apply H5. rewrite <- (Qinv_involutive (x + 1)).
apply Qinv_lt_0_compat. auto. }
right. apply Qnot_le_lt in H5. split.
apply Qinv_lt_0_compat;auto. exists 1.
rewrite Qinv_involutive. split. reflexivity.
rewrite <- Qplus_assoc. rewrite Qplus_opp_r.
rewrite Qplus_0_r. auto. }
{ assert(x + 1 <= 0 \/ ~ x + 1 <= 0). apply classic. destruct H5.
{ destruct H4. apply (Dedekind_properties2 _ H 0).
split;auto. apply Qle_trans with(y:=x+1);auto.
rewrite <- Qplus_0_r. rewrite <- Qplus_assoc.
apply Qplus_le_r. apply Qlt_le_weak. reflexivity. }
{ apply Qnot_le_lt in H5. apply Qinv_lt_0_compat in H5.
apply Qle_lt_trans with (y:=0);auto. } }
* assert(p <= 0 \/ ~ p <= 0). apply classic. destruct H3.
{ destruct H2, H4, H4, H5. apply Qle_not_lt in H3.
destruct H3;auto. } destruct H2, H4, H4.
exists (/((/p) + - (x/(2#1)))).
assert(p < / (/ p + - (x / (2 # 1)))).
{ rewrite <- Qmult_lt_l with (z:=(/ p + - (x / (2 # 1)))).
rewrite Qmult_inv_r. rewrite Qmult_comm.
rewrite Qmult_plus_distr_r. rewrite Qmult_inv_r. rewrite <- (Qplus_0_r 1).
rewrite Qplus_lt_r. rewrite <- Qopp_involutive.
rewrite <- (Qopp_involutive 0). apply Qopp_lt_compat.
rewrite Qmult_opp_assoc_l. rewrite Qmult_opp_assoc.
assert((-0)==0)%Q. reflexivity. rewrite H6.
rewrite <- (Qmult_0_l 0). apply Qmult_lt_compat;try apply Qle_refl;auto.
apply Qlt_shift_div_l. reflexivity. rewrite Qmult_0_l. auto.
apply Qlt_not_0;auto. apply Qlt_not_0.
apply Qlt_trans with (y:=(/ p + - x)).
apply (Dedekind_le A);auto. apply Qplus_lt_r.
rewrite Qdiv2. rewrite <- Qmult_lt_r with (z:=(2#1));try reflexivity.
assert(-(x / (2 # 1)) * (2 # 1)==-x)%Q. field.
assert((- x * / (2 # 1) + - x * / (2 # 1)) * (2 # 1)==-(x+x))%Q. field.
rewrite H6. rewrite H7. apply Qlt_minus_iff.
rewrite Qopp_involutive. rewrite Qplus_comm.
rewrite <- Qplus_assoc. rewrite Qplus_opp_r. rewrite Qplus_0_r. auto.
apply Qlt_trans with (y:=(/ p + - x)).
apply (Dedekind_le A);auto. apply Qplus_lt_r.
rewrite Qdiv2. rewrite <- Qmult_lt_r with (z:=(2#1));try reflexivity.
assert(-(x / (2 # 1)) * (2 # 1)==-x)%Q. field.
assert((- x * / (2 # 1) + - x * / (2 # 1)) * (2 # 1)==-(x+x))%Q. field.
rewrite H6. rewrite H7. apply Qlt_minus_iff.
rewrite Qopp_involutive. rewrite Qplus_comm.
rewrite <- Qplus_assoc. rewrite Qplus_opp_r. rewrite Qplus_0_r. auto. }
split;auto. left. split;auto. right. split.
apply Qlt_trans with (y:=p);auto. exists (x/(2#1)).
split. assert((x / (2 # 1)) * (2 # 1)==x)%Q. field.
rewrite <- Qmult_lt_r with (z:=(2#1));try reflexivity.
rewrite H7. auto.
assert (/ / (/ p + - (x / (2 # 1))) + - (x / (2 # 1))==(/ p + - x))%Q.
rewrite Qinv_involutive. rewrite (Qdiv2_opp x). rewrite <- Qplus_assoc.
reflexivity. rewrite H7. auto.
+ destruct H1. apply Cut_cut_opp_not in H0;auto.
destruct H0;auto.
+ destruct H1, H1. auto.
- intros. hnf in H2. hnf. rewrite H1 in H2. destruct H2.
+ left. repeat split;auto. destruct H2. destruct H3.
* left. auto.
* destruct H3, H4, H4. right. split;auto. exists x. rewrite <- H1.
auto.
+ destruct H2.
* right;left. destruct H2, H3, H4, H4. repeat split;auto.
exists x. rewrite <- H1. auto.
* destruct H2, H3, H4. }
{ split.
- split.
+ destruct H0, H0.
exists (/-(x/(2#1))). right;left;split;auto.
* exists x. auto.
* assert((-x/(2#1))<0).
assert((-x / (2 # 1)) * (2 # 1)==-x)%Q. field.
rewrite <- Qmult_lt_r with (z:=(2#1));try reflexivity.
rewrite H2. rewrite Qlt_minus_iff.
assert(0 * (2 # 1) + - - x==x)%Q. field. rewrite H3. auto.
split.
apply Qinv_0_lt_compat. unfold Qdiv.
rewrite Qmult_opp_assoc_l. auto.
exists (x/(2#1)). split. rewrite <- Qopp_involutive.
rewrite <- (Qopp_involutive (x/(2#1))). apply Qopp_lt_compat.
unfold Qdiv. rewrite Qmult_opp_assoc_l. auto.
rewrite Qinv_involutive. rewrite <- (Qdiv2_opp x).
rewrite Qplus_0_l in H1. auto.
+ exists 0. hnf. intros. destruct H1, H1.
apply Cut_cut_opp_not in H1;auto.
destruct H1, H2. inversion H2. apply H1.
- intros. destruct H1. destruct H1 as [?|[]].
+ destruct H1. apply Cut_cut_opp_not in H1;auto.
destruct H1;auto.
+ destruct H1. destruct H3, H4, H4. right;left;auto.
repeat split;auto. pose proof Qle_lt_trans q p 0 H2 H3. auto.
exists x. split;auto. unfold not. intros. apply H5.
apply (Dedekind_properties2 _ H (/ q + - x));split;auto.
apply Qdiv_le_N in H2;auto. apply Qplus_le_l;auto.
+ exfalso. apply H1.
- intros. destruct H1, H1.
+ apply Cut_cut_opp_not in H1;auto.
destruct H1;auto.
+ destruct H1, H2, H3, H3.
exists (/((/p) + - (x/(2#1)))).
assert(p < / (/ p + - (x / (2 # 1)))).
{ rewrite <- Qopp_involutive. rewrite <- (Qopp_involutive (/ (/ - - p + - (x / (2 # 1))))).
apply Qopp_lt_compat. rewrite <- Qmult_lt_l with (z:=-(/ p + - (x / (2 # 1)))).
rewrite Qmult_opp_assoc. rewrite Qmult_opp_assoc. rewrite Qopp_involutive.
rewrite Qmult_inv_r. rewrite Qmult_comm.
rewrite Qmult_plus_distr_r. rewrite Qmult_inv_r. rewrite <- (Qplus_0_r 1).
rewrite Qplus_lt_r. rewrite Qmult_comm. rewrite <- Qmult_opp_assoc_l.
rewrite Qmult_comm. rewrite Qmult_opp_assoc_l.
rewrite <- (Qmult_0_l 0). apply Qmult_lt_compat;try apply Qle_refl;auto.
rewrite <- Qopp_involutive. apply Qopp_lt_compat. auto. apply Qlt_shift_div_l. reflexivity. rewrite Qmult_0_l. auto.
apply Qlt_not_eq;auto. apply Qlt_not_eq.
apply Qlt_trans with (y:=(/ p)).
rewrite <- (Qplus_0_r (/p)). rewrite <- Qplus_assoc. apply Qplus_lt_r.
rewrite Qplus_0_l.
assert((-x/(2#1))<0).
assert((-x / (2 # 1)) * (2 # 1)==-x)%Q. field.
rewrite <- Qmult_lt_r with (z:=(2#1));try reflexivity.
rewrite H5. rewrite Qlt_minus_iff.
assert(0 * (2 # 1) + - - x==x)%Q. field. rewrite H6. auto.
unfold Qdiv. rewrite Qmult_opp_assoc_l. auto. apply Qinv_0_lt_compat;auto.
rewrite <- Qopp_involutive. apply Qopp_lt_compat.
rewrite <- (Qplus_0_l 0). rewrite Qopp_plus. apply Qplus_lt_le_compat.
apply Qinv_0_lt_compat;auto. apply Qlt_le_weak.
unfold Qdiv. rewrite Qmult_opp_assoc_l.
assert((-x / (2 # 1)) * (2 # 1)==-x)%Q. field.
rewrite <- Qmult_lt_r with (z:=(2#1));try reflexivity.
rewrite H5. rewrite Qlt_minus_iff.
assert(0 * (2 # 1) + - - x==x)%Q. field. rewrite H6. auto. }
split;auto. right;left. split;auto. split.
assert(/ p + - (x / (2 # 1)) < 0).
{ rewrite <- (Qplus_0_l 0). apply Qplus_lt_le_compat.
apply Qinv_0_lt_compat;auto. apply Qlt_le_weak.
unfold Qdiv. rewrite Qmult_opp_assoc_l.
assert((-x / (2 # 1)) * (2 # 1)==-x)%Q. field.
rewrite <- Qmult_lt_r with (z:=(2#1));try reflexivity.
rewrite H6. rewrite Qlt_minus_iff.
assert(0 * (2 # 1) + - - x==x)%Q. field. rewrite H7. auto. }
apply Qinv_0_lt_compat;auto. exists (x/(2#1)).
split. assert((x / (2 # 1)) * (2 # 1)==x)%Q. field.
rewrite <- Qmult_lt_r with (z:=(2#1));try reflexivity.
rewrite H6. auto.
assert (/ / (/ p + - (x / (2 # 1))) + - (x / (2 # 1))==(/ p + - x))%Q.
rewrite Qinv_involutive. rewrite (Qdiv2_opp x). rewrite <- Qplus_assoc.
reflexivity. rewrite H6. auto.
+ exfalso. apply H1.
- intros. destruct H2 as [?|[]].
+ destruct H2. apply Cut_cut_opp_not in H2;auto.
destruct H2;auto.
+ destruct H2. destruct H3, H4, H4. right;left;auto.
repeat split;auto. rewrite <- H1. auto.
exists x. split;auto. unfold not. intros. apply H5.
apply (Dedekind_properties2 _ H (/ q + - x));split;auto.
rewrite H1. apply Qle_refl.
+ exfalso. apply H2. }
Qed.
Lemma Rinv_def_lemma : forall (A : Q->Prop)(HA:Dedekind A),
~Real_cons A HA==Rzero -> A 0 \/ Cut_opp A 0.
Proof.
intros. unfold Req, Rle, Rzero in *.
apply not_and_or in H. destruct H.
- apply not_all_ex_not in H. destruct H.
apply not_imply_to_or in H. destruct H.
apply Qnot_lt_le in H0.
left. apply (Dedekind_properties2 _ HA x);auto.
- apply not_all_ex_not in H. destruct H.
apply not_imply_to_or in H. destruct H.
right. exists (-x). split. rewrite <- Qopp_involutive.
apply Qopp_lt_compat. auto. hnf. intros. destruct H0.
apply (Dedekind_properties4 _ HA (-0+--x));auto. field.
Qed.
Definition Rinv (a : Real)(H:~a==Rzero) : Real.
destruct a. apply Rinv_def_lemma in H.
apply (Real_cons (Cut_inv A) (Dedekind_inv A H0 H)).
Defined.
Definition Rinv' (a: Real): Real.
apply Rsinglefun.
exists (fun b => (exists H: ~ a == Rzero, Rinv a H = b) \/
a == Rzero /\ b == Rzero).
split; [| split].
Abort.
Lemma Rnot_0 : forall (a : Real), (~ a == Rzero -> ~ - a == Rzero)%R.
Proof.
intros. hnf. intros. apply H. rewrite Ropp_opp.
rewrite H0. rewrite <- Rzero_opp. reflexivity.
Qed.
Theorem Cut_inv_same : forall (A : Q -> Prop), Dedekind A ->
A 0 -> Cut_inv A 0.
Proof.
intros. left. split;auto. left. apply Qle_refl.
Qed.
Lemma Cut_inv_eq' : forall (A B : Q -> Prop) (x : Q), Dedekind A ->
Dedekind B -> (forall x : Q, A x <-> B x) ->
Cut_inv B x -> Cut_inv A x.
Proof.
intros. destruct H2 as [?|[]].
- left. destruct H2. rewrite H1. split;auto.
destruct H3. left;auto. right.
destruct H3, H4, H4. split;auto.
exists x0. split;auto. hnf. intros. destruct H5. rewrite <- H1. auto.
- right. left. destruct H2, H3, H4, H4, H2, H2. rewrite <- H1 in *.
repeat split;auto. exists x1;auto. exists x0;auto.
- destruct H2, H3, H4.
Qed.
Lemma Cut_inv_eq : forall (A B : Q -> Prop), Dedekind A ->
Dedekind B -> (forall x : Q, A x <-> B x) -> forall x : Q,
Cut_inv B x <-> Cut_inv A x.
Proof.
intros. split;apply Cut_inv_eq';auto.
intros. rewrite H1. reflexivity.
Qed.
Lemma Cut_inv_opp : forall (A : Q -> Prop) (x : Q), Dedekind A ->
A 0 \/ Cut_opp A 0 ->
Cut_opp (Cut_inv A) x -> Cut_inv (Cut_opp A) x.
Proof.
intros. hnf.
pose proof Cut_mult_situation1 A.
destruct H2 as [?|[]].
+ right. left. repeat split.
* rewrite <- Cut_opp_opp;auto.
* destruct H1, H1. apply Qnot_le_lt. hnf. intros. apply H3.
left. split;auto. left. rewrite <- (Qplus_0_r 0).
apply Qplus_le_compat;rewrite Qle_minus_iff;
rewrite Qplus_0_l;rewrite Qopp_involutive;auto;
apply Qlt_le_weak;auto.
* destruct H1, H1. exists (/(-x + - x0)+-(/-x)). split.
{ rewrite <- Qlt_minus_iff. apply Qdiv_lt_P.
apply (Dedekind_le (Cut_inv A));auto. apply Dedekind_inv;auto.
apply Cut_inv_same;auto. rewrite <- (Qplus_0_r (-x)).
rewrite <- Qplus_assoc. rewrite Qplus_lt_r.
rewrite Qplus_0_l. rewrite Qlt_minus_iff.
rewrite Qplus_0_l. rewrite Qopp_involutive. auto. }
{ hnf. intros. apply H3. left. destruct H4, H4. split;auto.
right. split. apply (Dedekind_le (Cut_inv A));auto.
apply Dedekind_inv;auto. apply Cut_inv_same;auto.
exists x1. split;auto. hnf. intros. apply H5.
rewrite <- Qinv_opp.
{ rewrite (Qopp_plus (/ (- x + - x0)) (--/x)).
rewrite (Qplus_comm (- / (- x + - x0)) (---/x)).
rewrite Qplus_assoc. rewrite Qopp_involutive.
rewrite Qplus_opp_r. rewrite Qplus_0_l.
rewrite Qopp_involutive. auto. }
{ apply Qlt_not_eq. apply Qnot_le_lt. hnf. intros. apply H3.
left. split;auto. left. rewrite <- (Qplus_0_r 0).
apply Qplus_le_compat;rewrite Qle_minus_iff;
rewrite Qplus_0_l;rewrite Qopp_involutive;auto;
apply Qlt_le_weak;auto. } }
+ left. split;auto. assert(x<=0\/~x<=0). apply classic.
destruct H3. auto. right. split.
apply Qnot_le_lt;auto.
apply Qnot_le_lt in H3. destruct H1, H1.
exists (/x +-/(x + x0)). split.
{ rewrite <- Qlt_minus_iff. apply Qdiv_lt_P. auto.
rewrite <- Qplus_0_r. rewrite <- Qplus_assoc.
rewrite Qplus_lt_r. rewrite Qplus_0_l. auto. }
{ hnf. intros. apply H4. destruct H5, H5. right. left.
split;auto. split. rewrite <- Qopp_plus.
rewrite Qlt_minus_iff. rewrite Qopp_involutive.
rewrite Qplus_0_l. rewrite <- (Qplus_0_r 0).
apply Qplus_lt_le_compat. auto. apply Qlt_le_weak. auto.
exists x1. split;auto. hnf. intros. apply H6.
repeat rewrite Qopp_plus. rewrite Qplus_assoc.
rewrite Qplus_opp_r. rewrite Qopp_involutive.
rewrite Qplus_0_l. rewrite Qinv_opp. rewrite Qopp_plus. auto.
apply Qlt_not_0. rewrite <- (Qplus_0_r 0).
apply Qplus_lt_le_compat. auto. apply Qlt_le_weak. auto. }
+ destruct H2.
destruct H0;destruct H2;auto;destruct H3;auto.
Qed.
Lemma Cut_inv_x :
forall (A : Q -> Prop) (x : Q),Dedekind A -> x>0 -> A x -> ~ Cut_inv A (/x).
Proof.
intros. hnf. intros. destruct H2 as [?|[]].
- destruct H2. destruct H3.
+ rewrite <- Qmult_le_l with (z:=x) in H3;auto.
rewrite Qmult_0_r in H3. rewrite Qmult_inv_r in H3.
destruct H3. reflexivity. apply Qlt_not_0;auto.
+ destruct H3. destruct H4, H4, H5. rewrite Qinv_involutive.
apply (Dedekind_properties2 _ H x).
split;auto. rewrite <- (Qplus_0_r x).
apply Qplus_le_compat. rewrite Qplus_0_r. apply Qle_refl.
rewrite Qle_minus_iff.
assert(0+--x0==x0)%Q. field. rewrite H5.
apply Qlt_le_weak;auto.
- destruct H2. assert(A 0). apply (Dedekind_properties2 _ H x).
split;auto. apply Qlt_le_weak;auto.
apply Cut_cut_opp_not in H4;auto.
- destruct H2, H2. apply (Dedekind_properties2 _ H x).
split;auto. apply Qlt_le_weak;auto.
Qed.
Lemma Cut_inv_x' :
forall (A : Q -> Prop) (x : Q),Dedekind A -> Cut_opp A 0 ->
x<0 -> A (x) -> ~ Cut_inv A (/x).
Proof.
intros. hnf. intros. destruct H3 as [?|[]].
- destruct H3. apply Cut_cut_opp_not in H3;auto.
- destruct H3, H4, H5, H5, H6. rewrite Qinv_involutive.
apply (Dedekind_properties2 _ H x).
split;auto. rewrite <- (Qplus_0_r x). rewrite <- Qplus_assoc.
rewrite Qplus_le_r. apply Qlt_le_weak;auto. rewrite Qplus_0_l.
rewrite <- (Qopp_involutive 0). apply Qopp_lt_compat. auto.
- destruct H3, H4, H5.
Qed.
Lemma Cut_opp_inv : forall (A : Q -> Prop) (x : Q), Dedekind A ->
A 0 \/ Cut_opp A 0 ->
Cut_inv (Cut_opp A) x -> Cut_opp (Cut_inv A) x.
Proof.
intros. hnf.
destruct H1 as [?|[]].
- destruct H1. destruct H2.
+ apply Qle_lteq in H2. destruct H2.
{ exists (-x). split. rewrite <- Qplus_lt_r with (z:=x).
rewrite Qplus_opp_r. rewrite Qplus_0_r. auto.
hnf. intros. destruct H3 as [?|[]].
{ destruct H3. apply Cut_cut_opp_not in H3;auto. }
{ destruct H3, H4. rewrite (Qplus_opp_r (- x)) in H4. inversion H4. }
{ inversion H3. inversion H5. auto. } }
{ pose proof Dedekind_inv A H H0. rename H3 into HV.
destruct (Dedekind_properties1 _ H). destruct H3.
exists (-/(x0)). split.
rewrite <- Qplus_lt_r with (z:=(/x0)). rewrite Qplus_opp_r.
rewrite Qplus_0_r. apply Qinv_0_lt_compat.
apply (Dedekind_le A);auto. pose proof Dedekind_opp A H.
apply Cut_cut_opp_not in H1;auto. rewrite <- Cut_opp_opp in H1;auto.
rewrite H2. assert(forall x:Q, - 0 + - - x == x)%Q. intros. field.
rewrite H5. apply Cut_inv_x';auto. apply (Dedekind_le A);auto.
pose proof Dedekind_opp A H.
apply Cut_cut_opp_not in H1;auto. rewrite <- Cut_opp_opp in H1;auto. }
+ destruct H2, H3, H3. assert(A (- /x)).
{ apply NNPP. hnf. intros. apply H4. hnf.
exists x0. split;auto.
assert(forall x : Q, - (x + - x0) + - x0 == - x)%Q. intros. field.
rewrite H6. auto. }
destruct (Dedekind_properties3 _ H (-/x));auto. destruct H6.
exists (-x + /-x1). split. rewrite <- Qplus_lt_r with (z:=x).
rewrite Qplus_assoc. rewrite Qplus_opp_r. rewrite Qplus_0_r.
rewrite Qplus_0_l. rewrite <- Qinv_involutive. apply Qdiv_lt_P.
rewrite <- Qopp_involutive. apply Qopp_lt_compat.
apply (Dedekind_le A);auto. hnf. intros. destruct H1, H1, H9.
apply (Dedekind_properties2 _ H 0). split;auto.
apply Qlt_le_weak. rewrite <- (Qopp_involutive 0).
rewrite Qplus_0_l. apply Qopp_lt_compat. auto.
rewrite <- (Qopp_involutive (/x)).
apply Qopp_lt_compat. auto.
assert(forall y : Q, - x + - (- x + y) == - y)%Q. intros. field.
pose proof Dedekind_inv A H H0. rewrite H8.
rewrite <- Qinv_opp;try apply Qlt_not_eq;try rewrite Qopp_involutive;
try apply Cut_inv_x';auto;apply (Dedekind_le A);auto;hnf; intros; destruct H1, H1, H11;
apply (Dedekind_properties2 _ H 0); split;auto;
apply Qlt_le_weak; rewrite <- (Qopp_involutive 0);
rewrite Qplus_0_l; apply Qopp_lt_compat; auto.
- destruct H1, H2, H3, H3. assert(A (- /x)).
{ apply NNPP. hnf. intros. apply H4. hnf.
exists x0. split;auto.
assert(forall x : Q, - (x + - x0) + - x0 == - x)%Q. intros. field.
rewrite H6. auto. }
destruct (Dedekind_properties3 _ H (-/x));auto. destruct H6.
exists (-x + /-x1). split. rewrite <- Qplus_lt_r with (z:=x).
rewrite Qplus_assoc. rewrite Qplus_opp_r. rewrite Qplus_0_r.
rewrite Qplus_0_l. rewrite <- Qinv_involutive. apply Qdiv_lt_N.
apply Qinv_0_lt_compat;auto.
rewrite <- (Qopp_involutive (/x)). apply Qopp_lt_compat. auto.
assert(forall y : Q, - x + - (- x + y) == - y)%Q. intros. field.
pose proof Dedekind_inv A H H0. rewrite H8.
rewrite <- Qinv_opp;try apply Qlt_not_0; try rewrite Qopp_involutive;
try apply Cut_inv_x;auto;apply Qlt_trans with (y:=-/x);auto;
rewrite <- (Qopp_involutive 0);apply Qopp_lt_compat; auto;
apply Qinv_0_lt_compat;auto.
- destruct H1, H2, H3.
Qed.
Lemma invlemma1 : forall (A : Q -> Prop) (x : Q), A 0 \/ Cut_opp A 0
-> Dedekind A -> x < 1 ->A 0 -> Cut_inv A 0 -> A 1 ->
0<x -> Dedekind (Cut_inv A) -> Cut_multPP A (Cut_inv A) x.
Proof.
intros. rename H5 into H'. rename H6 into HV.
assert(A ((2#1) - x) \/ ~ A ((2#1) - x))%Q. apply classic.
assert(H'':0 < 1 - x).
{ rewrite <- Qplus_lt_l with (z:=x).
unfold Qminus. rewrite <- Qplus_assoc.
rewrite (Qplus_comm (-x)).
rewrite Qplus_opp_r. rewrite Qplus_0_r. rewrite Qplus_0_l. auto. }
destruct H5.
{ pose proof Dedekind1_strong A H0 (1 - x).
destruct H6. auto.
destruct H6.
destruct (Dedekind_properties3 _ H0 x0);auto. destruct H8.
assert( ~ A (x1 + (1 - x))). hnf. intros. apply H7.
apply (Dedekind_properties2 _ H0 (x1 + (1 - x))).
split. auto. rewrite Qplus_le_l. apply Qlt_le_weak. auto.
exists x1, (/(x1 + (1 - x))).
assert(1<x1).
{ assert(((2 # 1) - x)<(x1 + (1 - x))).
apply (Dedekind_le A);auto.
unfold Qminus in *. rewrite Qplus_assoc in H11.
rewrite Qplus_lt_l in H11. rewrite <- Qplus_lt_l with (z:=1).
auto. }
assert(0<x1). apply Qlt_trans with (y:=1).
reflexivity. auto.
assert(0 < / (x1 + (1 - x))). { apply Qinv_lt_0_compat. apply (Dedekind_le A);auto.
}
repeat split;auto.
left. split;auto. right. split. auto.
exists (x1 - x0). split. rewrite <- Qplus_lt_l with (z:=x0). unfold Qminus.
rewrite <- Qplus_assoc. rewrite (Qplus_comm (-x0)). rewrite Qplus_opp_r.
rewrite Qplus_0_l. rewrite Qplus_0_r. auto.
hnf. intros.
assert(((x1 + (1 - x)) + - (x1 - x0))==(x0 + (1 - x)))%Q. field.
rewrite Qinv_involutive in H14.
destruct H7. rewrite H15 in H14. auto.
assert(~(x1 + (1 - x))==0)%Q. { apply Qinv_lt_0_compat in H13. rewrite Qinv_involutive in H13.
apply Qlt_not_0. auto. }
assert((x1 * / (x1 + (1 - x))) == (1 - (1-x)*/(x1+(1-x))))%Q. field. auto.
rewrite H15. clear H15. rewrite <- Qplus_le_l with (z:=(1 - x) * / (x1 + (1 - x))).
rewrite <- Qplus_le_l with (z:=(-x)).
assert(x + (1 - x) * / (x1 + (1 - x)) + - x == (1 - x) * / (x1 + (1 - x)))%Q. field. auto.
rewrite H15. clear H15.
assert(1 - (1 - x) * / (x1 + (1 - x)) + (1 - x) * / (x1 + (1 - x)) + - x == 1 - x)%Q. field. auto.
rewrite H15. clear H15.
assert(~(1-x)==0)%Q. apply Qlt_not_0. auto.
rewrite <- Qmult_le_r with (z:=(x1 + (1 - x))).
rewrite <- Qmult_le_r with (z:=/(1 - x)).
assert((1 - x) * / (x1 + (1 - x)) * (x1 + (1 - x)) * / (1 - x)==1)%Q. field. split;auto.
rewrite H16. clear H16.
assert((1 - x) * (x1 + (1 - x)) * / (1 - x)==(x1 + (1 - x)))%Q. field. auto.
rewrite H16. clear H16. rewrite <- Qplus_0_r.
apply Qplus_le_compat;apply Qlt_le_weak;auto.
apply Qinv_lt_0_compat. auto.
apply Qinv_lt_0_compat in H13. rewrite Qinv_involutive in H13. auto. }
{ destruct (Dedekind_properties3 _ H0 1);auto. destruct H6.
assert( ~ A (x0 + (1 - x))). hnf. intros. apply H5.
apply (Dedekind_properties2 _ H0 (x0 + (1 - x))).
split. auto. assert((2 # 1) - x==1+(1-x))%Q. field. rewrite H9.
clear H9. rewrite Qplus_le_l. apply Qlt_le_weak. auto.
exists x0, (/(x0 + (1 - x))).
assert(0<x0). apply Qlt_trans with (y:=1).
reflexivity. auto.
assert(0 < / (x0 + (1 - x))). { apply Qinv_lt_0_compat. apply (Dedekind_le A);auto. }
repeat split;auto.
left. split;auto. right. split. auto.
exists (x0 - 1). split. rewrite <- Qplus_lt_l with (z:=1). unfold Qminus.
rewrite <- Qplus_assoc. rewrite Qplus_opp_r.
rewrite Qplus_0_l. rewrite Qplus_0_r. auto.
hnf. intros.
assert(((x0 + (1 - x)) + - (x0 - 1))==(1 + (1 - x)))%Q. field.
rewrite Qinv_involutive in H11.
destruct H5. rewrite H12 in H11.
apply (Dedekind_properties4 _ H0 (1 + (1 - x))). field. auto.
assert(~(x0 + (1 - x))==0)%Q. { apply Qinv_lt_0_compat in H10. rewrite Qinv_involutive in H10.
apply Qlt_not_0. auto. }
assert((x0 * / (x0 + (1 - x))) == (1 - (1-x)*/(x0+(1-x))))%Q. field. auto.
rewrite H12. clear H12. rewrite <- Qplus_le_l with (z:=(1 - x) * / (x0 + (1 - x))).
rewrite <- Qplus_le_l with (z:=(-x)).
assert(x + (1 - x) * / (x0 + (1 - x)) + - x == (1 - x) * / (x0 + (1 - x)))%Q. field. auto.
rewrite H12. clear H12.
assert(1 - (1 - x) * / (x0 + (1 - x)) + (1 - x) * / (x0 + (1 - x)) + - x == 1 - x)%Q. field. auto.
rewrite H12. clear H12.
assert(~(1-x)==0)%Q. apply Qlt_not_0. auto.
rewrite <- Qmult_le_r with (z:=(x0 + (1 - x))).
rewrite <- Qmult_le_r with (z:=/(1 - x)).
assert((1 - x) * / (x0 + (1 - x)) * (x0 + (1 - x)) * / (1 - x)==1)%Q. field. split;auto.
rewrite H13. clear H13.
assert((1 - x) * (x0 + (1 - x)) * / (1 - x)==(x0 + (1 - x)))%Q. field. auto.
rewrite H13. clear H13. rewrite <- Qplus_0_r.
apply Qplus_le_compat;apply Qlt_le_weak;auto.
apply Qinv_lt_0_compat. auto.
apply Qinv_lt_0_compat in H10. rewrite Qinv_involutive in H10. auto. }
Qed.
Lemma invlemma2 : forall (A : Q -> Prop) (x : Q), A 0 \/ Cut_opp A 0
-> Dedekind A -> x < 1 ->A 0 -> Cut_inv A 0 -> Cut_inv A 1 ->
0<x -> Dedekind (Cut_inv A) -> Cut_multPP A (Cut_inv A) x.
Proof.
intros. rename H5 into H'. rename H6 into HV.
assert(Cut_inv A ((2#1) - x) \/ ~ Cut_inv A ((2#1) - x))%Q. apply classic.
assert(H'':0 < 1 - x).
{ rewrite <- Qplus_lt_l with (z:=x).
unfold Qminus. rewrite <- Qplus_assoc.
rewrite (Qplus_comm (-x)).
rewrite Qplus_opp_r. rewrite Qplus_0_r. rewrite Qplus_0_l. auto. }
destruct H5.
{ pose proof Dedekind1_strong (Cut_inv A) HV (1 - x).
destruct H6. auto.
destruct H6.
destruct (Dedekind_properties3 _ HV x0);auto. destruct H8.
assert( ~Cut_inv A (x1 + (1 - x))). hnf. intros. apply H7.
apply (Dedekind_properties2 _ HV (x1 + (1 - x))).
split. auto. rewrite Qplus_le_l. apply Qlt_le_weak. auto.
exists (/(x1 + (1 - x))), x1.
assert(1<x1).
{ assert(((2 # 1) - x)<(x1 + (1 - x))).
apply (Dedekind_le (Cut_inv A));auto.
unfold Qminus in *. rewrite Qplus_assoc in H11.
rewrite Qplus_lt_l in H11. rewrite <- Qplus_lt_l with (z:=1).
auto. }
assert(0<x1). apply Qlt_trans with (y:=1).
reflexivity. auto.
assert(0 < / (x1 + (1 - x))). { apply Qinv_lt_0_compat. apply (Dedekind_le (Cut_inv A));auto.
}
repeat split;auto. {
apply NNPP. hnf. intros. apply H7.
hnf. left. split;auto. right. split.
apply (Dedekind_le (Cut_inv A));auto.
exists (/ (x0 + (1 - x)) - /(x1 + (1 - x))).
split. rewrite <- Qplus_lt_l with (z:=/ (x1 + (1 - x))).
unfold Qminus. rewrite <- Qplus_assoc. rewrite Qplus_0_l.
rewrite (Qplus_comm (-/ (x1 + (1 - x)))). rewrite Qplus_opp_r.
rewrite Qplus_0_r. apply Qdiv_lt_P;auto.
apply (Dedekind_le (Cut_inv A));auto.
rewrite Qplus_lt_l. auto. hnf. intros.
destruct H14. apply (Dedekind_properties4 _ H0 (/ (x0 + (1 - x)) + - (/ (x0 + (1 - x)) - / (x1 + (1 - x)))));auto.
unfold Qminus. rewrite Qopp_plus. rewrite Qplus_assoc.
rewrite Qplus_opp_r. rewrite Qopp_involutive.
rewrite Qplus_0_l. reflexivity. }
assert(~(x1 + (1 - x))==0)%Q. { apply Qinv_lt_0_compat in H13. rewrite Qinv_involutive in H13.
apply Qlt_not_0. auto. }
assert((/ (x1 + (1 - x)))*x1 == (1 - (1-x)*/(x1+(1-x))))%Q. field. auto.
rewrite H15. clear H15. rewrite <- Qplus_le_l with (z:=(1 - x) * / (x1 + (1 - x))).
rewrite <- Qplus_le_l with (z:=(-x)).
assert(x + (1 - x) * / (x1 + (1 - x)) + - x == (1 - x) * / (x1 + (1 - x)))%Q. field. auto.
rewrite H15. clear H15.
assert(1 - (1 - x) * / (x1 + (1 - x)) + (1 - x) * / (x1 + (1 - x)) + - x == 1 - x)%Q. field. auto.
rewrite H15. clear H15.
assert(~(1-x)==0)%Q. apply Qlt_not_0. auto.
rewrite <- Qmult_le_r with (z:=(x1 + (1 - x))).
rewrite <- Qmult_le_r with (z:=/(1 - x)).
assert((1 - x) * / (x1 + (1 - x)) * (x1 + (1 - x)) * / (1 - x)==1)%Q. field. split;auto.
rewrite H16. clear H16.
assert((1 - x) * (x1 + (1 - x)) * / (1 - x)==(x1 + (1 - x)))%Q. field. auto.
rewrite H16. clear H16. rewrite <- Qplus_0_r.
apply Qplus_le_compat;apply Qlt_le_weak;auto.
apply Qinv_lt_0_compat. auto.
apply Qinv_lt_0_compat in H13. rewrite Qinv_involutive in H13. auto. }
{ destruct (Dedekind_properties3 _ HV 1);auto. destruct H6.
assert( ~Cut_inv A (x0 + (1 - x))). hnf. intros. apply H5.
apply (Dedekind_properties2 _ HV (x0 + (1 - x))).
split. auto. assert((2 # 1) - x==1+(1-x))%Q. field. rewrite H9.
clear H9. rewrite Qplus_le_l. apply Qlt_le_weak. auto.
exists (/(x0 + (1 - x))), x0.
assert(0<x0). apply Qlt_trans with (y:=1).
reflexivity. auto.
assert(0 < / (x0 + (1 - x))). { apply Qinv_lt_0_compat. apply (Dedekind_le (Cut_inv A));auto. }
repeat split;auto. {
apply NNPP. hnf. intros. apply H5.
hnf. left. split;auto. right. split.
apply (Dedekind_le (Cut_inv A));auto.
exists (/ (1 + (1 - x)) - /(x0 + (1 - x))).
split. rewrite <- Qplus_lt_l with (z:=/ (x0 + (1 - x))).
unfold Qminus. rewrite <- Qplus_assoc. rewrite Qplus_0_l.
rewrite (Qplus_comm (-/ (x0 + (1 - x)))). rewrite Qplus_opp_r.
rewrite Qplus_0_r. apply Qdiv_lt_P;auto.
apply (Dedekind_le (Cut_inv A));auto. hnf. intros.
apply H5. assert(1 + (1 + - x)==((2 # 1) - x))%Q. field.
rewrite <- H13. auto.
rewrite Qplus_lt_l. auto. hnf. intros.
destruct H11. apply (Dedekind_properties4 _ H0 (/ (1 + (1 - x)) + - (/ (1 + (1 - x)) - / (x0 + (1 - x)))));auto.
unfold Qminus. rewrite Qopp_plus. rewrite Qplus_assoc.
rewrite Qplus_opp_r. rewrite Qopp_involutive.
rewrite Qplus_0_l. reflexivity. assert(1 + (1 + - x)==((2 # 1) - x))%Q. field.
rewrite <- H11 in H12. auto. }
assert(~(x0 + (1 - x))==0)%Q. { apply Qinv_lt_0_compat in H10. rewrite Qinv_involutive in H10.
apply Qlt_not_0. auto. }
assert((/ (x0 + (1 - x)))*x0 == (1 - (1-x)*/(x0+(1-x))))%Q. field. auto.
rewrite H12. clear H12. rewrite <- Qplus_le_l with (z:=(1 - x) * / (x0 + (1 - x))).
rewrite <- Qplus_le_l with (z:=(-x)).
assert(x + (1 - x) * / (x0 + (1 - x)) + - x == (1 - x) * / (x0 + (1 - x)))%Q. field. auto.
rewrite H12. clear H12.
assert(1 - (1 - x) * / (x0 + (1 - x)) + (1 - x) * / (x0 + (1 - x)) + - x == 1 - x)%Q. field. auto.
rewrite H12. clear H12.
assert(~(1-x)==0)%Q. apply Qlt_not_0. auto.
rewrite <- Qmult_le_r with (z:=(x0 + (1 - x))).
rewrite <- Qmult_le_r with (z:=/(1 - x)).
assert((1 - x) * / (x0 + (1 - x)) * (x0 + (1 - x)) * / (1 - x)==1)%Q. field. split;auto.
rewrite H13. clear H13.
assert((1 - x) * (x0 + (1 - x)) * / (1 - x)==(x0 + (1 - x)))%Q. field. auto.
rewrite H13. clear H13. rewrite <- Qplus_0_r.
apply Qplus_le_compat;apply Qlt_le_weak;auto.
apply Qinv_lt_0_compat. auto.
apply Qinv_lt_0_compat in H10. rewrite Qinv_involutive in H10. auto. }
Qed.
Lemma Rmult_inv' : (forall (a : Real) (H : ~ a == Rzero) (H0 : (Rzero < a)%R),
(a * Rinv a H <= Rone)%R /\ (Rone <= a * Rinv a H)%R).
Proof.
intros. rename H0 into IH. destruct a. unfold Rinv, Rone, Rzero in *. split.
- hnf. intros. destruct H1 as [?|[?|[?|[]]]].
+ destruct H1, H1. destruct H2 as [?[?[?[?[?[]]]]]].
destruct H6 as [?|[]].
* destruct H6. destruct H8.
{ apply Qle_not_lt in H8. destruct H8. auto. }
destruct H8, H9, H9.
apply Qle_lt_trans with (y:= x0 * x1);auto.
apply Qlt_le_trans with (y:= (/x1) * x1).
{ apply Qmult_lt_r;auto.
apply (Dedekind_le A);auto. hnf. intros.
apply H10. apply (Dedekind_properties2 _ H0 (/x1)).
split;auto. rewrite <- (Qplus_0_r (/x1)).
rewrite <- Qplus_assoc. rewrite Qplus_le_r.
rewrite Qplus_0_l. rewrite Qle_minus_iff.
rewrite Qplus_0_l. rewrite Qopp_involutive.
apply Qlt_le_weak. auto. }
rewrite Qmult_comm. rewrite Qmult_inv_r. apply Qle_refl.
apply Qlt_not_eq in H8. hnf. intros.
apply H8. rewrite H11. reflexivity.
* destruct H6. apply Cut_cut_opp_not in H1;auto.
destruct H1. auto.
* destruct H6, H8, H9.
+ destruct H1, H1. destruct H3 as [?|[]].
* destruct H3. apply Cut_cut_opp_not in H3;auto.
destruct H3. auto.
* destruct H3, H4. inversion H4.
* destruct H3, H4, H5.
+ destruct H1, H1. destruct H3 as [?[]].
destruct H4. left. split;auto. left.
rewrite Qplus_0_l. rewrite Qle_minus_iff.
rewrite Qplus_0_l. rewrite Qopp_involutive.
apply Qlt_le_weak. auto.
+ pose proof Dedekind_opp A H0. rename H2 into HN.
destruct H1, H1. destruct H3 as [?[]].
destruct H2 as [?[?[?[?[?[]]]]]]. apply Cut_inv_opp in H7;auto.
destruct H7 as [?|[]].
* destruct H7. destruct H9.
{ apply Qle_not_lt in H9. destruct H9. auto. }
destruct H9, H10, H10.
apply Qle_lt_trans with (y:= x1 * x2);auto.
apply Qlt_le_trans with (y:= (/x2) * x2).
{ apply Qmult_lt_r;auto.
apply (Dedekind_le (Cut_opp A));auto;try apply Dedekind_opp;auto. hnf. intros.
apply H11. apply (Dedekind_properties2 _ HN (/x2)).
split;auto. rewrite <- (Qplus_0_r (/x2)).
rewrite <- Qplus_assoc. rewrite Qplus_le_r.
rewrite Qplus_0_l. rewrite Qle_minus_iff.
rewrite Qplus_0_l. rewrite Qopp_involutive.
apply Qlt_le_weak. auto. }
rewrite Qmult_comm. rewrite Qmult_inv_r. apply Qle_refl.
apply Qlt_not_eq in H9. hnf. intros.
apply H9. rewrite H12. reflexivity.
* destruct H7. apply Cut_cut_opp_not in H1;auto.
destruct H1. auto.
* destruct H7, H9, H10.
+ destruct H1, H1;unfold Cut_mult0 in H2;apply Qlt_trans with (y:=0);
auto;reflexivity.
- hnf. intros. apply Rinv_def_lemma in H. pose proof Dedekind_inv A H0 H.
rename H2 into HV. pose proof Rmult_situation A (Cut_inv A) H0 HV.
assert( A 1 \/ Cut_inv A 1 \/(~ A 1 /\ ~ Cut_inv A 1)).
{ intros. assert(A 1 \/ ~ A 1). apply classic.
destruct H3. auto.
assert(Cut_inv A 1 \/ ~ Cut_inv A 1). apply classic.
destruct H4. auto.
repeat right. split;auto. }
destruct H3 as [?|[]].
+ destruct H2 as [?|[?|[?|[]]]].
* left. split;auto.
destruct H2.
assert(x <= 0 \/ ~ x <= 0). apply classic. destruct H5.
{ destruct (Dedekind_properties3 _ H0 0);auto. destruct H6.
destruct (Dedekind_properties3 _ HV 0);auto. destruct H8.
exists x0, x1. repeat split;auto.
apply Qle_trans with (y:=0). auto.
apply Qlt_le_weak. apply Qlt_mult0;auto. }
{ apply Qnot_le_lt in H5. apply invlemma1;auto. }
* destruct H2, H2, H2, H5.
apply (Dedekind_properties2 _ H0 1).
split;auto. rewrite <- Qplus_le_l with (z:=x0).
assert(- 0 + - x0 + x0==0)%Q. field. rewrite H5.
rewrite <- Qplus_0_r.
apply Qplus_le_compat;apply Qlt_le_weak;auto;reflexivity.
* destruct H2. pose proof Cut_inv_same A H0 H2.
apply Cut_cut_opp_not in H5;auto. destruct H5. auto.
* destruct H2, H2, H2, H5. apply (Dedekind_properties2 _ H0 1).
split;auto. rewrite <- Qplus_le_l with (z:=x0).
assert(- 0 + - x0 + x0==0)%Q. field. rewrite H5.
rewrite <- Qplus_0_r.
apply Qplus_le_compat;apply Qlt_le_weak;auto;reflexivity.
* destruct H2, H2.
{ destruct H2. apply (Dedekind_properties2 _ H0 1).
split. auto. apply Qlt_le_weak. reflexivity. }
{ destruct H2. apply Cut_inv_same;auto. apply (Dedekind_properties2 _ H0 1).
split. auto. apply Qlt_le_weak. reflexivity. }
+ rename HV into H'.
rename H0 into HV. rename H' into H0.
destruct H2 as [?|[?|[?|[]]]].
* left.
destruct H2.
assert(x <= 0 \/ ~ x <= 0). apply classic. destruct H5.
{ destruct (Dedekind_properties3 _ H0 0);auto. destruct H6.
destruct (Dedekind_properties3 _ HV 0);auto. destruct H8.
repeat split;auto.
exists x1, x0. repeat split;auto.
apply Qle_trans with (y:=0). auto.
apply Qlt_le_weak. apply Qlt_mult0;auto. }
{ apply Qnot_le_lt in H5. repeat split;auto. apply invlemma2;auto. }
* destruct H2, H2, H2, H5. destruct H4 as [?|[]].
** destruct H4.
apply (Dedekind_properties2 _ HV 0).
split;auto. rewrite <- Qplus_le_l with (z:=x0).
assert(- 0 + - x0 + x0==0)%Q. field. rewrite H6.
rewrite Qplus_0_l. apply Qlt_le_weak. auto.
** destruct H4, H5. inversion H5.
** destruct H4, H5, H6.
* destruct H2. pose proof Cut_inv_same A HV H2.
apply Cut_cut_opp_not in H5;auto. destruct H5. auto.
* destruct H2, H4, H4, H5. apply (Dedekind_properties2 _ H0 1).
split;auto. rewrite <- Qplus_le_l with (z:=x0).
assert(- 0 + - x0 + x0==0)%Q. field. rewrite H5.
rewrite <- Qplus_0_r.
apply Qplus_le_compat;apply Qlt_le_weak;auto;reflexivity.
* destruct H2, H2.
{ destruct H2. destruct H3 as [?|[]].
** apply H2.
** destruct H2, H3. inversion H3.
** destruct H2, H3, H5. }
{ destruct H2. apply (Dedekind_properties2 _ H0 1).
split. auto. apply Qlt_le_weak. reflexivity. }
+ assert(forall y : Q, y< 1 -> A y /\ Cut_inv A y).
{ intros. split.
* destruct H3. apply NNPP. hnf. intros. destruct H5.
hnf in IH. destruct IH. destruct H7, H7.
assert(A 0). apply (Dedekind_properties2 _ H0 x0);split;auto.
apply Qnot_lt_le. auto.
left. split;auto. right. split. reflexivity.
exists (1-y). split. rewrite <- Qplus_lt_r with (z:=y).
assert(y + (1 - y)==1)%Q. field. rewrite H10. rewrite Qplus_0_r. apply H4.
assert(/ 1 + - (1 - y)==y)%Q. field. rewrite H10. auto.
* destruct H3. left. assert(A 0).
hnf in IH. destruct IH. destruct H7, H7.
apply (Dedekind_properties2 _ H0 x0);split;auto.
apply Qnot_lt_le. auto. split;auto.
assert(y <= 0 \/ ~ y <= 0). apply classic. destruct H7.
left. auto. right. apply Qnot_le_lt in H7. split. auto.
exists (/y - 1). split. rewrite <- Qplus_lt_r with (z:=1).
assert(forall y : Q, 1 + (y -1)==y)%Q. intros. field.
rewrite H8. rewrite Qplus_0_r. rewrite <- Qinv_involutive.
apply Qdiv_lt_P;auto.
assert(forall y : Q, y + - (y - 1)==1)%Q. intros. field. rewrite H8. auto. }
destruct (H4 (/(2#1) * (1+x))).
{ rewrite <- Qmult_lt_r with (z:=(2#1));try reflexivity.
assert(/ (2 # 1) * (1 + x) * (2 # 1)==1+x)%Q. field. rewrite H5.
rewrite <- Qplus_lt_l with (z:=-(1)%Q).
assert(1 + x + - (1)==x)%Q. field. rewrite H6. auto. }
left. destruct (H4 0). reflexivity. repeat split;auto.
assert((x <= 0 \/ ~ x <= 0)). apply classic. destruct H9.
{ destruct (Dedekind_properties3 _ H0 0);auto. destruct H10.
destruct (Dedekind_properties3 _ HV 0);auto. destruct H12.
exists x0, x1. repeat split;auto.
apply Qle_trans with (y:=0);auto.
apply Qmult_le_0_compat;apply Qlt_le_weak;auto. }
apply Qnot_le_lt in H9.
assert(0 < / (2 # 1) * (1 + x)). apply Qlt_mult0. reflexivity.
apply Qlt_trans with (y:=1+0). reflexivity. apply Qplus_lt_r. auto.
exists (/ (2 # 1) * (1 + x)), (/ (2 # 1) * (1 + x)).
repeat split;auto. rewrite <- Qplus_le_l with (z:=-x).
rewrite Qplus_opp_r.
assert(/ (2 # 1) * (1 + x) * (/ (2 # 1) * (1 + x)) + - x ==
/ (2 # 1) * (1 - x) * (/ (2 # 1) * (1 - x)) )%Q. field.
rewrite H11.
rewrite <- Qmult_le_r with (z:=4#1);try reflexivity.
assert(/ (2 # 1) * (1 - x) * (/ (2 # 1) * (1 - x)) * (4 # 1)==
(1-x)*(1-x))%Q. field. rewrite H12. rewrite Qmult_0_l.
apply Qmult_le_0_compat;apply Qlt_le_weak;unfold Qminus;rewrite <- Qlt_minus_iff;auto.
Qed.
Lemma Rinv_eq' : forall (a b: Real) (H1 : ~ a == Rzero) (H2 : ~ b == Rzero),
a == b -> (Rinv a H1 <= Rinv b H2)%R.
Proof.
intros. hnf.
+ hnf. destruct a, b. hnf. intros. destruct H. hnf in *.
destruct H4 as [?|[]].
{ left. destruct H4. repeat split;auto.
destruct H6. left. auto. right.
destruct H6, H7, H7. split;auto.
exists x0. split;auto. }
{ right. left. destruct H4, H6, H7, H7.
pose proof Cut_opp_eq A A0 H0 H3. unfold Cuteq in *. destruct H9.
assert(forall x : Q, Cut_opp A x <-> Cut_opp A0 x). apply H9.
split;auto. split;auto. apply H11;auto. split;auto.
exists x0. split;auto. }
{ destruct H4, H6, H7. }
Qed.
Lemma Rinv_eq : forall (a b: Real) (H1 : ~ a == Rzero) (H2 : ~ b == Rzero),
a == b -> (Rinv a H1 == Rinv b H2)%R.
Proof.
intros. split;apply Rinv_eq';auto. rewrite H. reflexivity.
Qed.
Theorem Rinv_opp :
forall (a : Real) (H : ~ a == Rzero),(- Rinv a H == Rinv (-a) (Rnot_0 a H))%R.
Proof.
intros. hnf. split.
- destruct a. hnf. intros.
apply Rinv_def_lemma in H. apply Cut_inv_opp;auto.
- destruct a. hnf. intros. apply Cut_opp_inv;auto.
apply Rinv_def_lemma in H. auto.
Qed.
Theorem Rmult_inv :
forall (a : Real) (H : ~ a == Rzero),(a * Rinv a H == Rone)%R.
Proof.
intros. hnf. assert(Rzero<a\/~Rzero<a)%R. apply classic.
destruct H0. rename H0 into IH.
- apply Rmult_inv'. auto.
- pose proof Ropp_opp a. assert(~--a==Rzero)%R.
{ rewrite <- H1. auto. }
assert(Rinv a H == Rinv (--a)%R H2).
{ apply Rinv_eq. auto. }
rewrite H3.
pose proof Rnot_0 (a)%R H.
pose proof Rinv_opp (-a)%R H4.
assert(Rinv (- - a)%R (Rnot_0 (- a)%R H4) == Rinv (- - a)%R H2).
{ apply Rinv_eq. reflexivity. }
rewrite H6 in H5. clear H6. rewrite <- H5.
rewrite <- Rmult_opp_r. rewrite Rmult_opp_l.
apply Rmult_inv'. destruct (R_three_dis Rzero (-a)%R) as [?|[]].
+ auto.
+ destruct H4. rewrite H6. reflexivity.
+ apply Rnot_lt_le in H0. rewrite Rle_lt_eq in H0.
destruct H0. destruct H. auto. rewrite Ropp_opp.
apply Ropp_lt_compat. assert(-Rzero == Rzero)%R.
{ assert(-Rzero == (Rzero + - Rzero))%R. rewrite Rplus_0_l. reflexivity.
rewrite H7. rewrite Rplus_opp. reflexivity. }
rewrite H7. auto.
Qed.
Record Rdedekind ( A : Real-> Prop) : Prop := {
Rdedekind_properties1 : (exists (x : Real) , A x) /\ (exists (x : Real) , ~ A x) ;
Rdedekind_properties2 : forall (p q : Real) , A p /\ (Rle q p) -> A q ;
Rdedekind_properties3 : forall (p : Real) , A p -> (exists r, A r /\ (Rlt p r)) ;
Rdedekind_properties4 : forall (p q : Real), p == q -> A p -> A q ;
}.
Lemma RQle : forall (a : Real), exists x : Q, ((Q_to_R x) <= a)%R.
Proof.
intros. destruct a. destruct (Dedekind_properties1 _ H), H0, H1.
exists x. hnf. intros.
apply (Dedekind_properties2 _ H x);split;try apply Qlt_le_weak;auto.
Qed.
Lemma QRle : forall (a : Real), exists x : Q, (a <= (Q_to_R x))%R.
Proof.
intros. destruct a. destruct (Dedekind_properties1 _ H), H0, H1.
exists x0. hnf. intros.
apply (Dedekind_le A);auto.
Qed.
Lemma RQdensity : forall p q : Real, (p < q ->
exists x : Q, p < (Q_to_R x) /\ (Q_to_R x) < q)%R.
Proof.
intros. hnf in *. destruct p, q, H, H2, H2.
apply (Dedekind_properties3 _ H1) in H2. destruct H2, H2.
exists x0. split.
- hnf. split.
+ intros. apply (Dedekind_le A);auto. hnf. intros.
apply H3. apply (Dedekind_properties2 _ H0 x0);split;try apply Qlt_le_weak;auto.
+ exists x. auto.
- hnf. split.
+ intros. apply (Dedekind_properties2 _ H1 x0);split;try apply Qlt_le_weak;auto.
+ apply (Dedekind_properties3 _ H1) in H2. destruct H2, H2.
exists x1. split;auto. apply Qle_not_lt. apply Qlt_le_weak. auto.
Qed.
Lemma Dedekind_complete : forall ( A : Real-> Prop),
Rdedekind A -> Dedekind (fun x : Q =>A (Q_to_R x)).
Proof.
intros. split.
- split.
+ destruct (Rdedekind_properties1 _ H). destruct H0.
pose proof RQle x. destruct H2.
exists x0. apply (Rdedekind_properties2 _ H x);auto.
+ destruct (Rdedekind_properties1 _ H). destruct H1.
pose proof QRle x. destruct H2.
exists x0. hnf. intros. apply H1.
apply (Rdedekind_properties2 _ H (Q_to_R x0));auto.
- intros. destruct H0.
apply (Rdedekind_properties2 _ H (Q_to_R p));split;auto.
hnf. intros. apply Qlt_le_trans with (y:=q);auto.
- intros. apply (Rdedekind_properties3 _ H) in H0. destruct H0, H0.
pose proof RQdensity (Q_to_R p) x H1. destruct H2, H2.
exists x0. split. apply (Rdedekind_properties2 _ H x);split;try apply Rlt_le_weak;auto.
hnf in H2. destruct H2, H4, H4. apply Qnot_lt_le in H5.
apply Qle_lt_trans with (y:= x1);auto.
- intros. apply (Rdedekind_properties4 _ H (Q_to_R p)).
hnf. split;hnf;intros;rewrite H0 in *;auto. auto.
Qed.
Theorem R_complete' : forall A : Real -> Prop, Rdedekind A ->
exists a : Real, forall b : Real, A b <-> (b < a)%R.
Proof.
intros. pose proof Dedekind_complete A H.
exists (Real_cons (fun x : Q =>A (Q_to_R x)) H0).
intros. split.
- intros. hnf. destruct b. split.
+ intros. apply (Rdedekind_properties2 _ H (Real_cons A0 H2)).
split;auto. hnf. intros.
apply (Dedekind_properties2 _ H2 x);split;try apply Qlt_le_weak;auto.
+ apply (Rdedekind_properties3 _ H) in H1. destruct H1, H1.
hnf in H3. destruct x, H3, H5, H5. exists x. split;auto.
apply (Rdedekind_properties2 _ H (Real_cons A1 H4)).
split;auto. hnf. intros.
apply (Dedekind_properties2 _ H4 x);split;try apply Qlt_le_weak;auto.
- intros. hnf in *. destruct b. destruct H1, H3, H3.
apply (Rdedekind_properties2 _ H (Q_to_R x));split;auto.
hnf. intros. apply (Dedekind_le A0);auto.
Qed.
Theorem R_complete : forall A : Real -> Prop, Rdedekind A ->
exists a : Real, ~ A a /\ (forall b : Real,~ A b <-> (a <= b)%R).
Proof.
intros. pose proof R_complete' A H. destruct H0. exists x.
split.
- hnf. intros. apply H0 in H1. apply Rlt_not_refl in H1. auto.
- intros. split.
+ intros. apply Rnot_lt_le. hnf. intros. apply H1.
apply H0. auto.
+ intros. hnf. intros. apply H0 in H2. apply Rlt_not_le in H1;auto.
Qed.
|
[STATEMENT]
lemma conforms_hext: "[|(x,(h,l))::\<preceq>(G,lT); h\<le>|h'; G\<turnstile>h h'\<surd> |]
==> (x,(h',l))::\<preceq>(G,lT)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>(x, h, l) ::\<preceq> (G, lT); h \<le>| h'; G \<turnstile>h h' \<surd>\<rbrakk> \<Longrightarrow> (x, h', l) ::\<preceq> (G, lT)
[PROOF STEP]
by (fast dest: conforms_localD conforms_xcptD elim!: conformsI xconf_hext) |
namespace prop_logic
/-
This assignment has five problems. The first
is to extend our propositional logic syntax
and semantics to support the three additional
connectives, exclusive or (⊕), implies (which
we will write as ⇒), and if and only iff (↔).
We first give you the definitions developed
in class. You are to extend/modify them to
support expressions with the new connectives.
The remaining problems use this definition of
our language of expressions in propositional
logic.
-/
/-
1. Extend our syntax and semantics
for propositional logic to support
the xor, implies, and iff and only
iff connectives/operators.
A. Add support for the exclusive or
connective/operator. Define the symbol,
⊕, as an infix notation.
Here are specific steps to take for the
exclusive or connective, as an example.
1. Add new binary connective, xorOp
2. Add pXor as shorthand for binOpExp xorOp
3. Add ⊕ as an infix notation for pXor
4. Specify the interpretation of ⊕ to be bxor
5. Extend interpBinOp to handle the new case
Then add support for the implies connective,
using the symbol, ⇒, as an infix operator.
We can't use → because it's reserved by Lean
and cannot be overloaded. Lean does not have
a Boolean implies operator (analogous to bor),
so you will have to define one. Call it bimpl.
Finally add support for if and only iff. Use
the symbol ↔ as an infix notation. You will
have to define a Boolean function as Lean
does not provide one for iff. Call it biff.
Here is the code as developed in class.
Now review the step-by-step instructions,
and proceed to read and midify this logic
as required. We've bracketed areas where
new material will have to be added.
-/
/- *** SYNTAX *** -/
inductive var : Type
| mkVar : ℕ → var
inductive unOp : Type
| notOp
inductive binOp : Type
| andOp
| orOp
| xorOp
| implOp
| iffOp
inductive pExp : Type
| litExp : bool → pExp
| varExp : var → pExp
| unOpExp : unOp → pExp → pExp
| binOpExp : binOp → pExp → pExp → pExp
open var
open pExp
open unOp
open binOp
-- Shorthand notations
def pTrue := litExp tt
def pFalse := litExp ff
def pNot := unOpExp notOp
def pAnd := binOpExp andOp
def pOr := binOpExp orOp
def pXor := binOpExp xorOp
def pImpl := binOpExp implOp
def pIff := binOpExp iffOp
-- conventional notation
notation e1 ∧ e2 := pAnd e1 e2
notation e1 ∨ e2 := pOr e1 e2
notation ¬ e := pNot e
notation e1 ⊕ e2 := pXor e1 e2
notation e1 ⇒ e2 := pImpl e1 e2
notation e1 ↔ e2 := pIff e1 e2
/-
*****************
*** SEMANTICS ***
*****************
-/
def interpUnOp : unOp → (bool → bool)
| notOp := bnot
def bimpl: bool → bool → bool
| tt tt:= tt
| tt ff:= ff
| ff tt:= tt
| ff ff:= tt
def biff: bool → bool → bool
| tt tt:= tt
| tt ff:= ff
| ff tt:= ff
| ff ff:= tt
def interpBinOp : binOp → (bool → bool → bool)
| andOp := band
| orOp := bor
| xorOp := bxor
| implOp := bimpl
| iffOp := biff
/- *** SEMANTICS *** -/
/-
Given a pExp and an interpretation
for the variables, compute and return
the Boolean value of the expression.
-/
def pEval : pExp → (var → bool) → bool
| (litExp b) i := b
| (varExp v) i := i v
| (unOpExp op e) i :=
(interpUnOp op) (pEval e i)
| (binOpExp op e1 e2) i :=
(interpBinOp op)
(pEval e1 i)
(pEval e2 i)
/-
Note: You are free to use pEval, if you
wish to, to check answers to some of the
questions below. It is not mandatory and
you will not be marked down for not doing
this.
-/
/-
#2. Define X, Y, and Z to be variable
expressions bound to a different variable
expression terms. Hint: Look at the
prop_logic_test.lean file to remind
yourself how we did this in class.
-/
def X : pExp := varExp (mkVar 0)
def Y : pExp := varExp (mkVar 1)
def Z : pExp := varExp (mkVar 2)
/-
#3. Here are some English language
sentences that you are to re-express
in propositional logic. Here's one
example.
-/
/-
EXAMPLE:
Formalize the following proposition,
as a formula in propositional logic:
If it's raining then it's raining.
-/
-- Use R to represent "it's raining"
def R : pExp := varExp (mkVar 4)
-- Solution here
def p1 : pExp := pImpl R R
/-
Explanation: We first choose to represent
the smaller proposition, "it's raining",
by the variable expression, R. We then
formalize the overall natural language
expression, if R then R, as the formula,
R ⇒ R.
Note: R ⇒ R can be pronounced as any of:
- if R is true then R is true
- if R then R
- the truth of R implies the truth of R
- R implies R
The second and fourth pronounciations
are the two that we prefer to use.
-/
/-
For the remaining problems, use the
variables expressions, X, Y, and Z,
as already defined. Use parentheses
if needed to group sub-expressions.
-/
/-
A.
If it's raining and the streets are
wet then it's raining.
-/
def p2 : pExp := (X ∧ Y) ⇒ X
/-
B. If it's raining and the streets
are wet, then the streets are wet
and it's raining.
-/
def p3 := (X ∧ Y) ⇒ (Y ∧ X)
/-
C. If it's raining then if the
streets are wet then it's raining
and the streets are wet.
-/
def p4 := X ⇒ (Y ⇒ (X ∧ Y))
/-
D. If it's raining then it's
raining or the moon is made of
green cheese.
-/
def p5 := X ⇒ (X ∨ Z)
/-
E. If it's raining, then if it's
raining implies that the streets
are wet, then the streets are wet.
-/
def p6 := X ⇒ ((X ⇒ Y) ⇒ Y)
/-
#4. For each of the propositional
logic expressions below, write a truth
table and based on your result, state
whether the expression is unsatisfiable,
satisfiable but not valid, or valid.
Here's an example solution for the
expression, (X ∧ Y) ⇒ Y.
X Y X ∧ Y (X ∧ Y) ⇒ Y
- - ----- -----------
T T T T
T F F T
F T F T
F F F T
The proposition is valid.
-/
/-
A. After each "#check" give your
answer for the specified proposition.
That is, write a truth table in a
comment and then say whether given the
proposition is valid, satisfiable but
not valid, or unsatisifiable.
Note: This expression reqires that
you have properly specified ¬ and
⇒ as notations in our pExp language.
The errors indicated in many of the
following lines will go away once
you have these notations properly
defined.
-/
#check (X ⇒ Y) ⇒ (¬ X ⇒ ¬ Y)
/-
X Y ¬X ¬Y X⇒Y ¬X⇒¬Y (X⇒Y)⇒(¬X⇒¬Y)
- - -- -- --- ----- -------------
T T F F T T T
T F F T F T T
F T T F T F F
F F T T T T T
The proposition is satisfiable but not valid
-/
/-
B.
-/
#check ((X ⇒ Y) ∧ (Y ⇒ X)) ⇒ (X ⇒ Z)
/-
X Y Z X⇒Y Y⇒X (X⇒Y)∧(Y⇒X) (X⇒Z) ((X⇒Y)∧(Y⇒X))⇒(X⇒Z)
- - - --- --- ----------- ----- -------------------
T T T T T T T T
T T F T T T F F
T F T F T F T T
T F F F T F F T
F T T T F F T T
F T F T F F T T
F F T T T T T T
F F F T T T T T
The proposition is satisfiable but not valid
-/
/-
C.
-/
#check pFalse ⇒ (X ∧ ¬ X)
/-
pFalse X ¬X X∧¬X pFalse⇒(X∧¬X)
------ - -- ---- -------------
F T F F T
F F T F T
The proposition is valid
-/
/-
D.
-/
#check pTrue ⇒ (X ∧ ¬ X)
/-
pTrue X ¬X X∧¬X pTrue⇒(X∧¬X)
------ - -- ---- -------------
T T F F F
T F T F F
The proposition is unsatisifiable
-/
/-
E.
-/
#check (X ∨ Y) ∧ X ⇒ ¬ Y
/-
X Y ¬Y X∨Y (X∨Y)∧X (X∨Y)∧X⇒¬Y
- - -- --- ------- ----------
T T F T T F
T F T T T T
F T F T F T
F F T F F T
The proposition is satisfiable but not valid
-/
/-
#5.
A. Find and present an interpretation
that causes the following proposition
to be satisfied (to evaluate to true).
(X ∨ Y) ∧ (¬ Y ∨ Z)
Answer:
Let X be True, Y be True and Z be True. Then X ∨ Y is True and
¬ Y ∨ Z is also True. It follows that (X ∨ Y) ∧ (¬ Y ∨ Z) is True.
B. Count and state how many of the
possible interpretations satisfy the
formula.
Answer:
X Y Z X∨Y ¬Y ¬Y∨Z (X∨Y)∧(¬Y∨Z)
- - - --- -- ---- ------------
T T T T F T T
T T F T F F F
T F T T T T T
T F F T T T T
F T T T F T T
F T F T F F F
F F T F T T F
F F F F T T F
There are 4 interpretations satisfying the formula.
-/
end prop_logic
|
### Reference state
using DocStringExtensions
using ..TemperatureProfiles
export NoReferenceState, HydrostaticState
using CLIMAParameters.Planet: R_d, MSLP, cp_d, grav, T_surf_ref, T_min_ref
"""
ReferenceState
Reference state, for example, used as initial
condition or for linearization.
"""
abstract type ReferenceState end
vars_state_conservative(m::ReferenceState, FT) = @vars()
vars_state_gradient(m::ReferenceState, FT) = @vars()
vars_state_gradient_flux(m::ReferenceState, FT) = @vars()
vars_state_auxiliary(m::ReferenceState, FT) = @vars()
atmos_init_aux!(
::ReferenceState,
::AtmosModel,
aux::Vars,
geom::LocalGeometry,
) = nothing
"""
NoReferenceState <: ReferenceState
No reference state used
"""
struct NoReferenceState <: ReferenceState end
"""
HydrostaticState{P,T} <: ReferenceState
A hydrostatic state specified by a virtual temperature profile and relative humidity.
"""
struct HydrostaticState{P, FT} <: ReferenceState
virtual_temperature_profile::P
relative_humidity::FT
end
function HydrostaticState(
virtual_temperature_profile::TemperatureProfile{FT},
) where {FT}
return HydrostaticState{typeof(virtual_temperature_profile), FT}(
virtual_temperature_profile,
FT(0),
)
end
vars_state_auxiliary(m::HydrostaticState, FT) =
@vars(ρ::FT, p::FT, T::FT, ρe::FT, ρq_tot::FT)
function atmos_init_aux!(
m::HydrostaticState{P, F},
atmos::AtmosModel,
aux::Vars,
geom::LocalGeometry,
) where {P, F}
z = altitude(atmos, aux)
T_virt, p = m.virtual_temperature_profile(atmos.param_set, z)
FT = eltype(aux)
_R_d::FT = R_d(atmos.param_set)
ρ = p / (_R_d * T_virt)
aux.ref_state.ρ = ρ
aux.ref_state.p = p
# We evaluate the saturation vapor pressure, approximating
# temperature by virtual temperature
# ts = TemperatureSHumEquil(atmos.param_set, T_virt, ρ, FT(0))
ts = PhaseDry_given_ρT(atmos.param_set, ρ, T_virt)
q_vap_sat = q_vap_saturation(ts)
ρq_tot = ρ * relative_humidity(m) * q_vap_sat
aux.ref_state.ρq_tot = ρq_tot
q_pt = PhasePartition(ρq_tot)
R_m = gas_constant_air(atmos.param_set, q_pt)
T = T_virt * R_m / _R_d
aux.ref_state.T = T
aux.ref_state.ρe = ρ * internal_energy(atmos.param_set, T, q_pt)
e_kin = F(0)
e_pot = gravitational_potential(atmos.orientation, aux)
aux.ref_state.ρe = ρ * total_energy(atmos.param_set, e_kin, e_pot, T, q_pt)
end
"""
relative_humidity(hs::HydrostaticState{P,FT})
Here, we enforce that relative humidity is zero
for a dry adiabatic profile.
"""
relative_humidity(hs::HydrostaticState{P, FT}) where {P, FT} =
hs.relative_humidity
relative_humidity(hs::HydrostaticState{DryAdiabaticProfile, FT}) where {FT} =
FT(0)
|
Formal statement is: lemma open_Times: "open S \<Longrightarrow> open T \<Longrightarrow> open (S \<times> T)" Informal statement is: If $S$ and $T$ are open sets, then $S \times T$ is open. |
#' Plot catch curves for catch
#'
#' Creates catch curves to estimate Z from catch data. Useful???
#' @param asap name of the variable that read in the asap.rdat file
#' @param a1 list file produced by grab.aux.files function
#' @param save.plots save individual plots
#' @param od output directory for plots and csv files
#' @param plotf type of plot to save
#' @param first.age youngest age to use in catch curve, -999 finds peak age (defaults to -999)
#' @export
PlotCatchCurvesForCatch <- function(asap,a1,save.plots,od,plotf,first.age=-999){
# create catch curve plots for catch by fleet
usr <- par("usr"); on.exit(par(usr))
par(oma=c(1,1,1,1),mar=c(4,4,1,0.5))
cohort <- seq(asap$parms$styr-asap$parms$nages-1, asap$parms$endyr+asap$parms$nages-1)
ages <- seq(1,asap$parms$nages)
my.col <- rep(c("blue","red","green","orange","gray50"),50)
for (ifleet in 1:asap$parms$nfleets){
if (asap$parms$nfleets == 1) title1 = "Catch"
if (asap$parms$nfleets >= 2) title1 = paste0("Catch for Fleet ",ifleet)
# set up full age range matrices
catch.comp.mat.ob <- matrix(0, nrow=asap$parms$nyears, ncol=asap$parms$nages)
catch.comp.mat.pr <- matrix(0, nrow=asap$parms$nyears, ncol=asap$parms$nages)
# determine age range for fleet and fill in appropriate ages
age1 <- asap$fleet.sel.start.age[ifleet]
age2 <- asap$fleet.sel.end.age[ifleet]
catch.comp.mat.ob[,age1:age2] <- asap$catch.comp.mats[[(ifleet*4-3)]]
catch.comp.mat.pr[,age1:age2] <- asap$catch.comp.mats[[(ifleet*4-2)]]
# get catch at age
catchob <- wtprop2caa(asap$catch.obs[ifleet,], asap$WAA.mats[[(ifleet*2-1)]], catch.comp.mat.ob)
catchpr <- wtprop2caa(asap$catch.pred[ifleet,], asap$WAA.mats[[(ifleet*2-1)]], catch.comp.mat.pr)
# replace zeros with NA and take logs
cob <- rep0log(catchob)
cpr <- rep0log(catchpr)
# make cohorts
cob.coh <- makecohorts(cob)
cpr.coh <- makecohorts(cpr)
# drop plus group
cob.coh[,asap$parms$nages] <- NA
cpr.coh[,asap$parms$nages] <- NA
first.age.label <- 1
if (first.age==1) title1 <- paste0(title1," First Age = 1")
# determine which ages to use for each cohort (default)
if (first.age == -999){
cob.coh <- find_peak_age(cob.coh)
cpr.coh <- find_peak_age(cpr.coh)
first.age.label <- "find_peak"
title1 <- paste0(title1," (Peak Age)")
}
# or drop youngest ages based on user control
if (first.age > 1) {
cob.coh[,1:(first.age-1)] <- NA
cpr.coh[,1:(first.age-1)] <- NA
title1 <- paste0(title1," First Age = ",first.age)
first.age.label <- first.age
}
# compute Z by cohort
z.ob <- calc_Z_cohort(cob.coh)
z.pr <- calc_Z_cohort(cpr.coh)
# make the plots
par(mfrow=c(2,1))
plot(cohort,cohort,type='n',ylim=range(c(cob.coh,cpr.coh,0),na.rm=T),xlab="",ylab="Log(Catch)",main=paste0(title1," Observed"))
for (i in 1:length(cob.coh[,1])){
lines(seq(cohort[i],cohort[i]+asap$parms$nages-1),cob.coh[i,],type='p',lty=1,pch=seq(1,asap$parms$nages),col="gray50")
lines(seq(cohort[i],cohort[i]+asap$parms$nages-1),cob.coh[i,],type='l',lty=1,col=my.col[i])
}
Hmisc::errbar(cohort,z.ob[,1],z.ob[,3],z.ob[,2],xlab="Year Class",ylab="Z",ylim=range(c(z.ob,z.pr,0),na.rm=T))
if (save.plots) savePlot(paste0(od,"catch_curve_",title1,"_Observed_first_age_",first.age.label,".",plotf), type=plotf)
plot(cohort,cohort,type='n',ylim=range(c(cob.coh,cpr.coh,0),na.rm=T),xlab="",ylab="Log(Catch)",main=paste0(title1," Predicted"))
for (i in 1:length(cob.coh[,1])){
lines(seq(cohort[i],cohort[i]+asap$parms$nages-1),cpr.coh[i,],type='p',lty=1,pch=seq(1,asap$parms$nages),col="gray50")
lines(seq(cohort[i],cohort[i]+asap$parms$nages-1),cpr.coh[i,],type='l',lty=1,col=my.col[i])
}
Hmisc::errbar(cohort,z.pr[,1],z.pr[,3],z.pr[,2],xlab="Year Class",ylab="Z",ylim=range(c(z.ob,z.pr,0),na.rm=T))
if (save.plots) savePlot(paste0(od,"catch_curve_",title1,"_Predicted_first_age_",first.age.label,".",plotf), type=plotf)
# write out .csv files for Z, one file for each fleet
asap.name <- a1$asap.name
colnames(z.ob) <-c("Z.obs","low.80%", "high.80%")
write.csv(z.ob, file=paste0(od,"Z.Ob.Fleet",ifleet,"_",asap.name,".csv"), row.names=cohort)
colnames(z.pr) <-c("Z.pred","low.80%", "high.80%")
write.csv(z.pr, file=paste0(od,"Z.Pr.Fleet.",ifleet,"_",asap.name,".csv"), row.names=cohort)
}
return()
}
|
[GOAL]
𝕜 : Type u_1
inst✝¹⁰ : NontriviallyNormedField 𝕜
𝕜' : Type u_2
inst✝⁹ : NontriviallyNormedField 𝕜'
inst✝⁸ : NormedAlgebra 𝕜 𝕜'
E : Type u_3
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
inst✝⁵ : NormedSpace 𝕜' E
inst✝⁴ : IsScalarTower 𝕜 𝕜' E
F : Type u_4
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace 𝕜 F
inst✝¹ : NormedSpace 𝕜' F
inst✝ : IsScalarTower 𝕜 𝕜' F
f : E → F
f' : E →L[𝕜'] F
s : Set E
x : E
g' : E →L[𝕜] F
h : HasFDerivWithinAt f g' s x
H : restrictScalars 𝕜 f' = g'
⊢ HasFDerivWithinAt f f' s x
[PROOFSTEP]
rw [← H] at h
[GOAL]
𝕜 : Type u_1
inst✝¹⁰ : NontriviallyNormedField 𝕜
𝕜' : Type u_2
inst✝⁹ : NontriviallyNormedField 𝕜'
inst✝⁸ : NormedAlgebra 𝕜 𝕜'
E : Type u_3
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
inst✝⁵ : NormedSpace 𝕜' E
inst✝⁴ : IsScalarTower 𝕜 𝕜' E
F : Type u_4
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace 𝕜 F
inst✝¹ : NormedSpace 𝕜' F
inst✝ : IsScalarTower 𝕜 𝕜' F
f : E → F
f' : E →L[𝕜'] F
s : Set E
x : E
g' : E →L[𝕜] F
h : HasFDerivWithinAt f (restrictScalars 𝕜 f') s x
H : restrictScalars 𝕜 f' = g'
⊢ HasFDerivWithinAt f f' s x
[PROOFSTEP]
exact h
[GOAL]
𝕜 : Type u_1
inst✝¹⁰ : NontriviallyNormedField 𝕜
𝕜' : Type u_2
inst✝⁹ : NontriviallyNormedField 𝕜'
inst✝⁸ : NormedAlgebra 𝕜 𝕜'
E : Type u_3
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
inst✝⁵ : NormedSpace 𝕜' E
inst✝⁴ : IsScalarTower 𝕜 𝕜' E
F : Type u_4
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace 𝕜 F
inst✝¹ : NormedSpace 𝕜' F
inst✝ : IsScalarTower 𝕜 𝕜' F
f : E → F
f' : E →L[𝕜'] F
s : Set E
x : E
g' : E →L[𝕜] F
h : HasFDerivAt f g' x
H : restrictScalars 𝕜 f' = g'
⊢ HasFDerivAt f f' x
[PROOFSTEP]
rw [← H] at h
[GOAL]
𝕜 : Type u_1
inst✝¹⁰ : NontriviallyNormedField 𝕜
𝕜' : Type u_2
inst✝⁹ : NontriviallyNormedField 𝕜'
inst✝⁸ : NormedAlgebra 𝕜 𝕜'
E : Type u_3
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
inst✝⁵ : NormedSpace 𝕜' E
inst✝⁴ : IsScalarTower 𝕜 𝕜' E
F : Type u_4
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace 𝕜 F
inst✝¹ : NormedSpace 𝕜' F
inst✝ : IsScalarTower 𝕜 𝕜' F
f : E → F
f' : E →L[𝕜'] F
s : Set E
x : E
g' : E →L[𝕜] F
h : HasFDerivAt f (restrictScalars 𝕜 f') x
H : restrictScalars 𝕜 f' = g'
⊢ HasFDerivAt f f' x
[PROOFSTEP]
exact h
[GOAL]
𝕜 : Type u_1
inst✝¹⁰ : NontriviallyNormedField 𝕜
𝕜' : Type u_2
inst✝⁹ : NontriviallyNormedField 𝕜'
inst✝⁸ : NormedAlgebra 𝕜 𝕜'
E : Type u_3
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
inst✝⁵ : NormedSpace 𝕜' E
inst✝⁴ : IsScalarTower 𝕜 𝕜' E
F : Type u_4
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace 𝕜 F
inst✝¹ : NormedSpace 𝕜' F
inst✝ : IsScalarTower 𝕜 𝕜' F
f : E → F
f' : E →L[𝕜'] F
s : Set E
x : E
hf : DifferentiableWithinAt 𝕜 f s x
hs : UniqueDiffWithinAt 𝕜 s x
⊢ DifferentiableWithinAt 𝕜' f s x ↔ ∃ g', restrictScalars 𝕜 g' = fderivWithin 𝕜 f s x
[PROOFSTEP]
constructor
[GOAL]
case mp
𝕜 : Type u_1
inst✝¹⁰ : NontriviallyNormedField 𝕜
𝕜' : Type u_2
inst✝⁹ : NontriviallyNormedField 𝕜'
inst✝⁸ : NormedAlgebra 𝕜 𝕜'
E : Type u_3
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
inst✝⁵ : NormedSpace 𝕜' E
inst✝⁴ : IsScalarTower 𝕜 𝕜' E
F : Type u_4
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace 𝕜 F
inst✝¹ : NormedSpace 𝕜' F
inst✝ : IsScalarTower 𝕜 𝕜' F
f : E → F
f' : E →L[𝕜'] F
s : Set E
x : E
hf : DifferentiableWithinAt 𝕜 f s x
hs : UniqueDiffWithinAt 𝕜 s x
⊢ DifferentiableWithinAt 𝕜' f s x → ∃ g', restrictScalars 𝕜 g' = fderivWithin 𝕜 f s x
[PROOFSTEP]
rintro ⟨g', hg'⟩
[GOAL]
case mp.intro
𝕜 : Type u_1
inst✝¹⁰ : NontriviallyNormedField 𝕜
𝕜' : Type u_2
inst✝⁹ : NontriviallyNormedField 𝕜'
inst✝⁸ : NormedAlgebra 𝕜 𝕜'
E : Type u_3
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
inst✝⁵ : NormedSpace 𝕜' E
inst✝⁴ : IsScalarTower 𝕜 𝕜' E
F : Type u_4
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace 𝕜 F
inst✝¹ : NormedSpace 𝕜' F
inst✝ : IsScalarTower 𝕜 𝕜' F
f : E → F
f' : E →L[𝕜'] F
s : Set E
x : E
hf : DifferentiableWithinAt 𝕜 f s x
hs : UniqueDiffWithinAt 𝕜 s x
g' : E →L[𝕜'] F
hg' : HasFDerivWithinAt f g' s x
⊢ ∃ g', restrictScalars 𝕜 g' = fderivWithin 𝕜 f s x
[PROOFSTEP]
exact ⟨g', hs.eq (hg'.restrictScalars 𝕜) hf.hasFDerivWithinAt⟩
[GOAL]
case mpr
𝕜 : Type u_1
inst✝¹⁰ : NontriviallyNormedField 𝕜
𝕜' : Type u_2
inst✝⁹ : NontriviallyNormedField 𝕜'
inst✝⁸ : NormedAlgebra 𝕜 𝕜'
E : Type u_3
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
inst✝⁵ : NormedSpace 𝕜' E
inst✝⁴ : IsScalarTower 𝕜 𝕜' E
F : Type u_4
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace 𝕜 F
inst✝¹ : NormedSpace 𝕜' F
inst✝ : IsScalarTower 𝕜 𝕜' F
f : E → F
f' : E →L[𝕜'] F
s : Set E
x : E
hf : DifferentiableWithinAt 𝕜 f s x
hs : UniqueDiffWithinAt 𝕜 s x
⊢ (∃ g', restrictScalars 𝕜 g' = fderivWithin 𝕜 f s x) → DifferentiableWithinAt 𝕜' f s x
[PROOFSTEP]
rintro ⟨f', hf'⟩
[GOAL]
case mpr.intro
𝕜 : Type u_1
inst✝¹⁰ : NontriviallyNormedField 𝕜
𝕜' : Type u_2
inst✝⁹ : NontriviallyNormedField 𝕜'
inst✝⁸ : NormedAlgebra 𝕜 𝕜'
E : Type u_3
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
inst✝⁵ : NormedSpace 𝕜' E
inst✝⁴ : IsScalarTower 𝕜 𝕜' E
F : Type u_4
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace 𝕜 F
inst✝¹ : NormedSpace 𝕜' F
inst✝ : IsScalarTower 𝕜 𝕜' F
f : E → F
f'✝ : E →L[𝕜'] F
s : Set E
x : E
hf : DifferentiableWithinAt 𝕜 f s x
hs : UniqueDiffWithinAt 𝕜 s x
f' : E →L[𝕜'] F
hf' : restrictScalars 𝕜 f' = fderivWithin 𝕜 f s x
⊢ DifferentiableWithinAt 𝕜' f s x
[PROOFSTEP]
exact ⟨f', hasFDerivWithinAt_of_restrictScalars 𝕜 hf.hasFDerivWithinAt hf'⟩
[GOAL]
𝕜 : Type u_1
inst✝¹⁰ : NontriviallyNormedField 𝕜
𝕜' : Type u_2
inst✝⁹ : NontriviallyNormedField 𝕜'
inst✝⁸ : NormedAlgebra 𝕜 𝕜'
E : Type u_3
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
inst✝⁵ : NormedSpace 𝕜' E
inst✝⁴ : IsScalarTower 𝕜 𝕜' E
F : Type u_4
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace 𝕜 F
inst✝¹ : NormedSpace 𝕜' F
inst✝ : IsScalarTower 𝕜 𝕜' F
f : E → F
f' : E →L[𝕜'] F
s : Set E
x : E
hf : DifferentiableAt 𝕜 f x
⊢ DifferentiableAt 𝕜' f x ↔ ∃ g', restrictScalars 𝕜 g' = fderiv 𝕜 f x
[PROOFSTEP]
rw [← differentiableWithinAt_univ, ← fderivWithin_univ]
[GOAL]
𝕜 : Type u_1
inst✝¹⁰ : NontriviallyNormedField 𝕜
𝕜' : Type u_2
inst✝⁹ : NontriviallyNormedField 𝕜'
inst✝⁸ : NormedAlgebra 𝕜 𝕜'
E : Type u_3
inst✝⁷ : NormedAddCommGroup E
inst✝⁶ : NormedSpace 𝕜 E
inst✝⁵ : NormedSpace 𝕜' E
inst✝⁴ : IsScalarTower 𝕜 𝕜' E
F : Type u_4
inst✝³ : NormedAddCommGroup F
inst✝² : NormedSpace 𝕜 F
inst✝¹ : NormedSpace 𝕜' F
inst✝ : IsScalarTower 𝕜 𝕜' F
f : E → F
f' : E →L[𝕜'] F
s : Set E
x : E
hf : DifferentiableAt 𝕜 f x
⊢ DifferentiableWithinAt 𝕜' f univ x ↔ ∃ g', restrictScalars 𝕜 g' = fderivWithin 𝕜 f univ x
[PROOFSTEP]
exact differentiableWithinAt_iff_restrictScalars 𝕜 hf.differentiableWithinAt uniqueDiffWithinAt_univ
|
# Bayesian Logistic Regression
Contact: [email protected]
Aim of this colab:
Logistic regression with a twist! We will use variational inference to learn a distribution over the learned parameters.
Througout this work we will be focusing on a binary classification task, on
a small dataset (the UCD breast cancer dataset).
## Logistic regression
Learn the weights which best classify the $(x, y)$ pairs in the dataset.
The weights ($w$) and biases $b$, form the parameters which are learned via the following maximization problem:
\begin{equation}
\mathbb{E}_{p^*(x, y)} \log p(y|x, \theta) = \\
\mathbb{E}_{p^*(x, y)} \left[y \log \sigma(w x + b) + (1 - y) \log(1- \sigma(w x + b)\right]
\end{equation}
Here $\sigma$ denotes the sigmoid function.
## Bayesian logistic regression - computing the evidence lower bound
Learn a distribution over the weights which best classify the $(x, y)$ pairs in the dataset.
We now want to learn the distributional parameters of $q(w)$ in order to maximize:
\begin{equation}
\mathbb{E}_{p^*(x, y)} \log p_w(y| x) = \\
\mathbb{E}_{p^*(x, y)} \log \int p(y|x, w) p(w) \delta w = \\
\mathbb{E}_{p^*(x, y)} \log \int p(y|x, w) p(w) \frac{q(w)}{q(w)} \delta w \ge \\
\mathbb{E}_{p^*(x, y)} \mathbb{E}_{q(w)} \log \left[p(y| x, w) \frac{p(w)}{q(w)} \right]= \\
\mathbb{E}_{q(w)} \mathbb{E}_{p^*(x, y)} \log p(y|x, w) - KL(q(w)||p(w)) = \\
\mathbb{E}_{q(w)}\mathbb{E}_{p^*(x, y)} \left[y \log \sigma(w x + b) + (1 - y) \log(1- \sigma(w x + b)\right] - KL(q(w)||p(w))
\end{equation}
In Bayesian Logistic Regression, we thus learn a distribution over parameters
$w$ which can explain the data, while staying close to a chosen prior $p(w)$.
Throughout this lab, we will use Gaussian Distributions for $p(w)$ and $q(w)$.
For more details, see
[this paper](https://pdfs.semanticscholar.org/e407/ea7fda6d152d2186f4b5e27aa04ec2d32dcd.pdf)
or this tutorial
[https://www.ece.rice.edu/~vc3/elec633/logistic.pdf].
### Gradient estimation
In Bayesian Logistic Regression, we aim to learn the parameters of the distribution $q(w)$. We will call these parameters $\theta$. In the case of a
Gaussian distribution, these will be the mean and covariance matrix of a
multivariate distribution. Since we will use stochastic gradient descent to learn $\theta$, we need to be able to compute the gradients with respect to
$\theta$ of our objective. Since our objective contains an expectation with respect to $q(w)$, this can be challenging. To illustrate this, from now on we will denote $q(w)$ as $q_{\theta}(w)$.
Specifically, we are interested in:
\begin{equation}
\nabla_{\theta} \left[\mathbb{E}_{q_{\theta}(w)} \mathbb{E}_{p^*(x, y)} \log p(y|x, w) - KL(q_{\theta}(w)||p(w))\right]
\end{equation}
Since in we will be using Gaussian distributions for $q_{\theta}(w)$ and $p(w)$
$KL(q_{\theta}(w)||p(w))$ can be computed in closed form and we can rely on
TensorFlow's automatic differentiation to compute
$\nabla_{\theta} KL(q_{\theta}(w)||p(w))$.
Let's now turn attention to computing $\nabla_{\theta} \mathbb{E}_{q_{\theta}(w)} \mathbb{E}_{p^*(x, y)} \log p(y| x, w)$. Unlike the KL, the integral
$\mathbb{E}_{q_{\theta}(w)} \mathbb{E}_{p^*(x, y)} \log p(y|x, w)$
is not tractable, and thus cannot be computed in closed form. Thus, we are interested in other approaches to compute the gradient.
### Reinforce gradient estimation
A first approach to compute an estimate of the gradient is to use the
REINFORCE gradient estimator:
\begin{equation}
\nabla_{\theta} \mathbb{E}_{q_{\theta}(w)} \mathbb{E}_{p^*(x, y)} \log p(y| x, w) = \\
\nabla_{\theta} \int q_{\theta}(w) \mathbb{E}_{p^*(x, y)} \log p(y| x, w) \delta w = \\
\int \nabla_{\theta} \left[q_{\theta}(w) \mathbb{E}_{p^*(x, y)} \log p(y| x, w) \right] \delta w = \\
\int \nabla_{\theta} \left[q_{\theta}(w)\right] \mathbb{E}_{p^*(x, y)} \log p(y| x, w) \delta w = \\
\int q_{\theta}(w) \nabla_{\theta} \left[\log q_{\theta}(w)\right] \mathbb{E}_{p^*(x, y)} \log p(y| x, w) \delta w = \\
\mathbb{E}_{q_{\theta}(w)} \left[ \nabla_{\theta} \log q_{\theta}(w) \mathbb{E}_{p^*(x, y)} \log p(y| x, w) \right]
\end{equation}
We can use samples from $q_{\theta}(w)$ to compute the Monte Carlo estimate of
the last integral, to get an unbiased estimator of the true gradient. The more
samples we use to estimate the integral, the more accurate the gradient estimate
will be.
### Pathwise gradient estimation (reparametrization)
In the REINFORCE estimator, we did not use any knowledge of the variational
distribution $q_{\theta}(w)$.
For a Gaussian distribution, we can use the reparametrization trick to obtain
an unbiased gradient estimator of $\nabla_{\theta} \mathbb{E}_{q_{\theta}(w)} \mathbb{E}_{p^*(x, y)} \log p(y| x, w)$.
To do so, we will use the fact that
\begin{equation}
z \sim N(\mu, \sigma), z = \mu + \epsilon \sigma, {\text {with }} \epsilon \sim N(0, 1)
\end{equation}
Namely:
\begin{equation}
\nabla_{\theta} \mathbb{E}_{q_{\theta}(w)} \mathbb{E}_{p^*(x, y)} \log p(y| x, w) = \\
\nabla_{\theta} \mathbb{E}_{p(\epsilon)} \mathbb{E}_{p^*(x, y)} \log p(y| x, \mu + \epsilon \sigma) = \\
\mathbb{E}_{p(\epsilon)} \nabla_{\theta} \mathbb{E}_{p^*(x, y)} \log p(y| x, \mu + \epsilon \sigma)
\end{equation}
Note that we were able to move the gradient inside the integral since
$p(\epsilon)$ does not depend on $\theta$.
To estimate the last integral, we can use a Monte Carlo estimate using samples
of $p(\epsilon)$.
## Your tasks
* Define the Gaussian posterior distribution.
* Fill in the code for the ELBO
* Fill in the reinforce function to create the surrogate loss
* Fill in the loss function for reparametrization
* Visualize the effects of batch size, learning rates and number of posterior samples on the learned model, as well as gradient variance.
```
import enum
import numpy as np
import math
from sklearn import datasets
from sklearn import linear_model
import collections
from matplotlib import pyplot as plt
import tensorflow as tf
import tensorflow_probability as tfp
import seaborn as sns
tfd = tfp.distributions
```
```
sns.set(rc={"lines.linewidth": 2.8}, font_scale=2)
sns.set_style("whitegrid")
```
## Get the dataset and visualize it
```
def get_data(normalize = True):
data = datasets.load_breast_cancer()
print(data.target_names)
print(data.feature_names)
features = np.array(data.data, dtype=np.float32)
targets = np.array(data.target, dtype=np.float32)
if normalize:
# Note: the data dimensions have very different scales.
# We normalize by the mean and scale of the entire dataset.
features = features - features.mean(axis=0)
features = features / features.std(axis=0)
# Add a dimension of 1 (bias).
features = np.concatenate((features, np.ones((features.shape[0], 1))), axis=1)
features = np.array(features, dtype=np.float32)
return features, targets, data.feature_names
```
### Dataset
This datasets has meaningful features: we are trying to classify based on these features whether someone has breast cancer or not. We can look at the
features we are using to classify the data below.
```
features, targets, feature_names = get_data()
```
### Trivial baseline
How well can we do with a constant classifier?
If we look at the average label, we can see how many 1s are in the data, so we know that our classifier has to get more than that accuracy
```
np.mean(targets)
```
```
features.shape
```
```
dataset_size = features.shape[0]
data_dims = features.shape[-1]
```
## Logistic regression baseline - how well can we do on this dataset?
Let's look at a simple, non Bayesian classification approach to get an idea of how well we can do on the dataset.
```
lr = linear_model.LogisticRegression()
```
```
lr.fit(features, targets)
lr.score(features, targets)
```
## Utilities
```
def get_shape_list(tensor):
return tensor.shape.as_list()
```
```
def get_sklearn_data_as_tensors(
features, targets, batch_size, dataset_name='breast_cancer'):
"""Read sklearn datasets as tf.Tensors.
Args:
batch_size: Integer or None. If None, the entire dataset is used.
dataset_name: A string, the name of the dataset.
Returns:
A tuple of size two containing two tensors of rank 2 `[B, F]`, the data
features and targets.
"""
dataset = tf.data.Dataset.from_tensor_slices((features, targets))
if batch_size:
# Shuffle, repeat, and batch the examples.
batched_dataset = dataset.shuffle(1000).repeat().batch(batch_size)
else:
batch_size = features.shape[0]
batched_dataset = dataset.repeat().batch(batch_size)
iterator = batched_dataset.make_one_shot_iterator()
batch_features, batch_targets = iterator.get_next()
data_dim = features.shape[1]
batch_features.set_shape([batch_size, data_dim])
batch_targets.set_shape([batch_size])
return batch_features, batch_targets
```
## Bayesian Logistic Regression - define the prior and the posterior
We will learn a distribution over parameters, so we will first define prior distribution, and then a posterior distribution over parameters which we
will learn.
Both of these distibutions will be Gaussian.
## Task: implement the posterior distribution
You have to implement two functions
1. multi_normal, which takes as arguments the mean and the log scale of the normal distribution, and returns a tensorflow distribution object. Have a look at the TensorFlow distibutions package.
2. diagonal_gaussian_posterior which returns a tuple of two elements, one being the posterior distribution (a call to multi_normal) and the learned variables. Your task here is to define the variables we will learn. The argument `data_dims` tells you the size of the learned parameters, and thus the size of the variables of the distribution).
```
def multi_normal(loc, log_scale):
raise NotImplementedError(
'Implement the definition of multi normal')
def diagonal_gaussian_posterior(data_dims):
mean = None
log_scale = None
learned_vars = [mean, log_scale]
return multi_normal(loc=mean, log_scale=log_scale), learned_vars
```
## Bayesian Logistic Regression - the model
### Hypers
```
BATCH_SIZE = 500
NUM_POSTERIOR_SAMPLES = 100
```
```
prior = multi_normal(loc=tf.zeros(data_dims), log_scale=tf.zeros(data_dims))
posterior, learned_vars = diagonal_gaussian_posterior(data_dims)
```
```
def _predictions(logits):
return tf.to_float(logits >= 0)
def _accuracy(targets, predictions):
# `predictions` have rank 2: batch_size, num_posterior samples.
# We expand dims the targets to compute the accuracy per sample.
targets = tf.expand_dims(targets, axis=1)
return tf.reduce_mean(tf.to_float(tf.equal(targets, predictions)))
def linear_model(data, targets, posterior_samples):
num_posterior_samples = tf.shape(posterior_samples)[0]
logits = tf.matmul(data, posterior_samples, transpose_b=True)
# Make targets [B, 1] to use broadcasting.
targets = tf.expand_dims(targets, axis=1)
targets = targets * tf.ones([1, num_posterior_samples])
log_probs = - tf.nn.sigmoid_cross_entropy_with_logits(
labels=targets, logits=logits)
return log_probs, logits
```
## Task: Run the model and return the components of the elbo
```
def run_model(features, targets, prior, posterior, num_samples):
# Sample from the posterior to obtain a set of parameters used for
# prediction. Use `num_samples` for the number of samples.
posterior_samples = None
# Compute the log probs of the data under all the models we have sampled.
# These tensors are [num_samples, B]. Use the features and targets tensors.
log_probs, logits = None
# Compute the KL between the posterior and the prior.
# Note: since we use Gaussian distributions, the closed form of the
# KL can be computed. Remember that distributions are objects in TensorFlow!
kl = None
# Sum over data. Normalize by dataset size to ensure that the gradients
# are not very different in magnitude when we change batch size.
param_log_probs = tf.reduce_mean(log_probs, axis=0) * dataset_size
param_log_probs.shape.assert_is_compatible_with([num_samples])
return param_log_probs, kl, posterior_samples, logits
```
```
param_log_probs, kl, posterior_samples, logits = run_model(
features, targets, prior, posterior, NUM_POSTERIOR_SAMPLES)
predictions = _predictions(logits)
accuracy = _accuracy(targets=targets, predictions=predictions)
accuracy = tf.reduce_mean(accuracy)
```
## Task: compute the elbo from the log probs and the KL
`per_sample_elbo` should have shape [num_samples], since we obtain a model prediction for each of the sampled parameters.
```
per_sample_elbo = None
elbo = tf.reduce_mean(per_sample_elbo)
```
## Training loop
## Training the model via reparametrization
```
# Stochastic loss depends on the output of a sampling operation (posterior samples)
# but tensorflow implements reparametrization by default.
per_sample_reparametrization_loss = - per_sample_elbo
reparametrization_loss = tf.reduce_mean(per_sample_reparametrization_loss)
```
```
optimizer = tf.train.GradientDescentOptimizer(0.0001)
reparam_min_op = optimizer.minimize(reparametrization_loss)
```
```
NUM_ITERATIONS = 1000
```
```
sess = tf.Session()
# Initialize all variables
sess.run(tf.initialize_all_variables())
reparam_accuracies = []
reparam_kls = []
reparam_elbos = []
for i in xrange(NUM_ITERATIONS):
sess.run(reparam_min_op)
if i % 10 == 0:
reparam_acc, reparam_kl, reparam_elbo = sess.run([accuracy, kl, elbo])
reparam_accuracies += [reparam_acc]
reparam_kls += [reparam_kl]
reparam_elbos += [reparam_elbo]
print('Iteration {}. Elbo {}. KL {}'.format(
i, reparam_elbo, reparam_kl))
reparam_learned_mean, reparam_learned_log_scale = sess.run(learned_vars)
```
```
fig, axes = plt.subplots(1, 3, figsize=(3*8,5))
axes[0].plot(reparam_elbos, label='ELBO')
axes[0].set_title('Time', fontsize=15)
axes[0].set_ylim((-500, -50))
axes[0].legend()
axes[1].plot(reparam_kls, label='KL')
axes[1].set_title('Time', fontsize=15)
axes[1].legend()
axes[2].plot(reparam_accuracies, label='Accuracy')
axes[2].set_title('Time', fontsize=15)
axes[2].legend()
```
## Training the model via reinforce
## Task: define the surrogate reinforce loss for the log prob term.
Note: we do not need to use reinforce the KL term, since we can compute the KL analytically for the two Gaussians, and can use standard backprop.
For the reinforce implementation, instead of changing the gradients, we will change the loss such that TensorFlow's automatic differentiation does the right thing. This is called a surrogate loss.
The gradient we want to obtain is the following (since we want to minimize the loss, we add a minus):
\begin{equation}
- \mathbb{E}_{q_{\theta}(w)} \left[ \nabla_{\theta} \log q_{\theta}(w) \mathbb{E}_{p^*(x, y)} \log p(y| x, w) \right]
\end{equation}
so we need to construct a loss which has this gradient, by ensuring that the gradients will flow through the $\log q_{\theta}(w)$ term, but not the rest.
```
# Since TensorFlow does automatic differentation, we have to use
# tf.stop_gradient to ensure the gradient only flows to
# the log_{q_\theta}(w) term.
per_sample_reinforce_loss = None # Shape [num_samples, batch size].
# Reduce now over the number of samples.
reinforce_loss = tf.reduce_mean(per_sample_reinforce_loss) + kl
```
```
optimizer = tf.train.GradientDescentOptimizer(0.0001)
reinforce_min_op = optimizer.minimize(reinforce_loss)
```
```
NUM_ITERATIONS = 1000
```
```
reinforce_accuracies = []
reinforce_kls = []
reinforce_elbos = []
sess = tf.Session()
# Initialize all variables
sess.run(tf.initialize_all_variables())
for i in xrange(NUM_ITERATIONS):
sess.run(reinforce_min_op)
if i % 10 == 0:
reinforce_acc, reinforce_kl, reinforce_elbo = sess.run([accuracy, kl, elbo])
reinforce_accuracies += [reinforce_acc]
reinforce_kls += [reinforce_kl]
reinforce_elbos += [reinforce_elbo]
print('Iteration {}. Elbo {}. KL {}'.format(
i, reinforce_elbo, reinforce_kl))
reinforce_learned_mean, reinforce_learned_log_scale = sess.run(learned_vars)
```
```
fig, axes = plt.subplots(1, 3, figsize=(3*8,5))
axes[0].plot(reinforce_elbos, label='ELBO')
axes[0].set_title('Time', fontsize=15)
axes[0].set_ylim((-500, -50))
axes[0].legend()
axes[1].plot(reinforce_kls, label='KL')
axes[1].set_title('Time', fontsize=15)
axes[1].legend()
axes[2].plot(reinforce_accuracies, label='Accuracy')
axes[2].set_title('Time', fontsize=15)
axes[2].legend()
```
## Task: Analysis
* How sensitive are the different estimators to the number of posterior samples used? Try 1, 10, 100.
* How sensitive are the different estimators to the learning rate used? Try 1e-4, 1e-3 and 1e-2 for both estimators.
* How sensitive are the different estimators to batch size? Try batch size 10 for both estimators.
# Visualize learned parameters
* Let's visualize the learned parameters, as well as check the different uncertanties around different parameters
* Can we now see which parameters are most important in the classification problem?
```
learned_mean = reparam_learned_mean
learned_scale = np.exp(reparam_learned_log_scale)
```
```
PARAM_INDEX = 10
```
```
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
```
```
mean = learned_mean[PARAM_INDEX]
scale = learned_scale[PARAM_INDEX]
x_values = np.linspace(-3, 3, num=1000)
y_values = [gaussian(x, mean, scale) for x in x_values]
plt.figure(figsize=(7,5))
plt.plot(x_values, y_values)
plt.vlines(
learned_mean[PARAM_INDEX],
ymin=0,
ymax=gaussian(mean, mean, scale),
colors='g',
alpha=0.8)
plt.grid('off')
x_std_values = np.linspace(mean - scale, mean + scale, num=1000)
y_std_values = [gaussian(x, mean, scale) for x in x_std_values]
plt.fill_between(x_std_values, y_std_values, 0, alpha=0.3, color='b')
plt.title('Parameter name= {}'.format(feature_names[PARAM_INDEX]))
```
## Visualize gradient variance - which estimator has lower variance?
* Let's assess the gradient variance per of each estimator, by looking at how much gradients vary for each estimators.
```
def per_batch_grads(ys, xs):
"""Computes the gradients of ys[i] wrt xs."""
grads = []
for y in tf.unstack(ys, axis=0):
grads.append(tf.squeeze(tf.gradients(y, xs)[0]))
return tf.stack(grads, axis=0)
```
```
def compute_grad_var(grads, param_index):
return np.mean(grads[:, param_index]), np.std(grads[:, param_index])**2
```
```
per_batch_reinforce_grads = per_batch_grads(per_sample_reinforce_loss, learned_vars[0])
per_batch_reinforce_grads.shape
```
```
per_batch_reparam_grads = per_batch_grads(per_sample_reparametrization_loss, learned_vars[0])
per_batch_reparam_grads.shape
```
```
reinforce_grads = []
sess = tf.Session()
# Initialize all variables
sess.run(tf.initialize_all_variables())
for i in xrange(NUM_ITERATIONS):
sess.run(reinforce_min_op)
if i % 10 == 0:
reinforce_grads.append(sess.run(per_batch_reinforce_grads))
```
```
reparam_grads = []
sess = tf.Session()
# Initialize all variables
sess.run(tf.initialize_all_variables())
for i in xrange(NUM_ITERATIONS):
sess.run(reparam_min_op)
if i % 10 == 0:
reparam_grads.append(sess.run(per_batch_reparam_grads))
```
```
PARAM_INDEX = 19
```
```
reinforce_grad_vars = []
for timestep_grad in reinforce_grads:
_, reinforce_grad_var = compute_grad_var(timestep_grad, PARAM_INDEX)
reinforce_grad_vars.append(reinforce_grad_var)
```
```
reparam_grad_vars = []
for timestep_grad in reparam_grads:
_, reparam_grad_var = compute_grad_var(timestep_grad, PARAM_INDEX)
reparam_grad_vars.append(reparam_grad_var)
```
```
plt.figure(figsize=(7,5))
plt.plot(reinforce_grad_vars, label='reinforce')
plt.plot(reparam_grad_vars, label='reparametrization')
plt.yscale('log')
plt.xlabel('It')
plt.ylabel('Gradient variance')
plt.legend()
```
### Task: Analysis
* What do you notice about gradient variance as training progresses?
* What do you notice about the variance of the different estimators?
* How do batch size and number of posterior samples affect the variance of the different estimators?
* How does gradient variance affect convergence?
* Which gradient estimator would you use in practice for this problem?
## More
You can find similar experiments with more analysis and more gradient estimators in [this paper](https://arxiv.org/pdf/1906.10652.pdf). See Section 8.3.
|
function U = phi2u(phi)
m = length(phi);
k = ceil(sqrt(2*m));
U = eye(k);
c = cos(phi);
s = sin(phi);
count = 1;
for i=1:k
for j=i+1:k
R = eye(k);
R(i,i) = c(count);
R(i,j) = -s(count);
R(j,i) = s(count);
R(j,j) = c(count);
U = U*R;
count = count + 1;
end
end
|
//-*-C++-*-
/***************************************************************************
*
* Copyright (C) 2008 by Willem van Straten
* Licensed under the Academic Free License version 2.1
*
***************************************************************************/
#ifndef __Pulsar_Interpolation_h
#define __Pulsar_Interpolation_h
#include "Reference.h"
#include <gsl/gsl_interp.h>
#include <gsl/gsl_spline.h>
#include <vector>
//! Interface to GSL interpolation routines
class Interpolation : public Reference::Able
{
public:
//! Default constructor
Interpolation ();
//! Destructor
virtual ~Interpolation ();
//! Initialize interpolation object
void init (const std::vector<double>& x, const std::vector<double>& y);
//! Evaluate at the given abscissa
double eval (double x);
protected:
const double* xa;
const double* ya;
size_t size;
gsl_interp* interp;
gsl_interp_accel* acc;
void destroy ();
};
#endif
|
/-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import linear_algebra.matrix.determinant
import data.mv_polynomial.basic
import data.mv_polynomial.comm_ring
/-!
# Matrices of multivariate polynomials
In this file, we prove results about matrices over an mv_polynomial ring.
In particular, we provide `matrix.mv_polynomial_X` which associates every entry of a matrix with a
unique variable.
## Tags
matrix determinant, multivariate polynomial
-/
variables {m n R S : Type*}
namespace matrix
variables (m n R)
/-- The matrix with variable `X (i,j)` at location `(i,j)`. -/
noncomputable def mv_polynomial_X [comm_semiring R] : matrix m n (mv_polynomial (m × n) R) :=
of $ λ i j, mv_polynomial.X (i, j)
-- TODO: set as an equation lemma for `mv_polynomial_X`, see mathlib4#3024
@[simp]
lemma mv_polynomial_X_apply [comm_semiring R] (i j) :
mv_polynomial_X m n R i j = mv_polynomial.X (i, j) := rfl
variables {m n R S}
/-- Any matrix `A` can be expressed as the evaluation of `matrix.mv_polynomial_X`.
This is of particular use when `mv_polynomial (m × n) R` is an integral domain but `S` is
not, as if the `mv_polynomial.eval₂` can be pulled to the outside of a goal, it can be solved in
under cancellative assumptions. -/
lemma mv_polynomial_X_map_eval₂ [comm_semiring R] [comm_semiring S]
(f : R →+* S) (A : matrix m n S) :
(mv_polynomial_X m n R).map (mv_polynomial.eval₂ f $ λ p : m × n, A p.1 p.2) = A :=
ext $ λ i j, mv_polynomial.eval₂_X _ (λ p : m × n, A p.1 p.2) (i, j)
/-- A variant of `matrix.mv_polynomial_X_map_eval₂` with a bundled `ring_hom` on the LHS. -/
lemma mv_polynomial_X_map_matrix_eval [fintype m] [decidable_eq m]
[comm_semiring R] (A : matrix m m R) :
(mv_polynomial.eval $ λ p : m × m, A p.1 p.2).map_matrix (mv_polynomial_X m m R) = A :=
mv_polynomial_X_map_eval₂ _ A
variables (R)
/-- A variant of `matrix.mv_polynomial_X_map_eval₂` with a bundled `alg_hom` on the LHS. -/
lemma mv_polynomial_X_map_matrix_aeval [fintype m] [decidable_eq m]
[comm_semiring R] [comm_semiring S] [algebra R S] (A : matrix m m S) :
(mv_polynomial.aeval $ λ p : m × m, A p.1 p.2).map_matrix (mv_polynomial_X m m R) = A :=
mv_polynomial_X_map_eval₂ _ A
variables (m R)
/-- In a nontrivial ring, `matrix.mv_polynomial_X m m R` has non-zero determinant. -/
lemma det_mv_polynomial_X_ne_zero [decidable_eq m] [fintype m] [comm_ring R] [nontrivial R] :
det (mv_polynomial_X m m R) ≠ 0 :=
begin
intro h_det,
have := congr_arg matrix.det (mv_polynomial_X_map_matrix_eval (1 : matrix m m R)),
rw [det_one, ←ring_hom.map_det, h_det, ring_hom.map_zero] at this,
exact zero_ne_one this,
end
end matrix
|
## Element type
struct IIDMVoltMeasure <: AbstractNodeLabel
V::Complex # p.u.
S::Complex # MW + im*MVar
end
|
# Packages ----------------------------------------------------------------
library(here)
library(dplyr)
library(brms)
library(parallel)
# Options -----------------------------------------------------------------
options(mc.cores = detectCores())
# Get data ----------------------------------------------------------------
utla_rt_with_covariates <-
readRDS(here("data", "utla_rt_with_covariates.rds")) %>%
filter(week_infection > "2020-10-01") %>%
mutate(tier = if_else(tier == tier[1], paste0("_", tier), tier)) %>%
mutate(prop = 1 - prop) %>%
mutate(tier = if_else(tier == "none", "_none", tier)) %>%
mutate(positive_samples = as.integer(prop * samples),
id = 1:n(), positive_prop = NA_real_)
# model with uncertainty ------------------------------------------------
source(here("R", "variant_rt.r"))
# no uncertainty on sgtf
fit_cert <- variant_rt(
log_rt = ~ 1,
data = utla_rt_with_covariates %>%
rename(rt_mean = rt_mean_long_gt, rt_sd = rt_sd_long_gt)%>%
mutate(positive_prop = prop) %>%
mutate(
positive_prop = ifelse(positive_prop <= 0, 1e-5, ifelse(prop >= 1, 0.9999, prop))
),
brm_fn = brm
)
summary(fit_cert)
# uncertainty on sgtf
fit_ <- variant_rt(
log_rt = ~ 1,
data = utla_rt_with_covariates %>%
rename(rt_mean = rt_mean_long_gt, rt_sd = rt_sd_long_gt),
brm_fn = brm
)
summary(fit)
|
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import tactic.basic
/-!
# Extra facts about `prod`
This file defines `prod.swap : α × β → β × α` and proves various simple lemmas about `prod`.
-/
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
@[simp]
namespace prod
@[simp] theorem «forall» {p : α × β → Prop} : (∀ x, p x) ↔ (∀ a b, p (a, b)) :=
⟨assume h a b, h (a, b), assume h ⟨a, b⟩, h a b⟩
@[simp] theorem «exists» {p : α × β → Prop} : (∃ x, p x) ↔ (∃ a b, p (a, b)) :=
⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩
theorem forall' {p : α → β → Prop} : (∀ x : α × β, p x.1 x.2) ↔ ∀ a b, p a b :=
prod.forall
theorem exists' {p : α → β → Prop} : (∃ x : α × β, p x.1 x.2) ↔ ∃ a b, p a b :=
prod.exists
@[simp] lemma snd_comp_mk (x : α) : prod.snd ∘ (prod.mk x : β → α × β) = id := rfl
@[simp] lemma fst_comp_mk (x : α) : prod.fst ∘ (prod.mk x : β → α × β) = function.const β x := rfl
@[simp] lemma map_mk (f : α → γ) (g : β → δ) (a : α) (b : β) : map f g (a, b) = (f a, g b) := rfl
lemma map_fst (f : α → γ) (g : β → δ) (p : α × β) : (map f g p).1 = f (p.1) := rfl
lemma map_snd (f : α → γ) (g : β → δ) (p : α × β) : (map f g p).2 = g (p.2) := rfl
lemma map_fst' (f : α → γ) (g : β → δ) : (prod.fst ∘ map f g) = f ∘ prod.fst :=
funext $ map_fst f g
lemma map_snd' (f : α → γ) (g : β → δ) : (prod.snd ∘ map f g) = g ∘ prod.snd :=
funext $ map_snd f g
/--
Composing a `prod.map` with another `prod.map` is equal to
a single `prod.map` of composed functions.
-/
lemma map_comp_map {ε ζ : Type*}
(f : α → β) (f' : γ → δ) (g : β → ε) (g' : δ → ζ) :
prod.map g g' ∘ prod.map f f' = prod.map (g ∘ f) (g' ∘ f') :=
rfl
/--
Composing a `prod.map` with another `prod.map` is equal to
a single `prod.map` of composed functions, fully applied.
-/
lemma map_map {ε ζ : Type*}
(f : α → β) (f' : γ → δ) (g : β → ε) (g' : δ → ζ) (x : α × γ) :
prod.map g g' (prod.map f f' x) = prod.map (g ∘ f) (g' ∘ f') x :=
rfl
@[simp] theorem mk.inj_iff {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) = (a₂, b₂) ↔ (a₁ = a₂ ∧ b₁ = b₂) :=
⟨prod.mk.inj, by cc⟩
lemma mk.inj_left {α β : Type*} (a : α) :
function.injective (prod.mk a : β → α × β) :=
by { intros b₁ b₂ h, simpa only [true_and, prod.mk.inj_iff, eq_self_iff_true] using h }
lemma mk.inj_right {α β : Type*} (b : β) :
function.injective (λ a, prod.mk a b : α → α × β) :=
by { intros b₁ b₂ h, by simpa only [and_true, eq_self_iff_true, mk.inj_iff] using h }
lemma ext_iff {p q : α × β} : p = q ↔ p.1 = q.1 ∧ p.2 = q.2 :=
by rw [← @mk.eta _ _ p, ← @mk.eta _ _ q, mk.inj_iff]
@[ext]
lemma ext {α β} {p q : α × β} (h₁ : p.1 = q.1) (h₂ : p.2 = q.2) : p = q :=
ext_iff.2 ⟨h₁, h₂⟩
lemma map_def {f : α → γ} {g : β → δ} : prod.map f g = λ (p : α × β), (f p.1, g p.2) :=
funext (λ p, ext (map_fst f g p) (map_snd f g p))
lemma id_prod : (λ (p : α × β), (p.1, p.2)) = id :=
funext $ λ ⟨a, b⟩, rfl
lemma map_id : (prod.map (@id α) (@id β)) = id :=
id_prod
lemma fst_surjective [h : nonempty β] : function.surjective (@fst α β) :=
λ x, h.elim $ λ y, ⟨⟨x, y⟩, rfl⟩
lemma snd_surjective [h : nonempty α] : function.surjective (@snd α β) :=
λ y, h.elim $ λ x, ⟨⟨x, y⟩, rfl⟩
lemma fst_injective [subsingleton β] : function.injective (@fst α β) :=
λ x y h, ext h (subsingleton.elim _ _)
lemma snd_injective [subsingleton α] : function.injective (@snd α β) :=
λ x y h, ext (subsingleton.elim _ _) h
/-- Swap the factors of a product. `swap (a, b) = (b, a)` -/
def swap : α × β → β × α := λp, (p.2, p.1)
@[simp] lemma swap_swap : ∀ x : α × β, swap (swap x) = x
| ⟨a, b⟩ := rfl
@[simp] lemma fst_swap {p : α × β} : (swap p).1 = p.2 := rfl
@[simp] lemma snd_swap {p : α × β} : (swap p).2 = p.1 := rfl
@[simp] lemma swap_prod_mk {a : α} {b : β} : swap (a, b) = (b, a) := rfl
@[simp] lemma swap_swap_eq : swap ∘ swap = @id (α × β) :=
funext swap_swap
@[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap :=
swap_swap
@[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap :=
swap_swap
lemma swap_injective : function.injective (@swap α β) :=
swap_left_inverse.injective
lemma swap_surjective : function.surjective (@swap α β) :=
swap_left_inverse.surjective
lemma swap_bijective : function.bijective (@swap α β) :=
⟨swap_injective, swap_surjective⟩
@[simp] lemma swap_inj {p q : α × β} : swap p = swap q ↔ p = q := swap_injective.eq_iff
lemma eq_iff_fst_eq_snd_eq : ∀{p q : α × β}, p = q ↔ (p.1 = q.1 ∧ p.2 = q.2)
| ⟨p₁, p₂⟩ ⟨q₁, q₂⟩ := by simp
lemma fst_eq_iff : ∀ {p : α × β} {x : α}, p.1 = x ↔ p = (x, p.2)
| ⟨a, b⟩ x := by simp
lemma snd_eq_iff : ∀ {p : α × β} {x : β}, p.2 = x ↔ p = (p.1, x)
| ⟨a, b⟩ x := by simp
theorem lex_def (r : α → α → Prop) (s : β → β → Prop)
{p q : α × β} : prod.lex r s p q ↔ r p.1 q.1 ∨ p.1 = q.1 ∧ s p.2 q.2 :=
⟨λ h, by cases h; simp *,
λ h, match p, q, h with
| (a, b), (c, d), or.inl h := lex.left _ _ h
| (a, b), (c, d), or.inr ⟨e, h⟩ :=
by change a = c at e; subst e; exact lex.right _ h
end⟩
instance lex.decidable [decidable_eq α]
(r : α → α → Prop) (s : β → β → Prop) [decidable_rel r] [decidable_rel s] :
decidable_rel (prod.lex r s) :=
λ p q, decidable_of_decidable_of_iff (by apply_instance) (lex_def r s).symm
@[refl] lemma lex.refl_left (r : α → α → Prop) (s : β → β → Prop) [is_refl α r] :
∀ x, prod.lex r s x x
| (x₁, x₂) := lex.left _ _ (refl _)
instance is_refl_left {r : α → α → Prop} {s : β → β → Prop} [is_refl α r] :
is_refl (α × β) (lex r s) :=
⟨lex.refl_left _ _⟩
@[refl] lemma lex.refl_right (r : α → α → Prop) (s : β → β → Prop) [is_refl β s] :
∀ x, prod.lex r s x x
| (x₁, x₂) := lex.right _ (refl _)
instance is_refl_right {r : α → α → Prop} {s : β → β → Prop} [is_refl β s] :
is_refl (α × β) (lex r s) :=
⟨lex.refl_right _ _⟩
@[trans] lemma lex.trans {r : α → α → Prop} {s : β → β → Prop} [is_trans α r] [is_trans β s] :
∀ {x y z : α × β}, prod.lex r s x y → prod.lex r s y z → prod.lex r s x z
| (x₁, x₂) (y₁, y₂) (z₁, z₂) (lex.left _ _ hxy₁) (lex.left _ _ hyz₁) :=
lex.left _ _ (trans hxy₁ hyz₁)
| (x₁, x₂) (y₁, y₂) (z₁, z₂) (lex.left _ _ hxy₁) (lex.right _ hyz₂) := lex.left _ _ hxy₁
| (x₁, x₂) (y₁, y₂) (z₁, z₂) (lex.right _ _) (lex.left _ _ hyz₁) := lex.left _ _ hyz₁
| (x₁, x₂) (y₁, y₂) (z₁, z₂) (lex.right _ hxy₂) (lex.right _ hyz₂) := lex.right _ (trans hxy₂ hyz₂)
instance {r : α → α → Prop} {s : β → β → Prop} [is_trans α r] [is_trans β s] :
is_trans (α × β) (lex r s) :=
⟨λ _ _ _, lex.trans⟩
instance {r : α → α → Prop} {s : β → β → Prop} [is_strict_order α r] [is_antisymm β s] :
is_antisymm (α × β) (lex r s) :=
⟨λ x₁ x₂ h₁₂ h₂₁, match x₁, x₂, h₁₂, h₂₁ with
| (a₁, b₁), (a₂, b₂), lex.left _ _ hr₁, lex.left _ _ hr₂ := (irrefl a₁ (trans hr₁ hr₂)).elim
| (a₁, b₁), (a₂, b₂), lex.left _ _ hr₁, lex.right _ _ := (irrefl _ hr₁).elim
| (a₁, b₁), (a₂, b₂), lex.right _ _, lex.left _ _ hr₂ := (irrefl _ hr₂).elim
| (a₁, b₁), (a₂, b₂), lex.right _ hs₁, lex.right _ hs₂ := antisymm hs₁ hs₂ ▸ rfl
end⟩
instance is_total_left {r : α → α → Prop} {s : β → β → Prop} [is_total α r] :
is_total (α × β) (lex r s) :=
⟨λ ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, (is_total.total a₁ a₂).imp (lex.left _ _) (lex.left _ _)⟩
instance is_total_right {r : α → α → Prop} {s : β → β → Prop} [is_trichotomous α r] [is_total β s] :
is_total (α × β) (lex r s) :=
⟨λ ⟨i, a⟩ ⟨j, b⟩, begin
obtain hij | rfl | hji := trichotomous_of r i j,
{ exact or.inl (lex.left _ _ hij) },
{ exact (total_of (s) a b).imp (lex.right _) (lex.right _), },
{ exact or.inr (lex.left _ _ hji) }
end⟩
end prod
open prod
namespace function
variables {f : α → γ} {g : β → δ} {f₁ : α → β} {g₁ : γ → δ} {f₂ : β → α} {g₂ : δ → γ}
lemma injective.prod_map (hf : injective f) (hg : injective g) : injective (map f g) :=
λ x y h, ext (hf (ext_iff.1 h).1) (hg $ (ext_iff.1 h).2)
lemma surjective.prod_map (hf : surjective f) (hg : surjective g) : surjective (map f g) :=
λ p, let ⟨x, hx⟩ := hf p.1 in let ⟨y, hy⟩ := hg p.2 in ⟨(x, y), prod.ext hx hy⟩
lemma bijective.prod_map (hf : bijective f) (hg : bijective g) : bijective (map f g) :=
⟨hf.1.prod_map hg.1, hf.2.prod_map hg.2⟩
lemma left_inverse.prod_map (hf : left_inverse f₁ f₂) (hg : left_inverse g₁ g₂) :
left_inverse (map f₁ g₁) (map f₂ g₂) :=
λ a, by rw [prod.map_map, hf.comp_eq_id, hg.comp_eq_id, map_id, id]
lemma right_inverse.prod_map :
right_inverse f₁ f₂ → right_inverse g₁ g₂ → right_inverse (map f₁ g₁) (map f₂ g₂) :=
left_inverse.prod_map
lemma involutive.prod_map {f : α → α} {g : β → β} :
involutive f → involutive g → involutive (map f g) :=
left_inverse.prod_map
end function
|
% $Header$
\documentclass{beamer}
% This file is a solution template for:
% - Giving a talk on some subject.
% - The talk is between 15min and 45min long.
% - Style is ornate.
% Copyright 2004 by Till Tantau <[email protected]>.
%
% In principle, this file can be redistributed and/or modified under
% the terms of the GNU Public License, version 2.
%
% However, this file is supposed to be a template to be modified
% for your own needs. For this reason, if you use this file as a
% template and not specifically distribute it as part of a another
% package/program, I grant the extra permission to freely copy and
% modify this file as you see fit and even to delete this copyright
% notice.
\mode<presentation>
{
\usetheme{Pittsburgh}
\usecolortheme{dove}
\usefonttheme{professionalfonts}
\setbeamertemplate{blocks}[rounded][shadow=false]
\setbeamercolor{block title}{fg=structure,bg=white}
}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{CJKutf8}
\usepackage{amsfonts}
\usepackage{color}
\usepackage{pstricks,pst-text}
\usepackage{pst-node,pst-tree}
\usepackage{concrete}
\usepackage[T1]{fontenc}
\usepackage{amsmath}%
\usepackage{amsthm}
\usepackage{amssymb}%
\usepackage{graphicx}
\usepackage{float}
\usepackage{caption}
\usepackage{bbold}
% Or whatever. Note that the encoding and the font should match. If T1
% does not look nice, try deleting the line with the fontenc.
\title{Algebraic generating functions for languages avoiding Riordan
patterns\footnote{\scriptsize submitted to the \emph{Journal of Integer Sequences} in
January and recently reviewed} and\\ matrices functions for the Riordan group}
%\subtitle {Presentation Subtitle} % (optional)
\author[Merlini, Nocentini] % (optional, use only with lots of authors)
{Massimo Nocentini}
% - Use the \inst{?} command only if the authors have different
% affiliation.
\institute[Universities of Somewhere and Elsewhere] % (optional, but mostly needed)
{
Dipartimento di Statistica, Informatica, Applicazioni \\
University of Florence, Italy
}
% - Use the \inst command only if there are several affiliations.
% - Keep it simple, no one is interested in your street address.
\date{\today}
\subject{
We study the languages $\mathfrak{L}^{[\mathfrak{p}]}\subset \{0,1\}^*$ of
binary words $w$ avoiding a given pattern $\mathfrak{p}$ such that $|w|_0\leq
|w|_1$ for any $w\in \mathfrak{L}^{[\mathfrak{p}]},$ where $|w|_0$ and $|w|_1$
correspond to the number of bits $1$ and $0$ in the word $w$, respectively. In
particular, we concentrate on patterns $\mathfrak{p}$ related to the concept
of Riordan arrays. These languages are not regular and can be enumerated by
algebraic generating functions corresponding to many integer sequences which
are unknown in the OEIS. We give explicit formulas for these generating
functions expressed in terms of the autocorrelation polynomial of
$\mathfrak{p}$ and also give explicit formulas for the coefficients of some
particular patterns, algebraically and combinatorially.}
% This is only inserted into the PDF information catalog. Can be left
% out.
% If you have a file called "university-logo-filename.xxx", where xxx
% is a graphic format that can be processed by latex or pdflatex,
% resp., then you can add a logo as follows:
% \pgfdeclareimage[height=0.5cm]{university-logo}{university-logo-filename}
% \logo{\pgfuseimage{university-logo}}
% Delete this, if you do not want the table of contents to pop up at
% the beginning of each subsection:
\AtBeginSection[]
{
\begin{frame}<beamer>{Outline}
\tableofcontents[currentsection]
\end{frame}
}
% If you wish to uncover everything in a step-wise fashion, uncomment
% the following command:
%\beamerdefaultoverlayspecification{<+->}
\begin{document}
\begin{frame}
\titlepage
\end{frame}
\begin{frame}{Outline}
\tableofcontents
% You might wish to add the option [pausesections]
\end{frame}
% Since this a solution template for a generic talk, very little can
% be said about how it should be structured. However, the talk length
% of between 15min and 45min and the theme suggest that you stick to
% the following rules:
% - Exactly two or three sections (other than the summary).
% - At *most* three subsections per section.
% - Talk about 30s to 2min per frame. So there should be between about
% 15 and 30 frames, all told.
\section{Introduction}
\begin{frame}
\frametitle{Definition in terms of $d(t)$ and $h(t)$}
\begin{itemize}
\item A \emph{Riordan array} $\mathcal{R}$ is a pair
$$\mathcal{R}=(d(t),\ h(t))$$
where $d(t)$ and $h(t)$ are formal power series in the undeterminate $t$, such
that $d(0)\neq 0$ and $h(0)= 0$
\item if $h^\prime(0)\neq 0$ the Riordan array is called \emph{proper}
\item $\mathcal{R}$ denotes an infinite, lower triangular array $(d_{n,k})_{n,k\in N}$ where:
$$d_{n,k}=[t^n]d(t)h(t)^k$$
\end{itemize}
\end{frame}
\section{Binary words avoiding patterns}
\begin{frame} \frametitle{Binary words avoiding a pattern}
\begin{itemize}
\item We consider the language $\mathcal{L}^{[\mathfrak{p}]}$ of binary words
with no occurrence of a pattern $\mathfrak{p}=p_0\cdots p_{h-1}$
\item The problem of determining the generating function counting
the number of words \emph{with respect to their length} has been studied
by several authors:
\begin{enumerate}
\item L.~J. Guibas and M.~Odlyzko.
Long repetitive patterns in random sequences.
{\em Zeitschrift f\"{u}r Wahrscheinlichkeitstheorie}, 53:241--262,
1980.
\item R.~Sedgewick and P.~Flajolet.
{\em An {I}ntroduction to the {A}nalysis of {A}lgorithms}.
Addison-Wesley, Reading, MA, 1996.
\end{enumerate}
\item The fundamental notion is that of the \emph{autocorrelation vector} of
bits $c=(c_0,\ldots ,c_{h-1})$ associated to a given $\mathfrak{p}$
\end{itemize}
\end{frame}
\begin{frame} \frametitle{The pattern $\mathfrak{p}=10101$}
\begin{center}
\begin{tabular}{ccccc|cccccccc}
$1$ & $0$ & $1$ & $0$ & $1$ & \multicolumn{6}{l}{Tails} & $c_{i}$ \\
\hline
$1$ & $0$ & $1$ & $0$ & $1$ & & & & & & & $1$ \\
& $1$ & $0$ & $1$ & $0$ & $1$ & & & & & & $0$ \\
& & $1$ & $0$ & $1$ & $0$ & $1$ & & & & & $1$ \\
& & & $1$ & $0$ & $1$ & $0$ & $1$ & & & & $0$ \\
& & & & $1$ & $0$ & $1$ & $0$ & $1$ & & & $1$\\
\end{tabular}
\end{center}
The autocorrelation vector is then $c=(1,0,1,0,1)$ and
$C^{[\mathfrak{p}]}(t)=1+t^{2}+t^{4}$ is the associated
autocorrelation polynomial
\end{frame}
\begin{frame} \frametitle{Count respect bits $1$ and $0$}
The gf counting the number $F_{n}$ of binary words with
length $n$ not containing the pattern $\mathfrak{p}$ is
\begin{displaymath}
F(t) = \frac{C^{[\mathfrak{p}]}(t)}{t^{h} + (1-2t)C^{[\mathfrak{p}]}(t)}
\end{displaymath}
Taking into account the number of bits $1$ and $0$ in $\mathfrak{p}$:
\begin{displaymath}
F^{[\mathfrak{p}]}(x, y) = \frac{C^{[\mathfrak{p}]}(x,y)}{x^{n_{1}^{[\mathfrak{p}]}} y^{n_{0}^{[\mathfrak{p}]}}
+ (1-x-y)C^{[\mathfrak{p}]}(x, y)}
\end{displaymath}
where $h = {n_{0}^{[\mathfrak{p}]}}+{n_{1}^{[\mathfrak{p}]}}$ and $C^{[\mathfrak{p}]}(x, y)$
is the bivariate autocorrelation polynomial. Moreover,
$F_{n, k}^{[\mathfrak{p}]} =[x^n y^k]F^{[\mathfrak{p}]}(x,y)$ denotes the number of binary
words avoiding the pattern $\mathfrak{p}$ with $n$ bits $1$ and $k$ bits $0$
\end{frame}
\begin{frame}\frametitle{An example with $\mathfrak{p}= 10101$}
Since $C^{[\mathfrak{p}]}(x,y)=1+xy+x^2y^2$ we have:
$$F^{[\mathfrak{p}]}(x,y)={1+xy+x^2y^2 \over (1-x-y)(1+xy+x^2y^2)+x^3y^2}. $$
$$
\begin{array}{c|cccccccc}
n/k & 0 & 1 & 2 & 3 & 4 &5 &6 &7 \\ \cline{1-9} 0 & {\bf\color{red} 1} & {\bf\color{green} 1} & {\bf\color{green}1} & {\bf\color{green}1}&
{\bf\color{green}1}
& {\bf\color{green}1} & {\bf\color{green}1} & {\bf\color{green}1}\\
1 & {\bf\color{blue} 1} & {\bf\color{red}2} & 3 & 4 & 5 & 6 & 7 & 8 \\
2 & {\bf\color{blue} 1} & 3 & {\bf\color{red}6} & 10 & 15 & 21 & 28 & 36\\
3 & {\bf\color{blue} 1} & 4 & 9 & {\bf\color{red}18} & 32 & 52& 79 & 114\\
4 & {\bf\color{blue} 1} & 5 & 13 & 30 & {\bf\color{red}60} & 109& 184 & 293\\
5 & {\bf\color{blue} 1} & 6 & 18 & 46 & 102 & {\bf\color{red}204} & 377 & 654\\
6 & {\bf\color{blue} 1} & 7 & 24 & 67 & 163 & 354& {\bf\color{red}708} & 1324\\
7 & {\bf\color{blue} 1} & 8 & 31 & 94 & 248 &580& 1245 &{\bf\color{red}2490}
\end{array}
$$
\end{frame}
\begin{frame}\frametitle{...the lower and upper triangular parts}
\begin{columns}
\begin{column}{5cm}
$$
\begin{array}{c|cccccc}
n/k & 0 & 1 & 2 & 3 & 4 &5 \\ \cline{1-7}
0 & {\bf\color{red}1} & & & & & \\
1 & {\bf\color{red}2} & {\bf\color{blue} 1} & & & & \\
2 & {\bf\color{red}6}& 3 & {\bf\color{blue} 1} & & & \\
3 & {\bf\color{red}18} & 9 & 4 & {\bf\color{blue} 1} & & \\
4 & {\bf\color{red}60} & 30 & 13 & 5 & {\bf\color{blue} 1}& \\
5 & {\bf\color{red}204} & 102 & 46 & 18 & 6 &{\bf\color{blue} 1} \\
\end{array}
$$
$(n,k)\mapsto(n,n-k)$ if $k\leq n$
\end{column}
\begin{column}{5cm}
$$
\begin{array}{c|cccccc}
n/k & 0 & 1 & 2 & 3 & 4 &5 \\ \cline{1-7}
0 & {\bf\color{red}1} & & & & & \\
1 & {\bf\color{red}2} & {\bf\color{green}1} & & & & \\
2 & {\bf\color{red}6}& 3 & {\bf\color{green}1} & & & \\
3 & {\bf\color{red}18} & 10 & 4 & {\bf\color{green}1} & & \\
4 & {\bf\color{red}60} & 32 & 15 & 5 & {\bf\color{green}1}& \\
5 & {\bf\color{red}204} & 109 & 52 & 21 & 6 &{\bf\color{green}1} \\
\end{array}
$$
$(n,k)\mapsto(k,k-n)$ if $n\leq k$
\end{column}
\end{columns}
\end{frame}
\begin{frame}\frametitle{Matrices ${{R}^{[\mathfrak{p}]}}$ and ${{R}^{[\bar{\mathfrak{p}]}}}$}
\begin{itemize}
\item Let $R_{n,k}^{[\mathfrak{p}]}=F_{n,n-k}^{[\mathfrak{p}]}$ with $k\leq n.$
In other words, $R_{n,k}^{[\mathfrak{p}]}$ counts the number of words avoiding
$\mathfrak{p}$ with $n$ bits $1$ and $n-k$ bits $0$ \item Let
$\bar{\mathfrak{p}}=\bar{p}_{0}\ldots\bar{p}_{h-1}$ be the $\mathfrak{p}$'s conjugate,
where $\bar{p}_{i} = 1-p_{i}$
\item We obviously have
$R_{n,k}^{[\bar{\mathfrak{p}}]}=F_{n,n-k}^{[\bar{\mathfrak{p}}]}=F_{k,k-n}^{[\mathfrak{p}]}$.
Therefore, the matrices ${{R}^{[\mathfrak{p}]}}$ and
${{R}^{[\bar{\mathfrak{p}]}}}$ represent the lower and upper triangular part of
the array ${{F}^{[\mathfrak{p}]}},$ respectively
\end{itemize}
\end{frame}
\section{Riordan patterns}
\begin{frame}\frametitle{Riordan patterns {\tiny [MS11]}}
\begin{itemize}
\item
When matrices
${{R}^{[\mathfrak{p}]}}$ and ${{R}^{[\bar{\mathfrak{p}]}}}$ are (both) Riordan arrays?
\item
We say that $\mathfrak{p}=p_0...p_{h-1}$ is a Riordan pattern if
and only if
$$C^{[\mathfrak{p}]}(x,y)=C^{[\mathfrak{p}]}(y,x)=
\sum_{i=0}^{\lfloor(h-1)/2\rfloor}c_{2i}x^iy^i$$
provided that $\left|n_1^{[\mathfrak{p}]}-n_0^{[\mathfrak{p}]}\right|\in \left\{0,1\right\}$
\end{itemize}
\begin{enumerate}
\item {\small D. Merlini and R. Sprugnoli. Algebraic aspects of some Riordan arrays related to binary words avoiding a pattern.
{\em Theoretical Computer Science}, 412 (27), 2988-3001, 2011.}
\end{enumerate}
\end{frame}
%\begin{frame}\frametitle{Theorem 1}
%The matrices ${\cal{R}^{[\mathfrak{p}]}}$ and
%${\cal{R}^{[\bar{\mathfrak{p}]}}}$ are both Riordan arrays
%${\cal{R}^{[\mathfrak{p}]}}=(d^{[\mathfrak{p}]}(t),h^{[\mathfrak{p}]}(t))$
% and ${\cal{R}^{[\bar{\mathfrak{p}]}}}=(d^{[\bar{\mathfrak{p}}]}(t),h^{[\bar{\mathfrak{p}}]}(t))$
%if and only if $\mathfrak{p}$ is a Riordan pattern. Moreover we have:
%\begin{alertblock}{ }
%$$d^{[\mathfrak{p}]}(t)=d^{[\bar{\mathfrak{p}}]}(t)=
%[x^0]F\left(x,\dfrac{t}{x}\right)=\dfrac{1}{2\pi i}\displaystyle\oint{F\left(x,\dfrac{t}{x}\right)\dfrac{dx}{x}}
%$$
%and {\tiny $$h^{[\mathfrak{p}]}(t)={1- \sum_{i =
%0}^{n_1^{\mathfrak{p}}-1} \alpha_{i,1}t^{i+1}-
%\sqrt{(1-\sum_{i=0}^{n_1^{\mathfrak{p}}-1} \alpha_{i,1}t^{i+1})^2
%- 4\sum_{i = 0}^{n_1^{\mathfrak{p}}-1} \alpha_{i,0}t^{i+1}(\sum_{i
%= 0}^{n_1^{\mathfrak{p}}-1} \alpha_{i,2}t^{i+1}+1)} \over
%2(\sum_{i = 0}^{n_1^{\mathfrak{p}}-1} \alpha_{i,2}t^{i+1}+1)} $$}
%\end{alertblock}
%\end{frame}
\begin{frame}\frametitle{Theorem 1}
Matrices
\begin{displaymath}
{{R}^{[\mathfrak{p}]}}=(d^{[\mathfrak{p}]}(t),h^{[\mathfrak{p}]}(t)), \quad
{{R}^{[\bar{\mathfrak{p}]}}}=(d^{[\bar{\mathfrak{p}}]}(t),h^{[\bar{\mathfrak{p}}]}(t))
\end{displaymath}
are both RAs $\leftrightarrow$ $\mathfrak{p}$ is a Riordan pattern.
\begin{block}{}
By specializing this result to the cases
$\left|n_1^{[\mathfrak{p}]}-n_0^{[\mathfrak{p}]}\right|\in \{0,1\}$ and by
setting
$C^{[\mathfrak{p}]}(t)=C^{[\mathfrak{p}]}\left(\sqrt{t},\sqrt{t}\right)=\sum_{i
\geq 0}c_{2i}t^i,$ we have explicit formulae for both functions $d(t)$ and $h(t)$
wrt polynomial $C^{[\mathfrak{p}]}(t)$.
\end{block}
\end{frame}
\begin{frame}\frametitle{Theorem 1: the case $n_1^{[\mathfrak{p}]}-n_0^{[\mathfrak{p}]}=1$}
$$d^{[\mathfrak{p}]}(t)={C^{[\mathfrak{p}]}(t)
\over \sqrt{C^{[\mathfrak{p}]}(t)^2-4tC^{[\mathfrak{p}]}(t)(C^{[\mathfrak{p}]}(t)-t^{n_0^{\mathfrak{p}}})}}, $$
$$h^{[\mathfrak{p}]}(t)={C^{[\mathfrak{p}]}(t) -\sqrt{C^{[\mathfrak{p}]}(t)^2-4tC^{[\mathfrak{p}]}(t)(C^{[\mathfrak{p}]}(t)-t^{n_0^{\mathfrak{p}}})}
\over 2 C^{[\mathfrak{p}]}(t)}.$$
\end{frame}
\begin{frame}\frametitle{Theorem 1: the case $n_1^{[\mathfrak{p}]}-n_0^{[\mathfrak{p}]}=0$}
$$d^{[\mathfrak{p}]}(t)={C^{[\mathfrak{p}]}(t)
\over \sqrt{( C^{[\mathfrak{p}]}(t)+t^{n_0^{\mathfrak{p}}})^2-4tC^{[\mathfrak{p}]}(t)^2}}, $$
$$h^{[\mathfrak{p}]}(t)=
{C^{[\mathfrak{p}]}(t)+ t^{n_0^{\mathfrak{p}}} - \sqrt{( C^{[\mathfrak{p}]}(t)+t^{n_0^{\mathfrak{p}}})^2-4tC^{[\mathfrak{p}]}(t)^2} \over 2
C^{[\mathfrak{p}]}(t)}.$$
\end{frame}
\begin{frame}\frametitle{Theorem 1: the case $n_0^{[\mathfrak{p}]}-n_1^{[\mathfrak{p}]}=1$}
$$d^{[\mathfrak{p}]}(t)={C^{[\mathfrak{p}]}(t)
\over \sqrt{C^{[\mathfrak{p}]}(t)^2-4tC^{[\mathfrak{p}]}(t)(C^{[\mathfrak{p}]}(t)-t^{n_1^{\mathfrak{p}}})}}, $$
$$h^{[\mathfrak{p}]}(t)={C^{[\mathfrak{p}]}(t) -\sqrt{C^{[\mathfrak{p}]}(t)^2-4tC^{[\mathfrak{p}]}(t)(C^{[\mathfrak{p}]}(t)-t^{n_1^{\mathfrak{p}}})}
\over 2 (C^{[\mathfrak{p}]}(t)- t^{n_1^{\mathfrak{p}}})}.$$
\end{frame}
%\begin{frame}\frametitle{Theorem 1 -b-}
%... where $\delta_{i,j}$ is the Kronecker delta,
%$$\sum_{i = 0}^{n_1^{\mathfrak{p}}-1} \alpha_{i,0}t^{i}=\sum_{i = 0}^{n_1^{\mathfrak{p}}-1} c_{2i}t^{i}-
%\delta_{-1,n_0^{\mathfrak{p}}-n_1^{\mathfrak{p}}}t^{n_1^{\mathfrak{p}}-1}, $$
%$$\sum_{i = 0}^{n_1^{\mathfrak{p}}-1} \alpha_{i,1}t^{i}=-\sum_{i = 0}^{n_1^{\mathfrak{p}}-1} c_{2(i+1)}t^{i}-
%\delta_{0,n_0^{\mathfrak{p}}-n_1^{\mathfrak{p}}}t^{n_1^{\mathfrak{p}}-1}, $$
%$$\sum_{i = 0}^{n_1^{\mathfrak{p}}-1} \alpha_{i,2}t^{i}=\sum_{i = 0}^{n_1^{\mathfrak{p}}-1} c_{2(i+1)}t^{i}-
%\delta_{1,n_0^{\mathfrak{p}}-n_1^{\mathfrak{p}}}t^{n_1^{\mathfrak{p}}-1},$$ and the coefficients $c_i$ are given by the autocorrelation vector
%of $\mathfrak{p}.$
% An analogous formula holds for $h^{[\bar{\mathfrak{p}}]}(t)$.
%\end{frame}
\begin{frame}\frametitle{Classes of patterns}
\begin{itemize}
\item $\mathfrak{p}=1^{j+1}0^j$
\item $\mathfrak{p}=0^{j+1}1^j$
\item $\mathfrak{p}=1^{j}0^j$ and $\mathfrak{p}=0^{j}1^j$
\item $\mathfrak{p}=(10)^j1$
\item $\mathfrak{p}=(01)^j0$
\end{itemize}
\end{frame}
\begin{frame}\frametitle{A combinatorial interpretation for $\mathfrak{p}=10$}
In this case we get the RA ${\mathcal{R}^{[10]}} = \left(d^{[10]}(t), h^{[10]}(t)\right)$
such that
\begin{displaymath}
d^{[10]}(t)=\frac{1}{1-t} \quad \text{and} \quad h^{[10]}(t) = t,
\end{displaymath} so the number $R_{n, 0}^{[10]}$ of words
containing $n$ bits $1$ and $n$ bits $0$, avoiding pattern $\mathfrak{p}=10$, is
$[t^{n}] d^{[10]}(t) = 1$ for $n\in\mathbb{N}$.
In terms of lattice paths this corresponds to the fact that there is exactly
one \emph{valley}-shaped path having $n$ steps of both kinds $\diagup$ and
$\diagdown$, avoiding $\mathfrak{p}=10$ and terminating at coordinate $(2n, 0)$
for each $n\in\mathbb{N}$, formally the path $0^{n}1^{n}$.
\end{frame}
\iffalse
\begin{frame}\frametitle{A Lemma}
Let $\mathfrak{p}$ be a Riordan pattern. Then the Riordan array ${{R}^{[\mathfrak{p}]}}$ is characterized by the $A$-matrix
defined by the following relation:
$$R_{n+1,k+1}^{[\mathfrak{p}]}=R_{n,k}^{[\mathfrak{p}]}
+R_{n+1,k+2}^{[\mathfrak{p}]}-R_{n+1-n_1^{\mathfrak{p}},k+1+n_0^{\mathfrak{p}}-n_1^{\mathfrak{p}}}^{[\mathfrak{p}]} +$$
$$- \sum_{i\geq 1} c_{2i}\left( R_{n+1-i,k+1}^{[\mathfrak{p}]} -R_{n-i,k}^{[\mathfrak{p}]} -R_{n+1-i,k+2}^{[\mathfrak{p}]} \right),$$
where the $c_i$ are given by the autocorrelation vector of
$\mathfrak{p}.$
\end{frame}
\fi
\section{The $|w|_{0}\leq |w|_{1}$ constraint}
\begin{frame}\frametitle{The $|w|_{0}\leq |w|_{1}$ constraint}
\begin{itemize}
\item let $|w|_{i}$ be the number of bits $i$ in word $w$
\item enumeration of binary words avoiding a pattern $\mathfrak{p}$, without the
constraint $|w|_0\leq |w|_1,$ gives a {\bf \red rational} bivariate generating function
for the sequence $F^{[\mathfrak{p}]}_n=\sum_{k=0}^nF_{n,k}^{[\mathfrak{p}]}$
\item under the restriction such that words have to have no more bits $0$ than
bits $1$, then the language is no longer regular and its enumeration becomes
more difficult
\item using gf $R^{[\mathfrak{p}]}(x,y)$ and the fundamental theorem of RAs:
$$\sum_{k=0}^n d_{n,k}f_k=[t^n]d(t)f(h(t)) $$ we obtain many {\bf \red new
algebraic generating functions} expressed in terms of the autocorrelation
polynomial of $\mathfrak{p}$
\end{itemize}
\end{frame}
\begin{frame}\frametitle{Theorem 2: the case $n_1^{[\mathfrak{p}]}-n_0^{[\mathfrak{p}]}=1$}
Recall that
\begin{displaymath}
R^{[\mathfrak{p}]}(t,w)=\sum_{n,k\in\mathbb{N}} R_{n, k}^{[\mathfrak{p}]}t^n
w^k={d^{[\mathfrak{p}]}(t) \over 1-wh^{[\mathfrak{p}]}(t)}
\end{displaymath}
Let $S^{[\mathfrak{p}]}(t)=\sum_{n\geq 0}S_n^{[\mathfrak{p}]}t^n$ be the gf
enumerating the set of binary words $\left\lbrace
w\in\mathcal{L}^{[\mathfrak{p}]} : |w|_0\leq |w|_1\right\rbrace$ according to
{\bf \red the number of bits $1$}
\begin{itemize}
\item if $n_1^{[\mathfrak{p}]}=n_0^{[\mathfrak{p}]}+1:$
$$S^{[\mathfrak{p}]}(t)={2C^{[\mathfrak{p}]}(t) \over \sqrt{Q(t)}\left(\sqrt{C^{[\mathfrak{p}]}(t)}+ \sqrt{Q(t)} \right)} $$
where $Q(t)={(1-4t)C^{[\mathfrak{p}]}(t)^2+4t^{n_1^{[\mathfrak{p}]}}}$
\end{itemize}
\end{frame}
\begin{frame}\frametitle{Theorem 2: the case $n_0^{[\mathfrak{p}]}-n_1^{[\mathfrak{p}]}=1$}
\begin{itemize}
\item if $n_0^{[\mathfrak{p}]}=n_1^{[\mathfrak{p}]}+1:$
$$S^{[\mathfrak{p}]}(t)={2C^{[\mathfrak{p}]}(t)(C^{[\mathfrak{p}]}(t)-t^{n_1^{[\mathfrak{p}]}}
) \over \sqrt{Q(t)} \left(C^{[\mathfrak{p}]}(t)-2t^{n_1^{[\mathfrak{p}]}}+ \sqrt{Q(t)} \right) }$$
where $Q(t)={ (1-4t)C^{[\mathfrak{p}]}(t)^2+4t^{n_0^{[\mathfrak{p}]}}C^{[\mathfrak{p}]}(t)}$
\end{itemize}
\end{frame}
\begin{frame}\frametitle{Theorem 2: the case $n_0^{[\mathfrak{p}]}-n_1^{[\mathfrak{p}]}=0$}
\begin{itemize}
\item if $n_1^{[\mathfrak{p}]}=n_0^{[\mathfrak{p}]}:$
$$S^{[\mathfrak{p}]}(t)={2C^{[\mathfrak{p}]}(t)^2 \over \sqrt{Q(t)}
\left(C^{[\mathfrak{p}]}(t)-t^{n_0^{[\mathfrak{p}]}}+ \sqrt{Q(t)} \right) }$$
where $Q(t)=(1-4t)C^{[\mathfrak{p}]}(t)^2+2t^{n_0^{[\mathfrak{p}]}}C^{[\mathfrak{p}]}(t)+t^{2n_0^{[\mathfrak{p}]}}$
\end{itemize}
\begin{proof}
Observe that $S^{[\mathfrak{p}]}(t)=R^{[\mathfrak{p}]}(t,1),$ or, equivalently, that
$S_n^{[\mathfrak{p}]}=\sum_{k=0}^nR_{n, k}^{[\mathfrak{p}]}$ and apply the
fundamental rule with $f_k=1$.
\end{proof}
\end{frame}
\begin{frame}\frametitle{Theorem 3: the case $n_1^{[\mathfrak{p}]}-n_0^{[\mathfrak{p}]}=1$}
Let $L^{[\mathfrak{p}]}(t)=\sum_{n\geq 0}L_n^{[\mathfrak{p}]}t^n$ be the
gf enumerating the set of binary words $\left\lbrace
w\in\mathcal{L}^{[\mathfrak{p}]} : |w|_0\leq |w|_1\right\rbrace$ according to
{\bf \red the length}
\begin{itemize}
\item if $n_1^{[\mathfrak{p}]}=n_0^{[\mathfrak{p}]}+1:$
$$L^{[\mathfrak{p}]}(t)= {2tC^{[\mathfrak{p}]}(t^2)^2 \over \sqrt{Q(t)}\left((2t-1)C(t^2)+ \sqrt{ Q(t) } \right)}$$
where $Q(t)=C^{[\mathfrak{p}]}(t^2)\left( (1-4t^2)C^{[\mathfrak{p}]}(t^2)+4t^{2n_1^{[\mathfrak{p}]}}\right)$
\end{itemize}
\end{frame}
\begin{frame}\frametitle{Theorem 3: the case $n_0^{[\mathfrak{p}]}-n_1^{[\mathfrak{p}]}=1$}
\begin{itemize}
\item if $n_0^{[\mathfrak{p}]}=n_1^{[\mathfrak{p}]}+1:$
$$L^{[\mathfrak{p}]}(t)={2t\sqrt{C^{[\mathfrak{p}]}(t^2)}(t^{2n_1^{[\mathfrak{p}]}}-C^{[\mathfrak{p}]}(t^2))
\over \sqrt{ Q(t) }\left((1-2t)C^{[\mathfrak{p}]}(t^2)+ B(t) - \sqrt{C^{[\mathfrak{p}]}(t^2) Q(t) } \right)}$$
where $Q(t)=(1-4t^2)C^{[\mathfrak{p}]}(t^2)+4t^{2n_0^{[\mathfrak{p}]}}$ and
$B(t)=2t^{n_0^{[\mathfrak{p}]} +n_1^{[\mathfrak{p}]}}$
\end{itemize}
\end{frame}
\begin{frame}\frametitle{Theorem 3: the case $n_1^{[\mathfrak{p}]}-n_0^{[\mathfrak{p}]}=0$}
\begin{itemize}
\item if $n_1^{[\mathfrak{p}]}=n_0^{[\mathfrak{p}]}:$ $$L^{[\mathfrak{p}]}(t)=
{2tC^{[\mathfrak{p}]}(t^2)^2 \over \sqrt{ Q(t)
}\left((2t-1)C(t^2)-t^{2n_0^{[\mathfrak{p}]}} + \sqrt{ Q(t) } \right)}$$
where
$Q(t)=(1-4t^2)C^{[\mathfrak{p}]}(t^2)^2+2t^{2n_0^{[\mathfrak{p}]}}C^{[\mathfrak{p}]}(t^2)+t^{4n_0^{[\mathfrak{p}]}}$
\end{itemize}
\end{frame}
\begin{frame}\frametitle{Theorem 3: proof}
\begin{proof}
Observe that the application of generating function $R^{[\mathfrak{p}]}(t, w)$ as
\begin{displaymath}
R^{[\mathfrak{p}]}\left(tw,{1 \over w}\right)=\sum_{n,k\in\mathbb{N}} R_{n, k}^{[\mathfrak{p}]}t^n w^{n-k}
\end{displaymath}
entails that $[t^{r}w^{s}]R^{[\mathfrak{p}]}\left(tw,{1 \over w}\right)=R_{r,
r-s}^{[\mathfrak{p}]}$ which is the number of binary words with $r$ bits $1$
and $s$ bits $0$. To enumerate according to the length let $t=w$, therefore
$$L^{[\mathfrak{p}]}(t)=\sum_{n\geq 0}L_n^{[\mathfrak{p}]}t^n=R^{[\mathfrak{p}]}\left(t^2,\frac{1}{t}\right)$$
\end{proof}
\end{frame}
\section{Series developments and closed formulae}
\begin{frame}\frametitle{Series development for $S^{[1^{j+1}0^{j}]}(t)$}
{\tiny
\begin{table}
\begin{equation*}\begin{array}{c|cccccccccccc}j/n & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11\\\hline0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\1 & 1 & 3 & 7 & 15 & 31 & 63 & 127 & 255 & 511 & 1023 & 2047 & 4095\\2 & 1 & 3 & 10 & 32 & 106 & 357 & 1222 & 4230 & 14770 & 51918 & 183472 & 651191\\3 & 1 & 3 & 10 & 35 & 123 & 442 & 1611 & 5931 & 22010 & 82187 & 308427 & 1162218\\4 & 1 & 3 & 10 & 35 & 126 & 459 & 1696 & 6330 & 23806 & 90068 & 342430 & 1307138\\5 & 1 & 3 & 10 & 35 & 126 & 462 & 1713 & 6415 & 24205 & 91874 & 350406 & 1341782\\6 & 1 & 3 & 10 & 35 & 126 & 462 & 1716 & 6432 & 24290 & 92273 & 352212 & 1349768\\7 & 1 & 3 & 10 & 35 & 126 & 462 & 1716 & 6435 & 24307 & 92358 & 352611 & 1351574\\8 & 1 & 3 & 10 & 35 & 126 & 462 & 1716 & 6435 & 24310 & 92375 & 352696 & 1351973\end{array}\end{equation*}
\begin{displaymath}
\begin{split}
[t^{3}]S^{[110]}(t) &= \big|\lbrace 111, 0111, 1011, 00111, 01011, 10011, 10101, 000111, \\
& 001011, 010011, 010101, 100011, 100101, 101001, 101010\rbrace\big| = 15
\end{split}
\end{displaymath}
\caption{Some series developments for $S^{[1^{j+1}0^j]}(t)$ and the set of
words with $n=3$ bits $1$, avoiding pattern $\mathfrak{p}=110$, so $j=1$ in the
family; moreover, for $j=1$ the sequence corresponds to $A000225$, for $j=2$ the
sequence corresponds to $A261058$.}
\end{table}
}
\end{frame}
\begin{frame}\frametitle{Series development for $L^{[1^{j+1}0^{j}]}(t)$}
{\tiny
\begin{table}
\begin{equation*}\begin{array}{c|ccccccccccccccc}j/n & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14\\\hline0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\1 & 1 & 1 & 3 & 3 & 7 & 7 & 15 & 15 & 31 & 31 & 63 & 63 & 127 & 127 & 255\\2 & 1 & 1 & 3 & 4 & 11 & 15 & 38 & 55 & 135 & 201 & 483 & 736 & 1742 & 2699 & 6313\\3 & 1 & 1 & 3 & 4 & 11 & 16 & 42 & 63 & 159 & 247 & 610 & 969 & 2354 & 3802 & 9117\\4 & 1 & 1 & 3 & 4 & 11 & 16 & 42 & 64 & 163 & 255 & 634 & 1015 & 2482 & 4041 & 9752\\5 & 1 & 1 & 3 & 4 & 11 & 16 & 42 & 64 & 163 & 256 & 638 & 1023 & 2506 & 4087 & 9880\\6 & 1 & 1 & 3 & 4 & 11 & 16 & 42 & 64 & 163 & 256 & 638 & 1024 & 2510 & 4095 & 9904\\7 & 1 & 1 & 3 & 4 & 11 & 16 & 42 & 64 & 163 & 256 & 638 & 1024 & 2510 & 4096 & 9908\end{array}\end{equation*}
\caption{Some series developments for $L^{[1^{j+1}0^j]}(t)$; moreover, for
$j=1$ the sequence corresponds to $A052551$.}
\end{table}
}
\end{frame}
\begin{frame}\frametitle{Closed formulae for particular cases}
When the parameter $j$ for a pattern $\mathfrak{p}$ assumes values $0$ and $1$
it is possible to find closed formulae for coefficients
$S_{n}^{[\mathfrak{p}]}$ and $L_{n}^{[\mathfrak{p}]}$; moreover, in a recent
submitted paper we give combinatorial interpretations, in terms of inversions
in words and boxes occupancy, too.
\begin{block}{$S_{n}^{[\mathfrak{p}]}$}
\begin{displaymath}
\begin{array}{c|ccc}
j/\mathfrak{p} & {1^{j+1}0^{j}} & {0^{j+1}1^{j}} & {1^{j}0^{j}} \\
\hline
0 & [\![n = 0]\!] & 1 & { {2n+1}\choose{n} } \\
1 & 2^{n+1} -1 & (n+2)2^{n-1} & n+1 \\
\end{array}{}
\end{displaymath}
\end{block}
\end{frame}
\begin{frame}\frametitle{Closed formulae for particular cases}
\begin{block}{$L_{2m}^{[\mathfrak{p}]}$}
\begin{displaymath}
\begin{array}{c|ccc}
j/\mathfrak{p} & {1^{j+1}0^{j}} & {0^{j+1}1^{j}} & {1^{j}0^{j}} \\
\hline
0 & [\![n = 0]\!] & 1 & 2^{2m-1} + \frac{1}{2}{ {2m}\choose{m} } \\
1 & 2^{m+1} -1 & F_{2m+3}-2^{m} & m+1 \\
\end{array}{}
\end{displaymath}
\end{block}
\begin{block}{$L_{2m+1}^{[\mathfrak{p}]}$}
\begin{displaymath}
\begin{array}{c|ccc}
j/\mathfrak{p} & {1^{j+1}0^{j}} & {0^{j+1}1^{j}} & {1^{j}0^{j}} \\
\hline
0 & 0 & 1 & 2^{2m-1} \\
1 & 2^{m+1} -1 & F_{2m+3}-2^{m+1} & m+1 \\
\end{array}{}
\end{displaymath}
\end{block}
\end{frame}
\begin{frame}{Summary}
% Keep the summary *very short*.
\begin{block}{Key points}
\begin{itemize}
\item split $F(t)$ in $F^{[\mathfrak{p}]}(x,y)$ to account for bits $1$ and $0$
\item ${{R}^{[\mathfrak{p}]}}$ and ${{R}^{[\bar{\mathfrak{p}]}}}$ are both RA
$\leftrightarrow$ $\mathfrak{p}$ is a Riordan pattern.
\item requiring $|w|_{0}\leq|w|_{1}$ entails
\begin{displaymath}
\begin{split}
S^{[\mathfrak{p}]}(t)&=R^{[\mathfrak{p}]}(t,1)\rightarrow
[t^{n}]S^{[\mathfrak{p}]}(t)= \left|\left\lbrace w \in \mathcal{L}^{[\mathfrak{p}]}:
\begin{array}{l} |w|_{1} = n \\ |w|_{0}\leq|w|_{1} \end{array}\right\rbrace\right|\\
L^{[\mathfrak{p}]}(t)&=R^{[\mathfrak{p}]}\left(t^2,\frac{1}{t}\right)\rightarrow
[t^{n}]L^{[\mathfrak{p}]}(t)= \left|\left\lbrace w \in \mathcal{L}^{[\mathfrak{p}]}:
\begin{array}{l} |w| = n \\ |w|_{0}\leq|w|_{1} \end{array}\right\rbrace\right|\\
\end{split}
\end{displaymath}
\end{itemize}
\end{block}
\end{frame}
\section{Matrices functions}
\begin{frame}{Defs}
Let $A\in\mathbb{C}^{m\times m}$ be a matrix and denote with $\sigma$ the
spectre of $A$, formally $\sigma(A) =
\lbrace \lambda_{i}: 1\leq i\leq \nu\rbrace$, with multiplicities $\lbrace
m_{i}: 1\leq i\leq \nu\rbrace$, respectively, such that
$\sum_{i=1}^{\nu}{m_{i}}=m$
\vfill
We say that function $f$
\emph{is defined on the spectre $\sigma$ of matrix $A$} if exists
$\left. \frac{\partial^{(j)}{f}}{\partial{z}} \right|_{z=\lambda_{i}}$
for $i\in \lbrace 1, \ldots, \nu \rbrace$, for $j \in \lbrace 0, \ldots, m_{i}-1 \rbrace$.
\vfill
Given a function $f$ defined on the spectre of a matrix $A$, define the polynomial $g$ such that
it takes the same values of $f$ on the spectre of $A$, formally:
$\left. \frac{\partial^{(j)}{f}}{\partial{z}} \right|_{z=\lambda_{i}} =
\left. \frac{\partial^{(j)}{g}}{\partial{z}} \right|_{z=\lambda_{i}}$
for $i\in \lbrace 1, \ldots, \nu \rbrace$, for $j \in \lbrace 0, \ldots, m_{i}-1 \rbrace$,
then $f(A) = g(A)$.
\end{frame}
\begin{frame}{Defs}
\vfill
Polynomial $g$ is an \emph{interpolating Hermite polynomial} which
can be defined using the generalized Lagrange base $ \lbrace \Phi_{ij} \rbrace$, formally:
\begin{displaymath}
g(z) = \sum_{i=1}^{\nu}{\sum_{j=1}^{m_{i}}{
\left. \frac{\partial^{(j-1)}{f}}{\partial{z}} \right|_{z=\lambda_{i}}\Phi_{ij}(z)
}}
\end{displaymath}
where each polynomial $\Phi_{ij}$, of degree $m-1$, is defined implicitly as the solution of the system:
\begin{displaymath}
\left. \frac{\partial^{(r-1)}{\Phi_{ij}}}{\partial{z}} \right|_{z=\lambda_{l}} = \delta_{il}\delta_{jr}
\end{displaymath}
for $l\in \lbrace 1, \ldots, \nu \rbrace$, for $r \in \lbrace 1, \ldots, m_{l} \rbrace$, where
$\delta$ is the Kroneker delta, defined as $\delta_{ij}=1 \leftrightarrow i=j$.
\end{frame}
\begin{frame}{Defs}
Let $\mathcal{R}_{m}\in\mathbb{C}^{m\times m}$ be a \emph{finite Riordan matrix},
hence $\sigma(\mathcal{R}_{m})= \lbrace \lambda_{1} \rbrace$, so $\nu=1$, where $\lambda_{1}=1$
with multiplicity $m_{1}=m$.
\vfill
Therefore, the generalized Lagrange base is composed of polynomials
\begin{displaymath}
\Phi_{1j}(z) = \sum_{k=0}^{j-1}{\frac{(-1)^{j-1-k}}{(j-1-k)!}\frac{z^{k}}{k!}}
\end{displaymath}
\vfill
For the sake of clarity we show polynomials $\Phi_{1j}$ for $j\in \lbrace
1,\ldots,m \rbrace$ relative to any finite Riordan matrix $\mathcal{R}_{m}$
where $m=8$:
{\tiny
\begin{displaymath}
\begin{array}{c}
\Phi_{ 1, 1 }{\left (z \right )} = 1\\
\Phi_{ 1, 2 }{\left (z \right )} = z - 1\\
\Phi_{ 1, 3 }{\left (z \right )} = \frac{z^{2}}{2} - z + \frac{1}{2}\\
\Phi_{ 1, 4 }{\left (z \right )} = \frac{z^{3}}{6} - \frac{z^{2}}{2} + \frac{z}{2} - \frac{1}{6}\\
\Phi_{ 1, 5 }{\left (z \right )} = \frac{z^{4}}{24} - \frac{z^{3}}{6} + \frac{z^{2}}{4} - \frac{z}{6} + \frac{1}{24}\\
\Phi_{ 1, 6 }{\left (z \right )} = \frac{z^{5}}{120} - \frac{z^{4}}{24} + \frac{z^{3}}{12} - \frac{z^{2}}{12} + \frac{z}{24} - \frac{1}{120}\\
\Phi_{ 1, 7 }{\left (z \right )} = \frac{z^{6}}{720} - \frac{z^{5}}{120} + \frac{z^{4}}{48} - \frac{z^{3}}{36} + \frac{z^{2}}{48} - \frac{z}{120} + \frac{1}{720}\\
\Phi_{ 1, 8 }{\left (z \right )} = \frac{z^{7}}{5040} - \frac{z^{6}}{720} + \frac{z^{5}}{240} - \frac{z^{4}}{144} + \frac{z^{3}}{144} - \frac{z^{2}}{240} + \frac{z}{720} - \frac{1}{5040}\\
%\Phi_{ 1, 9 }{\left (z \right )} = \frac{z^{8}}{40320} - \frac{z^{7}}{5040} + \frac{z^{6}}{1440} - \frac{z^{5}}{720} + \frac{z^{4}}{576} - \frac{z^{3}}{720} + \frac{z^{2}}{1440} - \frac{z}{5040} + \frac{1}{40320}\\
%\Phi_{ 1, 10 }{\left (z \right )} = \frac{z^{9}}{362880} - \frac{z^{8}}{40320} + \frac{z^{7}}{10080} - \frac{z^{6}}{4320} + \frac{z^{5}}{2880} - \frac{z^{4}}{2880} + \frac{z^{3}}{4320} - \frac{z^{2}}{10080} + \frac{z}{40320} - \frac{1}{362880}\\
\end{array}
\end{displaymath}
}
\end{frame}
\begin{frame}{$f(z)=\frac{1}{z}$}
The general form of $j$th derivative of function $f$ is
$$\frac{\partial^{(j)}{f}(z)}{\partial{z}} = \frac{(-1)^{j}j!}{z^{j+1}}$$
therefore
\begin{displaymath}
g(z) = \sum_{j=1}^{m}{\sum_{k=0}^{j-1}{{{j-1}\choose{k}}(-z)^{k}}}
= \sum_{k=0}^{m-1}{{{m}\choose{k+1}}(-z)^{k}}
\end{displaymath}
\vfill
Polynomial $g$ where $m=8$ is defined according to
\[g{\left (z \right )} = - z^{7} + 8 z^{6} - 28 z^{5} + 56 z^{4} - 70 z^{3} + 56 z^{2} - 28 z + 8\]
\end{frame}
\begin{frame}{$\mathcal{P}^{-1}$ and $\mathcal{C}^{-1}$}
{\footnotesize
\begin{displaymath}
g(\mathcal{P})=\mathcal{P}^{-1}= \left[\begin{matrix}1 & & & & & & & \\-1 & 1 & & & & & & \\1 & -2 & 1 & & & & & \\-1 & 3 & -3 & 1 & & & & \\1 & -4 & 6 & -4 & 1 & & & \\-1 & 5 & -10 & 10 & -5 & 1 & & \\1 & -6 & 15 & -20 & 15 & -6 & 1 & \\-1 & 7 & -21 & 35 & -35 & 21 & -7 & 1\end{matrix}\right]
\end{displaymath}
\begin{displaymath}
g(\mathcal{C})=\mathcal{C}^{-1}=\left[\begin{matrix}1 & & & & & & & \\-1 & 1 & & & & & & \\ & -2 & 1 & & & & & \\ & 1 & -3 & 1 & & & & \\ & & 3 & -4 & 1 & & & \\ & & -1 & 6 & -5 & 1 & & \\ & & & -4 & 1 & -6 & 1 & \\ & & & 1 & -1 & 15 & -7 & 1\end{matrix}\right]
\end{displaymath}
}
\end{frame}
\begin{frame}{Fibonacci numbers}
\begin{displaymath}
\mathcal{F} = \left[\begin{matrix}1 & 1\\1 & 0\end{matrix}\right],
\quad \lambda_{1} = \frac{1}{2}- \frac{\sqrt{5}}{2} ,
\quad \lambda_{2} = \frac{1}{2} + \frac{\sqrt{5}}{2}
\end{displaymath}
\vfill
\begin{displaymath}
\Phi_{ 1, 1 }{\left (z \right )} = \frac{z}{\lambda_{1} - \lambda_{2}} - \frac{\lambda_{2}}{\lambda_{1} - \lambda_{2}}, \quad \Phi_{ 2, 1 }{\left (z \right )} = - \frac{z}{\lambda_{1} - \lambda_{2}} + \frac{\lambda_{1}}{\lambda_{1} - \lambda_{2}}
\end{displaymath}
\vfill
\begin{displaymath}
g{\left (z \right )} = z \left(\frac{\lambda_{1}^{r}}{\lambda_{1} - \lambda_{2}} - \frac{\lambda_{2}^{r}}{\lambda_{1} - \lambda_{2}}\right) + \frac{\lambda_{1} \lambda_{2}^{r}}{\lambda_{1} - \lambda_{2}} - \frac{\lambda_{1}^{r} \lambda_{2}}{\lambda_{1} - \lambda_{2}}
\end{displaymath}
\vfill
\begin{displaymath}
\mathcal{F}^{r}=\left[\begin{matrix}\frac{1}{\lambda_{1} - \lambda_{2}} \left(\lambda_{1} \lambda_{2}^{r} - \lambda_{1}^{r} \lambda_{2} + \lambda_{1}^{r} - \lambda_{2}^{r}\right) & \frac{\lambda_{1}^{r} - \lambda_{2}^{r}}{\lambda_{1} - \lambda_{2}}\\\frac{\lambda_{1}^{r} - \lambda_{2}^{r}}{\lambda_{1} - \lambda_{2}} & \frac{\lambda_{1} \lambda_{2}^{r} - \lambda_{1}^{r} \lambda_{2}}{\lambda_{1} - \lambda_{2}}\end{matrix}\right]
\end{displaymath}
\vfill
\begin{displaymath}
\mathcal{F}^{8} = \left[\begin{matrix}f_{9} & f_{8}\\f_{8} & f_{7}\end{matrix}\right] = \left[\begin{matrix}34 & 21\\21 & 13\end{matrix}\right]
\end{displaymath}
\end{frame}
\begin{frame}{ }
\begin{CJK}{UTF8}{mj}
\Huge 고맙습니다
\end{CJK}
\end{frame}
\end{document}
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RankNTypes #-}
module Grenade.Utils.OneHot (
oneHot
, hotMap
, makeHot
, unHot
, sample
) where
import qualified Control.Monad.Random as MR
import Data.List ( group, sort )
import Data.Map ( Map )
import qualified Data.Map as M
import Data.Proxy
import Data.Singletons.TypeLits
import Data.Vector ( Vector )
import qualified Data.Vector as V
import qualified Data.Vector.Storable as VS
import Numeric.LinearAlgebra ( maxIndex )
import Numeric.LinearAlgebra.Devel
import Numeric.LinearAlgebra.Static
import Grenade.Core.Shape
-- | From an int which is hot, create a 1D Shape
-- with one index hot (1) with the rest 0.
-- Rerurns Nothing if the hot number is larger
-- than the length of the vector.
oneHot :: forall n. (KnownNat n)
=> Int -> Maybe (S ('D1 n))
oneHot hot =
let len = fromIntegral $ natVal (Proxy :: Proxy n)
in if hot < len
then
fmap S1D . create $ runSTVector $ do
vec <- newVector 0 len
writeVector vec hot 1
return vec
else Nothing
-- | Create a one hot map from any enumerable.
-- Returns a map, and the ordered list for the reverse transformation
hotMap :: (Ord a, KnownNat n) => Proxy n -> [a] -> Either String (Map a Int, Vector a)
hotMap n as =
let len = fromIntegral $ natVal n
uniq = [ c | (c:_) <- group $ sort as]
hotl = length uniq
in if hotl == len
then
Right (M.fromList $ zip uniq [0..], V.fromList uniq)
else
Left ("Couldn't create hotMap of size " ++ show len ++ " from vector with " ++ show hotl ++ " unique characters")
-- | From a map and value, create a 1D Shape
-- with one index hot (1) with the rest 0.
-- Rerurns Nothing if the hot number is larger
-- than the length of the vector or the map
-- doesn't contain the value.
makeHot :: forall a n. (Ord a, KnownNat n)
=> Map a Int -> a -> Maybe (S ('D1 n))
makeHot m x = do
hot <- M.lookup x m
let len = fromIntegral $ natVal (Proxy :: Proxy n)
if hot < len
then
fmap S1D . create $ runSTVector $ do
vec <- newVector 0 len
writeVector vec hot 1
return vec
else Nothing
unHot :: forall a n. KnownNat n
=> Vector a -> S ('D1 n) -> Maybe a
unHot v (S1D xs)
= (V.!?) v
$ maxIndex (extract xs)
sample :: forall a n m. (KnownNat n, MR.MonadRandom m)
=> Double -> Vector a -> S ('D1 n) -> m a
sample temperature v (S1D xs) = do
ix <- MR.fromList . zip [0..] . fmap (toRational . exp . (/ temperature) . log) . VS.toList . extract $ xs
return $ v V.! ix
|
(*
Copyright (C) 2017 M.A.L. Marques
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*)
(* type: mgga_exc *)
(* prefix:
mgga_x_tpss_params *params;
assert(p->params != NULL);
params = (mgga_x_tpss_params * ) (p->params);
*)
$ifdef mgga_x_revtpss_params
params_a_b := 0.40:
params_a_c := 2.35203946:
params_a_e := 2.16769874:
params_a_kappa := 0.804:
params_a_mu := 0.14:
params_a_BLOC_a := 3.0:
params_a_BLOC_b := 0.0:
$endif
tpss_ff := z -> params_a_BLOC_a + params_a_BLOC_b*z:
tpss_kappa := (x, t) -> params_a_kappa:
$include "tpss_x.mpl"
(* Equation (5) *)
tpss_a1 := (x, t) -> tpss_kappa(x, t)/(tpss_kappa(x, t) + tpss_fx(x, t)):
tpss_f := (x, u, t) -> 1 + tpss_kappa(x, t)*(1 - tpss_a1(x, t)):
f := (rs, z, xt, xs0, xs1, u0, u1, t0, t1) -> mgga_exchange(tpss_f, rs, z, xs0, xs1, u0, u1, t0, t1):
|
(*
* Copyright 2014, NICTA
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* @TAG(NICTA_BSD)
*)
theory CTranslation
imports
"../../lib/String_Compare"
"PackedTypes"
"PrettyProgs"
"StaticFun"
"IndirectCalls"
keywords
"install_C_file"
"install_C_types"
"new_C_include_dir":: thy_decl
and
"memsafe"
"c_types"
"c_defs"
begin
declare Char_eq_Char_iff [simp del]
lemma TWO: "Suc (Suc 0) = 2"
by arith
definition
fun_addr_of :: "int \<Rightarrow> unit ptr" where
"fun_addr_of i \<equiv> Ptr (word_of_int i)"
definition
ptr_range :: "'a::c_type ptr \<Rightarrow> addr set" where
"ptr_range p \<equiv> {ptr_val (p::'a ptr) ..<
ptr_val p + word_of_int(int(size_of (TYPE('a)))) }"
definition
creturn :: "((c_exntype \<Rightarrow> c_exntype) \<Rightarrow> ('c, 'd) state_scheme \<Rightarrow> ('c, 'd) state_scheme)
\<Rightarrow> (('a \<Rightarrow> 'a) \<Rightarrow> ('c, 'd) state_scheme \<Rightarrow> ('c, 'd) state_scheme)
\<Rightarrow> (('c, 'd) state_scheme \<Rightarrow> 'a) \<Rightarrow> (('c, 'd) state_scheme,'p,'f) com"
where
"creturn rtu xfu v \<equiv> (Basic (\<lambda>s. xfu (\<lambda>_. v s) s);; (Basic (rtu (\<lambda>_. Return));; THROW))"
definition
creturn_void :: "((c_exntype \<Rightarrow> c_exntype) \<Rightarrow> ('c, 'd) state_scheme
\<Rightarrow> ('c, 'd) state_scheme) \<Rightarrow> (('c, 'd) state_scheme,'p,'f) com"
where
"creturn_void rtu \<equiv> (Basic (rtu (\<lambda>_. Return));; THROW)"
definition
cbreak :: "((c_exntype \<Rightarrow> c_exntype) \<Rightarrow> ('c, 'd) state_scheme
\<Rightarrow> ('c, 'd) state_scheme) \<Rightarrow> (('c, 'd) state_scheme,'p,'f) com"
where
"cbreak rtu \<equiv> (Basic (rtu (\<lambda>_. Break));; THROW)"
definition
ccatchbrk :: "( ('c, 'd) state_scheme \<Rightarrow> c_exntype) \<Rightarrow> (('c, 'd) state_scheme,'p,'f) com"
where
"ccatchbrk rt \<equiv> Cond {s. rt s = Break} SKIP THROW"
definition
cchaos :: "('b \<Rightarrow> 'a \<Rightarrow> 'a) \<Rightarrow> ('a,'c,'d) com"
where
"cchaos upd \<equiv> Spec { (s0,s) . \<exists>v. s = upd v s0 }"
definition
"guarded_spec_body F R = Guard F (fst ` R) (Spec R)"
lemma guarded_spec_body_wp [vcg_hoare]:
"P \<subseteq>
{s. (\<forall>t. (s,t) \<in> R \<longrightarrow> t \<in> Q) \<and> (Ft \<notin> F \<longrightarrow> (\<exists>t. (s,t) \<in> R))}
\<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub> P (guarded_spec_body Ft R) Q, A"
apply (simp add: guarded_spec_body_def)
apply (cases "Ft \<in> F")
apply (erule HoarePartialDef.Guarantee)
apply (rule HoarePartialDef.conseqPre, rule HoarePartialDef.Spec)
apply auto[1]
apply (rule HoarePartialDef.conseqPre, rule HoarePartialDef.Guard[where P=P])
apply (rule HoarePartialDef.conseqPre, rule HoarePartialDef.Spec)
apply auto[1]
apply simp
apply (erule order_trans)
apply (auto simp: image_def Bex_def)
done
ML_file "tools/mlyacc/mlyacclib/MLY_base-sig.ML"
ML_file "tools/mlyacc/mlyacclib/MLY_join.ML"
ML_file "tools/mlyacc/mlyacclib/MLY_lrtable.ML"
ML_file "tools/mlyacc/mlyacclib/MLY_stream.ML"
ML_file "tools/mlyacc/mlyacclib/MLY_parser2.ML"
ML_file "FunctionalRecordUpdate.ML"
ML_file "topo_sort.ML"
ML_file "isa_termstypes.ML"
ML_file "StrictC.grm.sig"
ML_file "StrictC.grm.sml"
ML_file "StrictC.lex.sml"
ML_file "StrictCParser.ML"
ML_file "complit.ML"
ML_file "hp_termstypes.ML"
ML_file "termstypes-sig.ML"
ML_file "termstypes.ML"
ML_file "UMM_termstypes.ML"
ML_file "recursive_records/recursive_record_pp.ML"
ML_file "recursive_records/recursive_record_package.ML"
ML_file "expression_typing.ML"
ML_file "UMM_Proofs.ML"
ML_file "program_analysis.ML"
ML_file "heapstatetype.ML"
ML_file "MemoryModelExtras-sig.ML"
ML_file "MemoryModelExtras.ML"
ML_file "calculate_state.ML"
ML_file "syntax_transforms.ML"
ML_file "expression_translation.ML"
ML_file "modifies_proofs.ML"
ML_file "HPInter.ML"
ML_file "stmt_translation.ML"
ML_file "isar_install.ML"
declare typ_info_word [simp del]
declare typ_info_ptr [simp del]
lemma valid_call_Spec_eq_subset:
"\<Gamma>' procname = Some (Spec R) \<Longrightarrow>
HoarePartialDef.valid \<Gamma>' NF P (Call procname) Q A = (P \<subseteq> fst ` R \<and> (R \<subseteq> (- P) \<times> UNIV \<union> UNIV \<times> Q))"
apply (safe, simp_all)
apply (clarsimp simp: HoarePartialDef.valid_def)
apply (rule ccontr)
apply (drule_tac x="Normal x" in spec, elim allE,
drule mp, erule exec.Call, rule exec.SpecStuck)
apply (auto simp: image_def)[2]
apply (clarsimp simp: HoarePartialDef.valid_def)
apply (elim allE, drule mp, erule exec.Call, erule exec.Spec)
apply auto[1]
apply (clarsimp simp: HoarePartialDef.valid_def)
apply (erule exec_Normal_elim_cases, simp_all)
apply (erule exec_Normal_elim_cases, auto)
done
lemma creturn_wp [vcg_hoare]:
assumes "P \<subseteq> {s. (exnupd (\<lambda>_. Return)) (rvupd (\<lambda>_. v s) s) \<in> A}"
shows "\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P creturn exnupd rvupd v Q, A"
unfolding creturn_def
by vcg
lemma creturn_void_wp [vcg_hoare]:
assumes "P \<subseteq> {s. (exnupd (\<lambda>_. Return)) s \<in> A}"
shows "\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P creturn_void exnupd Q, A"
unfolding creturn_void_def
by vcg
lemma cbreak_wp [vcg_hoare]:
assumes "P \<subseteq> {s. (exnupd (\<lambda>_. Break)) s \<in> A}"
shows "\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P cbreak exnupd Q, A"
unfolding cbreak_def
by vcg
lemma ccatchbrk_wp [vcg_hoare]:
assumes "P \<subseteq> {s. (exnupd s = Break \<longrightarrow> s \<in> Q) \<and>
(exnupd s \<noteq> Break \<longrightarrow> s \<in> A)}"
shows "\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P ccatchbrk exnupd Q, A"
unfolding ccatchbrk_def
by vcg
lemma cchaos_wp [vcg_hoare]:
assumes "P \<subseteq> {s. \<forall>x. (v x s) \<in> Q }"
shows "\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P cchaos v Q, A"
unfolding cchaos_def
apply (rule HoarePartial.Spec)
using assms
apply blast
done
lemma lvar_nondet_init_wp [vcg_hoare]:
"P \<subseteq> {s. \<forall>v. (upd (\<lambda>_. v)) s \<in> Q} \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub> P lvar_nondet_init accessor upd Q, A"
unfolding lvar_nondet_init_def
by (rule HoarePartialDef.conseqPre, vcg, auto)
lemma mem_safe_lvar_init [simp,intro]:
assumes upd: "\<And>g v s. globals_update g (upd (\<lambda>_. v) s) = upd (\<lambda>_. v) (globals_update g s)"
assumes acc: "\<And>v s. globals (upd (\<lambda>_. v) s) = globals s"
assumes upd_acc: "\<And>s. upd (\<lambda>_. accessor s) s = s"
shows "mem_safe (lvar_nondet_init accessor upd) x"
apply (clarsimp simp: mem_safe_def lvar_nondet_init_def)
apply (erule exec.cases, simp_all)
apply clarsimp
apply (clarsimp simp: restrict_safe_def restrict_safe_OK_def acc)
apply (rule exec.Spec)
apply clarsimp
apply (rule exI)
apply (simp add: restrict_htd_def upd acc)
apply (clarsimp simp: restrict_safe_def)
apply (simp add: exec_fatal_def)
apply (rule disjI2)
apply (rule exec.SpecStuck)
apply (clarsimp simp: restrict_htd_def upd acc)
apply (erule allE)+
apply (erule notE)
apply (rule sym)
apply (rule upd_acc)
done
lemma intra_safe_lvar_nondet_init [simp]:
"intra_safe (lvar_nondet_init accessor upd :: (('a::heap_state_type','d) state_scheme,'b,'c) com) =
(\<forall>\<Gamma>. mem_safe (lvar_nondet_init accessor upd :: (('a::heap_state_type','d) state_scheme,'b,'c) com) (\<Gamma> :: (('a,'d) state_scheme,'b,'c) body))"
by (simp add: lvar_nondet_init_def)
lemma proc_deps_lvar_nondet_init [simp]:
"proc_deps (lvar_nondet_init accessor upd) \<Gamma> = {}"
by (simp add: lvar_nondet_init_def)
end
|
\section{Presentations}
\cvitem{$\bullet$}{\textbf{Presentation Title:} Description here. Is it a poster, contributed talk, or an invited talk? Conference ZZZ, January 2018.}
\cvitem{$\bullet$}{\textbf{Undergraduate Presentation:} Description here. What is this presentation about? University of Somewhere, April 2016.} |
function [w,rho] = mh(A)
% Computes the Metropolis-Hastings heuristic edge weights
%
% [W,RHO] = MH(A) gives a vector of the Metropolis-Hastings edge weights
% for a graphb described by the incidence matrix A (NxM). N is the number
% of nodes, and M is the number of edges. Each column of A has exactly one
% +1 and one -1. RHO is computed from the weights W as follows:
% RHO = max(abs(eig( eye(n,n) - (1/n)*ones(n,n) - A*W*A' ))).
%
% The M.-H. weight on an edge is one over the maximum of the degrees of the
% adjacent nodes.
%
% For more details, see the references:
% "Fast linear iterations for distributed averaging" by L. Xiao and S. Boyd
% "Fastest mixing Markov chain on a graph" by S. Boyd, P. Diaconis, and L. Xiao
% "Convex Optimization of Graph Laplacian Eigenvalues" by S. Boyd
%
% Almir Mutapcic 08/29/06
% degrees of the nodes
n = size(A,1);
Lunw = A*A'; % unweighted Laplacian matrix
degs = diag(Lunw);
% Metropolis-Hastings weights
mh_degs = abs(A)'*diag(degs);
w = 1./max(mh_degs,[],2);
% compute the norm
if nargout > 1,
rho = norm( eye(n) - A*diag(w)*A' - (1/n)*ones(n) );
end
|
example (P Q : Prop) : Q → P ∨ Q :=
begin
intro q,
right,
exact q,
end |
\chapter{The Very High Level Layer \label{veryhigh}}
The functions in this chapter will let you execute Python source code
given in a file or a buffer, but they will not let you interact in a
more detailed way with the interpreter.
Several of these functions accept a start symbol from the grammar as a
parameter. The available start symbols are \constant{Py_eval_input},
\constant{Py_file_input}, and \constant{Py_single_input}. These are
described following the functions which accept them as parameters.
Note also that several of these functions take \ctype{FILE*}
parameters. On particular issue which needs to be handled carefully
is that the \ctype{FILE} structure for different C libraries can be
different and incompatible. Under Windows (at least), it is possible
for dynamically linked extensions to actually use different libraries,
so care should be taken that \ctype{FILE*} parameters are only passed
to these functions if it is certain that they were created by the same
library that the Python runtime is using.
\begin{cfuncdesc}{int}{Py_Main}{int argc, char **argv}
The main program for the standard interpreter. This is made
available for programs which embed Python. The \var{argc} and
\var{argv} parameters should be prepared exactly as those which are
passed to a C program's \cfunction{main()} function. It is
important to note that the argument list may be modified (but the
contents of the strings pointed to by the argument list are not).
The return value will be the integer passed to the
\function{sys.exit()} function, \code{1} if the interpreter exits
due to an exception, or \code{2} if the parameter list does not
represent a valid Python command line.
\end{cfuncdesc}
\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *fp, const char *filename}
This is a simplified interface to \cfunction{PyRun_AnyFileExFlags()}
below, leaving \var{closeit} set to \code{0} and \var{flags} set to \NULL.
\end{cfuncdesc}
\begin{cfuncdesc}{int}{PyRun_AnyFileFlags}{FILE *fp, const char *filename,
PyCompilerFlags *flags}
This is a simplified interface to \cfunction{PyRun_AnyFileExFlags()}
below, leaving the \var{closeit} argument set to \code{0}.
\end{cfuncdesc}
\begin{cfuncdesc}{int}{PyRun_AnyFileEx}{FILE *fp, const char *filename,
int closeit}
This is a simplified interface to \cfunction{PyRun_AnyFileExFlags()}
below, leaving the \var{flags} argument set to \NULL.
\end{cfuncdesc}
\begin{cfuncdesc}{int}{PyRun_AnyFileExFlags}{FILE *fp, const char *filename,
int closeit,
PyCompilerFlags *flags}
If \var{fp} refers to a file associated with an interactive device
(console or terminal input or \UNIX{} pseudo-terminal), return the
value of \cfunction{PyRun_InteractiveLoop()}, otherwise return the
result of \cfunction{PyRun_SimpleFile()}. If \var{filename} is
\NULL, this function uses \code{"???"} as the filename.
\end{cfuncdesc}
\begin{cfuncdesc}{int}{PyRun_SimpleString}{const char *command}
This is a simplified interface to \cfunction{PyRun_SimpleStringFlags()}
below, leaving the \var{PyCompilerFlags*} argument set to NULL.
\end{cfuncdesc}
\begin{cfuncdesc}{int}{PyRun_SimpleStringFlags}{const char *command,
PyCompilerFlags *flags}
Executes the Python source code from \var{command} in the
\module{__main__} module according to the \var{flags} argument.
If \module{__main__} does not already exist, it is created. Returns
\code{0} on success or \code{-1} if an exception was raised. If there
was an error, there is no way to get the exception information.
For the meaning of \var{flags}, see below.
\end{cfuncdesc}
\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *fp, const char *filename}
This is a simplified interface to \cfunction{PyRun_SimpleFileExFlags()}
below, leaving \var{closeit} set to \code{0} and \var{flags} set to
\NULL.
\end{cfuncdesc}
\begin{cfuncdesc}{int}{PyRun_SimpleFileFlags}{FILE *fp, const char *filename,
PyCompilerFlags *flags}
This is a simplified interface to \cfunction{PyRun_SimpleFileExFlags()}
below, leaving \var{closeit} set to \code{0}.
\end{cfuncdesc}
\begin{cfuncdesc}{int}{PyRun_SimpleFileEx}{FILE *fp, const char *filename,
int closeit}
This is a simplified interface to \cfunction{PyRun_SimpleFileExFlags()}
below, leaving \var{flags} set to \NULL.
\end{cfuncdesc}
\begin{cfuncdesc}{int}{PyRun_SimpleFileExFlags}{FILE *fp, const char *filename,
int closeit,
PyCompilerFlags *flags}
Similar to \cfunction{PyRun_SimpleStringFlags()}, but the Python source
code is read from \var{fp} instead of an in-memory string.
\var{filename} should be the name of the file. If \var{closeit} is
true, the file is closed before PyRun_SimpleFileExFlags returns.
\end{cfuncdesc}
\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *fp, const char *filename}
This is a simplified interface to \cfunction{PyRun_InteractiveOneFlags()}
below, leaving \var{flags} set to \NULL.
\end{cfuncdesc}
\begin{cfuncdesc}{int}{PyRun_InteractiveOneFlags}{FILE *fp,
const char *filename,
PyCompilerFlags *flags}
Read and execute a single statement from a file associated with an
interactive device according to the \var{flags} argument. If
\var{filename} is \NULL, \code{"???"} is used instead. The user will
be prompted using \code{sys.ps1} and \code{sys.ps2}. Returns \code{0}
when the input was executed successfully, \code{-1} if there was an
exception, or an error code from the \file{errcode.h} include file
distributed as part of Python if there was a parse error. (Note that
\file{errcode.h} is not included by \file{Python.h}, so must be included
specifically if needed.)
\end{cfuncdesc}
\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *fp, const char *filename}
This is a simplified interface to \cfunction{PyRun_InteractiveLoopFlags()}
below, leaving \var{flags} set to \NULL.
\end{cfuncdesc}
\begin{cfuncdesc}{int}{PyRun_InteractiveLoopFlags}{FILE *fp,
const char *filename,
PyCompilerFlags *flags}
Read and execute statements from a file associated with an
interactive device until \EOF{} is reached. If \var{filename} is
\NULL, \code{"???"} is used instead. The user will be prompted
using \code{sys.ps1} and \code{sys.ps2}. Returns \code{0} at \EOF.
\end{cfuncdesc}
\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseString}{const char *str,
int start}
This is a simplified interface to
\cfunction{PyParser_SimpleParseStringFlagsFilename()} below, leaving
\var{filename} set to \NULL{} and \var{flags} set to \code{0}.
\end{cfuncdesc}
\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseStringFlags}{
const char *str, int start, int flags}
This is a simplified interface to
\cfunction{PyParser_SimpleParseStringFlagsFilename()} below, leaving
\var{filename} set to \NULL.
\end{cfuncdesc}
\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseStringFlagsFilename}{
const char *str, const char *filename,
int start, int flags}
Parse Python source code from \var{str} using the start token
\var{start} according to the \var{flags} argument. The result can
be used to create a code object which can be evaluated efficiently.
This is useful if a code fragment must be evaluated many times.
\end{cfuncdesc}
\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseFile}{FILE *fp,
const char *filename, int start}
This is a simplified interface to \cfunction{PyParser_SimpleParseFileFlags()}
below, leaving \var{flags} set to \code{0}
\end{cfuncdesc}
\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseFileFlags}{FILE *fp,
const char *filename, int start, int flags}
Similar to \cfunction{PyParser_SimpleParseStringFlagsFilename()}, but
the Python source code is read from \var{fp} instead of an in-memory
string.
\end{cfuncdesc}
\begin{cfuncdesc}{PyObject*}{PyRun_String}{const char *str, int start,
PyObject *globals,
PyObject *locals}
This is a simplified interface to \cfunction{PyRun_StringFlags()} below,
leaving \var{flags} set to \NULL.
\end{cfuncdesc}
\begin{cfuncdesc}{PyObject*}{PyRun_StringFlags}{const char *str, int start,
PyObject *globals,
PyObject *locals,
PyCompilerFlags *flags}
Execute Python source code from \var{str} in the context specified
by the dictionaries \var{globals} and \var{locals} with the compiler
flags specified by \var{flags}. The parameter \var{start} specifies
the start token that should be used to parse the source code.
Returns the result of executing the code as a Python object, or
\NULL{} if an exception was raised.
\end{cfuncdesc}
\begin{cfuncdesc}{PyObject*}{PyRun_File}{FILE *fp, const char *filename,
int start, PyObject *globals,
PyObject *locals}
This is a simplified interface to \cfunction{PyRun_FileExFlags()} below,
leaving \var{closeit} set to \code{0} and \var{flags} set to \NULL.
\end{cfuncdesc}
\begin{cfuncdesc}{PyObject*}{PyRun_FileEx}{FILE *fp, const char *filename,
int start, PyObject *globals,
PyObject *locals, int closeit}
This is a simplified interface to \cfunction{PyRun_FileExFlags()} below,
leaving \var{flags} set to \NULL.
\end{cfuncdesc}
\begin{cfuncdesc}{PyObject*}{PyRun_FileFlags}{FILE *fp, const char *filename,
int start, PyObject *globals,
PyObject *locals,
PyCompilerFlags *flags}
This is a simplified interface to \cfunction{PyRun_FileExFlags()} below,
leaving \var{closeit} set to \code{0}.
\end{cfuncdesc}
\begin{cfuncdesc}{PyObject*}{PyRun_FileExFlags}{FILE *fp, const char *filename,
int start, PyObject *globals,
PyObject *locals, int closeit,
PyCompilerFlags *flags}
Similar to \cfunction{PyRun_StringFlags()}, but the Python source code is
read from \var{fp} instead of an in-memory string.
\var{filename} should be the name of the file.
If \var{closeit} is true, the file is closed before
\cfunction{PyRun_FileExFlags()} returns.
\end{cfuncdesc}
\begin{cfuncdesc}{PyObject*}{Py_CompileString}{const char *str,
const char *filename,
int start}
This is a simplified interface to \cfunction{Py_CompileStringFlags()} below,
leaving \var{flags} set to \NULL.
\end{cfuncdesc}
\begin{cfuncdesc}{PyObject*}{Py_CompileStringFlags}{const char *str,
const char *filename,
int start,
PyCompilerFlags *flags}
Parse and compile the Python source code in \var{str}, returning the
resulting code object. The start token is given by \var{start};
this can be used to constrain the code which can be compiled and should
be \constant{Py_eval_input}, \constant{Py_file_input}, or
\constant{Py_single_input}. The filename specified by
\var{filename} is used to construct the code object and may appear
in tracebacks or \exception{SyntaxError} exception messages. This
returns \NULL{} if the code cannot be parsed or compiled.
\end{cfuncdesc}
\begin{cvardesc}{int}{Py_eval_input}
The start symbol from the Python grammar for isolated expressions;
for use with
\cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
\end{cvardesc}
\begin{cvardesc}{int}{Py_file_input}
The start symbol from the Python grammar for sequences of statements
as read from a file or other source; for use with
\cfunction{Py_CompileString()}\ttindex{Py_CompileString()}. This is
the symbol to use when compiling arbitrarily long Python source code.
\end{cvardesc}
\begin{cvardesc}{int}{Py_single_input}
The start symbol from the Python grammar for a single statement; for
use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
This is the symbol used for the interactive interpreter loop.
\end{cvardesc}
\begin{ctypedesc}[PyCompilerFlags]{struct PyCompilerFlags}
This is the structure used to hold compiler flags. In cases where
code is only being compiled, it is passed as \code{int flags}, and in
cases where code is being executed, it is passed as
\code{PyCompilerFlags *flags}. In this case, \code{from __future__
import} can modify \var{flags}.
Whenever \code{PyCompilerFlags *flags} is \NULL, \member{cf_flags}
is treated as equal to \code{0}, and any modification due to
\code{from __future__ import} is discarded.
\begin{verbatim}
struct PyCompilerFlags {
int cf_flags;
}
\end{verbatim}
\end{ctypedesc}
\begin{cvardesc}{int}{CO_FUTURE_DIVISION}
This bit can be set in \var{flags} to cause division operator \code{/}
to be interpreted as ``true division'' according to \pep{238}.
\end{cvardesc}
|
proposition Bolzano_Weierstrass_imp_seq_compact: fixes s :: "'a::{t1_space, first_countable_topology} set" shows "\<forall>t. infinite t \<and> t \<subseteq> s \<longrightarrow> (\<exists>x \<in> s. x islimpt t) \<Longrightarrow> seq_compact s" |
(*
* Copyright 2014, General Dynamics C4 Systems
*
* SPDX-License-Identifier: GPL-2.0-only
*)
(*
Top level architecture related proofs.
*)
theory Arch_R
imports Untyped_R Finalise_R
begin
unbundle l4v_word_context
context begin interpretation Arch . (*FIXME: arch_split*)
declare is_aligned_shiftl [intro!]
declare is_aligned_shiftr [intro!]
definition
"asid_ci_map i \<equiv>
case i of X64_A.MakePool frame slot parent base \<Rightarrow>
X64_H.MakePool frame (cte_map slot) (cte_map parent) base"
definition
"valid_aci' aci \<equiv> case aci of MakePool frame slot parent base \<Rightarrow>
\<lambda>s. cte_wp_at' (\<lambda>c. cteCap c = NullCap) slot s \<and>
cte_wp_at' (\<lambda>cte. \<exists>idx. cteCap cte = UntypedCap False frame pageBits idx) parent s \<and>
descendants_of' parent (ctes_of s) = {} \<and>
slot \<noteq> parent \<and>
ex_cte_cap_to' slot s \<and>
sch_act_simple s \<and>
is_aligned base asid_low_bits \<and> asid_wf base"
lemma vp_strgs':
"valid_pspace' s \<longrightarrow> pspace_distinct' s"
"valid_pspace' s \<longrightarrow> pspace_aligned' s"
"valid_pspace' s \<longrightarrow> valid_mdb' s"
by auto
lemma safe_parent_strg':
"cte_wp_at' (\<lambda>cte. cteCap cte = UntypedCap False frame pageBits idx) p s \<and>
descendants_of' p (ctes_of s) = {} \<and>
valid_pspace' s
\<longrightarrow> safe_parent_for' (ctes_of s) p (ArchObjectCap (ASIDPoolCap frame base))"
apply (clarsimp simp: safe_parent_for'_def cte_wp_at_ctes_of)
apply (case_tac cte)
apply (simp add: isCap_simps)
apply (subst conj_comms)
apply (rule context_conjI)
apply (drule ctes_of_valid_cap', fastforce)
apply (clarsimp simp: valid_cap'_def capAligned_def)
apply (drule is_aligned_no_overflow)
apply (clarsimp simp: capRange_def asid_low_bits_def bit_simps)
apply (clarsimp simp: sameRegionAs_def2 isCap_simps capRange_def asid_low_bits_def bit_simps)
done
lemma descendants_of'_helper:
"\<lbrace>P\<rbrace> f \<lbrace>\<lambda>r s. Q (descendants_of' t (null_filter' (ctes_of s)))\<rbrace>
\<Longrightarrow> \<lbrace>P\<rbrace> f \<lbrace>\<lambda>r s. Q (descendants_of' t (ctes_of s))\<rbrace>"
apply (clarsimp simp:valid_def)
apply (subst null_filter_descendants_of')
prefer 2
apply fastforce
apply simp
done
lemma createObject_typ_at':
"\<lbrace>\<lambda>s. koTypeOf ty = otype \<and> is_aligned ptr (objBitsKO ty) \<and>
pspace_aligned' s \<and> pspace_no_overlap' ptr (objBitsKO ty) s\<rbrace>
createObjects' ptr (Suc 0) ty 0
\<lbrace>\<lambda>rv s. typ_at' otype ptr s\<rbrace>"
supply
is_aligned_neg_mask_eq[simp del]
is_aligned_neg_mask_weaken[simp del]
apply (clarsimp simp:createObjects'_def alignError_def split_def | wp unless_wp | wpc )+
apply (clarsimp simp:obj_at'_def ko_wp_at'_def typ_at'_def pspace_distinct'_def)+
apply (subgoal_tac "ps_clear ptr (objBitsKO ty)
(s\<lparr>ksPSpace := \<lambda>a. if a = ptr then Some ty else ksPSpace s a\<rparr>)")
apply (simp add:ps_clear_def)+
apply (rule ccontr)
apply (drule int_not_emptyD)
apply clarsimp
apply (unfold pspace_no_overlap'_def)
apply (erule allE)+
apply (erule(1) impE)
apply (subgoal_tac "x \<in> {x..x + 2 ^ objBitsKO y - 1}")
apply (fastforce simp:is_aligned_neg_mask_eq p_assoc_help)
apply (drule(1) pspace_alignedD')
apply (clarsimp simp: is_aligned_no_wrap' p_assoc_help)
done
lemma retype_region2_ext_retype_region_ArchObject:
"retype_region ptr n us (ArchObject x)=
retype_region2 ptr n us (ArchObject x)"
apply (rule ext)
apply (simp add:retype_region_def retype_region2_def bind_assoc
retype_region2_ext_def retype_region_ext_def default_ext_def)
apply (rule ext)
apply (intro monad_eq_split_tail ext)+
apply simp
apply simp
apply (simp add:gets_def get_def bind_def return_def simpler_modify_def )
apply (rule_tac x = xc in fun_cong)
apply (rule_tac f = do_extended_op in arg_cong)
apply (rule ext)
apply simp
apply simp
done
lemma set_cap_device_and_range_aligned:
"is_aligned ptr sz \<Longrightarrow> \<lbrace>\<lambda>_. True\<rbrace>
set_cap
(cap.UntypedCap dev ptr sz idx)
aref
\<lbrace>\<lambda>rv s.
\<exists>slot.
cte_wp_at
(\<lambda>c. cap_is_device c = dev \<and>
up_aligned_area ptr sz \<subseteq> cap_range c)
slot s\<rbrace>"
apply (subst is_aligned_neg_mask_eq[symmetric])
apply simp
apply (wp set_cap_device_and_range)
done
lemma performASIDControlInvocation_corres:
"asid_ci_map i = i' \<Longrightarrow>
corres dc
(einvs and ct_active and valid_aci i)
(invs' and ct_active' and valid_aci' i')
(perform_asid_control_invocation i)
(performASIDControlInvocation i')"
supply
is_aligned_neg_mask_eq[simp del]
is_aligned_neg_mask_weaken[simp del]
apply (cases i)
apply (rename_tac word1 prod1 prod2 word2)
apply (clarsimp simp: asid_ci_map_def)
apply (simp add: perform_asid_control_invocation_def placeNewObject_def2
performASIDControlInvocation_def)
apply (rule corres_name_pre)
apply (clarsimp simp:valid_aci_def valid_aci'_def cte_wp_at_ctes_of cte_wp_at_caps_of_state)
apply (subgoal_tac "valid_cap' (capability.UntypedCap False word1 pageBits idx) s'")
prefer 2
apply (case_tac ctea)
apply clarsimp
apply (erule ctes_of_valid_cap')
apply fastforce
apply (frule valid_capAligned)
apply (clarsimp simp: capAligned_def page_bits_def)
apply (rule corres_guard_imp)
apply (rule corres_split)
apply (erule deleteObjects_corres)
apply (simp add:pageBits_def)
apply (rule corres_split[OF getSlotCap_corres])
apply simp
apply (rule_tac F = " pcap = (cap.UntypedCap False word1 pageBits idxa)"
in corres_gen_asm)
apply (rule corres_split[OF updateFreeIndex_corres])
apply (clarsimp simp:is_cap_simps)
apply (simp add: free_index_of_def)
apply (rule corres_split)
apply (simp add: retype_region2_ext_retype_region_ArchObject )
apply (rule corres_retype [where ty="Inl (KOArch (KOASIDPool F))" for F,
unfolded APIType_map2_def makeObjectKO_def,
THEN createObjects_corres',simplified,
where val = "makeObject::asidpool"])
apply simp
apply (simp add: objBits_simps obj_bits_api_def arch_kobj_size_def
default_arch_object_def archObjSize_def)+
apply (simp add: obj_relation_retype_def default_object_def
default_arch_object_def objBits_simps archObjSize_def)
apply (simp add: other_obj_relation_def asid_pool_relation_def)
apply (simp add: makeObject_asidpool const_def inv_def)
apply (rule range_cover_full)
apply (simp add:obj_bits_api_def arch_kobj_size_def default_arch_object_def)+
apply (rule corres_split)
apply (rule cteInsert_simple_corres, simp, rule refl, rule refl)
apply (rule_tac F="asid_low_bits_of word2 = 0" in corres_gen_asm)
apply (simp add: is_aligned_mask dc_def[symmetric])
apply (rule corres_split[where P=\<top> and P'=\<top> and r'="\<lambda>t t'. t = t' o ucast"])
apply (clarsimp simp: state_relation_def arch_state_relation_def)
apply (rule corres_trivial)
apply (rule corres_modify)
apply (thin_tac "x \<in> state_relation" for x)
apply (clarsimp simp: state_relation_def arch_state_relation_def o_def)
apply (rule ext)
apply clarsimp
apply (erule_tac P = "x = asid_high_bits_of word2" in notE)
apply (rule word_eqI[rule_format])
apply (drule_tac x1="ucast x" in bang_eq [THEN iffD1])
apply (erule_tac x=n in allE)
apply (simp add: word_size nth_ucast)
apply wp+
apply (strengthen safe_parent_strg[where idx = "2^pageBits"])
apply (strengthen invs_valid_objs invs_distinct
invs_psp_aligned invs_mdb
| simp cong:conj_cong)+
apply (wp retype_region_plain_invs[where sz = pageBits]
retype_cte_wp_at[where sz = pageBits])+
apply (strengthen vp_strgs'
safe_parent_strg'[where idx = "2^pageBits"])
apply (simp cong: conj_cong)
apply (wp createObjects_valid_pspace'
[where sz = pageBits and ty="Inl (KOArch (KOASIDPool undefined))"])
apply (simp add: makeObjectKO_def)+
apply (simp add:objBits_simps archObjSize_def range_cover_full valid_cap'_def)+
apply (fastforce elim!: canonical_address_neq_mask)
apply (rule in_kernel_mappings_neq_mask, (simp add: valid_cap'_def bit_simps)+)[1]
apply (clarsimp simp:valid_cap'_def)
apply (wp createObject_typ_at'
createObjects_orig_cte_wp_at'[where sz = pageBits])
apply (rule descendants_of'_helper)
apply (wp createObjects_null_filter'
[where sz = pageBits and ty="Inl (KOArch (KOASIDPool undefined))"])
apply (clarsimp simp: conj_comms obj_bits_api_def arch_kobj_size_def
objBits_simps archObjSize_def default_arch_object_def
pred_conj_def)
apply (clarsimp simp: conj_comms
| strengthen invs_mdb invs_valid_pspace)+
apply (simp add:region_in_kernel_window_def)
apply (wp set_untyped_cap_invs_simple[where sz = pageBits]
set_cap_cte_wp_at
set_cap_caps_no_overlap[where sz = pageBits]
set_cap_no_overlap
set_cap_device_and_range_aligned[where dev = False,simplified]
set_untyped_cap_caps_overlap_reserved[where sz = pageBits])+
apply (clarsimp simp: conj_comms obj_bits_api_def arch_kobj_size_def
objBits_simps archObjSize_def default_arch_object_def
makeObjectKO_def range_cover_full
simp del: capFreeIndex_update.simps
| strengthen invs_valid_pspace' invs_pspace_aligned'
invs_pspace_distinct'
exI[where x="makeObject :: asidpool"])+
apply (wp updateFreeIndex_forward_invs'
updateFreeIndex_pspace_no_overlap'
updateFreeIndex_caps_no_overlap''
updateFreeIndex_descendants_of2
updateFreeIndex_cte_wp_at
updateFreeIndex_caps_overlap_reserved
| simp add: descendants_of_null_filter' split del: if_split)+
apply (wp get_cap_wp)+
apply (subgoal_tac "word1 && ~~ mask pageBits = word1 \<and> pageBits \<le> word_bits \<and> word_size_bits \<le> pageBits")
prefer 2
apply (clarsimp simp:bit_simps word_bits_def is_aligned_neg_mask_eq)
apply (simp only:delete_objects_rewrite)
apply wp+
apply (clarsimp simp: conj_comms)
apply (clarsimp simp: conj_comms ex_disj_distrib
| strengthen invs_valid_pspace' invs_pspace_aligned'
invs_pspace_distinct')+
apply (wp deleteObjects_invs'[where p="makePoolParent i'"]
deleteObjects_cte_wp_at'
deleteObjects_descendants[where p="makePoolParent i'"])
apply (clarsimp split del: if_split simp:valid_cap'_def)
apply (wp hoare_vcg_ex_lift
deleteObjects_caps_no_overlap''[where slot="makePoolParent i'"]
deleteObject_no_overlap
deleteObjects_ct_active'[where cref="makePoolParent i'"])
apply (clarsimp simp: is_simple_cap_def valid_cap'_def max_free_index_def is_cap_simps
cong: conj_cong)
apply (strengthen empty_descendants_range_in')
apply (wp deleteObjects_descendants[where p="makePoolParent i'"]
deleteObjects_cte_wp_at'
deleteObjects_null_filter[where p="makePoolParent i'"])
apply (clarsimp simp:invs_mdb max_free_index_def invs_untyped_children)
apply (subgoal_tac "detype_locale x y sa" for x y)
prefer 2
apply (simp add:detype_locale_def)
apply (fastforce simp:cte_wp_at_caps_of_state descendants_range_def2
empty_descendants_range_in invs_untyped_children)
apply (intro conjI)
apply (clarsimp)
apply (erule(1) caps_of_state_valid)
subgoal by (fastforce simp:cte_wp_at_caps_of_state
descendants_range_def2 empty_descendants_range_in)
apply (fold_subgoals (prefix))[2]
subgoal premises prems using prems by (clarsimp simp:invs_def valid_state_def)+
apply (clarsimp simp:cte_wp_at_caps_of_state)
apply (drule detype_locale.non_null_present)
apply (fastforce simp:cte_wp_at_caps_of_state)
apply simp
apply (frule_tac ptr = "(aa,ba)" in detype_invariants [rotated 3])
apply fastforce
apply simp
apply (simp add: cte_wp_at_caps_of_state)
apply (simp add: is_cap_simps)
apply (simp add:empty_descendants_range_in descendants_range_def2)
apply (frule intvl_range_conv[where bits = pageBits])
apply (clarsimp simp:pageBits_def word_bits_def)
apply (clarsimp simp: invs_valid_objs cte_wp_at_caps_of_state range_cover_full
invs_psp_aligned invs_distinct cap_master_cap_simps is_cap_simps
is_simple_cap_def)
apply (clarsimp simp: conj_comms)
apply (rule conjI, clarsimp simp: is_aligned_asid_low_bits_of_zero)
apply (frule ex_cte_cap_protects)
apply (simp add:cte_wp_at_caps_of_state)
apply (simp add:empty_descendants_range_in)
apply fastforce
apply (rule subset_refl)
apply fastforce
apply clarsimp
apply (rule conjI, clarsimp)
apply (rule conjI, clarsimp simp: clear_um_def)
apply (simp add:detype_clear_um_independent)
apply (rule conjI,erule caps_no_overlap_detype[OF descendants_range_caps_no_overlapI])
apply (clarsimp simp:is_aligned_neg_mask_eq cte_wp_at_caps_of_state)
apply (simp add:empty_descendants_range_in)+
apply (rule conjI)
apply clarsimp
apply (drule_tac p = "(aa,ba)" in cap_refs_in_kernel_windowD2[OF caps_of_state_cteD])
apply fastforce
apply (clarsimp simp: region_in_kernel_window_def valid_cap_def
cap_aligned_def is_aligned_neg_mask_eq detype_def clear_um_def)
apply (rule conjI, rule pspace_no_overlap_subset,
rule pspace_no_overlap_detype[OF caps_of_state_valid])
apply (simp add:invs_psp_aligned invs_valid_objs is_aligned_neg_mask_eq)+
apply (clarsimp simp: detype_def clear_um_def detype_ext_def valid_sched_def valid_etcbs_def
st_tcb_at_kh_def obj_at_kh_def st_tcb_at_def obj_at_def is_etcb_at_def)
apply (simp add: detype_def clear_um_def)
apply (drule_tac x = "cte_map (aa,ba)" in pspace_relation_cte_wp_atI[OF state_relation_pspace_relation])
apply (simp add:invs_valid_objs)+
apply clarsimp
apply (drule cte_map_inj_eq)
apply ((fastforce simp:cte_wp_at_caps_of_state)+)[5]
apply (clarsimp simp:cte_wp_at_caps_of_state invs_valid_pspace' conj_comms cte_wp_at_ctes_of
valid_cap_simps')
apply (strengthen refl)
apply clarsimp
apply (frule empty_descendants_range_in')
apply (intro conjI,
simp_all add: is_simple_cap'_def isCap_simps descendants_range'_def2
null_filter_descendants_of'[OF null_filter_simp']
capAligned_def asid_low_bits_def)
apply (erule descendants_range_caps_no_overlapI')
apply (fastforce simp:cte_wp_at_ctes_of is_aligned_neg_mask_eq)
apply (simp add:empty_descendants_range_in')
apply (simp add:word_bits_def bit_simps)
apply (rule is_aligned_weaken)
apply (rule is_aligned_shiftl_self[unfolded shiftl_t2n,where p = 1,simplified])
apply (simp add:pageBits_def)
apply clarsimp
apply (drule(1) cte_cap_in_untyped_range)
apply (fastforce simp:cte_wp_at_ctes_of)
apply assumption+
apply fastforce
apply simp
apply clarsimp
apply (drule (1) cte_cap_in_untyped_range)
apply (fastforce simp add: cte_wp_at_ctes_of)
apply assumption+
apply (clarsimp simp: invs'_def valid_state'_def if_unsafe_then_cap'_def cte_wp_at_ctes_of)
apply fastforce
apply simp
done
(* FIXME x64: move *)
definition
ioport_data_relation :: "io_port_invocation_data \<Rightarrow> ioport_invocation_data \<Rightarrow> bool"
where
"ioport_data_relation d d' \<equiv> case d of
X64_A.IOPortIn8 \<Rightarrow> d' = IOPortIn8
| X64_A.IOPortIn16 \<Rightarrow> d' = IOPortIn16
| X64_A.IOPortIn32 \<Rightarrow> d' = IOPortIn32
| X64_A.IOPortOut8 w \<Rightarrow> d' = IOPortOut8 w
| X64_A.IOPortOut16 w \<Rightarrow> d' = IOPortOut16 w
| X64_A.IOPortOut32 w \<Rightarrow> d' = IOPortOut32 w"
definition
ioport_invocation_map :: "io_port_invocation \<Rightarrow> ioport_invocation \<Rightarrow> bool"
where
"ioport_invocation_map i i' \<equiv> case i of
X64_A.IOPortInvocation iop dat \<Rightarrow> \<exists>dat'. i' = IOPortInvocation iop dat' \<and> ioport_data_relation dat dat'"
definition
ioport_control_inv_relation :: "io_port_control_invocation \<Rightarrow> ioport_control_invocation \<Rightarrow> bool"
where
"ioport_control_inv_relation i i' \<equiv> case i of
IOPortControlInvocation f l slot slot' \<Rightarrow>
(i' = IOPortControlIssue f l (cte_map slot) (cte_map slot'))"
definition
ioport_control_inv_valid' :: "ioport_control_invocation \<Rightarrow> kernel_state \<Rightarrow> bool"
where
"ioport_control_inv_valid' i \<equiv> case i of
IOPortControlIssue f l ptr ptr' \<Rightarrow> (cte_wp_at' (\<lambda>cte. cteCap cte = NullCap) ptr and
cte_wp_at' (\<lambda>cte. cteCap cte = ArchObjectCap IOPortControlCap) ptr' and
ex_cte_cap_to' ptr and real_cte_at' ptr and
(\<lambda>s. {f..l} \<inter> issued_ioports' (ksArchState s) = {}) and K (f \<le> l))"
definition
archinv_relation :: "arch_invocation \<Rightarrow> Arch.invocation \<Rightarrow> bool"
where
"archinv_relation ai ai' \<equiv> case ai of
arch_invocation.InvokePageTable pti \<Rightarrow>
\<exists>pti'. ai' = InvokePageTable pti' \<and> page_table_invocation_map pti pti'
| arch_invocation.InvokePageDirectory pdi \<Rightarrow>
\<exists>pdi'. ai' = InvokePageDirectory pdi' \<and> page_directory_invocation_map pdi pdi'
| arch_invocation.InvokePDPT pdpti \<Rightarrow>
\<exists>pdpti'. ai' = InvokePDPT pdpti' \<and> pdpt_invocation_map pdpti pdpti'
| arch_invocation.InvokePage pgi \<Rightarrow>
\<exists>pgi'. ai' = InvokePage pgi' \<and> page_invocation_map pgi pgi'
| arch_invocation.InvokeASIDControl aci \<Rightarrow>
\<exists>aci'. ai' = InvokeASIDControl aci' \<and> aci' = asid_ci_map aci
| arch_invocation.InvokeASIDPool ap \<Rightarrow>
\<exists>ap'. ai' = InvokeASIDPool ap' \<and> ap' = asid_pool_invocation_map ap
| arch_invocation.InvokeIOPort iopi \<Rightarrow>
\<exists>iopi'. ai' = InvokeIOPort iopi' \<and> ioport_invocation_map iopi iopi'
| arch_invocation.InvokeIOPortControl iopci \<Rightarrow>
\<exists>iopci'. ai' = InvokeIOPortControl iopci' \<and> ioport_control_inv_relation iopci iopci'"
definition
valid_arch_inv' :: "Arch.invocation \<Rightarrow> kernel_state \<Rightarrow> bool"
where
"valid_arch_inv' ai \<equiv> case ai of
InvokePageTable pti \<Rightarrow> valid_pti' pti
| InvokePageDirectory pdi \<Rightarrow> valid_pdi' pdi
| InvokePDPT pdpti \<Rightarrow> valid_pdpti' pdpti
| InvokePage pgi \<Rightarrow> valid_page_inv' pgi
| InvokeASIDControl aci \<Rightarrow> valid_aci' aci
| InvokeASIDPool ap \<Rightarrow> valid_apinv' ap
| InvokeIOPort i \<Rightarrow> \<top>
| InvokeIOPortControl ic \<Rightarrow> ioport_control_inv_valid' ic"
lemma mask_vmrights_corres:
"maskVMRights (vmrights_map R) (rightsFromWord d) =
vmrights_map (mask_vm_rights R (data_to_rights d))"
by (clarsimp simp: rightsFromWord_def data_to_rights_def
vmrights_map_def Let_def maskVMRights_def
mask_vm_rights_def nth_ucast
validate_vm_rights_def vm_read_write_def
vm_kernel_only_def vm_read_only_def
split: bool.splits)
lemma vm_attributes_corres:
"vmattributes_map (attribs_from_word w) = attribsFromWord w"
by (clarsimp simp: attribsFromWord_def attribs_from_word_def
Let_def vmattributes_map_def)
lemma checkVPAlignment_corres:
"corres (ser \<oplus> dc) \<top> \<top>
(check_vp_alignment sz w)
(checkVPAlignment sz w)"
apply (simp add: check_vp_alignment_def checkVPAlignment_def)
apply (cases sz, simp_all add: corres_returnOk unlessE_whenE is_aligned_mask)
apply ((rule corres_guard_imp, rule corres_whenE, rule refl, auto)[1])+
done
lemma checkVP_wpR [wp]:
"\<lbrace>\<lambda>s. vmsz_aligned w sz \<longrightarrow> P () s\<rbrace>
checkVPAlignment sz w \<lbrace>P\<rbrace>, -"
apply (simp add: checkVPAlignment_def)
by (wpsimp wp: whenE_wp simp: is_aligned_mask vmsz_aligned_def)
lemma asidHighBits [simp]:
"asidHighBits = asid_high_bits"
by (simp add: asidHighBits_def asid_high_bits_def)
declare word_unat_power [symmetric, simp del]
crunch inv [wp]: "X64_H.decodeInvocation" "P"
(wp: crunch_wps mapME_x_inv_wp getASID_wp
simp: forME_x_def crunch_simps)
lemma case_option_corresE:
assumes nonec: "corres r Pn Qn (nc >>=E f) (nc' >>=E g)"
and somec: "\<And>v'. corres r (Ps v') (Qs v') (sc v' >>=E f) (sc' v' >>=E g)"
shows "corres r (case_option Pn Ps v) (case_option Qn Qs v) (case_option nc sc v >>=E f) (case_option nc' sc' v >>=E g)"
apply (cases v)
apply simp
apply (rule nonec)
apply simp
apply (rule somec)
done
lemma cap_relation_Untyped_eq:
"cap_relation c (UntypedCap d p sz f) = (c = cap.UntypedCap d p sz f)"
by (cases c) auto
declare check_vp_alignment_inv[wp del]
lemma select_ext_fa:
"free_asid_select asid_tbl \<in> S
\<Longrightarrow> ((select_ext (\<lambda>_. free_asid_select asid_tbl) S) :: (3 word) det_ext_monad)
= return (free_asid_select asid_tbl)"
by (simp add: select_ext_def get_def gets_def bind_def assert_def return_def fail_def)
lemma select_ext_fap:
"free_asid_pool_select p b \<in> S
\<Longrightarrow> ((select_ext (\<lambda>_. free_asid_pool_select p b) S) :: (9 word) det_ext_monad)
= return (free_asid_pool_select p b)"
by (simp add: select_ext_def get_def gets_def bind_def assert_def return_def)
lemma vs_refs_pages_ptI:
"pt x = pte \<Longrightarrow> pte_ref_pages pte = Some r'
\<Longrightarrow> (VSRef (ucast x) (Some APageTable), r') \<in> vs_refs_pages (ArchObj (PageTable pt))"
apply (simp add: vs_refs_pages_def)
apply (rule image_eqI[rotated], rule graph_ofI[where x=x], simp)
apply simp
done
lemmas vs_refs_pages_pt_smallI
= vs_refs_pages_ptI[where pte="X64_A.pte.SmallPagePTE x y z" for x y z,
unfolded pte_ref_pages_def, simplified, OF _ refl]
lemma vs_refs_pages_pdI:
"pd x = pde \<Longrightarrow> pde_ref_pages pde = Some r'
\<Longrightarrow> (VSRef (ucast x) (Some APageDirectory), r') \<in> vs_refs_pages (ArchObj (PageDirectory pd))"
apply (simp add: vs_refs_pages_def)
apply (rule image_eqI[rotated], rule graph_ofI[where x=x], simp)
apply simp
done
lemmas vs_refs_pages_pd_largeI
= vs_refs_pages_pdI[where pde="X64_A.pde.LargePagePDE x y z " for x y z ,
unfolded pde_ref_pages_def, simplified, OF _ refl]
lemma vs_refs_pages_pdptI:
"pdpt x = pdpte \<Longrightarrow> pdpte_ref_pages pdpte = Some r'
\<Longrightarrow> (VSRef (ucast x) (Some APDPointerTable), r') \<in> vs_refs_pages (ArchObj (PDPointerTable pdpt))"
apply (simp add: vs_refs_pages_def)
apply (rule image_eqI[rotated], rule graph_ofI[where x=x], simp)
apply simp
done
lemmas vs_refs_pages_pdpt_hugeI
= vs_refs_pages_pdptI[where pdpte="X64_A.pdpte.HugePagePDPTE x y z " for x y z ,
unfolded pdpte_ref_pages_def, simplified, OF _ refl]
lemma userVTop_conv[simp]: "userVTop = user_vtop"
by (simp add: userVTop_def user_vtop_def X64.pptrUserTop_def)
lemma find_vspace_for_asid_lookup_slot [wp]:
"\<lbrace>pspace_aligned and valid_vspace_objs\<rbrace>
find_vspace_for_asid asid
\<lbrace>\<lambda>rv. \<exists>\<rhd> (lookup_pml4_slot rv vptr && ~~ mask pml4_bits)\<rbrace>, -"
apply (rule hoare_pre)
apply (rule hoare_post_imp_R)
apply (rule hoare_vcg_R_conj)
apply (rule hoare_vcg_R_conj)
apply (rule find_vspace_for_asid_inv [where P="\<top>", THEN valid_validE_R])
apply (rule find_vspace_for_asid_lookup)
apply (rule find_vspace_for_asid_aligned_pm)
apply clarsimp
apply (subst lookup_pml4_slot_eq)
apply (auto simp: bit_simps)
done
lemmas vmsz_aligned_imp_aligned
= vmsz_aligned_def[THEN meta_eq_to_obj_eq, THEN iffD1, THEN is_aligned_weaken]
lemma corres_splitEE':
assumes "corres_underlying sr nf nf' (f \<oplus> r') P P' a c"
assumes "\<And>rv rv'. r' rv rv'
\<Longrightarrow> corres_underlying sr nf nf' (f \<oplus> r) (R rv) (R' rv') (b rv) (d rv')"
assumes "\<lbrace>Q\<rbrace> a \<lbrace>R\<rbrace>,\<lbrace>\<top>\<top>\<rbrace>" "\<lbrace>Q'\<rbrace> c \<lbrace>R'\<rbrace>,\<lbrace>\<top>\<top>\<rbrace>"
shows "corres_underlying sr nf nf' (f \<oplus> r) (P and Q) (P' and Q') (a >>=E (\<lambda>rv. b rv)) (c >>=E (\<lambda>rv'. d rv'))"
by (rule corres_splitEE; rule assms)
lemma decodeX64FrameInvocation_corres:
"\<lbrakk>cap = arch_cap.PageCap d p R mt sz opt; acap_relation cap cap';
list_all2 cap_relation (map fst excaps) (map fst excaps');
list_all2 (\<lambda>s s'. s' = cte_map s) (map snd excaps) (map snd excaps') \<rbrakk> \<Longrightarrow>
corres (ser \<oplus> archinv_relation)
(invs and valid_cap (cap.ArchObjectCap cap) and
cte_wp_at ((=) (cap.ArchObjectCap cap)) slot and
(\<lambda>s. \<forall>x\<in>set excaps. s \<turnstile> fst x \<and> cte_wp_at (\<lambda>_. True) (snd x) s))
(invs' and valid_cap' (capability.ArchObjectCap cap') and
(\<lambda>s. \<forall>x\<in>set excaps'. valid_cap' (fst x) s \<and> cte_wp_at' (\<lambda>_. True) (snd x) s))
(decode_page_invocation l args slot cap excaps)
(decodeX64FrameInvocation l args (cte_map slot) cap' excaps')"
apply (simp add: decode_page_invocation_def decodeX64FrameInvocation_def Let_def isCap_simps
split del: if_split)
apply (cases "invocation_type l = ArchInvocationLabel X64PageMap")
apply (case_tac "\<not>(2 < length args \<and> excaps \<noteq> [])", clarsimp split: list.splits)
apply (simp add: Let_def neq_Nil_conv)
apply (elim exE conjE)
apply (rename_tac pm_cap pm_cap_cnode pm_cap_slot excaps_rest)
apply (clarsimp split: list.split, intro conjI impI allI; clarsimp)
apply (rename_tac vaddr rights_mask attr pd_cap' excaps'_rest args_rest)
apply (rule corres_guard_imp)
apply (rule_tac P="\<nexists>pm asid. pm_cap = cap.ArchObjectCap (arch_cap.PML4Cap pm (Some asid))"
in corres_symmetric_bool_cases[where Q=\<top> and Q'=\<top>, OF refl])
apply (case_tac pm_cap; clarsimp; rename_tac pm_acap pm_acap'; case_tac pm_acap; clarsimp)
apply (rule corres_splitEE'[where r'="(=)" and P=\<top> and P'=\<top>])
apply (clarsimp simp: corres_returnOkTT)
apply (rule_tac F="pm_cap = cap.ArchObjectCap (arch_cap.PML4Cap (fst rv) (Some (snd rv)))"
in corres_gen_asm)
apply (clarsimp cong: option.case_cong)
apply (rename_tac vspace asid)
apply wpfix \<comment> \<open>get asid and vspace parameters in schematic preconditions\<close>
apply (rule_tac P=
"(opt = None \<and> (user_vtop < vaddr \<or> user_vtop < vaddr + 2 ^ pageBitsForSize sz))
\<or> (\<exists>asid' vaddr'. opt = Some (asid', vaddr')
\<and> (asid' \<noteq> asid \<or> mt \<noteq> VMVSpaceMap \<or> vaddr' \<noteq> vaddr))"
in corres_symmetric_bool_cases[where Q=\<top> and Q'=\<top>, OF refl]; clarsimp)
apply (case_tac opt; clarsimp)
apply (case_tac "asid' \<noteq> asid"; clarsimp)
apply (case_tac "mt \<noteq> VMVSpaceMap"; clarsimp)
apply (rule corres_splitEE'[where r'=dc])
apply (case_tac opt; clarsimp simp: whenE_def)
apply (rule corres_returnOkTT, simp)
apply (rule corres_returnOkTT, simp)
apply (rule corres_splitEE'[OF corres_lookup_error[OF findVSpaceForASID_corres]], simp)
apply (rule whenE_throwError_corres; simp)
apply (rule corres_splitEE'[where r'=dc, OF checkVPAlignment_corres])
apply (rule corres_splitEE'[OF createMappingEntries_corres]
; simp add: mask_vmrights_corres vm_attributes_corres)
apply (rule corres_splitEE'[OF ensureSafeMapping_corres], assumption)
apply (rule corres_returnOkTT)
\<comment> \<open>program split done, now prove resulting preconditions and Hoare triples\<close>
apply (simp add: archinv_relation_def page_invocation_map_def)
apply wpsimp+
apply (wp createMappingEntries_wf)
apply wpsimp+
apply (wp find_vspace_for_asid_wp)
apply (wp findVSpaceForASID_vs_at_wp)
apply wpsimp
apply wpsimp
apply wpsimp
apply wpsimp
apply (clarsimp simp: cte_wp_at_caps_of_state cong: conj_cong)
apply (rename_tac pm_ptr asid')
apply (prop_tac "is_aligned pm_ptr pml4_bits")
apply (clarsimp simp: valid_cap_simps cap_aligned_def pml4_bits_def)
apply (clarsimp simp: invs_implies)
apply (case_tac "asid' = asid"; clarsimp)
apply (prop_tac "0 < asid \<and> asid_wf asid \<and> asid \<noteq> 0", clarsimp simp: valid_cap_simps)
apply clarsimp
apply (prop_tac "vspace_at_asid asid pm_ptr s \<longrightarrow> (\<exists>ref. (ref \<rhd> pm_ptr) s)")
apply (fastforce simp: vspace_at_asid_def)
apply (case_tac opt; clarsimp simp: valid_cap_simps)
using aligned_sum_le_user_vtop le_user_vtop_canonical_address le_user_vtop_less_pptr_base word_not_le
apply blast
apply fastforce
\<comment> \<open>PageUnmap\<close>
apply (simp split del: if_split)
apply (cases "invocation_type l = ArchInvocationLabel X64PageUnmap")
apply simp
apply (rule corres_returnOk)
apply (clarsimp simp: archinv_relation_def page_invocation_map_def)
\<comment> \<open>PageGetAddress\<close>
apply (cases "invocation_type l = ArchInvocationLabel X64PageGetAddress")
apply simp
apply (rule corres_returnOk)
apply (clarsimp simp: archinv_relation_def page_invocation_map_def)
by (clarsimp split: invocation_label.splits arch_invocation_label.splits split del: if_split)
lemma VMReadWrite_vmrights_map[simp]: "vmrights_map vm_read_write = VMReadWrite"
by (simp add: vmrights_map_def vm_read_write_def)
lemma decodeX64PageTableInvocation_corres:
"\<lbrakk>cap = arch_cap.PageTableCap p opt; acap_relation cap cap';
list_all2 cap_relation (map fst excaps) (map fst excaps');
list_all2 (\<lambda>s s'. s' = cte_map s) (map snd excaps) (map snd excaps') \<rbrakk> \<Longrightarrow>
corres (ser \<oplus> archinv_relation)
(invs and valid_cap (cap.ArchObjectCap cap) and
cte_wp_at ((=) (cap.ArchObjectCap cap)) slot and
(\<lambda>s. \<forall>x\<in>set excaps. s \<turnstile> fst x \<and> cte_wp_at (\<lambda>_. True) (snd x) s))
(invs' and valid_cap' (capability.ArchObjectCap cap') and
(\<lambda>s. \<forall>x\<in>set excaps'. valid_cap' (fst x) s \<and> cte_wp_at' (\<lambda>_. True) (snd x) s))
(decode_page_table_invocation l args slot cap excaps)
(decodeX64PageTableInvocation l args (cte_map slot) cap' excaps')"
apply (simp add: decode_page_table_invocation_def decodeX64PageTableInvocation_def Let_def
isCap_simps
split del: if_split)
apply (cases "invocation_type l = ArchInvocationLabel X64PageTableMap")
apply (simp split: invocation_label.split arch_invocation_label.splits split del: if_split)
apply (simp split: list.split, intro conjI impI allI, simp_all)[1]
apply (clarsimp simp: neq_Nil_conv Let_def)
apply (rule whenE_throwError_corres_initial, simp+)
apply (simp split: cap.split arch_cap.split option.split,
intro conjI allI impI, simp_all)[1]
apply (rule whenE_throwError_corres_initial, simp+)
apply (rule corres_guard_imp)
apply (rule corres_splitEE)
apply (rule corres_lookup_error)
apply (rule findVSpaceForASID_corres[OF refl])
apply (rule whenE_throwError_corres, simp, simp)
apply (rule corres_splitEE)
apply (rule corres_lookup_error)
apply (rule lookupPDSlot_corres)
apply (rule corres_splitEE)
apply simp
apply (rule getObject_PDE_corres')
apply (simp add: unlessE_whenE)
apply (rule corres_splitEE)
apply (rule corres_whenE)
apply clarsimp
apply (case_tac old_pde; simp )[1]
apply (rule corres_trivial)
apply simp
apply simp
apply (rule corres_trivial)
apply (rule corres_returnOk)
apply (clarsimp simp: archinv_relation_def page_table_invocation_map_def)
apply (clarsimp simp: attribs_from_word_def filter_frame_attrs_def
attribsFromWord_def Let_def)
apply ((clarsimp cong: if_cong
| wp whenE_wp hoare_vcg_all_lift_R getPDE_wp get_pde_wp
| wp (once) hoare_drop_imps)+)[6]
apply (clarsimp intro!: validE_R_validE)
apply (rule_tac Q'="\<lambda>rv s. pspace_aligned s \<and> valid_vspace_objs s \<and> valid_arch_state s \<and>
equal_kernel_mappings s \<and> valid_global_objs s \<and>
(\<exists>ref. (ref \<rhd> rv) s) \<and> typ_at (AArch APageMapL4) rv s \<and>
is_aligned rv pml4_bits"
in hoare_post_imp_R[rotated])
apply fastforce
apply (wpsimp | wp (once) hoare_drop_imps)+
apply (fastforce simp: valid_cap_def mask_def)
apply (clarsimp simp: valid_cap'_def)
apply fastforce
\<comment> \<open>PageTableUnmap\<close>
apply (clarsimp simp: isCap_simps)+
apply (cases "invocation_type l = ArchInvocationLabel X64PageTableUnmap")
apply (clarsimp simp: unlessE_whenE liftE_bindE)
apply (rule stronger_corres_guard_imp)
apply (rule corres_symb_exec_r_conj)
apply (rule_tac F="isArchCap isPageTableCap (cteCap cteVal)"
in corres_gen_asm2)
apply (rule corres_split[OF isFinalCapability_corres[where ptr=slot]])
apply (drule mp)
apply (clarsimp simp: isCap_simps final_matters'_def)
apply (rule whenE_throwError_corres)
apply simp
apply simp
apply (rule corres_trivial, simp add: returnOk_def archinv_relation_def
page_table_invocation_map_def)
apply (wp getCTE_wp' | wp (once) hoare_drop_imps)+
apply (clarsimp)
apply (rule no_fail_pre, rule no_fail_getCTE)
apply (erule conjunct2)
apply (clarsimp simp: cte_wp_at_caps_of_state cap_rights_update_def acap_rights_update_def)
apply (clarsimp simp add: cap_rights_update_def acap_rights_update_def)
apply (clarsimp simp: cte_wp_at_ctes_of cap_rights_update_def acap_rights_update_def
cte_wp_at_caps_of_state)
apply (drule pspace_relation_ctes_ofI[OF _ caps_of_state_cteD, rotated],
erule invs_pspace_aligned', clarsimp+)
apply (simp add: isCap_simps)
apply (simp add: isCap_simps split del: if_split)
by (clarsimp split: invocation_label.splits arch_invocation_label.splits)
lemma decodeX64PageDirectoryInvocation_corres:
"\<lbrakk>cap = arch_cap.PageDirectoryCap p opt; acap_relation cap cap';
list_all2 cap_relation (map fst excaps) (map fst excaps');
list_all2 (\<lambda>s s'. s' = cte_map s) (map snd excaps) (map snd excaps') \<rbrakk> \<Longrightarrow>
corres (ser \<oplus> archinv_relation)
(invs and valid_cap (cap.ArchObjectCap cap) and
cte_wp_at ((=) (cap.ArchObjectCap cap)) slot and
(\<lambda>s. \<forall>x\<in>set excaps. s \<turnstile> fst x \<and> cte_wp_at (\<lambda>_. True) (snd x) s))
(invs' and valid_cap' (capability.ArchObjectCap cap') and
(\<lambda>s. \<forall>x\<in>set excaps'. valid_cap' (fst x) s \<and> cte_wp_at' (\<lambda>_. True) (snd x) s))
(decode_page_directory_invocation l args slot cap excaps)
(decodeX64PageDirectoryInvocation l args (cte_map slot) cap' excaps')"
apply (simp add: decode_page_directory_invocation_def decodeX64PageDirectoryInvocation_def Let_def
isCap_simps
split del: if_split)
apply (cases "invocation_type l = ArchInvocationLabel X64PageDirectoryMap")
apply (simp split: invocation_label.split arch_invocation_label.splits split del: if_split)
apply (simp split: list.split, intro conjI impI allI, simp_all)[1]
apply (clarsimp simp: neq_Nil_conv Let_def)
apply (rule whenE_throwError_corres_initial, simp+)
apply (simp split: cap.split arch_cap.split option.split,
intro conjI allI impI, simp_all)[1]
apply (rule whenE_throwError_corres_initial, simp+)
apply (rule corres_guard_imp)
apply (rule corres_splitEE)
apply (rule corres_lookup_error)
apply (rule findVSpaceForASID_corres[OF refl])
apply (rule whenE_throwError_corres, simp, simp)
apply (rule corres_splitEE)
apply (rule corres_lookup_error)
apply (rule lookupPDPTSlot_corres)
apply (rule corres_splitEE)
apply simp
apply (rule getObject_PDPTE_corres')
apply (simp add: unlessE_whenE)
apply (rule corres_splitEE)
apply (rule corres_whenE)
apply clarsimp
apply (case_tac old_pdpte; simp )[1]
apply (rule corres_trivial)
apply simp
apply simp
apply (rule corres_trivial)
apply (rule corres_returnOk)
apply (clarsimp simp: archinv_relation_def page_directory_invocation_map_def)
apply (clarsimp simp: attribs_from_word_def filter_frame_attrs_def
attribsFromWord_def Let_def)
apply ((clarsimp cong: if_cong
| wp whenE_wp hoare_vcg_all_lift_R getPDPTE_wp get_pdpte_wp
| wp (once) hoare_drop_imps)+)[6]
apply (clarsimp intro!: validE_R_validE)
apply (rule_tac Q'="\<lambda>rv s. pspace_aligned s \<and> valid_vspace_objs s \<and> valid_arch_state s \<and>
equal_kernel_mappings s \<and> valid_global_objs s \<and>
(\<exists>ref. (ref \<rhd> rv) s) \<and> typ_at (AArch APageMapL4) rv s \<and>
is_aligned rv pml4_bits"
in hoare_post_imp_R[rotated])
apply fastforce
apply (wpsimp | wp (once) hoare_drop_imps)+
apply (fastforce simp: valid_cap_def mask_def)
apply (clarsimp simp: valid_cap'_def)
apply fastforce
\<comment> \<open>PageDirectoryUnmap\<close>
apply (clarsimp simp: isCap_simps)+
apply (cases "invocation_type l = ArchInvocationLabel X64PageDirectoryUnmap")
apply (clarsimp simp: unlessE_whenE liftE_bindE)
apply (rule stronger_corres_guard_imp)
apply (rule corres_symb_exec_r_conj)
apply (rule_tac F="isArchCap isPageDirectoryCap (cteCap cteVal)"
in corres_gen_asm2)
apply (rule corres_split[OF isFinalCapability_corres[where ptr=slot]])
apply (drule mp)
apply (clarsimp simp: isCap_simps final_matters'_def)
apply (rule whenE_throwError_corres)
apply simp
apply simp
apply (rule corres_trivial, simp add: returnOk_def archinv_relation_def
page_directory_invocation_map_def)
apply (wp getCTE_wp' | wp (once) hoare_drop_imps)+
apply (clarsimp)
apply (rule no_fail_pre, rule no_fail_getCTE)
apply (erule conjunct2)
apply (clarsimp simp: cte_wp_at_caps_of_state cap_rights_update_def acap_rights_update_def)
apply (clarsimp simp add: cap_rights_update_def acap_rights_update_def)
apply (clarsimp simp: cte_wp_at_ctes_of cap_rights_update_def acap_rights_update_def
cte_wp_at_caps_of_state)
apply (drule pspace_relation_ctes_ofI[OF _ caps_of_state_cteD, rotated],
erule invs_pspace_aligned', clarsimp+)
apply (simp add: isCap_simps)
apply (simp add: isCap_simps split del: if_split)
by (clarsimp split: invocation_label.splits arch_invocation_label.splits)
lemma decodeX64PDPointerTableInvocation_corres:
"\<lbrakk>cap = arch_cap.PDPointerTableCap p opt; acap_relation cap cap';
list_all2 cap_relation (map fst excaps) (map fst excaps');
list_all2 (\<lambda>s s'. s' = cte_map s) (map snd excaps) (map snd excaps') \<rbrakk> \<Longrightarrow>
corres (ser \<oplus> archinv_relation)
(invs and valid_cap (cap.ArchObjectCap cap) and
cte_wp_at ((=) (cap.ArchObjectCap cap)) slot and
(\<lambda>s. \<forall>x\<in>set excaps. s \<turnstile> fst x \<and> cte_wp_at (\<lambda>_. True) (snd x) s))
(invs' and valid_cap' (capability.ArchObjectCap cap') and
(\<lambda>s. \<forall>x\<in>set excaps'. valid_cap' (fst x) s \<and> cte_wp_at' (\<lambda>_. True) (snd x) s))
(decode_pdpt_invocation l args slot cap excaps)
(decodeX64PDPointerTableInvocation l args (cte_map slot) cap' excaps')"
apply (simp add: decode_pdpt_invocation_def decodeX64PDPointerTableInvocation_def Let_def
isCap_simps
split del: if_split)
apply (cases "invocation_type l = ArchInvocationLabel X64PDPTMap")
apply (simp split: invocation_label.split arch_invocation_label.splits split del: if_split)
apply (simp split: list.split, intro conjI impI allI, simp_all)[1]
apply (clarsimp simp: neq_Nil_conv Let_def)
apply (rule whenE_throwError_corres_initial, simp+)
apply (simp split: cap.split arch_cap.split option.split,
intro conjI allI impI, simp_all)[1]
apply (rule whenE_throwError_corres_initial, simp+)
apply (rule corres_guard_imp)
apply (rule corres_splitEE)
apply (rule corres_lookup_error)
apply (rule findVSpaceForASID_corres[OF refl])
apply (rule whenE_throwError_corres, simp, simp)
apply (rule corres_splitEE)
apply simp
apply (rule get_pml4e_corres')
apply (simp add: unlessE_whenE)
apply (rule corres_splitEE)
apply (rule corres_whenE)
apply clarsimp
apply (case_tac old_pml4e; simp )[1]
apply (rule corres_trivial)
apply simp
apply simp
apply (rule corres_trivial)
apply (rule corres_returnOk)
apply (clarsimp simp: archinv_relation_def pdpt_invocation_map_def)
apply (clarsimp simp: attribs_from_word_def filter_frame_attrs_def
attribsFromWord_def Let_def)
apply ((clarsimp cong: if_cong
| wp whenE_wp hoare_vcg_all_lift_R getPML4E_wp get_pml4e_wp
| wp (once) hoare_drop_imps)+)
apply (fastforce simp: valid_cap_def mask_def intro!: page_map_l4_pml4e_at_lookupI)
apply (clarsimp simp: valid_cap'_def)
apply fastforce
\<comment> \<open>PDPTUnmap\<close>
apply (clarsimp simp: isCap_simps)+
apply (cases "invocation_type l = ArchInvocationLabel X64PDPTUnmap")
apply (clarsimp simp: unlessE_whenE liftE_bindE)
apply (rule stronger_corres_guard_imp)
apply (rule corres_symb_exec_r_conj)
apply (rule_tac F="isArchCap isPDPointerTableCap (cteCap cteVal)"
in corres_gen_asm2)
apply (rule corres_split[OF isFinalCapability_corres[where ptr=slot]])
apply (drule mp)
apply (clarsimp simp: isCap_simps final_matters'_def)
apply (rule whenE_throwError_corres)
apply simp
apply simp
apply (rule corres_trivial, simp add: returnOk_def archinv_relation_def
pdpt_invocation_map_def)
apply (wp getCTE_wp' | wp (once) hoare_drop_imps)+
apply (clarsimp)
apply (rule no_fail_pre, rule no_fail_getCTE)
apply (erule conjunct2)
apply (clarsimp simp: cte_wp_at_caps_of_state cap_rights_update_def acap_rights_update_def)
apply (clarsimp simp: cte_wp_at_ctes_of cap_rights_update_def acap_rights_update_def
cte_wp_at_caps_of_state)
apply (drule pspace_relation_ctes_ofI[OF _ caps_of_state_cteD, rotated],
erule invs_pspace_aligned', clarsimp+)
apply (simp add: isCap_simps)
apply (simp add: isCap_simps split del: if_split)
by (clarsimp split: invocation_label.splits arch_invocation_label.splits)
lemma ensurePortOperationAllowed_corres:
"\<lbrakk>cap = arch_cap.IOPortCap f l; acap_relation cap cap'\<rbrakk> \<Longrightarrow>
corres (ser \<oplus> dc) (valid_cap (cap.ArchObjectCap cap) and K (w \<le> 0xFFFF \<and> (x = 1\<or> x = 2 \<or> x = 4))) (valid_cap' (ArchObjectCap cap'))
(ensure_port_operation_allowed cap w x)
(ensurePortOperationAllowed cap' w x)"
apply (simp add: ensure_port_operation_allowed_def ensurePortOperationAllowed_def)
apply (rule corres_gen_asm)
apply (rule corres_guard_imp)
apply (rule corres_split_eqrE)
apply (rule corres_assertE_assume; (rule impI, assumption))
apply (rule corres_split_eqrE)
apply (rule corres_assertE_assume)
apply (rule impI, assumption)+
apply (rule corres_whenE, simp)
apply clarsimp
apply clarsimp
apply wp+
apply (clarsimp simp: valid_cap_def; elim disjE; clarsimp)
apply (subst add.commute, subst no_olen_add, simp add: word_le_def)+
apply (clarsimp simp: valid_cap'_def; elim disjE; clarsimp)
apply (subst add.commute, subst no_olen_add, simp add: word_le_def)+
done
lemma ucast_ucast_ioport_max [simp]:
"UCAST(16 \<rightarrow> 32) (UCAST(64 \<rightarrow> 16) y) \<le> 0xFFFF"
by word_bitwise
lemma decode_port_inv_corres:
"\<lbrakk>cap = arch_cap.IOPortCap f l; acap_relation cap cap' \<rbrakk> \<Longrightarrow>
corres (ser \<oplus> archinv_relation)
(invs and valid_cap (cap.ArchObjectCap cap))
(invs' and valid_cap' (capability.ArchObjectCap cap'))
(decode_port_invocation label args cap)
(decodeX64PortInvocation label args slot cap' extraCaps')"
apply (simp add: decode_port_invocation_def decodeX64PortInvocation_def)
apply (cases "invocation_type label = ArchInvocationLabel X64IOPortIn8")
apply (simp add: Let_def isCap_simps whenE_def)
apply (intro conjI impI)
apply (clarsimp simp: neq_Nil_conv)
apply (rule corres_guard_imp)
apply (rule corres_split_norE)
apply (rule ensurePortOperationAllowed_corres, simp, simp)
apply (rule corres_returnOkTT)
apply (clarsimp simp: archinv_relation_def ioport_invocation_map_def ioport_data_relation_def)
apply wpsimp+
apply (cases "invocation_type label = ArchInvocationLabel X64IOPortIn16")
apply (simp add: Let_def isCap_simps whenE_def)
apply (intro conjI impI)
apply (clarsimp simp: neq_Nil_conv)
apply (rule corres_guard_imp)
apply (rule corres_split_norE)
apply (rule ensurePortOperationAllowed_corres, simp, simp)
apply (rule corres_returnOkTT)
apply (clarsimp simp: archinv_relation_def ioport_invocation_map_def ioport_data_relation_def)
apply wpsimp+
apply (cases "invocation_type label = ArchInvocationLabel X64IOPortIn32")
apply (simp add: Let_def isCap_simps whenE_def)
apply (intro conjI impI)
apply (clarsimp simp: neq_Nil_conv)
apply (rule corres_guard_imp)
apply (rule corres_split_norE)
apply (rule ensurePortOperationAllowed_corres, simp, simp)
apply (rule corres_returnOkTT)
apply (clarsimp simp: archinv_relation_def ioport_invocation_map_def ioport_data_relation_def)
apply wpsimp+
apply (cases "invocation_type label = ArchInvocationLabel X64IOPortOut8")
apply (simp add: Let_def isCap_simps whenE_def)
apply (clarsimp simp: neq_Nil_conv split: list.splits)+
apply (rule corres_guard_imp)
apply (rule corres_split_norE)
apply (rule ensurePortOperationAllowed_corres, simp, simp)
apply (rule corres_returnOkTT)
apply (clarsimp simp: archinv_relation_def ioport_invocation_map_def ioport_data_relation_def)
apply wpsimp+
apply (cases "invocation_type label = ArchInvocationLabel X64IOPortOut16")
apply (simp add: Let_def isCap_simps whenE_def)
apply (clarsimp simp: neq_Nil_conv split: list.splits)+
apply (rule corres_guard_imp)
apply (rule corres_split_norE)
apply (rule ensurePortOperationAllowed_corres, simp, simp)
apply (rule corres_returnOkTT)
apply (clarsimp simp: archinv_relation_def ioport_invocation_map_def ioport_data_relation_def)
apply wpsimp+
apply (cases "invocation_type label = ArchInvocationLabel X64IOPortOut32")
apply (simp add: Let_def isCap_simps whenE_def)
apply (clarsimp simp: neq_Nil_conv split: list.splits)+
apply (rule corres_guard_imp)
apply (rule corres_split_norE)
apply (rule ensurePortOperationAllowed_corres, simp, simp)
apply (rule corres_returnOkTT)
apply (clarsimp simp: archinv_relation_def ioport_invocation_map_def ioport_data_relation_def)
apply wpsimp+
apply (clarsimp simp: isCap_simps Let_def split: arch_invocation_label.splits invocation_label.splits)
done
lemma free_range_corres:
"(\<not> foldl (\<lambda>x y. x \<or> f y) False (ls::'a::len word list)) = (set ls \<inter> Collect f = {})"
apply (subst foldl_fun_or_alt)
apply (fold orList_def)
apply (simp only: orList_False)
by auto
lemma isIOPortRangeFree_corres:
"f \<le> l \<Longrightarrow> corres (=) \<top> \<top>
(is_ioport_range_free f l)
(isIOPortRangeFree f l)"
apply (clarsimp simp: is_ioport_range_free_def isIOPortRangeFree_def)
apply (rule corres_guard_imp)
apply (rule corres_split_eqr[OF corres_gets_allocated_io_ports])
apply (rule corres_return_eq_same)
apply (auto simp: free_range_corres)
done
lemma isIOPortRangeFree_wp:
"\<lbrace>\<lambda>s. \<forall>rv. (rv \<longrightarrow> {f..l} \<inter> issued_ioports' (ksArchState s) = {}) \<longrightarrow> Q rv s\<rbrace> isIOPortRangeFree f l \<lbrace>Q\<rbrace>"
apply (wpsimp simp: isIOPortRangeFree_def)
apply (subst free_range_corres)
apply (clarsimp simp: issued_ioports'_def)
by (simp add: disjoint_iff_not_equal)
lemma decodeX64PortInvocation_corres:
"\<lbrakk>list_all2 cap_relation caps caps'; cap = arch_cap.IOPortControlCap; acap_relation cap cap'\<rbrakk> \<Longrightarrow>
corres (ser \<oplus> archinv_relation)
(invs and (\<lambda>s. \<forall>cp \<in> set caps. s \<turnstile> cp))
(invs' and (\<lambda>s. \<forall>cp \<in> set caps'. s \<turnstile>' cp))
(decode_ioport_control_invocation label args slot cap caps)
(decodeX64PortInvocation label args (cte_map slot) cap' caps')"
supply if_splits[split del]
apply (clarsimp simp: decode_ioport_control_invocation_def X64_H.decodeX64PortInvocation_def Let_def)
apply (cases "invocation_type label = ArchInvocationLabel X64IOPortControlIssue")
apply (clarsimp split: if_splits simp: isCap_simps)
apply (rule conjI, clarsimp split del: if_splits)
prefer 2
apply clarsimp
apply (cases caps, simp)
apply (auto split: arch_invocation_label.splits list.splits invocation_label.splits
simp: length_Suc_conv list_all2_Cons1 whenE_rangeCheck_eq liftE_bindE split_def)[2]
apply (cases caps, simp split: list.split)
apply (case_tac "\<exists>n. length args = Suc (Suc (Suc (Suc n)))",
clarsimp simp: length_Suc_conv list_all2_Cons1 whenE_rangeCheck_eq
liftE_bindE split_def)
prefer 2 apply (auto split: list.split)[1]
apply (clarsimp simp: Let_def)
apply (rule corres_guard_imp)
apply (rule whenE_throwError_corres)
apply clarsimp
apply clarsimp
apply (rule corres_split_eqr[OF isIOPortRangeFree_corres])
apply (clarsimp simp: word_le_not_less)
apply (clarsimp simp: unlessE_whenE)
apply (rule whenE_throwError_corres)
apply clarsimp
apply clarsimp
apply (clarsimp simp: lookupTargetSlot_def)
apply (rule corres_splitEE[OF lookupSlotForCNodeOp_corres])
apply (clarsimp simp: cap_relation_def)
apply clarsimp
apply (rule corres_splitEE[OF ensureEmptySlot_corres])
apply clarsimp
apply (rule corres_returnOkTT)
apply (clarsimp simp: archinv_relation_def ioport_control_inv_relation_def)
apply wp
apply wp
apply wpsimp
apply wpsimp
apply clarsimp
apply (wpsimp wp: is_ioport_range_free_wp)
apply clarsimp
apply (wpsimp wp: isIOPortRangeFree_wp)
apply (clarsimp simp: invs_valid_objs)
apply (clarsimp simp: invs_valid_objs' invs_pspace_aligned')
apply (clarsimp simp: isCap_simps split: invocation_label.splits arch_invocation_label.splits)
done
lemma arch_decodeInvocation_corres:
notes check_vp_inv[wp del] check_vp_wpR[wp]
(* FIXME: check_vp_inv shadowed check_vp_wpR. Instead,
check_vp_wpR should probably be generalised to replace check_vp_inv. *)
shows
"\<lbrakk> acap_relation arch_cap arch_cap';
list_all2 cap_relation (map fst excaps) (map fst excaps');
list_all2 (\<lambda>s s'. s' = cte_map s) (map snd excaps) (map snd excaps') \<rbrakk> \<Longrightarrow>
corres
(ser \<oplus> archinv_relation)
(invs and valid_cap (cap.ArchObjectCap arch_cap) and
cte_wp_at ((=) (cap.ArchObjectCap arch_cap)) slot and
(\<lambda>s. \<forall>x\<in>set excaps. s \<turnstile> fst x \<and> cte_at (snd x) s))
(invs' and valid_cap' (capability.ArchObjectCap arch_cap') and
(\<lambda>s. \<forall>x\<in>set excaps'. s \<turnstile>' fst x \<and> cte_at' (snd x) s))
(arch_decode_invocation (mi_label mi) args (to_bl cptr') slot
arch_cap excaps)
(Arch.decodeInvocation (mi_label mi) args cptr'
(cte_map slot) arch_cap' excaps')"
apply (simp add: arch_decode_invocation_def
X64_H.decodeInvocation_def
decodeX64MMUInvocation_def
split del: if_split)
apply (cases arch_cap)
\<comment> \<open>ASIDPoolCap\<close>
apply (simp add: isCap_simps isIOCap_def decodeX64MMUInvocation_def
decodeX64ASIDPoolInvocation_def Let_def
split del: if_split)
apply (cases "invocation_type (mi_label mi) \<noteq> ArchInvocationLabel X64ASIDPoolAssign")
apply (simp split: invocation_label.split arch_invocation_label.split)
apply (rename_tac word1 word2)
apply (cases "excaps", simp)
apply (cases "excaps'", simp)
apply clarsimp
apply (case_tac a, simp_all)[1]
apply (rename_tac arch_capa)
apply (case_tac arch_capa, simp_all)[1]
apply (rename_tac word3 option)
apply (case_tac option, simp_all)[1]
apply (rule corres_guard_imp)
apply (rule corres_splitEE)
apply (rule corres_trivial [where r="ser \<oplus> (\<lambda>p p'. p = p' o ucast)"])
apply (clarsimp simp: state_relation_def arch_state_relation_def)
apply (rule whenE_throwError_corres, simp)
apply (simp add: lookup_failure_map_def)
apply simp
apply (rule_tac P="\<lambda>s. asid_table (asid_high_bits_of word2) = Some word1 \<longrightarrow> asid_pool_at word1 s" and
P'="pspace_aligned' and pspace_distinct'" in corres_inst)
apply (simp add: liftME_return)
apply (rule whenE_throwError_corres_initial, simp)
apply auto[1]
apply (rule corres_guard_imp)
apply (rule corres_splitEE)
apply simp
apply (rule get_asid_pool_corres_inv'[OF refl])
apply (simp add: bindE_assoc)
apply (rule corres_splitEE)
apply (rule corres_whenE)
apply (subst conj_assoc [symmetric])
apply (subst assocs_empty_dom_comp [symmetric])
apply (rule dom_ucast_eq)
apply (rule corres_trivial)
apply simp
apply simp
apply (rule_tac F="- dom pool \<inter> {x. ucast x + word2 \<noteq> 0} \<noteq> {}" in corres_gen_asm)
apply (frule dom_hd_assocsD)
apply (simp add: select_ext_fap[simplified free_asid_pool_select_def]
free_asid_pool_select_def)
apply (simp add: returnOk_liftE[symmetric])
apply (rule corres_returnOk)
apply (simp add: archinv_relation_def asid_pool_invocation_map_def)
apply (rule hoare_pre, wp whenE_wp)
apply (clarsimp simp: ucast_fst_hd_assocs)
apply (wp hoareE_TrueI whenE_wp getASID_wp | simp)+
apply ((clarsimp simp: p2_low_bits_max | rule TrueI impI)+)[2]
apply (wp whenE_wp getASID_wp)+
apply (clarsimp simp: valid_cap_def)
apply auto[1]
\<comment> \<open>ASIDControlCap\<close>
apply (simp add: isCap_simps isIOCap_def decodeX64MMUInvocation_def
Let_def decodeX64ASIDControlInvocation_def
split del: if_split)
apply (cases "invocation_type (mi_label mi) \<noteq> ArchInvocationLabel X64ASIDControlMakePool")
apply (simp split: invocation_label.split arch_invocation_label.split)
apply (subgoal_tac "length excaps' = length excaps")
prefer 2
apply (simp add: list_all2_iff)
apply (cases args, simp)
apply (rename_tac a0 as)
apply (case_tac as, simp)
apply (rename_tac a1 as')
apply (cases excaps, simp)
apply (rename_tac excap0 exs)
apply (case_tac exs)
apply (auto split: list.split)[1]
apply (rename_tac excap1 exss)
apply (case_tac excap0)
apply (rename_tac c0 slot0)
apply (case_tac excap1)
apply (rename_tac c1 slot1)
apply (clarsimp simp: Let_def split del: if_split)
apply (cases excaps', simp)
apply (case_tac list, simp)
apply (rename_tac c0' exs' c1' exss')
apply (clarsimp split del: if_split)
apply (rule corres_guard_imp)
apply (rule corres_splitEE[where r'="\<lambda>p p'. p = p' o ucast"])
apply (rule corres_trivial)
apply (clarsimp simp: state_relation_def arch_state_relation_def)
apply (rule corres_splitEE)
apply (rule corres_whenE)
apply (subst assocs_empty_dom_comp [symmetric])
apply (simp add: o_def)
apply (rule dom_ucast_eq_8)
apply (rule corres_trivial, simp, simp)
apply (simp split del: if_split)
apply (rule_tac F="- dom (asidTable \<circ> ucast) \<inter> {x. x \<le> 2 ^ asid_high_bits - 1} \<noteq> {}" in corres_gen_asm)
apply (drule dom_hd_assocsD)
apply (simp add: select_ext_fa[simplified free_asid_select_def]
free_asid_select_def o_def returnOk_liftE[symmetric] split del: if_split)
apply (thin_tac "fst a \<notin> b \<and> P" for a b P)
apply (case_tac "isUntypedCap a \<and> capBlockSize a = objBits (makeObject::asidpool) \<and> \<not> capIsDevice a")
prefer 2
apply (rule corres_guard_imp)
apply (rule corres_trivial)
apply (case_tac ad, simp_all add: isCap_simps
split del: if_split)[1]
apply (case_tac x21, simp_all split del: if_split)[1]
apply (clarsimp simp: objBits_simps archObjSize_def
split del: if_split)
apply clarsimp
apply (rule TrueI)+
apply (clarsimp simp: isCap_simps cap_relation_Untyped_eq lookupTargetSlot_def
objBits_simps archObjSize_def bindE_assoc split_def)
apply (rule corres_splitEE)
apply (rule ensureNoChildren_corres, rule refl)
apply (rule corres_splitEE)
apply (erule lookupSlotForCNodeOp_corres, rule refl)
apply (rule corres_splitEE)
apply (rule ensureEmptySlot_corres)
apply clarsimp
apply (rule corres_returnOk[where P="\<top>"])
apply (clarsimp simp add: archinv_relation_def asid_ci_map_def split_def)
apply (clarsimp simp add: ucast_assocs[unfolded o_def] split_def
filter_map asid_high_bits_def)
apply (simp add: ord_le_eq_trans [OF word_n1_ge])
apply (wp hoare_drop_imps)+
apply (simp add: o_def validE_R_def)
apply (fastforce simp: asid_high_bits_def)
apply clarsimp
apply (simp add: null_def split_def asid_high_bits_def
word_le_make_less)
apply (subst hd_map, assumption)
(* need abstract guard to show list nonempty *)
apply (simp add: word_le_make_less)
apply (subst ucast_ucast_len)
apply (drule hd_in_set)
apply simp
apply fastforce
\<comment> \<open>IOPortCap\<close>
apply (simp add: isCap_simps isIOCap_def Let_def split del: if_split)
apply (rule corres_guard_imp, rule decode_port_inv_corres; simp)
\<comment> \<open>IOPortControlCap\<close>
apply (simp add: isCap_simps isIOCap_def Let_def split del: if_split)
apply (rule corres_guard_imp, rule decodeX64PortInvocation_corres; simp)
\<comment> \<open>PageCap\<close>
apply (rename_tac word cap_rights vmpage_size option)
apply (simp add: isCap_simps isIOCap_def decodeX64MMUInvocation_def Let_def
split del: if_split)
apply (rule decodeX64FrameInvocation_corres; simp)
\<comment> \<open>PageTableCap\<close>
apply (simp add: isCap_simps isIOCap_def decodeX64MMUInvocation_def Let_def
split del: if_split)
apply (rule decodeX64PageTableInvocation_corres; simp)
\<comment> \<open>PageDirectoryCap\<close>
apply (simp add: isCap_simps isIOCap_def decodeX64MMUInvocation_def Let_def
split del: if_split)
apply (rule decodeX64PageDirectoryInvocation_corres; simp)
\<comment> \<open>PDPointerTableCap\<close>
apply (simp add: isCap_simps isIOCap_def decodeX64MMUInvocation_def Let_def
split del: if_split)
apply (rule decodeX64PDPointerTableInvocation_corres; simp)
\<comment> \<open>PML4Cap - no invocations\<close>
apply (clarsimp simp: isCap_simps isIOCap_def decodeX64MMUInvocation_def Let_def
split del: if_split)
done
lemma not_InvokeIOPort_rel:"\<lbrakk>archinv_relation ai ai'; \<forall>x. ai \<noteq> arch_invocation.InvokeIOPort x\<rbrakk> \<Longrightarrow>
\<forall>y. ai' \<noteq> InvokeIOPort y"
by (clarsimp simp: archinv_relation_def split: arch_invocation.splits)
lemma not_InvokeIOPort_perform_simp':"\<forall>y. ai' \<noteq> InvokeIOPort y \<Longrightarrow>
(case ai' of invocation.InvokeIOPort x \<Rightarrow> performX64PortInvocation ai'
| _ \<Rightarrow> performX64MMUInvocation ai') = performX64MMUInvocation ai'"
by (case_tac ai'; clarsimp)
lemmas not_InvokeIOPort_perform_simp[simp] = not_InvokeIOPort_perform_simp'[OF not_InvokeIOPort_rel]
lemma port_in_corres[corres]:
"no_fail \<top> a \<Longrightarrow> corres (=) \<top> \<top> (port_in a) (portIn a)"
apply (clarsimp simp: port_in_def portIn_def)
apply (rule corres_guard_imp)
apply (rule corres_split_eqr)
apply (rule corres_machine_op[OF corres_Id], simp+)
by wpsimp+
lemma port_out_corres[@lift_corres_args, corres]:
"no_fail \<top> (a w) \<Longrightarrow> corres (=) \<top> \<top> (port_out a w) (portOut a w)"
apply (clarsimp simp: port_out_def portOut_def)
apply (rule corres_guard_imp)
apply (rule corres_split_eqr)
apply (rule corres_machine_op[OF corres_Id], simp+)
apply wpsimp+
done
lemma perform_port_inv_corres:
"\<lbrakk>archinv_relation ai ai'; ai = arch_invocation.InvokeIOPort x\<rbrakk>
\<Longrightarrow> corres (dc \<oplus> (=))
(einvs and ct_active and valid_arch_inv ai)
(invs' and ct_active' and valid_arch_inv' ai')
(liftE (perform_io_port_invocation x))
(performX64PortInvocation ai')"
apply (clarsimp simp: perform_io_port_invocation_def performX64PortInvocation_def
archinv_relation_def ioport_invocation_map_def)
apply (case_tac x; clarsimp)
apply (corressimp corres: port_in_corres simp: ioport_data_relation_def)
by (auto simp: no_fail_in8 no_fail_in16 no_fail_in32
no_fail_out8 no_fail_out16 no_fail_out32)
crunches setIOPortMask
for valid_pspace'[wp]: valid_pspace'
and valid_cap'[wp]: "valid_cap' c"
lemma setIOPortMask_invs':
"\<lbrace>invs' and (\<lambda>s. \<not> b \<longrightarrow> (\<forall>cap'\<in>ran (cteCaps_of s). cap_ioports' cap' \<inter> {f..l} = {}))\<rbrace> setIOPortMask f l b \<lbrace>\<lambda>rv. invs'\<rbrace>"
apply (wpsimp wp: setIOPortMask_ioports' simp: invs'_def valid_state'_def setIOPortMask_def simp_del: fun_upd_apply)
apply (clarsimp simp: foldl_map foldl_fun_upd_value valid_global_refs'_def global_refs'_def
valid_arch_state'_def valid_machine_state'_def)
apply (case_tac b; clarsimp simp: valid_ioports'_simps foldl_fun_upd_value)
apply (drule_tac x=cap in bspec, assumption)
apply auto[1]
apply (drule_tac x=cap in bspec, assumption)
by auto
lemma valid_ioports_issuedD':
"\<lbrakk>valid_ioports' s; cteCaps_of s src = Some cap\<rbrakk> \<Longrightarrow> cap_ioports' cap \<subseteq> issued_ioports' (ksArchState s)"
apply (clarsimp simp: valid_ioports'_def all_ioports_issued'_def)
by auto
lemma performX64PortInvocation_corres:
"\<lbrakk>archinv_relation ai ai'; ai = arch_invocation.InvokeIOPortControl x\<rbrakk> \<Longrightarrow>
corres (dc \<oplus> (=))
(einvs and ct_active and valid_arch_inv ai)
(invs' and ct_active' and valid_arch_inv' ai')
(liftE (do perform_ioport_control_invocation x; return [] od))
(performX64PortInvocation ai')"
apply (clarsimp simp: perform_ioport_control_invocation_def performX64PortInvocation_def
archinv_relation_def ioport_control_inv_relation_def)
apply (case_tac x; clarsimp simp: bind_assoc simp del: split_paired_All)
apply (rule corres_guard_imp)
apply (rule corres_split_nor[OF set_ioport_mask_corres])
apply (rule corres_split_nor[OF cteInsert_simple_corres])
apply (clarsimp simp: cap_relation_def)
apply simp
apply simp
apply (rule corres_return_eq_same, simp)
apply wpsimp
apply wpsimp
apply (clarsimp simp: is_simple_cap_def is_cap_simps)
apply wpsimp
apply (strengthen invs_distinct[mk_strg] invs_psp_aligned_strg invs_strgs)
apply (wpsimp wp: set_ioport_mask_invs set_ioport_mask_safe_parent_for)
apply (clarsimp simp: is_simple_cap'_def isCap_simps)
apply wpsimp
apply (strengthen invs_mdb'[mk_strg])
apply (wpsimp wp: setIOPortMask_invs')
apply (clarsimp simp: invs_valid_objs valid_arch_inv_def valid_iocontrol_inv_def cte_wp_at_caps_of_state)
apply (rule conjI, clarsimp)
apply (clarsimp simp: safe_parent_for_def safe_parent_for_arch_def)
apply (clarsimp simp: invs_pspace_distinct' invs_pspace_aligned' valid_arch_inv'_def ioport_control_inv_valid'_def
valid_cap'_def capAligned_def word_bits_def)
apply (clarsimp simp: safe_parent_for'_def cte_wp_at_ctes_of)
apply (case_tac ctea)
apply (clarsimp simp: isCap_simps sameRegionAs_def3)
apply (drule_tac src=p in valid_ioports_issuedD'[OF invs_valid_ioports'])
apply (fastforce simp: cteCaps_of_def)
apply force
done
lemma arch_ioport_inv_case_simp:
"\<lbrakk>archinv_relation ai ai';
\<nexists>x. ai = arch_invocation.InvokeIOPort x;
\<nexists>x. ai = arch_invocation.InvokeIOPortControl x\<rbrakk>
\<Longrightarrow> (case ai' of
invocation.InvokeIOPort x \<Rightarrow> performX64PortInvocation ai'
| invocation.InvokeIOPortControl x \<Rightarrow>
performX64PortInvocation ai'
| _ \<Rightarrow> performX64MMUInvocation ai') = performX64MMUInvocation ai'"
by (clarsimp simp: archinv_relation_def split: invocation.splits arch_invocation.splits)
lemma arch_performInvocation_corres:
"archinv_relation ai ai' \<Longrightarrow>
corres (dc \<oplus> (=))
(einvs and ct_active and valid_arch_inv ai)
(invs' and ct_active' and valid_arch_inv' ai')
(arch_perform_invocation ai) (Arch.performInvocation ai')"
apply (clarsimp simp: arch_perform_invocation_def
X64_H.performInvocation_def
performX64MMUInvocation_def)
apply (cases "\<exists>x. ai = arch_invocation.InvokeIOPort x")
apply (clarsimp simp: archinv_relation_def)
apply (rule corres_guard_imp[OF perform_port_inv_corres[where ai=ai, simplified]];
clarsimp simp: archinv_relation_def)
apply (cases "\<exists>x. ai = arch_invocation.InvokeIOPortControl x")
apply (clarsimp simp: archinv_relation_def)
apply (rule corres_guard_imp[OF performX64PortInvocation_corres[where ai=ai, simplified]];
clarsimp simp: archinv_relation_def)
apply (subst arch_ioport_inv_case_simp; simp)
apply (clarsimp simp: archinv_relation_def)
apply (clarsimp simp: performX64MMUInvocation_def)
apply (cases ai)
apply (clarsimp simp: archinv_relation_def performX64MMUInvocation_def)
apply (rule corres_guard_imp, rule corres_split_nor)
apply (rule performPageTableInvocation_corres; wpsimp)
apply (rule corres_trivial, simp)
apply wpsimp+
apply (fastforce simp: valid_arch_inv_def)
apply (fastforce simp: valid_arch_inv'_def)
apply (clarsimp simp: archinv_relation_def)
apply (rule corres_guard_imp, rule corres_split_nor)
apply (rule performPageDirectoryInvocation_corres; wpsimp)
apply (rule corres_trivial, simp)
apply wpsimp+
apply (fastforce simp: valid_arch_inv_def)
apply (fastforce simp: valid_arch_inv'_def)
apply (clarsimp simp: archinv_relation_def)
apply (rule corres_guard_imp, rule corres_split_nor)
apply (rule performPDPTInvocation_corres; wpsimp)
apply (rule corres_trivial, simp)
apply wpsimp+
apply (fastforce simp: valid_arch_inv_def)
apply (fastforce simp: valid_arch_inv'_def)
apply (clarsimp simp: archinv_relation_def)
apply (rule corres_guard_imp)
apply (rule performPageInvocation_corres; wpsimp)
apply wpsimp+
apply (fastforce simp: valid_arch_inv_def)
apply (fastforce simp: valid_arch_inv'_def)
apply (clarsimp simp: archinv_relation_def)
apply (rule corres_guard_imp, rule corres_split_nor)
apply (rule performASIDControlInvocation_corres; wpsimp)
apply (rule corres_trivial, simp)
apply wpsimp+
apply (fastforce simp: valid_arch_inv_def)
apply (fastforce simp: valid_arch_inv'_def)
apply (clarsimp simp: archinv_relation_def)
apply (rule corres_guard_imp, rule corres_split_nor)
apply (rule performASIDPoolInvocation_corres; wpsimp)
apply (rule corres_trivial, simp)
apply wpsimp+
apply (fastforce simp: valid_arch_inv_def)
apply (fastforce simp: valid_arch_inv'_def)
apply clarsimp
apply clarsimp
done
lemma asid_pool_typ_at_ext':
"asid_pool_at' = obj_at' (\<top>::asidpool \<Rightarrow> bool)"
apply (rule ext)+
apply (simp add: typ_at_to_obj_at_arches)
done
lemma st_tcb_strg':
"st_tcb_at' P p s \<longrightarrow> tcb_at' p s"
by (auto simp: pred_tcb_at')
lemma performASIDControlInvocation_tcb_at':
"\<lbrace>st_tcb_at' active' p and invs' and ct_active' and valid_aci' aci\<rbrace>
performASIDControlInvocation aci
\<lbrace>\<lambda>y. tcb_at' p\<rbrace>"
apply (rule hoare_name_pre_state)
apply (clarsimp simp: performASIDControlInvocation_def split: asidcontrol_invocation.splits)
apply (clarsimp simp: valid_aci'_def cte_wp_at_ctes_of cong: conj_cong)
apply (wp static_imp_wp |simp add:placeNewObject_def2)+
apply (wp createObjects_orig_obj_at2' updateFreeIndex_pspace_no_overlap' getSlotCap_wp static_imp_wp)+
apply (clarsimp simp: projectKO_opts_defs)
apply (strengthen st_tcb_strg' [where P=\<top>])
apply (wp deleteObjects_invs_derivatives[where p="makePoolParent aci"]
hoare_vcg_ex_lift deleteObjects_cte_wp_at'[where d=False]
deleteObjects_st_tcb_at'[where p="makePoolParent aci"] static_imp_wp
updateFreeIndex_pspace_no_overlap' deleteObject_no_overlap[where d=False])+
apply (case_tac ctea)
apply (clarsimp)
apply (frule ctes_of_valid_cap')
apply (simp add:invs_valid_objs')+
apply (clarsimp simp:valid_cap'_def capAligned_def cte_wp_at_ctes_of)
apply (strengthen refl order_refl
pred_tcb'_weakenE[mk_strg I E])
apply (clarsimp simp: conj_comms invs_valid_pspace' isCap_simps
descendants_range'_def2 empty_descendants_range_in')
apply (frule ctes_of_valid', clarsimp, simp,
drule capFreeIndex_update_valid_cap'[where fb="2 ^ pageBits", rotated -1],
simp_all)
apply (simp add: pageBits_def is_aligned_def untypedBits_defs)
apply (simp add: valid_cap_simps' range_cover_def objBits_simps archObjSize_def untypedBits_defs
capAligned_def unat_eq_0 and_mask_eq_iff_shiftr_0[symmetric]
word_bw_assocs)
apply clarsimp
apply (drule(1) cte_cap_in_untyped_range,
fastforce simp add: cte_wp_at_ctes_of, assumption, simp_all)
apply (clarsimp simp: invs'_def valid_state'_def if_unsafe_then_cap'_def cte_wp_at_ctes_of)
apply clarsimp
done
crunch tcb_at'[wp]: performX64PortInvocation "tcb_at' t"
lemma invokeArch_tcb_at':
"\<lbrace>invs' and valid_arch_inv' ai and ct_active' and st_tcb_at' active' p\<rbrace>
Arch.performInvocation ai
\<lbrace>\<lambda>rv. tcb_at' p\<rbrace>"
apply (simp add: X64_H.performInvocation_def performX64MMUInvocation_def)
apply (wpsimp simp: performX64MMUInvocation_def pred_tcb_at' valid_arch_inv'_def
wp: performASIDControlInvocation_tcb_at')
done
crunch pspace_no_overlap'[wp]: setThreadState "pspace_no_overlap' w s"
(simp: unless_def)
lemma sts_cte_cap_to'[wp]:
"\<lbrace>ex_cte_cap_to' p\<rbrace> setThreadState st t \<lbrace>\<lambda>rv. ex_cte_cap_to' p\<rbrace>"
by (wp ex_cte_cap_to'_pres)
lemma valid_slots_lift':
assumes t: "\<And>T p. \<lbrace>typ_at' T p\<rbrace> f \<lbrace>\<lambda>rv. typ_at' T p\<rbrace>"
shows "\<lbrace>valid_slots' x\<rbrace> f \<lbrace>\<lambda>rv. valid_slots' x\<rbrace>"
apply (clarsimp simp: valid_slots'_def)
apply (case_tac x, clarsimp split: vmpage_entry.splits)
apply safe
apply (rule hoare_pre, wp hoare_vcg_const_Ball_lift t valid_pde_lift' valid_pte_lift' valid_pdpte_lift', simp)+
done
lemma sts_valid_arch_inv':
"\<lbrace>valid_arch_inv' ai\<rbrace> setThreadState st t \<lbrace>\<lambda>rv. valid_arch_inv' ai\<rbrace>"
apply (cases ai, simp_all add: valid_arch_inv'_def)
apply (clarsimp simp: valid_pdpti'_def split: pdptinvocation.splits)
apply (intro allI conjI impI)
apply wpsimp+
apply (clarsimp simp: valid_pdi'_def split: page_directory_invocation.splits)
apply (intro allI conjI impI)
apply wpsimp+
apply (clarsimp simp: valid_pti'_def split: page_table_invocation.splits)
apply (intro allI conjI impI)
apply (wp | simp)+
apply (rename_tac page_invocation)
apply (case_tac page_invocation, simp_all add: valid_page_inv'_def)[1]
apply (wp valid_slots_lift' |simp)+
apply (clarsimp simp: valid_aci'_def split: asidcontrol_invocation.splits)
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (rule hoare_pre, wp)
apply clarsimp
apply (clarsimp simp: valid_apinv'_def split: asidpool_invocation.splits)
apply (rule hoare_pre, wp)
apply simp
apply wp
apply (clarsimp simp: ioport_control_inv_valid'_def split:ioport_control_invocation.splits)
apply wpsimp
done
lemma inv_ASIDPool: "inv ASIDPool = (\<lambda>v. case v of ASIDPool a \<Rightarrow> a)"
apply (rule ext)
apply (case_tac v)
apply simp
apply (rule inv_f_f, rule inj_onI)
apply simp
done
lemma eq_arch_update':
"ArchObjectCap cp = cteCap cte \<Longrightarrow> is_arch_update' (ArchObjectCap cp) cte"
by (clarsimp simp: is_arch_update'_def isCap_simps)
lemma lookup_pdpt_slot_no_fail_corres[simp]:
"lookupPDPTSlotFromPDPT pt vptr
= (do stateAssert (pd_pointer_table_at' pt) []; return (lookup_pdpt_slot_no_fail pt vptr) od)"
by (simp add: lookup_pdpt_slot_no_fail_def lookupPDPTSlotFromPDPT_def
mask_def checkPDPTAt_def word_size_bits_def)
lemma lookup_pd_slot_no_fail_corres[simp]:
"lookupPDSlotFromPD pt vptr
= (do stateAssert (page_directory_at' pt) []; return (lookup_pd_slot_no_fail pt vptr) od)"
by (simp add: lookup_pd_slot_no_fail_def lookupPDSlotFromPD_def
mask_def checkPDAt_def word_size_bits_def)
lemma lookup_pt_slot_no_fail_corres[simp]:
"lookupPTSlotFromPT pt vptr
= (do stateAssert (page_table_at' pt) []; return (lookup_pt_slot_no_fail pt vptr) od)"
by (simp add: lookup_pt_slot_no_fail_def lookupPTSlotFromPT_def
mask_def checkPTAt_def word_size_bits_def)
lemma decode_page_inv_wf[wp]:
"cap = (arch_capability.PageCap word vmrights mt vmpage_size d option) \<Longrightarrow>
\<lbrace>invs' and valid_cap' (capability.ArchObjectCap cap ) and
cte_wp_at' ((=) (capability.ArchObjectCap cap) \<circ> cteCap) slot and
(\<lambda>s. \<forall>x\<in>set excaps. cte_wp_at' ((=) (fst x) \<circ> cteCap) (snd x) s) and
sch_act_simple\<rbrace>
decodeX64FrameInvocation label args slot cap excaps
\<lbrace>valid_arch_inv'\<rbrace>, -"
apply (simp add: decodeX64FrameInvocation_def Let_def isCap_simps
cong: if_cong split del: if_split)
apply (cases "invocation_type label = ArchInvocationLabel X64PageMap")
apply (simp add: split_def split del: if_split
cong: list.case_cong prod.case_cong)
apply (rule hoare_pre)
apply (wp createMappingEntries_wf checkVP_wpR whenE_throwError_wp hoare_vcg_const_imp_lift_R
| wpc | simp add: valid_arch_inv'_def valid_page_inv'_def | wp (once) hoare_drop_imps)+
apply (clarsimp simp: neq_Nil_conv invs_valid_objs' linorder_not_le
cte_wp_at_ctes_of)
apply (drule ctes_of_valid', fastforce)+
apply (drule_tac t="cteCap cte" in sym)
apply (clarsimp simp: valid_cap'_def ptBits_def pageBits_def)
apply (clarsimp simp: is_arch_update'_def isCap_simps capAligned_def vmsz_aligned_def)
apply (rule conjI)
apply (clarsimp simp: valid_cap_simps)
apply (rule conjI)
apply (erule is_aligned_addrFromPPtr_n, case_tac vmpage_size; simp add: bit_simps)
apply (subgoal_tac "x < pptr_base", simp add: pptr_base_def)
apply (fastforce simp flip: word_le_not_less
intro: le_user_vtop_less_pptr_base
elim: word_add_increasing[where w="w-1" for w, simplified algebra_simps]
is_aligned_no_overflow)
apply clarsimp
apply (erule is_aligned_addrFromPPtr_n, case_tac vmpage_size; simp add: bit_simps)
apply (cases "invocation_type label = ArchInvocationLabel X64PageUnmap")
apply (simp split del: if_split)
apply (rule hoare_pre, wp)
apply (clarsimp simp: valid_arch_inv'_def valid_page_inv'_def)
apply (thin_tac "Ball S P" for S P)
apply (erule cte_wp_at_weakenE')
apply (clarsimp simp: is_arch_update'_def isCap_simps)
apply (cases "invocation_type label = ArchInvocationLabel X64PageGetAddress")
apply (simp split del: if_split)
apply (rule hoare_pre, wp)
apply (clarsimp simp: valid_arch_inv'_def valid_page_inv'_def)
by (simp add:throwError_R'
split: invocation_label.splits arch_invocation_label.splits)
lemma decode_page_table_inv_wf[wp]:
"arch_cap = PageTableCap word option \<Longrightarrow>
\<lbrace>invs' and valid_cap' (capability.ArchObjectCap arch_cap) and
cte_wp_at' ((=) (capability.ArchObjectCap arch_cap) \<circ> cteCap) slot and
(\<lambda>s. \<forall>x\<in>set excaps. cte_wp_at' ((=) (fst x) \<circ> cteCap) (snd x) s) and
sch_act_simple\<rbrace>
decodeX64PageTableInvocation label args slot arch_cap excaps
\<lbrace>valid_arch_inv'\<rbrace>, - "
apply (simp add: decodeX64PageTableInvocation_def Let_def isCap_simps split del: if_split cong: if_cong)
apply (rule hoare_pre)
apply ((wp whenE_throwError_wp isFinalCapability_inv getPDE_wp
| wpc
| simp add: valid_arch_inv'_def valid_pti'_def if_apply_def2
| wp (once) hoare_drop_imps)+)
apply (clarsimp simp: linorder_not_le isCap_simps cte_wp_at_ctes_of)
apply (frule eq_arch_update')
apply (case_tac option; clarsimp)
apply (drule_tac t="cteCap ctea" in sym, simp)
apply (clarsimp simp: is_arch_update'_def isCap_simps valid_cap'_def capAligned_def)
apply (thin_tac "Ball S P" for S P)+
apply (drule ctes_of_valid', fastforce)+
apply (clarsimp simp: valid_cap'_def bit_simps is_aligned_addrFromPPtr_n
invs_valid_objs' and_not_mask[symmetric])
apply (clarsimp simp: mask_def X64.pptrBase_def X64.pptrUserTop_def user_vtop_def)
apply word_bitwise
apply auto
done
lemma decode_page_directory_inv_wf[wp]:
"arch_cap = PageDirectoryCap word option \<Longrightarrow>
\<lbrace>invs' and valid_cap' (capability.ArchObjectCap arch_cap) and
cte_wp_at' ((=) (capability.ArchObjectCap arch_cap) \<circ> cteCap) slot and
(\<lambda>s. \<forall>x\<in>set excaps. cte_wp_at' ((=) (fst x) \<circ> cteCap) (snd x) s) and
sch_act_simple\<rbrace>
decodeX64PageDirectoryInvocation label args slot arch_cap excaps
\<lbrace>valid_arch_inv'\<rbrace>, - "
apply (simp add: decodeX64PageDirectoryInvocation_def Let_def isCap_simps split del: if_split cong: if_cong)
apply (rule hoare_pre)
apply ((wp whenE_throwError_wp isFinalCapability_inv getPDPTE_wp
| wpc
| simp add: valid_arch_inv'_def valid_pdi'_def if_apply_def2
| wp (once) hoare_drop_imps)+)
apply (clarsimp simp: linorder_not_le isCap_simps cte_wp_at_ctes_of)
apply (frule eq_arch_update')
apply (case_tac option; clarsimp)
apply (drule_tac t="cteCap ctea" in sym, simp)
apply (clarsimp simp: is_arch_update'_def isCap_simps valid_cap'_def capAligned_def)
apply (thin_tac "Ball S P" for S P)+
apply (drule ctes_of_valid', fastforce)+
apply (clarsimp simp: valid_cap'_def bit_simps is_aligned_addrFromPPtr_n
invs_valid_objs' and_not_mask[symmetric])
apply (clarsimp simp: mask_def X64.pptrBase_def X64.pptrUserTop_def user_vtop_def)
apply word_bitwise
apply auto
done
lemma decode_pdpt_inv_wf[wp]:
"arch_cap = PDPointerTableCap word option \<Longrightarrow>
\<lbrace>invs' and valid_cap' (capability.ArchObjectCap arch_cap) and
cte_wp_at' ((=) (capability.ArchObjectCap arch_cap) \<circ> cteCap) slot and
(\<lambda>s. \<forall>x\<in>set excaps. cte_wp_at' ((=) (fst x) \<circ> cteCap) (snd x) s) and
sch_act_simple\<rbrace>
decodeX64PDPointerTableInvocation label args slot arch_cap excaps
\<lbrace>valid_arch_inv'\<rbrace>, - "
apply (simp add: decodeX64PDPointerTableInvocation_def Let_def isCap_simps split del: if_split cong: if_cong)
apply (rule hoare_pre)
apply ((wp whenE_throwError_wp isFinalCapability_inv getPML4E_wp
| wpc
| simp add: valid_arch_inv'_def valid_pdpti'_def if_apply_def2
| wp (once) hoare_drop_imps)+)
apply (clarsimp simp: linorder_not_le isCap_simps cte_wp_at_ctes_of)
apply (frule eq_arch_update')
apply (case_tac option; clarsimp)
apply (drule_tac t="cteCap ctea" in sym, simp)
apply (clarsimp simp: is_arch_update'_def isCap_simps valid_cap'_def capAligned_def)
apply (thin_tac "Ball S P" for S P)+
apply (drule ctes_of_valid', fastforce)+
apply (clarsimp simp: valid_cap'_def bit_simps is_aligned_addrFromPPtr_n
invs_valid_objs' and_not_mask[symmetric])
apply (clarsimp simp: mask_def X64.pptrBase_def X64.pptrUserTop_def user_vtop_def)
apply word_bitwise
apply auto
done
lemma decode_port_inv_wf:
"arch_cap = IOPortCap f l \<Longrightarrow>
\<lbrace>\<top>\<rbrace>
decodeX64PortInvocation label args slot arch_cap excaps
\<lbrace>valid_arch_inv'\<rbrace>, - "
apply (clarsimp simp: decodeX64PortInvocation_def Let_def isCap_simps split del: if_split cong: if_cong)
by (wpsimp simp: valid_arch_inv'_def)
lemma decode_port_control_inv_wf:
"arch_cap = IOPortControlCap \<Longrightarrow>
\<lbrace>\<lambda>s. invs' s \<and> (\<forall>cap \<in> set caps. s \<turnstile>' cap)
\<and> (\<forall>cap \<in> set caps. \<forall>r \<in> cte_refs' cap (irq_node' s). ex_cte_cap_to' r s)
\<and> cte_wp_at' (\<lambda>cte. cteCap cte = ArchObjectCap IOPortControlCap) slot s\<rbrace>
decodeX64PortInvocation label args slot arch_cap caps
\<lbrace>valid_arch_inv'\<rbrace>, -"
apply (clarsimp simp add: decodeX64PortInvocation_def Let_def split_def
unlessE_whenE isCap_simps lookupTargetSlot_def
split del: if_split cong: if_cong list.case_cong prod.case_cong
arch_invocation_label.case_cong)
apply (rule hoare_pre)
apply (simp add: rangeCheck_def unlessE_whenE lookupTargetSlot_def valid_arch_inv'_def
ioport_control_inv_valid'_def
cong: list.case_cong prod.case_cong
| wp whenE_throwError_wp ensureEmptySlot_stronger isIOPortRangeFree_wp
| wpc
| wp (once) hoare_drop_imps)+
by (auto simp: invs_valid_objs')
lemma arch_decodeInvocation_wf[wp]:
notes ensureSafeMapping_inv[wp del]
shows "\<lbrace>invs' and valid_cap' (ArchObjectCap arch_cap) and
cte_wp_at' ((=) (ArchObjectCap arch_cap) o cteCap) slot and
(\<lambda>s. \<forall>x \<in> set excaps. cte_wp_at' ((=) (fst x) o cteCap) (snd x) s) and
(\<lambda>s. \<forall>x \<in> set excaps. \<forall>r \<in> cte_refs' (fst x) (irq_node' s). ex_cte_cap_to' r s) and
(\<lambda>s. \<forall>x \<in> set excaps. s \<turnstile>' fst x) and
sch_act_simple\<rbrace>
Arch.decodeInvocation label args cap_index slot arch_cap excaps
\<lbrace>valid_arch_inv'\<rbrace>,-"
apply (cases arch_cap)
\<comment> \<open>ASIDPool cap\<close>
apply (simp add: decodeX64MMUInvocation_def X64_H.decodeInvocation_def
Let_def split_def isCap_simps isIOCap_def decodeX64ASIDPoolInvocation_def
cong: if_cong split del: if_split)
apply (rule hoare_pre)
apply ((wp whenE_throwError_wp getASID_wp|
wpc|
simp add: valid_arch_inv'_def valid_apinv'_def)+)[1]
apply (clarsimp simp: word_neq_0_conv valid_cap'_def valid_arch_inv'_def valid_apinv'_def)
apply (rule conjI)
apply (erule cte_wp_at_weakenE')
apply (simp, drule_tac t="cteCap c" in sym, simp)
apply (subst (asm) conj_assoc [symmetric])
apply (subst (asm) assocs_empty_dom_comp [symmetric])
apply (drule dom_hd_assocsD)
apply (simp add: capAligned_def asid_wf_def)
apply (elim conjE)
apply (subst field_simps, erule is_aligned_add_less_t2n)
apply assumption
apply (simp add: asid_low_bits_def asid_bits_def)
apply assumption
\<comment> \<open>ASIDControlCap\<close>
apply (simp add: decodeX64MMUInvocation_def X64_H.decodeInvocation_def
Let_def split_def isCap_simps isIOCap_def decodeX64ASIDControlInvocation_def
cong: if_cong invocation_label.case_cong arch_invocation_label.case_cong list.case_cong prod.case_cong
split del: if_split)
apply (rule hoare_pre)
apply ((wp whenE_throwError_wp ensureEmptySlot_stronger|
wpc|
simp add: valid_arch_inv'_def valid_aci'_def is_aligned_shiftl_self
split del: if_split)+)[1]
apply (rule_tac Q'=
"\<lambda>rv. K (fst (hd [p\<leftarrow>assocs asidTable . fst p \<le> 2 ^ asid_high_bits - 1 \<and> snd p = None])
<< asid_low_bits \<le> 2 ^ asid_bits - 1) and
real_cte_at' rv and
ex_cte_cap_to' rv and
cte_wp_at' (\<lambda>cte. \<exists>idx. cteCap cte = (UntypedCap False frame pageBits idx)) (snd (excaps!0)) and
sch_act_simple and
(\<lambda>s. descendants_of' (snd (excaps!0)) (ctes_of s) = {}) "
in hoare_post_imp_R)
apply (simp add: lookupTargetSlot_def)
apply wp
apply (clarsimp simp: cte_wp_at_ctes_of asid_wf_def)
apply (simp split del: if_split)
apply (wp ensureNoChildren_sp whenE_throwError_wp|wpc)+
apply clarsimp
apply (rule conjI)
apply (clarsimp simp: null_def neq_Nil_conv)
apply (drule filter_eq_ConsD)
apply clarsimp
apply (rule shiftl_less_t2n)
apply (simp add: asid_bits_def asid_low_bits_def asid_high_bits_def)
apply unat_arith
apply (simp add: asid_bits_def)
apply clarsimp
apply (rule conjI, fastforce)
apply (clarsimp simp: cte_wp_at_ctes_of objBits_simps archObjSize_def)
\<comment> \<open>IOPortCap\<close>
apply (simp add: decodeX64MMUInvocation_def X64_H.decodeInvocation_def
Let_def split_def isCap_simps isIOCap_def valid_arch_inv'_def
cong: if_cong split del: if_split)
apply (wp decode_port_inv_wf, simp+)
\<comment> \<open>IOPortControlCap\<close>
apply (simp add: decodeX64MMUInvocation_def X64_H.decodeInvocation_def Let_def isCap_simps
split_def isIOCap_def
cong: if_cong
split del: if_split)
apply (wp decode_port_control_inv_wf, simp)
apply (clarsimp simp: cte_wp_at_ctes_of)
\<comment> \<open>PageCap\<close>
apply (simp add: decodeX64MMUInvocation_def isCap_simps X64_H.decodeInvocation_def Let_def isIOCap_def
cong: if_cong split del: if_split)
apply (wp, simp+)
\<comment> \<open>PageTableCap\<close>
apply (simp add: decodeX64MMUInvocation_def isCap_simps X64_H.decodeInvocation_def isIOCap_def Let_def
cong: if_cong split del: if_split)
apply (wpsimp, simp+)
\<comment> \<open>PageDirectoryCap\<close>
apply (simp add: decodeX64MMUInvocation_def isCap_simps X64_H.decodeInvocation_def isIOCap_def Let_def
cong: if_cong split del: if_split)
apply (wpsimp, simp+)
\<comment> \<open>PDPointerTableCap\<close>
apply (simp add: decodeX64MMUInvocation_def isCap_simps X64_H.decodeInvocation_def isIOCap_def Let_def
cong: if_cong split del: if_split)
apply (wpsimp, simp+)
\<comment> \<open>PML4Cap\<close>
apply (simp add: decodeX64MMUInvocation_def isCap_simps X64_H.decodeInvocation_def isIOCap_def Let_def
cong: if_cong split del: if_split)
by (wpsimp)
crunch nosch[wp]: setMRs "\<lambda>s. P (ksSchedulerAction s)"
(ignore: getRestartPC setRegister transferCapsToSlots
wp: hoare_drop_imps hoare_vcg_split_case_option
mapM_wp'
simp: split_def zipWithM_x_mapM)
crunches performX64MMUInvocation, performX64PortInvocation
for nosch [wp]: "\<lambda>s. P (ksSchedulerAction s)"
(simp: crunch_simps
wp: crunch_wps getObject_cte_inv getASID_wp)
lemmas setObject_cte_st_tcb_at' [wp] = setCTE_pred_tcb_at' [unfolded setCTE_def]
crunch st_tcb_at': performPageDirectoryInvocation, performPageTableInvocation,
performPageInvocation, performPDPTInvocation,
performASIDPoolInvocation, performX64PortInvocation "st_tcb_at' P t"
(wp: crunch_wps getASID_wp getObject_cte_inv simp: crunch_simps)
lemma performASIDControlInvocation_st_tcb_at':
"\<lbrace>st_tcb_at' (P and (\<noteq>) Inactive and (\<noteq>) IdleThreadState) t and
valid_aci' aci and invs' and ct_active'\<rbrace>
performASIDControlInvocation aci
\<lbrace>\<lambda>y. st_tcb_at' P t\<rbrace>"
apply (rule hoare_name_pre_state)
apply (clarsimp simp: performASIDControlInvocation_def split: asidcontrol_invocation.splits)
apply (clarsimp simp: valid_aci'_def cte_wp_at_ctes_of cong: conj_cong)
apply (rule hoare_pre)
apply (wp createObjects_orig_obj_at'[where P="P \<circ> tcbState", folded st_tcb_at'_def]
updateFreeIndex_pspace_no_overlap' getSlotCap_wp
hoare_vcg_ex_lift
deleteObjects_cte_wp_at' deleteObjects_invs_derivatives
deleteObjects_st_tcb_at'
static_imp_wp
| simp add: placeNewObject_def2)+
apply (case_tac ctea)
apply (clarsimp)
apply (frule ctes_of_valid_cap')
apply (simp add:invs_valid_objs')+
apply (clarsimp simp:valid_cap'_def capAligned_def cte_wp_at_ctes_of)
apply (rule conjI)
apply clarsimp
apply (drule (1) cte_cap_in_untyped_range)
apply (fastforce simp add: cte_wp_at_ctes_of)
apply assumption+
subgoal by (clarsimp simp: invs'_def valid_state'_def if_unsafe_then_cap'_def cte_wp_at_ctes_of)
subgoal by fastforce
apply simp
apply (rule conjI,assumption)
apply (clarsimp simp:invs_valid_pspace' objBits_simps archObjSize_def
range_cover_full descendants_range'_def2 isCap_simps)
apply (intro conjI)
apply (fastforce simp:empty_descendants_range_in')+
apply clarsimp
apply (drule (1) cte_cap_in_untyped_range)
apply (fastforce simp add: cte_wp_at_ctes_of)
apply assumption+
apply (clarsimp simp: invs'_def valid_state'_def if_unsafe_then_cap'_def cte_wp_at_ctes_of)
apply fastforce
apply simp
apply auto
done
crunch aligned': "Arch.finaliseCap" pspace_aligned'
(wp: crunch_wps getASID_wp simp: crunch_simps)
lemmas arch_finalise_cap_aligned' = finaliseCap_aligned'
crunch distinct': "Arch.finaliseCap" pspace_distinct'
(wp: crunch_wps getASID_wp simp: crunch_simps)
lemmas arch_finalise_cap_distinct' = finaliseCap_distinct'
crunch nosch [wp]: "Arch.finaliseCap" "\<lambda>s. P (ksSchedulerAction s)"
(wp: crunch_wps getASID_wp simp: crunch_simps updateObject_default_def)
crunch st_tcb_at' [wp]: "Arch.finaliseCap" "st_tcb_at' P t"
(wp: crunch_wps getASID_wp simp: crunch_simps)
crunch typ_at' [wp]: "Arch.finaliseCap" "\<lambda>s. P (typ_at' T p s)"
(wp: crunch_wps getASID_wp simp: crunch_simps)
crunch cte_wp_at': "Arch.finaliseCap" "cte_wp_at' P p"
(wp: crunch_wps getASID_wp simp: crunch_simps)
lemma invs_asid_table_strengthen':
"invs' s \<and> asid_pool_at' ap s \<and> asid \<le> 2 ^ asid_high_bits - 1 \<longrightarrow>
invs' (s\<lparr>ksArchState :=
x64KSASIDTable_update (\<lambda>_. (x64KSASIDTable \<circ> ksArchState) s(asid \<mapsto> ap)) (ksArchState s)\<rparr>)"
apply (clarsimp simp: invs'_def valid_state'_def)
apply (rule conjI)
apply (clarsimp simp: valid_global_refs'_def global_refs'_def)
apply (clarsimp simp: valid_arch_state'_def)
apply (clarsimp simp: valid_asid_table'_def ran_def)
apply (rule conjI)
apply (clarsimp split: if_split_asm)
apply fastforce
apply (rule conjI)
apply (clarsimp simp: valid_pspace'_def)
apply (simp add: valid_machine_state'_def)
apply (clarsimp simp: valid_ioports'_simps)
done
lemma ex_cte_not_in_untyped_range:
"\<lbrakk>(ctes_of s) cref = Some (CTE (capability.UntypedCap d ptr bits idx) mnode);
descendants_of' cref (ctes_of s) = {}; invs' s;
ex_cte_cap_wp_to' (\<lambda>_. True) x s; valid_global_refs' s\<rbrakk>
\<Longrightarrow> x \<notin> {ptr .. ptr + 2 ^ bits - 1}"
apply clarsimp
apply (drule(1) cte_cap_in_untyped_range)
apply (fastforce simp:cte_wp_at_ctes_of)+
done
lemma ucast_asid_high_btis_of_le [simp]:
"ucast (asid_high_bits_of w) \<le> (2 ^ asid_high_bits - 1 :: machine_word)"
apply (simp add: asid_high_bits_of_def)
apply (rule word_less_sub_1)
apply (rule order_less_le_trans)
apply (rule ucast_less)
apply simp
apply (simp add: asid_high_bits_def)
done
lemma performASIDControlInvocation_invs' [wp]:
"\<lbrace>invs' and ct_active' and valid_aci' aci\<rbrace>
performASIDControlInvocation aci \<lbrace>\<lambda>y. invs'\<rbrace>"
apply (rule hoare_name_pre_state)
apply (clarsimp simp: performASIDControlInvocation_def valid_aci'_def
placeNewObject_def2 cte_wp_at_ctes_of
split: asidcontrol_invocation.splits)
apply (rename_tac w1 w2 w3 w4 cte ctea idx)
apply (case_tac ctea)
apply (clarsimp)
apply (frule ctes_of_valid_cap')
apply fastforce
apply (rule hoare_pre)
apply (wp hoare_vcg_const_imp_lift)
apply (strengthen invs_asid_table_strengthen')
apply (wp cteInsert_simple_invs)
apply (wp createObjects'_wp_subst[OF
createObjects_no_cte_invs[where sz = pageBits and ty="Inl (KOArch (KOASIDPool pool))" for pool]]
createObjects_orig_cte_wp_at'[where sz = pageBits] hoare_vcg_const_imp_lift
|simp add: makeObjectKO_def projectKOs asid_pool_typ_at_ext' valid_cap'_def cong: rev_conj_cong
|strengthen safe_parent_strg'[where idx= "2^ pageBits"])+
apply (rule hoare_vcg_conj_lift)
apply (rule descendants_of'_helper)
apply (wp createObjects_null_filter'
[where sz = pageBits and ty="Inl (KOArch (KOASIDPool ap))" for ap]
createObjects_valid_pspace'
[where sz = pageBits and ty="Inl (KOArch (KOASIDPool ap))" for ap]
| simp add: makeObjectKO_def projectKOs asid_pool_typ_at_ext' valid_cap'_def
cong: rev_conj_cong)+
apply (simp add: objBits_simps archObjSize_def valid_cap'_def capAligned_def range_cover_full)
apply (wp createObjects'_wp_subst[OF createObjects_ex_cte_cap_to[where sz = pageBits]]
createObjects_orig_cte_wp_at'[where sz = pageBits]
hoare_vcg_const_imp_lift
|simp add: makeObjectKO_def projectKOs asid_pool_typ_at_ext' valid_cap'_def
not_ioport_cap_safe_ioport_insert' isCap_simps
canonical_address_neq_mask
cong: rev_conj_cong
|strengthen safe_parent_strg'[where idx = "2^ pageBits"]
| rule in_kernel_mappings_neq_mask
| simp add: bit_simps)+
apply (simp add:asid_pool_typ_at_ext'[symmetric])
apply (wp createObject_typ_at')
apply (simp add: objBits_simps archObjSize_def valid_cap'_def
capAligned_def range_cover_full makeObjectKO_def
projectKOs asid_pool_typ_at_ext'
cong: rev_conj_cong)
apply (clarsimp simp:conj_comms
descendants_of_null_filter'
| strengthen invs_pspace_aligned' invs_pspace_distinct'
invs_pspace_aligned' invs_valid_pspace')+
apply (wp updateFreeIndex_forward_invs'
updateFreeIndex_cte_wp_at
updateFreeIndex_pspace_no_overlap'
updateFreeIndex_caps_no_overlap''
updateFreeIndex_descendants_of2
updateFreeIndex_caps_overlap_reserved
updateCap_cte_wp_at_cases static_imp_wp
getSlotCap_wp)+
apply (clarsimp simp:conj_comms ex_disj_distrib is_aligned_mask
| strengthen invs_valid_pspace' invs_pspace_aligned'
invs_pspace_distinct' empty_descendants_range_in')+
apply (wp deleteObjects_invs'[where p="makePoolParent aci"]
hoare_vcg_ex_lift
deleteObjects_caps_no_overlap''[where slot="makePoolParent aci"]
deleteObject_no_overlap
deleteObjects_cap_to'[where p="makePoolParent aci"]
deleteObjects_ct_active'[where cref="makePoolParent aci"]
deleteObjects_descendants[where p="makePoolParent aci"]
deleteObjects_cte_wp_at'
deleteObjects_null_filter[where p="makePoolParent aci"])
apply (frule valid_capAligned)
apply (clarsimp simp: invs_mdb' invs_valid_pspace' capAligned_def
cte_wp_at_ctes_of is_simple_cap'_def isCap_simps)
apply (strengthen refl ctes_of_valid_cap'[mk_strg I E])
apply (clarsimp simp: conj_comms invs_valid_objs')
apply (frule_tac ptr="w1" in descendants_range_caps_no_overlapI'[where sz = pageBits])
apply (fastforce simp: cte_wp_at_ctes_of)
apply (simp add:empty_descendants_range_in')
apply (frule(1) if_unsafe_then_capD'[OF _ invs_unsafe_then_cap',rotated])
apply (fastforce simp:cte_wp_at_ctes_of)
apply (drule ex_cte_not_in_untyped_range[rotated -2])
apply (simp add:invs_valid_global')+
apply (drule ex_cte_not_in_untyped_range[rotated -2])
apply (simp add:invs_valid_global')+
apply (subgoal_tac "is_aligned (2 ^ pageBits) minUntypedSizeBits")
prefer 2
apply (rule is_aligned_weaken)
apply (rule is_aligned_shiftl_self[unfolded shiftl_t2n,where p = 1, simplified])
apply (simp add: pageBits_def untypedBits_defs)
apply (frule_tac cte="CTE (capability.UntypedCap False a b c) m" for a b c m in valid_global_refsD', clarsimp)
apply (simp add: Int_commute)
by (auto simp:empty_descendants_range_in' objBits_simps max_free_index_def
archObjSize_def asid_low_bits_def word_bits_def
range_cover_full descendants_range'_def2 is_aligned_mask
null_filter_descendants_of'[OF null_filter_simp'] bit_simps
valid_cap_simps' mask_def)+
lemma dmo_out8_invs'[wp]:
"\<lbrace>invs'\<rbrace> doMachineOp (out8 a b) \<lbrace>\<lambda>_. invs'\<rbrace>"
apply (wp dmo_invs' no_irq_out8 no_irq)
apply clarsimp
apply (drule_tac P4="\<lambda>m'. underlying_memory m' p = underlying_memory m p"
in use_valid[where P=P and Q="\<lambda>_. P" for P])
apply (simp add: out8_def machine_op_lift_def
machine_rest_lift_def split_def | wp)+
done
lemma dmo_out16_invs'[wp]:
"\<lbrace>invs'\<rbrace> doMachineOp (out16 a b) \<lbrace>\<lambda>_. invs'\<rbrace>"
apply (wp dmo_invs' no_irq_out16 no_irq)
apply clarsimp
apply (drule_tac P4="\<lambda>m'. underlying_memory m' p = underlying_memory m p"
in use_valid[where P=P and Q="\<lambda>_. P" for P])
apply (simp add: out16_def machine_op_lift_def
machine_rest_lift_def split_def | wp)+
done
lemma dmo_out32_invs'[wp]:
"\<lbrace>invs'\<rbrace> doMachineOp (out32 a b) \<lbrace>\<lambda>_. invs'\<rbrace>"
apply (wp dmo_invs' no_irq_out32 no_irq)
apply clarsimp
apply (drule_tac P4="\<lambda>m'. underlying_memory m' p = underlying_memory m p"
in use_valid[where P=P and Q="\<lambda>_. P" for P])
apply (simp add: out32_def machine_op_lift_def
machine_rest_lift_def split_def | wp)+
done
lemma dmo_in8_invs'[wp]:
"\<lbrace>invs'\<rbrace> doMachineOp (in8 a) \<lbrace>\<lambda>_. invs'\<rbrace>"
apply (wp dmo_invs' no_irq_in8 no_irq)
apply clarsimp
apply (drule_tac P4="\<lambda>m'. underlying_memory m' p = underlying_memory m p"
in use_valid[where P=P and Q="\<lambda>_. P" for P])
apply (simp add: in8_def machine_op_lift_def
machine_rest_lift_def split_def | wp)+
done
lemma dmo_in16_invs'[wp]:
"\<lbrace>invs'\<rbrace> doMachineOp (in16 a) \<lbrace>\<lambda>_. invs'\<rbrace>"
apply (wp dmo_invs' no_irq_in16 no_irq)
apply clarsimp
apply (drule_tac P4="\<lambda>m'. underlying_memory m' p = underlying_memory m p"
in use_valid[where P=P and Q="\<lambda>_. P" for P])
apply (simp add: in16_def machine_op_lift_def
machine_rest_lift_def split_def | wp)+
done
lemma dmo_in32_invs'[wp]:
"\<lbrace>invs'\<rbrace> doMachineOp (in32 a) \<lbrace>\<lambda>_. invs'\<rbrace>"
apply (wp dmo_invs' no_irq_in32 no_irq)
apply clarsimp
apply (drule_tac P4="\<lambda>m'. underlying_memory m' p = underlying_memory m p"
in use_valid[where P=P and Q="\<lambda>_. P" for P])
apply (simp add: in32_def machine_op_lift_def
machine_rest_lift_def split_def | wp)+
done
lemma setIOPortMask_safe_ioport_insert':
"\<lbrace>\<lambda>s. (\<forall>cap\<in>ran (cteCaps_of s). cap_ioports' ac \<inter> cap_ioports' cap = {}) \<and>
ac = ArchObjectCap (IOPortCap f l)\<rbrace>
setIOPortMask f l True
\<lbrace>\<lambda>rv s. safe_ioport_insert' ac NullCap s\<rbrace>"
supply fun_upd_apply[simp del]
apply (clarsimp simp: safe_ioport_insert'_def issued_ioports'_def setIOPortMask_def)
apply wpsimp
by (clarsimp simp: cte_wp_at_ctes_of foldl_map foldl_fun_upd_value)
lemma setIOPortMask_cte_cap_to'[wp]:
"\<lbrace>ex_cte_cap_to' p\<rbrace> setIOPortMask f l b \<lbrace>\<lambda>rv. ex_cte_cap_to' p\<rbrace>"
by (wp ex_cte_cap_to'_pres)
lemma arch_performInvocation_invs':
"\<lbrace>invs' and ct_active' and valid_arch_inv' invocation\<rbrace>
Arch.performInvocation invocation
\<lbrace>\<lambda>rv. invs'\<rbrace>"
unfolding X64_H.performInvocation_def
apply (cases invocation, simp_all add: performX64MMUInvocation_def valid_arch_inv'_def,
(wp|wpc|simp)+)
apply (clarsimp simp: performX64PortInvocation_def)
apply (wpsimp simp: portIn_def portOut_def)
apply (clarsimp simp: invs'_def cur_tcb'_def)
apply (clarsimp simp: performX64PortInvocation_def)
apply (wpsimp wp: cteInsert_simple_invs setIOPortMask_invs' setIOPortMask_safe_ioport_insert')
apply (clarsimp simp: ioport_control_inv_valid'_def valid_cap'_def capAligned_def word_bits_def
is_simple_cap'_def isCap_simps)
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (rule conjI, clarsimp)
apply (rule conjI, clarsimp simp: safe_parent_for'_def)
apply (case_tac ctea)
apply (clarsimp simp: isCap_simps sameRegionAs_def3)
apply (drule_tac src=p in valid_ioports_issuedD'[OF invs_valid_ioports'])
apply (fastforce simp: cteCaps_of_def)
apply force
by (force simp: cteCaps_of_def ran_def valid_ioports'_simps dest!: invs_valid_ioports')
end
end
|
lemma tendsto_cong_limit: "(f \<longlongrightarrow> l) F \<Longrightarrow> k = l \<Longrightarrow> (f \<longlongrightarrow> k) F" |
State Before: R : Type u
S : Type v
k : Type y
A : Type z
a b : R
n : ℕ
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : NormalizationMonoid R
p : R[X]
⊢ leadingCoeff (↑normalize p) = ↑normalize (leadingCoeff p) State After: no goals Tactic: simp |
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
(Least / Greatest) upper / lower bounds
-/
import order.complete_lattice
open set lattice
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a a₁ a₂ : α} {b b₁ b₂ : β} {s t : set α}
section preorder
variables [preorder α] [preorder β] {f : α → β}
def upper_bounds (s : set α) : set α := { x | ∀a ∈ s, a ≤ x }
def lower_bounds (s : set α) : set α := { x | ∀a ∈ s, x ≤ a }
def is_least (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ lower_bounds s
def is_greatest (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ upper_bounds s
def is_lub (s : set α) : α → Prop := is_least (upper_bounds s)
def is_glb (s : set α) : α → Prop := is_greatest (lower_bounds s)
lemma mem_upper_bounds_image (Hf : monotone f) (Ha : a ∈ upper_bounds s) :
f a ∈ upper_bounds (f '' s) :=
ball_image_of_ball (assume x H, Hf (Ha _ ‹x ∈ s›))
lemma mem_lower_bounds_image (Hf : monotone f) (Ha : a ∈ lower_bounds s) :
f a ∈ lower_bounds (f '' s) :=
ball_image_of_ball (assume x H, Hf (Ha _ ‹x ∈ s›))
lemma is_lub_singleton {a : α} : is_lub {a} a :=
by simp [is_lub, is_least, upper_bounds, lower_bounds] {contextual := tt}
lemma is_glb_singleton {a : α} : is_glb {a} a :=
by simp [is_glb, is_greatest, upper_bounds, lower_bounds] {contextual := tt}
end preorder
section partial_order
variables [partial_order α]
lemma eq_of_is_least_of_is_least (Ha : is_least s a₁) (Hb : is_least s a₂) : a₁ = a₂ :=
le_antisymm (Ha.right _ Hb.left) (Hb.right _ Ha.left)
lemma is_least_iff_eq_of_is_least (Ha : is_least s a₁) : is_least s a₂ ↔ a₁ = a₂ :=
iff.intro (eq_of_is_least_of_is_least Ha) (assume h, h ▸ Ha)
lemma eq_of_is_greatest_of_is_greatest (Ha : is_greatest s a₁) (Hb : is_greatest s a₂) : a₁ = a₂ :=
le_antisymm (Hb.right _ Ha.left) (Ha.right _ Hb.left)
lemma is_greatest_iff_eq_of_is_greatest (Ha : is_greatest s a₁) : is_greatest s a₂ ↔ a₁ = a₂ :=
iff.intro (eq_of_is_greatest_of_is_greatest Ha) (assume h, h ▸ Ha)
lemma eq_of_is_lub_of_is_lub : is_lub s a₁ → is_lub s a₂ → a₁ = a₂ :=
eq_of_is_least_of_is_least
lemma is_lub_iff_eq_of_is_lub : is_lub s a₁ → (is_lub s a₂ ↔ a₁ = a₂) :=
is_least_iff_eq_of_is_least
lemma eq_of_is_glb_of_is_glb : is_glb s a₁ → is_glb s a₂ → a₁ = a₂ :=
eq_of_is_greatest_of_is_greatest
lemma is_glb_iff_eq_of_is_glb : is_glb s a₁ → (is_glb s a₂ ↔ a₁ = a₂) :=
is_greatest_iff_eq_of_is_greatest
lemma ne_empty_of_is_lub [no_bot_order α] (hs : is_lub s a) : s ≠ ∅ :=
let ⟨a', ha'⟩ := no_bot a in
assume h,
have a ≤ a', from hs.right _ (by simp [upper_bounds, h]),
lt_irrefl a $ lt_of_le_of_lt this ha'
lemma ne_empty_of_is_glb [no_top_order α] (hs : is_glb s a) : s ≠ ∅ :=
let ⟨a', ha'⟩ := no_top a in
assume h,
have a' ≤ a, from hs.right _ (by simp [lower_bounds, h]),
lt_irrefl a $ lt_of_lt_of_le ha' this
end partial_order
section lattice
lemma is_glb_empty [order_top α] : is_glb ∅ (⊤:α) :=
by simp [is_glb, is_greatest, lower_bounds, upper_bounds]
lemma is_lub_empty [order_bot α] : is_lub ∅ (⊥:α) :=
by simp [is_lub, is_least, lower_bounds, upper_bounds]
lemma is_lub_union_sup [semilattice_sup α] (hs : is_lub s a₁) (ht : is_lub t a₂) :
is_lub (s ∪ t) (a₁ ⊔ a₂) :=
⟨assume c h, h.cases_on (le_sup_left_of_le ∘ hs.left c) (le_sup_right_of_le ∘ ht.left c),
assume c hc, sup_le
(hs.right _ $ assume d hd, hc _ $ or.inl hd) (ht.right _ $ assume d hd, hc _ $ or.inr hd)⟩
lemma is_glb_union_inf [semilattice_inf α] (hs : is_glb s a₁) (ht : is_glb t a₂) :
is_glb (s ∪ t) (a₁ ⊓ a₂) :=
⟨assume c h, h.cases_on (inf_le_left_of_le ∘ hs.left c) (inf_le_right_of_le ∘ ht.left c),
assume c hc, le_inf
(hs.right _ $ assume d hd, hc _ $ or.inl hd) (ht.right _ $ assume d hd, hc _ $ or.inr hd)⟩
lemma is_lub_insert_sup [semilattice_sup α] (h : is_lub s a₁) : is_lub (insert a₂ s) (a₂ ⊔ a₁) :=
by rw [insert_eq]; exact is_lub_union_sup is_lub_singleton h
lemma is_lub_iff_sup_eq [semilattice_sup α] : is_lub {a₁, a₂} a ↔ a₂ ⊔ a₁ = a :=
is_lub_iff_eq_of_is_lub $ is_lub_insert_sup $ is_lub_singleton
lemma is_glb_insert_inf [semilattice_inf α] (h : is_glb s a₁) : is_glb (insert a₂ s) (a₂ ⊓ a₁) :=
by rw [insert_eq]; exact is_glb_union_inf is_glb_singleton h
lemma is_glb_iff_inf_eq [semilattice_inf α] : is_glb {a₁, a₂} a ↔ a₂ ⊓ a₁ = a :=
is_glb_iff_eq_of_is_glb $ is_glb_insert_inf $ is_glb_singleton
end lattice
section complete_lattice
variables [complete_lattice α] {f : ι → α}
lemma is_lub_Sup : is_lub s (Sup s) := and.intro (assume x, le_Sup) (assume x, Sup_le)
lemma is_lub_supr : is_lub (range f) (⨆j, f j) :=
have is_lub (range f) (Sup (range f)), from is_lub_Sup,
by rwa [Sup_range] at this
lemma is_lub_iff_supr_eq : is_lub (range f) a ↔ (⨆j, f j) = a := is_lub_iff_eq_of_is_lub is_lub_supr
lemma is_lub_iff_Sup_eq : is_lub s a ↔ Sup s = a := is_lub_iff_eq_of_is_lub is_lub_Sup
lemma is_glb_Inf : is_glb s (Inf s) := and.intro (assume a, Inf_le) (assume a, le_Inf)
lemma is_glb_infi : is_glb (range f) (⨅j, f j) :=
have is_glb (range f) (Inf (range f)), from is_glb_Inf,
by rwa [Inf_range] at this
lemma is_glb_iff_infi_eq : is_glb (range f) a ↔ (⨅j, f j) = a := is_glb_iff_eq_of_is_glb is_glb_infi
lemma is_glb_iff_Inf_eq : is_glb s a ↔ Inf s = a := is_glb_iff_eq_of_is_glb is_glb_Inf
end complete_lattice
|
[STATEMENT]
lemma analytic_at_ball:
"f analytic_on {z} \<longleftrightarrow> (\<exists>e. 0<e \<and> f holomorphic_on ball z e)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (f analytic_on {z}) = (\<exists>e>0. f holomorphic_on ball z e)
[PROOF STEP]
by (metis analytic_on_def singleton_iff) |
#!/usr/bin/env python3
import sys
import numpy as np
dc = {}
name = sys.argv[1].split('/')
name = name[len(name)-1].split('.')[0]
with open(sys.argv[1]) as f:
for i in f:
i = i.strip().split('\t')
dc.setdefault(i[4],[]).append([i[0],i[1],i[2]])
#
for i in dc:
info = dc[i]
CHR = ''
start = []
end = []
for j in range(len(info)):
CHR = info[j][0]
start.append(int(info[j][1]))
end.append(int(info[j][2]))
left = str(int(np.median(start)))
right = str(int(np.median(end)))
print('\t'.join([CHR,left,right,name+'.'+i,'.','+']))
|
""" Utilities for IGMSurvey code
"""
from __future__ import print_function, absolute_import, division, unicode_literals
import glob
import json
import pdb
import numpy as np
from astropy.coordinates import SkyCoord
from linetools import utils as ltu
from linetools.lists.linelist import LineList
from pyigm.abssys import utils as pyasu
from .igmsurvey import IGMSurvey
# Load here to speed up line making
llist = LineList('ISM')
def load_sys_files(inp, type, ref=None, sys_path=False, build_abs_sys=False, **kwargs):
""" Load up a set of SYS files from the hard-drive (JSON files)
Parameters
----------
inp : str
Name of JSON tarball or if sys_path=True then the path to a folder of JSON files
type : str
type of IGMSystem, e.g. LLS
ref : str, optional
Reference label
sys_path : str, optional
indicates that inp is a path to a set of JSON SYS files
otherwise, inp should be the filename of a tarball of JSON files
build_abs_sys : bool, optional
Build a list of AbsSystem's? Can always be instantiated later
**kwargs :
Passed to system
Returns
-------
survey : IGMSurvey
"""
import tarfile
#
survey = class_by_type(type)(ref=ref)
system = pyasu.class_by_type(type)
if sys_path:
pdb.set_trace() # THIS NEEDS TO BE UPDATED AS WAS DONE FOR THE TARBALL
# Individual files
files = glob.glob(inp+'*.json')
files.sort()
for ifile in files:
tdict = ltu.loadjson(ifile)
abssys = system.from_dict(tdict, linelist=llist)
survey._abs_sys.append(abssys)
else: # tarball
print('Loading systems from {:s}'.format(inp))
tar = tarfile.open(inp,'r:gz')
for member in tar.getmembers():
if '.' not in member.name:
print('Skipping a likely folder: {:s}'.format(member.name))
continue
# Extract
f = tar.extractfile(member)
f = f.read()
f = f.decode('utf-8')
tdict = json.loads(f)
# Add keys (for backwards compatability)
if ('NHI' in tdict.keys()) and ('flag_NHI' not in tdict.keys()):
tdict['flag_NHI'] = 1
# Add to list of dicts
survey._dict[tdict['Name']] = tdict
tar.close()
# Mask
survey.init_mask()
# Set coordinates
ras = [survey._dict[key]['RA'] for key in survey._dict.keys()]
decs = [survey._dict[key]['DEC'] for key in survey._dict.keys()]
survey.coords = SkyCoord(ra=ras, dec=decs, unit='deg')
# Build AbsSystem objects?
if build_abs_sys:
survey.build_all_abs_sys(linelist=llist)
# Generate the data table
print("Building the data Table from the internal dict")
survey.data_from_dict()
# Return
return survey
def class_by_type(type):
""" Enable IGMSurvey init by type
Parameters
----------
type : str
Returns
-------
"""
from .llssurvey import LLSSurvey
from .dlasurvey import DLASurvey
if type == 'LLS':
survey = LLSSurvey
elif type == 'DLA':
survey = DLASurvey
else:
raise IOError("Bad survey type!")
# Return
return survey
def is_not_HILya(wvobs, comps):
"""Given an array of wavelengths, this function returns a boolean array of same shape as
`wvobs` with True for pixels known to be contaminated by non HI Lya absorption given a list
of AbsComponent objects
Parameters
----------
wvobs : Quantity array
Observed wavelength
comp : list of AbsComponent objects
List of abscomponent objects identified
Returns
-------
answer : boolean array
Same shape as `wvobs`. True if there is a identified line that is not HI Lya at
the corresponding wavelength, otherwise False
"""
# loop over component and abslines
cond = False * len(wvobs)
for comp in comps:
for line in comp._abslines:
if line.name != 'HI 1215':
wvlims = line.limits.wvlim
cond_aux = (wvobs >= wvlims[0]) & (wvobs <= wvlims[1])
cond = cond_aux | cond
return np.array(cond).astype(bool)
|
Zhou has appeared in various kinds of media including novels , comic books , and movies . Apart from The Story of Yue Fei and Iron Arm , Golden Sabre , he appears in a novel based around his older martial arts brother , Jin Tai . A recent graphic novel of The Story of Yue Fei , deletes all mythological elements from the storyline and presents it in a historical manner . Instead of traveling from Hebei to Hubei to inspect land , Zhou travels from Shaanxi to Kaifeng City in Henan to visit an old friend who had been promoted to General . While en route to the capital city , Zhou takes note of a great famine plaguing the peasantry and even hears stories of some people resorting to Cannibalism . However , when he arrives in Kaifeng , he sees the empire is wasting money on the construction of large imperial gardens , the court officials Cai Jing and Wang Pu have extravagant residencies , and hears that even eunuchs are rich because they are given high government posts . Upon locating his friend , Zhou is distressed to find him in stocks and shackles and being escorted to the farthest reaches of China by imperial guards . He later learns that the General had accidentally offended some court officials and was sentenced to permanent exile on some trumped up charges . Apparently having little or no money , Zhou decides to visit Wang Ming in Hubei ( mistakenly called Hebei ) and becomes the estate 's tutor .
|
% ~~~ [ Test Cases ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\subsubsection{Test Cases}
Travis CI has been configured to run the test cases for each component with race detection\footnote{Introducing the Go Race Detector: \url{https://blog.golang.org/race-detector}} enabled. In addition to monitoring the status of test cases, this may help identify data race conditions which occur when concurrent code read from and write to the same memory locations.
|
(*******************************************************************)
(* This is part of RelationAlgebra, it is distributed under the *)
(* terms of the GNU Lesser General Public License version 3 *)
(* (see file LICENSE for more details) *)
(* *)
(* Copyright 2012: Damien Pous. (CNRS, LIP - ENS Lyon, UMR 5668) *)
(*******************************************************************)
(** * lsyntax: syntactic model for types structures (monoid operations) *)
Require Export positives comparisons.
Require Import Eqdep.
Require Import monoid.
Set Implicit Arguments.
Set Asymmetric Patterns.
(** * Free syntactic model *)
Section s.
Notation I := positive.
Variable A : Set.
(* [A=positive] for normalisation tactics
[A=positive+lsyntax.expr (ord n)] for KAT proofs
[A=positive+lsyntax.expr positive] for KAT computations (not yet) *)
Variables s t: A -> I.
(** residuated Kleene allegory expressions over a set [A] of
variables, the variables being typed according to the functions [s]
(source) and [t] (target).
The indexing types ([I]) are fixed to be [positive] numbers:
- this is convenient and efficient in practice, for reification
- we need a decidable type to get the untyping theorems without axioms
Note that we include constructors for flat operations
(cup,cap,bot,top,neg): it is not convenient to reuse [lsyntax.expr]
here since we would need to restrict the alphabet under those nodes to
something like [A_(n,m) = { a: A / s a = n /\ t a = m }].
*)
(* TOTHINK: add a phantom/strong dependency on [l] on the expr type ? *)
Inductive expr: I -> I -> Type :=
| e_zer: forall n m, expr n m
| e_top: forall n m, expr n m
| e_one: forall n, expr n n
| e_pls: forall n m, expr n m -> expr n m -> expr n m
| e_cap: forall n m, expr n m -> expr n m -> expr n m
| e_neg: forall n m, expr n m -> expr n m
(* | e_not: forall n, expr n n -> expr n n *)
| e_dot: forall n m p, expr n m -> expr m p -> expr n p
| e_itr: forall n, expr n n -> expr n n
| e_str: forall n, expr n n -> expr n n
| e_cnv: forall n m, expr n m -> expr m n
| e_ldv: forall n m p, expr n m -> expr n p -> expr m p
| e_rdv: forall n m p, expr m n -> expr p n -> expr p m
| e_var: forall a, expr (s a) (t a).
(** level of an expression: the set of operations that appear in that expression *)
Fixpoint e_level n m (x: expr n m): level :=
match x with
| e_zer _ _ => BOT
| e_top _ _ => TOP
| e_one _ => MIN
| e_pls _ _ x y => CUP + e_level x + e_level y
| e_cap _ _ x y => CAP + e_level x + e_level y
| e_neg _ _ x => BL + e_level x
(* negation is ill-defined without the other Boolean operations,
whence the [BL] rather than [NEG] *)
| e_dot _ _ _ x y => e_level x + e_level y
| e_itr _ x => STR + e_level x
| e_str _ x => STR + e_level x
| e_cnv _ _ x => CNV + e_level x
| e_ldv _ _ _ x y
| e_rdv _ _ _ x y => DIV + e_level x + e_level y
| e_var a => MIN
end%level.
Section e.
Context {X: ops} {f': I -> ob X}.
Variable f: forall a, X (f' (s a)) (f' (t a)).
(** interpretation of an expression into an arbitray structure, given
an assignation [f] of the variables (and a interpretation function
[f'] for the types) *)
Fixpoint eval n m (x: expr n m): X (f' n) (f' m) :=
match x with
| e_zer _ _ => 0
| e_top _ _ => top
| e_one _ => 1
| e_pls _ _ x y => eval x + eval y
| e_cap _ _ x y => eval x ^ eval y
| e_neg _ _ x => ! eval x
(* | e_not _ x => eval x ^~ *)
| e_dot _ _ _ x y => eval x * eval y
| e_itr _ x => eval x ^+
| e_str _ x => eval x ^*
| e_cnv _ _ x => eval x `
| e_ldv _ _ _ x y => eval x -o eval y
| e_rdv _ _ _ x y => eval y o- eval x
| e_var a => f a
end.
End e.
Section l.
Variable l: level.
(** * (In)equality of syntactic expressions.
Like in [lsyntax], we use an impredicative encoding to define
(in)equality in the free syntactic model, and we parametrise all
definition with the level [l] at which we want to interpret the
given expressions. *)
Definition e_leq n m (x y: expr n m) :=
forall X (L:laws l X) f' (f: forall a, X (f' (s a)) (f' (t a))), eval f x <== eval f y.
Definition e_weq n m (x y: expr n m) :=
forall X (L:laws l X) f' (f: forall a, X (f' (s a)) (f' (t a))), eval f x == eval f y.
(** by packing syntactic expressions and the above predicates into a
canonical structure for flat operations, and another one for the
other operations, we get all notations for free *)
Canonical Structure expr_lattice_ops n m := {|
car := expr n m;
leq := @e_leq n m;
weq := @e_weq n m;
cup := @e_pls n m;
cap := @e_cap n m;
neg := @e_neg n m;
bot := @e_zer n m;
top := @e_top n m
|}.
Canonical Structure expr_ops := {|
ob := I;
mor := expr_lattice_ops;
dot := e_dot;
one := e_one;
itr := e_itr;
str := e_str;
cnv := e_cnv;
ldv := e_ldv;
rdv := e_rdv
|}.
(** we easily show that we get a model so that we immediately benefit
from all lemmas about the various structures *)
Global Instance expr_lattice_laws n m: lattice.laws l (expr_lattice_ops n m).
Proof.
constructor; try right. constructor.
intros x X L u f. reflexivity.
intros x y z H H' X L u f. transitivity (eval f y); auto.
intros x y. split.
intro H. split; intros X L u f. now apply weq_leq, H. now apply weq_geq, H.
intros [H H'] X L u f. apply antisym; auto.
intros Hl x y z. split.
intro H. split; intros X L u f; specialize (H X L u f); simpl in H; hlattice.
intros [H H'] X L u f. simpl. apply cup_spec; auto.
intros Hl x y z. split.
intro H. split; intros X L u f; specialize (H X L u f); simpl in H; hlattice.
intros [H H'] X L u f. simpl. apply cap_spec; auto.
intros x X L u f. apply leq_bx.
intros x X L u f. apply leq_xt.
intros Hl x y z X L u f. apply cupcap_.
intros Hl x X L u f. apply capneg.
intros Hl x X L u f. apply cupneg.
Qed.
Global Instance expr_laws: laws l expr_ops.
Proof.
constructor; repeat right; repeat intro; simpl.
apply expr_lattice_laws.
apply dotA.
apply dot1x.
apply dotx1.
apply dot_leq; auto.
now rewrite dotplsx.
now rewrite dotxpls.
now rewrite dot0x.
now rewrite dotx0.
apply cnvdot_.
apply cnv_invol.
apply cnv_leq. now refine (H0 _ _ _ _).
apply cnv_ext.
apply str_refl.
apply str_cons.
apply str_ind_l. now refine (H0 _ _ _ _).
apply str_ind_r. now refine (H0 _ _ _ _).
apply itr_str_l.
apply capdotx.
split; intros E X L f' f; intros; simpl; apply ldv_spec, (E X L f' f).
split; intros E X L f' f; intros; simpl; apply rdv_spec, (E X L f' f).
Qed.
End l.
(** * Testing for particular constants *)
Definition is_zer n m (x: expr n m) :=
match x with e_zer _ _ => true | _ => false end.
Definition is_top n m (x: expr n m) :=
match x with e_top _ _ => true | _ => false end.
Inductive is_case n m (k x: expr n m): expr n m -> bool -> Prop :=
| is_case_true: x=k -> is_case k x k true
| is_case_false: x<>k -> is_case k x x false.
Lemma is_zer_spec n m (x: expr n m): is_case (e_zer n m) x x (is_zer x).
Proof. destruct x; constructor; discriminate || reflexivity. Qed.
Lemma is_top_spec n m (x: expr n m): is_case (e_top n m) x x (is_top x).
Proof. destruct x; constructor; discriminate || reflexivity. Qed.
(** casting the type of an expression *)
Definition cast n m n' m' (Hn: n=n') (Hm: m=m') (x: expr n m): expr n' m' :=
eq_rect n (fun n => expr n m') (eq_rect m (expr n) x _ Hm) _ Hn.
End s.
Arguments e_var [A s t] a.
Arguments e_one [A s t] n.
Arguments e_zer [A s t] n m.
Arguments e_top [A s t] n m.
Bind Scope ast_scope with expr.
Delimit Scope ast_scope with ast.
(** additional notations, to specify explicitly at which level
expressions are considered, or to work directly with the
bare constructors (by opposition with the encapsulated ones,
through monoid.ops) *)
Notation expr_ l s t n m := (expr_ops s t l n m).
Notation "x <==_[ l ] y" := (@leq (expr_ops _ _ l _ _) x y) (at level 79): ra_scope.
Notation "x ==_[ l ] y" := (@weq (expr_ops _ _ l _ _) x y) (at level 79): ra_scope.
Infix "+" := e_pls: ast_scope.
Infix "^" := e_cap: ast_scope.
Infix "*" := e_dot: ast_scope.
Notation "1" := (e_one _): ast_scope.
Notation "0" := (e_zer _ _): ast_scope.
Notation top := (e_top _ _).
Notation "x ^+" := (e_itr x): ast_scope.
Notation "x `" := (e_cnv x): ast_scope.
Notation "x ^*" := (e_str x): ast_scope.
Notation "! x" := (e_neg x): ast_scope.
Notation "x -o y" := (e_ldv x y) (right associativity, at level 60): ast_scope.
Notation "y o- x" := (e_rdv x y) (left associativity, at level 61): ast_scope.
(** * weakening (in)equations *)
(** any equation holding at some level holds at all higher levels *)
Lemma e_leq_weaken {h k} {Hl: h<<k} A s t n m (x y: @expr A s t n m):
x <==_[h] y -> x <==_[k] y.
Proof. intros H X L f' f. eapply @H, lower_laws. Qed.
Lemma e_weq_weaken {h k} {Hl: h<<k} A s t n m (x y: @expr A s t n m):
x ==_[h] y -> x ==_[k] y.
Proof. intros H X L f' f. eapply @H, lower_laws. Qed.
(** * comparing expressions syntactically *)
Section expr_cmp.
Notation I := positive.
Context {A : cmpType}.
Variables s t: A -> I.
Notation expr := (expr s t).
(** we need to generalise the comparison function to expressions of
distinct types because of Coq's dependent types *)
Fixpoint expr_compare n m (x: expr n m) p q (y: expr p q) :=
match x,y with
| e_zer _ _, e_zer _ _
| e_top _ _, e_top _ _
| e_one _, e_one _ => Eq
| e_var a, e_var b => cmp a b
| e_pls _ _ x x', e_pls _ _ y y'
| e_cap _ _ x x', e_cap _ _ y y' =>
lex (expr_compare x y) (expr_compare x' y')
| e_dot _ u _ x x', e_dot _ v _ y y'
| e_ldv u _ _ x x', e_ldv v _ _ y y'
| e_rdv u _ _ x x', e_rdv v _ _ y y' =>
lex (cmp u v) (lex (expr_compare x y) (expr_compare x' y'))
| e_neg _ _ x, e_neg _ _ y
| e_itr _ x, e_itr _ y
| e_str _ x, e_str _ y
| e_cnv _ _ x, e_cnv _ _ y => expr_compare x y
| e_zer _ _, _ => Lt
| _, e_zer _ _ => Gt
| e_one _, _ => Lt
| _, e_one _ => Gt
| e_top _ _, _ => Lt
| _, e_top _ _ => Gt
| e_var _, _ => Lt
| _, e_var _ => Gt
| e_itr _ _, _ => Lt
| _, e_itr _ _ => Gt
| e_str _ _, _ => Lt
| _, e_str _ _ => Gt
| e_cnv _ _ _, _ => Lt
| _, e_cnv _ _ _ => Gt
| e_ldv _ _ _ _ _, _ => Lt
| _, e_ldv _ _ _ _ _ => Gt
| e_rdv _ _ _ _ _, _ => Lt
| _, e_rdv _ _ _ _ _ => Gt
| e_pls _ _ _ _, _ => Lt
| _, e_pls _ _ _ _ => Gt
| e_cap _ _ _ _, _ => Lt
| _, e_cap _ _ _ _ => Gt
| e_neg _ _ _, _ => Lt
| _, e_neg _ _ _ => Gt
end.
(** since [A] is decidable, [cast] provably acts as an identity *)
Lemma cast_eq n m (x: expr n m) (H: n=n) (H': m=m): cast H H' x = x.
Proof. unfold cast. now rewrite 2 cmp_eq_rect_eq. Qed.
(** auxiliary lemma for [expr_compare_spec] below, using dependent equality *)
Lemma expr_compare_eq_dep n m (x: expr n m): forall p q (y: expr p q),
expr_compare x y = Eq -> n=p -> m=q ->
eq_dep (I*I) (fun x => expr (fst x) (snd x)) (n,m) x (p,q) y.
Proof.
induction x; intros ? ? z C; destruct z; try discriminate C;
try (intros <- <- || intros <- _); try reflexivity;
simpl expr_compare in C.
apply compare_lex_eq in C as [C1 C2].
apply IHx1, cmp_eq_dep_eq in C1; trivial.
apply IHx2, cmp_eq_dep_eq in C2; trivial.
subst. reflexivity.
apply compare_lex_eq in C as [C1 C2].
apply IHx1, cmp_eq_dep_eq in C1; trivial.
apply IHx2, cmp_eq_dep_eq in C2; trivial.
subst. reflexivity.
apply IHx, cmp_eq_dep_eq in C; trivial. subst. reflexivity.
apply compare_lex_eq in C as [C C']. apply cmp_eq in C. subst.
apply compare_lex_eq in C' as [C1 C2].
apply IHx1, cmp_eq_dep_eq in C1; trivial.
apply IHx2, cmp_eq_dep_eq in C2; trivial.
subst. reflexivity.
apply IHx, cmp_eq_dep_eq in C; trivial. subst. reflexivity.
apply IHx, cmp_eq_dep_eq in C; trivial. subst. reflexivity.
apply IHx, cmp_eq_dep_eq in C; trivial. subst. reflexivity.
apply compare_lex_eq in C as [C C']. apply cmp_eq in C. subst.
apply compare_lex_eq in C' as [C1 C2].
apply IHx1, cmp_eq_dep_eq in C1; trivial.
apply IHx2, cmp_eq_dep_eq in C2; trivial.
subst. reflexivity.
apply compare_lex_eq in C as [C C']. apply cmp_eq in C. subst.
apply compare_lex_eq in C' as [C1 C2].
apply IHx1, cmp_eq_dep_eq in C1; trivial.
apply IHx2, cmp_eq_dep_eq in C2; trivial.
subst. reflexivity.
apply cmp_eq in C. subst. reflexivity.
Qed.
Lemma expr_compare_eq n m (x y: expr n m): x=y -> expr_compare x y = Eq.
Proof.
intros <-. induction x; simpl expr_compare; trivial;
rewrite ?compare_lex_eq, ?cmp_refl; tauto.
Qed.
(** final specification of the comparison function *)
Lemma expr_compare_spec n m (x y: expr n m): compare_spec (x=y) (expr_compare x y).
Proof.
generalize (fun H => expr_compare_eq_dep x y H eq_refl eq_refl) as H.
generalize (@expr_compare_eq _ _ x y) as H'.
case (expr_compare x y); intros H' H; constructor.
now apply cmp_eq_dep_eq in H.
intro E. now discriminate H'.
intro E. now discriminate H'.
Qed.
(** packaging as a [cmpType] *)
Definition expr_compare_ n m (x y: expr n m) := expr_compare x y.
Canonical Structure cmp_expr n m := mk_simple_cmp (@expr_compare_ n m) (@expr_compare_spec n m).
End expr_cmp.
(** * Packages for typed reification *)
(** according to the interpretation function [eval], (typed)
reification has to provide a set [A] for indexing variables, and four maps:
- [f': I -> ob X], to interpret types as written in the expressions ([I=positive])
- [s] and [t]: A -> I, to specify the source and target types of each variable
- [f: forall a: A, expr s t (s a) (t a)], to interpret each variable
[A] is also fixed to be [positive], so that we can use simple and
efficient positive maps, but the fact that [f] has a dependent type
is not convenient.
This is why we introduce the additionnal layer, to ease the
definition of such maps: thanks to the definitions below, it
suffices to provide the map [f'], and a map [f: A -> Pack X f']. *)
Record Pack (X: ops) (f': positive -> ob X) := pack {
src: positive;
tgt: positive;
val: X (f' src) (f' tgt)
}.
Definition packed_eval (X: ops) (f': positive -> ob X) (f: positive -> Pack X f') :=
eval (fun a => val (f a)) : forall n m, expr _ _ n m -> X (f' n) (f' m) .
(** these projections are used to build the reified expressions *)
Definition src_ (X: ops) (f': positive -> ob X) (f: positive -> Pack X f') a := src (f a).
Definition tgt_ (X: ops) (f': positive -> ob X) (f: positive -> Pack X f') a := tgt (f a).
(** loading ML reification module *)
Declare ML Module "ra_reification".
|
This pier cabinet features a modern design with three open shelves and one door storage at the bottom with metal handle on right side. Enough spacing between the shelves allows you to place media components or other accents easily. Sturdily made up of metal and has finished look in brushed silver color. The metal cabinet at the bottom has slight corrugated effect with bucket handle pull on right side. It also has block metal feet offers a raw feel to this piece. This will go with any theme or color interior. |
-- Equality of terms
module Syntax.Equality where
open import Syntax.Types
open import Syntax.Context
open import Syntax.Terms
open import Syntax.Substitution.Kits
open import Syntax.Substitution.Instances
open import Syntax.Substitution.Lemmas
open Kit 𝒯erm
-- Shorthands for de Bruijn indices
x₁ : ∀{Γ A} -> Γ , A now ⊢ A now
x₁ = var top
x₂ : ∀{Γ A B} -> Γ , A now , B ⊢ A now
x₂ = var (pop top)
x₃ : ∀{Γ A B C} -> Γ , A now , B , C ⊢ A now
x₃ = var (pop (pop top))
x₄ : ∀{Γ A B C D} -> Γ , A now , B , C , D ⊢ A now
x₄ = var (pop (pop (pop top)))
s₁ : ∀{Γ A} -> Γ , A always ⊢ A always
s₁ = var top
s₂ : ∀{Γ A B} -> Γ , A always , B ⊢ A always
s₂ = var (pop top)
s₃ : ∀{Γ A B C} -> Γ , A always , B , C ⊢ A always
s₃ = var (pop (pop top))
s₄ : ∀{Γ A B C D} -> Γ , A always , B , C , D ⊢ A always
s₄ = var (pop (pop (pop top)))
-- β-η equality of terms
data Eq (Γ : Context) : (A : Judgement) -> Γ ⊢ A -> Γ ⊢ A -> Set
data Eq′ (Γ : Context) : (A : Judgement) -> Γ ⊨ A -> Γ ⊨ A -> Set
syntax Eq Γ A M N = Γ ⊢ M ≡ N ∷ A
syntax Eq′ Γ A M N = Γ ⊨ M ≡ N ∷ A
data Eq Γ where
-- | Equivalence relation
-- Reflexivity
refl : ∀{A} -> (M : Γ ⊢ A)
---------------
-> Γ ⊢ M ≡ M ∷ A
-- Symmetry
sym : ∀{A}{M₁ M₂ : Γ ⊢ A}
-> Γ ⊢ M₁ ≡ M₂ ∷ A
-----------------
-> Γ ⊢ M₂ ≡ M₁ ∷ A
-- Transitivity
trans : ∀{A}{M₁ M₂ M₃ : Γ ⊢ A}
-> Γ ⊢ M₁ ≡ M₂ ∷ A -> Γ ⊢ M₂ ≡ M₃ ∷ A
-----------------------------------------
-> Γ ⊢ M₁ ≡ M₃ ∷ A
-- | β-equality
-- β-reduction for function application
β-lam : ∀{A B} -> (N : Γ , A now ⊢ B now) (M : Γ ⊢ A now)
-------------------------------------------
-> Γ ⊢ (lam N) $ M ≡ [ M /] N ∷ B now
-- β-reduction for first projection
β-fst : ∀{A B} -> (M : Γ ⊢ A now) (N : Γ ⊢ B now)
-----------------------------------
-> Γ ⊢ fst [ M ,, N ] ≡ M ∷ A now
-- β-reduction for second projection
β-snd : ∀{A B} -> (M : Γ ⊢ A now) (N : Γ ⊢ B now)
-----------------------------------
-> Γ ⊢ snd [ M ,, N ] ≡ N ∷ B now
-- β-reduction for case split on first injection
β-inl : ∀{A B C} -> (M : Γ ⊢ A now)
(N₁ : Γ , A now ⊢ C now) (N₂ : Γ , B now ⊢ C now)
---------------------------------------------------
-> Γ ⊢ case (inl M) inl↦ N₁
||inr↦ N₂ ≡ [ M /] N₁ ∷ C now
-- β-reduction for case split on first injection
β-inr : ∀{A B C} -> (M : Γ ⊢ B now)
(N₁ : Γ , A now ⊢ C now) (N₂ : Γ , B now ⊢ C now)
---------------------------------------------------
-> Γ ⊢ case (inr M) inl↦ N₁
||inr↦ N₂ ≡ [ M /] N₂ ∷ C now
-- β-reduction for signal binding
β-sig : ∀{A B} -> (N : Γ , A always ⊢ B now) (M : Γ ⊢ A always)
--------------------------------------------------
-> Γ ⊢ letSig (sig M) In N ≡ [ M /] N ∷ B now
-- | η-equality
-- η-expansion for functions
η-lam : ∀{A B} -> (M : Γ ⊢ A => B now)
--------------------------------------
-> Γ ⊢ M ≡ lam (𝓌 M $ x₁) ∷ A => B now
-- η-expansion for pairs
η-pair : ∀{A B} -> (M : Γ ⊢ A & B now)
----------------------------------------
-> Γ ⊢ M ≡ [ fst M ,, snd M ] ∷ A & B now
-- η-expansion for unit
η-unit : (M : Γ ⊢ Unit now)
-------------------------
-> Γ ⊢ M ≡ unit ∷ Unit now
-- η-expansion for sums
η-sum : ∀{A B} -> (M : Γ ⊢ A + B now)
------------------------------------------
-> Γ ⊢ M ≡ case M inl↦ inl x₁
||inr↦ inr x₁ ∷ A + B now
-- η-expansion for signals
η-sig : ∀{A} -> (M : Γ ⊢ Signal A now)
-------------------------------------------
-> Γ ⊢ M ≡ letSig M In (sig s₁) ∷ Signal A now
-- η-expansion for events in computational terms
η-evt : ∀{A} -> (M : Γ ⊢ Event A now)
----------------------------------------------------
-> Γ ⊢ M ≡ event (letEvt M In pure x₁) ∷ Event A now
-- | Congruence rules
-- Congruence in pairs
cong-pair : ∀{A B}{M₁ M₂ : Γ ⊢ A now}{N₁ N₂ : Γ ⊢ B now}
-> Γ ⊢ M₁ ≡ M₂ ∷ A now -> Γ ⊢ N₁ ≡ N₂ ∷ B now
------------------------------------------------
-> Γ ⊢ [ M₁ ,, N₁ ] ≡ [ M₂ ,, N₂ ] ∷ A & B now
-- Congruence in first projection
cong-fst : ∀{A B}{M₁ M₂ : Γ ⊢ A & B now}
-> Γ ⊢ M₁ ≡ M₂ ∷ A & B now
------------------------------
-> Γ ⊢ fst M₁ ≡ fst M₂ ∷ A now
-- Congruence in second projection
cong-snd : ∀{A B}{M₁ M₂ : Γ ⊢ A & B now}
-> Γ ⊢ M₁ ≡ M₂ ∷ A & B now
------------------------------
-> Γ ⊢ snd M₁ ≡ snd M₂ ∷ B now
-- Congruence in lambda body
cong-lam : ∀{A B}{M₁ M₂ : Γ , A now ⊢ B now}
-> Γ , A now ⊢ M₁ ≡ M₂ ∷ B now
----------------------------------
-> Γ ⊢ lam M₁ ≡ lam M₂ ∷ A => B now
-- Congruence in application
cong-app : ∀{A B}{N₁ N₂ : Γ ⊢ A => B now}{M₁ M₂ : Γ ⊢ A now}
-> Γ ⊢ N₁ ≡ N₂ ∷ A => B now -> Γ ⊢ M₁ ≡ M₂ ∷ A now
---------------------------------------------------
-> Γ ⊢ N₁ $ M₁ ≡ N₂ $ M₂ ∷ B now
-- Congruence in case split
cong-case : ∀{A B C}{M₁ M₂ : Γ ⊢ A + B now}
-> Γ ⊢ M₁ ≡ M₂ ∷ A + B now
-> (N₁ : Γ , A now ⊢ C now) (N₂ : Γ , B now ⊢ C now)
---------------------------------------------------
-> Γ ⊢ case M₁ inl↦ N₁ ||inr↦ N₂
≡ case M₂ inl↦ N₁ ||inr↦ N₂ ∷ C now
-- Congruence in first injection
cong-inl : ∀{A B}{M₁ M₂ : Γ ⊢ A now}
-> Γ ⊢ M₁ ≡ M₂ ∷ A now
------------------------------------
-> Γ ⊢ inl M₁ ≡ inl M₂ ∷ A + B now
-- Congruence in second injection
cong-inr : ∀{A B}{M₁ M₂ : Γ ⊢ B now}
-> Γ ⊢ M₁ ≡ M₂ ∷ B now
------------------------------------
-> Γ ⊢ inr M₁ ≡ inr M₂ ∷ A + B now
-- Congruence in signal constructor
cong-sig : ∀{A}{M₁ M₂ : Γ ⊢ A always}
-> Γ ⊢ M₁ ≡ M₂ ∷ A always
------------------------------------
-> Γ ⊢ sig M₁ ≡ sig M₂ ∷ Signal A now
-- Congruence in signal binding
cong-letSig : ∀{A B}{S₁ S₂ : Γ ⊢ Signal A now}
-> Γ ⊢ S₁ ≡ S₂ ∷ Signal A now
-> (N : Γ , A always ⊢ B now)
---------------------------------------------
-> Γ ⊢ letSig S₁ In N ≡ letSig S₂ In N ∷ B now
-- Congruence in sampling
cong-sample : ∀{A}{M₁ M₂ : Γ ⊢ A always}
-> Γ ⊢ M₁ ≡ M₂ ∷ A always
-------------------------------------
-> Γ ⊢ sample M₁ ≡ sample M₂ ∷ A now
-- Congruence in stabilisation
cong-stable : ∀{A}{M₁ M₂ : Γ ˢ ⊢ A now}
-> Γ ˢ ⊢ M₁ ≡ M₂ ∷ A now
-------------------------------------
-> Γ ⊢ stable M₁ ≡ stable M₂ ∷ A always
-- Congruence in events
cong-event : ∀{A}{E₁ E₂ : Γ ⊨ A now}
-> Γ ⊨ E₁ ≡ E₂ ∷ A now
-------------------------------------
-> Γ ⊢ event E₁ ≡ event E₂ ∷ Event A now
data Eq′ (Γ : Context) where
-- | Equivalence relation
-- Reflexivity
refl : ∀{A} -> (M : Γ ⊨ A)
---------------
-> Γ ⊨ M ≡ M ∷ A
-- Symmetry
sym : ∀{A}{M₁ M₂ : Γ ⊨ A}
-> Γ ⊨ M₁ ≡ M₂ ∷ A
-----------------
-> Γ ⊨ M₂ ≡ M₁ ∷ A
-- Transitivity
trans : ∀{A}{M₁ M₂ M₃ : Γ ⊨ A}
-> Γ ⊨ M₁ ≡ M₂ ∷ A -> Γ ⊨ M₂ ≡ M₃ ∷ A
-----------------------------------------
-> Γ ⊨ M₁ ≡ M₃ ∷ A
-- | β-equality
-- β-reduction for signal binding in computational terms
β-sig′ : ∀{A B} -> (C : Γ , A always ⊨ B now) (M : Γ ⊢ A always)
--------------------------------------------------
-> Γ ⊨ letSig (sig M) InC C ≡ [ M /′] C ∷ B now
-- β-reduction for event binding in computational terms
β-evt′ : ∀{A B} -> (C : Γ ˢ , A now ⊨ B now) (D : Γ ⊨ A now)
---------------------------------------------
-> Γ ⊨ letEvt (event D) In C ≡ ⟨ D /⟩ C ∷ B now
-- β-reduction for event binding in computational terms
β-selectₚ : ∀{A B C} -> (C₁ : Γ ˢ , A now , Event B now ⊨ C now)
(C₂ : Γ ˢ , Event A now , B now ⊨ C now)
(C₃ : Γ ˢ , A now , B now ⊨ C now)
(M₁ : Γ ⊢ A now) (M₂ : Γ ⊢ B now)
---------------------------------------------
-> Γ ⊨ select event (pure M₁) ↦ C₁
|| event (pure M₂) ↦ C₂
||both↦ C₃
≡ [ M₁ /′] ([ 𝓌 M₂ /′]
(weakening′ (keep (keep (Γˢ⊆Γ Γ))) C₃)) ∷ C now
-- | η-equality
-- η-expansion for signals in computational terms
η-sig′ : ∀{A} -> (M : Γ ⊢ Signal A now)
--------------------------------------------------------
-> Γ ⊨ pure M ≡ letSig M InC (pure (sig s₁)) ∷ Signal A now
-- | Congruence rules
-- Congruence in pure computational term
cong-pure′ : ∀{A}{M₁ M₂ : Γ ⊢ A}
-> Γ ⊢ M₁ ≡ M₂ ∷ A
---------------------------
-> Γ ⊨ pure M₁ ≡ pure M₂ ∷ A
-- Congruence in signal binding
cong-letSig′ : ∀{A B}{S₁ S₂ : Γ ⊢ Signal A now}
-> Γ ⊢ S₁ ≡ S₂ ∷ Signal A now
-> (N : Γ , A always ⊨ B now)
-----------------------------------------------
-> Γ ⊨ letSig S₁ InC N ≡ letSig S₂ InC N ∷ B now
-- Congruence in event binding
cong-letEvt′ : ∀{A B}{E₁ E₂ : Γ ⊢ Event A now}
-> Γ ⊢ E₁ ≡ E₂ ∷ Event A now
-> (D : Γ ˢ , A now ⊨ B now)
-----------------------------------------------
-> Γ ⊨ letEvt E₁ In D ≡ letEvt E₂ In D ∷ B now
test : ∀{A} -> ∙ ⊢ (Signal A => A) now
test = lam (letSig x₁ In sample s₁)
tes : ∀{A} -> ∙ ⊢ (Signal A => Signal (Signal A)) now
tes = lam (letSig x₁ In sig (stable (sig s₁)))
te : ∀{A} -> ∙ ⊢ (A => Event A) now
te = lam (event (pure x₁))
t2 : ∀{A} -> ∙ ⊢ (Signal A) now -> ∙ ⊢ A always
t2 M = stable (letSig M In sample s₁)
t : ∀{A} -> ∙ ⊢ (Event (Event A) => Event A) now
t = lam (event (letEvt x₁ In (letEvt x₁ In pure x₁)))
t3 : ∀{A B} -> ∙ ⊢ (Event A => Signal (A => Event B) => Event B) now
t3 = lam (lam
(letSig x₁ In (event
(letEvt x₃ In
(letEvt (sample s₂ $ x₁) In pure x₁)))))
-- t4 : ∀{A B C} -> ∙ ⊢ (Event A => Event B => Signal (A => Event C) => Signal (B => Event C) => Event C) now
-- t4 = lam (lam (lam (lam (
-- letSig x₂ In (
-- letSig x₂ In (event (
-- select (var (pop (pop (pop (pop (pop top)))))) ↦ letEvt sample s₄ $ x₁ In pure x₁
-- || (var (pop (pop (pop (pop top))))) ↦ letEvt (sample s₃ $ x₁) In pure x₁
-- ||both↦ {! !})))))))
t5 : ∀{A B} -> ∙ , Signal A now , Event (A => B) now ⊨ B now
t5 = letSig (var (pop top)) InC (letEvt (var (pop top)) In pure (x₁ $ sample s₂))
t6 : ∀{A B} -> ∙ , Event (Signal A) now , Signal B now ⊢ Event (Signal (A & B)) now
t6 = event (letSig x₁ InC (letEvt x₃ In (pure (letSig x₁ In (sig (stable [ sample s₁ ,, sample s₂ ]))))))
-- t6 = event (letSig x₁ InC (letEvt x₃ In (letSig x₁ InC (pure [ sample s₁ ,, sample s₃ ]))))
too : ∀{A B} -> ∙ ⊢ Signal (A => B) => (Event A => Event B) now
too = lam (lam (letSig x₂ In event (letEvt x₂ In pure (sample s₂ $ x₁))))
|
\subsection{\stid{2} \tools}\label{subsect:tools}
\textbf{End State:} A suite of compilers and development tools aimed at improving developer productivity across increasingly complex heterogeneous architectures, primarily focused on those architectures expected for the upcoming Exascale platforms of Frontier and Aurora.
\subsubsection{Scope and Requirements}
For Exascale systems, the compilers, profilers, debuggers, and other software development tools must be increasingly sophisticated to give software developers insight into the behavior of not only the application and the underlying hardware but also the details corresponding to the underlying programming model implementation and supporting runtimes (e.g., capturing details of locality and affinity). These capabilities should be enhanced with further integration into the supporting compiler infrastructure and lower layers of the system software stack (e.g., threading, runtime systems, and data transport libraries), and hardware support. Most of the infrastructure will be released as open source, as many of them already are, with a supplementary goal of transferring the technology into commercial products (including reuse by vendors of ECP enhancements to LLVM, such as Fortran/Flang, or direct distributions by vendors of software on platforms). Given the diversity of Exascale systems architectures, some subset of the tools may be specific to one or more architectural features and is potentially best implemented and supported by the vendor; however, the vendor will be encouraged to use open APIs to provide portability, additional innovation, and integration into the tool suite and the overall software stack.
\subsubsection{Assumptions and Feasibility }
The overarching goal of improving developer productivity for Exascale platforms introduces new issues of scale that will require more lightweight methods, hierarchical approaches, and improved techniques to guide the developer in understanding the characteristics of their applications and to discover sources of the errors and performance issues. Additional efforts for both static and dynamic analysis tools to help identify lurking bugs in a program, such as race conditions, are also likely needed. The suite of needed capabilities spans interfaces to hardware-centric resources (e.g., hardware counters, interconnects, and memory hierarchies) to a scalable infrastructure that can collect, organize, and distill data to help identify performance bottlenecks and transform them into an actionable set of steps and information for the software developer. Therefore, these tools share significant challenges due to the increase in data and the resulting issues with management, storage, selection, analysis, and interactive data exploration. This increased data volume stems from multiple sources, including increased concurrency, processor counts, additional hardware sensors and counters on the systems, and increasing complexity in application codes and workflows.
Compilers obviously play a fundamental role in the overall programming environment but can also serve as a powerful entry point for the overall tool infrastructure. In addition to optimizations and performance profiling, compiler-based tools can help with aspects of correctness, establishing connections between programming model implementations and the underlying runtime infrastructures, and auto-tuning. In many cases, today's compiler infrastructure is proprietary and closed source, limiting the amount of flexibility for integration and exploration into the Exascale development environment. In addition to vendor compiler options, this project aims to provide an open source compiler capability (via the LLVM ecosystem) that can play a role in better supporting and addressing the challenges of programming at Exascale.
\subsubsection{Objectives}
This project will design, develop, and deploy an Exascale suite of compilers and development tools for development, analysis, and optimization of applications, libraries, and infrastructure from the programming environments of the project.
The project will seek to leverage techniques for common and identified problem patterns and create new techniques for data exploration related to profiling and debugging and support advanced techniques such as autotuning and compiler integration.
We will leverage the open-source LLVM compiler ecosystem.
For tools, the overarching goal is to leverage and integrate the data measurement, acquisition, storage, and analysis and visualization techniques being developed in other projects of the software stack.
These efforts will require collaboration and integration with system monitoring and various layers within the software stack.
\subsubsection{Plan}
Multiple projects will be supported under this effort. To ensure relevance to DOE missions, a majority of these efforts shall be DOE laboratory led, and collaborate with existing activities within the broader HPC community.
Initial efforts will focus on identifying the core capabilities needed by the selected ECP applications, components of the software stack, expected hardware features, and the selected industry activities from within the Hardware and Integration focus area.
The supported projects will target and implement early versions of their software on both CORAL and APEX systems, with an ultimate target of production-ready deployment on Frontier and Aurora.
Throughout this effort the, applications teams and other elements of the software stack will evaluate and provide feedback on their functionality, performance, and robustness.
These goals will be evaluated annually at the ST reviews and for milestones.
\subsubsection{Risk and Mitigation Strategies}
A primary risk exists in terms of adoption of the various tools by the broader community, including support by system vendors. Past experience has shown that a combination of laboratory-supported open source software and vendor-optimized solutions built around standard APIs that encourage innovation across multiple platforms is a viable approach, and this will be undertaken.
We will track this risk primarily via the risk register.
Given its wide use within a range of different communities, and its modular design principles, the project's open source compiler activities will focus on the use of the LLVM compiler ecosystem (\url{https://llvm.org/}) as a path to reduce both scope and complexity risks and leverage with an already established path for NRE investments across multiple vendors.
The compilers and their effectiveness are tracked in the risk register.
%
In fact, in 2020, we created a fork of the \texttt{llvm-project} upstream repository (see \url{https://github.com/llvm-doe-org}) to capture, integrate, and test LLVM projects. This repo also serves as a risk mitigation option that can be easily enabled if other compilers are not working successfully on the target platforms.
Another major risk for projects in this area is the lack of low-level access to hardware and software necessary for using emerging architectural features. Many of these nascent architectural features have immature implementations and software interfaces that must be refined prior to release to the broader community. This project should be at the forefront of this interaction with early delivery systems. This risk is also tracked in the risk register for compilers, which are particularly vulnerable.
\subsubsection{Future Trends}
Future architectures are becoming more heterogeneous and complex~\cite{vetter:2018:extreme}. As such, the role of languages, compilers, runtime systems, and performance and debugging tools will becoming increasingly important for productivity and performance portability.
%
In particular, our ECP strategy focuses on improving the open source LLVM compiler and runtime ecosystem; LLVM has gained considerable traction in the vendor software community, and it is the core of many existing heterogeneous compiler systems from NVIDIA, AMD, Intel, ARM, IBM, and others.
Over the past two years, several vendors including IBM and Intel have abandoned their proprietary compiler software in favor of LLVM.
We foresee that this trend will continue, which is why we have organized the \tools\ technical area around LLVM-oriented projects.
%
We expect for many of our contributions to LLVM to address these trends for the entire community and will persist long after ECP ends.
%
For example, our contributions for directive-based features for heterogeneous computing (e.g., OpenMP, OpenACC) will not only provide direct capabilities to ECP applications, but it will also impact the redesign and optimization of the LLVM infrastructure to support heterogeneous computing.
%
In a second example, Flang (open source Fortran compiler for LLVM; [the second version is also known as F18]) will become increasingly important to the worldwide Fortran application base, as vendors find it easier to maintain and deploy to their own Fortran frontend (based on Flang).
%
Furthermore, as Flang become increasingly robust, researchers and vendors developing new architectures will have immediate access to Flang, making initial Fortran support straightforward in ways similar to what we are seeing in Clang as the community C/C++ frontend.
%
|
\documentclass[12pt]{report}
% packages used for many things
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{hyperref}
\hypersetup{
colorlinks=true,
linkcolor=blue,
filecolor=magenta,
urlcolor=cyan,
}
\urlstyle{same}
\usepackage{enumitem}
\usepackage{amsmath}
\usepackage{mathtools}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{MnSymbol}
\usepackage{csquotes}
\usepackage{arydshln}
\usepackage{algorithm}
\usepackage{algorithmic}
\usepackage{extarrows}
\usepackage{tikz}
\usepackage{comment}
% declare here the expectation symbol
\DeclareMathOperator{\E}{\mathbb{E}}
% argmin operator
\DeclareMathOperator*{\argmin}{\arg\!\min}
% for text over equal sign
\newcommand\prone{\mathrel{\overset{\makebox[0pt]
{\mbox{\normalfont\tiny\sffamily (1)}}}{=}}}
\newcommand\prtwo{\mathrel{\overset{\makebox[0pt]
{\mbox{\normalfont\tiny\sffamily (2)}}}{=}}}
\newcommand\prthr{\mathrel{\overset{\makebox[0pt]
{\mbox{\normalfont\tiny\sffamily (3)}}}{=}}}
% for images
\usepackage{graphicx}
\graphicspath{{./images/}}
% qed black square
\newcommand*{\QEDA}{\hfill\ensuremath{\blacksquare}}
% Author of this mathematical analysis
\begin{comment}
@ Author: Andreas Spanopoulos
\end{comment}
% title, date, etc..
\title{Variational Autoencoder Mathematics}
\author{\LARGE{Andreas Spanopoulos} \\ [email protected] \\ \\
\LARGE{Dimitrios Konstantinidis} \\ [email protected] \\}
% ---------------- START OF DOCUMENT ------------ %
\begin{document}
\maketitle
% -------------------- PAGE 1 ---------------------- %
\section*{Introduction}
\smallskip
The \textbf{Variational Autoencoder} (aka \textbf{VAE}) is a generative model.
This means that it is a model which produces new unseen data. Unlike the normal
Autoencoder, VAE focuses on understanding the distribution of a smaller
representation of the data. This lower-dimensional representation of the data is
known as \textquote{latent vector $\textbf{z}$}.
\bigskip
The dimension of the latent vector z is a hyperparameter which we choose along
with the architecture of the Network. Keep in mind that we don't want
$\textbf{z}$ to be too large. It should be a relatively small vector, so that an
information bottleneck is created. One other reason for $\textbf{z}$ being small,
is that we want to be able to sample easily new vectors, without having to take
into consideration many features.
\bigskip
With that said, the question arises: How can we pick the values of $\textbf{z}$
which will make sense, that is, which will generate a new data point from the
distribution of our original data?
\bigskip
Here is the beauty of the \textbf{Variational Autoencoder}: We will learn the
distribution of $\textbf{z}$. That is, for every component of $\textbf{z}$, we
will learn a mean and a standard deviation.
\bigskip
Suppose $\textbf{z}$ has $k$ components:
\begin{align*}
z \;=\;
\begin{bmatrix}
z_1 \\
z_2 \\
\vdots \\
z_k
\end{bmatrix}
\end{align*}
Then, the mean and standard deviation vectors are defined as:
\begin{align*}
\mu \;=\;
\begin{bmatrix}
\mu_1 \\
\mu_2 \\
\vdots \\
\mu_k
\end{bmatrix}
,\quad \sigma \;=\;
\begin{bmatrix}
\sigma_1 \\
\sigma_2 \\
\vdots \\
\sigma_k
\end{bmatrix}
\end{align*}
Our goal is to learn the $\mu$ and $\sigma$ vectors in order to be able to sample
$\textbf{z}$ as follows $$z \;=\; \mu + \epsilon \odot \sigma$$
where $\epsilon \sim N(0, 1)$ is a gaussian with mean 0 and standard deviation 1.
\clearpage
% -------------------- PAGE 2 ---------------------- %
\begin{figure}
\includegraphics[scale=0.31]{vae-gaussian.png}
\caption{This picture demonstrates the architecture of a Variational
Autoencoder. The input \textbf{x} gets fed in a Probabilistic
Encoder $q_{\phi}(z | x)$, which in turns connects with the
$\mu$ and $\sigma$ layers. Note that usually there is a encoder
Network before the mean and std layers, but here in the figure
it is ommitted. Then, they sample $\textbf{z}$ which
in turn is fed to the Probabilistic Decoder $p_{\theta}(x | z)$.
The result is then fed to an output layer which represents the
reconstructed input data. The original picture can be found
\href{https://blog.bayeslabs.co/2019/06/04/All-you-need-to-
know-about-Vae.html}{here}.}
\label{fig:Architecture}
\end{figure}
\subsection*{Brief Explanation of architecture}
The architecture of a \textbf{VAE} is briefly portrayed in
Figure~\ref{fig:Architecture}. Let's take a closer look in each part:
\begin{enumerate}
\item The encoder part consists of a Probabilistic Encoder $q_{\phi}(z | x)$.
Given some parameters $\phi$ (which are parameters of the model),
$q_{\phi}(z | x)$ models the probability of obtaining the latent vector
$\textbf{z}$ given input data $\textbf{x}$. Afterwards, it connects to
the $\mu$ and $\sigma$ layers, as there might a whole encoder network
before those.
\item The latent vector $\textbf{z}$.
\item The decoder part which consists of a Probabilistic Decoder
$p_{\theta}(x | z)$. As with the probabilistic encoder, given some
parameters $\theta$ which are parameters of the model, we want to learn
the probability of obtaining a data point $\textbf{x}$ given a latent
vector $\textbf{z}$.
\item The reconstructed input $\hat{x}$.
\end{enumerate}
\clearpage
% -------------------- PAGE 3 ---------------------- %
\section*{Loss function}
The loss function of the VAE is:
\begin{align*}
L(\theta,\, \phi,\, x) \;=\; -\E_{z \sim q_{\phi}(z | x)}
\left[\log p_{\theta}(x | z) \right]\;
+\; D_{KL}\left[q_{\phi}(z | x) \;||\; p_{\theta}(z) \right]
\end{align*}
It may seem daunting at first, but if we break it down into pieces then it gets
much simpler.
\subsection*{KL-Divergence and multivariate Normal Distribution}
Let's start by explaining what the second term of the loss function is. The
\textbf{K}ullback \textbf{L}eibler Divergence, also known as
\href{https://en.wikipedia.org/wiki/Relative_entropy}{Relative Entropy}, is
a measure of similarity between two probability distributions. It is denoted by
$D_{KL}(\cdot \;||\; \cdot)$, its unit of measure it called \textbf{nat} and it
can computed by the formula (for continuous probability distributions $P,\; Q$):
\begin{equation}\label{eq:KLD}
D_{KL} \left[ P \,||\, Q \right] \;=\;
\int P(x) \log\left(\frac{P(x)}{Q(x)}\right) dx
\end{equation}
Of course, this implies that $D_{KL} (P \,||\, Q) \neq D_{KL} (Q \,||\, P)$.
\bigskip
Now, let's suppose that both $P,\; Q$ are multivariate
normal distributions with means $\mu_1, \mu_2$ and
\href{https://en.wikipedia.org/wiki/Covariance_matrix}{covariance} matrices
$\Sigma_1, \Sigma_2$:
\begin{align*}
P(x) \,=&\, N(x;\, \mu_1,\, \Sigma_1) \,=\,
\frac{1}{\sqrt{(2\pi)^k|\Sigma_1|}}
e^{-\frac{1}{2}(x-\mu_1)^T\Sigma_1^{-1}(x - \mu_1)} \\
Q(x) \,=&\, N(x;\, \mu_2,\, \Sigma_2) \,=\,
\frac{1}{\sqrt{(2\pi)^k|\Sigma_2|}}
e^{-\frac{1}{2}(x-\mu_2)^T\Sigma_2^{-1}(x - \mu_2)}
\end{align*}
where $k$ is the magnitude (length) of vector $x$.
\smallskip
\noindent Hence
\begin{align*}
\log(P(x)) \;=\;& \log\left(\frac{1}{\sqrt{(2\pi)^k|\Sigma_1|}}
e^{-\frac{1}{2}(x-\mu_1)^T\Sigma_1^{-1}(x - \mu_1)} \right) \\
\;=\;& \log \left( \frac{1}{\sqrt{(2\pi)^k|\Sigma_1|}} \right) +
\log \left( e^{-\frac{1}{2}(x-\mu_1)^T\Sigma_1^{-1}
(x - \mu_1)} \right) \\
\;=\;& -\frac{k}{2}\log(2\pi) -\frac{1}{2}\log(|\Sigma_1|) -
\frac{1}{2}(x-\mu_1)^T\Sigma_1^{-1} (x - \mu_1)
\end{align*}
\clearpage
% -------------------- PAGE 4 ---------------------- %
\noindent Following the exact same steps, we also get that
\begin{align*}
\log(Q(x)) \;=\; -\frac{k}{2}\log(2\pi) -\frac{1}{2}\log(|\Sigma_2|) -
\frac{1}{2}(x-\mu_2)^T\Sigma_2^{-1} (x - \mu_2)
\end{align*}
\noindent With the help of the above equalities, expanding \eqref{eq:KLD} yields:
\begin{align*}
D_{KL} \left[ P \,||\, Q \right]
\;=&\; \int P(x) \left[\log(P(x)) - \log(Q(x)) \right] dx\\
\;=&\; \int P(x) \left[ \frac{1}{2}\log\left(\frac{|\Sigma_2|}{|\Sigma_1|}\right)
- \frac{1}{2}(x-\mu_1)^T\Sigma_1^{-1} (x - \mu_1) \right. \\
&\left.\qquad\qquad\qquad\qquad\quad\;\;\;\,
+ \frac{1}{2}(x-\mu_2)^T\Sigma_2^{-1} (x - \mu_2)\right] dx
\end{align*}
We can rewrite the above term an an Expectation over $P$:
\begin{align*}
D_{KL} \left[ P \,||\, Q \right]
\;=&\; \E_P \left[ \frac{1}{2}\log\left(\frac{|\Sigma_2|}{|\Sigma_1|}\right)
- \frac{1}{2}(x-\mu_1)^T\Sigma_1^{-1} (x - \mu_1) \right. \\
&\left.\qquad\qquad\qquad\quad\;\;\,
+ \frac{1}{2}(x-\mu_2)^T\Sigma_2^{-1} (x - \mu_2)\right]
\end{align*}
Since the logarithmic term is independent of $x$, we can move it outside the
expectation. This leaves us with
\begin{align}\label{eq:kld_exp}
D_{KL} \left[ P \,||\, Q \right]
\;=\quad &\frac{1}{2}\log\left(\frac{|\Sigma_2|}{|\Sigma_1|}\right) \nonumber \\
\; -\, &\frac{1}{2} \E_P \left[ (x-\mu_1)^T\Sigma_1^{-1} (x - \mu_1) \right]
\nonumber \\
\; +\, &\frac{1}{2} \E_P \left[ (x-\mu_2)^T\Sigma_2^{-1} (x - \mu_2) \right]
\end{align}
Let's now try to simplify the 2nd and 3rd terms of the above expression.
\bigskip
\noindent First, we have to recall the
\href{https://en.wikipedia.org/wiki/Trace_(linear_algebra)}{trace}
function and some of its properties. The trace of a square matrix $A$,
denoted as $tr(A)$, is the sum of the elements along the main diagonal of $A$.
The \href{https://en.wikipedia.org/wiki/Trace_(linear_algebra)#Properties}{properties}
of the trace function which we will need are:
\begin{enumerate}
\item \href{https://math.stackexchange.com/questions/3098841/how-could-a-scalar-
be-equal-to-the-trace-of-the-same-scalar}{Trace of scalar}:
Considering the scalar as a $1\times1$ matrix, gives: $x = tr(x)$
\item \href{https://math.stackexchange.com/questions/2228398/trace-trick-for-
expectations-of-quadratic-forms}{Trace of Expectation}:
From 1: $\E[x] = \E[tr(x)] \Rightarrow tr(\E[x]) = \E[tr(x)]$
\item \href{https://en.wikipedia.org/wiki/Trace_(linear_algebra)#Cyclic_property}
{Cyclic Property}: $tr(ABC) \;=\; tr(CAB)$
\end{enumerate}
\clearpage
% -------------------- PAGE 5 ---------------------- %
\noindent Having these properties in mind, we are now ready to simplify the
expectation terms computed before during the simplification of the KL Divergence.
\begin{itemize}
\item Term 2. Note that the matrix multiplications inside the expectation reduce
to a scalar value.
\begin{align*}
\E_P \left[ (x-\mu_1)^T\Sigma_1^{-1} (x - \mu_1) \right]
\;\prone\;& \E_P \left[ tr\left((x-\mu_1)^T\Sigma_1^{-1}
(x - \mu_1)\right) \right] \\
\;\prthr\;& \E_P \left[ tr\left( (x - \mu_1)(x - \mu_1)^T
\Sigma_1^{-1} \right) \right] \\
\;\prtwo\;& tr\left( \E_P\left[ (x - \mu_1)(x - \mu_1)^T
\Sigma_1^{-1} \right] \right)
\end{align*}
$\Sigma_1^{-1}$ is independent from the expectation over $P$, so it can
be moved outside, thus giving:
\begin{align*}
\E_P \left[ (x-\mu_1)^T\Sigma_1^{-1} (x - \mu_1) \right] \;=\;
tr\left( \E_P\left[ (x - \mu_1)(x - \mu_1)^T
\right] \Sigma_1^{-1} \right)
\end{align*}
But the term $E_P\left[ (x - \mu_1)(x - \mu_1)^T \right]$ is equal to the
\href{https://en.wikipedia.org/wiki/Covariance_matrix#Definition}
{Covariance Matrix} $\Sigma_1$, thus yielding
\begin{align}\label{eq:kld_term2}
\E_P \left[ (x-\mu_1)^T\Sigma_1^{-1} (x - \mu_1) \right]
\;=\; tr\left( \Sigma_1 \Sigma_1^{-1} \right) \;=\; tr(I_k) \;=\; k
\end{align}
\item Term 3. Again, the term inside the expectation reduces to a scalar.
\begin{align*}
\E_P &\left[ (x - \mu_2)^T\Sigma_2^{-1} (x - \mu_2) \right] \\[2ex]
\mbox{Add and}& \mbox{ subtract } \mu_1: \\[2ex]
\;=&\; \E_P \left[ [(x - \mu_1) + (\mu_1 - \mu_2)]^T\Sigma_2^{-1}
[(x - \mu_1) + (\mu_1 - \mu_2)] \right] \\[2ex]
\;=&\; \E_P \left[ \left[(x - \mu_1)^T + (\mu_1 - \mu_2)^T\right]
\Sigma_2^{-1} [(x - \mu_1) + (\mu_1 - \mu_2)] \right] \\[2.5ex]
(A^T + B^T&)C(A + B) \;=\; A^TCA + A^TCB + B^TCA + B^TB: \\[2.5ex]
\;=&\; \E_P \left[ (x - \mu_1)^T\Sigma_2^{-1}(x - \mu_1) \;+\;
(x - \mu_1)^T\Sigma_2^{-1}(\mu_1 - \mu_2) \;+ \right. \\[2ex]
& \quad\;\;\;\,
\left. (\mu_1 - \mu_2)^T\Sigma_2^{-1}(x - \mu_1) \;+\;
(\mu_1 - \mu_2)^T\Sigma_2^{-1}(\mu_1 - \mu_2) \right]
\end{align*}
\clearpage
% -------------------- PAGE 6 ---------------------- %
Taking the expectation over each term individually:
\begin{align*}
\E_P \left[(x - \mu_2)^T\Sigma_2^{-1} (x - \mu_2)\right]
\;=\; &\E_P \left[(x - \mu_1)^T\Sigma_2^{-1}(x - \mu_1)\right] \;+\\[2ex]
&\E_P \left[(x - \mu_1)^T\Sigma_2^{-1}(\mu_1 - \mu_2)\right]\;+\\[2ex]
&\E_P \left[(\mu_1 - \mu_2)^T\Sigma_2^{-1}(x - \mu_1)\right]\;+\\[2ex]
&\E_P \left[(\mu_1 - \mu_2)^T\Sigma_2^{-1}(\mu_1 - \mu_2)\right]
\end{align*}
\begin{itemize}
\item The first sub-term has the same derivation as the first
term from before:
$$\E_P \left[ (x - \mu_1)^T\Sigma_2^{-1}(x - \mu_1) \right] \;=\;
tr(\Sigma_1\Sigma_2^{-1})$$
\item The second and third sub-terms are equal to $0$ due to the
expectation over $(x - \mu_1)^T$. Specifically, the factor
$\Sigma_2^{-1} (\mu_1 - \mu_2)$ can be moved out of the expectation
as it is a constant:
\begin{align*}
\E_P \left[ (x - \mu_1)^T\Sigma_2^{-1}(\mu_1 - \mu_2) \right]
\;=&\; \E_P \left[ (x - \mu_1)^T \right]
\Sigma_2^{-1}(\mu_1 - \mu_2) \\
\;=&\; 0_k \; \Sigma_2^{-1}(\mu_1 - \mu_2) \;=\; 0 \\[1.5ex]
\E_P \left[ (\mu_1 - \mu_2)^T\Sigma_2^{-1}(x - \mu_1) \right]
\;=&\; (\mu_1 - \mu_2)^T\Sigma_2^{-1}
\E_P \left[ (x - \mu_1)^T \right] \\
\;=&\; \Sigma_2^{-1}(\mu_1 - \mu_2) \; 0_k \;=\; 0
\end{align*}
\item The fourth sub-term is the expectation of a constant, so it is equal
to the constant itself:
$$\E_P \left[ (\mu_1 - \mu_2)^T\Sigma_2^{-1}(\mu_1 - \mu_2)\right] \;=\;
(\mu_1 - \mu_2)^T\Sigma_2^{-1}(\mu_1 - \mu_2)$$
\end{itemize}
These simplifications leave us with:
\begin{align}\label{eq:kld_term3}
\E_P \left[ (x - \mu_2)^T\Sigma_2^{-1} (x - \mu_2) \right] \;=\;\,
&tr(\Sigma_1\Sigma_2^{-1}) \,+ \nonumber \\
&(\mu_1 - \mu_2)^T\Sigma_2^{-1}(\mu_1 - \mu_2)
\end{align}
\end{itemize}
\noindent Finally, formula \eqref{eq:kld_exp} for the KL-Divergence can be ultimately
simplified using equations \eqref{eq:kld_term2}, \eqref{eq:kld_term3} to:
\begin{align}\label{eq:kld_gauss}
D_{KL} \left[ P \,||\, Q \right] \;=\;
\frac{1}{2}\left[ \log\left(\frac{|\Sigma_2|}{|\Sigma_1|}\right) \;-\;
k \;+\;
tr(\Sigma_1\Sigma_2^{-1}) \;+\; (\mu_1 - \mu_2)^T\Sigma_2^{-1}
(\mu_1 - \mu_2) \right]
\end{align}
\QEDA
\clearpage
% -------------------- PAGE 7 ---------------------- %
\subsection*{Goal of VAE}
As mentioned in the introduction, the goal of the \textbf{VAE} is to learn the
distribution $q_{\phi}(\textbf{z} | \textbf{x})$ of the latent vector $\textbf{z}$.
After the distribution of the latent vector has been learnt, we can sample
$\textbf{z}$ and feed it to the Generator Network defined by the distribution
$p_{\theta}(\textbf{x} | \textbf{z})$ (aka decoder) in order to obtain a new
data point $\tilde{x}$. Of course during training, we want $\tilde{x} \approx x$.
The training process can be thought of graphically as follows
\bigskip
\begin{center}
\begin{tikzpicture}
% nodes x, z
\node[draw, circle, minimum size=1cm, inner sep=0pt,
label=above:input vector $\textbf{x}$] (x) at (0, 0) {$x$};
\node[draw, circle, minimum size=1cm, inner sep=0pt,
label=below:latent vector $\textbf{z}$] (z) at (0, -4) {$z$};
% edge q_phi
\draw[->] (x) to node[midway, above, xshift=25, yshift=-10]
{$q_{\phi}(z | x)$} (z);
% edge p_theta
\draw[->] (z) to[bend right=-40] node[midway, above, xshift=-25, yshift=-10]
{$p_{\theta}(x | z)$} (x);
\end{tikzpicture}
\end{center}
\bigskip
\subsection*{Derivation of Loss Function}
We would like the two distributions to be approximately same, that is
$$q_{\phi}(z | x) \approx p_{\theta}(z| x)$$
How can we force the two distributions to come close? We could view this
as a minimization problem of the KL-Divergence between $Q$ and $P$.
\begin{align*}
D_{KL} \left[ q_{\phi}(z | x) \,||\, p_{\theta}(z | x) \right]
\;=\; \int q_{\phi}(z | x) \log \left(
\frac{q_{\phi}(z | x)}{p_{\theta}(z | x)} \right) dz
\end{align*}
\clearpage
% -------------------- PAGE 8 ---------------------- %
Rewriting this term as an Expectation yields:
\begin{align*}
D_{KL} &\left[ q_{\phi}(z | x) \,||\, p_{\theta}(z | x) \right] \\[2ex]
\;=&\; \E_{z \sim q_{\phi}(z|x)}\left[ \log \left(
\frac{q_{\phi}(z | x)}{p_{\theta}(z | x)} \right) \right] \\[2ex]
\;=&\; \E_{z \sim q_{\phi}(z|x)}\left[ \log q_{\phi}(z | x)
- \log p_{\theta}(z | x) \right] \\[2ex]
\;=&\; \E_{z \sim q_{\phi}(z|x)}\left[ \log q_{\phi}(z | x)
- \log \left( \frac{p_{\theta}(x | z) \; p_{\theta}(z)}
{p_{\theta}(x)} \right) \right] \\[2ex]
\;=&\; \E_{z \sim q_{\phi}(z|x)}\left[ \log q_{\phi}(z | x)
- \log p_{\theta}(x | z) - \log p_{\theta}(z)
+ \log p_{\theta}(x) \right]
% \;=&\; \E_{z \sim q_{\phi}(z|x)} [\log q_{\phi}(z | x)] -
% \E_{z \sim q_{\phi}(z|x)} [\log p_{\theta}(x | z)] \,-\\[2ex]
% &\; \E_{z \sim q_{\phi}(z|x)} [\log p_{\theta}(z)] +
% \E_{z \sim q_{\phi}(z|x)} [\log p_{\theta}(x)]
\end{align*}
Since $\log p_{\theta}(x)$ is independent from the Expectation of $z$, it can be moved
outside, thus giving
\begin{align*}
D_{KL} &\left[ q_{\phi}(z | x) \,||\, p_{\theta}(z | x) \right]
- \log p_{\theta}(x) \\[2ex]
\;=&\; -\E_{z \sim q_{\phi}(z|x)}[\log p_{\theta}(x | z)] \;+\;
\E_{z \sim q_{\phi}(z|x)}[\log q_{\phi}(z | x) - \log p_{\theta}(z)] \\[2ex]
\;=&\; -\E_{z \sim q_{\phi}(z|x)}[\log p_{\theta}(x | z)] \;+\;
\E_{z \sim q_{\phi}(z|x)} \left[ \log \left(
\frac{q_{\phi}(z | x)}{p_{\theta}(z)} \right) \right] \\[2ex]
\;=&\; -\E_{z \sim q_{\phi}(z|x)}[\log p_{\theta}(x | z)] \;+\;
D_{KL} \left[ q_{\phi}(z | x) \,||\, p_{\theta}(z) \right]
\end{align*}
which is the loss function $L$, defined in terms of $\phi,\, \theta,\, x$:
\begin{align*}
L(\theta,\, \phi,\, x) \;=\; -\E_{z \sim q_{\phi}(z | x)}
\left[\log p_{\theta}(x | z) \right]\;
+\; D_{KL}\left[q_{\phi}(z | x) \;||\; p_{\theta}(z) \right]
\end{align*}
which is also known as
\href{https://en.wikipedia.org/wiki/Variational_Bayesian_methods#Evidence_lower_bound}
{Evidence Lower BOund} (ELBO).
Of course, our target is to find the $\theta,\, \phi$ that minimize the loss
$L(\theta,\, \phi,\, x)$ for all data points $x$ in the training set, $X$ that is:
$$\theta^*,\, \phi^* \;=\; \argmin_{\phi,\, \theta} L(\theta,\, \phi,\, x)
\text{ over all } x \in X$$
Where in our case $\theta^*$ are the weights of the Recognition Network (aka encoder)
and $\phi^*$ are the weights of the Generator Network (aka decoder). \clearpage
% -------------------- PAGE 9 ---------------------- %
\subsection*{Simplifying the Loss Function}
How could we simplify the Loss function $L(\theta,\, \phi,\, x)$ such that it can be
computed using known information? The problem is the KL-Divergence term, as we don't
have a closed form for it. The first solution that comes to mind is to model both
distributions of the KL-Divergence term as Gaussians, with $p_{\theta}(z)$ having
mean 0 and standard deviation 1, thus pushing $q_{\phi}(z | x)$ to come close
to it. Specifically:
\begin{enumerate}
\item $q_{\phi}(z | x) \sim N(\mu_{\phi}(x),\, \Sigma_{\phi}(x))$
\item $p_{\theta}(z) \sim N(0_k,\, I_k)$
\end{enumerate}
\noindent This in turn allows us to use eq. \eqref{eq:kld_gauss}, substituting the values
\begin{enumerate}
\item $\mu_1 \,=\, \mu_{\phi}(x),\; \Sigma_1 \,=\, \Sigma_{\phi}(x)$
\item $\mu_2 \,=\, 0_k,\; \Sigma_2 \,=\, I_k$
\end{enumerate}
Thus yielding:
\begin{align*}
D_{KL}&\left[q_{\phi}(z | x) \;||\; p_{\theta}(z) \right] \\[2ex]
\;=&\; \frac{1}{2} \left[ \log \left(\frac{|I_k|}{|\Sigma_{\phi}(x)|} \right)
- k
+ tr(\Sigma_{\phi}(x) \, I_k)
+ (\mu_{\phi}(x) - 0_k)^T I_k (\mu_{\phi}(x) - 0_k) \right] \\[2ex]
\;=&\; \frac{1}{2} \left[ -\log |\Sigma_{\phi}(x)|
- k
+ tr(\Sigma_{\phi}(x))
+ \mu_{\phi}(x)^T \mu_{\phi}(x) \right]
\end{align*}
Note that $\Sigma_{\phi}(x)$ is a diagonal matrix with $k$ elements. Hence we can
write
\begin{align*}
D_{KL}&\left[q_{\phi}(z | x) \;||\; p_{\theta}(z) \right] \\[2ex]
\;=&\; \frac{1}{2} \left[ -\log \left( \prod_k {\Sigma_{\phi}}_k(x) \right)
- k
+ \sum_{i=1}^k {\Sigma_{\phi}}_i(x)
+ \sum_{i=1}^k {\mu_{\phi}}_i^2 \right] \\[2ex]
\;=&\; \frac{1}{2} \left[ - \sum_{i=1}^k \log {\Sigma_{\phi}}_i(x)
- \sum_{i=1}^k 1
+ \sum_{i=1}^k {\Sigma_{\phi}}_i(x)
+ \sum_{i=1}^k {\mu_{\phi}}_i^2 \right] \\[2ex]
\;=&\; \frac{1}{2} \sum_{i=1}^k \left[ - \log {\Sigma_{\phi}}_i(x)
- 1
+ {\Sigma_{\phi}}_i(x)
+ {\mu_{\phi}}_i^2 \right] \\[2ex]
\end{align*}
% -------------------- PAGE 10 ---------------------- %
\noindent which is the fully simplified version of the KL-Divergence term. The final
loss function will is
\begin{equation}\label{eq:final_loss}
L(\theta,\, \phi,\, x)
\;=\; -\E_{z \sim q_{\phi}(z | x)} \left[\log p_{\theta}(x | z) \right]
+ \frac{1}{2} \sum_{i=1}^k \left[ - \log {\Sigma_{\phi}}_i(x)
- 1
+ {\Sigma_{\phi}}_i(x)
+ {\mu_{\phi}}_i^2 \right]
\end{equation}
\subsection*{Backpropagation}
In order to perform backpropagation in the VAE model, we need to compute the partial
derivatives $$\frac{\partial L}{\partial \theta},\;\, \frac{\partial L}{\partial \phi}$$
\begin{enumerate}
\item Partial derivative w.r.t. $\theta$:
\begin{align*}
\frac{\partial L}{\partial \theta}
\;=&\; \frac{\partial}{\partial \theta} \left[
-\E_{z \sim q_{\phi}(z | x)} \left[\log p_{\theta}(x | z) \right]
+ D_{KL}\left[q_{\phi}(z | x) \;||\; p_{\theta}(z) \right]
\right] \\[2ex]
\;=&\; -\frac{\partial}{\partial \theta}
\E_{z \sim q_{\phi}(z | x)} \left[\log p_{\theta}(x | z) \right]
\end{align*}
Using a \href{http://ib.berkeley.edu/labs/slatkin/eriq/classes/guest_
lect/mc_lecture_notes.pdf}{Monte Carlo Estimator} for the Expectation,
we get
\begin{align*}
\frac{\partial L}{\partial \theta}
\;=&\; -\frac{1}{L} \;\sum_{l=1}^L \frac{\partial}{\partial \theta}
\log p_{\theta}(x | z^{(l)})
\end{align*}
where $z^{(l)} \sim q_{\theta}(z | x)$
\item Partial derivative w.r.t. $\phi$:
\bigskip
Here, a problem arises. If we try to take the partial derivative of the
first term w.r.t. $\phi$, then the gradient is being blocked by the
distribution $q_{\phi}$ for which the expectation is taken. This problem can
be solved by using the
\href{https://towardsdatascience.com/reparameterization-trick-126062cfd3c3}
{Reparameterization Trick}, that is, performing a linear substituion
$z = g_{\phi}(\epsilon, x)$ with $\epsilon \sim N(0, 1)$ in order to
\textquote{push} the stochasticity out of the latent vector $z$, into the
newly introduced $\epsilon$ node.
The linear transformation $g$ can be as simple as
$$g_{\phi}(\epsilon, x) \;=\; \mu_{\phi}(x) +
\epsilon \odot \Sigma_{\phi}^{\frac{1}{2}}(x)
\;=\; z \sim N(\mu_{\phi}(x),\, \Sigma_{\phi}(x))$$
\end{enumerate}
\clearpage
% -------------------- PAGE 11 ---------------------- %
\begin{figure}
\includegraphics[scale=0.35]{reptr.png}
\caption{Visual Representation of the effect of the Reparameterization Trick.
The linear substituion introduces the stochastic node $\epsilon$, thus
removing the stochasticity from $z$ and allowing the gradients to flow
backwards. This fig. can be found in the Introduction to Variational
Autoencoders paper, \href{https://arxiv.org/abs/1906.02691}{here}.}
\label{fig:RepTrick}
\end{figure}
\bigskip
Figure \ref{fig:RepTrick} is a visual representation of the reparameterization trick.
Now, again using a Monte Carlo Estimator for the Expectation of the first term,
we can compute the gradient of the loss function $L$ w.r.t. $\phi$ as follows
\begin{align*}
\frac{\partial L}{\partial \phi}
\;=&\; -\E_{z \sim p(\epsilon)} \left[ \frac{\partial}{\partial \phi}
\log p_{\theta}(x | z^{(l)}) \right] +
\frac{\partial}{\partial \phi}
\frac{1}{2} \sum_{i=1}^k \left[ - \log {\Sigma_{\phi}}_i(x)
- 1
+ {\Sigma_{\phi}}_i(x)
+ {\mu_{\phi}}_i^2 \right] \\[2ex]
%
\;=&\; -\frac{1}{S} \;\sum_{s=1}^S \frac{\partial}{\partial \phi}
\log p_{\theta}(x | z^{(l)}) \,+\,
\frac{1}{2} \sum_{i=1}^k \left[ -
\frac{\partial}{\partial \phi} \log {\Sigma_{\phi}}_i(x)
+ \frac{\partial}{\partial \phi} {\Sigma_{\phi}}_i(x)
+ \frac{\partial}{\partial \phi} {\mu_{\phi}}_i^2 \right]
\end{align*}
where $z^{(l)} \;=\; m_{\phi}(x) + \epsilon \odot \sigma_{\phi}(x)$ and
$\epsilon^{(l)} \sim N(0, 1)$.
\clearpage
% -------------------- PAGE 12 ---------------------- %
\section*{Resources}
\begin{itemize}
\item \underline{Papers}:
\begin{itemize}
\item \href{https://arxiv.org/abs/1312.6114}
{Auto-Encoding Variational Bayes}
\item \href{https://arxiv.org/abs/1906.02691}
{An Introduction to Variational Autoencoders}
\item \href{https://arxiv.org/pdf/1606.05579}
{Early Visual Concept Learning with Unsupervised Deep Learning}
\end{itemize}
\item \underline{Online Lectures}:
\begin{itemize}
\item \href{https://www.youtube.com/watch?v=w8F7_rQZxXk&list=PLdxQ7SoC
LQANizknbIiHzL_hYjEaI-wUe}{Ahlad Kumar}
\item \href{https://www.youtube.com/watch?v=uaaqyVS9-rM}{Ali Ghodsi}
\end{itemize}
\end{itemize}
\end{document}
% ---------------- END OF DOCUMENT ------------ %
|
/-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.hom_functor
import category_theory.currying
import category_theory.products.basic
/-!
# The Yoneda embedding
The Yoneda embedding as a functor `yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁)`,
along with an instance that it is `fully_faithful`.
Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C)`.
## References
* [Stacks: Opposite Categories and the Yoneda Lemma](https://stacks.math.columbia.edu/tag/001L)
-/
namespace category_theory
open opposite
universes v₁ u₁ u₂-- morphism levels before object levels. See note [category_theory universes].
variables {C : Type u₁} [category.{v₁} C]
/--
The Yoneda embedding, as a functor from `C` into presheaves on `C`.
See https://stacks.math.columbia.edu/tag/001O.
-/
@[simps]
def yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁) :=
{ obj := λ X,
{ obj := λ Y, unop Y ⟶ X,
map := λ Y Y' f g, f.unop ≫ g,
map_comp' := λ _ _ _ f g, begin ext, dsimp, erw [category.assoc] end,
map_id' := λ Y, begin ext, dsimp, erw [category.id_comp] end },
map := λ X X' f, { app := λ Y g, g ≫ f } }
/--
The co-Yoneda embedding, as a functor from `Cᵒᵖ` into co-presheaves on `C`.
-/
@[simps] def coyoneda : Cᵒᵖ ⥤ (C ⥤ Type v₁) :=
{ obj := λ X,
{ obj := λ Y, unop X ⟶ Y,
map := λ Y Y' f g, g ≫ f },
map := λ X X' f, { app := λ Y g, f.unop ≫ g } }
namespace yoneda
lemma obj_map_id {X Y : C} (f : op X ⟶ op Y) :
(yoneda.obj X).map f (𝟙 X) = (yoneda.map f.unop).app (op Y) (𝟙 Y) :=
by { dsimp, simp }
@[simp] lemma naturality {X Y : C} (α : yoneda.obj X ⟶ yoneda.obj Y)
{Z Z' : C} (f : Z ⟶ Z') (h : Z' ⟶ X) : f ≫ α.app (op Z') h = α.app (op Z) (f ≫ h) :=
(functor_to_types.naturality _ _ α f.op h).symm
/--
The Yoneda embedding is full.
See https://stacks.math.columbia.edu/tag/001P.
-/
instance yoneda_full : full (yoneda : C ⥤ Cᵒᵖ ⥤ Type v₁) :=
{ preimage := λ X Y f, f.app (op X) (𝟙 X) }
/--
The Yoneda embedding is faithful.
See https://stacks.math.columbia.edu/tag/001P.
-/
instance yoneda_faithful : faithful (yoneda : C ⥤ Cᵒᵖ ⥤ Type v₁) :=
{ map_injective' := λ X Y f g p, by convert (congr_fun (congr_app p (op X)) (𝟙 X)); dsimp; simp }
/-- Extensionality via Yoneda. The typical usage would be
```
-- Goal is `X ≅ Y`
apply yoneda.ext,
-- Goals are now functions `(Z ⟶ X) → (Z ⟶ Y)`, `(Z ⟶ Y) → (Z ⟶ X)`, and the fact that these
functions are inverses and natural in `Z`.
```
-/
def ext (X Y : C)
(p : Π {Z : C}, (Z ⟶ X) → (Z ⟶ Y)) (q : Π {Z : C}, (Z ⟶ Y) → (Z ⟶ X))
(h₁ : Π {Z : C} (f : Z ⟶ X), q (p f) = f) (h₂ : Π {Z : C} (f : Z ⟶ Y), p (q f) = f)
(n : Π {Z Z' : C} (f : Z' ⟶ Z) (g : Z ⟶ X), p (f ≫ g) = f ≫ p g) : X ≅ Y :=
@preimage_iso _ _ _ _ yoneda _ _ _ _
(nat_iso.of_components (λ Z, { hom := p, inv := q, }) (by tidy))
/--
If `yoneda.map f` is an isomorphism, so was `f`.
-/
lemma is_iso {X Y : C} (f : X ⟶ Y) [is_iso (yoneda.map f)] : is_iso f :=
is_iso_of_fully_faithful yoneda f
end yoneda
namespace coyoneda
@[simp] lemma naturality {X Y : Cᵒᵖ} (α : coyoneda.obj X ⟶ coyoneda.obj Y)
{Z Z' : C} (f : Z' ⟶ Z) (h : unop X ⟶ Z') : (α.app Z' h) ≫ f = α.app Z (h ≫ f) :=
(functor_to_types.naturality _ _ α f h).symm
instance coyoneda_full : full (coyoneda : Cᵒᵖ ⥤ C ⥤ Type v₁) :=
{ preimage := λ X Y f, (f.app _ (𝟙 X.unop)).op }
instance coyoneda_faithful : faithful (coyoneda : Cᵒᵖ ⥤ C ⥤ Type v₁) :=
{ map_injective' := λ X Y f g p,
begin
have t := congr_fun (congr_app p X.unop) (𝟙 _),
simpa using congr_arg quiver.hom.op t,
end }
/--
If `coyoneda.map f` is an isomorphism, so was `f`.
-/
lemma is_iso {X Y : Cᵒᵖ} (f : X ⟶ Y) [is_iso (coyoneda.map f)] : is_iso f :=
is_iso_of_fully_faithful coyoneda f
/-- The identity functor on `Type` is isomorphic to the coyoneda functor coming from `punit`. -/
def punit_iso : coyoneda.obj (opposite.op punit) ≅ 𝟭 (Type v₁) :=
nat_iso.of_components
(λ X, { hom := λ f, f ⟨⟩, inv := λ x _, x })
(by tidy)
end coyoneda
namespace functor
/--
A functor `F : Cᵒᵖ ⥤ Type v₁` is representable if there is object `X` so `F ≅ yoneda.obj X`.
See https://stacks.math.columbia.edu/tag/001Q.
-/
class representable (F : Cᵒᵖ ⥤ Type v₁) : Prop :=
(has_representation : ∃ X (f : yoneda.obj X ⟶ F), is_iso f)
instance {X : C} : representable (yoneda.obj X) :=
{ has_representation := ⟨X, 𝟙 _, infer_instance⟩ }
/--
A functor `F : C ⥤ Type v₁` is corepresentable if there is object `X` so `F ≅ coyoneda.obj X`.
See https://stacks.math.columbia.edu/tag/001Q.
-/
class corepresentable (F : C ⥤ Type v₁) : Prop :=
(has_corepresentation : ∃ X (f : coyoneda.obj X ⟶ F), is_iso f)
instance {X : Cᵒᵖ} : corepresentable (coyoneda.obj X) :=
{ has_corepresentation := ⟨X, 𝟙 _, infer_instance⟩ }
-- instance : corepresentable (𝟭 (Type v₁)) :=
-- corepresentable_of_nat_iso (op punit) coyoneda.punit_iso
section representable
variables (F : Cᵒᵖ ⥤ Type v₁)
variable [F.representable]
/-- The representing object for the representable functor `F`. -/
noncomputable def repr_X : C :=
(representable.has_representation : ∃ X (f : _ ⟶ F), _).some
/-- The (forward direction of the) isomorphism witnessing `F` is representable. -/
noncomputable def repr_f : yoneda.obj F.repr_X ⟶ F :=
representable.has_representation.some_spec.some
/--
The representing element for the representable functor `F`, sometimes called the universal
element of the functor.
-/
noncomputable def repr_x : F.obj (op F.repr_X) :=
F.repr_f.app (op F.repr_X) (𝟙 F.repr_X)
instance : is_iso F.repr_f :=
representable.has_representation.some_spec.some_spec
/--
An isomorphism between `F` and a functor of the form `C(-, F.repr_X)`. Note the components
`F.repr_w.app X` definitionally have type `(X.unop ⟶ F.repr_X) ≅ F.obj X`.
-/
noncomputable def repr_w : yoneda.obj F.repr_X ≅ F := as_iso F.repr_f
@[simp] lemma repr_w_hom : F.repr_w.hom = F.repr_f := rfl
lemma repr_w_app_hom (X : Cᵒᵖ) (f : unop X ⟶ F.repr_X) :
(F.repr_w.app X).hom f = F.map f.op F.repr_x :=
begin
change F.repr_f.app X f = (F.repr_f.app (op F.repr_X) ≫ F.map f.op) (𝟙 F.repr_X),
rw ←F.repr_f.naturality,
dsimp,
simp
end
end representable
section corepresentable
variables (F : C ⥤ Type v₁)
variable [F.corepresentable]
/-- The representing object for the corepresentable functor `F`. -/
noncomputable def corepr_X : C :=
(corepresentable.has_corepresentation : ∃ X (f : _ ⟶ F), _).some.unop
/-- The (forward direction of the) isomorphism witnessing `F` is corepresentable. -/
noncomputable def corepr_f : coyoneda.obj (op F.corepr_X) ⟶ F :=
corepresentable.has_corepresentation.some_spec.some
/--
The representing element for the corepresentable functor `F`, sometimes called the universal
element of the functor.
-/
noncomputable def corepr_x : F.obj F.corepr_X :=
F.corepr_f.app F.corepr_X (𝟙 F.corepr_X)
instance : is_iso F.corepr_f :=
corepresentable.has_corepresentation.some_spec.some_spec
/--
An isomorphism between `F` and a functor of the form `C(F.corepr X, -)`. Note the components
`F.corepr_w.app X` definitionally have type `F.corepr_X ⟶ X ≅ F.obj X`.
-/
noncomputable def corepr_w : coyoneda.obj (op F.corepr_X) ≅ F := as_iso F.corepr_f
lemma corepr_w_app_hom (X : C) (f : F.corepr_X ⟶ X) :
(F.corepr_w.app X).hom f = F.map f F.corepr_x :=
begin
change F.corepr_f.app X f = (F.corepr_f.app F.corepr_X ≫ F.map f) (𝟙 F.corepr_X),
rw ←F.corepr_f.naturality,
dsimp,
simp
end
end corepresentable
end functor
lemma representable_of_nat_iso (F : Cᵒᵖ ⥤ Type v₁) {G} (i : F ≅ G) [F.representable] :
G.representable :=
{ has_representation := ⟨F.repr_X, F.repr_f ≫ i.hom, infer_instance⟩ }
lemma corepresentable_of_nat_iso (F : C ⥤ Type v₁) {G} (i : F ≅ G) [F.corepresentable] :
G.corepresentable :=
{ has_corepresentation := ⟨op F.corepr_X, F.corepr_f ≫ i.hom, infer_instance⟩ }
instance : functor.corepresentable (𝟭 (Type v₁)) :=
corepresentable_of_nat_iso (coyoneda.obj (op punit)) coyoneda.punit_iso
open opposite
variables (C)
-- We need to help typeclass inference with some awkward universe levels here.
instance prod_category_instance_1 : category ((Cᵒᵖ ⥤ Type v₁) × Cᵒᵖ) :=
category_theory.prod.{(max u₁ v₁) v₁} (Cᵒᵖ ⥤ Type v₁) Cᵒᵖ
instance prod_category_instance_2 : category (Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) :=
category_theory.prod.{v₁ (max u₁ v₁)} Cᵒᵖ (Cᵒᵖ ⥤ Type v₁)
open yoneda
/--
The "Yoneda evaluation" functor, which sends `X : Cᵒᵖ` and `F : Cᵒᵖ ⥤ Type`
to `F.obj X`, functorially in both `X` and `F`.
-/
def yoneda_evaluation : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) :=
evaluation_uncurried Cᵒᵖ (Type v₁) ⋙ ulift_functor.{u₁}
@[simp] lemma yoneda_evaluation_map_down
(P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (x : (yoneda_evaluation C).obj P) :
((yoneda_evaluation C).map α x).down = α.2.app Q.1 (P.2.map α.1 x.down) := rfl
/--
The "Yoneda pairing" functor, which sends `X : Cᵒᵖ` and `F : Cᵒᵖ ⥤ Type`
to `yoneda.op.obj X ⟶ F`, functorially in both `X` and `F`.
-/
def yoneda_pairing : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) :=
functor.prod yoneda.op (𝟭 (Cᵒᵖ ⥤ Type v₁)) ⋙ functor.hom (Cᵒᵖ ⥤ Type v₁)
@[simp] lemma yoneda_pairing_map
(P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (β : (yoneda_pairing C).obj P) :
(yoneda_pairing C).map α β = yoneda.map α.1.unop ≫ β ≫ α.2 := rfl
/--
The Yoneda lemma asserts that that the Yoneda pairing
`(X : Cᵒᵖ, F : Cᵒᵖ ⥤ Type) ↦ (yoneda.obj (unop X) ⟶ F)`
is naturally isomorphic to the evaluation `(X, F) ↦ F.obj X`.
See https://stacks.math.columbia.edu/tag/001P.
-/
def yoneda_lemma : yoneda_pairing C ≅ yoneda_evaluation C :=
{ hom :=
{ app := λ F x, ulift.up ((x.app F.1) (𝟙 (unop F.1))),
naturality' :=
begin
intros X Y f, ext, dsimp,
erw [category.id_comp, ←functor_to_types.naturality],
simp only [category.comp_id, yoneda_obj_map],
end },
inv :=
{ app := λ F x,
{ app := λ X a, (F.2.map a.op) x.down,
naturality' :=
begin
intros X Y f, ext, dsimp,
rw [functor_to_types.map_comp_apply]
end },
naturality' :=
begin
intros X Y f, ext, dsimp,
rw [←functor_to_types.naturality, functor_to_types.map_comp_apply]
end },
hom_inv_id' :=
begin
ext, dsimp,
erw [←functor_to_types.naturality,
obj_map_id],
simp only [yoneda_map_app, quiver.hom.unop_op],
erw [category.id_comp],
end,
inv_hom_id' :=
begin
ext, dsimp,
rw [functor_to_types.map_id_apply]
end }.
variables {C}
/--
The isomorphism between `yoneda.obj X ⟶ F` and `F.obj (op X)`
(we need to insert a `ulift` to get the universes right!)
given by the Yoneda lemma.
-/
@[simps] def yoneda_sections (X : C) (F : Cᵒᵖ ⥤ Type v₁) :
(yoneda.obj X ⟶ F) ≅ ulift.{u₁} (F.obj (op X)) :=
(yoneda_lemma C).app (op X, F)
/--
We have a type-level equivalence between natural transformations from the yoneda embedding
and elements of `F.obj X`, without any universe switching.
-/
def yoneda_equiv {X : C} {F : Cᵒᵖ ⥤ Type v₁} : (yoneda.obj X ⟶ F) ≃ F.obj (op X) :=
(yoneda_sections X F).to_equiv.trans equiv.ulift
@[simp]
lemma yoneda_equiv_apply {X : C} {F : Cᵒᵖ ⥤ Type v₁} (f : yoneda.obj X ⟶ F) :
yoneda_equiv f = f.app (op X) (𝟙 X) :=
rfl
@[simp]
lemma yoneda_equiv_symm_app_apply {X : C} {F : Cᵒᵖ ⥤ Type v₁} (x : F.obj (op X))
(Y : Cᵒᵖ) (f : Y.unop ⟶ X) :
(yoneda_equiv.symm x).app Y f = F.map f.op x :=
rfl
lemma yoneda_equiv_naturality {X Y : C} {F : Cᵒᵖ ⥤ Type v₁} (f : yoneda.obj X ⟶ F) (g : Y ⟶ X) :
F.map g.op (yoneda_equiv f) = yoneda_equiv (yoneda.map g ≫ f) :=
begin
change (f.app (op X) ≫ F.map g.op) (𝟙 X) = f.app (op Y) (𝟙 Y ≫ g),
rw ←f.naturality,
dsimp,
simp,
end
/--
When `C` is a small category, we can restate the isomorphism from `yoneda_sections`
without having to change universes.
-/
def yoneda_sections_small {C : Type u₁} [small_category C] (X : C)
(F : Cᵒᵖ ⥤ Type u₁) :
(yoneda.obj X ⟶ F) ≅ F.obj (op X) :=
yoneda_sections X F ≪≫ ulift_trivial _
@[simp]
lemma yoneda_sections_small_hom {C : Type u₁} [small_category C] (X : C)
(F : Cᵒᵖ ⥤ Type u₁) (f : yoneda.obj X ⟶ F) :
(yoneda_sections_small X F).hom f = f.app _ (𝟙 _) :=
rfl
@[simp]
lemma yoneda_sections_small_inv_app_apply {C : Type u₁} [small_category C] (X : C)
(F : Cᵒᵖ ⥤ Type u₁) (t : F.obj (op X)) (Y : Cᵒᵖ) (f : Y.unop ⟶ X) :
((yoneda_sections_small X F).inv t).app Y f = F.map f.op t :=
rfl
local attribute[ext] functor.ext
/-- The curried version of yoneda lemma when `C` is small. -/
def curried_yoneda_lemma {C : Type u₁} [small_category C] :
(yoneda.op ⋙ coyoneda : Cᵒᵖ ⥤ (Cᵒᵖ ⥤ Type u₁) ⥤ Type u₁) ≅ evaluation Cᵒᵖ (Type u₁) :=
eq_to_iso (by tidy) ≪≫ curry.map_iso (yoneda_lemma C ≪≫
iso_whisker_left (evaluation_uncurried Cᵒᵖ (Type u₁)) ulift_functor_trivial) ≪≫
eq_to_iso (by tidy)
/-- The curried version of yoneda lemma when `C` is small. -/
def curried_yoneda_lemma' {C : Type u₁} [small_category C] :
yoneda ⋙ (whiskering_left Cᵒᵖ (Cᵒᵖ ⥤ Type u₁)ᵒᵖ (Type u₁)).obj yoneda.op ≅ 𝟭 (Cᵒᵖ ⥤ Type u₁) :=
eq_to_iso (by tidy) ≪≫ curry.map_iso (iso_whisker_left (prod.swap _ _)
(yoneda_lemma C ≪≫ iso_whisker_left
(evaluation_uncurried Cᵒᵖ (Type u₁)) ulift_functor_trivial : _)) ≪≫ eq_to_iso (by tidy)
end category_theory
|
/-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import category_theory.category.Bipointed
import order.category.PartialOrder
import order.hom.bounded
/-!
# The category of bounded orders
This defines `BoundedOrder`, the category of bounded orders.
-/
universes u v
open category_theory
/-- The category of bounded orders with monotone functions. -/
structure BoundedOrder :=
(to_PartialOrder : PartialOrder)
[is_bounded_order : bounded_order to_PartialOrder]
namespace BoundedOrder
instance : has_coe_to_sort BoundedOrder Type* := induced_category.has_coe_to_sort to_PartialOrder
instance (X : BoundedOrder) : partial_order X := X.to_PartialOrder.str
attribute [instance] BoundedOrder.is_bounded_order
/-- Construct a bundled `BoundedOrder` from a `fintype` `partial_order`. -/
def of (α : Type*) [partial_order α] [bounded_order α] : BoundedOrder := ⟨⟨α⟩⟩
@[simp] lemma coe_of (α : Type*) [partial_order α] [bounded_order α] : ↥(of α) = α := rfl
instance : inhabited BoundedOrder := ⟨of punit⟩
instance large_category : large_category.{u} BoundedOrder :=
{ hom := λ X Y, bounded_order_hom X Y,
id := λ X, bounded_order_hom.id X,
comp := λ X Y Z f g, g.comp f,
id_comp' := λ X Y, bounded_order_hom.comp_id,
comp_id' := λ X Y, bounded_order_hom.id_comp,
assoc' := λ W X Y Z _ _ _, bounded_order_hom.comp_assoc _ _ _ }
instance concrete_category : concrete_category BoundedOrder :=
{ forget := ⟨coe_sort, λ X Y, coe_fn, λ X, rfl, λ X Y Z f g, rfl⟩,
forget_faithful := ⟨λ X Y, by convert fun_like.coe_injective⟩ }
instance has_forget_to_PartialOrder : has_forget₂ BoundedOrder PartialOrder :=
{ forget₂ := { obj := λ X, X.to_PartialOrder, map := λ X Y, bounded_order_hom.to_order_hom } }
instance has_forget_to_Bipointed : has_forget₂ BoundedOrder Bipointed :=
{ forget₂ := { obj := λ X, ⟨X, ⊥, ⊤⟩, map := λ X Y f, ⟨f, map_bot f, map_top f⟩ },
forget_comp := rfl }
/-- `order_dual` as a functor. -/
@[simps] def dual : BoundedOrder ⥤ BoundedOrder :=
{ obj := λ X, of (order_dual X), map := λ X Y, bounded_order_hom.dual }
/-- Constructs an equivalence between bounded orders from an order isomorphism between them. -/
@[simps] def iso.mk {α β : BoundedOrder.{u}} (e : α ≃o β) : α ≅ β :=
{ hom := e,
inv := e.symm,
hom_inv_id' := by { ext, exact e.symm_apply_apply _ },
inv_hom_id' := by { ext, exact e.apply_symm_apply _ } }
/-- The equivalence between `BoundedOrder` and itself induced by `order_dual` both ways. -/
@[simps functor inverse] def dual_equiv : BoundedOrder ≌ BoundedOrder :=
equivalence.mk dual dual
(nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl)
(nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl)
end BoundedOrder
lemma BoundedOrder_dual_comp_forget_to_PartialOrder :
BoundedOrder.dual ⋙ forget₂ BoundedOrder PartialOrder =
forget₂ BoundedOrder PartialOrder ⋙ PartialOrder.dual := rfl
lemma BoundedOrder_dual_comp_forget_to_Bipointed :
BoundedOrder.dual ⋙ forget₂ BoundedOrder Bipointed =
forget₂ BoundedOrder Bipointed ⋙ Bipointed.swap := rfl
|
[STATEMENT]
lemma ctx_inv_anno:
"cxt_to_stmt E c = c'@[mu] \<Longrightarrow> c = c'@[mu] \<and> E = []"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. cxt_to_stmt E c = c'@[mu] \<Longrightarrow> c = c'@[mu] \<and> E = []
[PROOF STEP]
using cxt_inv
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>cxt_to_stmt ?E ?c = ?c'; \<And>p q. ?c' \<noteq> p ;; q\<rbrakk> \<Longrightarrow> ?E = [] \<and> ?c' = ?c
goal (1 subgoal):
1. cxt_to_stmt E c = c'@[mu] \<Longrightarrow> c = c'@[mu] \<and> E = []
[PROOF STEP]
by blast |
! DART $Id: test.f90 Wed Apr 11 20:26:43 CEST 2018 $
PROGRAM test
!----------------------------------------------------------------------
! purpose: test routines
!----------------------------------------------------------------------
use types_mod, only : r4, r8, digits12, SECPERDAY, MISSING_R8, &
rad2deg, deg2rad, PI
use time_manager_mod, only : time_type, set_time, set_date, get_date, get_time,&
print_time, print_date, set_calendar_type, &
operator(*), operator(+), operator(-), &
operator(>), operator(<), operator(/), &
operator(/=), operator(<=)
use model_mod, only : static_init_model,get_model_size,get_state_meta_data,&
model_interpolate, state_vector,grib_to_sv
use location_mod, only : location_type, get_dist, query_location, &
get_close_maxdist_init, get_close_type, &
set_location, get_location, horiz_dist_only, &
vert_is_undef, VERTISUNDEF, &
vert_is_surface, VERTISSURFACE, &
vert_is_level, VERTISLEVEL, &
vert_is_pressure, VERTISPRESSURE, &
vert_is_height, VERTISHEIGHT, &
get_close_obs_init, loc_get_close_obs => get_close_obs
IMPLICIT NONE
! version controlled file description for error handling, do not edit
character(len=*), parameter :: source = "$URL: test.f90 $"
character(len=*), parameter :: revision = "$Revision: Bonn $"
character(len=*), parameter :: revdate = "$Date: Wed Apr 11 2018 $"
INTEGER :: var_type,index,istat,n,i
integer,allocatable :: seed(:)
TYPE(location_type) :: loc
REAL(r8) :: lo,la,h,val
REAL(r8),allocatable :: x(:)
REAL(r8) :: lop,lap,x1,lo1,la1,x2,lo2,la2,xo,loo,lao
TYPE(time_type) :: time
! CALL static_init_model()
! print*,get_model_size()
! index=1940880
! CALL get_state_meta_data(index,loc,var_type)
! print*,get_location(loc)
! print*,var_type
! n=get_model_size()
! allocate(x(1:n))
! allocate(seed(1:n))
! seed(1:n)=1
!
! CALL RANDOM_SEED (PUT = seed (1:n))
! CALL RANDOM_NUMBER(x)
! x=x*10-5
! h=70500.
! lo=0.8
! la=54.5
! loc=set_location(lo,la,h,VERTISPRESSURE)
! call model_interpolate(x,loc,1,val,istat)
! print*,istat
STOP
h=10.
lo=22.9
la=53.2
loc=set_location(lo,la,h,VERTISLEVEL)
call model_interpolate(x,loc,1,val,istat)
print*,istat
h=10.
lo=22.95
la=53.2
loc=set_location(lo,la,h,VERTISLEVEL)
call model_interpolate(x,loc,1,val,istat)
print*,istat
h=10.
lo=22.97
la=53.2
loc=set_location(lo,la,h,VERTISLEVEL)
call model_interpolate(x,loc,1,val,istat)
print*,istat
h=10.
lo=23.0
la=53.2
loc=set_location(lo,la,h,VERTISLEVEL)
call model_interpolate(x,loc,1,val,istat)
print*,istat
END PROGRAM test
|
[STATEMENT]
lemma dom_char\<^sub>S\<^sub>b\<^sub>C:
shows "dom f = (if arr f then C.dom f else C.null)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. local.dom f = (if arr f then C.dom f else C.null)
[PROOF STEP]
using dom_simp dom_def arr_def arr_char\<^sub>S\<^sub>b\<^sub>C
[PROOF STATE]
proof (prove)
using this:
arr ?f \<Longrightarrow> local.dom ?f = C.dom ?f
local.dom ?f = (if domains ?f \<noteq> {} then SOME a. a \<in> domains ?f else null)
arr ?f \<equiv> domains ?f \<noteq> {} \<or> codomains ?f \<noteq> {}
arr ?f = Arr ?f
goal (1 subgoal):
1. local.dom f = (if arr f then C.dom f else C.null)
[PROOF STEP]
by auto |
\documentclass[a4paper]{article}
\title{Trajectory Model Code}
\author{Jamie Kettleborough}
\begin{document}
\maketitle
\section{Introduction}
This document outlines the numerical method and code used by the BADC
trajectory model. It does not outline the details of the CGI
interface.
These are given in separate document.
\section{Numerical methods}
\subsection{Forward Time Stepping}
The time stepping of the trajectory positions is performed by a fourth
order Runge Kutta method. Details of the Runge Kutta method can be
found in standard texts such as `Numerical Recipes'. Stepping the
trajectories forward in time is simply solving the equation
\begin{displaymath}
\frac{d\bf{x}}{dt}=\bf{u}(\bf{x},t)
\end{displaymath}
where $\bf{x}$ are the parcel positions, $\bf{u}$ are the parcel
velocities, and $t$ is time.
The method requires interpolation of the forcing wind
fields onto the parcel positions. The Runge Kutta requires the
velocities at three time levels during each time step: the current
time ($t$), halfway through the time step ($t+\frac{\delta t}{2}$), and
at the end of the time step ($t+\delta t$). Depending on the relative
number of parcels being advected and the number of grid points on the
wind forcing fields it can be more efficient to interpolate in time
first or in space first. When interpolating in time first
interpolation has to be done at all the forcing field grid points.
This can be more efficient, however, since the wind from the end of
one time step ($t+\delta t$) can be carried over to become the gridded
wind at the beginning of the next time step ($t$). The code, as
written, supports both interpolation in time first or interpolation in
space first. (In retrospect the way that this is supported in the
code is not very well implemented and complicates the code
unnecessarily.)
The main time stepping routine is called {\tt runge\_kutta}.
Some important relevant variables are
\begin{tabular}{|l|l|}
\hline
Variable Name & Meaning \\
\hline
{\tt velt} & Gridded wind at current time step \\
{\tt velthdt} & Gridded wind at centre of current time step \\
{\tt veltdt} & Gridded wind at end of current time step \\
{\tt ltfirst} & Switch time interpolation first on or off \\
\hline
\end{tabular}
\subsection{Spherical Geometry}
The advection is done on a sphere (so the geometry of the surfaces of
constant height variable are approximated by spheres). This is
achieved by using Cartesian coordinates $(x,y,z)$ on a sphere. The
local vertical coordinate (pressure, or potential temperature) is
supported by a fourth dimension ($zhm$). The gridded winds are given
on a latitude-longitude grid and with eastward and northward
components. The Cartesian parcel positions have to be transformed
into latitude-longitude coordinates, and the winds then transformed
into Cartesian components. During the time stepping the Cartesian
coordinate of the parcels are renormalised to keep them on the surface
of a unit sphere.
Relevant routines include
\begin{tabular}{|l|p{15pc}|}
\hline
Routine & Purpose \\
\hline
{\tt latlon\_from\_cartesians} & convert Cartesian parcel positions in
lat-lon coordinates \\
{\tt find\_parcel\_cartesians} & convert lat-lon coordinates of parcels
to Cartesian \\
{\tt uvw} & part of this routine converts Eastward/Northward winds to
Cartesian coordinates\\
{\tt adjust} & remornamlise the Cartesian parcel positions to lie on a
unit sphere \\
\hline
\end{tabular}
\subsection{Time interpolation}
Simple linear interpolation is used to get the velocities onto the
current time. The routine {\tt time\_interp} performs the time
interpolation.
\subsection{Space interpolation}
The space interpolation is also performed by linear interpolation.
The routine {\tt uvw} is responsible for the interpolation (as well as
transforming the interpolated winds into Cartesian components). {\tt
uvw} calls helper routines:
\begin{tabular}{|l|p{15pc}|}
\hline
Routine & Purpose \\
\hline
{\tt get\_horizontal\_weights } & Calculate the interpolation weights
for the horizontal direction \\
{\tt find\_vert} & find the location of the parcels on the vertical
grid and calculate vertical interpolation weight\\
{\tt interpolate} & built in IDL routine for linear interpolation\\
\hline
\end{tabular}
\subsection{Vertical Coordinates}
The trajectory model supports parcel vertical coordinates of hybrid
pressure or potential temperature. When the vertical
coordinate of the parcel positions is the same as that of the wind
field then the wind grid information simply carries the one
dimensional level information. If the vertical coordinate of the
parcel positions is not the same as those of the gridded wind field
then there has be be a way of calculating the the gridded values of
the parcel vertical coordinate from the gridded fields, this gridded
vertical coordinate is then carried around as the three dimensional
level information. This has to be done, for instance, when the parcel
vertical coordinate is potential temperate, but the gridded wind
vertical coordinate is pressure, or hybrid sigma-pressure.
\subsection{Undefined points}
Parcels that are initialised close to the boundaries of the wind
domain may be advected out of the domain. These parcels are set as
undefined. Within the code a list of undefined parcels is carried
around as the variable {\tt in\_range}. Only parcels that are defined
are advected. Carrying the {\tt in\_range} array around probably is
not the best way to account of for undefined parcels. Simply setting
the coordinates as $-999$ may be better.
\section{Outline}
An outline of the steps made by the code is as follows:
\begin{enumerate}
\item initialise parcel positions (external to main model)
\item set inputs
\item initialise model grid (defines grid wind files are present on)
\item read first wind file
\item loop around time
\begin{enumerate}
\item read and swap winds if needed
\item new release if needed (include interpolation of temperature etc)
\item perform Runge-Kutta step
\item increment time step
\item output on this time step if needed.
\item delete an old release if needed.
\end{enumerate}
\item close any unclosed output files
\end{enumerate}
\section{Multiple Releases}
Many users want to run the same trajectories for a number of different
times, say to build up a climatology of air origins at their observing
station. To help with this kind of study trajectories can be run as a
set of multiple release trajectories. In this case trajectories are
run with identical spatial starting positions for a set of times.
\section{Time step and date handling}
The trajectory model uses a set of routines, such as {\tt dt\_add}
that were available at IDL 5.2, but which have since been
removed. They have to be made available (in Traj:Job.pm) in order to
run the trajectory model.
\end{document} |
lemma eventually_floor_less: fixes f :: "'a \<Rightarrow> 'b::{order_topology,floor_ceiling}" assumes f: "(f \<longlongrightarrow> l) F" and l: "l \<notin> \<int>" shows "\<forall>\<^sub>F x in F. of_int (floor l) < f x" |
"""
CNN for image classification
- MIT License
- Author: Sungjin Kim
"""
from sklearn import model_selection, metrics
from sklearn.preprocessing import MinMaxScaler
import numpy as np
import matplotlib.pyplot as plt
import os
from keras import backend as K
from keras.utils import np_utils
from keras.models import Model
from keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from . import skeras
from . import sfile
class CNN(Model):
def __init__(model, nb_classes, in_shape=None):
model.nb_classes = nb_classes
model.in_shape = in_shape
model.build_model()
super().__init__(model.x, model.y)
model.compile()
def build_model(model):
nb_classes = model.nb_classes
in_shape = model.in_shape
x = Input(in_shape)
h = Conv2D(32, kernel_size=(3, 3), activation='relu',
input_shape=in_shape)(x)
h = Conv2D(64, (3, 3), activation='relu')(h)
h = MaxPooling2D(pool_size=(2, 2))(h)
h = Dropout(0.25)(h)
h = Flatten()(h)
z_cl = h
h = Dense(128, activation='relu')(h)
h = Dropout(0.5)(h)
z_fl = h
y = Dense(nb_classes, activation='softmax', name='preds')(h)
model.cl_part = Model(x, z_cl)
model.fl_part = Model(x, z_fl)
model.x, model.y = x, y
def compile(model):
Model.compile(model, loss='categorical_crossentropy',
optimizer='adadelta', metrics=['accuracy'])
class DataSet:
def __init__(self, X, y, nb_classes, scaling=True, test_size=0.2, random_state=0):
"""
X is originally vector. Hence, it will be transformed
to 2D images with a channel (i.e, 3D).
"""
self.X = X
self.add_channels()
X = self.X
# the data, shuffled and split between train and test sets
X_train, X_test, y_train, y_test = model_selection.train_test_split(
X, y, test_size=0.2, random_state=random_state)
print(X_train.shape, y_train.shape)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
if scaling:
# scaling to have (0, 1) for each feature (each pixel)
scaler = MinMaxScaler()
n = X_train.shape[0]
X_train = scaler.fit_transform(
X_train.reshape(n, -1)).reshape(X_train.shape)
n = X_test.shape[0]
X_test = scaler.transform(
X_test.reshape(n, -1)).reshape(X_test.shape)
self.scaler = scaler
print('X_train shape:', X_train.shape)
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)
self.X_train, self.X_test = X_train, X_test
self.Y_train, self.Y_test = Y_train, Y_test
self.y_train, self.y_test = y_train, y_test
# self.input_shape = input_shape
def add_channels(self):
X = self.X
if len(X.shape) == 3:
N, img_rows, img_cols = X.shape
if K.image_dim_ordering() == 'th':
X = X.reshape(X.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
X = X.reshape(X.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
else:
input_shape = X.shape[1:] # channel is already included.
self.X = X
self.input_shape = input_shape
class Machine():
def __init__(self, X, y, nb_classes=2, fig=True):
self.nb_classes = nb_classes
self.set_data(X, y)
self.set_model()
self.fig = fig
def set_data(self, X, y):
nb_classes = self.nb_classes
self.data = DataSet(X, y, nb_classes)
print('data.input_shape', self.data.input_shape)
def set_model(self):
nb_classes = self.nb_classes
data = self.data
self.model = CNN(nb_classes=nb_classes, in_shape=data.input_shape)
# cnn_lenet(nb_classes=nb_classes, in_shape=data.input_shape)
def fit(self, epochs=10, batch_size=128, verbose=1):
data = self.data
model = self.model
history = model.fit(data.X_train, data.Y_train, batch_size=batch_size, epochs=epochs,
verbose=verbose, validation_data=(data.X_test, data.Y_test))
return history
def run(self, epochs=100, batch_size=128, verbose=1):
data = self.data
model = self.model
fig = self.fig
history = self.fit(epochs=epochs,
batch_size=batch_size, verbose=verbose)
score = model.evaluate(data.X_test, data.Y_test, verbose=0)
print('Confusion matrix')
Y_test_pred = model.predict(data.X_test, verbose=0)
y_test_pred = np.argmax(Y_test_pred, axis=1)
print(metrics.confusion_matrix(data.y_test, y_test_pred))
print('Test score:', score[0])
print('Test accuracy:', score[1])
# Save results
suffix = sfile.unique_filename('datatime')
foldname = 'output_' + suffix
os.makedirs(foldname)
skeras.save_history_history(
'history_history.npy', history.history, fold=foldname)
model.save_weights(os.path.join(foldname, 'dl_model.h5'))
print('Output results are saved in', foldname)
if fig:
skeras.plot_acc_loss(history)
self.history = history
return foldname
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.