text
stringlengths 0
3.34M
|
---|
using Test
@testset "ImageShow" begin
include("writemime.jl")
include("gif.jl")
include("keyboard.jl")
include("multipage.jl")
end
|
context("Test various utility functions")
test_that("Can find {{ mustache }} tags", {
test_toml = file.path("test_files", "test.toml")
test_xml = file.path("test_files", "test.xml")
test_other = tempfile(fileext=".other")
cat("I live AGAIN!", file=test_other)
expect_equal(find_tags("foo bar {{baz}}"), "baz")
expect_equal(find_tags(test_toml), c("baz", "foo"))
expect_equal(find_tags(test_xml), c("foo", "bar", "baz"))
expect_error(find_tags(test_other))
})
test_that("settmpdir is working temporaly and not pernamently", {
wd = getwd()
tmpdir = tempdir()
test_settmpdir = function(){
settmpdir(tmpdir)
getwd()
}
expect_equal(test_settmpdir(), tmpdir)
expect_equal({test_settmpdir(); getwd()}, wd)
})
test_that("test mkdir is silently creating path", {
tmpdir = tempdir()
test_dir = file.path(tmpdir, "test")
expect_false(dir.exists(test_dir))
expect_silent(mkdir(test_dir))
expect_true(dir.exists(test_dir))
expect_silent(mkdir(test_dir))
unlink(test_dir, recursive=TRUE)
})
test_that("joining text ignores empty symbols", {
expect_equal(join(NULL, "foo"), "foo")
expect_equal(join("foo", NULL), "foo")
expect_equal(join(NA, "foo"), "foo")
expect_equal(join("foo", NA), "foo")
expect_equal(join("", "foo"), "foo")
expect_equal(join("foo", ""), "foo")
expect_equal(join("foo", "foo"), paste("foo", "foo"))
})
|
State Before: R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
hp : p ≠ 0
⊢ weightedTotalDegree' w p = ↑(weightedTotalDegree w p) State After: R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
hp : ∃ a, ↑a = weightedTotalDegree' w p
⊢ weightedTotalDegree' w p = ↑(weightedTotalDegree w p) Tactic: rw [Ne.def, ← weightedTotalDegree'_eq_bot_iff w p, ← Ne.def, WithBot.ne_bot_iff_exists] at hp State Before: R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
hp : ∃ a, ↑a = weightedTotalDegree' w p
⊢ weightedTotalDegree' w p = ↑(weightedTotalDegree w p) State After: case intro
R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
m : M
hm : ↑m = weightedTotalDegree' w p
⊢ weightedTotalDegree' w p = ↑(weightedTotalDegree w p) Tactic: obtain ⟨m, hm⟩ := hp State Before: case intro
R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
m : M
hm : ↑m = weightedTotalDegree' w p
⊢ weightedTotalDegree' w p = ↑(weightedTotalDegree w p) State After: case intro.a
R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
m : M
hm : ↑m = weightedTotalDegree' w p
⊢ weightedTotalDegree' w p ≤ ↑(weightedTotalDegree w p)
case intro.a
R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
m : M
hm : ↑m = weightedTotalDegree' w p
⊢ ↑(weightedTotalDegree w p) ≤ weightedTotalDegree' w p Tactic: apply le_antisymm State Before: case intro.a
R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
m : M
hm : ↑m = weightedTotalDegree' w p
⊢ weightedTotalDegree' w p ≤ ↑(weightedTotalDegree w p) State After: case intro.a
R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
m : M
hm : ↑m = weightedTotalDegree' w p
⊢ ∀ (b : σ →₀ ℕ), b ∈ support p → ↑(weightedDegree' w) b ≤ sup (support p) fun s => ↑(weightedDegree' w) s Tactic: simp only [weightedTotalDegree, weightedTotalDegree', Finset.sup_le_iff, WithBot.coe_le_coe] State Before: case intro.a
R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
m : M
hm : ↑m = weightedTotalDegree' w p
⊢ ∀ (b : σ →₀ ℕ), b ∈ support p → ↑(weightedDegree' w) b ≤ sup (support p) fun s => ↑(weightedDegree' w) s State After: case intro.a
R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
m : M
hm : ↑m = weightedTotalDegree' w p
b : σ →₀ ℕ
⊢ b ∈ support p → ↑(weightedDegree' w) b ≤ sup (support p) fun s => ↑(weightedDegree' w) s Tactic: intro b State Before: case intro.a
R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
m : M
hm : ↑m = weightedTotalDegree' w p
b : σ →₀ ℕ
⊢ b ∈ support p → ↑(weightedDegree' w) b ≤ sup (support p) fun s => ↑(weightedDegree' w) s State After: no goals Tactic: exact Finset.le_sup State Before: case intro.a
R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
m : M
hm : ↑m = weightedTotalDegree' w p
⊢ ↑(weightedTotalDegree w p) ≤ weightedTotalDegree' w p State After: case intro.a
R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
m : M
hm : ↑m = weightedTotalDegree' w p
⊢ ↑(sup (support p) fun s => ↑(weightedDegree' w) s) ≤ weightedTotalDegree' w p Tactic: simp only [weightedTotalDegree] State Before: case intro.a
R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
m : M
hm : ↑m = weightedTotalDegree' w p
⊢ ↑(sup (support p) fun s => ↑(weightedDegree' w) s) ≤ weightedTotalDegree' w p State After: case intro.a
R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
m : M
hm : ↑m = weightedTotalDegree' w p
hm' : weightedTotalDegree' w p ≤ ↑m
⊢ ↑(sup (support p) fun s => ↑(weightedDegree' w) s) ≤ weightedTotalDegree' w p Tactic: have hm' : weightedTotalDegree' w p ≤ m := le_of_eq hm.symm State Before: case intro.a
R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
m : M
hm : ↑m = weightedTotalDegree' w p
hm' : weightedTotalDegree' w p ≤ ↑m
⊢ ↑(sup (support p) fun s => ↑(weightedDegree' w) s) ≤ weightedTotalDegree' w p State After: case intro.a
R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
m : M
hm : ↑m = weightedTotalDegree' w p
hm' : weightedTotalDegree' w p ≤ ↑m
⊢ ↑(sup (support p) fun s => ↑(weightedDegree' w) s) ≤ ↑m Tactic: rw [← hm] State Before: case intro.a
R : Type u_2
M : Type u_3
inst✝³ : CommSemiring R
σ : Type u_1
inst✝² : AddCommMonoid M
inst✝¹ : SemilatticeSup M
inst✝ : OrderBot M
w : σ → M
p : MvPolynomial σ R
m : M
hm : ↑m = weightedTotalDegree' w p
hm' : weightedTotalDegree' w p ≤ ↑m
⊢ ↑(sup (support p) fun s => ↑(weightedDegree' w) s) ≤ ↑m State After: no goals Tactic: simpa [weightedTotalDegree'] using hm'
|
# ML 101
## 3. SVD
```python
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import scipy.stats
import sklearn.preprocessing
```
We start off with the [Iris flower dataset](https://en.wikipedia.org/wiki/Iris_flower_data_set). The data is multivariate, with 150 measurements of 4 features (length and width cm of both sepal and petal) on 3 distinct Iris species. Of the 150 measurements, there are 50 measurements each for _Iris setosa_, _Iris versicolor_, and _Iris virginica_.
```python
data = pd.read_csv('https://media.githubusercontent.com/media/mariolpantunes/ml101/main/datasets/iris.csv')
variety={'Setosa':0, 'Versicolor':1, 'Virginica':2}
data.variety = [variety[item] for item in data.variety]
df_iris = data[['sepal.length','sepal.width','petal.length','petal.width']]
iris = data[['variety']]
iris = iris.to_numpy()[:,0]
print('Iris dataset has {} rows and {} columns\n'.format(*df_iris.shape))
print('Here are the first 5 rows of the data:\n\n{}\n'.format(df_iris.head(5)))
print('Some simple statistics on the Iris dataset:\n\n{}\n'.format(df_iris.describe()))
```
As we are exploring the dataset, it would be nice to view the data in order to get an idea of how the 3 species might be distributed with respect to one another in terms of their features. Perhaps we are interested in finding clusters, or maybe we would like to find a way to make class predictions?
However, since the data has 4 dimensions, we would be hard-pressed to come up with a good way to graph the data in 4D that we could easily understand.
_But what if we could reduce or compress the data so that we could work in 3 dimensions or less?_
[Singular value decomposition](http://mathworld.wolfram.com/SingularValueDecomposition.html) lets us do just that.
## Singular value decomposition
Singular value decomposition factorizes an $\mathbb{R}^{m \times n}$ matrix $X$ into
* matrix $U \in \mathbb{R}^{m \times m}$ are the left-singular vectors of $X$, where columns are the set of orthonormal eigenvectors of $X \, X^{\intercal}$
* diagonal matrix $\Sigma$ with entries $\sigma \in \mathbb{R}$ that are the non-negative singular values of $X$
* matrix $V \in \mathbb{R}^{n \times n}$ are the right-singular vectors $X$, where the columns are the set of orthonormal eigenvectors of $X^{\intercal} \, X$
such that
\begin{align}
X &= U \, \Sigma \, V^{\intercal}
\end{align}
We can use [`numpy.linalg.svd`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.svd.html) to factorize the Iris data matrix into three components $U$, $\Sigma$, and $V^{\intercal}$.
```python
U_iris, S_iris, Vt_iris = np.linalg.svd(df_iris)
```
#### $U$: left-singular vectors of $X$
The rows of the $U$ correspond to the rows of original data matrix $X$, while the columns are the set of ordered, orthornormal eigenvectors of $X \, X^{\intercal}$.
```python
print('matrix U has {} rows, {} columns\n'.format(*U_iris.shape))
print('{}'.format(pd.DataFrame(U_iris).head(5)))
```
#### $V$: right-singular vectors of $X$
[`numpy.linalg.svd`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.svd.html) actually returns $V^{\intercal}$ instead of $V$, so it is the _columns_ of $V^{\intercal}$ that correspond to the columns of original data matrix $X$. Hence, the _rows_ are the set of ordered, orthornormal eigenvectors of $X^{\intercal} \, X$.
```python
print('matrix Vt has {} rows, {} columns\n'.format(*Vt_iris.shape))
print('{}'.format(pd.DataFrame(Vt_iris).head()))
```
#### $\Sigma$: singular values of $X$
The elements $\sigma_{i}$ of diagonal matrix $\Sigma$ are the non-zero singular values of matrix $X$, which are really just the square roots of the non-zero eigenvalues of $X^{\intercal} \, X$ (and also for $X \, X^{\intercal}$). These singular values can be used to determine the amount of variance $X^{\prime}$ explains of the original data matrix $X$ when reducing the dimensions to find a lower rank approximation.
\begin{align}
X^{\prime}_{k} &= U_{k} \, \Sigma_{k} \, V^{\intercal}_{k} \\
&\approx X_{r} & \text{ where } rank(X^{\prime}) = k \lt rank(X) = r
\end{align}
The amount of variance that the reduced rank approximation $X^{\prime}_{k}$ explains of $X_{r}$ is
\begin{align}
\text{cum. variance explained} &= \frac{\sum_{j=1}^{k} \sigma_{j}^{2}}{\sum_{i=1}^{r} \sigma_{i}^{2}}
\end{align}
**NOTE**: [`numpy.linalg.svd`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.svd.html) actually returns a $\Sigma$ that is not a diagonal _matrix_, but a _list_ of the entries on the diagonal.
```python
num_sv_iris = np.arange(1, S_iris.size+1)
cum_var_explained_iris = [np.sum(np.square(S_iris[0:n])) / np.sum(np.square(S_iris)) for n in num_sv_iris]
```
Let's have a look at the cumulative variance explained visually as a function of the number of singular values used when reducing rank to find a lower-ranked matrix $X^{\prime}$ to approximate $X$. This will inform us as to how many dimensions we should use.
```python
fig = plt.figure(figsize=(7.0,5.5))
ax = fig.add_subplot(111)
plt.plot(num_sv_iris,
cum_var_explained_iris,
color='#2171b5',
label='variance explained',
alpha=0.65,
zorder=1000)
plt.scatter(num_sv_iris,
sklearn.preprocessing.normalize(S_iris.reshape((1,-1))),
color='#fc4e2a',
label='singular values (normalized)',
alpha=0.65,
zorder=1000)
plt.legend(loc='center right', scatterpoints=1, fontsize=8)
ax.set_xticks(num_sv_iris)
ax.set_xlim(0.8, 4.1)
ax.set_ylim(0.0, 1.1)
ax.set_xlabel(r'Number of singular values used')
ax.set_ylabel('Variance in data explained')
ax.set_title('Iris dataset: cumulative variance explained & singular values',
fontsize=14,
y=1.03)
ax.set_facecolor('0.98')
plt.grid(alpha=0.8, zorder=1)
plt.tight_layout()
plt.show()
```
#### Dimension reduction
Judging from the curve representing cumulative variance explained in the figure above, we can see that
* with 1 singular value, about 96.5% of the variance of $X$ can be explained
* with 2 singular values, that number goes up to approximately 99.8%
Since graphing the Iris dataset in 1D wouldn't be all that interesting (just dots on a line segment), let's try using the first 2 singular values to represent the data on the $x$- and $y$-axes, respectively.
```python
idx_setosa = np.where(iris==0)[0]
idx_versicolor = np.where(iris==1)[0]
idx_virginica = np.where(iris==2)[0]
setosa_x = U_iris[idx_setosa, 0]
setosa_y = U_iris[idx_setosa, 1]
versicolor_x = U_iris[idx_versicolor, 0]
versicolor_y = U_iris[idx_versicolor, 1]
virginica_x = U_iris[idx_virginica, 0]
virginica_y = U_iris[idx_virginica, 1]
```
We will use different marker shapes and colors to represent the three Iris species on our 2D graph.
```python
fig = plt.figure(figsize=(7.0,5.5))
ax = fig.add_subplot(111)
plt.scatter(setosa_x,
setosa_y,
marker='o',
color='#66c2a5',
label='Iris-setosa',
zorder=1000)
plt.scatter(versicolor_x,
versicolor_y,
marker='D',
color='#fc8d62',
label='Iris-versicolor',
zorder=1000)
plt.scatter(virginica_x,
virginica_y,
marker='^',
color='#8da0cb',
label='Iris-virginica',
zorder=1000)
plt.legend(loc='upper left', scatterpoints=1, fontsize=8)
ax.set_xlabel(r'singular value $\sigma_{1}$')
ax.set_ylabel(r'singular value $\sigma_{2}$')
ax.set_title('2D plot of Iris dataset',
fontsize=14,
y=1.03)
ax.set_facecolor('0.98')
plt.grid(alpha=0.6, zorder=1)
plt.tight_layout()
```
There!
Now that we are viewing the originally 4D data with 2 dimensions using the first 2 singular value columns of the $U$ left singular vectors matrix, we can see that there should be a very clear separation for the _Iris setosa_ class and the others. On the other hand, the demarcation between _Iris versicolor_ and _Iris virginica_ might not be as clear cut.
Nevertheless, since this 2D reduced-rank matrix representation $X^{\prime}$ explains nearly 99.8% of the variance in the original dataset, we can be pretty certain that clustering and classification should be possible.
# Helpful Resources
* [Making sense of principal component analysis, eigenvectors & eigenvalues](https://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues/140579#140579)
* [Correspondence analysis is a useful tool to uncover the relationships among categorical variables](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3718710/)
----
# Appendix A
## PCA and SVD
Principal components analysis (PCA) and singular value decomposition are closely related, and you may often hear both these terms used in the same breath.
Here is a quick mathematical treatment explaining how PCA and SVD are related.
Consider data matrix $X \in \mathbb{R}^{m \times n}$ where $m > n$, and all $x_{ij}$ are centered about the column means. With principal components analysis, we have
\begin{align}
\text{covariance matrix } C &= \frac{1}{m} \, X^{\intercal} \, X & \text{from PCA} \\
&= \frac{1}{m} \, V \, \Gamma \, V^{\intercal} & \text{by eigendecomposition of } X^{\intercal} \, X \\
\\
\text{ but } X &= U \, \Sigma V^{\intercal} & \text{from SVD} \\
\\
\Rightarrow C &= \frac{1}{m} \, V \, \Sigma \, U^{\intercal} \, U \, \Sigma V^{\intercal} \\
&= \frac{1}{m} \, V \, \Sigma^{2} \, V^{\intercal} \\
\end{align}
So we see that:
1. the singular values in $\Sigma$ obtained via SVD are really just the square roots of the eigenvalues in $\Gamma$ of the covariance matrix in PCA.
1. if you mean-center your raw data matrix $X$ and then calculate SVD, you are doing the same thing as PCA.
1. the above example shows covariance of $X$ with respect to its columns ($X^{\intercal} \, X$); it also applies for covariance of $X$ with respect to rows ($X \, X^{\intercal}$).
#### Iris dataset: PCA & SVD
```python
from sklearn.decomposition import PCA
pca = PCA()
pca.fit(df_iris)
# don't forget to mean-center the data before SVD
X = df_iris - np.mean(df_iris, axis=0)
U, S, Vt = np.linalg.svd(X)
```
#### Compare the eigenvalues of $\Gamma$ derived from PCA with the singular values from $\Sigma$ derived with SVD: $\Gamma = \Sigma^{2}$?
```python
Cov_pca = pca.get_covariance()
print('eigenvalues from PCA:\n{}\n'.format(np.linalg.eigvals(Cov_pca * X.shape[0])))
print('squared singular values from SVD:\n{}'.format(np.square(S)))
```
#### Can we obtain the covariance matrix $C$ derived with PCA, but using $\frac{1}{m} \, V \, \Sigma^{2} \, V^{\intercal}$ from SVD?
```python
print('covariance matrix C derived from PCA:\n{}\n'.format(Cov_pca))
Cov_svd = (1. / X.shape[0]) * Vt.T.dot(np.diag(np.square(S))).dot(Vt)
print('covariance matrix using S and Vt from SVD:\n{}\n'.format(Cov_svd))
allclose = np.allclose(Cov_pca, Cov_svd, atol=1e-1)
print('Are these matrices equivalent (element-wise closeness comparison)?\n{}'.format(allclose))
```
|
/-
Tests for norm_cast
-/
import Mathlib.Tactic.NormCast
import Mathlib.Tactic.Ring
import Mathlib.Data.Option.Defs
import Mathlib.Data.Rat.Cast
-- import data.complex.basic -- ℕ, ℤ, ℚ, ℝ, ℂ
-- import data.real.ennreal
-- set_option trace.Tactic.norm_cast true
-- set_option trace.Meta.Tactic.simp true
variable (an bn cn dn : ℕ) (az bz cz dz : ℤ)
variable (aq bq cq dq : ℚ)
-- variable (ar br cr dr : ℝ) (ac bc cc dc : ℂ)
example : (an : ℤ) = bn → an = bn := by intro h; exact_mod_cast h
example : an = bn → (an : ℤ) = bn := by intro h; exact_mod_cast h
example : az = bz ↔ (az : ℚ) = bz := by norm_cast
-- example : (aq : ℝ) = br ↔ (aq : ℂ) = br := by norm_cast
-- example : (an : ℚ) = bz ↔ (an : ℂ) = bz := by norm_cast
-- example : (((an : ℤ) : ℚ) : ℝ) = bq ↔ ((an : ℚ) : ℂ) = (bq : ℝ) :=
-- by norm_cast
example : (an : ℤ) < bn ↔ an < bn := by norm_cast
-- example : (an : ℚ) < bz ↔ (an : ℝ) < bz := by norm_cast
-- example : ((an : ℤ) : ℝ) < bq ↔ (an : ℚ) < bq := by norm_cast
example : (an : ℤ) ≠ (bn : ℤ) ↔ an ≠ bn := by norm_cast
-- zero and one cause special problems
-- example : 0 < (bq : ℝ) ↔ 0 < bq := by norm_cast
example : az > (1 : ℕ) ↔ az > 1 := by norm_cast
example : az > (0 : ℕ) ↔ az > 0 := by norm_cast
example : (an : ℤ) ≠ 0 ↔ an ≠ 0 := by norm_cast
example : aq < (1 : ℕ) ↔ (aq : ℚ) < (1 : ℤ) := by norm_cast
-- example : aq < (1 : ℕ) ↔ (aq : ℝ) < (1 : ℤ) := by norm_cast
example : (an : ℤ) + bn = (an + bn : ℕ) := by norm_cast
-- example : (an : ℂ) + bq = ((an + bq) : ℚ) := by norm_cast
-- example : (((an : ℤ) : ℚ) : ℝ) + bn = (an + (bn : ℤ)) := by norm_cast
example (h : ((an + bn : ℕ) : ℤ) = (an : ℤ) + (bn : ℤ)) : True := by
push_cast at h
guard_hyp h : (an : ℤ) + (bn : ℤ) = (an : ℤ) + (bn : ℤ)
trivial
example (h : ((an * bn : ℕ) : ℤ) = (an : ℤ) * (bn : ℤ)) : True := by
push_cast at h
guard_hyp h : (an : ℤ) * (bn : ℤ) = (an : ℤ) * (bn : ℤ)
trivial
-- example : (((((an : ℚ) : ℝ) * bq) + (cq : ℝ) ^ dn) : ℂ) = (an : ℂ) * (bq : ℝ) + cq ^ dn :=
-- by norm_cast
-- example : ((an : ℤ) : ℝ) < bq ∧ (cr : ℂ) ^ 2 = dz ↔ (an : ℚ) < bq ∧ ((cr ^ 2) : ℂ) = dz :=
-- by norm_cast
--testing numerals
example : ((42 : ℕ) : ℤ) = 42 := by norm_cast
-- example : ((42 : ℕ) : ℂ) = 42 := by norm_cast
example : ((42 : ℤ) : ℚ) = 42 := by norm_cast
-- example : ((42 : ℚ) : ℝ) = 42 := by norm_cast
structure p (n : ℤ)
example : p 42 := by
norm_cast
-- TODO: guard_target_mod_implicit
-- guard_target = p 42
exact ⟨⟩
-- example (h : (an : ℝ) = 0) : an = 0 := by exact_mod_cast h
-- example (h : (an : ℝ) = 42) : an = 42 := by exact_mod_cast h
-- example (h : (an + 42) ≠ 42) : (an : ℝ) + 42 ≠ 42 := by exact_mod_cast h
example (n : ℤ) (h : n + 1 > 0) : ((n + 1 : ℤ) : ℚ) > 0 := by exact_mod_cast h
-- testing the heuristic
example (h : bn ≤ an) : an - bn = 1 ↔ (an - bn : ℤ) = 1 :=
by norm_cast
-- example (h : (cz : ℚ) = az / bz) : (cz : ℝ) = az / bz :=
-- by assumption_mod_cast
namespace hidden
def WithZero (α) := Option α
@[coe]
def WithZero.of (a : α) : WithZero α := some a
instance : CoeTail α (WithZero α) := ⟨WithZero.of⟩
instance : Zero (WithZero α) := ⟨none⟩
instance [One α] : One (WithZero α) := ⟨some 1⟩
instance [Mul α] : MulZeroClass (WithZero α) where
mul o₁ o₂ := o₁.bind fun a => o₂.map fun b => a * b
zero_mul a := rfl
mul_zero a := by cases a <;> rfl
@[norm_cast] lemma coe_one [One α] : ((1 : α) : WithZero α) = 1 := rfl
@[norm_cast] lemma coe_inj {a b : α} : (a : WithZero α) = b ↔ a = b :=
Option.some_inj
@[norm_cast] lemma mul_coe [Mul α] (a b : α) :
((a * b : α) : WithZero α) = (a : WithZero α) * b := rfl
example [Mul α] [One α] (x y : α) (h : (x : WithZero α) * y = 1) : x * y = 1 := by
exact_mod_cast h
end hidden
example (k : ℕ) {x y : ℕ} :
(x * x + y * y : ℤ) - ↑((x * y + 1) * k) = ↑y * ↑y - ↑k * ↑x * ↑y + (↑x * ↑x - ↑k) :=
by
push_cast
ring
example (k : ℕ) {x y : ℕ} (h : ((x + y + k : ℕ) : ℤ) = 0) : x + y + k = 0 := by
push_cast at h
-- TODO: guard_hyp_mod_implicit
-- guard_hyp h : (x : ℤ) + y + k = 0
assumption_mod_cast
example (a b : ℕ) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) :
((a + b : ℕ) : ℤ) = 10 :=
by
push_cast
push_cast [Int.add_zero] at h2
exact h2
-- example {x : ℚ} : ((x + 42 : ℚ) : ℝ) = x + 42 := by push_cast
namespace ennreal
-- --TODO: debug
-- lemma half_lt_self_bis {a : ℝ≥0∞} (hz : a ≠ 0) (ht : a ≠ ⊤) : a / 2 < a :=
-- begin
-- lift a to nnreal using ht,
-- have h : (2 : ℝ≥0∞) = ((2 : nnreal) : ℝ≥0∞), from rfl,
-- have h' : (2 : nnreal) ≠ 0, from _root_.two_ne_zero',
-- rw [h, ← coe_div h', coe_lt_coe], -- `norm_cast` fails to apply `coe_div`
-- norm_cast at hz,
-- exact nnreal.half_lt_self hz
-- end
end ennreal
lemma b (h g : true) : true ∧ true := by
constructor
assumption_mod_cast
assumption_mod_cast
|
(* Title: Pnet.thy
License: BSD 2-Clause. See LICENSE.
Author: Timothy Bourke
*)
header "Lemmas for partial networks"
theory Pnet
imports AWN_SOS Invariants
begin
text \<open>
These lemmas mostly concern the preservation of node structure by @{term pnet_sos} transitions.
\<close>
lemma pnet_maintains_dom:
assumes "(s, a, s') \<in> trans (pnet np p)"
shows "net_ips s = net_ips s'"
using assms proof (induction p arbitrary: s a s')
fix i R \<sigma> s a s'
assume "(s, a, s') \<in> trans (pnet np \<langle>i; R\<rangle>)"
hence "(s, a, s') \<in> node_sos (trans (np i))" ..
thus "net_ips s = net_ips s'"
by (rule node_sos.cases) simp_all
next
fix p1 p2 s a s'
assume "\<And>s a s'. (s, a, s') \<in> trans (pnet np p1) \<Longrightarrow> net_ips s = net_ips s'"
and "\<And>s a s'. (s, a, s') \<in> trans (pnet np p2) \<Longrightarrow> net_ips s = net_ips s'"
and "(s, a, s') \<in> trans (pnet np (p1 \<parallel> p2))"
thus "net_ips s = net_ips s'"
by simp (erule pnet_sos.cases, simp_all)
qed
lemma pnet_net_ips_net_tree_ips [elim]:
assumes "s \<in> reachable (pnet np p) I"
shows "net_ips s = net_tree_ips p"
using assms proof induction
fix s
assume "s \<in> init (pnet np p)"
thus "net_ips s = net_tree_ips p"
proof (induction p arbitrary: s)
fix i R s
assume "s \<in> init (pnet np \<langle>i; R\<rangle>)"
then obtain ns where "s = NodeS i ns R" ..
thus "net_ips s = net_tree_ips \<langle>i; R\<rangle>"
by simp
next
fix p1 p2 s
assume IH1: "\<And>s. s \<in> init (pnet np p1) \<Longrightarrow> net_ips s = net_tree_ips p1"
and IH2: "\<And>s. s \<in> init (pnet np p2) \<Longrightarrow> net_ips s = net_tree_ips p2"
and "s \<in> init (pnet np (p1 \<parallel> p2))"
from this(3) obtain s1 s2 where "s1 \<in> init (pnet np p1)"
and "s2 \<in> init (pnet np p2)"
and "s = SubnetS s1 s2" by auto
from this(1-2) have "net_ips s1 = net_tree_ips p1"
and "net_ips s2 = net_tree_ips p2"
using IH1 IH2 by auto
with \<open>s = SubnetS s1 s2\<close> show "net_ips s = net_tree_ips (p1 \<parallel> p2)" by auto
qed
next
fix s a s'
assume "(s, a, s') \<in> trans (pnet np p)"
and "net_ips s = net_tree_ips p"
from this(1) have "net_ips s = net_ips s'"
by (rule pnet_maintains_dom)
with \<open>net_ips s = net_tree_ips p\<close> show "net_ips s' = net_tree_ips p"
by simp
qed
lemma pnet_init_net_ips_net_tree_ips:
assumes "s \<in> init (pnet np p)"
shows "net_ips s = net_tree_ips p"
using assms(1) by (rule reachable_init [THEN pnet_net_ips_net_tree_ips])
lemma pnet_init_in_net_ips_in_net_tree_ips [elim]:
assumes "s \<in> init (pnet np p)"
and "i \<in> net_ips s"
shows "i \<in> net_tree_ips p"
using assms by (clarsimp dest!: pnet_init_net_ips_net_tree_ips)
lemma pnet_init_not_in_net_tree_ips_not_in_net_ips [elim]:
assumes "s \<in> init (pnet np p)"
and "i \<notin> net_tree_ips p"
shows "i \<notin> net_ips s"
proof
assume "i \<in> net_ips s"
with assms(1) have "i \<in> net_tree_ips p" ..
with assms(2) show False ..
qed
lemma net_node_reachable_is_node:
assumes "st \<in> reachable (pnet np \<langle>ii; R\<^sub>i\<rangle>) I"
shows "\<exists>ns R. st = NodeS ii ns R"
using assms proof induct
fix s
assume "s \<in> init (pnet np \<langle>ii; R\<^sub>i\<rangle>)"
thus "\<exists>ns R. s = NodeS ii ns R"
by (rule pnet_node_init') simp
next
fix s a s'
assume "s \<in> reachable (pnet np \<langle>ii; R\<^sub>i\<rangle>) I"
and "\<exists>ns R. s = NodeS ii ns R"
and "(s, a, s') \<in> trans (pnet np \<langle>ii; R\<^sub>i\<rangle>)"
and "I a"
thus "\<exists>ns R. s' = NodeS ii ns R"
by (auto simp add: trans_node_comp dest!: node_sos_dest)
qed
lemma partial_net_preserves_subnets:
assumes "(SubnetS s t, a, st') \<in> pnet_sos (trans (pnet np p1)) (trans (pnet np p2))"
shows "\<exists>s' t'. st' = SubnetS s' t'"
using assms by cases simp_all
lemma net_par_reachable_is_subnet:
assumes "st \<in> reachable (pnet np (p1 \<parallel> p2)) I"
shows "\<exists>s t. st = SubnetS s t"
using assms by induct (auto dest!: partial_net_preserves_subnets)
lemma reachable_par_subnet_induct [consumes, case_names init step]:
assumes "SubnetS s t \<in> reachable (pnet np (p1 \<parallel> p2)) I"
and init: "\<And>s t. SubnetS s t \<in> init (pnet np (p1 \<parallel> p2)) \<Longrightarrow> P s t"
and step: "\<And>s t s' t' a. \<lbrakk>
SubnetS s t \<in> reachable (pnet np (p1 \<parallel> p2)) I;
P s t; (SubnetS s t, a, SubnetS s' t') \<in> (trans (pnet np (p1 \<parallel> p2))); I a \<rbrakk>
\<Longrightarrow> P s' t'"
shows "P s t"
using assms(1) proof (induction "SubnetS s t" arbitrary: s t)
fix s t
assume "SubnetS s t \<in> init (pnet np (p1 \<parallel> p2))"
with init show "P s t" .
next
fix st a s' t'
assume "st \<in> reachable (pnet np (p1 \<parallel> p2)) I"
and tr: "(st, a, SubnetS s' t') \<in> trans (pnet np (p1 \<parallel> p2))"
and "I a"
and IH: "\<And>s t. st = SubnetS s t \<Longrightarrow> P s t"
from this(1) obtain s t where "st = SubnetS s t"
and str: "SubnetS s t \<in> reachable (pnet np (p1 \<parallel> p2)) I"
by (metis net_par_reachable_is_subnet)
note this(2)
moreover from IH and \<open>st = SubnetS s t\<close> have "P s t" .
moreover from \<open>st = SubnetS s t\<close> and tr
have "(SubnetS s t, a, SubnetS s' t') \<in> trans (pnet np (p1 \<parallel> p2))" by simp
ultimately show "P s' t'"
using \<open>I a\<close> by (rule step)
qed
lemma subnet_reachable:
assumes "SubnetS s1 s2 \<in> reachable (pnet np (p1 \<parallel> p2)) TT"
shows "s1 \<in> reachable (pnet np p1) TT"
"s2 \<in> reachable (pnet np p2) TT"
proof -
from assms have "s1 \<in> reachable (pnet np p1) TT
\<and> s2 \<in> reachable (pnet np p2) TT"
proof (induction rule: reachable_par_subnet_induct)
fix s1 s2
assume "SubnetS s1 s2 \<in> init (pnet np (p1 \<parallel> p2))"
thus "s1 \<in> reachable (pnet np p1) TT
\<and> s2 \<in> reachable (pnet np p2) TT"
by (auto dest: reachable_init)
next
case (step s1 s2 s1' s2' a)
hence "SubnetS s1 s2 \<in> reachable (pnet np (p1 \<parallel> p2)) TT"
and sr1: "s1 \<in> reachable (pnet np p1) TT"
and sr2: "s2 \<in> reachable (pnet np p2) TT"
and "(SubnetS s1 s2, a, SubnetS s1' s2') \<in> trans (pnet np (p1 \<parallel> p2))" by auto
from this(4)
have "(SubnetS s1 s2, a, SubnetS s1' s2') \<in> pnet_sos (trans (pnet np p1)) (trans (pnet np p2))"
by simp
thus "s1' \<in> reachable (pnet np p1) TT
\<and> s2' \<in> reachable (pnet np p2) TT"
by cases (insert sr1 sr2, auto elim: reachable_step)
qed
thus "s1 \<in> reachable (pnet np p1) TT"
"s2 \<in> reachable (pnet np p2) TT" by auto
qed
lemma delivered_to_node [elim]:
assumes "s \<in> reachable (pnet np \<langle>ii; R\<^sub>i\<rangle>) TT"
and "(s, i:deliver(d), s') \<in> trans (pnet np \<langle>ii; R\<^sub>i\<rangle>)"
shows "i = ii"
proof -
from assms(1) obtain P R where "s = NodeS ii P R"
by (metis net_node_reachable_is_node)
with assms(2) show "i = ii"
by (clarsimp simp add: trans_node_comp elim!: node_deliverTE')
qed
lemma delivered_to_net_ips:
assumes "s \<in> reachable (pnet np p) TT"
and "(s, i:deliver(d), s') \<in> trans (pnet np p)"
shows "i \<in> net_ips s"
using assms proof (induction p arbitrary: s s')
fix ii R\<^sub>i s s'
assume sr: "s \<in> reachable (pnet np \<langle>ii; R\<^sub>i\<rangle>) TT"
and "(s, i:deliver(d), s') \<in> trans (pnet np \<langle>ii; R\<^sub>i\<rangle>)"
from this(2) have tr: "(s, i:deliver(d), s') \<in> node_sos (trans (np ii))" by simp
from sr obtain P R where [simp]: "s = NodeS ii P R"
by (metis net_node_reachable_is_node)
moreover from tr obtain P' R' where [simp]: "s' = NodeS ii P' R'"
by simp (metis node_sos_dest)
ultimately have "i = ii" using tr by auto
thus "i \<in> net_ips s" by simp
next
fix p1 p2 s s'
assume IH1: "\<And>s s'. \<lbrakk> s \<in> reachable (pnet np p1) TT;
(s, i:deliver(d), s') \<in> trans (pnet np p1) \<rbrakk> \<Longrightarrow> i \<in> net_ips s"
and IH2: "\<And>s s'. \<lbrakk> s \<in> reachable (pnet np p2) TT;
(s, i:deliver(d), s') \<in> trans (pnet np p2) \<rbrakk> \<Longrightarrow> i \<in> net_ips s"
and sr: "s \<in> reachable (pnet np (p1 \<parallel> p2)) TT"
and tr: "(s, i:deliver(d), s') \<in> trans (pnet np (p1 \<parallel> p2))"
from tr have "(s, i:deliver(d), s') \<in> pnet_sos (trans (pnet np p1)) (trans (pnet np p2))"
by simp
thus "i \<in> net_ips s"
proof (rule partial_deliverTE)
fix s1 s1' s2
assume "s = SubnetS s1 s2"
and "s' = SubnetS s1' s2"
and tr: "(s1, i:deliver(d), s1') \<in> trans (pnet np p1)"
from sr have "s1 \<in> reachable (pnet np p1) TT"
by (auto simp only: \<open>s = SubnetS s1 s2\<close> elim: subnet_reachable)
hence "i \<in> net_ips s1" using tr by (rule IH1)
thus "i \<in> net_ips s" by (simp add: \<open>s = SubnetS s1 s2\<close>)
next
fix s2 s2' s1
assume "s = SubnetS s1 s2"
and "s' = SubnetS s1 s2'"
and tr: "(s2, i:deliver(d), s2') \<in> trans (pnet np p2)"
from sr have "s2 \<in> reachable (pnet np p2) TT"
by (auto simp only: \<open>s = SubnetS s1 s2\<close> elim: subnet_reachable)
hence "i \<in> net_ips s2" using tr by (rule IH2)
thus "i \<in> net_ips s" by (simp add: \<open>s = SubnetS s1 s2\<close>)
qed
qed
lemma wf_net_tree_net_ips_disjoint [elim]:
assumes "wf_net_tree (p1 \<parallel> p2)"
and "s1 \<in> reachable (pnet np p1) S"
and "s2 \<in> reachable (pnet np p2) S"
shows "net_ips s1 \<inter> net_ips s2 = {}"
proof -
from \<open>wf_net_tree (p1 \<parallel> p2)\<close> have "net_tree_ips p1 \<inter> net_tree_ips p2 = {}" by auto
moreover from assms(2) have "net_ips s1 = net_tree_ips p1" ..
moreover from assms(3) have "net_ips s2 = net_tree_ips p2" ..
ultimately show ?thesis by simp
qed
lemma init_mapstate_Some_aodv_init [elim]:
assumes "s \<in> init (pnet np p)"
and "netmap s i = Some v"
shows "v \<in> init (np i)"
using assms proof (induction p arbitrary: s)
fix ii R s
assume "s \<in> init (pnet np \<langle>ii; R\<rangle>)"
and "netmap s i = Some v"
from this(1) obtain ns where "s = NodeS ii ns R"
and "ns \<in> init (np ii)" ..
moreover from this(1) and \<open>netmap s i = Some v\<close> have "i = ii"
by simp (metis domI domIff)
ultimately show "v \<in> init (np i)"
using \<open>netmap s i = Some v\<close> by simp
next
fix p1 p2 s
assume IH1: "\<And>s. s \<in> init (pnet np p1) \<Longrightarrow> netmap s i = Some v \<Longrightarrow> v \<in> init (np i)"
and IH2: "\<And>s. s \<in> init (pnet np p2) \<Longrightarrow> netmap s i = Some v \<Longrightarrow> v \<in> init (np i)"
and "s \<in> init (pnet np (p1 \<parallel> p2))"
and "netmap s i = Some v"
from this(3) obtain s1 s2 where "s = SubnetS s1 s2"
and "s1 \<in> init (pnet np p1)"
and "s2 \<in> init (pnet np p2)" by auto
from this(1) and \<open>netmap s i = Some v\<close>
have "netmap s1 i = Some v \<or> netmap s2 i = Some v" by auto
thus "v \<in> init (np i)"
proof
assume "netmap s1 i = Some v"
with \<open>s1 \<in> init (pnet np p1)\<close> show ?thesis by (rule IH1)
next
assume "netmap s2 i = Some v"
with \<open>s2 \<in> init (pnet np p2)\<close> show ?thesis by (rule IH2)
qed
qed
lemma reachable_connect_netmap [elim]:
assumes "s \<in> reachable (pnet np n) TT"
and "(s, connect(i, i'), s') \<in> trans (pnet np n)"
shows "netmap s' = netmap s"
using assms proof (induction n arbitrary: s s')
fix ii R\<^sub>i s s'
assume sr: "s \<in> reachable (pnet np \<langle>ii; R\<^sub>i\<rangle>) TT"
and "(s, connect(i, i'), s') \<in> trans (pnet np \<langle>ii; R\<^sub>i\<rangle>)"
from this(2) have tr: "(s, connect(i, i'), s') \<in> node_sos (trans (np ii))" ..
from sr obtain p R where "s = NodeS ii p R"
by (metis net_node_reachable_is_node)
with tr show "netmap s' = netmap s"
by (auto elim!: node_sos.cases)
next
fix p1 p2 s s'
assume IH1: "\<And>s s'. \<lbrakk> s \<in> reachable (pnet np p1) TT;
(s, connect(i, i'), s') \<in> trans (pnet np p1) \<rbrakk> \<Longrightarrow> netmap s' = netmap s"
and IH2: "\<And>s s'. \<lbrakk> s \<in> reachable (pnet np p2) TT;
(s, connect(i, i'), s') \<in> trans (pnet np p2) \<rbrakk> \<Longrightarrow> netmap s' = netmap s"
and sr: "s \<in> reachable (pnet np (p1 \<parallel> p2)) TT"
and tr: "(s, connect(i, i'), s') \<in> trans (pnet np (p1 \<parallel> p2))"
from tr have "(s, connect(i, i'), s') \<in> pnet_sos (trans (pnet np p1)) (trans (pnet np p2))"
by simp
thus "netmap s' = netmap s"
proof cases
fix s1 s1' s2 s2'
assume "s = SubnetS s1 s2"
and "s' = SubnetS s1' s2'"
and tr1: "(s1, connect(i, i'), s1') \<in> trans (pnet np p1)"
and tr2: "(s2, connect(i, i'), s2') \<in> trans (pnet np p2)"
from this(1) and sr
have "SubnetS s1 s2 \<in> reachable (pnet np (p1 \<parallel> p2)) TT" by simp
hence sr1: "s1 \<in> reachable (pnet np p1) TT"
and sr2: "s2 \<in> reachable (pnet np p2) TT"
by (auto intro: subnet_reachable)
from sr1 tr1 have "netmap s1' = netmap s1" by (rule IH1)
moreover from sr2 tr2 have "netmap s2' = netmap s2" by (rule IH2)
ultimately show "netmap s' = netmap s"
using \<open>s = SubnetS s1 s2\<close> and \<open>s' = SubnetS s1' s2'\<close> by simp
qed simp_all
qed
lemma reachable_disconnect_netmap [elim]:
assumes "s \<in> reachable (pnet np n) TT"
and "(s, disconnect(i, i'), s') \<in> trans (pnet np n)"
shows "netmap s' = netmap s"
using assms proof (induction n arbitrary: s s')
fix ii R\<^sub>i s s'
assume sr: "s \<in> reachable (pnet np \<langle>ii; R\<^sub>i\<rangle>) TT"
and "(s, disconnect(i, i'), s') \<in> trans (pnet np \<langle>ii; R\<^sub>i\<rangle>)"
from this(2) have tr: "(s, disconnect(i, i'), s') \<in> node_sos (trans (np ii))" ..
from sr obtain p R where "s = NodeS ii p R"
by (metis net_node_reachable_is_node)
with tr show "netmap s' = netmap s"
by (auto elim!: node_sos.cases)
next
fix p1 p2 s s'
assume IH1: "\<And>s s'. \<lbrakk> s \<in> reachable (pnet np p1) TT;
(s, disconnect(i, i'), s') \<in> trans (pnet np p1) \<rbrakk> \<Longrightarrow> netmap s' = netmap s"
and IH2: "\<And>s s'. \<lbrakk> s \<in> reachable (pnet np p2) TT;
(s, disconnect(i, i'), s') \<in> trans (pnet np p2) \<rbrakk> \<Longrightarrow> netmap s' = netmap s"
and sr: "s \<in> reachable (pnet np (p1 \<parallel> p2)) TT"
and tr: "(s, disconnect(i, i'), s') \<in> trans (pnet np (p1 \<parallel> p2))"
from tr have "(s, disconnect(i, i'), s') \<in> pnet_sos (trans (pnet np p1)) (trans (pnet np p2))"
by simp
thus "netmap s' = netmap s"
proof cases
fix s1 s1' s2 s2'
assume "s = SubnetS s1 s2"
and "s' = SubnetS s1' s2'"
and tr1: "(s1, disconnect(i, i'), s1') \<in> trans (pnet np p1)"
and tr2: "(s2, disconnect(i, i'), s2') \<in> trans (pnet np p2)"
from this(1) and sr
have "SubnetS s1 s2 \<in> reachable (pnet np (p1 \<parallel> p2)) TT" by simp
hence sr1: "s1 \<in> reachable (pnet np p1) TT"
and sr2: "s2 \<in> reachable (pnet np p2) TT"
by (auto intro: subnet_reachable)
from sr1 tr1 have "netmap s1' = netmap s1" by (rule IH1)
moreover from sr2 tr2 have "netmap s2' = netmap s2" by (rule IH2)
ultimately show "netmap s' = netmap s"
using \<open>s = SubnetS s1 s2\<close> and \<open>s' = SubnetS s1' s2'\<close> by simp
qed simp_all
qed
fun net_ip_action :: "(ip \<Rightarrow> ('s, 'm seq_action) automaton)
\<Rightarrow> 'm node_action \<Rightarrow> ip \<Rightarrow> net_tree \<Rightarrow> 's net_state \<Rightarrow> 's net_state \<Rightarrow> bool"
where
"net_ip_action np a i (p1 \<parallel> p2) (SubnetS s1 s2) (SubnetS s1' s2') =
((i \<in> net_ips s1 \<longrightarrow> ((s1, a, s1') \<in> trans (pnet np p1)
\<and> s2' = s2 \<and> net_ip_action np a i p1 s1 s1'))
\<and> (i \<in> net_ips s2 \<longrightarrow> ((s2, a, s2') \<in> trans (pnet np p2))
\<and> s1' = s1 \<and> net_ip_action np a i p2 s2 s2'))"
| "net_ip_action np a i p s s' = True"
lemma pnet_tau_single_node [elim]:
assumes "wf_net_tree p"
and "s \<in> reachable (pnet np p) TT"
and "(s, \<tau>, s') \<in> trans (pnet np p)"
shows "\<exists>i\<in>net_ips s. ((\<forall>j. j\<noteq>i \<longrightarrow> netmap s' j = netmap s j)
\<and> net_ip_action np \<tau> i p s s')"
using assms proof (induction p arbitrary: s s')
fix ii R\<^sub>i s s'
assume "s \<in> reachable (pnet np \<langle>ii; R\<^sub>i\<rangle>) TT"
and "(s, \<tau>, s') \<in> trans (pnet np \<langle>ii; R\<^sub>i\<rangle>)"
from this obtain p R p' R' where "s = NodeS ii p R" and "s' = NodeS ii p' R'"
by (metis (hide_lams, no_types) TT_True net_node_reachable_is_node
reachable_step)
hence "net_ips s = {ii}"
and "net_ips s' = {ii}" by simp_all
hence "\<exists>i\<in>dom (netmap s). \<forall>j. j \<noteq> i \<longrightarrow> netmap s' j = netmap s j"
by (simp add: net_ips_is_dom_netmap)
thus "\<exists>i\<in>net_ips s. (\<forall>j. j \<noteq> i \<longrightarrow> netmap s' j = netmap s j)
\<and> net_ip_action np \<tau> i (\<langle>ii; R\<^sub>i\<rangle>) s s'"
by (simp add: net_ips_is_dom_netmap)
next
fix p1 p2 s s'
assume IH1: "\<And>s s'. \<lbrakk> wf_net_tree p1;
s \<in> reachable (pnet np p1) TT;
(s, \<tau>, s') \<in> trans (pnet np p1) \<rbrakk>
\<Longrightarrow> \<exists>i\<in>net_ips s. (\<forall>j. j \<noteq> i \<longrightarrow> netmap s' j = netmap s j)
\<and> net_ip_action np \<tau> i p1 s s'"
and IH2: "\<And>s s'. \<lbrakk> wf_net_tree p2;
s \<in> reachable (pnet np p2) TT;
(s, \<tau>, s') \<in> trans (pnet np p2) \<rbrakk>
\<Longrightarrow> \<exists>i\<in>net_ips s. (\<forall>j. j \<noteq> i \<longrightarrow> netmap s' j = netmap s j)
\<and> net_ip_action np \<tau> i p2 s s'"
and sr: "s \<in> reachable (pnet np (p1 \<parallel> p2)) TT"
and "wf_net_tree (p1 \<parallel> p2)"
and tr: "(s, \<tau>, s') \<in> trans (pnet np (p1 \<parallel> p2))"
from \<open>wf_net_tree (p1 \<parallel> p2)\<close> have "net_tree_ips p1 \<inter> net_tree_ips p2 = {}"
and "wf_net_tree p1"
and "wf_net_tree p2" by auto
from tr have "(s, \<tau>, s') \<in> pnet_sos (trans (pnet np p1)) (trans (pnet np p2))" by simp
thus "\<exists>i\<in>net_ips s. (\<forall>j. j \<noteq> i \<longrightarrow> netmap s' j = netmap s j)
\<and> net_ip_action np \<tau> i (p1 \<parallel> p2) s s'"
proof cases
fix s1 s1' s2
assume subs: "s = SubnetS s1 s2"
and subs': "s' = SubnetS s1' s2"
and tr1: "(s1, \<tau>, s1') \<in> trans (pnet np p1)"
from sr have sr1: "s1 \<in> reachable (pnet np p1) TT"
and "s2 \<in> reachable (pnet np p2) TT"
by (simp_all only: subs) (erule subnet_reachable)+
with \<open>net_tree_ips p1 \<inter> net_tree_ips p2 = {}\<close> have "dom(netmap s1) \<inter> dom(netmap s2) = {}"
by (metis net_ips_is_dom_netmap pnet_net_ips_net_tree_ips)
from \<open>wf_net_tree p1\<close> sr1 tr1 obtain i where "i\<in>dom(netmap s1)"
and *: "\<forall>j. j \<noteq> i \<longrightarrow> netmap s1' j = netmap s1 j"
and "net_ip_action np \<tau> i p1 s1 s1'"
by (auto simp add: net_ips_is_dom_netmap dest!: IH1)
from this(1) and \<open>dom(netmap s1) \<inter> dom(netmap s2) = {}\<close> have "i\<notin>dom(netmap s2)"
by auto
with subs subs' tr1 \<open>net_ip_action np \<tau> i p1 s1 s1'\<close> have "net_ip_action np \<tau> i (p1 \<parallel> p2) s s'"
by (simp add: net_ips_is_dom_netmap)
moreover have "\<forall>j. j \<noteq> i \<longrightarrow> (netmap s1' ++ netmap s2) j = (netmap s1 ++ netmap s2) j"
proof (intro allI impI)
fix j
assume "j \<noteq> i"
with * have "netmap s1' j = netmap s1 j" by simp
thus "(netmap s1' ++ netmap s2) j = (netmap s1 ++ netmap s2) j"
by (metis (hide_lams, mono_tags) map_add_dom_app_simps(1) map_add_dom_app_simps(3))
qed
ultimately show ?thesis using \<open>i\<in>dom(netmap s1)\<close> subs subs'
by (auto simp add: net_ips_is_dom_netmap)
next
fix s2 s2' s1
assume subs: "s = SubnetS s1 s2"
and subs': "s' = SubnetS s1 s2'"
and tr2: "(s2, \<tau>, s2') \<in> trans (pnet np p2)"
from sr have "s1 \<in> reachable (pnet np p1) TT"
and sr2: "s2 \<in> reachable (pnet np p2) TT"
by (simp_all only: subs) (erule subnet_reachable)+
with \<open>net_tree_ips p1 \<inter> net_tree_ips p2 = {}\<close> have "dom(netmap s1) \<inter> dom(netmap s2) = {}"
by (metis net_ips_is_dom_netmap pnet_net_ips_net_tree_ips)
from \<open>wf_net_tree p2\<close> sr2 tr2 obtain i where "i\<in>dom(netmap s2)"
and *: "\<forall>j. j \<noteq> i \<longrightarrow> netmap s2' j = netmap s2 j"
and "net_ip_action np \<tau> i p2 s2 s2'"
by (auto simp add: net_ips_is_dom_netmap dest!: IH2)
from this(1) and \<open>dom(netmap s1) \<inter> dom(netmap s2) = {}\<close> have "i\<notin>dom(netmap s1)"
by auto
with subs subs' tr2 \<open>net_ip_action np \<tau> i p2 s2 s2'\<close> have "net_ip_action np \<tau> i (p1 \<parallel> p2) s s'"
by (simp add: net_ips_is_dom_netmap)
moreover have "\<forall>j. j \<noteq> i \<longrightarrow> (netmap s1 ++ netmap s2') j = (netmap s1 ++ netmap s2) j"
proof (intro allI impI)
fix j
assume "j \<noteq> i"
with * have "netmap s2' j = netmap s2 j" by simp
thus "(netmap s1 ++ netmap s2') j = (netmap s1 ++ netmap s2) j"
by (metis (hide_lams, mono_tags) domD map_add_Some_iff map_add_dom_app_simps(3))
qed
ultimately show ?thesis using \<open>i\<in>dom(netmap s2)\<close> subs subs'
by (clarsimp simp add: net_ips_is_dom_netmap)
(metis domI dom_map_add map_add_find_right)
qed simp_all
qed
lemma pnet_deliver_single_node [elim]:
assumes "wf_net_tree p"
and "s \<in> reachable (pnet np p) TT"
and "(s, i:deliver(d), s') \<in> trans (pnet np p)"
shows "(\<forall>j. j\<noteq>i \<longrightarrow> netmap s' j = netmap s j) \<and> net_ip_action np (i:deliver(d)) i p s s'"
(is "?P p s s'")
using assms proof (induction p arbitrary: s s')
fix ii R\<^sub>i s s'
assume sr: "s \<in> reachable (pnet np \<langle>ii; R\<^sub>i\<rangle>) TT"
and tr: "(s, i:deliver(d), s') \<in> trans (pnet np \<langle>ii; R\<^sub>i\<rangle>)"
from this obtain p R p' R' where "s = NodeS ii p R" and "s' = NodeS ii p' R'"
by (metis (hide_lams, no_types) TT_True net_node_reachable_is_node
reachable_step)
hence "net_ips s = {ii}"
and "net_ips s' = {ii}" by simp_all
hence "\<forall>j. j \<noteq> ii \<longrightarrow> netmap s' j = netmap s j"
by simp
moreover from sr tr have "i = ii" by (rule delivered_to_node)
ultimately show "(\<forall>j. j \<noteq> i \<longrightarrow> netmap s' j = netmap s j)
\<and> net_ip_action np (i:deliver(d)) i (\<langle>ii; R\<^sub>i\<rangle>) s s'"
by simp
next
fix p1 p2 s s'
assume IH1: "\<And>s s'. \<lbrakk> wf_net_tree p1;
s \<in> reachable (pnet np p1) TT;
(s, i:deliver(d), s') \<in> trans (pnet np p1) \<rbrakk>
\<Longrightarrow> (\<forall>j. j \<noteq> i \<longrightarrow> netmap s' j = netmap s j)
\<and> net_ip_action np (i:deliver(d)) i p1 s s'"
and IH2: "\<And>s s'. \<lbrakk> wf_net_tree p2;
s \<in> reachable (pnet np p2) TT;
(s, i:deliver(d), s') \<in> trans (pnet np p2) \<rbrakk>
\<Longrightarrow> (\<forall>j. j \<noteq> i \<longrightarrow> netmap s' j = netmap s j)
\<and> net_ip_action np (i:deliver(d)) i p2 s s'"
and sr: "s \<in> reachable (pnet np (p1 \<parallel> p2)) TT"
and "wf_net_tree (p1 \<parallel> p2)"
and tr: "(s, i:deliver(d), s') \<in> trans (pnet np (p1 \<parallel> p2))"
from \<open>wf_net_tree (p1 \<parallel> p2)\<close> have "net_tree_ips p1 \<inter> net_tree_ips p2 = {}"
and "wf_net_tree p1"
and "wf_net_tree p2" by auto
from tr have "(s, i:deliver(d), s') \<in> pnet_sos (trans (pnet np p1)) (trans (pnet np p2))" by simp
thus "(\<forall>j. j \<noteq> i \<longrightarrow> netmap s' j = netmap s j)
\<and> net_ip_action np (i:deliver(d)) i (p1 \<parallel> p2) s s'"
proof cases
fix s1 s1' s2
assume subs: "s = SubnetS s1 s2"
and subs': "s' = SubnetS s1' s2"
and tr1: "(s1, i:deliver(d), s1') \<in> trans (pnet np p1)"
from sr have sr1: "s1 \<in> reachable (pnet np p1) TT"
and "s2 \<in> reachable (pnet np p2) TT"
by (simp_all only: subs) (erule subnet_reachable)+
with \<open>net_tree_ips p1 \<inter> net_tree_ips p2 = {}\<close> have "dom(netmap s1) \<inter> dom(netmap s2) = {}"
by (metis net_ips_is_dom_netmap pnet_net_ips_net_tree_ips)
moreover from sr1 tr1 have "i \<in> net_ips s1" by (rule delivered_to_net_ips)
ultimately have "i\<notin>dom(netmap s2)" by (auto simp add: net_ips_is_dom_netmap)
from \<open>wf_net_tree p1\<close> sr1 tr1 have *: "\<forall>j. j \<noteq> i \<longrightarrow> netmap s1' j = netmap s1 j"
and "net_ip_action np (i:deliver(d)) i p1 s1 s1'"
by (auto dest!: IH1)
from subs subs' tr1 this(2) \<open>i\<notin>dom(netmap s2)\<close>
have "net_ip_action np (i:deliver(d)) i (p1 \<parallel> p2) s s'"
by (simp add: net_ips_is_dom_netmap)
moreover have "\<forall>j. j \<noteq> i \<longrightarrow> (netmap s1' ++ netmap s2) j = (netmap s1 ++ netmap s2) j"
proof (intro allI impI)
fix j
assume "j \<noteq> i"
with * have "netmap s1' j = netmap s1 j" by simp
thus "(netmap s1' ++ netmap s2) j = (netmap s1 ++ netmap s2) j"
by (metis (hide_lams, mono_tags) map_add_dom_app_simps(1) map_add_dom_app_simps(3))
qed
ultimately show ?thesis using \<open>i\<in>net_ips s1\<close> subs subs' by auto
next
fix s2 s2' s1
assume subs: "s = SubnetS s1 s2"
and subs': "s' = SubnetS s1 s2'"
and tr2: "(s2, i:deliver(d), s2') \<in> trans (pnet np p2)"
from sr have "s1 \<in> reachable (pnet np p1) TT"
and sr2: "s2 \<in> reachable (pnet np p2) TT"
by (simp_all only: subs) (erule subnet_reachable)+
with \<open>net_tree_ips p1 \<inter> net_tree_ips p2 = {}\<close> have "dom(netmap s1) \<inter> dom(netmap s2) = {}"
by (metis net_ips_is_dom_netmap pnet_net_ips_net_tree_ips)
moreover from sr2 tr2 have "i \<in> net_ips s2" by (rule delivered_to_net_ips)
ultimately have "i\<notin>dom(netmap s1)" by (auto simp add: net_ips_is_dom_netmap)
from \<open>wf_net_tree p2\<close> sr2 tr2 have *: "\<forall>j. j \<noteq> i \<longrightarrow> netmap s2' j = netmap s2 j"
and "net_ip_action np (i:deliver(d)) i p2 s2 s2'"
by (auto dest!: IH2)
from subs subs' tr2 this(2) \<open>i\<notin>dom(netmap s1)\<close>
have "net_ip_action np (i:deliver(d)) i (p1 \<parallel> p2) s s'"
by (simp add: net_ips_is_dom_netmap)
moreover have "\<forall>j. j \<noteq> i \<longrightarrow> (netmap s1 ++ netmap s2') j = (netmap s1 ++ netmap s2) j"
proof (intro allI impI)
fix j
assume "j \<noteq> i"
with * have "netmap s2' j = netmap s2 j" by simp
thus "(netmap s1 ++ netmap s2') j = (netmap s1 ++ netmap s2) j"
by (metis (hide_lams, mono_tags) domD map_add_Some_iff map_add_dom_app_simps(3))
qed
ultimately show ?thesis using \<open>i\<in>net_ips s2\<close> subs subs' by auto
qed simp_all
qed
end
|
Formal statement is: lemma connected_connected_component [iff]: "connected (connected_component_set S x)" Informal statement is: The connected component of a point $x$ in a topological space $S$ is connected.
|
[STATEMENT]
lemma ipresCons_unique:
assumes "ipresCons f fA MOD" and "ipresCons ig igA MOD"
shows
"(wls s X \<longrightarrow> f X = ig X) \<and>
(wlsAbs (us,s') A \<longrightarrow> fA A = igA A)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (wls s X \<longrightarrow> f X = ig X) \<and> (wlsAbs (us, s') A \<longrightarrow> fA A = igA A)
[PROOF STEP]
proof(induction rule: wls_rawInduct)
[PROOF STATE]
proof (state)
goal (3 subgoals):
1. \<And>xs x. f (Var xs x) = ig (Var xs x)
2. \<And>delta inp binp. \<lbrakk>wlsInp delta inp; wlsBinp delta binp; liftAll2 (\<lambda>a b. f b = ig b) (arOf delta) inp; liftAll2 (\<lambda>a b. fA b = igA b) (barOf delta) binp\<rbrakk> \<Longrightarrow> f (Op delta inp binp) = ig (Op delta inp binp)
3. \<And>s xs x X. \<lbrakk>isInBar (xs, s); wls s X; f X = ig X\<rbrakk> \<Longrightarrow> fA (Abs xs x X) = igA (Abs xs x X)
[PROOF STEP]
case (Var xs x)
[PROOF STATE]
proof (state)
this:
goal (3 subgoals):
1. \<And>xs x. f (Var xs x) = ig (Var xs x)
2. \<And>delta inp binp. \<lbrakk>wlsInp delta inp; wlsBinp delta binp; liftAll2 (\<lambda>a b. f b = ig b) (arOf delta) inp; liftAll2 (\<lambda>a b. fA b = igA b) (barOf delta) binp\<rbrakk> \<Longrightarrow> f (Op delta inp binp) = ig (Op delta inp binp)
3. \<And>s xs x X. \<lbrakk>isInBar (xs, s); wls s X; f X = ig X\<rbrakk> \<Longrightarrow> fA (Abs xs x X) = igA (Abs xs x X)
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. f (Var xs x) = ig (Var xs x)
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
ipresCons f fA MOD
ipresCons ig igA MOD
goal (1 subgoal):
1. f (Var xs x) = ig (Var xs x)
[PROOF STEP]
unfolding ipresCons_def ipresVar_def
[PROOF STATE]
proof (prove)
using this:
(\<forall>xs x. f (Var xs x) = igVar MOD xs x) \<and> ipresAbs f fA MOD \<and> ipresOp f fA MOD
(\<forall>xs x. ig (Var xs x) = igVar MOD xs x) \<and> ipresAbs ig igA MOD \<and> ipresOp ig igA MOD
goal (1 subgoal):
1. f (Var xs x) = ig (Var xs x)
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
f (Var xs x) = ig (Var xs x)
goal (2 subgoals):
1. \<And>delta inp binp. \<lbrakk>wlsInp delta inp; wlsBinp delta binp; liftAll2 (\<lambda>a b. f b = ig b) (arOf delta) inp; liftAll2 (\<lambda>a b. fA b = igA b) (barOf delta) binp\<rbrakk> \<Longrightarrow> f (Op delta inp binp) = ig (Op delta inp binp)
2. \<And>s xs x X. \<lbrakk>isInBar (xs, s); wls s X; f X = ig X\<rbrakk> \<Longrightarrow> fA (Abs xs x X) = igA (Abs xs x X)
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>delta inp binp. \<lbrakk>wlsInp delta inp; wlsBinp delta binp; liftAll2 (\<lambda>a b. f b = ig b) (arOf delta) inp; liftAll2 (\<lambda>a b. fA b = igA b) (barOf delta) binp\<rbrakk> \<Longrightarrow> f (Op delta inp binp) = ig (Op delta inp binp)
2. \<And>s xs x X. \<lbrakk>isInBar (xs, s); wls s X; f X = ig X\<rbrakk> \<Longrightarrow> fA (Abs xs x X) = igA (Abs xs x X)
[PROOF STEP]
case (Op delta inp binp)
[PROOF STATE]
proof (state)
this:
wlsInp delta inp
wlsBinp delta binp
liftAll2 (\<lambda>a b. f b = ig b) (arOf delta) inp
liftAll2 (\<lambda>a b. fA b = igA b) (barOf delta) binp
goal (2 subgoals):
1. \<And>delta inp binp. \<lbrakk>wlsInp delta inp; wlsBinp delta binp; liftAll2 (\<lambda>a b. f b = ig b) (arOf delta) inp; liftAll2 (\<lambda>a b. fA b = igA b) (barOf delta) binp\<rbrakk> \<Longrightarrow> f (Op delta inp binp) = ig (Op delta inp binp)
2. \<And>s xs x X. \<lbrakk>isInBar (xs, s); wls s X; f X = ig X\<rbrakk> \<Longrightarrow> fA (Abs xs x X) = igA (Abs xs x X)
[PROOF STEP]
hence "lift f inp = lift ig inp \<and> lift fA binp = lift igA binp"
[PROOF STATE]
proof (prove)
using this:
wlsInp delta inp
wlsBinp delta binp
liftAll2 (\<lambda>a b. f b = ig b) (arOf delta) inp
liftAll2 (\<lambda>a b. fA b = igA b) (barOf delta) binp
goal (1 subgoal):
1. lift f inp = lift ig inp \<and> lift fA binp = lift igA binp
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
wlsInp delta inp
wlsBinp delta binp
liftAll2 (\<lambda>a b. f b = ig b) (arOf delta) inp
liftAll2 (\<lambda>a b. fA b = igA b) (barOf delta) binp
ipresCons f fA MOD
ipresCons ig igA MOD
goal (1 subgoal):
1. lift f inp = lift ig inp \<and> lift fA binp = lift igA binp
[PROOF STEP]
apply(simp add: lift_def liftAll2_def sameDom_def fun_eq_iff wlsInp_iff wlsBinp_iff split: option.splits)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>wlsOpS delta \<and> (\<forall>i. (arOf delta i = None) = (inp i = None)) \<and> (\<forall>i v1 v2. arOf delta i = Some v1 \<and> inp i = Some v2 \<longrightarrow> wls v1 v2); (\<forall>i. (barOf delta i = None) = (binp i = None)) \<and> (\<forall>i a b v2. barOf delta i = Some (a, b) \<and> binp i = Some v2 \<longrightarrow> wlsAbs (a, b) v2); \<forall>i v1 v2. arOf delta i = Some v1 \<and> inp i = Some v2 \<longrightarrow> f v2 = ig v2; \<forall>i a b v2. barOf delta i = Some (a, b) \<and> binp i = Some v2 \<longrightarrow> fA v2 = igA v2; ipresCons f fA MOD; ipresCons ig igA MOD\<rbrakk> \<Longrightarrow> (\<forall>x x2. inp x = Some x2 \<longrightarrow> f x2 = ig x2) \<and> (\<forall>x x2. binp x = Some x2 \<longrightarrow> fA x2 = igA x2)
[PROOF STEP]
using not_None_eq
[PROOF STATE]
proof (prove)
using this:
(?x \<noteq> None) = (\<exists>y. ?x = Some y)
goal (1 subgoal):
1. \<lbrakk>wlsOpS delta \<and> (\<forall>i. (arOf delta i = None) = (inp i = None)) \<and> (\<forall>i v1 v2. arOf delta i = Some v1 \<and> inp i = Some v2 \<longrightarrow> wls v1 v2); (\<forall>i. (barOf delta i = None) = (binp i = None)) \<and> (\<forall>i a b v2. barOf delta i = Some (a, b) \<and> binp i = Some v2 \<longrightarrow> wlsAbs (a, b) v2); \<forall>i v1 v2. arOf delta i = Some v1 \<and> inp i = Some v2 \<longrightarrow> f v2 = ig v2; \<forall>i a b v2. barOf delta i = Some (a, b) \<and> binp i = Some v2 \<longrightarrow> fA v2 = igA v2; ipresCons f fA MOD; ipresCons ig igA MOD\<rbrakk> \<Longrightarrow> (\<forall>x x2. inp x = Some x2 \<longrightarrow> f x2 = ig x2) \<and> (\<forall>x x2. binp x = Some x2 \<longrightarrow> fA x2 = igA x2)
[PROOF STEP]
by (metis surj_pair)
[PROOF STATE]
proof (state)
this:
lift f inp = lift ig inp \<and> lift fA binp = lift igA binp
goal (2 subgoals):
1. \<And>delta inp binp. \<lbrakk>wlsInp delta inp; wlsBinp delta binp; liftAll2 (\<lambda>a b. f b = ig b) (arOf delta) inp; liftAll2 (\<lambda>a b. fA b = igA b) (barOf delta) binp\<rbrakk> \<Longrightarrow> f (Op delta inp binp) = ig (Op delta inp binp)
2. \<And>s xs x X. \<lbrakk>isInBar (xs, s); wls s X; f X = ig X\<rbrakk> \<Longrightarrow> fA (Abs xs x X) = igA (Abs xs x X)
[PROOF STEP]
thus "f (Op delta inp binp) = ig (Op delta inp binp)"
[PROOF STATE]
proof (prove)
using this:
lift f inp = lift ig inp \<and> lift fA binp = lift igA binp
goal (1 subgoal):
1. f (Op delta inp binp) = ig (Op delta inp binp)
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
lift f inp = lift ig inp \<and> lift fA binp = lift igA binp
ipresCons f fA MOD
ipresCons ig igA MOD
goal (1 subgoal):
1. f (Op delta inp binp) = ig (Op delta inp binp)
[PROOF STEP]
unfolding ipresCons_def ipresOp_def
[PROOF STATE]
proof (prove)
using this:
lift f inp = lift ig inp \<and> lift fA binp = lift igA binp
ipresVar f MOD \<and> ipresAbs f fA MOD \<and> (\<forall>delta inp binp. wlsInp delta inp \<and> wlsBinp delta binp \<longrightarrow> f (Op delta inp binp) = igOp MOD delta (lift f inp) (lift fA binp))
ipresVar ig MOD \<and> ipresAbs ig igA MOD \<and> (\<forall>delta inp binp. wlsInp delta inp \<and> wlsBinp delta binp \<longrightarrow> ig (Op delta inp binp) = igOp MOD delta (lift ig inp) (lift igA binp))
goal (1 subgoal):
1. f (Op delta inp binp) = ig (Op delta inp binp)
[PROOF STEP]
by (simp add: Op.IH)
[PROOF STATE]
proof (state)
this:
f (Op delta inp binp) = ig (Op delta inp binp)
goal (1 subgoal):
1. \<And>s xs x X. \<lbrakk>isInBar (xs, s); wls s X; f X = ig X\<rbrakk> \<Longrightarrow> fA (Abs xs x X) = igA (Abs xs x X)
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s xs x X. \<lbrakk>isInBar (xs, s); wls s X; f X = ig X\<rbrakk> \<Longrightarrow> fA (Abs xs x X) = igA (Abs xs x X)
[PROOF STEP]
case (Abs s xs x X)
[PROOF STATE]
proof (state)
this:
isInBar (xs, s)
wls s X
f X = ig X
goal (1 subgoal):
1. \<And>s xs x X. \<lbrakk>isInBar (xs, s); wls s X; f X = ig X\<rbrakk> \<Longrightarrow> fA (Abs xs x X) = igA (Abs xs x X)
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
isInBar (xs, s)
wls s X
f X = ig X
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
isInBar (xs, s)
wls s X
f X = ig X
goal (1 subgoal):
1. fA (Abs xs x X) = igA (Abs xs x X)
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
isInBar (xs, s)
wls s X
f X = ig X
ipresCons f fA MOD
ipresCons ig igA MOD
goal (1 subgoal):
1. fA (Abs xs x X) = igA (Abs xs x X)
[PROOF STEP]
unfolding ipresCons_def ipresAbs_def
[PROOF STATE]
proof (prove)
using this:
isInBar (xs, s)
wls s X
f X = ig X
ipresVar f MOD \<and> (\<forall>xs x s X. isInBar (xs, s) \<and> wls s X \<longrightarrow> fA (Abs xs x X) = igAbs MOD xs x (f X)) \<and> ipresOp f fA MOD
ipresVar ig MOD \<and> (\<forall>xs x s X. isInBar (xs, s) \<and> wls s X \<longrightarrow> igA (Abs xs x X) = igAbs MOD xs x (ig X)) \<and> ipresOp ig igA MOD
goal (1 subgoal):
1. fA (Abs xs x X) = igA (Abs xs x X)
[PROOF STEP]
apply clarify
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>isInBar (xs, s); wls s X; f X = ig X; ipresVar f MOD; ipresVar ig MOD; \<forall>xs x s X. isInBar (xs, s) \<and> wls s X \<longrightarrow> fA (Abs xs x X) = igAbs MOD xs x (f X); ipresOp f fA MOD; \<forall>xs x s X. isInBar (xs, s) \<and> wls s X \<longrightarrow> igA (Abs xs x X) = igAbs MOD xs x (ig X); ipresOp ig igA MOD\<rbrakk> \<Longrightarrow> fA (Abs xs x X) = igA (Abs xs x X)
[PROOF STEP]
by (erule allE[of _ xs], erule allE[of _ x]) fastforce
[PROOF STATE]
proof (state)
this:
fA (Abs xs x X) = igA (Abs xs x X)
goal:
No subgoals!
[PROOF STEP]
qed
|
[STATEMENT]
lemma filter_conv_filter_it[code_unfold]:
"filter P xs = filter_it P xs"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. filter P xs = filter_it P xs
[PROOF STEP]
unfolding filter_it_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. filter P xs = filter_it' [] P xs
[PROOF STEP]
using filter_conv_filter_it' append_Nil rev.simps(1)
[PROOF STATE]
proof (prove)
using this:
rev ?acc @ filter ?P ?xs = filter_it' ?acc ?P ?xs
[] @ ?ys = ?ys
rev [] = []
goal (1 subgoal):
1. filter P xs = filter_it' [] P xs
[PROOF STEP]
by metis
|
function [img_pca,img_pca_null]=connectopic_laplacian(s,ind_ins,N,Vn,Null)
% Input:
% s: similarity matrx
% ind_ins: index of subcortical voxels
% N: size of image (MNI152:91x109x91)
% K: degree, used when Disparity=1
% Vn: index of gradient to compute: Vn=2 -> Gradint I; Vn=3 -> Gradient II; Vn=4 -> Gradient III
% Null: property of null data,structural variable including the following:
% Null.NumNull: Number of randomizations if compute the null data
% Null.T: number of time points in the empirical data
% Null.FWHM: Gaussian smooth kernel used in the empirical data
% Null.voxelsize: voxel size in mm in the empirical data
% Output:
% img_pca: eigenmap (main output)
% img_pca_null: eigenmap computed from null data
%Global thresholding. Haak et al 2017
img_pca=zeros(N);
w=squareform(pdist(s)); %similarity to distance mapping
fprintf('Thresholding to minimum density needed for graph to remain connected\n');
ind_upper=find(triu(ones(length(w),length(w)),1));
[~,ind_srt]=sort(w(ind_upper));
w_thresh=zeros(length(w),length(w));
dns=linspace(0.001,1,1000);
for i=1:length(dns)
ttl=ceil(length(ind_upper)*dns(i));
w_thresh(ind_upper(ind_srt(1:ttl)))=s(ind_upper(ind_srt(1:ttl)));
[~,comp_sizes]=get_components(~~w_thresh+~~w_thresh');
if length(comp_sizes)==1
break
end
end
fprintf('Density=%0.2f%%\n',100*(length(find(~~w_thresh))/length(ind_upper)));
dns=dns(i);
w_thresh=w_thresh+w_thresh';
fprintf('Computing Laplacian\n');
L=diag(sum(w_thresh))-w_thresh;
fprintf('Finding eigenvectors\n');
[v,d]=eig(L);d=diag(d);
% Variance explained
per=1./d(2:end);
per=per/sum(per)*100;
%figure; plot(per(1:20));
if v(1,Vn)>v(end,Vn)
y=v(:,Vn);
else
y=-v(:,Vn);
end
min_val=min(y);
y=y-min_val;
img_pca(ind_ins)=y;
if nargin==5
fprintf('Null Model: Synthetic data + MST + Geometry\n');
NumNull=Null.NumNull;
T=Null.T;
FWHM=Null.FWHM;
voxelsize=Null.voxelsize;
% Reference matrix
fprintf('Generating reference matrix\n')
M=zeros(length(ind_ins),length(ind_ins));
for i=1:length(ind_ins)
for j=1:length(ind_ins)
[xx1,yy1,zz1]=ind2sub(N,ind_ins(i));
[xx2,yy2,zz2]=ind2sub(N,ind_ins(j));
dd=sqrt((xx1-xx2)^2 + (yy1-yy2)^2 + (zz1-zz2)^2);
if dd<=sqrt(2)
M(i,j)=1;
end
end
end
ind_m_upper=find(triu(M,1)); % All the available locations (neighboring only)
% Randomizations
img_pca_null=zeros([N,NumNull]);
for nn=1:NumNull
fprintf('Simulating random data %d\n',nn)
x=randn([N,T]);
x_ins=zeros(T,length(ind_ins));
frst=0;
for i=1:T
x(:,:,:,i)=imgaussfilt3(x(:,:,:,i),FWHM/voxelsize/2.355);
tmp=x(:,:,:,i);
x_ins(i,:)=tmp(ind_ins);
show_progress(i,T,frst);frst=1;
end
clear x
% Normalization
x_ins=detrend(x_ins,'constant'); x_ins=x_ins./repmat(std(x_ins),T,1);
% Correlation
c=x_ins'*x_ins; c=c/T;z=atanh(c);
[~,ind_srt_z]=sort(z(ind_upper),'descend');
ind_z_upper=ind_upper(ind_srt_z(1:ttl)); % Available locations;ttl is computed from acutual data
% MST ensures that the graph is fully connected
% Only allow MST found in the neighboring locations
ss=zeros(size(s));
ss(ind_m_upper)=rand(length(ind_m_upper),1);
ss=ss+ss';
mst=adjacency(minspantree(graph(ss)));
ind_mst_upper=find(triu(mst,1));
% Randomise top weighted edges.
ind_srt_ttl=ind_upper(ind_srt(1:ttl));
ind_rand=randperm(length(ind_srt_ttl));
ind_srt_ttl=ind_srt_ttl(ind_rand);
% Add edges to mst locations first
Nm=length(ind_mst_upper);
w_thresh_null=zeros(size(s));
w_thresh_null(ind_mst_upper)=s(ind_srt_ttl(1:Nm));
% Then, add remaining edges to remaining desired locations
ind_remain=setdiff(ind_z_upper,ind_mst_upper);
ind_rand=randperm(length(ind_remain));
ind_remain=ind_remain(ind_rand);
w_thresh_null(ind_remain(1:ttl-Nm))=s(ind_srt_ttl(Nm+1:ttl));
[~,comp_sizes]=get_components(~~w_thresh_null+~~w_thresh_null');
if length(comp_sizes)~=1
fprintf('Warning: Null model is not fully connected\n')
end
dns_null=length(find(~~w_thresh_null))/length(ind_upper);
fprintf('Density null=%0.2f%%\n',dns_null*100);
w_thresh_null=w_thresh_null + w_thresh_null';
fprintf('Computing Laplacian\n');
L=diag(sum(w_thresh_null))-w_thresh_null;
fprintf('Finding eigenvectors\n');
[v,d]=eig(L);d=diag(d);
if v(1,Vn)>v(end,Vn)
y=v(:,Vn);
else
y=-v(:,Vn);
end
min_val_null=min(y);
y=y-min_val_null;
tmp=zeros(N);
tmp(ind_ins)=y;
img_pca_null(:,:,:,nn)=tmp;
end
else
img_pca_null=[];
end
|
%===========================================================
\documentclass[10pt]{article}
\usepackage[a4paper]{geometry}
\usepackage[T1]{fontenc}
\usepackage{CJKutf8}
\usepackage{graphicx}
\usepackage{alltt}
\usepackage{caption}
\usepackage{hyperref}
\captionsetup[figure]{labelformat=empty}
\captionsetup[table]{labelformat=empty}
\pagestyle{plain}
\thispagestyle{plain}
%===========================================================
% Title
%===========================================================
\title{HBF-701 Unofficial English Manual}
\author{Peter Senna Tschudin\footnote{I do not work for Omron. I just own one
HBF-701}\\ {\small [email protected]}}
\begin{document}
\maketitle
%===========================================================
% Title
%===========================================================
\begin{center}
\vspace{15pt}
\includegraphics[width=0.8\linewidth]{images/hbf701.jpg}
\end{center}
\section{Getting started}
\label{sec:starting}
The user manual of Omron HBF-516 has useful and valid information for HBF-701
owners. Search for \textit{hbf-516b-instruction-manual.pdf} to download it. For
safety instructions, an introduction to the basic features of the HBF-701, and
operation recommendations read pages 4-13 of
\textit{hbf-516b-instruction-manual.pdf}.
Future versions of this document will include all information needed to operate
the device.
\section{Configuring the HBF-701}
\label{sec:configuring}
Most configurations are done with three keys, arrow up, arrow down and confirm
which is the key that is immediately on the right of arrow down, something like
\begin{CJK}{UTF8}{min}体組成\end{CJK}. The first time you power on the unit, it
may ask for date and time. The first question is about time zone, which is
useless outside Japan.
\begin{enumerate}
\item For timezone you can select either 1 or 2, using arrow up / down and
confirm.
\item Then enter the year, followed by month and day.
\item Finally enter time in 24 hour format and minutes.
\end{enumerate}
For showing useful results, the HBF-701 need to know your age, sex and height.
It has memory positions for four family members, and an easy way to make
measurements for a guest. The steps below are for configuring the memory
position number 1. Configuring other memory positions, and the guest position is
similar. The guest button is located immediately on the right of the button 4,
and it is something like \begin{CJK}{UTF8}{min}ゲスト\end{CJK}. For configuring
the memory position number 1:
\begin{enumerate}
\item Power on the unit without lifting the display unit. Wait for it to show
0.0 kg.
\item Lift the Display Unit out of the Display Unit Holder, and press the
button 1.
\item Enter, using arrows and confirm, your birth date in the following order:
Year, month, day.
\item Enter your sex. The male symbol is: \begin{CJK}{UTF8}{min}男\end{CJK}.
\item Enter your height in centimeters.
\item If everything went well, then the display will show 0.0 kg, and
registration is complete.
\end{enumerate}
Now that the device is configured, follow the instructions on pages 25-31 of
\textit{hbf-516b-instruction-manual.pdf} for learning how to take a full or a
weight only measurement. Future versions of this document will include all
information needed to operate the device.
\section{TODO}
\label{sec:todo}
Please help me making this document better by sending pull requests and filling
issues on Github: \url{https://github.com/petersenna/HBF-701}
\begin{itemize}
\item Make a standalone document without dependency on
\textit{hbf-516b-instruction-manual.pdf}.
\item Add pictures.
\item Include a section on understanding the measurements.
\item Include a section on how to use the HBF-701 memory function.
\end{itemize}
\section{Legal notice}
\label{sec:legal}
\begin{itemize}
\item I do not work for Omron. I just own one HBF-701.
\item I give no warranty about the information on this document. Use the
information at your own risk.
\item All trademarks and/or brands cited in this document, including but not
limited to ``Omron'' are property of their respective owners.
\item The official manual in Japanese is available at:
\url{http://www.healthcare.omron.co.jp/product/hbf/hbf-701.html}
\item This work is licensed under a Creative Commons Attribution 4.0
International License.
\end{itemize}
\end{document}
|
The inclusion of occupational debris over the bones was not unique to the site but common in chambered tombs from southern England . On the basis of an example discovered at Kit 's Coty House , Ashbee thought it apparent that the contents of the Coldrum 's chamber would have been compartmentalised by medial slabs , which served the same purpose as the side chambers of West Kennet and Wayland 's Smithy .
|
# -*- coding: utf-8 -*-
# *****************************************************************************
#
# Copyright (c) 2021
# Georgia Institute of Technology
# Tomoki Koike
# <[email protected]>
#
# *****************************************************************************
#
# DESCRIPTION:
# Rigid body dynamics model of a quadrotor.
#
# LAST EDITED:
# 10-26-2021
#
# *****************************************************************************
# Modules *********************************************************************
from dataclasses import dataclass
import constants
import numpy as np
import utils
# Class
@dataclass(order=False, frozen=False)
class RBDYNAMICS:
m: float # mass of the quadrotor
I: np.ndarray # constant inertia matrix R[3x3]
small: int
|
[STATEMENT]
lemma FOREACH_rule:
assumes FIN: "finite S"
assumes I0: "I S \<sigma>0"
assumes IP:
"\<And>x it \<sigma>. \<lbrakk> x\<in>it; it\<subseteq>S; I it \<sigma> \<rbrakk> \<Longrightarrow> f x \<sigma> \<le> SPEC (I (it-{x}))"
assumes II: "\<And>\<sigma>. \<lbrakk>I {} \<sigma>\<rbrakk> \<Longrightarrow> P \<sigma>"
shows "FOREACH S f \<sigma>0 \<le> SPEC P"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. FOREACH S f \<sigma>0 \<le> SPEC P
[PROOF STEP]
unfolding FOREACH_def FOREACHc_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. FOREACH\<^sub>C\<^bsup>\<lambda>_ _. True\<^esup> S (\<lambda>_. True) f \<sigma>0 \<le> SPEC P
[PROOF STEP]
apply (rule order_trans[OF FOREACHci_weaken], rule TrueI)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. FOREACH\<^sub>C\<^bsup>?I1\<^esup> S (\<lambda>_. True) f \<sigma>0 \<le> SPEC P
[PROOF STEP]
apply (rule FOREACHci_rule[where I=I])
[PROOF STATE]
proof (prove)
goal (5 subgoals):
1. finite S
2. I S \<sigma>0
3. \<And>x it \<sigma>. \<lbrakk>x \<in> it; it \<subseteq> S; I it \<sigma>; True\<rbrakk> \<Longrightarrow> f x \<sigma> \<le> SPEC (I (it - {x}))
4. \<And>\<sigma>. I {} \<sigma> \<Longrightarrow> P \<sigma>
5. \<And>it \<sigma>. \<lbrakk>it \<noteq> {}; it \<subseteq> S; I it \<sigma>; \<not> True\<rbrakk> \<Longrightarrow> P \<sigma>
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
finite S
I S \<sigma>0
\<lbrakk>?x \<in> ?it; ?it \<subseteq> S; I ?it ?\<sigma>\<rbrakk> \<Longrightarrow> f ?x ?\<sigma> \<le> SPEC (I (?it - {?x}))
I {} ?\<sigma> \<Longrightarrow> P ?\<sigma>
goal (5 subgoals):
1. finite S
2. I S \<sigma>0
3. \<And>x it \<sigma>. \<lbrakk>x \<in> it; it \<subseteq> S; I it \<sigma>; True\<rbrakk> \<Longrightarrow> f x \<sigma> \<le> SPEC (I (it - {x}))
4. \<And>\<sigma>. I {} \<sigma> \<Longrightarrow> P \<sigma>
5. \<And>it \<sigma>. \<lbrakk>it \<noteq> {}; it \<subseteq> S; I it \<sigma>; \<not> True\<rbrakk> \<Longrightarrow> P \<sigma>
[PROOF STEP]
by auto
|
(*by Ammer*)
theory VEBT_DeleteCorrectness imports VEBT_Delete
begin
context VEBT_internal begin
subsection \<open>Validness Preservation\<close>
theorem delete_pres_valid: "invar_vebt t n \<Longrightarrow> invar_vebt (vebt_delete t x) n"
proof(induction t n arbitrary: x rule: invar_vebt.induct)
case (1 a b)
then show ?case
proof(cases x)
case 0
then show ?thesis
by (simp add: invar_vebt.intros(1))
next
case (Suc prex)
hence "x = Suc prex" by simp
then show ?thesis
proof(cases prex)
case 0
then show ?thesis
by (simp add: Suc invar_vebt.intros(1))
next
case (Suc preprex)
then show ?thesis
by (simp add: \<open>x = Suc prex\<close> invar_vebt.intros(1))
qed
qed
next
case (2 treeList n summary m deg)
then show ?case
using invar_vebt.intros(2) by force
next
case (3 treeList n summary m deg)
then show ?case
using invar_vebt.intros(3) by auto
next
case (4 treeList n summary m deg mi ma)
hence 0: "( \<forall> t \<in> set treeList. invar_vebt t n)" and 1: " invar_vebt summary m" and 2:"length treeList = 2^m" and 3:" deg = n+m" and
4: "(\<forall> i < 2^m. (\<exists> y. both_member_options (treeList ! i) y) \<longleftrightarrow> ( both_member_options summary i))" and
5: "(mi = ma \<longrightarrow> (\<forall> t \<in> set treeList. \<nexists> y. both_member_options t y))" and 6:"mi \<le> ma \<and> ma < 2^deg" and
7: "(mi \<noteq> ma \<longrightarrow> (\<forall> i < 2^m. (high ma n = i \<longrightarrow> both_member_options (treeList ! i) (low ma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (treeList ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ma)))"
and 8: "n = m" and 9: "deg div 2 = n" using "4" add_self_div_2 by auto
hence 10: "invar_vebt (Node (Some (mi, ma)) deg treeList summary) deg"
using invar_vebt.intros(4)[of treeList n summary m deg mi ma] by blast
hence 11:"n \<ge> 1 " and 12: " deg \<ge> 2"
by (metis "1" "8" "9" One_nat_def Suc_leI deg_not_0 div_greater_zero_iff)+
then show ?case
proof(cases "(x < mi \<or> x > ma)")
case True
hence "vebt_delete (Node (Some (mi, ma)) deg treeList summary) x = (Node (Some (mi, ma)) deg treeList summary)"
using delt_out_of_range[of x mi ma deg treeList summary]
using "1" "4.hyps"(3) "9" deg_not_0 div_greater_zero_iff by blast
then show ?thesis
by (simp add: "10")
next
case False
hence inrg: "mi\<le> x \<and> x \<le> ma" by simp
then show ?thesis
proof(cases "x = mi \<and> x = ma")
case True
hence" (\<forall> t \<in> set treeList. \<nexists> y. both_member_options t y)"
using "5" by blast
moreover have "vebt_delete (Node (Some (mi, ma)) deg treeList summary) x = (Node None deg treeList summary)"
using del_single_cont[of x mi ma deg treeList summary] "1" "8" "9" True deg_not_0 div_greater_zero_iff by blast
moreover have " (\<nexists> i. both_member_options summary i)"
using "10" True mi_eq_ma_no_ch by blast
ultimately show ?thesis
using "0" "1" "2" "3" "4.hyps"(3) invar_vebt.intros(2) by force
next
case False
hence "x \<noteq> mi \<or> x \<noteq> ma" by simp
hence "mi \<noteq> ma \<and> x < 2^deg"
by (metis "6" inrg le_antisym le_less_trans)
hence "7b": "(\<forall> i < 2^m. (high ma n = i \<longrightarrow> both_member_options (treeList ! i) (low ma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (treeList ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ma))"
using "7" by fastforce
hence "both_member_options (treeList ! (high ma n)) (low ma n)"
using "1" "3" "6" "8" deg_not_0 exp_split_high_low(1) by blast
hence yhelper:"both_member_options (treeList ! (high y n)) (low y n)
\<Longrightarrow> high y n < 2^m \<Longrightarrow> mi < y \<and> y \<le> ma \<and> low y n < 2^n" for y
by (simp add: "7b" low_def)
then show ?thesis
proof(cases "x \<noteq> mi")
case True
hence xnotmi: "x \<noteq> mi" by simp
let ?h = "high x n"
let ?l = "low x n"
have hlbound:"?h < 2^m \<and> ?l < 2^n"
using "1" "3" "8" \<open>mi \<noteq> ma \<and> x < 2 ^ deg\<close> deg_not_0 exp_split_high_low(1) exp_split_high_low(2) by blast
let ?newnode = "vebt_delete (treeList ! ?h) ?l"
have "treeList ! ?h \<in> set treeList "
by (metis "2" hlbound in_set_member inthall)
hence nnvalid: "invar_vebt ?newnode n"
by (simp add: "4.IH"(1))
let ?newlist = "treeList[?h:= ?newnode]"
have hlist:"?newlist ! ?h = ?newnode"
by (simp add: "2" hlbound)
have nothlist:"i \<noteq> ?h \<Longrightarrow> i < 2^m \<Longrightarrow> ?newlist ! i = treeList ! i" for i by simp
have allvalidinlist:"\<forall> t \<in> set ?newlist. invar_vebt t n"
proof
fix t
assume "t \<in> set ?newlist"
then obtain i where "i< 2^m \<and> ?newlist ! i = t"
by (metis "2" in_set_conv_nth length_list_update)
show "invar_vebt t n"
by (metis "0" "2" \<open>i < 2 ^ m \<and> treeList[high x n := vebt_delete (treeList ! high x n) (low x n)] ! i = t\<close> hlist nnvalid nth_list_update_neq nth_mem)
qed
have newlistlength: "length ?newlist = 2^m" using 2 by auto
then show ?thesis
proof(cases "minNull ?newnode")
case True
hence ninNullc: "minNull ?newnode" by simp
let ?sn = "vebt_delete summary ?h"
let ?newma= "(if x = ma then (let maxs = vebt_maxt ?sn in
(if maxs = None
then mi
else 2^(deg div 2) * the maxs
+ the (vebt_maxt (?newlist ! the maxs))
)
)
else ma)"
let ?delsimp =" (Node (Some (mi, ?newma)) deg ?newlist ?sn)"
have dsimp:"vebt_delete (Node (Some (mi, ma)) deg treeList summary) x = ?delsimp"
using del_x_not_mi_new_node_nil[of mi x ma deg ?h ?l ?newnode treeList ?sn summary ?newlist]
hlbound 9 11 12 True 2 inrg xnotmi by simp
have newsummvalid: "invar_vebt ?sn m"
by (simp add: "4.IH"(2))
have 111: "(\<forall> i < 2^m. (\<exists> x. both_member_options (?newlist ! i) x) \<longleftrightarrow> ( both_member_options ?sn i))"
proof
fix i
show " i < 2^m \<longrightarrow> ((\<exists> x. both_member_options (?newlist ! i) x) = ( both_member_options ?sn i))"
proof
assume "i < 2^m"
show "(\<exists> x. both_member_options (?newlist ! i) x) = ( both_member_options ?sn i)"
proof(cases "i = ?h")
case True
hence 1000:"?newlist ! i = ?newnode"
using hlist by blast
hence 1001:"\<nexists> x. vebt_member (?newlist ! i) x"
by (simp add: min_Null_member ninNullc)
hence 1002: "\<nexists> x. both_member_options (?newlist ! i) x"
using "1000" nnvalid valid_member_both_member_options by auto
have 1003: "\<not> both_member_options ?sn i"
using "1" True dele_bmo_cont_corr by auto
then show ?thesis
using "1002" by blast
next
case False
hence 1000:"?newlist ! i = treeList ! i"
using \<open>i < 2 ^ m\<close> nothlist by blast
hence "both_member_options (?newlist ! i) y \<Longrightarrow> both_member_options ?sn i" for y
proof-
assume "both_member_options (?newlist ! i) y"
hence "both_member_options summary i"
using "1000" "4" \<open>i < 2 ^ m\<close> by auto
thus "both_member_options ?sn i"
using "1" False dele_bmo_cont_corr by blast
qed
moreover have "both_member_options ?sn i \<Longrightarrow> \<exists> y. both_member_options (?newlist ! i) y"
proof-
assume "both_member_options ?sn i "
hence "both_member_options summary i"
using "1" dele_bmo_cont_corr by auto
thus " \<exists> y. both_member_options (?newlist ! i) y"
using "1000" "4" \<open>i < 2 ^ m\<close> by presburger
qed
then show ?thesis
using calculation by blast
qed
qed
qed
have 112:" (mi = ?newma \<longrightarrow> (\<forall> t \<in> set ?newlist. \<nexists> x. both_member_options t x))"
proof
assume aampt:"mi = ?newma"
show "(\<forall> t \<in> set ?newlist. \<nexists> y. both_member_options t y)"
proof(cases "x = ma")
case True
let ?maxs = "vebt_maxt ?sn"
show ?thesis
proof(cases "?maxs = None")
case True
hence aa:"\<nexists> y. vebt_member ?sn y"
using maxt_corr_help_empty newsummvalid set_vebt'_def by auto
hence "\<nexists> y. both_member_options ?sn y"
using newsummvalid valid_member_both_member_options by blast
hence "t \<in> set ?newlist \<Longrightarrow> \<nexists>y. both_member_options t y" for t
proof-
assume "t \<in> set ?newlist"
then obtain i where "?newlist ! i = t \<and> i< 2^m"
by (metis in_set_conv_nth newlistlength)
thus " \<nexists>y. both_member_options t y"
using "111" \<open>\<nexists>y. both_member_options (vebt_delete summary (high x n)) y\<close> by blast
qed
then show ?thesis by blast
next
case False
then obtain maxs where "Some maxs = ?maxs"
by fastforce
hence "both_member_options summary maxs"
by (metis "1" dele_bmo_cont_corr maxbmo)
have bb:"maxs \<noteq> ?h \<and> maxs < 2^m"
by (metis "1" \<open>Some maxs = vebt_maxt ?sn\<close> dele_bmo_cont_corr maxbmo member_bound valid_member_both_member_options)
hence "invar_vebt (?newlist ! maxs) n"using 0 "2" by auto
hence "\<exists> y. both_member_options (?newlist ! maxs) y"
using "4" bb \<open>both_member_options summary maxs\<close> nothlist by presburger
then obtain maxi where "Some maxi = vebt_maxt (?newlist ! maxs)" using
\<open>invar_vebt (treeList[high x n := vebt_delete (treeList ! high x n) (low x n)] ! maxs) n\<close>
empty_Collect_eq option.sel maxt_corr_help_empty set_vebt'_def valid_member_both_member_options by fastforce
hence "maxs = high mi n \<and> both_member_options (?newlist ! maxs) (low mi n)"
by (smt (z3) "9" True \<open>Some maxs = vebt_maxt (vebt_delete summary (high x n))\<close> \<open>invar_vebt (treeList[high x n := vebt_delete (treeList ! high x n) (low x n)] ! maxs) n\<close> aampt option.sel high_inv low_inv maxbmo member_bound mult.commute option.distinct(1) valid_member_both_member_options)
hence False
by (metis bb nat_less_le nothlist yhelper)
then show ?thesis by simp
qed
next
case False
then show ?thesis
using \<open>mi \<noteq> ma \<and> x < 2 ^ deg\<close> aampt by presburger
qed
qed
have 114: "?newma < 2^deg \<and> mi \<le> ?newma"
proof(cases "x = ma")
case True
hence "x = ma" by simp
let ?maxs = "vebt_maxt ?sn"
show ?thesis
proof(cases "?maxs = None")
case True
then show ?thesis
using "6" by fastforce
next
case False
then obtain maxs where "Some maxs = ?maxs"
by fastforce
hence "both_member_options summary maxs"
by (metis "1" dele_bmo_cont_corr maxbmo)
have bb:"maxs \<noteq> ?h \<and> maxs < 2^m"
by (metis "1" \<open>Some maxs = vebt_maxt ?sn\<close> dele_bmo_cont_corr maxbmo member_bound valid_member_both_member_options)
hence "invar_vebt (?newlist ! maxs) n"using 0 "2" by auto
hence "\<exists> y. both_member_options (?newlist ! maxs) y"
using "4" bb \<open>both_member_options summary maxs\<close> nothlist by presburger
then obtain maxi where "Some maxi = vebt_maxt (?newlist ! maxs)"
by (metis \<open>invar_vebt (treeList[high x n := vebt_delete (treeList ! high x n) (low x n)] ! maxs) n\<close> empty_Collect_eq maxt_corr_help_empty option_shift.elims set_vebt'_def valid_member_both_member_options)
then show ?thesis
by (smt (verit, best) "6" "9" \<open>Some maxs = vebt_maxt (vebt_delete summary (high x n))\<close> \<open>invar_vebt (?newlist ! maxs) n\<close> bb option.sel high_inv less_le_trans low_inv maxbmo maxt_member member_bound mult.commute not_less_iff_gr_or_eq nothlist verit_comp_simplify1(3) yhelper)
qed
next
case False
then show ?thesis
using "6" by auto
qed
have 115: "mi \<noteq> ?newma \<longrightarrow>
(\<forall> i < 2^m.
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma))"
proof
assume "mi \<noteq> ?newma"
show " (\<forall> i < 2^m.
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma))"
proof
fix i
show "i < 2^m \<longrightarrow>
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma)"
proof
assume assumption:"i < 2^m"
show " (high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma)"
proof-
have "(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n))"
proof
assume newmaassm: "high ?newma n = i"
thus " both_member_options (?newlist ! i) (low ?newma n)"
proof(cases "x = ma" )
case True
let ?maxs = "vebt_maxt ?sn"
show ?thesis
proof(cases "?maxs = None")
case True
then show ?thesis
by (smt (z3) "0" \<open>both_member_options (treeList ! high ma n) (low ma n)\<close> \<open>mi \<noteq> (if x = ma then let maxs = vebt_maxt (vebt_delete summary (high x n)) in if maxs = None then mi else 2 ^ (deg div 2) * the maxs + the (vebt_maxt (treeList [high x n := vebt_delete (treeList ! high x n) (low x n)] ! the maxs)) else ma)\<close> \<open>treeList ! high x n \<in> set treeList\<close> bit_split_inv dele_bmo_cont_corr hlist newmaassm nth_list_update_neq)
next
case False
then obtain maxs where "Some maxs = ?maxs"
by fastforce
hence "both_member_options summary maxs"
by (metis "1" dele_bmo_cont_corr maxbmo)
have bb:"maxs \<noteq> ?h \<and> maxs < 2^m"
by (metis "1" \<open>Some maxs = vebt_maxt ?sn\<close> dele_bmo_cont_corr maxbmo member_bound valid_member_both_member_options)
hence "invar_vebt (?newlist ! maxs) n"using 0 2 by auto
hence "\<exists> y. both_member_options (?newlist ! maxs) y"
using "4" bb \<open>both_member_options summary maxs\<close> nothlist by presburger
then obtain maxi where "Some maxi = vebt_maxt (?newlist ! maxs)" using
\<open>invar_vebt (treeList[high x n := vebt_delete (treeList ! high x n) (low x n)] ! maxs) n\<close>
empty_Collect_eq maxt_corr_help_empty set_vebt'_def valid_member_both_member_options
by (smt (z3) VEBT_Member.vebt_member.simps(2) \<open>invar_vebt (treeList[high x n := vebt_delete (treeList ! high x n) (low x n)] ! maxs) n\<close> vebt_maxt.elims minNull.simps(1) min_Null_member valid_member_both_member_options)
then show ?thesis
by (smt (z3) "9" False True \<open>Some maxs = vebt_maxt (vebt_delete summary (high x n))\<close> \<open>invar_vebt (treeList[high x n := vebt_delete (treeList ! high x n) (low x n)] ! maxs) n\<close> option.sel high_inv low_inv maxbmo maxt_member member_bound mult.commute newmaassm)
qed
next
case False
then show ?thesis
by (smt (z3) "0" \<open>both_member_options (treeList ! high ma n) (low ma n)\<close> \<open>treeList ! high x n \<in> set treeList\<close> assumption bit_split_inv dele_bmo_cont_corr hlist newmaassm nothlist)
qed
qed
moreover have " (\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma)"
proof
fix y
show "(high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma"
proof
assume yassm: "(high y n = i \<and> both_member_options (?newlist ! i) (low y n) )"
hence "mi < y"
proof(cases "i = ?h")
case True
hence "both_member_options (treeList ! i) (low y n)"
using "0" \<open>treeList ! high x n \<in> set treeList\<close> dele_bmo_cont_corr hlist yassm by auto
then show ?thesis
by (simp add: assumption yassm yhelper)
next
case False
then show ?thesis
using assumption nothlist yassm yhelper by presburger
qed
moreover have "y \<le> ?newma"
proof(cases "x = ma")
case True
hence "x= ma" by simp
let ?maxs = "vebt_maxt ?sn"
show ?thesis
proof(cases "?maxs = None")
case True
then show ?thesis
using \<open>mi \<noteq> ?newma\<close> \<open>x = ma\<close> by presburger
next
case False
then obtain maxs where "Some maxs = ?maxs"
by fastforce
hence "both_member_options summary maxs"
by (metis "1" dele_bmo_cont_corr maxbmo)
have bb:"maxs \<noteq> ?h \<and> maxs < 2^m"
by (metis "1" \<open>Some maxs = vebt_maxt ?sn\<close> dele_bmo_cont_corr maxbmo member_bound valid_member_both_member_options)
hence "invar_vebt (?newlist ! maxs) n"using 0 2 by auto
hence "\<exists> y. both_member_options (?newlist ! maxs) y"
using "4" bb \<open>both_member_options summary maxs\<close> nothlist by presburger
then obtain maxi where "Some maxi = vebt_maxt (?newlist ! maxs)"
by (metis "2" "4.IH"(1) Collect_empty_eq bb both_member_options_equiv_member maxt_corr_help_empty nth_list_update_neq nth_mem option.exhaust set_vebt'_def)
hence "maxs < 2^m \<and> maxi < 2^n"
by (metis \<open>invar_vebt (?newlist ! maxs) n\<close> bb maxt_member member_bound)
hence "?newma = 2^n* maxs + maxi"
by (smt (z3) "9" False True \<open>Some maxi = vebt_maxt (?newlist ! maxs)\<close> \<open>Some maxs = vebt_maxt (vebt_delete summary (high x n))\<close> option.sel)
hence "low ?newma n = maxi \<and> high ?newma n = maxs"
by (simp add: \<open>maxs < 2 ^ m \<and> maxi < 2 ^ n\<close> high_inv low_inv mult.commute)
hence "both_member_options (treeList ! (high y n)) (low y n)"
by (metis "0" \<open>treeList ! high x n \<in> set treeList\<close> assumption dele_bmo_cont_corr hlist nothlist yassm)
hence hleqdraft:"high y n > maxs \<Longrightarrow> False"
proof-
assume "high y n > maxs"
have "both_member_options summary (high y n)"
using "1" "111" assumption dele_bmo_cont_corr yassm by blast
moreover have "both_member_options ?sn (high y n)"
using "111" assumption yassm by blast
ultimately show False
by (metis \<open>Some maxs = vebt_maxt (vebt_delete summary (high x n))\<close> \<open>maxs < high y n\<close> leD maxt_corr_help newsummvalid valid_member_both_member_options)
qed
hence hleqmaxs: "high y n \<le> maxs" by presburger
then show ?thesis
proof(cases "high y n = maxs")
case True
hence "low y n \<le> maxi"
by (metis \<open>Some maxi = vebt_maxt (treeList[high x n := vebt_delete (treeList ! high x n) (low x n)] ! maxs)\<close> \<open>invar_vebt (treeList[high x n := vebt_delete (treeList ! high x n) (low x n)] ! maxs) n\<close> maxt_corr_help valid_member_both_member_options yassm)
then show ?thesis
by (smt (z3) True \<open>(if x = ma then let maxs = vebt_maxt (vebt_delete summary (high x n)) in if maxs = None then mi else 2 ^ (deg div 2) * the maxs + the (vebt_maxt ((?newlist) ! the maxs)) else ma) = 2 ^ n * maxs + maxi\<close> add_le_cancel_left bit_concat_def bit_split_inv mult.commute)
next
case False
then show ?thesis
by (metis \<open>low (if x = ma then let maxs = vebt_maxt (vebt_delete summary (high x n)) in if maxs = None then mi else 2 ^ (deg div 2) * the maxs + the (vebt_maxt ((?newlist) ! the maxs)) else ma) n = maxi \<and> high (if x = ma then let maxs = vebt_maxt (vebt_delete summary (high x n)) in if maxs = None then mi else 2 ^ (deg div 2) * the maxs + the (vebt_maxt ((?newlist) ! the maxs)) else ma) n = maxs\<close> div_le_mono high_def hleqdraft le_neq_implies_less nat_le_linear)
qed
qed
next
case False
then show ?thesis
by (smt (z3) "0" \<open>treeList ! high x n \<in> set treeList\<close> assumption dele_bmo_cont_corr hlist nothlist yassm yhelper)
qed
ultimately show " mi < y \<and> y \<le> ?newma" by simp
qed
qed
ultimately show ?thesis by simp
qed
qed
qed
qed
hence 117: "?newma < 2^deg" and 118: "mi \<le> ?newma" using 114 by auto
have 116: " invar_vebt (Node (Some (mi, ?newma)) deg ?newlist ?sn) deg"
using invar_vebt.intros(4)[of ?newlist n ?sn m deg mi ?newma]
using 3 allvalidinlist newlistlength newsummvalid "4.hyps"(3) 111 112 118 117 115 by fastforce
show ?thesis
using "116" dsimp by presburger
next
case False
hence notemp:"\<exists> z. both_member_options ?newnode z"
using not_min_Null_member by auto
let ?newma = "(if x = ma then
?h * 2^(deg div 2) + the( vebt_maxt (?newlist ! ?h))
else ma)"
let ?delsimp =" (Node (Some (mi, ?newma)) deg ?newlist summary)"
have dsimp:"vebt_delete (Node (Some (mi, ma)) deg treeList summary) x = ?delsimp"
using del_x_not_mi_newnode_not_nil[of mi x ma deg ?h ?l ?newnode treeList ?newlist summary]
by (metis "12" "2" "9" False dual_order.eq_iff hlbound inrg order.not_eq_order_implies_strict xnotmi)
have 111: "(\<forall> i < 2^m. (\<exists> x. both_member_options (?newlist ! i) x) \<longleftrightarrow> ( both_member_options summary i))"
proof
fix i
show " i < 2^m \<longrightarrow> ((\<exists> x. both_member_options (?newlist ! i) x) = ( both_member_options summary i))"
proof
assume "i < 2^m"
show "(\<exists> x. both_member_options (?newlist ! i) x) = ( both_member_options summary i)"
proof(cases "i = ?h")
case True
hence 1000:"?newlist ! i = ?newnode"
using hlist by blast
hence 1001:"\<exists> x. vebt_member (?newlist ! i) x"
using nnvalid notemp valid_member_both_member_options by auto
hence 1002: "\<exists> x. both_member_options (?newlist ! i) x"
using "1000" notemp by presburger
have 1003: "both_member_options summary i"
using "0" "1000" "1002" "4" True \<open>i < 2 ^ m\<close> \<open>treeList ! high x n \<in> set treeList\<close> dele_bmo_cont_corr by fastforce
then show ?thesis
using "1002" by blast
next
case False
hence 1000:"?newlist ! i = treeList ! i"
using \<open>i < 2 ^ m\<close> nothlist by blast
then show ?thesis
using "4" \<open>i < 2 ^ m\<close> by presburger
qed
qed
qed
have 112:" (mi = ?newma \<longrightarrow> (\<forall> t \<in> set ?newlist. \<nexists> x. both_member_options t x))"
proof
assume aampt:"mi = ?newma"
show "(\<forall> t \<in> set ?newlist. \<nexists> y. both_member_options t y)"
proof(cases "x = ma")
case True
obtain maxi where " vebt_maxt (?newlist ! ?h) = Some maxi"
by (metis False VEBT_Member.vebt_member.simps(2) hlist vebt_maxt.elims minNull.simps(1) nnvalid notemp valid_member_both_member_options)
hence "both_member_options ?newnode maxi"
using hlist maxbmo by auto
hence "both_member_options (treeList ! ?h) maxi"
using "0" \<open>treeList ! high x n \<in> set treeList\<close> dele_bmo_cont_corr by blast
hence False
by (metis "9" True \<open>both_member_options ?newnode maxi\<close> \<open>vebt_maxt (?newlist ! high x n) = Some maxi\<close> aampt option.sel high_inv hlbound low_inv member_bound nnvalid not_less_iff_gr_or_eq valid_member_both_member_options yhelper)
then show ?thesis by blast
next
case False
then show ?thesis
using \<open>mi \<noteq> ma \<and> x < 2 ^ deg\<close> aampt by presburger
qed
qed
have 114: "?newma < 2^deg \<and> mi \<le> ?newma"
proof(cases "x = ma")
case True
hence "x = ma" by simp
obtain maxi where " vebt_maxt (?newlist ! ?h) = Some maxi"
by (metis empty_Collect_eq hlist maxt_corr_help_empty nnvalid notemp option.exhaust set_vebt'_def valid_member_both_member_options)
hence "both_member_options ?newnode maxi"
using hlist maxbmo by auto
hence "both_member_options (treeList ! ?h) maxi"
using "0" \<open>treeList ! high x n \<in> set treeList\<close> dele_bmo_cont_corr by blast
hence "maxi < 2^n"
using \<open>both_member_options?newnode maxi\<close> member_bound nnvalid valid_member_both_member_options by blast
show ?thesis
by (smt (z3) "3" "9" div_eq_0_iff True \<open>both_member_options (treeList ! high x n) maxi\<close> \<open>maxi < 2 ^ n\<close> \<open>vebt_maxt (?newlist ! high x n) = Some maxi\<close> add.right_neutral div_exp_eq div_mult_self3 option.sel high_inv hlbound le_0_eq less_imp_le_nat low_inv power_not_zero rel_simps(28) yhelper)
next
case False
then show ?thesis
using "6" by auto
qed
have 115: "mi \<noteq> ?newma \<longrightarrow>
(\<forall> i < 2^m.
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma))"
proof
assume "mi \<noteq> ?newma"
show " (\<forall> i < 2^m.
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma))"
proof
fix i
show "i < 2^m \<longrightarrow>
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma)"
proof
assume assumption:"i < 2^m"
show " (high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma)"
proof-
have "(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n))"
proof
assume newmaassm: "high ?newma n = i"
thus " both_member_options (?newlist ! i) (low ?newma n)"
proof(cases "x = ma")
case True
obtain maxi where "vebt_maxt (?newlist ! ?h) = Some maxi"
by (metis Collect_empty_eq both_member_options_equiv_member hlist maxt_corr_help_empty nnvalid not_Some_eq notemp set_vebt'_def)
hence "both_member_options (?newlist ! ?h) maxi"
using maxbmo by blast
then show ?thesis
by (smt (z3) "9" True \<open>vebt_maxt (?newlist ! high x n) = Some maxi\<close> option.sel high_inv hlist low_inv maxt_member member_bound newmaassm nnvalid)
next
case False
then show ?thesis
by (smt (z3) "0" \<open>both_member_options (treeList ! high ma n) (low ma n)\<close> \<open>treeList ! high x n \<in> set treeList\<close> assumption bit_split_inv dele_bmo_cont_corr hlist newmaassm nothlist)
qed
qed
moreover have " (\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma)"
proof
fix y
show "(high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma"
proof
assume yassm: "(high y n = i \<and> both_member_options (?newlist ! i) (low y n) )"
hence "mi < y"
proof(cases "i = ?h")
case True
hence "both_member_options (treeList ! i) (low y n)"
using "0" \<open>treeList ! high x n \<in> set treeList\<close> dele_bmo_cont_corr hlist yassm by auto
then show ?thesis
by (simp add: assumption yassm yhelper)
next
case False
then show ?thesis
using assumption nothlist yassm yhelper by presburger
qed
moreover have "y \<le> ?newma"
proof(cases "x = ma")
case True
hence "x= ma" by simp
obtain maxi where "vebt_maxt (?newlist ! ?h) = Some maxi"
by (metis Collect_empty_eq both_member_options_equiv_member hlist maxt_corr_help_empty nnvalid not_Some_eq notemp set_vebt'_def)
hence "both_member_options (?newlist ! ?h) maxi"
using maxbmo by blast
have "high y n \<le> ?h"
by (metis "7b" True assumption div_le_mono high_def nothlist yassm)
then show ?thesis
proof(cases "high y n = ?h")
case True
have "low y n > maxi \<Longrightarrow> False"
by (metis True \<open>vebt_maxt (?newlist ! ?h) = Some maxi\<close> hlist leD maxt_corr_help nnvalid valid_member_both_member_options yassm)
then show ?thesis
by (smt (z3) "9" True \<open>vebt_maxt (?newlist ! ?h) = Some maxi\<close> \<open>x = ma\<close> add_le_cancel_left div_mult_mod_eq option.sel high_def low_def nat_le_linear nat_less_le)
next
case False
then show ?thesis
by (smt (z3) "9" True \<open>both_member_options (?newlist ! high x n) maxi\<close> \<open>high y n \<le> high x n\<close> \<open>vebt_maxt (?newlist ! high x n) = Some maxi\<close> div_le_mono option.sel high_def high_inv hlist le_antisym member_bound nat_le_linear nnvalid valid_member_both_member_options)
qed
next
case False
then show ?thesis
by (smt (z3) "0" \<open>treeList ! high x n \<in> set treeList\<close> assumption dele_bmo_cont_corr hlist nothlist yassm yhelper)
qed
ultimately show " mi < y \<and> y \<le> ?newma" by simp
qed
qed
ultimately show ?thesis by simp
qed
qed
qed
qed
hence 117: "?newma < 2^deg" and 118: "mi \<le> ?newma" using 114 by auto
have 116: " invar_vebt (Node (Some (mi, ?newma)) deg ?newlist summary) deg"
using invar_vebt.intros(4)[of ?newlist n summary m deg mi ?newma] allvalidinlist
1 newlistlength 8 3 111 112 117 118 115 by fastforce
then show ?thesis
using dsimp by presburger
qed
next
case False
hence xmi:"x = mi" by simp
have "both_member_options summary (high ma n)"
using "1" "3" "4" "4.hyps"(3) "6" \<open>both_member_options (treeList ! high ma n) (low ma n)\<close> deg_not_0 exp_split_high_low(1) by blast
hence "vebt_member summary (high ma n)"
using "4.hyps"(1) valid_member_both_member_options by blast
obtain summin where "Some summin = vebt_mint summary"
by (metis "4.hyps"(1) \<open>vebt_member summary (high ma n)\<close> empty_Collect_eq mint_corr_help_empty not_None_eq set_vebt'_def)
hence "\<exists> z . both_member_options (treeList ! summin) z"
by (metis "4.hyps"(1) "4.hyps"(5) both_member_options_equiv_member member_bound mint_member)
moreover have "invar_vebt (treeList ! summin) n"
by (metis "0" "1" "2" \<open>Some summin = vebt_mint summary\<close> member_bound mint_member nth_mem)
ultimately obtain lx where "Some lx = vebt_mint (treeList ! summin)"
by (metis empty_Collect_eq mint_corr_help_empty not_None_eq set_vebt'_def valid_member_both_member_options)
let ?xn = "summin*2^n + lx"
have "?xn = (if x = mi
then the (vebt_mint summary) * 2^(deg div 2)
+ the (vebt_mint (treeList ! the (vebt_mint summary)))
else x)"
by (metis False \<open>Some lx = vebt_mint (treeList ! summin)\<close> \<open>Some summin = vebt_mint summary\<close> \<open>deg div 2 = n\<close> option.sel)
have "vebt_member (treeList ! summin) lx"
using \<open>Some lx = vebt_mint (treeList ! summin)\<close> \<open>invar_vebt (treeList ! summin) n\<close> mint_member by auto
moreover have "summin < 2^m"
by (metis "4.hyps"(1) \<open>Some summin = vebt_mint summary\<close> member_bound mint_member)
ultimately have xnin: "both_member_options (Node (Some (mi, ma)) deg treeList summary) ?xn"
by (metis "12" "2" "9" \<open>invar_vebt (treeList ! summin) n\<close> add_leD1 both_member_options_equiv_member both_member_options_from_chilf_to_complete_tree high_inv low_inv member_bound numeral_2_eq_2 plus_1_eq_Suc)
let ?h ="high ?xn n"
let ?l = "low ?xn n"
have "?xn < 2^deg"
by (smt (verit, ccfv_SIG) "4.hyps"(1) "4.hyps"(4) div_eq_0_iff \<open>Some lx = vebt_mint (treeList ! summin)\<close> \<open>Some summin = vebt_mint summary\<close> \<open>invar_vebt (treeList ! summin) n\<close> div_exp_eq high_def high_inv le_0_eq member_bound mint_member not_numeral_le_zero power_not_zero)
hence "?h < length treeList"
using "4.hyps"(2) "4.hyps"(3) "4.hyps"(4) \<open>invar_vebt (treeList ! summin) n\<close> deg_not_0 exp_split_high_low(1) by metis
let ?newnode = "vebt_delete (treeList ! ?h) ?l"
let ?newlist = "treeList[?h:= ?newnode]"
have "length treeList = length ?newlist" by simp
hence hprolist: "?newlist ! ?h = ?newnode"
by (meson \<open>high (summin * 2 ^ n + lx) n < length treeList\<close> nth_list_update_eq)
have nothprolist: "i \<noteq> ?h \<and> i < 2^m \<Longrightarrow> ?newlist ! i = treeList ! i" for i by simp
have hlbound:"?h < 2^m \<and> ?l < 2^n"
using "1" "2" "3" "8" \<open>high (summin * 2 ^ n + lx) n < length treeList\<close> \<open>summin * 2 ^ n + lx < 2 ^ deg\<close> deg_not_0 exp_split_high_low(2) by presburger
hence nnvalid: "invar_vebt ?newnode n"
by (metis "4.IH"(1) \<open>high (summin * 2 ^ n + lx) n < length treeList\<close> inthall member_def)
have allvalidinlist:"\<forall> t \<in> set ?newlist. invar_vebt t n"
proof
fix t
assume "t \<in> set ?newlist"
then obtain i where "i < 2^m \<and> ?newlist ! i = t"
by (metis "2" \<open>length treeList = length (treeList [high (summin * 2 ^ n + lx) n := vebt_delete (treeList ! high (summin * 2 ^ n + lx) n) (low (summin * 2 ^ n + lx) n)])\<close> in_set_conv_nth)
then show "invar_vebt t n"
by (metis "0" "2" hprolist nnvalid nth_list_update_neq nth_mem)
qed
have newlistlength: "length ?newlist = 2^m"
by (simp add: "2")
then show ?thesis
proof(cases "minNull ?newnode")
case True
hence ninNullc: "minNull ?newnode" by simp
let ?sn = "vebt_delete summary ?h"
let ?newma= "(if ?xn = ma then (let maxs = vebt_maxt ?sn in
(if maxs = None
then ?xn
else 2^(deg div 2) * the maxs
+ the (vebt_maxt (?newlist ! the maxs))
)
)
else ma)"
let ?delsimp =" (Node (Some (?xn, ?newma)) deg ?newlist ?sn)"
have dsimp:"vebt_delete (Node (Some (mi, ma)) deg treeList summary) x = ?delsimp"
using del_x_mi_lets_in_minNull[of x mi ma deg ?xn ?h summary treeList ?l ?newnode ?newlist ?sn]
by (metis "12" "9" \<open>high (summin * 2 ^ n + lx) n < length treeList\<close> \<open>summin * 2 ^ n + lx = (if x = mi then the (vebt_mint summary) * 2 ^ (deg div 2) + the (vebt_mint (treeList ! the (vebt_mint summary))) else x)\<close> \<open>x = mi\<close> \<open>x \<noteq> mi \<or> x \<noteq> ma\<close> inrg nat_less_le ninNullc)
have newsummvalid: "invar_vebt ?sn m"
by (simp add: "4.IH"(2))
have 111: "(\<forall> i < 2^m. (\<exists> x. both_member_options (?newlist ! i) x) \<longleftrightarrow> ( both_member_options ?sn i))"
proof
fix i
show " i < 2^m \<longrightarrow> ((\<exists> x. both_member_options (?newlist ! i) x) = ( both_member_options ?sn i))"
proof
assume "i < 2^m"
show "(\<exists> x. both_member_options (?newlist ! i) x) = ( both_member_options ?sn i)"
proof(cases "i = ?h")
case True
hence 1000:"?newlist ! i = ?newnode"
using hprolist by fastforce
hence 1001:"\<nexists> x. vebt_member (?newlist ! i) x"
by (simp add: min_Null_member ninNullc)
hence 1002: "\<nexists> x. both_member_options (?newlist ! i) x"
using "1000" nnvalid valid_member_both_member_options by auto
have 1003: "\<not> both_member_options ?sn i"
using "1" True dele_bmo_cont_corr by auto
then show ?thesis
using "1002" by blast
next
case False
hence 1000:"?newlist ! i = treeList ! i"
using \<open>i < 2 ^ m\<close> nothprolist by blast
hence "both_member_options (?newlist ! i) y \<Longrightarrow> both_member_options ?sn i" for y
proof-
assume "both_member_options (?newlist ! i) y"
hence "both_member_options summary i"
using "1000" "4" \<open>i < 2 ^ m\<close> by auto
thus "both_member_options ?sn i"
using "1" False dele_bmo_cont_corr by blast
qed
moreover have "both_member_options ?sn i \<Longrightarrow> \<exists> y. both_member_options (?newlist ! i) y"
proof-
assume "both_member_options ?sn i "
hence "both_member_options summary i"
using "1" dele_bmo_cont_corr by auto
thus " \<exists> y. both_member_options (?newlist ! i) y"
using "1000" "4" \<open>i < 2 ^ m\<close> by presburger
qed
then show ?thesis
using calculation by blast
qed
qed
qed
have 112:" (?xn = ?newma \<longrightarrow> (\<forall> t \<in> set ?newlist. \<nexists> x. both_member_options t x))"
proof
assume aampt:"?xn = ?newma"
show "(\<forall> t \<in> set ?newlist. \<nexists> y. both_member_options t y)"
proof(cases "?xn = ma")
case True
let ?maxs = "vebt_maxt ?sn"
show ?thesis
proof(cases "?maxs = None")
case True
hence aa:"\<nexists> y. vebt_member ?sn y"
using maxt_corr_help_empty newsummvalid set_vebt'_def by auto
hence "\<nexists> y. both_member_options ?sn y"
using newsummvalid valid_member_both_member_options by blast
hence "t \<in> set ?newlist \<Longrightarrow> \<nexists>y. both_member_options t y" for t
proof-
assume "t \<in> set ?newlist"
then obtain i where "?newlist ! i = t \<and> i< 2^m"
by (metis "2" \<open>length treeList = length (treeList [high (summin * 2 ^ n + lx) n := vebt_delete (treeList ! high (summin * 2 ^ n + lx) n) (low (summin * 2 ^ n + lx) n)])\<close> in_set_conv_nth)
thus " \<nexists>y. both_member_options t y"
using "111" \<open>\<nexists>y. both_member_options (vebt_delete summary (high (summin * 2 ^ n + lx) n)) y\<close> by blast
qed
then show ?thesis by blast
next
case False
then obtain maxs where "Some maxs = ?maxs"
by fastforce
hence "both_member_options summary maxs"
by (metis "1" dele_bmo_cont_corr maxbmo)
have bb:"maxs \<noteq> ?h \<and> maxs < 2^m"
by (metis "1" \<open>Some maxs = vebt_maxt ?sn\<close> dele_bmo_cont_corr maxbmo member_bound valid_member_both_member_options)
hence "invar_vebt (?newlist ! maxs) n"using 0
by (simp add: "2" allvalidinlist)
hence "\<exists> y. both_member_options (?newlist ! maxs) y"
using "4" bb \<open>both_member_options summary maxs\<close> nothprolist by presburger
then obtain maxi where "Some maxi = vebt_maxt (?newlist ! maxs)"
using \<open>invar_vebt (treeList [high (summin * 2 ^ n + lx) n := vebt_delete (treeList ! high (summin * 2 ^ n + lx) n) (low (summin * 2 ^ n + lx) n)] ! maxs) n\<close> maxt_corr_help_empty set_vebt'_def valid_member_both_member_options by fastforce
hence "maxs = high ?xn n \<and> both_member_options (?newlist ! maxs) (low ?xn n)"
by (smt (z3) "9" False True \<open>Some maxs = vebt_maxt (vebt_delete summary ?h)\<close> \<open>invar_vebt (?newlist ! maxs) n\<close> aampt option.sel high_inv low_inv maxbmo maxt_member member_bound mult.commute)
hence False
using bb by blast
then show ?thesis by simp
qed
next
case False
hence "?xn \<noteq> ?newma" by simp
hence False using aampt by simp
then show ?thesis by blast
qed
qed
have 114: "?newma < 2^deg \<and> ?xn \<le> ?newma"
proof(cases "?xn = ma")
case True
hence "?xn = ma" by simp
let ?maxs = "vebt_maxt ?sn"
show ?thesis
proof(cases "?maxs = None")
case True
then show ?thesis
using "4.hyps"(8) \<open>?xn = ma\<close> by force
next
case False
then obtain maxs where "Some maxs = ?maxs"
by fastforce
hence "both_member_options summary maxs"
by (metis "1" dele_bmo_cont_corr maxbmo)
have bb:"maxs \<noteq> ?h \<and> maxs < 2^m"
by (metis "1" \<open>Some maxs = vebt_maxt ?sn\<close> dele_bmo_cont_corr maxbmo member_bound valid_member_both_member_options)
hence "invar_vebt (?newlist ! maxs) n"using 0 by (simp add: "2" allvalidinlist)
hence "\<exists> y. both_member_options (?newlist ! maxs) y"
using "4" \<open>both_member_options summary maxs\<close> bb nothprolist by presburger
then obtain maxi where "Some maxi = vebt_maxt (?newlist ! maxs)"
using \<open>invar_vebt (treeList [high (summin * 2 ^ n + lx) n := vebt_delete (treeList ! high (summin * 2 ^ n + lx) n) (low (summin * 2 ^ n + lx) n)] ! maxs) n\<close> empty_Collect_eq maxt_corr_help_empty not_Some_eq set_vebt'_def valid_member_both_member_options by fastforce
hence abc:"?newma = 2^n * maxs + maxi"
by (smt (z3) "9" True \<open>Some maxs = vebt_maxt (vebt_delete summary (high (summin * 2 ^ n + lx) n))\<close> option.sel not_None_eq)
have abd:"maxi < 2^n"
by (metis \<open>Some maxi = vebt_maxt (?newlist ! maxs)\<close> \<open>invar_vebt (?newlist ! maxs) n\<close> maxt_member member_bound)
have "high ?xn n \<le> maxs"
using "1" \<open>Some summin = vebt_mint summary\<close> \<open>both_member_options summary maxs\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> high_inv member_bound mint_corr_help valid_member_both_member_options by force
then show ?thesis
proof(cases "high ?xn n = maxs")
case True
then show ?thesis
using bb by fastforce
next
case False
hence "high ?xn n < maxs"
by (simp add: \<open>high (summin * 2 ^ n + lx) n \<le> maxs\<close> order.not_eq_order_implies_strict)
hence "?newma < 2^deg"using
"1" "10" "9" True \<open>both_member_options summary maxs\<close> \<open>mi \<noteq> ma \<and> x < 2 ^ deg\<close>
equals0D leD maxt_corr_help maxt_corr_help_empty mem_Collect_eq summaxma set_vebt'_def
valid_member_both_member_options
by (metis option.exhaust_sel)
moreover have "high ?xn n < high ?newma n"
by (smt (z3) "9" True \<open>Some maxi = vebt_maxt (treeList [high (summin * 2 ^ n + lx) n := vebt_delete (treeList ! high (summin * 2 ^ n + lx) n) (low (summin * 2 ^ n + lx) n)] ! maxs)\<close> \<open>Some maxs = vebt_maxt (vebt_delete summary (high (summin * 2 ^ n + lx) n))\<close> \<open>high (summin * 2 ^ n + lx) n < maxs\<close> abd option.sel high_inv mult.commute option.discI)
ultimately show ?thesis
by (metis div_le_mono high_def linear not_less)
qed
qed
next
case False
then show ?thesis
by (smt (z3) "12" "4.hyps"(7) "4.hyps"(8) "9" both_member_options_from_complete_tree_to_child dual_order.trans hlbound one_le_numeral xnin yhelper)
qed
have 115: "?xn \<noteq> ?newma \<longrightarrow>
(\<forall> i < 2^m.
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma))"
proof
assume assumption0:"?xn \<noteq> ?newma"
show " (\<forall> i < 2^m.
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma))"
proof
fix i
show "i < 2^m \<longrightarrow>
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma)"
proof
assume assumption:"i < 2^m"
show " (high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma)"
proof-
have "(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n))"
proof
assume newmaassm: "high ?newma n = i"
thus " both_member_options (?newlist ! i) (low ?newma n)"
proof(cases "?xn = ma" )
case True
hence bb:"?xn = ma" by simp
let ?maxs = "vebt_maxt ?sn"
show ?thesis
proof(cases "?maxs = None")
case True
hence "?newma = ?xn" using assumption Let_def bb by simp
hence False using assumption0 by simp
then show ?thesis by simp
next
case False
then obtain maxs where "Some maxs = ?maxs"
by fastforce
hence "both_member_options summary maxs"
by (metis "1" dele_bmo_cont_corr maxbmo)
have bb:"maxs \<noteq> ?h \<and> maxs < 2^m"
by (metis "1" \<open>Some maxs = vebt_maxt ?sn\<close> dele_bmo_cont_corr maxbmo member_bound valid_member_both_member_options)
hence "invar_vebt (?newlist ! maxs) n"using 0 by (simp add: "2" allvalidinlist)
hence "\<exists> y. both_member_options (?newlist ! maxs) y"
using "4" \<open>both_member_options summary maxs\<close> bb nothprolist by presburger
then obtain maxi where "Some maxi = vebt_maxt (?newlist ! maxs)" using
\<open>invar_vebt (treeList [high (summin * 2 ^ n + lx) n :=
vebt_delete (treeList ! high (summin * 2 ^ n + lx) n) (low (summin * 2 ^ n + lx) n)] ! maxs) n\<close>
equals0D maxt_corr_help_empty mem_Collect_eq set_vebt'_def
valid_member_both_member_options
by (metis option.collapse)
then show ?thesis using "1" "10" "9" True \<open>Some summin = vebt_mint summary\<close>
\<open>both_member_options summary maxs\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>mi \<noteq> ma \<and> x < 2 ^ deg\<close>
\<open>invar_vebt (treeList ! summin) n\<close> bb equals0D high_inv maxt_corr_help maxt_corr_help_empty
mem_Collect_eq member_bound mint_corr_help nat_less_le summaxma set_vebt'_def
valid_member_both_member_options verit_comp_simplify1(3)
by (metis option.collapse)
qed
next
case False
hence ccc:"?newma = ma" by simp
then show ?thesis
proof(cases "?xn = ma")
case True
hence "?xn = ?newma"
using False by blast
hence False
using False by auto
then show ?thesis by simp
next
case False
hence "both_member_options (?newlist ! high ma n) (low ma n)"
by (metis "1" \<open>both_member_options (treeList ! high ma n) (low ma n)\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>vebt_member summary (high ma n)\<close> \<open>invar_vebt (treeList ! summin) n\<close> bit_split_inv dele_bmo_cont_corr high_inv hprolist member_bound nothprolist)
moreover have "high ma n = i \<and> low ma n = low ?newma n" using ccc newmaassm by simp
ultimately show ?thesis by simp
qed
qed
qed
moreover have " (\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma)"
proof
fix y
show "(high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma"
proof
assume yassm: "(high y n = i \<and> both_member_options (?newlist ! i) (low y n) )"
hence "?xn < y"
proof(cases "i = ?h")
case True
hence "both_member_options (treeList ! i) (low y n)"
using \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> dele_bmo_cont_corr high_inv hprolist member_bound yassm by auto
then show ?thesis
using True hprolist min_Null_member ninNullc nnvalid valid_member_both_member_options yassm by fastforce
next
case False
hence "i \<le> ?h \<Longrightarrow> False"
by (metis "1" "111" \<open>Some summin = vebt_mint summary\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> assumption dele_bmo_cont_corr high_inv le_antisym member_bound mint_corr_help valid_member_both_member_options yassm)
hence "i > ?h"
using leI by blast
then show ?thesis
by (metis div_le_mono high_def not_less yassm)
qed
moreover have "y \<le> ?newma"
proof(cases "?xn = ma")
case True
hence "?xn= ma" by simp
let ?maxs = "vebt_maxt ?sn"
show ?thesis
proof(cases "?maxs = None")
case True
then show ?thesis
using "1" "111" assumption dele_bmo_cont_corr nothprolist yassm yhelper by auto
next
case False
then obtain maxs where "Some maxs = ?maxs"
by fastforce
hence "both_member_options summary maxs"
by (metis "1" dele_bmo_cont_corr maxbmo)
have bb:"maxs \<noteq> ?h \<and> maxs < 2^m"
by (metis "1" \<open>Some maxs = vebt_maxt ?sn\<close> dele_bmo_cont_corr maxbmo member_bound valid_member_both_member_options)
hence "invar_vebt (?newlist ! maxs) n"using 0
by (simp add: "2" allvalidinlist)
hence "\<exists> y. both_member_options (?newlist ! maxs) y"
using "4" \<open>both_member_options summary maxs\<close> bb nothprolist by presburger
then obtain maxi where "Some maxi = vebt_maxt (?newlist ! maxs)"
by (metis True \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> assumption calculation dele_bmo_cont_corr high_inv hprolist leD member_bound nth_list_update_neq yassm yhelper)
hence "maxs < 2^m \<and> maxi < 2^n"
by (metis \<open>invar_vebt (?newlist ! maxs) n\<close> bb maxt_member member_bound)
hence "?newma = 2^n* maxs + maxi"
by (smt (z3) "9" False True \<open>Some maxi = vebt_maxt (?newlist ! maxs)\<close> \<open>Some maxs = vebt_maxt (vebt_delete summary (high ?xn n))\<close> option.sel)
hence "low ?newma n = maxi \<and> high ?newma n = maxs"
by (simp add: \<open>maxs < 2 ^ m \<and> maxi < 2 ^ n\<close> high_inv low_inv mult.commute)
hence "both_member_options (treeList ! (high y n)) (low y n)"
by (metis "1" "111" assumption dele_bmo_cont_corr nothprolist yassm)
hence hleqdraft:"high y n > maxs \<Longrightarrow> False"
proof-
assume "high y n > maxs"
have "both_member_options summary (high y n)"
using "1" "111" assumption dele_bmo_cont_corr yassm by blast
moreover have "both_member_options ?sn (high y n)"
using "111" assumption yassm by blast
ultimately show False
using True \<open>both_member_options (treeList ! high y n) (low y n)\<close> \<open>summin * 2 ^ n + lx < y\<close> assumption leD yassm yhelper by blast
qed
hence hleqmaxs: "high y n \<le> maxs" by presburger
then show ?thesis
using \<open>both_member_options (treeList ! high y n) (low y n)\<close> assumption calculation dual_order.strict_trans1 yassm yhelper by auto
qed
next
case False
then show ?thesis
by (smt (z3) \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> assumption dele_bmo_cont_corr high_inv hprolist member_bound nothprolist yassm yhelper)
qed
ultimately show " ?xn < y \<and> y \<le> ?newma" by simp
qed
qed
ultimately show ?thesis by simp
qed
qed
qed
qed
hence 117: "?newma < 2^deg" and 118: "?xn \<le> ?newma" using 114 by auto
have 116: " invar_vebt (Node (Some (?xn, ?newma)) deg ?newlist ?sn) deg"
using invar_vebt.intros(4)[of ?newlist n ?sn m deg ?xn ?newma]
using 3 allvalidinlist newlistlength newsummvalid "4.hyps"(3) 111 112 118 117 115 by fastforce
show ?thesis
using "116" dsimp by presburger
next
case False
hence notemp:"\<exists> z. both_member_options ?newnode z"
using not_min_Null_member by auto
let ?newma = "(if ?xn = ma then
?h * 2^(deg div 2) + the( vebt_maxt (?newlist ! ?h))
else ma)"
let ?delsimp =" (Node (Some (?xn, ?newma)) deg ?newlist summary)"
have dsimp:"vebt_delete (Node (Some (x, ma)) deg treeList summary) x = ?delsimp"
using del_x_mi_lets_in_not_minNull[of x mi ma deg ?xn ?h summary treeList ?l ?newnode ?newlist]
"12" "2" "9" False dual_order.eq_iff hlbound inrg order.not_eq_order_implies_strict xmi
by (metis \<open>summin * 2 ^ n + lx = (if x = mi then the (vebt_mint summary) * 2 ^ (deg div 2) + the (vebt_mint (treeList ! the (vebt_mint summary))) else x)\<close> \<open>x \<noteq> mi \<or> x \<noteq> ma\<close>)
have 111: "(\<forall> i < 2^m. (\<exists> x. both_member_options (?newlist ! i) x) \<longleftrightarrow> ( both_member_options summary i))"
proof
fix i
show " i < 2^m \<longrightarrow> ((\<exists> x. both_member_options (?newlist ! i) x) = ( both_member_options summary i))"
proof
assume "i < 2^m"
show "(\<exists> x. both_member_options (?newlist ! i) x) = ( both_member_options summary i)"
proof(cases "i = ?h")
case True
hence 1000:"?newlist ! i = ?newnode"
using hprolist by blast
hence 1001:"\<exists> x. vebt_member (?newlist ! i) x"
using nnvalid notemp valid_member_both_member_options by auto
hence 1002: "\<exists> x. both_member_options (?newlist ! i) x"
using "1000" notemp by presburger
have 1003: "both_member_options summary i"
using "4" True \<open>\<exists>z. both_member_options (treeList ! summin) z\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>summin < 2 ^ m\<close> \<open>invar_vebt (treeList ! summin) n\<close> high_inv member_bound by auto
then show ?thesis
using "1002" by blast
next
case False
hence 1000:"?newlist ! i = treeList ! i"
using \<open>i < 2 ^ m\<close> nothprolist by blast
then show ?thesis
using "4" \<open>i < 2 ^ m\<close> by presburger
qed
qed
qed
have 112:" (?xn = ?newma \<longrightarrow> (\<forall> t \<in> set ?newlist. \<nexists> x. both_member_options t x))"
proof
assume aampt:"?xn = ?newma"
show "(\<forall> t \<in> set ?newlist. \<nexists> y. both_member_options t y)"
proof(cases "?xn = ma")
case True
obtain maxi where " vebt_maxt (?newlist ! ?h) = Some maxi"
by (metis Collect_empty_eq False hprolist maxt_corr_help_empty nnvalid not_None_eq not_min_Null_member set_vebt'_def valid_member_both_member_options)
hence "both_member_options ?newnode maxi"
using hprolist maxbmo by auto
hence "both_member_options (treeList ! ?h) maxi"
using \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> dele_bmo_cont_corr high_inv member_bound by force
hence False
by (metis "9" \<open>both_member_options (vebt_delete (treeList ! high (summin * 2 ^ n + lx) n) (low (summin * 2 ^ n + lx) n)) maxi\<close> \<open>vebt_maxt (?newlist ! ?h) = Some maxi\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> aampt add_diff_cancel_left' dele_bmo_cont_corr option.sel high_inv low_inv member_bound)
then show ?thesis by blast
next
case False
then show ?thesis
using \<open>mi \<noteq> ma \<and> x < 2 ^ deg\<close> aampt by presburger
qed
qed
have 114: "?newma < 2^deg \<and> ?xn \<le> ?newma"
proof(cases "?xn = ma")
case True
hence "?xn = ma" by simp
obtain maxi where " vebt_maxt (?newlist ! ?h) = Some maxi"
by (metis "111" "2" "4" Collect_empty_eq True \<open>both_member_options (treeList ! high ma n) (low ma n)\<close> \<open>high (summin * 2 ^ n + lx) n < length treeList\<close> hprolist maxt_corr_help_empty nnvalid not_None_eq set_vebt'_def valid_member_both_member_options)
hence "both_member_options ?newnode maxi"
using hprolist maxbmo by auto
hence "both_member_options (treeList ! ?h) maxi"
using \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> dele_bmo_cont_corr high_inv member_bound by force
hence "maxi < 2^n"
using \<open>both_member_options?newnode maxi\<close> member_bound nnvalid valid_member_both_member_options by blast
show ?thesis
by (smt (verit, ccfv_threshold) "3" "9" div_eq_0_iff True \<open>Some lx = vebt_mint (treeList ! summin)\<close> \<open>both_member_options (treeList ! high (summin * 2 ^ n + lx) n) maxi\<close> \<open>vebt_maxt (?newlist ! high (summin * 2 ^ n + lx) n) = Some maxi\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> add.right_neutral add_left_mono div_mult2_eq div_mult_self3 option.sel high_inv hlbound le_0_eq member_bound mint_corr_help power_add power_not_zero rel_simps(28) valid_member_both_member_options)
next
case False
then show ?thesis
using "10" "4.hyps"(8) maxt_corr_help valid_member_both_member_options xnin by force
qed
have 115: "?xn \<noteq> ?newma \<longrightarrow>
(\<forall> i < 2^m.
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma))"
proof
assume xnmassm:"?xn \<noteq> ?newma"
show " (\<forall> i < 2^m.
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma))"
proof
fix i
show "i < 2^m \<longrightarrow>
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma)"
proof
assume assumption:"i < 2^m"
show " (high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma)"
proof-
have "(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n))"
proof
assume newmaassm: "high ?newma n = i"
thus " both_member_options (?newlist ! i) (low ?newma n)"
proof(cases "?xn = ma")
case True
obtain maxi where "vebt_maxt (?newlist ! ?h) = Some maxi"
by (metis Collect_empty_eq both_member_options_equiv_member hprolist maxt_corr_help_empty nnvalid not_Some_eq notemp set_vebt'_def)
hence "both_member_options (?newlist ! ?h) maxi"
using maxbmo by blast
then show ?thesis
by (smt (z3) "2" "9" True \<open>Some lx = vebt_mint (treeList ! summin)\<close> \<open>high (summin * 2 ^ n + lx) n < length treeList\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> add_left_mono dele_bmo_cont_corr eq_iff high_inv hprolist low_inv member_bound mint_corr_help valid_member_both_member_options yhelper)
next
case False
hence abcd:"?newma = ma" by simp
then show ?thesis
proof(cases "high ma n = ?h")
case True
hence "?newlist ! high ma n = ?newnode"
using hprolist by presburger
then show ?thesis
by (smt (z3) False True \<open>both_member_options (treeList ! high ma n) (low ma n)\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> bit_split_inv dele_bmo_cont_corr high_inv member_bound newmaassm)
next
case False
hence "?newlist ! high ma n = treeList ! high ma n"
using "1" \<open>vebt_member summary (high ma n)\<close> member_bound nothprolist by blast
moreover hence "both_member_options (treeList ! high ma n) (low ma n)"
using \<open>both_member_options (treeList ! high ma n) (low ma n)\<close> by blast
ultimately show ?thesis using abcd newmaassm by simp
qed
qed
qed
moreover have " (\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma)"
proof
fix y
show "(high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma"
proof
assume yassm: "(high y n = i \<and> both_member_options (?newlist ! i) (low y n) )"
hence "?xn < y"
proof(cases "i = ?h")
case True
hence "both_member_options (treeList ! i) (low y n)"
using \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> dele_bmo_cont_corr high_inv hprolist member_bound yassm by force
moreover have "vebt_mint (treeList ! i) = Some (low ?xn n)"
using True \<open>Some lx = vebt_mint (treeList ! summin)\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> high_inv low_inv member_bound by presburger
moreover hence "low y n \<ge> low ?xn n"
using True \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> calculation(1) high_inv member_bound mint_corr_help valid_member_both_member_options by auto
moreover have "low y n \<noteq> low ?xn n"
using True \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> dele_bmo_cont_corr high_inv hprolist member_bound yassm by auto
ultimately have "low y n > low ?xn n" by simp
show ?thesis
by (metis True \<open>low (summin * 2 ^ n + lx) n \<le> low y n\<close> \<open>low y n \<noteq> low (summin * 2 ^ n + lx) n\<close> bit_concat_def bit_split_inv leD linorder_neqE_nat nat_add_left_cancel_less yassm)
next
case False
have "Some (high ?xn n) = vebt_mint summary"
using \<open>Some summin = vebt_mint summary\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> high_inv member_bound by presburger
moreover hence "high y n \<ge> high ?xn n"
by (metis "1" "111" assumption mint_corr_help valid_member_both_member_options yassm)
ultimately show ?thesis
by (metis False div_le_mono high_def leI le_antisym yassm)
qed
moreover have "y \<le> ?newma"
by (smt (z3) \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> assumption calculation dele_bmo_cont_corr high_inv hprolist leD member_bound nothprolist yassm yhelper)
ultimately show " ?xn < y \<and> y \<le> ?newma" by simp
qed
qed
ultimately show ?thesis by simp
qed
qed
qed
qed
hence 117: "?newma < 2^deg" and 118: "?xn \<le> ?newma" using 114 by auto
have 116: " invar_vebt (Node (Some (?xn, ?newma)) deg ?newlist summary) deg"
using invar_vebt.intros(4)[of ?newlist n summary m deg ?xn ?newma] allvalidinlist
1 newlistlength 8 3 111 112 117 118 115 by fastforce
hence "invar_vebt (?delsimp) deg" by simp
moreover obtain delsimp where 118:"delsimp = ?delsimp" by simp
ultimately have 119:"invar_vebt delsimp deg" by simp
have "vebt_delete (Node (Some (x, ma)) deg treeList summary) x = delsimp" using dsimp 118 by simp
hence "delsimp = vebt_delete (Node (Some (x, ma)) deg treeList summary) x" by simp
then show ?thesis using 119
using xmi by auto
qed
qed
qed
qed
next
case (5 treeList n summary m deg mi ma)
hence 0: "( \<forall> t \<in> set treeList. invar_vebt t n)" and 1: " invar_vebt summary m" and 2:"length treeList = 2^m" and 3:" deg = n+m" and
4: "(\<forall> i < 2^m. (\<exists> y. both_member_options (treeList ! i) y) \<longleftrightarrow> ( both_member_options summary i))" and
5: "(mi = ma \<longrightarrow> (\<forall> t \<in> set treeList. \<nexists> y. both_member_options t y))" and 6:"mi \<le> ma \<and> ma < 2^deg" and
7: "(mi \<noteq> ma \<longrightarrow> (\<forall> i < 2^m. (high ma n = i \<longrightarrow> both_member_options (treeList ! i) (low ma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (treeList ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ma)))"
and 8: "Suc n = m" and 9: "deg div 2 = n" using "5" add_self_div_2 by auto
hence 10: "invar_vebt (Node (Some (mi, ma)) deg treeList summary) deg"
using invar_vebt.intros(5)[of treeList n summary m deg mi ma] by blast
hence 11:"n \<ge> 1 " and 12: " deg \<ge> 2"
by (metis "0" "2" "9" One_nat_def deg_not_0 div_greater_zero_iff le_0_eq numeral_2_eq_2 set_n_deg_not_0)+
then show ?case
proof(cases "(x < mi \<or> x > ma)")
case True
hence "vebt_delete (Node (Some (mi, ma)) deg treeList summary) x = (Node (Some (mi, ma)) deg treeList summary)"
using delt_out_of_range[of x mi ma deg treeList summary]
using "12" by fastforce
then show ?thesis
by (simp add: "10")
next
case False
hence inrg: "mi\<le> x \<and> x \<le> ma" by simp
then show ?thesis
proof(cases "x = mi \<and> x = ma")
case True
hence" (\<forall> t \<in> set treeList. \<nexists> y. both_member_options t y)"
using "5" by blast
moreover have "vebt_delete (Node (Some (mi, ma)) deg treeList summary) x = (Node None deg treeList summary)"
using del_single_cont[of x mi ma deg treeList summary] "1" "8" "9" True deg_not_0 div_greater_zero_iff "12" by fastforce
moreover have " (\<nexists> i. both_member_options summary i)"
using "10" True mi_eq_ma_no_ch by blast
ultimately show ?thesis
using "0" "1" "2" "3" "8" invar_vebt.intros(3) by force
next
case False
hence "x \<noteq> mi \<or> x \<noteq> ma" by simp
hence "mi \<noteq> ma \<and> x < 2^deg"
by (metis "6" inrg le_antisym le_less_trans)
hence "7b": "(\<forall> i < 2^m. (high ma n = i \<longrightarrow> both_member_options (treeList ! i) (low ma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (treeList ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ma))"
using "7" by fastforce
hence "both_member_options (treeList ! (high ma n)) (low ma n)"
by (metis "1" "12" "3" "6" "9" deg_not_0 div_greater_zero_iff exp_split_high_low(1) zero_less_numeral)
hence yhelper:"both_member_options (treeList ! (high y n)) (low y n)
\<Longrightarrow> high y n < 2^m \<Longrightarrow> mi < y \<and> y \<le> ma \<and> low y n < 2^n" for y
by (simp add: "7b" low_def)
then show ?thesis
proof(cases "x \<noteq> mi")
case True
hence xnotmi: "x \<noteq> mi" by simp
let ?h = "high x n"
let ?l = "low x n"
have hlbound:"?h < 2^m \<and> ?l < 2^n"
by (metis "1" "11" "3" One_nat_def \<open>mi \<noteq> ma \<and> x < 2 ^ deg\<close> deg_not_0 dual_order.strict_trans1 exp_split_high_low(1) exp_split_high_low(2) zero_less_Suc)
let ?newnode = "vebt_delete (treeList ! ?h) ?l"
have "treeList ! ?h \<in> set treeList "
by (metis "2" hlbound in_set_member inthall)
hence nnvalid: "invar_vebt ?newnode n"
by (simp add: "5.IH"(1))
let ?newlist = "treeList[?h:= ?newnode]"
have hlist:"?newlist ! ?h = ?newnode"
by (simp add: "2" hlbound)
have nothlist:"i \<noteq> ?h \<Longrightarrow> i < 2^m \<Longrightarrow> ?newlist ! i = treeList ! i" for i by simp
have allvalidinlist:"\<forall> t \<in> set ?newlist. invar_vebt t n"
proof
fix t
assume "t \<in> set ?newlist"
then obtain i where "i< 2^m \<and> ?newlist ! i = t"
by (metis "2" in_set_conv_nth length_list_update)
then show "invar_vebt t n"
by (metis "0" "2" hlist nnvalid nth_list_update_neq nth_mem)
qed
have newlistlength: "length ?newlist = 2^m"
by (simp add: "2")
then show ?thesis
proof(cases "minNull ?newnode")
case True
hence ninNullc: "minNull ?newnode" by simp
let ?sn = "vebt_delete summary ?h"
let ?newma= "(if x = ma then (let maxs = vebt_maxt ?sn in
(if maxs = None
then mi
else 2^(deg div 2) * the maxs
+ the (vebt_maxt (?newlist ! the maxs))
)
)
else ma)"
let ?delsimp =" (Node (Some (mi, ?newma)) deg ?newlist ?sn)"
have dsimp:"vebt_delete (Node (Some (mi, ma)) deg treeList summary) x = ?delsimp"
using del_x_not_mi_new_node_nil[of mi x ma deg ?h ?l ?newnode treeList ?sn summary ?newlist]
hlbound 9 11 12 True 2 inrg xnotmi by simp
have newsummvalid: "invar_vebt ?sn m"
by (simp add: "5.IH"(2))
have 111: "(\<forall> i < 2^m. (\<exists> x. both_member_options (?newlist ! i) x) \<longleftrightarrow> ( both_member_options ?sn i))"
proof
fix i
show " i < 2^m \<longrightarrow> ((\<exists> x. both_member_options (?newlist ! i) x) = ( both_member_options ?sn i))"
proof
assume "i < 2^m"
show "(\<exists> x. both_member_options (?newlist ! i) x) = ( both_member_options ?sn i)"
proof(cases "i = ?h")
case True
hence 1000:"?newlist ! i = ?newnode"
using hlist by blast
hence 1001:"\<nexists> x. vebt_member (?newlist ! i) x"
by (simp add: min_Null_member ninNullc)
hence 1002: "\<nexists> x. both_member_options (?newlist ! i) x"
using "1000" nnvalid valid_member_both_member_options by auto
have 1003: "\<not> both_member_options ?sn i"
using "1" True dele_bmo_cont_corr by auto
then show ?thesis
using "1002" by blast
next
case False
hence 1000:"?newlist ! i = treeList ! i"
using \<open>i < 2 ^ m\<close> nothlist by blast
hence "both_member_options (?newlist ! i) y \<Longrightarrow> both_member_options ?sn i" for y
by (metis "1" "4" False \<open>i < 2 ^ m\<close> dele_bmo_cont_corr)
moreover have "both_member_options ?sn i \<Longrightarrow> \<exists> y. both_member_options (?newlist ! i) y"
using "1" "4" \<open>i < 2 ^ m\<close> dele_bmo_cont_corr by force
then show ?thesis
using calculation by blast
qed
qed
qed
have 112:" (mi = ?newma \<longrightarrow> (\<forall> t \<in> set ?newlist. \<nexists> x. both_member_options t x))"
proof
assume aampt:"mi = ?newma"
show "(\<forall> t \<in> set ?newlist. \<nexists> y. both_member_options t y)"
proof(cases "x = ma")
case True
let ?maxs = "vebt_maxt ?sn"
show ?thesis
proof(cases "?maxs = None")
case True
hence aa:"\<nexists> y. vebt_member ?sn y"
using maxt_corr_help_empty newsummvalid set_vebt'_def by auto
hence "\<nexists> y. both_member_options ?sn y"
using newsummvalid valid_member_both_member_options by blast
hence "t \<in> set ?newlist \<Longrightarrow> \<nexists>y. both_member_options t y" for t
proof-
assume "t \<in> set ?newlist"
then obtain i where "?newlist ! i = t \<and> i< 2^m"
by (metis in_set_conv_nth newlistlength)
thus " \<nexists>y. both_member_options t y"
using "111" \<open>\<nexists>y. both_member_options (vebt_delete summary (high x n)) y\<close> by blast
qed
then show ?thesis by blast
next
case False
then obtain maxs where "Some maxs = ?maxs"
by fastforce
hence "both_member_options summary maxs"
by (metis "1" dele_bmo_cont_corr maxbmo)
have bb:"maxs \<noteq> ?h \<and> maxs < 2^m"
by (metis "1" \<open>Some maxs = vebt_maxt ?sn\<close> dele_bmo_cont_corr maxbmo member_bound valid_member_both_member_options)
hence "invar_vebt (?newlist ! maxs) n"using 0
by (metis allvalidinlist newlistlength nth_mem)
hence "\<exists> y. both_member_options (?newlist ! maxs) y"
using "4" bb \<open>both_member_options summary maxs\<close> nothlist by presburger
then obtain maxi where "Some maxi = vebt_maxt (?newlist ! maxs)"
by (metis Collect_empty_eq_bot \<open>invar_vebt (treeList[high x n := vebt_delete (treeList ! high x n) (low x n)] ! maxs) n\<close> bb bot_empty_eq equals0D maxt_corr_help_empty nth_list_update_neq option_shift.elims set_vebt'_def valid_member_both_member_options)
hence "maxs = high mi n \<and> both_member_options (?newlist ! maxs) (low mi n)"
by (smt (z3) "9" False True \<open>Some maxs = vebt_maxt (vebt_delete summary (high x n))\<close> \<open>invar_vebt (?newlist ! maxs) n\<close> aampt option.sel high_inv low_inv maxbmo maxt_member member_bound mult.commute)
hence False
by (metis bb nat_less_le nothlist yhelper)
then show ?thesis by simp
qed
next
case False
then show ?thesis
using \<open>mi \<noteq> ma \<and> x < 2 ^ deg\<close> aampt by presburger
qed
qed
have 114: "?newma < 2^deg \<and> mi \<le> ?newma"
proof(cases "x = ma")
case True
hence "x = ma" by simp
let ?maxs = "vebt_maxt ?sn"
show ?thesis
proof(cases "?maxs = None")
case True
then show ?thesis
using "6" by fastforce
next
case False
then obtain maxs where "Some maxs = ?maxs"
by fastforce
hence "both_member_options summary maxs"
by (metis "1" dele_bmo_cont_corr maxbmo)
have bb:"maxs \<noteq> ?h \<and> maxs < 2^m"
by (metis "1" \<open>Some maxs = vebt_maxt ?sn\<close> dele_bmo_cont_corr maxbmo member_bound valid_member_both_member_options)
hence "invar_vebt (?newlist ! maxs) n"using 0
by (metis allvalidinlist newlistlength nth_mem)
hence "\<exists> y. both_member_options (?newlist ! maxs) y"
using "4" bb \<open>both_member_options summary maxs\<close> nothlist by presburger
then obtain maxi where "Some maxi = vebt_maxt (?newlist ! maxs)"
by (smt (z3) VEBT_Member.vebt_member.simps(2) \<open>invar_vebt (?newlist ! maxs) n\<close> vebt_maxt.elims minNull.simps(1) min_Null_member valid_member_both_member_options)
then show ?thesis
by (smt (verit, best) "6" "9" \<open>Some maxs = vebt_maxt (vebt_delete summary (high x n))\<close> \<open>invar_vebt (?newlist ! maxs) n\<close> bb option.sel high_inv less_le_trans low_inv maxbmo maxt_member member_bound mult.commute not_less_iff_gr_or_eq nothlist verit_comp_simplify1(3) yhelper)
qed
next
case False
then show ?thesis
using "6" by auto
qed
have 115: "mi \<noteq> ?newma \<longrightarrow>
(\<forall> i < 2^m.
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma))"
proof
assume "mi \<noteq> ?newma"
show " (\<forall> i < 2^m.
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma))"
proof
fix i
show "i < 2^m \<longrightarrow>
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma)"
proof
assume assumption:"i < 2^m"
show " (high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma)"
proof-
have "(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n))"
proof
assume newmaassm: "high ?newma n = i"
thus " both_member_options (?newlist ! i) (low ?newma n)"
proof(cases "x = ma" )
case True
let ?maxs = "vebt_maxt ?sn"
show ?thesis
proof(cases "?maxs = None")
case True
then show ?thesis
by (smt (z3) "0" \<open>both_member_options (treeList ! high ma n) (low ma n)\<close> \<open>mi \<noteq> (if x = ma then let maxs = vebt_maxt (vebt_delete summary (high x n)) in if maxs = None then mi else 2 ^ (deg div 2) * the maxs + the (vebt_maxt (?newlist ! the maxs)) else ma)\<close> \<open>treeList ! high x n \<in> set treeList\<close> assumption bit_split_inv dele_bmo_cont_corr hlist newmaassm nothlist)
next
case False
then obtain maxs where "Some maxs = ?maxs"
by fastforce
hence "both_member_options summary maxs"
by (metis "1" dele_bmo_cont_corr maxbmo)
have bb:"maxs \<noteq> ?h \<and> maxs < 2^m"
by (metis "1" \<open>Some maxs = vebt_maxt ?sn\<close> dele_bmo_cont_corr maxbmo member_bound valid_member_both_member_options)
hence "invar_vebt (?newlist ! maxs) n"using 0 "2" by auto
hence "\<exists> y. both_member_options (?newlist ! maxs) y"
using "4" bb \<open>both_member_options summary maxs\<close> nothlist by presburger
then obtain maxi where "Some maxi = vebt_maxt (?newlist ! maxs)"
by (smt (z3) VEBT_Member.vebt_member.simps(2) \<open>invar_vebt (treeList[high x n := vebt_delete (treeList ! high x n) (low x n)] ! maxs) n\<close> vebt_maxt.elims minNull.simps(1) min_Null_member valid_member_both_member_options)
then show ?thesis
by (smt (z3) "9" True \<open>Some maxs = vebt_maxt (vebt_delete summary (high x n))\<close> \<open>invar_vebt (treeList[high x n := vebt_delete (treeList ! high x n) (low x n)] ! maxs) n\<close> option.sel high_inv low_inv maxbmo maxt_member member_bound mult.commute newmaassm option.distinct(1))
qed
next
case False
then show ?thesis
by (smt (z3) "0" \<open>both_member_options (treeList ! high ma n) (low ma n)\<close> \<open>treeList ! high x n \<in> set treeList\<close> assumption bit_split_inv dele_bmo_cont_corr hlist newmaassm nothlist)
qed
qed
moreover have " (\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma)"
proof
fix y
show "(high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma"
proof
assume yassm: "(high y n = i \<and> both_member_options (?newlist ! i) (low y n) )"
hence "mi < y"
proof(cases "i = ?h")
case True
hence "both_member_options (treeList ! i) (low y n)"
using "0" \<open>treeList ! high x n \<in> set treeList\<close> dele_bmo_cont_corr hlist yassm by auto
then show ?thesis
by (simp add: assumption yassm yhelper)
next
case False
then show ?thesis
using assumption nothlist yassm yhelper by presburger
qed
moreover have "y \<le> ?newma"
proof(cases "x = ma")
case True
hence "x= ma" by simp
let ?maxs = "vebt_maxt ?sn"
show ?thesis
proof(cases "?maxs = None")
case True
then show ?thesis
using \<open>mi \<noteq> ?newma\<close> \<open>x = ma\<close> by presburger
next
case False
then obtain maxs where "Some maxs = ?maxs"
by fastforce
hence "both_member_options summary maxs"
by (metis "1" dele_bmo_cont_corr maxbmo)
have bb:"maxs \<noteq> ?h \<and> maxs < 2^m"
by (metis "1" \<open>Some maxs = vebt_maxt ?sn\<close> dele_bmo_cont_corr maxbmo member_bound valid_member_both_member_options)
hence "invar_vebt (?newlist ! maxs) n"using 0 "2" by fastforce
hence "\<exists> y. both_member_options (?newlist ! maxs) y"
using "4" bb \<open>both_member_options summary maxs\<close> nothlist by presburger
then obtain maxi where "Some maxi = vebt_maxt (?newlist ! maxs)"
by (metis \<open>invar_vebt (treeList[high x n := vebt_delete (treeList ! high x n) (low x n)] ! maxs) n\<close> equals0D maxt_corr_help_empty mem_Collect_eq option_shift.elims set_vebt'_def valid_member_both_member_options)
hence "maxs < 2^m \<and> maxi < 2^n"
by (metis \<open>invar_vebt (?newlist ! maxs) n\<close> bb maxt_member member_bound)
hence "?newma = 2^n* maxs + maxi"
by (smt (z3) "9" False True \<open>Some maxi = vebt_maxt (?newlist ! maxs)\<close> \<open>Some maxs = vebt_maxt (vebt_delete summary (high x n))\<close> option.sel)
hence "low ?newma n = maxi \<and> high ?newma n = maxs"
by (simp add: \<open>maxs < 2 ^ m \<and> maxi < 2 ^ n\<close> high_inv low_inv mult.commute)
hence "both_member_options (treeList ! (high y n)) (low y n)"
by (metis "0" \<open>treeList ! high x n \<in> set treeList\<close> assumption dele_bmo_cont_corr hlist nothlist yassm)
hence hleqdraft:"high y n > maxs \<Longrightarrow> False"
proof-
assume "high y n > maxs"
have "both_member_options summary (high y n)"
using "1" "111" assumption dele_bmo_cont_corr yassm by blast
moreover have "both_member_options ?sn (high y n)"
using "111" assumption yassm by blast
ultimately show False
by (metis \<open>Some maxs = vebt_maxt (vebt_delete summary (high x n))\<close> \<open>maxs < high y n\<close> leD maxt_corr_help newsummvalid valid_member_both_member_options)
qed
hence hleqmaxs: "high y n \<le> maxs" by presburger
then show ?thesis
proof(cases "high y n = maxs")
case True
hence "low y n \<le> maxi"
by (metis \<open>Some maxi = vebt_maxt (treeList[high x n := vebt_delete (treeList ! high x n) (low x n)] ! maxs)\<close> \<open>invar_vebt (treeList[high x n := vebt_delete (treeList ! high x n) (low x n)] ! maxs) n\<close> maxt_corr_help valid_member_both_member_options yassm)
then show ?thesis
by (smt (z3) True \<open>(if x = ma then let maxs = vebt_maxt (vebt_delete summary (high x n)) in if maxs = None then mi else 2 ^ (deg div 2) * the maxs + the (vebt_maxt (treeList [high x n := vebt_delete (treeList ! high x n) (low x n)] ! the maxs)) else ma) = 2 ^ n * maxs + maxi\<close> add_le_cancel_left bit_concat_def bit_split_inv mult.commute)
next
case False
then show ?thesis
by (smt (z3) \<open>low (if x = ma then let maxs = vebt_maxt (vebt_delete summary (high x n)) in if maxs = None then mi else 2 ^ (deg div 2) * the maxs + the (vebt_maxt (treeList [high x n := vebt_delete (treeList ! high x n) (low x n)] ! the maxs)) else ma) n = maxi \<and> high (if x = ma then let maxs = vebt_maxt (vebt_delete summary (high x n)) in if maxs = None then mi else 2 ^ (deg div 2) * the maxs + the (vebt_maxt (treeList [high x n := vebt_delete (treeList ! high x n) (low x n)] ! the maxs)) else ma) n = maxs\<close> div_le_mono high_def hleqmaxs le_antisym nat_le_linear)
qed
qed
next
case False
then show ?thesis
by (smt (z3) "0" \<open>treeList ! high x n \<in> set treeList\<close> assumption dele_bmo_cont_corr hlist nothlist yassm yhelper)
qed
ultimately show " mi < y \<and> y \<le> ?newma" by simp
qed
qed
ultimately show ?thesis by simp
qed
qed
qed
qed
hence 117: "?newma < 2^deg" and 118: "mi \<le> ?newma" using 114 by auto
have 116: " invar_vebt (Node (Some (mi, ?newma)) deg ?newlist ?sn) deg"
using invar_vebt.intros(5)[of ?newlist n ?sn m deg mi ?newma]
using 3 allvalidinlist newlistlength newsummvalid "5.hyps"(3) 111 112 118 117 115 by fastforce
show ?thesis
using "116" dsimp by presburger
next
case False
hence notemp:"\<exists> z. both_member_options ?newnode z"
using not_min_Null_member by auto
let ?newma = "(if x = ma then
?h * 2^(deg div 2) + the( vebt_maxt (?newlist ! ?h))
else ma)"
let ?delsimp =" (Node (Some (mi, ?newma)) deg ?newlist summary)"
have dsimp:"vebt_delete (Node (Some (mi, ma)) deg treeList summary) x = ?delsimp"
using del_x_not_mi_newnode_not_nil[of mi x ma deg ?h ?l ?newnode treeList ?newlist summary]
by (metis "12" "2" "9" False dual_order.eq_iff hlbound inrg order.not_eq_order_implies_strict xnotmi)
have 111: "(\<forall> i < 2^m. (\<exists> x. both_member_options (?newlist ! i) x) \<longleftrightarrow> ( both_member_options summary i))"
proof
fix i
show " i < 2^m \<longrightarrow> ((\<exists> x. both_member_options (?newlist ! i) x) = ( both_member_options summary i))"
proof
assume "i < 2^m"
show "(\<exists> x. both_member_options (?newlist ! i) x) = ( both_member_options summary i)"
proof(cases "i = ?h")
case True
hence 1000:"?newlist ! i = ?newnode"
using hlist by blast
hence 1001:"\<exists> x. vebt_member (?newlist ! i) x"
using nnvalid notemp valid_member_both_member_options by auto
hence 1002: "\<exists> x. both_member_options (?newlist ! i) x"
using "1000" notemp by presburger
have 1003: "both_member_options summary i"
using "0" "1000" "1002" "4" True \<open>i < 2 ^ m\<close> \<open>treeList ! high x n \<in> set treeList\<close> dele_bmo_cont_corr by fastforce
then show ?thesis
using "1002" by blast
next
case False
hence 1000:"?newlist ! i = treeList ! i"
using \<open>i < 2 ^ m\<close> nothlist by blast
then show ?thesis
using "4" \<open>i < 2 ^ m\<close> by presburger
qed
qed
qed
have 112:" (mi = ?newma \<longrightarrow> (\<forall> t \<in> set ?newlist. \<nexists> x. both_member_options t x))"
proof
assume aampt:"mi = ?newma"
show "(\<forall> t \<in> set ?newlist. \<nexists> y. both_member_options t y)"
proof(cases "x = ma")
case True
obtain maxi where " vebt_maxt (?newlist ! ?h) = Some maxi"
by (metis False VEBT_Member.vebt_member.simps(2) hlist vebt_maxt.elims minNull.simps(1) nnvalid notemp valid_member_both_member_options)
hence "both_member_options ?newnode maxi"
using hlist maxbmo by auto
hence "both_member_options (treeList ! ?h) maxi"
using "0" \<open>treeList ! high x n \<in> set treeList\<close> dele_bmo_cont_corr by blast
hence False
by (metis "9" True \<open>both_member_options ?newnode maxi\<close> \<open>vebt_maxt ( ?newlist ! high x n) = Some maxi\<close> aampt option.sel high_inv hlbound low_inv member_bound nnvalid not_less_iff_gr_or_eq valid_member_both_member_options yhelper)
then show ?thesis by blast
next
case False
then show ?thesis
using \<open>mi \<noteq> ma \<and> x < 2 ^ deg\<close> aampt by presburger
qed
qed
have 114: "?newma < 2^deg \<and> mi \<le> ?newma"
proof(cases "x = ma")
case True
hence "x = ma" by simp
obtain maxi where " vebt_maxt (?newlist ! ?h) = Some maxi"
by (metis False VEBT_Member.vebt_member.simps(2) hlist vebt_maxt.elims minNull.simps(1) nnvalid notemp valid_member_both_member_options)
hence "both_member_options ?newnode maxi"
using hlist maxbmo by auto
hence "both_member_options (treeList ! ?h) maxi"
using "0" \<open>treeList ! high x n \<in> set treeList\<close> dele_bmo_cont_corr by blast
hence "maxi < 2^n"
using \<open>both_member_options?newnode maxi\<close> member_bound nnvalid valid_member_both_member_options by blast
show ?thesis
by (smt (z3) "3" "9" div_eq_0_iff True \<open>both_member_options (treeList ! high x n) maxi\<close> \<open>maxi < 2 ^ n\<close> \<open>vebt_maxt ( ?newlist ! high x n) = Some maxi\<close> add.right_neutral div_exp_eq div_mult_self3 option.sel high_inv hlbound le_0_eq less_imp_le_nat low_inv power_not_zero rel_simps(28) yhelper)
next
case False
then show ?thesis
using "6" by auto
qed
have 115: "mi \<noteq> ?newma \<longrightarrow>
(\<forall> i < 2^m.
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma))"
proof
assume "mi \<noteq> ?newma"
show " (\<forall> i < 2^m.
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma))"
proof
fix i
show "i < 2^m \<longrightarrow>
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma)"
proof
assume assumption:"i < 2^m"
show " (high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma)"
proof-
have "(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n))"
proof
assume newmaassm: "high ?newma n = i"
thus " both_member_options (?newlist ! i) (low ?newma n)"
proof(cases "x = ma")
case True
obtain maxi where "vebt_maxt (?newlist ! ?h) = Some maxi"
by (metis Collect_empty_eq both_member_options_equiv_member hlist maxt_corr_help_empty nnvalid not_Some_eq notemp set_vebt'_def)
hence "both_member_options (?newlist ! ?h) maxi"
using maxbmo by blast
then show ?thesis
by (smt (z3) "9" True \<open>vebt_maxt (?newlist ! high x n) = Some maxi\<close> option.sel high_inv hlist low_inv maxt_member member_bound newmaassm nnvalid)
next
case False
then show ?thesis
by (smt (z3) "0" \<open>both_member_options (treeList ! high ma n) (low ma n)\<close> \<open>treeList ! high x n \<in> set treeList\<close> assumption bit_split_inv dele_bmo_cont_corr hlist newmaassm nothlist)
qed
qed
moreover have " (\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma)"
proof
fix y
show "(high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> mi < y \<and> y \<le> ?newma"
proof
assume yassm: "(high y n = i \<and> both_member_options (?newlist ! i) (low y n) )"
hence "mi < y"
proof(cases "i = ?h")
case True
hence "both_member_options (treeList ! i) (low y n)"
using "0" \<open>treeList ! high x n \<in> set treeList\<close> dele_bmo_cont_corr hlist yassm by auto
then show ?thesis
by (simp add: assumption yassm yhelper)
next
case False
then show ?thesis
using assumption nothlist yassm yhelper by presburger
qed
moreover have "y \<le> ?newma"
proof(cases "x = ma")
case True
hence "x= ma" by simp
obtain maxi where "vebt_maxt (?newlist ! ?h) = Some maxi"
by (metis Collect_empty_eq both_member_options_equiv_member hlist maxt_corr_help_empty nnvalid not_Some_eq notemp set_vebt'_def)
hence "both_member_options (?newlist ! ?h) maxi"
using maxbmo by blast
have "high y n \<le> ?h"
by (metis "7b" True assumption div_le_mono high_def nothlist yassm)
then show ?thesis
proof(cases "high y n = ?h")
case True
have "low y n > maxi \<Longrightarrow> False"
by (metis True \<open>vebt_maxt (?newlist ! ?h) = Some maxi\<close> hlist leD maxt_corr_help nnvalid valid_member_both_member_options yassm)
then show ?thesis
by (smt (z3) "9" True \<open>vebt_maxt (?newlist ! ?h) = Some maxi\<close> \<open>x = ma\<close> add_le_cancel_left div_mult_mod_eq option.sel high_def low_def nat_le_linear nat_less_le)
next
case False
then show ?thesis
by (smt (z3) "9" True \<open>both_member_options (?newlist ! high x n) maxi\<close> \<open>high y n \<le> high x n\<close> \<open>vebt_maxt (?newlist ! high x n) = Some maxi\<close> div_le_mono option.sel high_def high_inv hlist le_antisym member_bound nat_le_linear nnvalid valid_member_both_member_options)
qed
next
case False
then show ?thesis
by (smt (z3) "0" \<open>treeList ! high x n \<in> set treeList\<close> assumption dele_bmo_cont_corr hlist nothlist yassm yhelper)
qed
ultimately show " mi < y \<and> y \<le> ?newma" by simp
qed
qed
ultimately show ?thesis by simp
qed
qed
qed
qed
hence 117: "?newma < 2^deg" and 118: "mi \<le> ?newma" using 114 by auto
have 116: " invar_vebt (Node (Some (mi, ?newma)) deg ?newlist summary) deg"
using invar_vebt.intros(5)[of ?newlist n summary m deg mi ?newma] allvalidinlist
1 newlistlength 8 3 111 112 117 118 115 by fastforce
then show ?thesis
using dsimp by presburger
qed
next
case False
hence xmi:"x = mi" by simp
have "both_member_options summary (high ma n)"
by (metis "1" "11" "3" "4" "6" One_nat_def Suc_le_eq \<open>both_member_options (treeList ! high ma n) (low ma n)\<close> deg_not_0 exp_split_high_low(1))
hence "vebt_member summary (high ma n)"
using "5.hyps"(1) valid_member_both_member_options by blast
obtain summin where "Some summin = vebt_mint summary"
by (metis "5.hyps"(1) \<open>vebt_member summary (high ma n)\<close> empty_Collect_eq mint_corr_help_empty not_None_eq set_vebt'_def)
hence "\<exists> z . both_member_options (treeList ! summin) z"
by (metis "5.hyps"(1) "5.hyps"(5) both_member_options_equiv_member member_bound mint_member)
moreover have "invar_vebt (treeList ! summin) n"
by (metis "0" "1" "2" \<open>Some summin = vebt_mint summary\<close> member_bound mint_member nth_mem)
ultimately obtain lx where "Some lx = vebt_mint (treeList ! summin)"
by (metis empty_Collect_eq mint_corr_help_empty not_None_eq set_vebt'_def valid_member_both_member_options)
let ?xn = "summin*2^n + lx"
have "?xn = (if x = mi
then the (vebt_mint summary) * 2^(deg div 2)
+ the (vebt_mint (treeList ! the (vebt_mint summary)))
else x)"
by (metis False \<open>Some lx = vebt_mint (treeList ! summin)\<close> \<open>Some summin = vebt_mint summary\<close> \<open>deg div 2 = n\<close> option.sel)
have "vebt_member (treeList ! summin) lx"
using \<open>Some lx = vebt_mint (treeList ! summin)\<close> \<open>invar_vebt (treeList ! summin) n\<close> mint_member by auto
moreover have "summin < 2^m"
by (metis "5.hyps"(1) \<open>Some summin = vebt_mint summary\<close> member_bound mint_member)
ultimately have xnin: "both_member_options (Node (Some (mi, ma)) deg treeList summary) ?xn"
by (metis "12" "2" "9" \<open>invar_vebt (treeList ! summin) n\<close> add_leD1 both_member_options_equiv_member both_member_options_from_chilf_to_complete_tree high_inv low_inv member_bound numeral_2_eq_2 plus_1_eq_Suc)
let ?h ="high ?xn n"
let ?l = "low ?xn n"
have "?xn < 2^deg"
by (smt (verit, ccfv_SIG) "5.hyps"(1) "5.hyps"(4) div_eq_0_iff \<open>Some lx = vebt_mint (treeList ! summin)\<close> \<open>Some summin = vebt_mint summary\<close> \<open>invar_vebt (treeList ! summin) n\<close> div_exp_eq high_def high_inv le_0_eq member_bound mint_member not_numeral_le_zero power_not_zero)
hence "?h < length treeList"
using "2" \<open>vebt_member (treeList ! summin) lx\<close> \<open>summin < 2 ^ m\<close> \<open>invar_vebt (treeList ! summin) n\<close> high_inv member_bound by presburger
let ?newnode = "vebt_delete (treeList ! ?h) ?l"
let ?newlist = "treeList[?h:= ?newnode]"
have "length treeList = length ?newlist" by auto
hence hprolist: "?newlist ! ?h = ?newnode"
by (meson \<open>high (summin * 2 ^ n + lx) n < length treeList\<close> nth_list_update_eq)
have nothprolist: "i \<noteq> ?h \<and> i < 2^m \<Longrightarrow> ?newlist ! i = treeList ! i" for i by auto
have hlbound:"?h < 2^m \<and> ?l < 2^n"
using "2" \<open>high (summin * 2 ^ n + lx) n < length treeList\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> low_inv member_bound by presburger
hence nnvalid: "invar_vebt ?newnode n"
by (metis "5.IH"(1) \<open>high (summin * 2 ^ n + lx) n < length treeList\<close> inthall member_def)
have allvalidinlist:"\<forall> t \<in> set ?newlist. invar_vebt t n"
proof
fix t
assume "t \<in> set ?newlist"
then obtain i where "i < 2^m \<and> ?newlist ! i = t"
by (metis "2" in_set_conv_nth length_list_update)
then show "invar_vebt t n"
by (metis "0" "2" hprolist nnvalid nth_list_update_neq nth_mem)
qed
have newlistlength: "length ?newlist = 2^m"
by (simp add: "2")
then show ?thesis
proof(cases "minNull ?newnode")
case True
hence ninNullc: "minNull ?newnode" by simp
let ?sn = "vebt_delete summary ?h"
let ?newma= "(if ?xn = ma then (let maxs = vebt_maxt ?sn in
(if maxs = None
then ?xn
else 2^(deg div 2) * the maxs
+ the (vebt_maxt (?newlist ! the maxs))
)
)
else ma)"
let ?delsimp =" (Node (Some (?xn, ?newma)) deg ?newlist ?sn)"
have dsimp:"vebt_delete (Node (Some (mi, ma)) deg treeList summary) x = ?delsimp"
using del_x_mi_lets_in_minNull[of x mi ma deg ?xn ?h summary treeList ?l ?newnode ?newlist ?sn]
by (metis "12" "9" \<open>high (summin * 2 ^ n + lx) n < length treeList\<close> \<open>summin * 2 ^ n + lx = (if x = mi then the (vebt_mint summary) * 2 ^ (deg div 2) + the (vebt_mint (treeList ! the (vebt_mint summary))) else x)\<close> \<open>x = mi\<close> \<open>x \<noteq> mi \<or> x \<noteq> ma\<close> inrg nat_less_le ninNullc)
have newsummvalid: "invar_vebt ?sn m"
by (simp add: "5.IH"(2))
have 111: "(\<forall> i < 2^m. (\<exists> x. both_member_options (?newlist ! i) x) \<longleftrightarrow> ( both_member_options ?sn i))"
proof
fix i
show " i < 2^m \<longrightarrow> ((\<exists> x. both_member_options (?newlist ! i) x) = ( both_member_options ?sn i))"
proof
assume "i < 2^m"
show "(\<exists> x. both_member_options (?newlist ! i) x) = ( both_member_options ?sn i)"
proof(cases "i = ?h")
case True
hence 1000:"?newlist ! i = ?newnode"
using hprolist by fastforce
hence 1001:"\<nexists> x. vebt_member (?newlist ! i) x"
by (simp add: min_Null_member ninNullc)
hence 1002: "\<nexists> x. both_member_options (?newlist ! i) x"
using "1000" nnvalid valid_member_both_member_options by auto
have 1003: "\<not> both_member_options ?sn i"
using "1" True dele_bmo_cont_corr by auto
then show ?thesis
using "1002" by blast
next
case False
hence 1000:"?newlist ! i = treeList ! i"
using \<open>i < 2 ^ m\<close> nothprolist by blast
hence "both_member_options (?newlist ! i) y \<Longrightarrow> both_member_options ?sn i" for y
using "1" "4" False \<open>i < 2 ^ m\<close> dele_bmo_cont_corr by auto
moreover have "both_member_options ?sn i \<Longrightarrow> \<exists> y. both_member_options (?newlist ! i) y"
proof-
assume "both_member_options ?sn i "
hence "both_member_options summary i"
using "1" dele_bmo_cont_corr by auto
thus " \<exists> y. both_member_options (?newlist ! i) y"
using "1000" "4" \<open>i < 2 ^ m\<close> by presburger
qed
then show ?thesis
using calculation by blast
qed
qed
qed
have 112:" (?xn = ?newma \<longrightarrow> (\<forall> t \<in> set ?newlist. \<nexists> x. both_member_options t x))"
proof
assume aampt:"?xn = ?newma"
show "(\<forall> t \<in> set ?newlist. \<nexists> y. both_member_options t y)"
proof(cases "?xn = ma")
case True
let ?maxs = "vebt_maxt ?sn"
show ?thesis
proof(cases "?maxs = None")
case True
hence aa:"\<nexists> y. vebt_member ?sn y"
using maxt_corr_help_empty newsummvalid set_vebt'_def by auto
hence "\<nexists> y. both_member_options ?sn y"
using newsummvalid valid_member_both_member_options by blast
hence "t \<in> set ?newlist \<Longrightarrow> \<nexists>y. both_member_options t y" for t
proof-
assume "t \<in> set ?newlist"
then obtain i where "?newlist ! i = t \<and> i< 2^m"
by (metis "2" \<open>length treeList = length (treeList [high (summin * 2 ^ n + lx) n := vebt_delete (treeList ! high (summin * 2 ^ n + lx) n) (low (summin * 2 ^ n + lx) n)])\<close> in_set_conv_nth)
thus " \<nexists>y. both_member_options t y"
using "111" \<open>\<nexists>y. both_member_options (vebt_delete summary (high (summin * 2 ^ n + lx) n)) y\<close> by blast
qed
then show ?thesis by blast
next
case False
then obtain maxs where "Some maxs = ?maxs"
by fastforce
hence "both_member_options summary maxs"
by (metis "1" dele_bmo_cont_corr maxbmo)
have bb:"maxs \<noteq> ?h \<and> maxs < 2^m"
by (metis "1" \<open>Some maxs = vebt_maxt ?sn\<close> dele_bmo_cont_corr maxbmo member_bound valid_member_both_member_options)
hence "invar_vebt (?newlist ! maxs) n"using 0
by (simp add: "2" allvalidinlist)
hence "\<exists> y. both_member_options (?newlist ! maxs) y"
using "4" bb \<open>both_member_options summary maxs\<close> nothprolist by presburger
then obtain maxi where "Some maxi = vebt_maxt (?newlist ! maxs)"
by (smt (z3) VEBT_Member.vebt_member.simps(2) \<open>invar_vebt (?newlist ! maxs) n\<close> vebt_maxt.elims minNull.simps(1) min_Null_member valid_member_both_member_options)
hence "maxs = high ?xn n \<and> both_member_options (?newlist ! maxs) (low ?xn n)"
by (smt (z3) "9" False True \<open>Some maxs = vebt_maxt (vebt_delete summary ?h)\<close> \<open>invar_vebt (?newlist ! maxs) n\<close> aampt option.sel high_inv low_inv maxbmo maxt_member member_bound mult.commute)
hence False
using bb by blast
then show ?thesis by simp
qed
next
case False
hence "?xn \<noteq> ?newma" by simp
hence False using aampt by simp
then show ?thesis by blast
qed
qed
have 114: "?newma < 2^deg \<and> ?xn \<le> ?newma"
proof(cases "?xn = ma")
case True
hence "?xn = ma" by simp
let ?maxs = "vebt_maxt ?sn"
show ?thesis
proof(cases "?maxs = None")
case True
then show ?thesis
using "5.hyps"(8) \<open>?xn = ma\<close> by force
next
case False
then obtain maxs where "Some maxs = ?maxs"
by fastforce
hence "both_member_options summary maxs"
by (metis "1" dele_bmo_cont_corr maxbmo)
have bb:"maxs \<noteq> ?h \<and> maxs < 2^m"
by (metis "1" \<open>Some maxs = vebt_maxt ?sn\<close> dele_bmo_cont_corr maxbmo member_bound valid_member_both_member_options)
hence "invar_vebt (?newlist ! maxs) n"using 0 by (simp add: "2" allvalidinlist)
hence "\<exists> y. both_member_options (?newlist ! maxs) y"
using "4" \<open>both_member_options summary maxs\<close> bb nothprolist by presburger
then obtain maxi where "Some maxi = vebt_maxt (?newlist ! maxs)"
using \<open>invar_vebt (treeList [high (summin * 2 ^ n + lx) n := vebt_delete (treeList ! high (summin * 2 ^ n + lx) n) (low (summin * 2 ^ n + lx) n)] ! maxs) n\<close> maxt_corr_help_empty set_vebt'_def valid_member_both_member_options by fastforce
hence abc:"?newma = 2^n * maxs + maxi"
by (smt (z3) "9" True \<open>Some maxs = vebt_maxt (vebt_delete summary (high (summin * 2 ^ n + lx) n))\<close> option.sel not_None_eq)
have abd:"maxi < 2^n"
by (metis \<open>Some maxi = vebt_maxt (?newlist ! maxs)\<close> \<open>invar_vebt (?newlist ! maxs) n\<close> maxt_member member_bound)
have "high ?xn n \<le> maxs"
using "1" \<open>Some summin = vebt_mint summary\<close> \<open>both_member_options summary maxs\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> high_inv member_bound mint_corr_help valid_member_both_member_options by force
then show ?thesis
proof(cases "high ?xn n = maxs")
case True
then show ?thesis
using bb by fastforce
next
case False
hence "high ?xn n < maxs"
by (simp add: \<open>high (summin * 2 ^ n + lx) n \<le> maxs\<close> order.not_eq_order_implies_strict)
hence "?newma < 2^deg"
by (smt (z3) "5.hyps"(8) "9" \<open>Some maxi = vebt_maxt (?newlist ! maxs)\<close> \<open>Some maxs = vebt_maxt (vebt_delete summary (high (summin * 2 ^ n + lx) n))\<close> \<open>invar_vebt (?newlist ! maxs) n\<close> abd bb both_member_options_equiv_member option.sel high_inv less_le_trans low_inv maxt_member mult.commute nothprolist verit_comp_simplify1(3) yhelper)
moreover have "high ?xn n < high ?newma n"
by (smt (z3) "9" True \<open>Some maxi = vebt_maxt (?newlist ! maxs)\<close> \<open>Some maxs = vebt_maxt (vebt_delete summary (high (summin * 2 ^ n + lx) n))\<close> \<open>high (summin * 2 ^ n + lx) n < maxs\<close> abd option.sel high_inv mult.commute option.discI)
ultimately show ?thesis
by (metis div_le_mono high_def linear not_less)
qed
qed
next
case False
then show ?thesis
by (smt (z3) "12" "5.hyps"(7) "5.hyps"(8) "9" both_member_options_from_complete_tree_to_child dual_order.trans hlbound one_le_numeral xnin yhelper)
qed
have 115: "?xn \<noteq> ?newma \<longrightarrow>
(\<forall> i < 2^m.
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma))"
proof
assume assumption0:"?xn \<noteq> ?newma"
show " (\<forall> i < 2^m.
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma))"
proof
fix i
show "i < 2^m \<longrightarrow>
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma)"
proof
assume assumption:"i < 2^m"
show " (high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma)"
proof-
have "(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n))"
proof
assume newmaassm: "high ?newma n = i"
thus " both_member_options (?newlist ! i) (low ?newma n)"
proof(cases "?xn = ma" )
case True
hence bb:"?xn = ma" by simp
let ?maxs = "vebt_maxt ?sn"
show ?thesis
proof(cases "?maxs = None")
case True
hence "?newma = ?xn" using assumption Let_def bb by simp
hence False using assumption0 by simp
then show ?thesis by simp
next
case False
then obtain maxs where "Some maxs = ?maxs"
by fastforce
hence "both_member_options summary maxs"
by (metis "1" dele_bmo_cont_corr maxbmo)
have bb:"maxs \<noteq> ?h \<and> maxs < 2^m"
by (metis "1" \<open>Some maxs = vebt_maxt ?sn\<close> dele_bmo_cont_corr maxbmo member_bound valid_member_both_member_options)
hence "invar_vebt (?newlist ! maxs) n"using 0 by (simp add: "2" allvalidinlist)
hence "\<exists> y. both_member_options (?newlist ! maxs) y"
using "4" \<open>both_member_options summary maxs\<close> bb nothprolist by presburger
then obtain maxi where "Some maxi = vebt_maxt (?newlist ! maxs)"
using \<open>invar_vebt (treeList [high (summin * 2 ^ n + lx) n := vebt_delete (treeList ! high (summin * 2 ^ n + lx) n) (low (summin * 2 ^ n + lx) n)] ! maxs) n\<close> maxt_corr_help_empty set_vebt'_def valid_member_both_member_options by fastforce
then show ?thesis
by (metis "1" "10" "9" True \<open>Some summin = vebt_mint summary\<close> \<open>both_member_options summary maxs\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>mi \<noteq> ma \<and> x < 2 ^ deg\<close> \<open>invar_vebt (treeList ! summin) n\<close> bb equals0D high_inv le_antisym maxt_corr_help maxt_corr_help_empty mem_Collect_eq member_bound mint_corr_help option.collapse summaxma set_vebt'_def valid_member_both_member_options)
qed
next
case False
hence ccc:"?newma = ma" by simp
then show ?thesis
proof(cases "?xn = ma")
case True
hence "?xn = ?newma"
using False by blast
hence False
using False by auto
then show ?thesis by simp
next
case False
hence "both_member_options (?newlist ! high ma n) (low ma n)"
by (metis "1" \<open>both_member_options (treeList ! high ma n) (low ma n)\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>vebt_member summary (high ma n)\<close> \<open>invar_vebt (treeList ! summin) n\<close> bit_split_inv dele_bmo_cont_corr high_inv hprolist member_bound nothprolist)
moreover have "high ma n = i \<and> low ma n = low ?newma n" using ccc newmaassm by simp
ultimately show ?thesis by simp
qed
qed
qed
moreover have " (\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma)"
proof
fix y
show "(high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma"
proof
assume yassm: "(high y n = i \<and> both_member_options (?newlist ! i) (low y n) )"
hence "?xn < y"
proof(cases "i = ?h")
case True
hence "both_member_options (treeList ! i) (low y n)"
using \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> dele_bmo_cont_corr high_inv hprolist member_bound yassm by auto
then show ?thesis
using True hprolist min_Null_member ninNullc nnvalid valid_member_both_member_options yassm by fastforce
next
case False
hence "i \<le> ?h \<Longrightarrow> False"
by (metis "1" "111" \<open>Some summin = vebt_mint summary\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> assumption dele_bmo_cont_corr high_inv le_antisym member_bound mint_corr_help valid_member_both_member_options yassm)
hence "i > ?h"
using leI by blast
then show ?thesis
by (metis div_le_mono high_def not_less yassm)
qed
moreover have "y \<le> ?newma"
proof(cases "?xn = ma")
case True
hence "?xn= ma" by simp
let ?maxs = "vebt_maxt ?sn"
show ?thesis
proof(cases "?maxs = None")
case True
then show ?thesis
using "1" "111" assumption dele_bmo_cont_corr nothprolist yassm yhelper by auto
next
case False
then obtain maxs where "Some maxs = ?maxs"
by fastforce
hence "both_member_options summary maxs"
by (metis "1" dele_bmo_cont_corr maxbmo)
have bb:"maxs \<noteq> ?h \<and> maxs < 2^m"
by (metis "1" \<open>Some maxs = vebt_maxt ?sn\<close> dele_bmo_cont_corr maxbmo member_bound valid_member_both_member_options)
hence "invar_vebt (?newlist ! maxs) n"using 0 by (simp add: "2" allvalidinlist)
hence "\<exists> y. both_member_options (?newlist ! maxs) y"
using "4" \<open>both_member_options summary maxs\<close> bb nothprolist by presburger
then obtain maxi where "Some maxi = vebt_maxt (?newlist ! maxs)"
by (metis True \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> assumption calculation dele_bmo_cont_corr high_inv hprolist leD member_bound nth_list_update_neq yassm yhelper)
hence "maxs < 2^m \<and> maxi < 2^n"
by (metis \<open>invar_vebt (?newlist ! maxs) n\<close> bb maxt_member member_bound)
hence "?newma = 2^n* maxs + maxi"
by (smt (z3) "9" False True \<open>Some maxi = vebt_maxt (?newlist ! maxs)\<close> \<open>Some maxs = vebt_maxt (vebt_delete summary (high ?xn n))\<close> option.sel)
hence "low ?newma n = maxi \<and> high ?newma n = maxs"
by (simp add: \<open>maxs < 2 ^ m \<and> maxi < 2 ^ n\<close> high_inv low_inv mult.commute)
hence "both_member_options (treeList ! (high y n)) (low y n)"
by (metis "1" "111" assumption dele_bmo_cont_corr nothprolist yassm)
hence hleqdraft:"high y n > maxs \<Longrightarrow> False"
proof-
assume "high y n > maxs"
have "both_member_options summary (high y n)"
using "1" "111" assumption dele_bmo_cont_corr yassm by blast
moreover have "both_member_options ?sn (high y n)"
using "111" assumption yassm by blast
ultimately show False
using True \<open>both_member_options (treeList ! high y n) (low y n)\<close> \<open>summin * 2 ^ n + lx < y\<close> assumption leD yassm yhelper by blast
qed
hence hleqmaxs: "high y n \<le> maxs" by presburger
then show ?thesis
using \<open>both_member_options (treeList ! high y n) (low y n)\<close> assumption calculation dual_order.strict_trans1 yassm yhelper by auto
qed
next
case False
then show ?thesis
by (smt (z3) \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> assumption dele_bmo_cont_corr high_inv hprolist member_bound nothprolist yassm yhelper)
qed
ultimately show " ?xn < y \<and> y \<le> ?newma" by simp
qed
qed
ultimately show ?thesis by simp
qed
qed
qed
qed
hence 117: "?newma < 2^deg" and 118: "?xn \<le> ?newma" using 114 by auto
have 116: " invar_vebt (Node (Some (?xn, ?newma)) deg ?newlist ?sn) deg"
using invar_vebt.intros(5)[of ?newlist n ?sn m deg ?xn ?newma]
using 3 allvalidinlist newlistlength newsummvalid "5.hyps"(3) 111 112 118 117 115 by fastforce
show ?thesis
using "116" dsimp by presburger
next
case False
hence notemp:"\<exists> z. both_member_options ?newnode z"
using not_min_Null_member by auto
let ?newma = "(if ?xn = ma then
?h * 2^(deg div 2) + the( vebt_maxt (?newlist ! ?h))
else ma)"
let ?delsimp =" (Node (Some (?xn, ?newma)) deg ?newlist summary)"
have dsimp:"vebt_delete (Node (Some (x, ma)) deg treeList summary) x = ?delsimp"
using del_x_mi_lets_in_not_minNull[of x mi ma deg ?xn ?h summary treeList ?l ?newnode ?newlist]
"12" "2" "9" False dual_order.eq_iff hlbound inrg order.not_eq_order_implies_strict xmi
by (metis \<open>summin * 2 ^ n + lx = (if x = mi then the (vebt_mint summary) * 2 ^ (deg div 2) + the (vebt_mint (treeList ! the (vebt_mint summary))) else x)\<close> \<open>x \<noteq> mi \<or> x \<noteq> ma\<close>)
have 111: "(\<forall> i < 2^m. (\<exists> x. both_member_options (?newlist ! i) x) \<longleftrightarrow> ( both_member_options summary i))"
proof
fix i
show " i < 2^m \<longrightarrow> ((\<exists> x. both_member_options (?newlist ! i) x) = ( both_member_options summary i))"
proof
assume "i < 2^m"
show "(\<exists> x. both_member_options (?newlist ! i) x) = ( both_member_options summary i)"
proof(cases "i = ?h")
case True
hence 1000:"?newlist ! i = ?newnode"
using hprolist by blast
hence 1001:"\<exists> x. vebt_member (?newlist ! i) x"
using nnvalid notemp valid_member_both_member_options by auto
hence 1002: "\<exists> x. both_member_options (?newlist ! i) x"
using "1000" notemp by presburger
have 1003: "both_member_options summary i"
using "4" True \<open>\<exists>z. both_member_options (treeList ! summin) z\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>summin < 2 ^ m\<close> \<open>invar_vebt (treeList ! summin) n\<close> high_inv member_bound by auto
then show ?thesis
using "1002" by blast
next
case False
hence 1000:"?newlist ! i = treeList ! i"
using \<open>i < 2 ^ m\<close> nothprolist by blast
then show ?thesis
using "4" \<open>i < 2 ^ m\<close> by presburger
qed
qed
qed
have 112:" (?xn = ?newma \<longrightarrow> (\<forall> t \<in> set ?newlist. \<nexists> x. both_member_options t x))"
proof
assume aampt:"?xn = ?newma"
show "(\<forall> t \<in> set ?newlist. \<nexists> y. both_member_options t y)"
proof(cases "?xn = ma")
case True
obtain maxi where " vebt_maxt (?newlist ! ?h) = Some maxi"
by (metis Collect_empty_eq False hprolist maxt_corr_help_empty nnvalid not_None_eq not_min_Null_member set_vebt'_def valid_member_both_member_options)
hence "both_member_options ?newnode maxi"
using hprolist maxbmo by auto
hence "both_member_options (treeList ! ?h) maxi"
using \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> dele_bmo_cont_corr high_inv member_bound by force
hence False
by (metis "9" \<open>both_member_options (vebt_delete (treeList ! high (summin * 2 ^ n + lx) n) (low (summin * 2 ^ n + lx) n)) maxi\<close> \<open>vebt_maxt (?newlist ! ?h) = Some maxi\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> aampt add_diff_cancel_left' dele_bmo_cont_corr option.sel high_inv low_inv member_bound)
then show ?thesis by blast
next
case False
then show ?thesis
using \<open>mi \<noteq> ma \<and> x < 2 ^ deg\<close> aampt by presburger
qed
qed
have 114: "?newma < 2^deg \<and> ?xn \<le> ?newma"
proof(cases "?xn = ma")
case True
hence "?xn = ma" by simp
obtain maxi where " vebt_maxt (?newlist ! ?h) = Some maxi"
by (metis "111" "2" "4" Collect_empty_eq True \<open>both_member_options (treeList ! high ma n) (low ma n)\<close> \<open>high (summin * 2 ^ n + lx) n < length treeList\<close> hprolist maxt_corr_help_empty nnvalid not_None_eq set_vebt'_def valid_member_both_member_options)
hence "both_member_options ?newnode maxi"
using hprolist maxbmo by auto
hence "both_member_options (treeList ! ?h) maxi"
using \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> dele_bmo_cont_corr high_inv member_bound by force
hence "maxi < 2^n"
using \<open>both_member_options?newnode maxi\<close> member_bound nnvalid valid_member_both_member_options by blast
show ?thesis
by (smt (verit, ccfv_threshold) "3" "9" div_eq_0_iff True \<open>Some lx = vebt_mint (treeList ! summin)\<close> \<open>both_member_options (treeList ! high (summin * 2 ^ n + lx) n) maxi\<close> \<open>vebt_maxt (?newlist ! high (summin * 2 ^ n + lx) n) = Some maxi\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> add.right_neutral add_left_mono div_mult2_eq div_mult_self3 option.sel high_inv hlbound le_0_eq member_bound mint_corr_help power_add power_not_zero rel_simps(28) valid_member_both_member_options)
next
case False
then show ?thesis
using "10" "5.hyps"(8) maxt_corr_help valid_member_both_member_options xnin by force
qed
have 115: "?xn \<noteq> ?newma \<longrightarrow>
(\<forall> i < 2^m.
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma))"
proof
assume xnmassm:"?xn \<noteq> ?newma"
show " (\<forall> i < 2^m.
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma))"
proof
fix i
show "i < 2^m \<longrightarrow>
(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma)"
proof
assume assumption:"i < 2^m"
show " (high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n)) \<and>
(\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma)"
proof-
have "(high ?newma n = i \<longrightarrow> both_member_options (?newlist ! i) (low ?newma n))"
proof
assume newmaassm: "high ?newma n = i"
thus " both_member_options (?newlist ! i) (low ?newma n)"
proof(cases "?xn = ma")
case True
obtain maxi where "vebt_maxt (?newlist ! ?h) = Some maxi"
by (metis Collect_empty_eq both_member_options_equiv_member hprolist maxt_corr_help_empty nnvalid not_Some_eq notemp set_vebt'_def)
hence "both_member_options (?newlist ! ?h) maxi"
using maxbmo by blast
then show ?thesis
by (smt (z3) "2" "9" True \<open>Some lx = vebt_mint (treeList ! summin)\<close> \<open>high (summin * 2 ^ n + lx) n < length treeList\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> add_left_mono dele_bmo_cont_corr eq_iff high_inv hprolist low_inv member_bound mint_corr_help valid_member_both_member_options yhelper)
next
case False
hence abcd:"?newma = ma" by simp
then show ?thesis
proof(cases "high ma n = ?h")
case True
hence "?newlist ! high ma n = ?newnode"
using hprolist by presburger
then show ?thesis
proof(cases "low ma n = ?l")
case True
hence "?newma = ?xn"
by (metis "1" False \<open>?newlist ! high ma n = vebt_delete (treeList ! high (summin * 2 ^ n + lx) n) (low (summin * 2 ^ n + lx) n)\<close> \<open>both_member_options (treeList ! high ma n) (low ma n)\<close>
\<open>vebt_member (treeList ! summin) lx\<close> \<open>vebt_member summary (high ma n)\<close> \<open>invar_vebt (treeList ! summin) n\<close> bit_split_inv dele_bmo_cont_corr high_inv member_bound nothprolist)
hence False
using False by presburger
then show ?thesis by simp
next
case False
have "both_member_options (treeList ! high ma n) (low ma n)"
by (simp add: \<open>both_member_options (treeList ! high ma n) (low ma n)\<close>)
hence "both_member_options ?newnode (low ma n)"
using False True \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> dele_bmo_cont_corr high_inv member_bound by force
hence "both_member_options (?newlist ! high ma n) (low ma n)"
using True hprolist by presburger
then show ?thesis using abcd newmaassm by simp
qed
next
case False
hence "?newlist ! high ma n = treeList ! high ma n"
using "1" \<open>vebt_member summary (high ma n)\<close> member_bound nothprolist by blast
moreover hence "both_member_options (treeList ! high ma n) (low ma n)"
using \<open>both_member_options (treeList ! high ma n) (low ma n)\<close> by blast
ultimately show ?thesis using abcd newmaassm by simp
qed
qed
qed
moreover have " (\<forall> y. (high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma)"
proof
fix y
show "(high y n = i \<and> both_member_options (?newlist ! i) (low y n) ) \<longrightarrow> ?xn < y \<and> y \<le> ?newma"
proof
assume yassm: "(high y n = i \<and> both_member_options (?newlist ! i) (low y n) )"
hence "?xn < y"
proof(cases "i = ?h")
case True
hence "both_member_options (treeList ! i) (low y n)"
using \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> dele_bmo_cont_corr high_inv hprolist member_bound yassm by force
moreover have "vebt_mint (treeList ! i) = Some (low ?xn n)"
using True \<open>Some lx = vebt_mint (treeList ! summin)\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> high_inv low_inv member_bound by presburger
moreover hence "low y n \<ge> low ?xn n"
using True \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> calculation(1) high_inv member_bound mint_corr_help valid_member_both_member_options by auto
moreover have "low y n \<noteq> low ?xn n"
using True \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> dele_bmo_cont_corr high_inv hprolist member_bound yassm by auto
ultimately have "low y n > low ?xn n" by simp
show ?thesis
by (metis True \<open>low (summin * 2 ^ n + lx) n \<le> low y n\<close> \<open>low y n \<noteq> low (summin * 2 ^ n + lx) n\<close> bit_concat_def bit_split_inv leD linorder_neqE_nat nat_add_left_cancel_less yassm)
next
case False
have "Some (high ?xn n) = vebt_mint summary"
using \<open>Some summin = vebt_mint summary\<close> \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> high_inv member_bound by presburger
moreover hence "high y n \<ge> high ?xn n"
by (metis "1" "111" assumption mint_corr_help valid_member_both_member_options yassm)
ultimately show ?thesis
by (metis False div_le_mono high_def leI le_antisym yassm)
qed
moreover have "y \<le> ?newma"
by (smt (z3) \<open>vebt_member (treeList ! summin) lx\<close> \<open>invar_vebt (treeList ! summin) n\<close> assumption calculation dele_bmo_cont_corr high_inv hprolist leD member_bound nothprolist yassm yhelper)
ultimately show " ?xn < y \<and> y \<le> ?newma" by simp
qed
qed
ultimately show ?thesis by simp
qed
qed
qed
qed
hence 117: "?newma < 2^deg" and 118: "?xn \<le> ?newma" using 114 by auto
have 116: " invar_vebt (Node (Some (?xn, ?newma)) deg ?newlist summary) deg"
using invar_vebt.intros(5)[of ?newlist n summary m deg ?xn ?newma] allvalidinlist
1 newlistlength 8 3 111 112 117 118 115 by fastforce
hence "invar_vebt (?delsimp) deg" by simp
moreover obtain delsimp where 118:"delsimp = ?delsimp" by simp
ultimately have 119:"invar_vebt delsimp deg" by simp
have "vebt_delete (Node (Some (x, ma)) deg treeList summary) x = delsimp" using dsimp 118 by simp
hence "delsimp = vebt_delete (Node (Some (x, ma)) deg treeList summary) x" by simp
then show ?thesis using 119
using xmi by auto
qed
qed
qed
qed
qed
corollary dele_member_cont_corr:"invar_vebt t n \<Longrightarrow> (vebt_member (vebt_delete t x) y \<longleftrightarrow> x \<noteq> y \<and> vebt_member t y)"
by (meson both_member_options_equiv_member dele_bmo_cont_corr delete_pres_valid)
subsection \<open>Correctness with Respect to Set Interpretation\<close>
theorem delete_correct': assumes "invar_vebt t n"
shows "set_vebt' (vebt_delete t x) = set_vebt' t - {x}"
using assms by(auto simp add: set_vebt'_def dele_member_cont_corr)
corollary delete_correct: assumes "invar_vebt t n"
shows "set_vebt' (vebt_delete t x) = set_vebt t - {x}"
using assms delete_correct' set_vebt_set_vebt'_valid by auto
end
end
|
The inverse of a real number is real if and only if the number is real.
|
module SourceLoc
import Data.Vect
import Data.Fin
import Language.Reflection
import Language.Reflection.Utils
%default total
%language DSLNotation
||| A "function" that returns where it is called in the source
getLoc : {default tactics { sourceLocation } x : SourceLocation} -> SourceLocation
getLoc {x} = x
||| A test of getLoc
fromRHS : SourceLocation
fromRHS = getLoc
||| Testing getting source locations from RHS proof scripts
fromProofScript : SourceLocation
fromProofScript = proof sourceLocation
||| Testing getting source locations from deferred proofs.
fromMetavar : SourceLocation
fromMetavar = ?meta
--- Testing that getting source locations in ASTs constructed with DSL notation
data Ty = U | Arr Ty Ty
interp : Ty -> Type
interp U = ()
interp (Arr x y) = interp x -> Either SourceLocation (interp y)
using (ctxt : Vect n Ty)
data Tm : Vect n Ty -> Ty -> Type where
MkU : Tm ctxt U
Var : (i : Fin n) -> Tm ctxt (index i ctxt)
Lam : Tm (t::ctxt) t' -> Tm ctxt (Arr t t')
App : Tm ctxt (Arr t t') -> Tm ctxt t -> Tm ctxt t'
||| A term that makes the program halt and printLn where it halted
Die : {default tactics { sourceLocation } loc : SourceLocation} -> Tm ctxt t
data Env : Vect n Ty -> Type where
Nil : Env []
(::) : interp t -> Env ctxt -> Env (t::ctxt)
index : (i : Fin n) -> Env ctxt -> interp (index i ctxt)
index FZ (x::env) = x
index (FS i) (x::env) = index i env
run : Tm ctxt t -> Env ctxt -> Either SourceLocation (interp t)
run MkU _ = pure ()
run (Var i) env = pure $ index i env
run (Lam bdy) env = pure $ \x => run bdy (x::env)
run (App f x) env = !(run f env) !(run x env)
run (Die {loc}) _ = Left loc
lam_ : _ -> Tm (t::ctxt) t' -> Tm ctxt (Arr t t')
lam_ _ = Lam
exec : Tm [] t -> IO ()
exec tm = case run tm [] of
Left loc => putStrLn $ "Error at " ++ show loc
Right _ => putStrLn $ "Success!"
dsl lang
variable = Var
index_first = FZ
index_next = FS
lambda = lam_
testTerm1 : Tm [] (Arr U U)
testTerm1 = lang (\x=>Die)
testTerm2 : Tm [] U
testTerm2 = App testTerm1 MkU
testTerm3 : Tm [] (Arr U U)
testTerm3 = lang (\x => MkU)
testTerm4 : Tm [] U
testTerm4 = App testTerm3 MkU
namespace Main
main : IO ()
main = do putStrLn "Testing using definition"
printLn fromRHS
putStrLn "Testing using inline tactics"
printLn fromProofScript
putStrLn "Testing using metavariable with later definition"
printLn fromMetavar
putStrLn "-----------------------"
sequence_ $ with List [ exec testTerm1
, exec testTerm2
, exec testTerm3
, exec testTerm4
]
---------- Proofs ----------
SourceLoc.meta = proof
sourceLocation
|
%RangeBearingSensor Range and bearing sensor class
%
% A concrete subclass of the Sensor class that implements a range and bearing
% angle sensor that provides robot-centric measurements of landmark points in
% the world. To enable this it holds a references to a map of the world (LandmarkMap object)
% and a robot (Vehicle subclass object) that moves in SE(2).
%
% The sensor observes landmarks within its angular field of view between
% the minimum and maximum range.
%
% Methods::
%
% reading range/bearing observation of random landmark
% h range/bearing observation of specific landmark
% Hx Jacobian matrix with respect to vehicle pose dh/dx
% Hp Jacobian matrix with respect to landmark position dh/dp
% Hw Jacobian matrix with respect to noise dh/dw
%-
% g feature position given vehicle pose and observation
% Gx Jacobian matrix with respect to vehicle pose dg/dx
% Gz Jacobian matrix with respect to observation dg/dz
%
% Properties (read/write)::
% W measurement covariance matrix (2x2)
% interval valid measurements returned every interval'th call to reading()
% landmarklog time history of observed landmarks
%
% Reference::
%
% Robotics, Vision & Control, Chap 6,
% Peter Corke,
% Springer 2011
%
% See also Sensor, Vehicle, LandmarkMap, EKF.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
classdef RangeBearingSensor < Sensor
properties
W % measurment covariance
r_range % range limits
theta_range % angle limits
randstream % random stream just for Sensors
landmarklog % time history of observed landmarks
end
properties (SetAccess = private)
count % number of reading()s
end
methods
function s = RangeBearingSensor(robot, map, varargin)
%RangeBearingSensor.RangeBearingSensor Range and bearing sensor constructor
%
% S = RangeBearingSensor(VEHICLE, MAP, OPTIONS) is an object
% representing a range and bearing angle sensor mounted on the Vehicle
% subclass object VEHICLE and observing an environment of known landmarks
% represented by the LandmarkMap object MAP. The sensor covariance is W
% (2x2) representing range and bearing covariance.
%
% The sensor has specified angular field of view and minimum and maximum
% range.
%
% Options::
% 'covar',W covariance matrix (2x2)
% 'range',xmax maximum range of sensor
% 'range',[xmin xmax] minimum and maximum range of sensor
% 'angle',TH angular field of view, from -TH to +TH
% 'angle',[THMIN THMAX] detection for angles betwen THMIN
% and THMAX
% 'skip',K return a valid reading on every K'th call
% 'fail',[TMIN TMAX] sensor simulates failure between
% timesteps TMIN and TMAX
% 'animate' animate sensor readings
%
% See also options for Sensor constructor.
%
% See also RangeBearingSensor.reading, Sensor.Sensor, Vehicle, LandmarkMap, EKF.
% call the superclass constructor
s = s@Sensor(robot, map, varargin{:});
s.randstream = RandStream.create('mt19937ar');
opt.range = [];
opt.angle = [];
opt.covar = zeros(2,2);
[opt,args] = tb_optparse(opt, varargin);
s.W = opt.covar;
if ~isempty(opt.range)
if length(opt.range) == 1
s.r_range = [0 opt.range];
elseif length(opt.range) == 2
s.r_range = opt.range;
end
end
if ~isempty(opt.angle)
if length(opt.angle) == 1
s.theta_range = [-opt.angle opt.angle];
elseif length(opt.angle) == 2
s.theta_range = opt.angle;
end
end
s.count = 0;
s.verbose = opt.verbose;
end
function init(s)
s.landmarklog = [];
end
function k = selectFeature(s)
k = s.randstream.randi(s.map.nlandmarks);
end
function [z,jf] = reading(s)
%RangeBearingSensor.reading Choose landmark and return observation
%
% [Z,K] = S.reading() is an observation of a random visible landmark where
% Z=[R,THETA] is the range and bearing with additive Gaussian noise of
% covariance W (property W). K is the index of the map feature that was
% observed.
%
% The landmark is chosen randomly from the set of all visible landmarks,
% those within the angular field of view and range limits. If no valid
% measurement, ie. no features within range, interval subsampling enabled
% or simulated failure the return is Z=[] and K=0.
%
% Notes::
% - Noise with covariance W (property W) is added to each row of Z.
% - If 'animate' option set then show a line from the vehicle to the
% landmark
% - If 'animate' option set and the angular and distance limits are set
% then display that region as a shaded polygon.
% - Implements sensor failure and subsampling if specified to constructor.
%
% See also RangeBearingSensor.h.
% TODO probably should return K=0 to indicated invalid
% model a sensor that emits readings every interval samples
s.count = s.count + 1;
% check conditions for NOT returning a value
z = [];
jf = 0;
% sample interval
if mod(s.count, s.interval) ~= 0
return;
end
% simulated failure
if ~isempty(s.fail) && (s.count >= s.fail(1)) && (s.count <= s.fail(2))
return;
end
% create a polygon to indicate the active sensing area based on range+angle limits
if s.animate && ~isempty(s.theta_range) && ~isempty(s.r_range)
h = findobj(gca, 'tag', 'sensor-area');
if isempty(h)
th=linspace(s.theta_range(1), s.theta_range(2), 20);
x = s.r_range(2) * cos(th);
y = s.r_range(2) * sin(th);
if s.r_range(1) > 0
th = flip(th);
x = [x s.r_range(1) * cos(th)];
y = [y s.r_range(1) * sin(th)];
else
x = [x 0];
y = [y 0];
end
% no sensor zone, create one
plot_poly([x; y], 'fillcolor', 'r', 'alpha', 0.1, 'edgecolor', 'none', 'animate', 'tag', 'sensor-area');
else
%hg = get(h, 'Parent');
plot_poly(h, s.robot.x);
end
end
if ~isempty(s.r_range) || ~isempty(s.theta_range)
% if range and bearing angle limits are in place look for
% any landmarks that match criteria
% get range/bearing to all landmarks, one per row
z = s.h(s.robot.x');
jf = 1:numcols(s.map.map);
if ~isempty(s.r_range)
% find all within range
k = find( z(:,1) >= s.r_range(1) & z(:,1) <= s.r_range(2) );
z = z(k,:);
jf = jf(k);
end
if ~isempty(s.theta_range)
% find all within angular range as well
k = find( z(:,2) >= s.theta_range(1) & z(:,2) <= s.theta_range(2) );
z = z(k,:);
jf = jf(k);
end
% deal with cases for 0 or > 1 features found
if isempty(z)
% no landmarks found
jf = 0;
elseif length(k) >= 1
% more than 1 in range, pick a random one
i = s.randstream.randi(length(k));
z = z(i,:);
jf = jf(i);
end
else
% randomly choose the feature
jf = s.selectFeature();
% compute the range and bearing from robot to feature
z = s.h(s.robot.x', jf);
end
if s.verbose
if isempty(z)
fprintf('Sensor:: no features\n');
else
fprintf('Sensor:: feature %d: %.1f %.1f\n', jf, z);
end
end
if s.animate
s.plot(jf);
end
z = z';
% add the reading to the landmark log
s.landmarklog = [s.landmarklog jf];
end
function z = h(s, xv, jf)
%RangeBearingSensor.h Landmark range and bearing
%
% Z = S.h(X, K) is a sensor observation (1x2), range and bearing, from vehicle at
% pose X (1x3) to the K'th landmark.
%
% Z = S.h(X, P) as above but compute range and bearing to a landmark at coordinate P.
%
% Z = s.h(X) as above but computes range and bearing to all
% map features. Z has one row per landmark.
%
% Notes::
% - Noise with covariance W (propertyW) is added to each row of Z.
% - Supports vectorized operation where XV (Nx3) and Z (Nx2).
% - The landmark is assumed visible, field of view and range liits are not
% applied.
%
% See also RangeBearingSensor.reading, RangeBearingSensor.Hx, RangeBearingSensor.Hw, RangeBearingSensor.Hp.
% get the landmarks, one per row
if nargin < 3
% s.h(XV)
xlm = s.map.map';
elseif length(jf) == 1
% s.h(XV, JF)
xlm = s.map.map(:,jf)';
else
% s.h(XV, XF)
xlm = jf(:)';
end
% Straightforward code:
%
% dx = xf(1) - xv(1); dy = xf(2) - xv(2);
%
% z = zeros(2,1);
% z(1) = sqrt(dx^2 + dy^2); % range measurement
% z(2) = atan2(dy, dx) - xv(3); % bearing measurement
%
% Vectorized code:
% compute range and bearing
dx = xlm(:,1) - xv(:,1); dy = xlm(:,2) - xv(:,2);
z = [sqrt(dx.^2 + dy.^2) angdiff(atan2(dy, dx), xv(:,3)) ]; % range & bearing measurement
% add noise with covariance W
z = z + s.randstream.randn(size(z)) * sqrtm(s.W) ;
end
function J = Hx(s, xv, jf)
%RangeBearingSensor.Hx Jacobian dh/dx
%
% J = S.Hx(X, K) returns the Jacobian dh/dx (2x3) at the vehicle
% state X (3x1) for map landmark K.
%
% J = S.Hx(X, P) as above but for a landmark at coordinate P.
%
% See also RangeBearingSensor.h.
if length(jf) == 1
xf = s.map.map(:,jf);
else
xf = jf;
end
if isempty(xv)
xv = s.robot.x;
end
Delta = xf - xv(1:2)';
r = norm(Delta);
J = [
-Delta(1)/r, -Delta(2)/r, 0
Delta(2)/(r^2), -Delta(1)/(r^2), -1
];
end
function J = Hp(s, xv, jf)
%RangeBearingSensor.Hp Jacobian dh/dp
%
% J = S.Hp(X, K) is the Jacobian dh/dp (2x2) at the vehicle
% state X (3x1) for map landmark K.
%
% J = S.Hp(X, P) as above but for a landmark at coordinate P (1x2).
%
% See also RangeBearingSensor.h.
if length(jf) == 1
xf = s.map.map(:,jf);
else
xf = jf;
end
Delta = xf - xv(1:2)';
r = norm(Delta);
J = [
Delta(1)/r, Delta(2)/r
-Delta(2)/(r^2), Delta(1)/(r^2)
];
end
function J = Hw(s, xv, jf)
%RangeBearingSensor.Hx Jacobian dh/dw
%
% J = S.Hw(X, K) is the Jacobian dh/dw (2x2) at the vehicle
% state X (3x1) for map landmark K.
%
% See also RangeBearingSensor.h.
J = eye(2,2);
end
function xf = g(s, xv, z)
%RangeBearingSensor.g Compute landmark location
%
% P = S.g(X, Z) is the world coordinate (2x1) of a feature given
% the observation Z (1x2) from a vehicle state with X (3x1).
%
% See also RangeBearingSensor.Gx, RangeBearingSensor.Gz.
range = z(1);
bearing = z(2) + xv(3); % bearing angle in vehicle frame
xf = [xv(1)+range*cos(bearing); xv(2)+range*sin(bearing)];
end
function J = Gx(s, xv, z)
%RangeBearingSensor.Gxv Jacobian dg/dx
%
% J = S.Gx(X, Z) is the Jacobian dg/dx (2x3) at the vehicle state X (3x1) for
% sensor observation Z (2x1).
%
% See also RangeBearingSensor.g.
theta = xv(3);
r = z(1);
bearing = z(2);
J = [
1, 0, -r*sin(theta + bearing);
0, 1, r*cos(theta + bearing)
];
end
function J = Gz(s, xv, z)
%RangeBearingSensor.Gz Jacobian dg/dz
%
% J = S.Gz(X, Z) is the Jacobian dg/dz (2x2) at the vehicle state X (3x1) for
% sensor observation Z (2x1).
%
% See also RangeBearingSensor.g.
theta = xv(3);
r = z(1);
bearing = z(2);
J = [
cos(theta + bearing), -r*sin(theta + bearing);
sin(theta + bearing), r*cos(theta + bearing)
];
end
function str = char(s)
str = char@Sensor(s);
str = char(str, ['W = ', mat2str(s.W, 3)]);
str = char(str, sprintf('interval %d samples', s.interval) );
if ~isempty(s.r_range)
str = char(str, sprintf('range: %g to %g', s.r_range) );
end
if ~isempty(s.theta_range)
str = char(str, sprintf('angle: %g to %g', s.theta_range) );
end
end
end % method
end % classdef
|
\section{Modules}
\subsection{Definition and Examples}
\begin{definition}
A module over a ring $R$ (an $R$-module) is a triple $(M,+,\cdot)$ where $(M,+,0)$ for some $0\in M$ is an abelian group and $\cdot:R\times M\to M$ (called scalar multiplication) satisfies, for any $r,r_1,r_2\in R,m,m_1,m_2\in M$:\\
1. $(r_1+r_2)\cdot m=r_1\cdot m+r_2\cdot m$.\\
2. $r\cdot (m_1+m_2)=r\cdot m_1+r\cdot m_2$.\\
3. $r_1\cdot(r_2\cdot m)=(r_1r_2)\cdot m$.\\
4. $1\cdot m=m$.
\end{definition}
The function $\cdot$ is called the scalar multiplication and is omitted from writing sometimes.
\begin{remark}
To show something is a module, we also need to check closure (that is $+,\cdot$ are well-defined).
\end{remark}
\begin{example}
1. If $R$ is a field, then an $R$-module $M$ is a vector space over $R$.\\
2. A $\mathbb Z$-module is precisely the same as an abelian group as the scalar multiplication can be uniquely defined by $n\cdot a=a+\cdots +a$ for $n$ many copies of $a$.\\
3. Consider the ring $R=\mathbb F[X]$ for a field $\mathbb F$ and $V$ a vector space over $\mathbb F$.
Consider $\alpha:V\to V$ an endomorphism.
We can make $V$ an $R$-module over the scalar multiplication $\mathbb F[X]\times V\to V$ by $(f,v)\mapsto f(\alpha)(v)$.
Note that different choice of $\alpha$ makes $V$ a different module.
We sometimes write this as $V_\alpha$.
\end{example}
There are some general construction methods to produce a module.
\begin{example}
1. For any ring $R$, $R^n$ is an $R$-module by $r\cdot(r_1,\ldots,r_n)=(rr_1,\ldots,rr_n)$ for $r,r_i\in R$.
In particular, when $n=1$, $R$ itself is an $R$-module.\\
2. If $I$ is an ideal, then $I$ is an $R$-module by $r\cdot i=ri$ for $r\in R,i\in I$.\\
3. If $I$ is an ideal, then $R/I$ is an $R$-module by $r\cdot(s+I)=rs+I$ for $r,s\in R$.\\
4. If $\phi:R\to S$ is a ring homomorphism, then any $S$-module $M$ is also an $M$-module by $r\cdot m=\phi(r)\cdot m$ for $r\in R,m\in M$.
In particular, if $R\le S$, then any $S$-module can be viewed as an $R$-module.
\end{example}
\begin{definition}
Let $M$ be an $R$-module, a subset $N\subset M$ is called a $R$-submodule of $M$, written as $N\le M$, if $(N,+)\le (M,+)$ and for any $r\in R,n\in N$, we have $r\cdot n\in N$.
\end{definition}
\begin{example}
1. Any $R$-submodule of $R$ is an ideal.\\
2. When $R$ is a field, then an $R$-module is a vector space, then a submodule is a vector subspace.
\end{example}
\begin{definition}
If $N$ is a $R$-submodule of $M$, we can form the quotient $M/N$ by taking the quotient group under addition.
We can make it as an $R$-module by specifying the scalar multiplication $r\cdot (m+N)=r\cdot m+N$.
\end{definition}
We can check easily that the scalar multiplication defined in this way is well-defined and makes $M/N$ an $R$-module.
\subsection{Homomorphisms}
\begin{definition}
Let $M,N$ be $R$-modules, then a function $f:M\to N$ is a homomorphism of $R$-modules (or $R$-module map) if $f$ is a homomorphism of groups under addition and $\forall r\in R,m\in M,f(r\cdot m)=r\cdot f(m)$.\\
A bijective homomorphism is called an isomorphism, and two $R$-modules $M,N$ are called isomorphic (written as $M\cong N$) if there is an isomorphism between them.
\end{definition}
\begin{example}
When $R$ is a field, a homomorphism of $R$-modules is a linear map.
\end{example}
\begin{theorem}[(First) Isomorphism Theorem for Modules]
Suppose $M,N$ are $R$-modules and $f:M\to N$ is a homomorphism of $R$-modules, then $\ker f\le M,f(M)\le N$ and $M/\ker f\cong f(M)$.
\end{theorem}
\begin{proof}
Similar to before.
\end{proof}
\begin{theorem}[Second Isomorphism Theorem]
Let $A,B$ be $R$-submodules of an $R$=module $M$, then $A+B=\{a+b:a\in A,b\in B\}\le M$ and $A\cap B\le M$.
Moreover, $A/(A\cap B)\cong (A+B)/B$.
\end{theorem}
\begin{proof}
Use the First Isomorphism Theorem.
\end{proof}
To motivate the Third Isomorphism Theorem, we note that for $R$-modules $N\le M$, we have the correspondance between the submodules of $M/N$ and the submodules of $M$ containing $N$.
\begin{theorem}[Third Isomorphism Theorem]
Suppose $N\le L\le M$ are $R$-modules, then $M/L\cong (M/N)/(L/N)$.
\end{theorem}
\begin{proof}
Same.
\end{proof}
In partricular, these are all true for vector spaces by taking the ring to be a field.
One can compare these results to familiar results in linear algebra (e.g. the First Isomorphism Theorem implies the Rank-Nullity Theorem).
\subsection{Finitely Generated Modules}
\begin{definition}
Let $M$ be an $R$-module, and $m\in M$, then the submodule $Rm$ generated by $m$ is the smallest $R$-submodule of $M$ containing $m$, i.e. $Rm=\{r\cdot m:r\in R\}$.
\end{definition}
\begin{definition}
Let $M$ be an $R$-module.
$M$ is called cyclic if $M=Rm$ for some $m\in M$.
$M$ is finitely generated if $\exists m_1,\ldots,m_n\in M$ such that $Rm_1+\cdots Rm_n=M$.
\end{definition}
\begin{lemma}
An $R$-module $M$ is cyclic iff $M$ is isomorphic as an $R$-module to $R/I$ for some $I\unlhd R$.
\end{lemma}
\begin{proof}
If $M$ is cyclic, write $M=Rm$, then there is a surjective $R$-module homomorphism $R\to M$ by $r\mapsto r\cdot m$ so the claim follows by the First Isomorphism Theorem.\\
Conversely If $M\cong R/I$, then $M\cong R/I=R(1+I)$.
\end{proof}
\begin{lemma}
An $R$-module $M$ is finitely generated iff there exists a surjective $R$-module homomorphism from $f:R^n\to M$ for some $n$.
\end{lemma}
\begin{proof}
If $M$ is finitely generated, then $M=Rm_1+\cdots +Rm_n$ where $m_i\in M$, so we can take $f(r_1,\ldots,r_n)=r_1m_1+\cdots +r_nm_n$.\\
Conversely, if such a map $f$ exists, then $M=Rf(e_1)+\cdots+Rf(e_n)$, then $e_i$ has $1$ in $i^{th}$ entry and $0$ in $j^{th}$ entry for any $j\neq i$.
\end{proof}
\begin{corollary}
The quotient of a finitely generated $R$-module is a finitely generated $R$-module.
\end{corollary}
\begin{proof}
Obvious from the preceding lemma.
\end{proof}
\begin{remark}
A submodule of a finitely generated $R$-module needs not be finitely generated.
For example, we can take a non-Noetherian ring $R$ itself as an $R$-module and consider a non-finitely generated ideal of it.
\end{remark}
\begin{lemma}
Let $R$ be an integral domain, then every $R$-submodule of a cyclic $R$-module is cyclic iff $R$ is a PID.
\end{lemma}
\begin{proof}
$R$ itself is a cyclic $R$-module, so if all $R$-submodules of it are cyclic, then all of its ideals are generated by one element, so $R$ is a PID.\\
Conversely, if $R$ is a PID and $M$ is a cyclic $R$-module, so $M\cong R/I$ for $I\unlhd R$, so the $R$-submodules of $M$ are in the form $J/I$ for $I\subset J\unlhd R$.
Now since $R$ is a PID, $J$ is principal, so $J/I$ is cyclic.
\end{proof}
\begin{theorem}
Let $R$ be a PID, and $M$ an $R$-module.
Suppose $M$ is generated by $n$ elements, then any $R$-submodule $N$ of $M$ can also be generated by at most $n$ elements.
\end{theorem}
\begin{proof}
$n=1$ is the preceding lemma.
For general $n$, we proceed by induction.
Suppose $M=Rx_1+\cdots Rx_n$.
Let $M_i=Rx_1+\cdots Rx_i$ and $0=M_0\le M_1\le\cdots\le M_n=M$.
So we have
$$0=M_0\cap N\le M_1\cap N\le\cdots\le M_n\cap N=N$$
Then the $R$-module map $M_i\cap N\to M_i/M_{i-1}$ by $m\mapsto m+M_{i-1}$ has kernel $M_{i-1}\cap N$.
Hence
$$(M_i\cap N)/(M_{i-1}\cap N)\cong M'\le M_i/M_{i-1}$$
But $M_i/M_{i-1}$ is cyclic by hypothesis, so by preceding lemma, $(M_i\cap N)/(M_{i-1}\cap N)$ is also cyclic and is generated by $y_i+M_{i-1}\cap N$ where $y_i\in M_i\cap N$.
Therefore $M_i=M_{i-1}\cap N+Ry_i$.
It follows that $M_i\cap N=Ry_1+\cdots +Ry_i$.
In particular, $N=M_n\cap N=Ry_1+\cdots+Ry_n$, so $N$ is generated by $n$ elements.
\end{proof}
\begin{example}
Take $R=\mathbb Z$, then we know that any subgroup of $\mathbb Z^n$ can be generated by $n$ elements.
\end{example}
|
//popGen stuff for Next Gen Sequencing Data
#include "pgSummaryStats.h"
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "vector.h"
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_matrix.h>
//Sampling Probability stuff
//prob_i returns the probability under SNM of a snp freq i
double prob_i(int i, int n){
double tmp;
tmp = 1.0 / (double) i;
return(tmp/ a1f(n));
}
double prob_km(int k, int m, int n){
double sum = 0.0;
int i;
double tmpFreq;
for(i=1;i<n;i++){
tmpFreq = (double) i / (double) n;
sum += gsl_ran_binomial_pdf(k,tmpFreq,m) * prob_i(i,n);
}
return(sum);
}
//achaz system stuff
double achazSFS(gsl_matrix *sfsCount, gsl_matrix *weightMat){
int i, j;
double theta = 0.0;
double weightSum, tmpTheta;
//rows = sampleSizes
for(i = 2; i < sfsCount->size1; i++){
weightSum = 0.0;
tmpTheta = 0.0;
for(j = 1; j < i; j++){
//size i freq j
tmpTheta += gsl_matrix_get(sfsCount, i, j) * j * gsl_matrix_get(weightMat,i,j);
weightSum += gsl_matrix_get(weightMat,i,j);
}
if(weightSum > 0){ theta += tmpTheta / weightSum; }
}
return(theta);
}
double achazSFSCorrected(gsl_matrix *sfsCount, gsl_matrix *weightMat,int nPool){
int i, j;
double theta = 0.0;
double weightSum, tmpTheta;
//rows = sampleSizes
for(i = 2; i < sfsCount->size1; i++){
weightSum = 0.0;
tmpTheta = 0.0;
for(j = 1; j < i; j++){
//size i freq j
tmpTheta += gsl_matrix_get(sfsCount, i, j) * gsl_matrix_get(weightMat,i,j) * (1.0/prob_km(j,i,nPool));
weightSum += gsl_matrix_get(weightMat,i,j);
}
if(weightSum > 0){
theta += tmpTheta / weightSum / a1f(nPool);
}
}
return(theta);
}
// fillPiWeights -- returns the weight matrix for theta_pi
void fillPiWeights(gsl_matrix *weightMat, int minFreq){
int i, j;
gsl_matrix_set_zero(weightMat);
for(i=minFreq+1; i < weightMat->size1; i++){
for(j=minFreq;j<i;j++){
gsl_matrix_set(weightMat,i,j,i-j);
}
}
}
// fillHWeights -- returns the weight matrix for theta_H
void fillHWeights(gsl_matrix *weightMat, int minFreq){
int i, j;
gsl_matrix_set_zero(weightMat);
for(i=minFreq+1; i < weightMat->size1; i++){
for(j=minFreq;j<i;j++){
gsl_matrix_set(weightMat,i,j,j);
}
}
}
// fillWWeights -- returns the weight matrix for theta_w
void fillWWeights(gsl_matrix *weightMat, int minFreq){
int i, j;
gsl_matrix_set_zero(weightMat);
for(i=minFreq+1; i < weightMat->size1; i++){
for(j=minFreq;j<i;j++){
gsl_matrix_set(weightMat,i,j,1/(double)j);
}
}
}
|
import sys
import simtk.openmm as openmm
import simtk.openmm.app as app
import simtk.unit as unit
import mdtraj as md
import numpy as np
import copy
import enum
from io import StringIO
import lxml.etree as etree
from openmmtools.constants import ONE_4PI_EPS0
InteractionGroup = enum.Enum("InteractionGroup", ['unique_old', 'unique_new', 'core', 'environment'])
#######LOGGING#############################
import logging
logging.basicConfig(level = logging.NOTSET)
_logger = logging.getLogger("relative")
_logger.setLevel(logging.INFO)
###########################################
class HybridTopologyFactory(object):
"""
This class generates a hybrid topology based on a perses topology proposal. This class treats atoms
in the resulting hybrid system as being from one of four classes:
unique_old_atom : these atoms are not mapped and only present in the old system. Their interactions will be on for
lambda=0, off for lambda=1
unique_new_atom : these atoms are not mapped and only present in the new system. Their interactions will be off
for lambda=0, on for lambda=1
core_atom : these atoms are mapped, and are part of a residue that is changing. Their interactions will be those
corresponding to the old system at lambda=0, and those corresponding to the new system at lambda=1
environment_atom : these atoms are mapped, and are not part of a changing residue. Their interactions are always
on and are alchemically unmodified.
Properties
----------
hybrid_system : openmm.System
The hybrid system for simulation
new_to_hybrid_atom_map : dict of int : int
The mapping of new system atoms to hybrid atoms
old_to_hybrid_atom_map : dict of int : int
The mapping of old system atoms to hybrid atoms
hybrid_positions : [n, 3] np.ndarray
The positions of the hybrid system
hybrid_topology : mdtraj.Topology
The topology of the hybrid system
omm_hybrid_topology : openmm.app.Topology
The OpenMM topology object corresponding to the hybrid system
.. warning :: This API is experimental and subject to change.
"""
_known_forces = {'HarmonicBondForce', 'HarmonicAngleForce', 'PeriodicTorsionForce', 'NonbondedForce', 'MonteCarloBarostat'}
def __init__(self,
topology_proposal,
current_positions,
new_positions,
use_dispersion_correction=False,
functions=None,
softcore_alpha=None,
bond_softening_constant=1.0,
angle_softening_constant=1.0,
soften_only_new=False,
neglected_new_angle_terms = [],
neglected_old_angle_terms = [],
softcore_LJ_v2 = True,
softcore_electrostatics = True,
softcore_LJ_v2_alpha = 0.85,
softcore_electrostatics_alpha = 0.3,
softcore_sigma_Q = 1.0,
interpolate_old_and_new_14s = False):
"""
Initialize the Hybrid topology factory.
Parameters
----------
topology_proposal : perses.rjmc.topology_proposal.TopologyProposal object
TopologyProposal object rendered by the ProposalEngine
current_positions : [n,3] np.ndarray of float
The positions of the "old system"
new_positions : [m,3] np.ndarray of float
The positions of the "new system"
use_dispersion_correction : bool, default False
Whether to use the long range correction in the custom sterics force. This is very expensive for NCMC.
functions : dict, default None
Alchemical functions that determine how each force is scaled with lambda. The keys must be strings with
names beginning with lambda_ and ending with each of bonds, angles, torsions, sterics, electrostatics.
If functions is none, then the integrator will need to set each of these and parameter derivatives will be unavailable.
If functions is not None, all lambdas must be specified.
softcore_alpha: float, default None
"alpha" parameter of softcore sterics. If None is provided, value will be set to 0.5
bond_softening_constant : float
For bonds between unique atoms and unique-core atoms, soften the force constant at the "dummy" endpoint by this factor.
If 1.0, do not soften
angle_softening_constant : float
For bonds between unique atoms and unique-core atoms, soften the force constant at the "dummy" endpoint by this factor.
If 1.0, do not soften
neglected_new_angle_terms : list
list of indices from the HarmonicAngleForce of the new_system for which the geometry engine neglected.
Hence, these angles must be alchemically grown in for the unique new atoms (forward lambda protocol)
neglected_old_angle_terms : list
list of indices from the HarmonicAngleForce of the old_system for which the geometry engine neglected.
Hence, these angles must be alchemically deleted for the unique old atoms (reverse lambda protocol)
softcore_LJ_v2 : bool, default True
implement a new softcore LJ: citation below.
Gapsys, Vytautas, Daniel Seeliger, and Bert L. de Groot. "New soft-core potential function for molecular dynamics based alchemical free energy calculations." Journal of chemical theory and computation 8.7 (2012): 2373-2382.
softcore_electrostatics : bool, default True
softcore electrostatics: citation below.
Gapsys, Vytautas, Daniel Seeliger, and Bert L. de Groot. "New soft-core potential function for molecular dynamics based alchemical free energy calculations." Journal of chemical theory and computation 8.7 (2012): 2373-2382.
softcore_LJ_v2_alpha : float, default 0.85
softcore alpha parameter for LJ v2
softcore_electrostatics_alpha : float, default 0.3
softcore alpha parameter for softcore electrostatics.
softcore_sigma_Q : float, default 1.0
softcore sigma parameter for softcore electrostatics.
interpolate_old_and_new_14s : bool, default False
whether to turn on new 1,4 interactions and turn off old 1,4 interactions; if False, they are present in the nonbonded force
.. todo :: Document how positions for hybrid system are constructed
"""
_logger.info("Beginning nonbonded method, total particle, barostat, and exceptions retrieval...")
self._topology_proposal = topology_proposal
self._old_system = copy.deepcopy(topology_proposal.old_system)
self._new_system = copy.deepcopy(topology_proposal.new_system)
self._old_to_hybrid_map = {}
self._new_to_hybrid_map = {}
self._hybrid_system_forces = dict()
self._old_positions = current_positions
self._new_positions = new_positions
self._soften_only_new = soften_only_new
self._interpolate_14s = interpolate_old_and_new_14s
#new attributes from the modified geometry engine
if neglected_old_angle_terms:
self.neglected_old_angle_terms = neglected_old_angle_terms
else:
self.neglected_old_angle_terms = []
if neglected_new_angle_terms:
self.neglected_new_angle_terms = neglected_new_angle_terms
else:
self.neglected_new_angle_terms = []
if bond_softening_constant != 1.0:
self._bond_softening_constant = bond_softening_constant
self._soften_bonds = True
else:
self._soften_bonds = False
if angle_softening_constant != 1.0:
self._angle_softening_constant = angle_softening_constant
self._soften_angles = True
else:
self._soften_angles = False
self._use_dispersion_correction = use_dispersion_correction
self._softcore_LJ_v2 = softcore_LJ_v2
if self._softcore_LJ_v2:
self._softcore_LJ_v2_alpha = softcore_LJ_v2_alpha
assert self._softcore_LJ_v2_alpha >= 0.0 and self._softcore_LJ_v2_alpha <= 1.0, f"softcore_LJ_v2_alpha: ({self._softcore_LJ_v2_alpha}) is not in [0,1]"
self._softcore_electrostatics = softcore_electrostatics
if self._softcore_electrostatics:
self._softcore_electrostatics_alpha = softcore_electrostatics_alpha
self._softcore_sigma_Q = softcore_sigma_Q
assert self._softcore_electrostatics_alpha >= 0.0 and self._softcore_electrostatics_alpha <= 1.0, f"softcore_electrostatics_alpha: ({self._softcore_electrostatics_alpha}) is not in [0,1]"
assert self._softcore_sigma_Q >= 0.0 and self._softcore_sigma_Q <= 1.0, f"softcore_sigma_Q : {self._softcore_sigma_Q} is not in [0, 1]"
if softcore_alpha is None:
self.softcore_alpha = 0.5
else:
# TODO: Check that softcore_alpha is in a valid range
self.softcore_alpha = softcore_alpha
if functions:
self._functions = functions
self._has_functions = True
else:
self._has_functions = False
#prepare dicts of forces, which will be useful later
# TODO: Store this as self._system_forces[name], name in ('old', 'new', 'hybrid') for compactness
self._old_system_forces = {type(force).__name__ : force for force in self._old_system.getForces()}
self._new_system_forces = {type(force).__name__ : force for force in self._new_system.getForces()}
_logger.info(f"Old system forces: {self._old_system_forces.keys()}")
_logger.info(f"New system forces: {self._new_system_forces.keys()}")
#check that there are no unknown forces in the new and old systems:
for system_name in ('old', 'new'):
force_names = getattr(self, '_{}_system_forces'.format(system_name)).keys()
unknown_forces = set(force_names) - set(self._known_forces)
if len(unknown_forces) > 0:
raise ValueError("Unkown forces {} encountered in {} system" % (unknown_forces, system_name))
_logger.info("No unknown forces.")
#get and store the nonbonded method from the system:
self._nonbonded_method = self._old_system_forces['NonbondedForce'].getNonbondedMethod()
_logger.info(f"Nonbonded method to be used (i.e. from old system): {self._nonbonded_method}")
#start by creating an empty system. This will become the hybrid system.
self._hybrid_system = openmm.System()
#begin by copying all particles in the old system to the hybrid system. Note that this does not copy the
#interactions. It does, however, copy the particle masses. In general, hybrid index and old index should be
#the same.
# TODO: Refactor this into self._add_particles()
_logger.info("Adding and mapping old atoms to hybrid system...")
for particle_idx in range(self._topology_proposal.n_atoms_old):
particle_mass = self._old_system.getParticleMass(particle_idx)
hybrid_idx = self._hybrid_system.addParticle(particle_mass)
self._old_to_hybrid_map[particle_idx] = hybrid_idx
#If the particle index in question is mapped, make sure to add it to the new to hybrid map as well.
if particle_idx in self._topology_proposal.old_to_new_atom_map.keys():
particle_index_in_new_system = self._topology_proposal.old_to_new_atom_map[particle_idx]
self._new_to_hybrid_map[particle_index_in_new_system] = hybrid_idx
#Next, add the remaining unique atoms from the new system to the hybrid system and map accordingly.
#As before, this does not copy interactions, only particle indices and masses.
_logger.info("Adding and mapping new atoms to hybrid system...")
for particle_idx in self._topology_proposal.unique_new_atoms:
particle_mass = self._new_system.getParticleMass(particle_idx)
hybrid_idx = self._hybrid_system.addParticle(particle_mass)
self._new_to_hybrid_map[particle_idx] = hybrid_idx
#check that if there is a barostat in the original system, it is added to the hybrid.
#We copy the barostat from the old system.
if "MonteCarloBarostat" in self._old_system_forces.keys():
barostat = copy.deepcopy(self._old_system_forces["MonteCarloBarostat"])
self._hybrid_system.addForce(barostat)
_logger.info("Added MonteCarloBarostat.")
else:
_logger.info("No MonteCarloBarostat added.")
#Copy over the box vectors:
box_vectors = self._old_system.getDefaultPeriodicBoxVectors()
self._hybrid_system.setDefaultPeriodicBoxVectors(*box_vectors)
_logger.info(f"getDefaultPeriodicBoxVectors added to hybrid: {box_vectors}")
#assign atoms to one of the classes described in the class docstring
self._atom_classes = self._determine_atom_classes()
_logger.info("Determined atom classes.")
#create the opposite atom maps for use in nonbonded force processing; let's omit this from logger
self._hybrid_to_old_map = {value : key for key, value in self._old_to_hybrid_map.items()}
self._hybrid_to_new_map = {value : key for key, value in self._new_to_hybrid_map.items()}
#construct dictionary of exceptions in old and new systems
_logger.info("Generating old system exceptions dict...")
self._old_system_exceptions = self._generate_dict_from_exceptions(self._old_system_forces['NonbondedForce'])
_logger.info("Generating new system exceptions dict...")
self._new_system_exceptions = self._generate_dict_from_exceptions(self._new_system_forces['NonbondedForce'])
#copy constraints, checking to make sure they are not changing
_logger.info("Handling constraints...")
self._handle_constraints()
#copy over relevant virtual sites
_logger.info("Handling virtual sites...")
self._handle_virtual_sites()
#call each of the methods to add the corresponding force terms and prepare the forces:
_logger.info("Adding bond force terms...")
self._add_bond_force_terms()
_logger.info("Adding angle force terms...")
self._add_angle_force_terms()
_logger.info("Adding torsion force terms...")
self._add_torsion_force_terms()
if 'NonbondedForce' in self._old_system_forces or 'NonbondedForce' in self._new_system_forces:
_logger.info("Adding nonbonded force terms...")
self._add_nonbonded_force_terms()
#call each force preparation method to generate the actual interactions that we need:
_logger.info("Handling harmonic bonds...")
self.handle_harmonic_bonds()
_logger.info("Handling harmonic angles...")
self.handle_harmonic_angles()
_logger.info("Handling torsion forces...")
self.handle_periodic_torsion_force()
if 'NonbondedForce' in self._old_system_forces or 'NonbondedForce' in self._new_system_forces:
_logger.info("Handling nonbonded forces...")
self.handle_nonbonded()
if 'NonbondedForce' in self._old_system_forces or 'NonbondedForce' in self._new_system_forces:
_logger.info("Handling unique_new/old interaction exceptions...")
if len(self._old_system_exceptions.keys()) == 0 and len(self._new_system_exceptions.keys()) == 0:
_logger.info("There are no old/new system exceptions.")
else:
_logger.info("There are old or new system exceptions...proceeding.")
self.handle_old_new_exceptions()
#get positions for the hybrid
self._hybrid_positions = self._compute_hybrid_positions()
#generate the topology representation
self._hybrid_topology = self._create_topology()
def _handle_virtual_sites(self):
"""
Ensure that all virtual sites in old and new system are copied over to the hybrid system. Note that we do not
support virtual sites in the changing region.
"""
for system_name in ('old', 'new'):
system = getattr(self._topology_proposal, '{}_system'.format(system_name))
hybrid_atom_map = getattr(self, '_{}_to_hybrid_map'.format(system_name))
# Loop through virtual sites
numVirtualSites = 0
for particle_idx in range(system.getNumParticles()):
if system.isVirtualSite(particle_idx):
numVirtualSites += 1
# If it's a virtual site, make sure it is not in the unique or core atoms, since this is currently unsupported
hybrid_idx = hybrid_atom_map[particle_idx]
if hybrid_idx not in self._atom_classes['environment_atoms']:
raise Exception("Virtual sites in changing residue are unsupported.")
else:
virtual_site = system.getVirtualSite(particle_idx)
self._hybrid_system.setVirtualSite(hybrid_idx, virtual_site)
_logger.info(f"\t_handle_virtual_sites: numVirtualSites: {numVirtualSites}")
def _get_core_atoms(self):
"""
Determine which atoms in the old system are part of the "core" class.
All necessary information is contained in the topology proposal passed to the constructor.
Returns
-------
core_atoms : set of int
The set of atoms (hybrid topology indexed) that are core atoms.
environment_atoms : set of int
The set of atoms (hybrid topology indexed) that are environment atoms.
.. todo ::
Overhaul this method and methods it calls by instead having this class accept
an alchemical atom set that denotes atoms not in the environment. The core would
then be very easy to figure out.
"""
#In order to be either a core or environment atom, the atom must be mapped.
mapped_old_atoms_set = set(self._topology_proposal.old_to_new_atom_map.keys())
mapped_new_atoms_set = set(self._topology_proposal.old_to_new_atom_map.values())
mapped_hybrid_atoms_set = {self._old_to_hybrid_map[atom_idx] for atom_idx in mapped_old_atoms_set}
#create sets for set arithmetic
unique_old_set = set(self._topology_proposal.unique_old_atoms)
unique_new_set = set(self._topology_proposal.unique_new_atoms)
#we derive core atoms from the old topology:
name_of_residue = self._topology_proposal.old_residue_name
core_atoms_from_old = self._determine_core_atoms_in_topology(self._topology_proposal.old_topology,
unique_old_set, mapped_old_atoms_set,
self._old_to_hybrid_map, name_of_residue)
#we also derive core atoms from the new topology:
name_of_residue = self._topology_proposal.new_residue_name
core_atoms_from_new = self._determine_core_atoms_in_topology(self._topology_proposal.new_topology,
unique_new_set, mapped_new_atoms_set,
self._new_to_hybrid_map, name_of_residue)
#The union of the two will give the core atoms that can result from either new or old topology
total_core_atoms = core_atoms_from_old.union(core_atoms_from_new)
assert set(core_atoms_from_old) == set(core_atoms_from_new), 'Core atoms must match between old and new systems'
#as a side effect, we can now compute the environment atom indices too, by subtracting the core indices
#from the mapped atom set (since any atom that is mapped but not core is environment)
environment_atoms = mapped_hybrid_atoms_set.difference(total_core_atoms)
return total_core_atoms, environment_atoms
def _determine_core_atoms_in_topology(self, topology, unique_atoms, mapped_atoms, hybrid_map, residue_to_switch):
"""
Given a topology and its corresponding unique and mapped atoms, return the set of atom indices in the
hybrid system which would belong to the "core" atom class
Parameters
----------
topology : simtk.openmm.app.Topology
An OpenMM topology representing a system of interest
unique_atoms : set of int
A set of atoms that are unique to this topology
mapped_atoms : set of int
A set of atoms that are mapped to another topology
residue_to_switch : str
string name of a residue that is being mutated
Returns
-------
core_atoms : set of int
set of core atom indices in hybrid topology
"""
core_atoms = set()
#loop through the residues to look for ones with unique atoms
for residue in topology.residues():
atom_indices_old_system = {atom.index for atom in residue.atoms()}
#if the residue contains an atom index that is unique, then the residue is changing.
#We determine this by checking if the atom indices of the residue have any intersection with the unique atoms
#likewise, if the name of the residue matches the residue_to_match, then we look for mapped atoms
if len(atom_indices_old_system.intersection(unique_atoms)) > 0 or residue_to_switch == residue.name:
#we can add the atoms in this residue which are mapped to the core_atoms set:
for atom_index in atom_indices_old_system:
if atom_index in mapped_atoms:
#we specifically want to add the hybrid atom.
hybrid_index = hybrid_map[atom_index]
core_atoms.add(hybrid_index)
assert len(core_atoms) >= 3, 'Cannot run a simulation with fewer than 3 core atoms. System has {len(core_atoms)}'
return core_atoms
def _determine_atom_classes(self):
"""
This method determines whether each atom belongs to unique old, unique new, core, or environment, as defined above.
All the information required is contained in the TopologyProposal passed to the constructor. All indices are
indices in the hybrid system.
Returns
-------
atom_classes : dict of list
A dictionary of the form {'core' :core_list} etc.
"""
atom_classes = {'unique_old_atoms' : set(), 'unique_new_atoms' : set(), 'core_atoms' : set(), 'environment_atoms' : set()}
#first, find the unique old atoms, as this is the most straightforward:
for atom_idx in self._topology_proposal.unique_old_atoms:
hybrid_idx = self._old_to_hybrid_map[atom_idx]
atom_classes['unique_old_atoms'].add(hybrid_idx)
#Then the unique new atoms (this is substantially the same as above)
for atom_idx in self._topology_proposal.unique_new_atoms:
hybrid_idx = self._new_to_hybrid_map[atom_idx]
atom_classes['unique_new_atoms'].add(hybrid_idx)
core_atoms, environment_atoms = self._get_core_atoms()
atom_classes['core_atoms'] = core_atoms
atom_classes['environment_atoms'] = environment_atoms
return atom_classes
def _translate_nonbonded_method_to_custom(self, standard_nonbonded_method):
"""
Utility function to translate the nonbonded method enum from the standard nonbonded force to the custom version
`CutoffPeriodic`, `PME`, and `Ewald` all become `CutoffPeriodic`; `NoCutoff` becomes `NoCutoff`; `CutoffNonPeriodic` becomes `CutoffNonPeriodic`
Parameters
----------
standard_nonbonded_method : openmm.NonbondedForce.NonbondedMethod
the nonbonded method of the standard force
Returns
-------
custom_nonbonded_method : openmm.CustomNonbondedForce.NonbondedMethod
the nonbonded method for the equivalent customnonbonded force
"""
if standard_nonbonded_method in [openmm.NonbondedForce.CutoffPeriodic, openmm.NonbondedForce.PME, openmm.NonbondedForce.Ewald]:
return openmm.CustomNonbondedForce.CutoffPeriodic
elif standard_nonbonded_method == openmm.NonbondedForce.NoCutoff:
return openmm.CustomNonbondedForce.NoCutoff
elif standard_nonbonded_method == openmm.NonbondedForce.CutoffNonPeriodic:
return openmm.CustomNonbondedForce.CutoffNonPeriodic
else:
raise NotImplementedError("This nonbonded method is not supported.")
def _handle_constraints(self):
"""
This method adds relevant constraints from the old and new systems.
First, all constraints from the old systenm are added.
Then, constraints to atoms unique to the new system are added.
"""
constraint_lengths = dict() # lengths of constraints already added
for system_name in ('old', 'new'):
system = getattr(self._topology_proposal, '{}_system'.format(system_name))
hybrid_map = getattr(self, '_{}_to_hybrid_map'.format(system_name))
for constraint_idx in range(system.getNumConstraints()):
atom1, atom2, length = system.getConstraintParameters(constraint_idx)
hybrid_atoms = tuple(sorted([hybrid_map[atom1], hybrid_map[atom2]]))
if hybrid_atoms not in constraint_lengths.keys():
self._hybrid_system.addConstraint(hybrid_atoms[0], hybrid_atoms[1], length)
constraint_lengths[hybrid_atoms] = length
else:
# TODO: We can skip this if we have already checked for constraints changing lengths
if constraint_lengths[hybrid_atoms] != length:
raise Exception('Constraint length is changing for atoms {} in hybrid system: old {} new {}'.format(hybrid_atoms, constraint_lengths[hybrid_atoms], length))
_logger.debug(f"\t_handle_constraints: constraint_lengths dict: {constraint_lengths}")
def _determine_interaction_group(self, atoms_in_interaction):
"""
This method determines which interaction group the interaction should fall under. There are four groups:
Those involving unique old atoms: any interaction involving unique old atoms should be completely on at lambda=0
and completely off at lambda=1
Those involving unique new atoms: any interaction involving unique new atoms should be completely off at lambda=0
and completely on at lambda=1
Those involving core atoms and/or environment atoms: These interactions change their type, and should be the old
character at lambda=0, and the new character at lambda=1
Those involving only environment atoms: These interactions are unmodified.
Parameters
----------
atoms_in_interaction : list of int
List of (hybrid) indices of the atoms in this interaction
Returns
-------
interaction_group : InteractionGroup enum
The group to which this interaction should be assigned
"""
#make the interaction list a set to facilitate operations
atom_interaction_set = set(atoms_in_interaction)
#check if the interaction contains unique old atoms
if len(atom_interaction_set.intersection(self._atom_classes['unique_old_atoms'])) > 0:
return InteractionGroup.unique_old
#Do the same for new atoms
elif len(atom_interaction_set.intersection(self._atom_classes['unique_new_atoms'])) > 0:
return InteractionGroup.unique_new
#if the interaction set is a strict subset of the environment atoms, then it is in the environment group
#and should not be alchemically modified at all.
elif atom_interaction_set.issubset(self._atom_classes['environment_atoms']):
return InteractionGroup.environment
#having covered the cases of all-environment, unique old-containing, and unique-new-containing, anything else
#should belong to the last class--contains core atoms but not any unique atoms.
else:
return InteractionGroup.core
def _add_bond_force_terms(self):
"""
This function adds the appropriate bond forces to the system (according to groups defined above). Note that it
does _not_ add the particles to the force. It only adds the force to facilitate another method adding the
particles to the force.
"""
core_energy_expression = '(K/2)*(r-length)^2;'
core_energy_expression += 'K = (1-lambda_bonds)*K1 + lambda_bonds*K2;' # linearly interpolate spring constant
core_energy_expression += 'length = (1-lambda_bonds)*length1 + lambda_bonds*length2;' # linearly interpolate bond length
if self._has_functions:
try:
core_energy_expression += 'lambda_bonds = ' + self._functions['lambda_bonds']
except KeyError as e:
print("Functions were provided, but no term was provided for the bonds")
raise e
#create the force and add the relevant parameters
custom_core_force = openmm.CustomBondForce(core_energy_expression)
custom_core_force.addPerBondParameter('length1') # old bond length
custom_core_force.addPerBondParameter('K1') # old spring constant
custom_core_force.addPerBondParameter('length2') # new bond length
custom_core_force.addPerBondParameter('K2') #new spring constant
if self._has_functions:
custom_core_force.addGlobalParameter('lambda', 0.0)
custom_core_force.addEnergyParameterDerivative('lambda')
else:
custom_core_force.addGlobalParameter('lambda_bonds', 0.0)
self._hybrid_system.addForce(custom_core_force)
self._hybrid_system_forces['core_bond_force'] = custom_core_force
#add a bond force for environment and unique atoms (bonds are never scaled for these):
standard_bond_force = openmm.HarmonicBondForce()
self._hybrid_system.addForce(standard_bond_force)
self._hybrid_system_forces['standard_bond_force'] = standard_bond_force
def _add_angle_force_terms(self):
"""
This function adds the appropriate angle force terms to the hybrid system. It does not add particles
or parameters to the force; this is done elsewhere.
"""
energy_expression = '(K/2)*(theta-theta0)^2;'
energy_expression += 'K = (1.0-lambda_angles)*K_1 + lambda_angles*K_2;' # linearly interpolate spring constant
energy_expression += 'theta0 = (1.0-lambda_angles)*theta0_1 + lambda_angles*theta0_2;' # linearly interpolate equilibrium angle
if self._has_functions:
try:
energy_expression += 'lambda_angles = ' + self._functions['lambda_angles']
except KeyError as e:
print("Functions were provided, but no term was provided for the angles")
raise e
#create the force and add relevant parameters
custom_core_force = openmm.CustomAngleForce(energy_expression)
custom_core_force.addPerAngleParameter('theta0_1') # molecule1 equilibrium angle
custom_core_force.addPerAngleParameter('K_1') # molecule1 spring constant
custom_core_force.addPerAngleParameter('theta0_2') # molecule2 equilibrium angle
custom_core_force.addPerAngleParameter('K_2') # molecule2 spring constant
#create the force for neglected angles and relevant parameters; the K_1 term will be set to 0
if len(self.neglected_new_angle_terms) > 0: #if there is at least one neglected angle term from the geometry engine
_logger.info("\t_add_angle_force_terms: there are > 0 neglected new angles: adding CustomAngleForce")
custom_neglected_new_force = openmm.CustomAngleForce(energy_expression)
custom_neglected_new_force.addPerAngleParameter('theta0_1') # molecule1 equilibrium angle
custom_neglected_new_force.addPerAngleParameter('K_1') # molecule1 spring constant
custom_neglected_new_force.addPerAngleParameter('theta0_2') # molecule2 equilibrium angle
custom_neglected_new_force.addPerAngleParameter('K_2') # molecule2 spring constant
if len(self.neglected_old_angle_terms) > 0: #if there is at least one neglected angle term from the geometry engine
_logger.info("\t_add_angle_force_terms: there are > 0 neglected old angles: adding CustomAngleForce")
custom_neglected_old_force = openmm.CustomAngleForce(energy_expression)
custom_neglected_old_force.addPerAngleParameter('theta0_1') # molecule1 equilibrium angle
custom_neglected_old_force.addPerAngleParameter('K_1') # molecule1 spring constant
custom_neglected_old_force.addPerAngleParameter('theta0_2') # molecule2 equilibrium angle
custom_neglected_old_force.addPerAngleParameter('K_2') # molecule2 spring constant
if self._has_functions:
custom_core_force.addGlobalParameter('lambda', 0.0)
custom_core_force.addEnergyParameterDerivative('lambda')
if len(self.neglected_new_angle_terms) > 0:
custom_neglected_new_force.addGlobalParameter('lambda', 0.0)
custom_neglected_new_force.addEnergyParameterDerivative('lambda')
if len(self.neglected_old_angle_terms) > 0:
custom_neglected_old_force.addGlobalParameter('lambda', 0.0)
custom_neglected_old_force.addEnergyParameterDerivative('lambda')
else:
custom_core_force.addGlobalParameter('lambda_angles', 0.0)
if len(self.neglected_new_angle_terms) > 0:
custom_neglected_new_force.addGlobalParameter('lambda_angles', 0.0)
if len(self.neglected_new_angle_terms) > 0:
custom_neglected_old_force.addGlobalParameter('lambda_angles', 0.0)
#add the force to the system and the force dict.
self._hybrid_system.addForce(custom_core_force)
self._hybrid_system_forces['core_angle_force'] = custom_core_force
if len(self.neglected_new_angle_terms) > 0:
self._hybrid_system.addForce(custom_neglected_new_force)
self._hybrid_system_forces['custom_neglected_new_angle_force'] = custom_neglected_new_force
if len(self.neglected_old_angle_terms) > 0:
self._hybrid_system.addForce(custom_neglected_old_force)
self._hybrid_system_forces['custom_neglected_old_angle_force'] = custom_neglected_old_force
#add an angle term for environment/unique interactions--these are never scaled
standard_angle_force = openmm.HarmonicAngleForce()
self._hybrid_system.addForce(standard_angle_force)
self._hybrid_system_forces['standard_angle_force'] = standard_angle_force
def _add_torsion_force_terms(self):
"""
This function adds the appropriate PeriodicTorsionForce terms to the system. Core torsions are interpolated,
while environment and unique torsions are always on.
"""
energy_expression = '(1-lambda_torsions)*U1 + lambda_torsions*U2;'
energy_expression += 'U1 = K1*(1+cos(periodicity1*theta-phase1));'
energy_expression += 'U2 = K2*(1+cos(periodicity2*theta-phase2));'
if self._has_functions:
try:
energy_expression += 'lambda_torsions = ' + self._functions['lambda_torsions']
except KeyError as e:
print("Functions were provided, but no term was provided for torsions")
raise e
#create the force and add the relevant parameters
custom_core_force = openmm.CustomTorsionForce(energy_expression)
custom_core_force.addPerTorsionParameter('periodicity1') # molecule1 periodicity
custom_core_force.addPerTorsionParameter('phase1') # molecule1 phase
custom_core_force.addPerTorsionParameter('K1') # molecule1 spring constant
custom_core_force.addPerTorsionParameter('periodicity2') # molecule2 periodicity
custom_core_force.addPerTorsionParameter('phase2') # molecule2 phase
custom_core_force.addPerTorsionParameter('K2') # molecule2 spring constant
if self._has_functions:
custom_core_force.addGlobalParameter('lambda', 0.0)
custom_core_force.addEnergyParameterDerivative('lambda')
else:
custom_core_force.addGlobalParameter('lambda_torsions', 0.0)
#add the force to the system
self._hybrid_system.addForce(custom_core_force)
self._hybrid_system_forces['core_torsion_force'] = custom_core_force
#create and add the torsion term for unique/environment atoms
standard_torsion_force = openmm.PeriodicTorsionForce()
self._hybrid_system.addForce(standard_torsion_force)
self._hybrid_system_forces['standard_torsion_force'] = standard_torsion_force
def _add_nonbonded_force_terms(self):
"""
Add the nonbonded force terms to the hybrid system. Note that as with the other forces,
this method does not add any interactions. It only sets up the forces.
Parameters
----------
nonbonded_method : int
One of the openmm.NonbondedForce nonbonded methods.
"""
#Add a regular nonbonded force for all interactions that are not changing.
standard_nonbonded_force = openmm.NonbondedForce()
self._hybrid_system.addForce(standard_nonbonded_force)
_logger.info(f"\t_add_nonbonded_force_terms: {standard_nonbonded_force} added to hybrid system")
self._hybrid_system_forces['standard_nonbonded_force'] = standard_nonbonded_force
# Create a CustomNonbondedForce to handle alchemically interpolated nonbonded parameters.
# Select functional form based on nonbonded method.
# TODO: check _nonbonded_custom_ewald and _nonbonded_custom_cutoff since they take arguments that are never used...
if self._nonbonded_method in [openmm.NonbondedForce.NoCutoff]:
_logger.info("\t_add_nonbonded_force_terms: nonbonded_method is NoCutoff")
sterics_energy_expression = self._nonbonded_custom(self._softcore_LJ_v2)
elif self._nonbonded_method in [openmm.NonbondedForce.CutoffPeriodic, openmm.NonbondedForce.CutoffNonPeriodic]:
_logger.info("\t_add_nonbonded_force_terms: nonbonded_method is Cutoff(Periodic or NonPeriodic)")
epsilon_solvent = self._old_system_forces['NonbondedForce'].getReactionFieldDielectric()
r_cutoff = self._old_system_forces['NonbondedForce'].getCutoffDistance()
sterics_energy_expression = self._nonbonded_custom(self._softcore_LJ_v2)
standard_nonbonded_force.setReactionFieldDielectric(epsilon_solvent)
standard_nonbonded_force.setCutoffDistance(r_cutoff)
elif self._nonbonded_method in [openmm.NonbondedForce.PME, openmm.NonbondedForce.Ewald]:
_logger.info("\t_add_nonbonded_force_terms: nonbonded_method is PME or Ewald")
[alpha_ewald, nx, ny, nz] = self._old_system_forces['NonbondedForce'].getPMEParameters()
delta = self._old_system_forces['NonbondedForce'].getEwaldErrorTolerance()
r_cutoff = self._old_system_forces['NonbondedForce'].getCutoffDistance()
sterics_energy_expression = self._nonbonded_custom(self._softcore_LJ_v2)
standard_nonbonded_force.setPMEParameters(alpha_ewald, nx, ny, nz)
standard_nonbonded_force.setEwaldErrorTolerance(delta)
standard_nonbonded_force.setCutoffDistance(r_cutoff)
else:
raise Exception("Nonbonded method %s not supported yet." % str(self._nonbonded_method))
standard_nonbonded_force.setNonbondedMethod(self._nonbonded_method)
_logger.info(f"\t_add_nonbonded_force_terms: {self._nonbonded_method} added to standard nonbonded force")
sterics_energy_expression += self._nonbonded_custom_sterics_common()
sterics_mixing_rules = self._nonbonded_custom_mixing_rules()
custom_nonbonded_method = self._translate_nonbonded_method_to_custom(self._nonbonded_method)
total_sterics_energy = "U_sterics;" + sterics_energy_expression + sterics_mixing_rules
if self._has_functions:
try:
total_sterics_energy += 'lambda_sterics = ' + self._functions['lambda_sterics']
except KeyError as e:
print("Functions were provided, but there is no entry for sterics")
raise e
sterics_custom_nonbonded_force = openmm.CustomNonbondedForce(total_sterics_energy)
if self._softcore_LJ_v2:
sterics_custom_nonbonded_force.addGlobalParameter("softcore_alpha", self._softcore_LJ_v2_alpha)
else:
sterics_custom_nonbonded_force.addGlobalParameter("softcore_alpha", self.softcore_alpha)
sterics_custom_nonbonded_force.addPerParticleParameter("sigmaA") # Lennard-Jones sigma initial
sterics_custom_nonbonded_force.addPerParticleParameter("epsilonA") # Lennard-Jones epsilon initial
sterics_custom_nonbonded_force.addPerParticleParameter("sigmaB") # Lennard-Jones sigma final
sterics_custom_nonbonded_force.addPerParticleParameter("epsilonB") # Lennard-Jones epsilon final
sterics_custom_nonbonded_force.addPerParticleParameter("unique_old") # 1 = hybrid old atom, 0 otherwise
sterics_custom_nonbonded_force.addPerParticleParameter("unique_new") # 1 = hybrid new atom, 0 otherwise
if self._has_functions:
sterics_custom_nonbonded_force.addGlobalParameter('lambda', 0.0)
sterics_custom_nonbonded_force.addEnergyParameterDerivative('lambda')
else:
sterics_custom_nonbonded_force.addGlobalParameter("lambda_sterics_core", 0.0)
sterics_custom_nonbonded_force.addGlobalParameter("lambda_electrostatics_core", 0.0)
sterics_custom_nonbonded_force.addGlobalParameter("lambda_sterics_insert", 0.0)
sterics_custom_nonbonded_force.addGlobalParameter("lambda_sterics_delete", 0.0)
sterics_custom_nonbonded_force.setNonbondedMethod(custom_nonbonded_method)
_logger.info(f"\t_add_nonbonded_force_terms: {custom_nonbonded_method} added to sterics_custom_nonbonded force")
self._hybrid_system.addForce(sterics_custom_nonbonded_force)
self._hybrid_system_forces['core_sterics_force'] = sterics_custom_nonbonded_force
_logger.info(f"\t_add_nonbonded_force_terms: {sterics_custom_nonbonded_force} added to hybrid system")
#set the use of dispersion correction to be the same between the new nonbonded force and the old one:
#these will be ignored from the _logger for the time being
if self._old_system_forces['NonbondedForce'].getUseDispersionCorrection():
self._hybrid_system_forces['standard_nonbonded_force'].setUseDispersionCorrection(True)
if self._use_dispersion_correction:
sterics_custom_nonbonded_force.setUseLongRangeCorrection(True)
else:
self._hybrid_system_forces['standard_nonbonded_force'].setUseDispersionCorrection(False)
if self._old_system_forces['NonbondedForce'].getUseSwitchingFunction():
switching_distance = self._old_system_forces['NonbondedForce'].getSwitchingDistance()
standard_nonbonded_force.setUseSwitchingFunction(True)
standard_nonbonded_force.setSwitchingDistance(switching_distance)
sterics_custom_nonbonded_force.setUseSwitchingFunction(True)
sterics_custom_nonbonded_force.setSwitchingDistance(switching_distance)
else:
standard_nonbonded_force.setUseSwitchingFunction(False)
sterics_custom_nonbonded_force.setUseSwitchingFunction(False)
def _nonbonded_custom_sterics_common(self):
"""
Get a custom sterics expression using amber softcore expression
Returns
-------
sterics_addition : str
The common softcore sterics energy expression
"""
sterics_addition = "epsilon = (1-lambda_sterics)*epsilonA + lambda_sterics*epsilonB;" #interpolation
sterics_addition += "reff_sterics = sigma*((softcore_alpha*lambda_alpha + (r/sigma)^6))^(1/6);" # effective softcore distance for sterics
sterics_addition += "sigma = (1-lambda_sterics)*sigmaA + lambda_sterics*sigmaB;"
sterics_addition += "lambda_alpha = new_interaction*(1-lambda_sterics_insert) + old_interaction*lambda_sterics_delete;"
sterics_addition += "lambda_sterics = core_interaction*lambda_sterics_core + new_interaction*lambda_sterics_insert + old_interaction*lambda_sterics_delete;"
sterics_addition += "core_interaction = delta(unique_old1+unique_old2+unique_new1+unique_new2);new_interaction = max(unique_new1, unique_new2);old_interaction = max(unique_old1, unique_old2);"
return sterics_addition
def _nonbonded_custom(self, v2):
"""
Get a part of the nonbonded energy expression when there is no cutoff.
Returns
-------
sterics_energy_expression : str
The energy expression for U_sterics
electrostatics_energy_expression : str
The energy expression for electrostatics
"""
# soft-core Lennard-Jones
if v2:
sterics_energy_expression = "U_sterics = select(step(r - r_LJ), 4*epsilon*x*(x-1.0), U_sterics_quad);"
sterics_energy_expression += f"U_sterics_quad = Force*(((r - r_LJ)^2)/2 - (r - r_LJ)) + U_sterics_cut;"
sterics_energy_expression += f"U_sterics_cut = 4*epsilon*((sigma/r_LJ)^6)*(((sigma/r_LJ)^6) - 1.0);"
sterics_energy_expression += f"Force = -4*epsilon*((-12*sigma^12)/(r_LJ^13) + (6*sigma^6)/(r_LJ^7));"
sterics_energy_expression += f"x = (sigma/r)^6;"
sterics_energy_expression += f"r_LJ = softcore_alpha*((26/7)*(sigma^6)*lambda_sterics_deprecated)^(1/6);"
sterics_energy_expression += f"lambda_sterics_deprecated = new_interaction*(1.0 - lambda_sterics_insert) + old_interaction*lambda_sterics_delete;"
else:
sterics_energy_expression = "U_sterics = 4*epsilon*x*(x-1.0); x = (sigma/reff_sterics)^6;"
return sterics_energy_expression
def _nonbonded_custom_mixing_rules(self):
"""
Mixing rules for the custom nonbonded force.
Returns
-------
sterics_mixing_rules : str
The mixing expression for sterics
electrostatics_mixing_rules : str
The mixiing rules for electrostatics
"""
# Define mixing rules.
sterics_mixing_rules = "epsilonA = sqrt(epsilonA1*epsilonA2);" # mixing rule for epsilon
sterics_mixing_rules += "epsilonB = sqrt(epsilonB1*epsilonB2);" # mixing rule for epsilon
sterics_mixing_rules += "sigmaA = 0.5*(sigmaA1 + sigmaA2);" # mixing rule for sigma
sterics_mixing_rules += "sigmaB = 0.5*(sigmaB1 + sigmaB2);" # mixing rule for sigma
return sterics_mixing_rules
def _find_bond_parameters(self, bond_force, index1, index2):
"""
This is a convenience function to find bond parameters in another system given the two indices.
Parameters
----------
bond_force : openmm.HarmonicBondForce
The bond force where the parameters should be found
index1 : int
Index1 (order does not matter) of the bond atoms
index2 : int
Index2 (order does not matter) of the bond atoms
Returns
-------
bond_parameters : list
List of relevant bond parameters
"""
index_set = {index1, index2}
#loop through all the bonds:
for bond_index in range(bond_force.getNumBonds()):
parms = bond_force.getBondParameters(bond_index)
if index_set=={parms[0], parms[1]}:
return parms
return []
def handle_harmonic_bonds(self):
"""
This method adds the appropriate interaction for all bonds in the hybrid system. The scheme used is:
1) If the two atoms are both in the core, then we add to the CustomBondForce and interpolate between the two
parameters
2) Otherwise, we add the bond to a regular bond force.
"""
old_system_bond_force = self._old_system_forces['HarmonicBondForce']
new_system_bond_force = self._new_system_forces['HarmonicBondForce']
#first, loop through the old system bond forces and add relevant terms
_logger.info("\thandle_harmonic_bonds: looping through old_system to add relevant terms...")
for bond_index in range(old_system_bond_force.getNumBonds()):
_logger.debug(f"\t\thandle_harmonic_bonds: old bond_index: {bond_index}")
#get each set of bond parameters
[index1_old, index2_old, r0_old, k_old] = old_system_bond_force.getBondParameters(bond_index)
#map the indices to the hybrid system, for which our atom classes are defined.
index1_hybrid = self._old_to_hybrid_map[index1_old]
index2_hybrid = self._old_to_hybrid_map[index2_old]
index_set = {index1_hybrid, index2_hybrid}
#now check if it is a subset of the core atoms (that is, both atoms are in the core)
#if it is, we need to find the parameters in the old system so that we can interpolate
if index_set.issubset(self._atom_classes['core_atoms']):
_logger.debug(f"\t\thandle_harmonic_bonds: bond_index {bond_index} is a core (to custom bond force).")
index1_new = self._topology_proposal.old_to_new_atom_map[index1_old]
index2_new = self._topology_proposal.old_to_new_atom_map[index2_old]
new_bond_parameters = self._find_bond_parameters(new_system_bond_force, index1_new, index2_new)
if not new_bond_parameters:
r0_new = r0_old
k_new = 0.0*unit.kilojoule_per_mole/unit.angstrom**2
else:
[index1, index2, r0_new, k_new] = self._find_bond_parameters(new_system_bond_force, index1_new, index2_new)
self._hybrid_system_forces['core_bond_force'].addBond(index1_hybrid, index2_hybrid,[r0_old, k_old, r0_new, k_new])
#check if the index set is a subset of anything besides environemnt (in the case of environment, we just add the bond to the regular bond force)
# that would mean that this bond is core-unique_old or unique_old-unique_old
elif not index_set.issubset(self._atom_classes['environment_atoms']):
_logger.debug(f"\t\thandle_harmonic_bonds: bond_index {bond_index} is a core-unique_old or unique_old-unique old...")
# If we're not softening bonds, we can just add it to the regular bond force. Likewise if we are only softening new bonds
if not self._soften_bonds or self._soften_only_new:
_logger.debug(f"\t\t\thandle_harmonic_bonds: no softening (to standard bond force)")
self._hybrid_system_forces['standard_bond_force'].addBond(index1_hybrid, index2_hybrid, r0_old,
k_old)
# Otherwise, we will need to soften one of the endpoints. For unique old atoms, the softening endpoint is at lambda =1
else:
r0_new = r0_old # The bond length won't change
k_new = self._bond_softening_constant * k_old # We multiply the endpoint by the bond softening constant
# Now we add to the core bond force, since that is an alchemically-modified force.
self._hybrid_system_forces['core_bond_force'].addBond(index1_hybrid, index2_hybrid,
[r0_old, k_old, r0_new, k_new])
#otherwise, we just add the same parameters as those in the old system (these are environment atoms, and the parameters are the same)
else:
_logger.debug(f"\t\thandle_harmonic_bonds: bond_index {bond_index} is an environment (to standard bond force).")
self._hybrid_system_forces['standard_bond_force'].addBond(index1_hybrid, index2_hybrid, r0_old, k_old)
#now loop through the new system to get the interactions that are unique to it.
_logger.info("\thandle_harmonic_bonds: looping through new_system to add relevant terms...")
for bond_index in range(new_system_bond_force.getNumBonds()):
_logger.debug(f"\t\thandle_harmonic_bonds: new bond_index: {bond_index}")
#get each set of bond parameters
[index1_new, index2_new, r0_new, k_new] = new_system_bond_force.getBondParameters(bond_index)
#convert indices to hybrid, since that is how we represent atom classes:
index1_hybrid = self._new_to_hybrid_map[index1_new]
index2_hybrid = self._new_to_hybrid_map[index2_new]
index_set = {index1_hybrid, index2_hybrid}
#if the intersection of this set and unique new atoms contains anything, the bond is unique to the new system and must be added
#all other bonds in the new system have been accounted for already.
if len(index_set.intersection(self._atom_classes['unique_new_atoms'])) > 0:
_logger.debug(f"\t\thandle_harmonic_bonds: bond_index {bond_index} is a core-unique_new or unique_new-unique_new...")
# If we are softening bonds, we have to use the core bond force, and scale the force constant at lambda = 0:
if self._soften_bonds:
_logger.debug(f"\t\t\thandle_harmonic_bonds: softening (to custom bond force)")
r0_old = r0_new # Do not change the length
k_old = k_new * self._bond_softening_constant # Scale the force constant by the requested parameter
# Now we add to the core bond force, since that is an alchemically-modified force.
self._hybrid_system_forces['core_bond_force'].addBond(index1_hybrid, index2_hybrid,
[r0_old, k_old, r0_new, k_new])
# If we aren't softening bonds, then just add it to the standard bond force
else:
_logger.debug(f"\t\t\thandle_harmonic_bonds: no softening (to standard bond force)")
self._hybrid_system_forces['standard_bond_force'].addBond(index1_hybrid, index2_hybrid, r0_new, k_new)
#if the bond is in the core, it has probably already been added in the above loop. However, there are some circumstances
#where it was not (closing a ring). In that case, the bond has not been added and should be added here.
#This has some peculiarities to be discussed...
if index_set.issubset(self._atom_classes['core_atoms']):
if not self._find_bond_parameters(self._hybrid_system_forces['core_bond_force'], index1_hybrid, index2_hybrid):
_logger.debug(f"\t\thandle_harmonic_bonds: bond_index {bond_index} is a SPECIAL core-core (to custom bond force).")
r0_old = r0_new
k_old = 0.0*unit.kilojoule_per_mole/unit.angstrom**2
self._hybrid_system_forces['core_bond_force'].addBond(index1_hybrid, index2_hybrid,
[r0_old, k_old, r0_new, k_new])
def _find_angle_parameters(self, angle_force, indices):
"""
Convenience function to find the angle parameters corresponding to a particular set of indices
Parameters
----------
angle_force : openmm.HarmonicAngleForce
The force where the angle of interest may be found.
indices : list of int
The indices (any order) of the angle atoms
Returns
-------
angle_parameters : list
list of angle parameters
"""
#index_set = set(indices)
indices_reversed = indices[::-1]
#now loop through and try to find the angle:
for angle_index in range(angle_force.getNumAngles()):
angle_parameters = angle_force.getAngleParameters(angle_index)
#get a set representing the angle indices
angle_parameter_indices = angle_parameters[:3]
if indices == angle_parameter_indices or indices_reversed == angle_parameter_indices:
return angle_parameters
return [] # return empty if no matching angle found
def _find_torsion_parameters(self, torsion_force, indices):
"""
Convenience function to find the torsion parameters corresponding to a particular set of indices.
Parameters
----------
torsion_force : openmm.PeriodicTorsionForce
torsion force where the torsion of interest may be found
indices : list of int
The indices of the atoms of the torsion
Returns
-------
torsion_parameters : list
torsion parameters
"""
#index_set = set(indices)
indices_reversed = indices[::-1]
torsion_parameters_list = list()
#now loop through and try to find the torsion:
for torsion_index in range(torsion_force.getNumTorsions()):
torsion_parameters = torsion_force.getTorsionParameters(torsion_index)
#get a set representing the torsion indices:
torsion_parameter_indices = torsion_parameters[:4]
if indices == torsion_parameter_indices or indices_reversed == torsion_parameter_indices:
torsion_parameters_list.append(torsion_parameters)
return torsion_parameters_list
def handle_harmonic_angles(self):
"""
This method adds the appropriate interaction for all angles in the hybrid system. The scheme used, as with bonds, is:
1) If the three atoms are all in the core, then we add to the CustomAngleForce and interpolate between the two
parameters
2) If the three atoms contain at least one unique new, check if the angle is in the neglected new list, and if so, interpolate from K_1 = 0;
else, if the three atoms contain at least one unique old, check if the angle is in the neglected old list, and if so, interpolate from K_2 = 0.
3) Otherwise, we add the angle to a regular angle force.
"""
old_system_angle_force = self._old_system_forces['HarmonicAngleForce']
new_system_angle_force = self._new_system_forces['HarmonicAngleForce']
#first, loop through all the angles in the old system to determine what to do with them. We will only use the
#custom angle force if all atoms are part of "core." Otherwise, they are either unique to one system or never
#change.
_logger.info("\thandle_harmonic_angles: looping through old_system to add relevant terms...")
for angle_index in range(old_system_angle_force.getNumAngles()):
_logger.debug(f"\t\thandle_harmonic_angles: old angle_index: {angle_index}")
old_angle_parameters = old_system_angle_force.getAngleParameters(angle_index)
#get the indices in the hybrid system
hybrid_index_list = [self._old_to_hybrid_map[old_atomid] for old_atomid in old_angle_parameters[:3]]
hybrid_index_set = set(hybrid_index_list)
#if all atoms are in the core, we'll need to find the corresponding parameters in the old system and
#interpolate
if hybrid_index_set.issubset(self._atom_classes['core_atoms']):
_logger.debug(f"\t\thandle_harmonic_angles: angle_index {angle_index} is a core (to custom angle force).")
#get the new indices so we can get the new angle parameters
new_indices = [self._topology_proposal.old_to_new_atom_map[old_atomid] for old_atomid in old_angle_parameters[:3]]
new_angle_parameters = self._find_angle_parameters(new_system_angle_force, new_indices)
if not new_angle_parameters:
new_angle_parameters = [0, 0, 0, old_angle_parameters[3], 0.0*unit.kilojoule_per_mole/unit.radian**2]
#add to the hybrid force:
#the parameters at indices 3 and 4 represent theta0 and k, respectively.
hybrid_force_parameters = [old_angle_parameters[3], old_angle_parameters[4], new_angle_parameters[3], new_angle_parameters[4]]
self._hybrid_system_forces['core_angle_force'].addAngle(hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_force_parameters)
# Check if the atoms are neither all core nor all environment, which would mean they involve unique old interactions
elif not hybrid_index_set.issubset(self._atom_classes['environment_atoms']):
_logger.debug(f"\t\thandle_harmonic_angles: angle_index {angle_index} is an environment or core with unique_old...")
# Check if we are softening angles, and not softening only new angles:
if self._soften_angles and not self._soften_only_new:
_logger.debug(f"\t\t\thandle_harmonic_angles: softening (to custom angle force)")
# If we are, then we need to generate the softened parameters (at lambda=1 for old atoms)
# We do this by using the same equilibrium angle, and scaling the force constant at the non-interacting
# endpoint:
if angle_index in self.neglected_old_angle_terms:
_logger.debug("\t\t\tsoften angles on but angle is in neglected old, so softening constant is set to zero.")
hybrid_force_parameters = [old_angle_parameters[3], old_angle_parameters[4], old_angle_parameters[3], 0.0 * old_angle_parameters[4]]
self._hybrid_system_forces['custom_neglected_old_angle_force'].addAngle(hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_force_parameters)
else:
_logger.debug(f"\t\t\thandle_harmonic_angles: softening (to custom angle force)")
hybrid_force_parameters = [old_angle_parameters[3], old_angle_parameters[4], old_angle_parameters[3], self._angle_softening_constant * old_angle_parameters[4]]
self._hybrid_system_forces['core_angle_force'].addAngle(hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_force_parameters)
# If not, we can just add this to the standard angle force
else:
if angle_index in self.neglected_old_angle_terms:
_logger.debug(f"\t\t\tangle in neglected_old_angle_terms; K_2 is set to zero")
hybrid_force_parameters = [old_angle_parameters[3], old_angle_parameters[4], old_angle_parameters[3], 0.0 * old_angle_parameters[4]]
self._hybrid_system_forces['custom_neglected_old_angle_force'].addAngle(hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_force_parameters)
else:
_logger.debug(f"\t\t\thandle_harmonic_bonds: no softening (to standard angle force)")
self._hybrid_system_forces['standard_angle_force'].addAngle(hybrid_index_list[0],
hybrid_index_list[1],
hybrid_index_list[2],
old_angle_parameters[3],
old_angle_parameters[4])
#otherwise, only environment atoms are in this interaction, so add it to the standard angle force
else:
_logger.debug(f"\t\thandle_harmonic_angles: angle_index {angle_index} is an environment (to standard angle force)")
self._hybrid_system_forces['standard_angle_force'].addAngle(hybrid_index_list[0], hybrid_index_list[1],
hybrid_index_list[2], old_angle_parameters[3],
old_angle_parameters[4])
#finally, loop through the new system force to add any unique new angles
_logger.info("\thandle_harmonic_angles: looping through new_system to add relevant terms...")
for angle_index in range(new_system_angle_force.getNumAngles()):
_logger.debug(f"\t\thandle_harmonic_angles: new angle_index: {angle_index}")
new_angle_parameters = new_system_angle_force.getAngleParameters(angle_index)
#get the indices in the hybrid system
hybrid_index_list = [self._new_to_hybrid_map[new_atomid] for new_atomid in new_angle_parameters[:3]]
hybrid_index_set = set(hybrid_index_list)
#if the intersection of this hybrid set with the unique new atoms is nonempty, it must be added:
if len(hybrid_index_set.intersection(self._atom_classes['unique_new_atoms'])) > 0:
_logger.debug(f"\t\thandle_harmonic_bonds: angle_index {angle_index} is a core-unique_new or unique_new-unique_new...")
# Check to see if we are softening angles:
if self._soften_angles:
_logger.info(f"\t\t\thandle_harmonic_bonds: softening (to custom angle force)")
if angle_index in self.neglected_new_angle_terms:
_logger.debug("\t\t\tsoften angles on but angle is in neglected new, so softening constant is set to zero.")
hybrid_force_parameters = [new_angle_parameters[3], new_angle_parameters[4] * 0.0, new_angle_parameters[3], new_angle_parameters[4]]
self._hybrid_system_forces['custom_neglected_new_angle_force'].addAngle(hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_force_parameters)
else:
_logger.debug(f"\t\t\thandle_harmonic_angles: softening (to custom angle force)")
hybrid_force_parameters = [new_angle_parameters[3], new_angle_parameters[4] * self._angle_softening_constant, new_angle_parameters[3], new_angle_parameters[4]]
self._hybrid_system_forces['core_angle_force'].addAngle(hybrid_index_list[0], hybrid_index_list[1],
hybrid_index_list[2],
hybrid_force_parameters)
# Otherwise, just add to the nonalchemical force
else:
if angle_index in self.neglected_new_angle_terms:
_logger.debug(f"\t\t\tangle in neglected_new_angle_terms; K_1 is set to zero")
hybrid_force_parameters = [new_angle_parameters[3], 0.0 * new_angle_parameters[4], new_angle_parameters[3], new_angle_parameters[4]]
self._hybrid_system_forces['custom_neglected_new_angle_force'].addAngle(hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_force_parameters)
else:
_logger.debug(f"\t\t\thandle_harmonic_bonds: no softening (to standard angle force)")
self._hybrid_system_forces['standard_angle_force'].addAngle(hybrid_index_list[0], hybrid_index_list[1],
hybrid_index_list[2], new_angle_parameters[3],
new_angle_parameters[4])
if hybrid_index_set.issubset(self._atom_classes['core_atoms']):
_logger.debug(f"\t\thandle_harmonic_angles: angle_index {angle_index} is a core (to custom angle force).")
if not self._find_angle_parameters(self._hybrid_system_forces['core_angle_force'], hybrid_index_list):
_logger.debug(f"\t\t\thandle_harmonic_angles: angle_index {angle_index} NOT previously added...adding now...THERE IS A CONSIDERATION NOT BEING MADE!")
hybrid_force_parameters = [new_angle_parameters[3], 0.0*unit.kilojoule_per_mole/unit.radian**2, new_angle_parameters[3], new_angle_parameters[4]]
self._hybrid_system_forces['core_angle_force'].addAngle(hybrid_index_list[0], hybrid_index_list[1],
hybrid_index_list[2],
hybrid_force_parameters)
def handle_periodic_torsion_force(self):
"""
Handle the torsions in the hybrid system in the same way as the angles and bonds.
"""
old_system_torsion_force = self._old_system_forces['PeriodicTorsionForce']
new_system_torsion_force = self._new_system_forces['PeriodicTorsionForce']
#first, loop through all the torsions in the old system to determine what to do with them. We will only use the
#custom torsion force if all atoms are part of "core." Otherwise, they are either unique to one system or never
#change.
#we need to keep track of what torsions we added so that we do not double count.
added_torsions = []
_logger.info("\thandle_periodic_torsion_forces: looping through old_system to add relevant terms...")
for torsion_index in range(old_system_torsion_force.getNumTorsions()):
_logger.debug(f"\t\thandle_harmonic_torsion_forces: old torsion_index: {torsion_index}")
torsion_parameters = old_system_torsion_force.getTorsionParameters(torsion_index)
_logger.debug(f"\t\thandle_harmonic_torsion_forces: old_torsion parameters: {torsion_parameters}")
#get the indices in the hybrid system
hybrid_index_list = [self._old_to_hybrid_map[old_index] for old_index in torsion_parameters[:4]]
_logger.debug(f"\t\thandle_harmonic_torsion_forces: hybrid torsion index: {hybrid_index_list}")
hybrid_index_set = set(hybrid_index_list)
#if all atoms are in the core, we'll need to find the corresponding parameters in the old system and
#interpolate
if hybrid_index_set.issubset(self._atom_classes['core_atoms']):
_logger.debug(f"\t\thandle_periodic_torsion_forces: torsion_index {torsion_index} is a core (to custom torsion force).")
torsion_indices = torsion_parameters[:4]
#if we've already added these indices (they may appear >once for high periodicities)
#then just continue to the next torsion.
if torsion_indices in added_torsions:
continue #it doesn't matter if the torsion indices are already in the new hybrid torsion force object...some torsions have high periodicity
#get the new indices so we can get the new angle parameters, as well as all old parameters of the old torsion
#The reason we do it like this is to take care of varying periodicity between new and old system.
torsion_parameters_list = self._find_torsion_parameters(old_system_torsion_force, torsion_indices)
_logger.debug(f"\t\thandle_periodic_torsion_forces: old torsion parameters: {torsion_parameters_list}")
new_indices = [self._topology_proposal.old_to_new_atom_map[old_index] for old_index in torsion_indices]
_logger.debug(f"\t\thandle_periodic_torsion_forces: new indices: {new_indices}")
new_torsion_parameters_list = self._find_torsion_parameters(new_system_torsion_force, new_indices)
_logger.debug(f"\t\thandle_periodic_torsion_forces: new torsion parameters: {new_torsion_parameters_list}")
#for old torsions, have the energy scale from full at lambda=0 to off at lambda=1
for torsion_parameters in torsion_parameters_list:
hybrid_force_parameters = [torsion_parameters[4], torsion_parameters[5], torsion_parameters[6], 0.0, 0.0, 0.0]
self._hybrid_system_forces['core_torsion_force'].addTorsion(hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_index_list[3], hybrid_force_parameters)
#for new torsions, have the energy scale from 0 at lambda=0 to full at lambda=1
for torsion_parameters in new_torsion_parameters_list:
#add to the hybrid force:
#the parameters at indices 3 and 4 represent theta0 and k, respectively.
hybrid_force_parameters = [0.0, 0.0, 0.0,torsion_parameters[4], torsion_parameters[5], torsion_parameters[6]]
self._hybrid_system_forces['core_torsion_force'].addTorsion(hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_index_list[3], hybrid_force_parameters)
added_torsions.append(torsion_indices)
#otherwise, just add the parameters to the regular force:
else:
#TODO: make considerations for environment-core valence interactions. THESE will be important in protein mutation studies...
_logger.debug(f"\t\thandle_periodic_torsion_forces: torsion_index {torsion_index} is a core-unique_old or unique_old-unique_old (to standard torsion force).")
self._hybrid_system_forces['standard_torsion_force'].addTorsion(hybrid_index_list[0], hybrid_index_list[1],
hybrid_index_list[2], hybrid_index_list[3], torsion_parameters[4],
torsion_parameters[5], torsion_parameters[6])
_logger.info("\thandle_periodic_torsion_forces: looping through new_system to add relevant terms...")
for torsion_index in range(new_system_torsion_force.getNumTorsions()):
_logger.debug(f"\t\thandle_harmonic_angles: new torsion_index: {torsion_index}")
torsion_parameters = new_system_torsion_force.getTorsionParameters(torsion_index)
#get the indices in the hybrid system:
hybrid_index_list = [self._new_to_hybrid_map[new_index] for new_index in torsion_parameters[:4]]
hybrid_index_set = set(hybrid_index_list)
#if any are part of the unique new atoms, we will add them to the standard torsion force:
if len(hybrid_index_set.intersection(self._atom_classes['unique_new_atoms'])) > 0:
_logger.debug(f"\t\thandle_periodic_torsion_forces: torsion_index {torsion_index} is core-unique_new or unique_new-unique_new (to standard torsion force).")
self._hybrid_system_forces['standard_torsion_force'].addTorsion(hybrid_index_list[0], hybrid_index_list[1],
hybrid_index_list[2], hybrid_index_list[3], torsion_parameters[4],
torsion_parameters[5], torsion_parameters[6])
#another consideration has to be made for when a core-core-core-core torsion force appears in the new_system but is not present in the old system;
#this would not have been caught by the previous `for` loop over the old system core torsions
if hybrid_index_set.issubset(self._atom_classes['core_atoms']):
_logger.debug(f"\t\thandle_periodic_torsion_forces: torsion_index {torsion_index} is a core (to custom torsion force).")
torsion_indices = torsion_parameters[:4]
old_index_list = [self._hybrid_to_old_map[hybr_idx] for hybr_idx in hybrid_index_list]
old_index_list_reversed = [i for i in reversed(old_index_list)]
#if we've already added these indices (they may appear >once for high periodicities)
#then just continue to the next torsion.
if (old_index_list in added_torsions) or (old_index_list_reversed in added_torsions):
continue
new_torsion_parameters_list = self._find_torsion_parameters(new_system_torsion_force, torsion_indices)
for torsion_parameters in new_torsion_parameters_list:
#add to the hybrid force:
#the parameters at indices 3 and 4 represent theta0 and k, respectively.
hybrid_force_parameters = [0.0, 0.0, 0.0,torsion_parameters[4], torsion_parameters[5], torsion_parameters[6]]
self._hybrid_system_forces['core_torsion_force'].addTorsion(hybrid_index_list[0], hybrid_index_list[1], hybrid_index_list[2], hybrid_index_list[3], hybrid_force_parameters)
added_torsions.append(old_index_list)
added_torsions.append(old_index_list_reversed)
def handle_nonbonded(self):
"""
"""
old_system_nonbonded_force = self._old_system_forces['NonbondedForce']
new_system_nonbonded_force = self._new_system_forces['NonbondedForce']
hybrid_to_old_map = self._hybrid_to_old_map
hybrid_to_new_map = self._hybrid_to_new_map
# Define new global parameters for NonbondedForce
self._hybrid_system_forces['standard_nonbonded_force'].addGlobalParameter('lambda_electrostatics_core', 0.0)
self._hybrid_system_forces['standard_nonbonded_force'].addGlobalParameter('lambda_sterics_core', 0.0)
self._hybrid_system_forces['standard_nonbonded_force'].addGlobalParameter("lambda_electrostatics_delete", 0.0)
self._hybrid_system_forces['standard_nonbonded_force'].addGlobalParameter("lambda_electrostatics_insert", 0.0)
#We have to loop through the particles in the system, because nonbonded force does not accept index
_logger.info("\thandle_nonbonded: looping through all particles in hybrid...")
for particle_index in range(self._hybrid_system.getNumParticles()):
if particle_index in self._atom_classes['unique_old_atoms']:
_logger.debug(f"\t\thandle_nonbonded: particle {particle_index} is a unique_old")
#get the parameters in the old system
old_index = hybrid_to_old_map[particle_index]
[charge, sigma, epsilon] = old_system_nonbonded_force.getParticleParameters(old_index)
#add the particle to the hybrid custom sterics and electrostatics.
check_index = self._hybrid_system_forces['core_sterics_force'].addParticle([sigma, epsilon, sigma, 0.0*epsilon, 1, 0]) #turning off sterics in forward direction
assert (particle_index == check_index ), "Attempting to add incorrect particle to hybrid system"
# Add particle to the regular nonbonded force, but Lennard-Jones will be handled by CustomNonbondedForce
check_index = self._hybrid_system_forces['standard_nonbonded_force'].addParticle(charge, sigma, 0.0*epsilon) #add charge to standard_nonbonded force
assert (particle_index == check_index ), "Attempting to add incorrect particle to hybrid system"
# Charge will be turned off at lambda_electrostatics_delete = 0, on at lambda_electrostatics_delete = 1; kill charge with lambda_electrostatics_delete = 0 --> 1
self._hybrid_system_forces['standard_nonbonded_force'].addParticleParameterOffset('lambda_electrostatics_delete', particle_index, -charge, 0*sigma, 0*epsilon)
elif particle_index in self._atom_classes['unique_new_atoms']:
_logger.debug(f"\t\thandle_nonbonded: particle {particle_index} is a unique_new")
#get the parameters in the new system
new_index = hybrid_to_new_map[particle_index]
[charge, sigma, epsilon] = new_system_nonbonded_force.getParticleParameters(new_index)
#add the particle to the hybrid custom sterics and electrostatics
check_index = self._hybrid_system_forces['core_sterics_force'].addParticle([sigma, 0.0*epsilon, sigma, epsilon, 0, 1]) # turning on sterics in forward direction
assert (particle_index == check_index ), "Attempting to add incorrect particle to hybrid system"
# Add particle to the regular nonbonded force, but Lennard-Jones will be handled by CustomNonbondedForce
check_index = self._hybrid_system_forces['standard_nonbonded_force'].addParticle(0.0, sigma, 0.0) #charge starts at zero
assert (particle_index == check_index ), "Attempting to add incorrect particle to hybrid system"
# Charge will be turned off at lambda_electrostatics_insert = 0, on at lambda_electrostatics_insert = 1; add charge with lambda_electrostatics_insert = 0 --> 1
self._hybrid_system_forces['standard_nonbonded_force'].addParticleParameterOffset('lambda_electrostatics_insert', particle_index, +charge, 0, 0)
elif particle_index in self._atom_classes['core_atoms']:
_logger.debug(f"\t\thandle_nonbonded: particle {particle_index} is a core")
#get the parameters in the new and old systems:
old_index = hybrid_to_old_map[particle_index]
[charge_old, sigma_old, epsilon_old] = old_system_nonbonded_force.getParticleParameters(old_index)
new_index = hybrid_to_new_map[particle_index]
[charge_new, sigma_new, epsilon_new] = new_system_nonbonded_force.getParticleParameters(new_index)
#add the particle to the custom forces, interpolating between the two parameters; add steric params and zero electrostatics to core_sterics per usual
check_index = self._hybrid_system_forces['core_sterics_force'].addParticle([sigma_old, epsilon_old, sigma_new, epsilon_new, 0, 0])
assert (particle_index == check_index ), "Attempting to add incorrect particle to hybrid system"
#still add the particle to the regular nonbonded force, but with zeroed out parameters; add old charge to standard_nonbonded and zero sterics
check_index = self._hybrid_system_forces['standard_nonbonded_force'].addParticle(charge_old, 0.5*(sigma_old+sigma_new), 0.0)
assert (particle_index == check_index ), "Attempting to add incorrect particle to hybrid system"
# Charge is charge_old at lambda_electrostatics = 0, charge_new at lambda_electrostatics = 1
# TODO: We could also interpolate the Lennard-Jones here instead of core_sterics force so that core_sterics_force could just be softcore
# interpolate between old and new charge with lambda_electrostatics core; make sure to keep sterics off
self._hybrid_system_forces['standard_nonbonded_force'].addParticleParameterOffset('lambda_electrostatics_core', particle_index, (charge_new - charge_old), 0, 0)
#otherwise, the particle is in the environment
else:
_logger.debug(f"\t\thandle_nonbonded: particle {particle_index} is an envronment")
#the parameters will be the same in new and old system, so just take the old parameters
old_index = hybrid_to_old_map[particle_index]
[charge, sigma, epsilon] = old_system_nonbonded_force.getParticleParameters(old_index)
#add the particle to the hybrid custom sterics, but they dont change; electrostatics are ignored
self._hybrid_system_forces['core_sterics_force'].addParticle([sigma, epsilon, sigma, epsilon, 0, 0])
#add the environment atoms to the regular nonbonded force as well: should we be adding steric terms here, too?
self._hybrid_system_forces['standard_nonbonded_force'].addParticle(charge, sigma, epsilon)
# Now loop pairwise through (unique_old, unique_new) and add exceptions so that they never interact electrostatically (place into Nonbonded Force)
unique_old_atoms = self._atom_classes['unique_old_atoms']
unique_new_atoms = self._atom_classes['unique_new_atoms']
for old in unique_old_atoms:
for new in unique_new_atoms:
self._hybrid_system_forces['standard_nonbonded_force'].addException(old, new, 0.0*unit.elementary_charge**2, 1.0*unit.nanometers, 0.0*unit.kilojoules_per_mole)
self._hybrid_system_forces['core_sterics_force'].addExclusion(old, new) #this is only necessary to avoid the 'All forces must have identical exclusions' rule
_logger.info("\thandle_nonbonded: Handling Interaction Groups...")
self._handle_interaction_groups()
_logger.info("\thandle_nonbonded: Handling Hybrid Exceptions...")
self._handle_hybrid_exceptions()
_logger.info("\thandle_nonbonded: Handling Original Exceptions...")
self._handle_original_exceptions()
def _generate_dict_from_exceptions(self, force):
"""
This is a utility function to generate a dictionary of the form
(particle1_idx, particle2_idx) : [exception parameters]. This will facilitate access and search of exceptions
Parameters
----------
force : openmm.NonbondedForce object
a force containing exceptions
Returns
-------
exceptions_dict : dict
Dictionary of exceptions
"""
exceptions_dict = {}
for exception_index in range(force.getNumExceptions()):
[index1, index2, chargeProd, sigma, epsilon] = force.getExceptionParameters(exception_index)
exceptions_dict[(index1, index2)] = [chargeProd, sigma, epsilon]
_logger.debug(f"\t_generate_dict_from_exceptions: Exceptions Dict: {exceptions_dict}" )
return exceptions_dict
def _handle_interaction_groups(self):
"""
Create the appropriate interaction groups for the custom nonbonded forces. The groups are:
1) Unique-old - core
2) Unique-old - environment
3) Unique-new - core
4) Unique-new - environment
5) Core - environment
6) Core - core
Unique-old and Unique new are prevented from interacting this way, and intra-unique interactions occur in an
unmodified nonbonded force.
Must be called after particles are added to the Nonbonded forces
TODO: we should also be adding the following interaction groups...
7) Unique-new - Unique-new
8) Unique-old - Unique-old
"""
#get the force objects for convenience:
sterics_custom_force = self._hybrid_system_forces['core_sterics_force']
#also prepare the atom classes
core_atoms = self._atom_classes['core_atoms']
unique_old_atoms = self._atom_classes['unique_old_atoms']
unique_new_atoms = self._atom_classes['unique_new_atoms']
environment_atoms = self._atom_classes['environment_atoms']
sterics_custom_force.addInteractionGroup(unique_old_atoms, core_atoms)
sterics_custom_force.addInteractionGroup(unique_old_atoms, environment_atoms)
sterics_custom_force.addInteractionGroup(unique_new_atoms, core_atoms)
sterics_custom_force.addInteractionGroup(unique_new_atoms, environment_atoms)
sterics_custom_force.addInteractionGroup(core_atoms, environment_atoms)
sterics_custom_force.addInteractionGroup(core_atoms, core_atoms)
sterics_custom_force.addInteractionGroup(unique_new_atoms, unique_new_atoms)
sterics_custom_force.addInteractionGroup(unique_old_atoms, unique_old_atoms)
def _handle_hybrid_exceptions(self):
"""
Instead of excluding interactions that shouldn't occur, we provide exceptions for interactions that were zeroed
out but should occur.
Returns
-------
"""
old_system_nonbonded_force = self._old_system_forces['NonbondedForce']
new_system_nonbonded_force = self._new_system_forces['NonbondedForce']
import itertools
#prepare the atom classes
unique_old_atoms = self._atom_classes['unique_old_atoms']
unique_new_atoms = self._atom_classes['unique_new_atoms']
#get the list of interaction pairs for which we need to set exceptions:
unique_old_pairs = list(itertools.combinations(unique_old_atoms, 2))
unique_new_pairs = list(itertools.combinations(unique_new_atoms, 2))
#add back the interactions of the old unique atoms, unless there are exceptions
for atom_pair in unique_old_pairs:
#since the pairs are indexed in the dictionary by the old system indices, we need to convert
old_index_atom_pair = (self._hybrid_to_old_map[atom_pair[0]], self._hybrid_to_old_map[atom_pair[1]])
#now we check if the pair is in the exception dictionary
if old_index_atom_pair in self._old_system_exceptions:
_logger.debug(f"\t\thandle_nonbonded: _handle_hybrid_exceptions: {old_index_atom_pair} is an old system exception")
[chargeProd, sigma, epsilon] = self._old_system_exceptions[old_index_atom_pair]
if self._interpolate_14s: #if we are interpolating 1,4 exceptions then we have to
self._hybrid_system_forces['standard_nonbonded_force'].addException(atom_pair[0], atom_pair[1], chargeProd*0.0, sigma, epsilon*0.0)
else:
self._hybrid_system_forces['standard_nonbonded_force'].addException(atom_pair[0], atom_pair[1], chargeProd, sigma, epsilon)
self._hybrid_system_forces['core_sterics_force'].addExclusion(atom_pair[0], atom_pair[1]) # add exclusion to ensure exceptions are consistent
#check if the pair is in the reverse order and use that if so
elif old_index_atom_pair[::-1] in self._old_system_exceptions:
_logger.debug(f"\t\thandle_nonbonded: _handle_hybrid_exceptions: {old_index_atom_pair[::-1]} is an old system exception")
[chargeProd, sigma, epsilon] = self._old_system_exceptions[old_index_atom_pair[::-1]]
if self._interpolate_14s: #if we are interpolating 1,4 exceptions then we have to
self._hybrid_system_forces['standard_nonbonded_force'].addException(atom_pair[0], atom_pair[1], chargeProd*0.0, sigma, epsilon*0.0)
else:
self._hybrid_system_forces['standard_nonbonded_force'].addException(atom_pair[0], atom_pair[1], chargeProd, sigma, epsilon)
self._hybrid_system_forces['core_sterics_force'].addExclusion(atom_pair[0], atom_pair[1]) # add exclusion to ensure exceptions are consistent
#If it's not handled by an exception in the original system, we just add the regular parameters as an exception
# TODO: this implies that the old-old nonbonded interactions (those which are not exceptions) are always self-interacting throughout lambda protocol...
# else:
# _logger.info(f"\t\thandle_nonbonded: _handle_hybrid_exceptions: {old_index_atom_pair} is NOT an old exception...perhaps this is a problem!")
# [charge0, sigma0, epsilon0] = self._old_system_forces['NonbondedForce'].getParticleParameters(old_index_atom_pair[0])
# [charge1, sigma1, epsilon1] = self._old_system_forces['NonbondedForce'].getParticleParameters(old_index_atom_pair[1])
# chargeProd = charge0*charge1
# epsilon = unit.sqrt(epsilon0*epsilon1)
# sigma = 0.5*(sigma0+sigma1)
# self._hybrid_system_forces['standard_nonbonded_force'].addException(atom_pair[0], atom_pair[1], chargeProd, sigma, epsilon)
# self._hybrid_system_forces['core_sterics_force'].addExclusion(atom_pair[0], atom_pair[1]) # add exclusion to ensure exceptions are consistent
#add back the interactions of the new unique atoms, unless there are exceptions
for atom_pair in unique_new_pairs:
#since the pairs are indexed in the dictionary by the new system indices, we need to convert
new_index_atom_pair = (self._hybrid_to_new_map[atom_pair[0]], self._hybrid_to_new_map[atom_pair[1]])
#now we check if the pair is in the exception dictionary
if new_index_atom_pair in self._new_system_exceptions:
_logger.debug(f"\t\thandle_nonbonded: _handle_hybrid_exceptions: {new_index_atom_pair} is a new system exception")
[chargeProd, sigma, epsilon] = self._new_system_exceptions[new_index_atom_pair]
if self._interpolate_14s:
self._hybrid_system_forces['standard_nonbonded_force'].addException(atom_pair[0], atom_pair[1], chargeProd*0.0, sigma, epsilon*0.0)
else:
self._hybrid_system_forces['standard_nonbonded_force'].addException(atom_pair[0], atom_pair[1], chargeProd, sigma, epsilon)
self._hybrid_system_forces['core_sterics_force'].addExclusion(atom_pair[0], atom_pair[1])
#check if the pair is present in the reverse order and use that if so
elif new_index_atom_pair[::-1] in self._new_system_exceptions:
_logger.debug(f"\t\thandle_nonbonded: _handle_hybrid_exceptions: {new_index_atom_pair[::-1]} is a new system exception")
[chargeProd, sigma, epsilon] = self._new_system_exceptions[new_index_atom_pair[::-1]]
if self._interpolate_14s:
self._hybrid_system_forces['standard_nonbonded_force'].addException(atom_pair[0], atom_pair[1], chargeProd*0.0, sigma, epsilon*0.0)
else:
self._hybrid_system_forces['standard_nonbonded_force'].addException(atom_pair[0], atom_pair[1], chargeProd, sigma, epsilon)
self._hybrid_system_forces['core_sterics_force'].addExclusion(atom_pair[0], atom_pair[1])
#If it's not handled by an exception in the original system, we just add the regular parameters as an exception
# else:
# _logger.info(f"\t\thandle_nonbonded: _handle_hybrid_exceptions: {new_index_atom_pair} is NOT a new exception...perhaps this is a problem!")
# [charge0, sigma0, epsilon0] = self._new_system_forces['NonbondedForce'].getParticleParameters(new_index_atom_pair[0])
# [charge1, sigma1, epsilon1] = self._new_system_forces['NonbondedForce'].getParticleParameters(new_index_atom_pair[1])
# chargeProd = charge0*charge1
# epsilon = unit.sqrt(epsilon0*epsilon1)
# sigma = 0.5*(sigma0+sigma1)
# self._hybrid_system_forces['standard_nonbonded_force'].addException(atom_pair[0], atom_pair[1], chargeProd, sigma, epsilon)
# self._hybrid_system_forces['core_sterics_force'].addExclusion(atom_pair[0], atom_pair[1]) # add exclusion to ensure exceptions are consistent
def _handle_original_exceptions(self):
"""
This method ensures that exceptions present in the original systems are present in the hybrid appropriately.
"""
#get what we need to find the exceptions from the new and old systems:
old_system_nonbonded_force = self._old_system_forces['NonbondedForce']
new_system_nonbonded_force = self._new_system_forces['NonbondedForce']
hybrid_to_old_map = {value: key for key, value in self._old_to_hybrid_map.items()}
hybrid_to_new_map = {value: key for key, value in self._new_to_hybrid_map.items()}
#first, loop through the old system's exceptions and add them to the hybrid appropriately:
for exception_pair, exception_parameters in self._old_system_exceptions.items():
[index1_old, index2_old] = exception_pair
[chargeProd_old, sigma_old, epsilon_old] = exception_parameters
#get hybrid indices:
index1_hybrid = self._old_to_hybrid_map[index1_old]
index2_hybrid = self._old_to_hybrid_map[index2_old]
index_set = {index1_hybrid, index2_hybrid}
#in this case, the interaction is only covered by the regular nonbonded force, and as such will be copied to that force
#in the unique-old case, it is handled elsewhere due to internal peculiarities regarding exceptions
if index_set.issubset(self._atom_classes['environment_atoms']):
_logger.debug(f"\t\thandle_nonbonded: _handle_original_exceptions: {exception_pair} is an environment exception pair")
self._hybrid_system_forces['standard_nonbonded_force'].addException(index1_hybrid, index2_hybrid, chargeProd_old, sigma_old, epsilon_old)
self._hybrid_system_forces['core_sterics_force'].addExclusion(index1_hybrid, index2_hybrid)
#we have already handled unique old - unique old exceptions
elif len(index_set.intersection(self._atom_classes['unique_old_atoms'])) == 2:
_logger.debug(f"\t\thandle_nonbonded: _handle_original_exceptions: {exception_pair} is a unique_old-unique_old exception pair (already handled).")
continue
#otherwise, check if one of the atoms in the set is in the unique_old_group and the other is not:
elif len(index_set.intersection(self._atom_classes['unique_old_atoms'])) == 1:
_logger.debug(f"\t\thandle_nonbonded: _handle_original_exceptions: {exception_pair} is a unique_old-core or unique_old-environment exception pair.")
if self._interpolate_14s:
self._hybrid_system_forces['standard_nonbonded_force'].addException(index1_hybrid, index2_hybrid, chargeProd_old*0.0, sigma_old, epsilon_old*0.0)
else:
self._hybrid_system_forces['standard_nonbonded_force'].addException(index1_hybrid, index2_hybrid, chargeProd_old, sigma_old, epsilon_old)
self._hybrid_system_forces['core_sterics_force'].addExclusion(index1_hybrid, index2_hybrid)
#If the exception particles are neither solely old unique, solely environment, nor contain any unique old atoms, they are either core/environment or core/core
#In this case, we need to get the parameters from the exception in the other (new) system, and interpolate between the two
else:
_logger.debug(f"\t\thandle_nonbonded: _handle_original_exceptions: {exception_pair} is a core-core or core-environment exception pair.")
#first get the new indices.
index1_new = hybrid_to_new_map[index1_hybrid]
index2_new = hybrid_to_new_map[index2_hybrid]
#get the exception parameters:
new_exception_parms= self._find_exception(new_system_nonbonded_force, index1_new, index2_new)
#if there's no new exception, then we should just set the exception parameters to be the nonbonded parameters
if not new_exception_parms:
[charge1_new, sigma1_new, epsilon1_new] = new_system_nonbonded_force.getParticleParameters(index1_new)
[charge2_new, sigma2_new, epsilon2_new] = new_system_nonbonded_force.getParticleParameters(index2_new)
chargeProd_new = charge1_new * charge2_new
sigma_new = 0.5 * (sigma1_new + sigma2_new)
epsilon_new = unit.sqrt(epsilon1_new*epsilon2_new)
else:
[index1_new, index2_new, chargeProd_new, sigma_new, epsilon_new] = new_exception_parms
#interpolate between old and new
exception_index = self._hybrid_system_forces['standard_nonbonded_force'].addException(index1_hybrid, index2_hybrid, chargeProd_old, sigma_old, epsilon_old)
self._hybrid_system_forces['standard_nonbonded_force'].addExceptionParameterOffset('lambda_electrostatics_core', exception_index, (chargeProd_new - chargeProd_old), 0, 0)
self._hybrid_system_forces['standard_nonbonded_force'].addExceptionParameterOffset('lambda_sterics_core', exception_index, 0, (sigma_new - sigma_old), (epsilon_new - epsilon_old))
self._hybrid_system_forces['core_sterics_force'].addExclusion(index1_hybrid, index2_hybrid)
#now, loop through the new system to collect remaining interactions. The only that remain here are
#uniquenew-uniquenew, uniquenew-core, and uniquenew-environment. There might also be core-core, since not all
#core-core exceptions exist in both
for exception_pair, exception_parameters in self._new_system_exceptions.items():
[index1_new, index2_new] = exception_pair
[chargeProd_new, sigma_new, epsilon_new] = exception_parameters
#get hybrid indices:
index1_hybrid = self._new_to_hybrid_map[index1_new]
index2_hybrid = self._new_to_hybrid_map[index2_new]
index_set = {index1_hybrid, index2_hybrid}
#if it's a subset of unique_new_atoms, then this is an intra-unique interaction and should have its exceptions
#specified in the regular nonbonded force. However, this is handled elsewhere as above due to pecularities with exception handling
if index_set.issubset(self._atom_classes['unique_new_atoms']):
_logger.debug(f"\t\thandle_nonbonded: _handle_original_exceptions: {exception_pair} is a unique_new-unique_new exception pair (already handled).")
continue
#look for the final class- interactions between uniquenew-core and uniquenew-environment. They are treated
#similarly: they are simply on and constant the entire time (as a valence term)
elif len(index_set.intersection(self._atom_classes['unique_new_atoms'])) > 0:
_logger.debug(f"\t\thandle_nonbonded: _handle_original_exceptions: {exception_pair} is a unique_new-core or unique_new-environment exception pair.")
if self._interpolate_14s:
self._hybrid_system_forces['standard_nonbonded_force'].addException(index1_hybrid, index2_hybrid, chargeProd_new*0.0, sigma_new, epsilon_new*0.0)
else:
self._hybrid_system_forces['standard_nonbonded_force'].addException(index1_hybrid, index2_hybrid, chargeProd_new, sigma_new, epsilon_new)
self._hybrid_system_forces['core_sterics_force'].addExclusion(index1_hybrid, index2_hybrid)
#however, there may be a core exception that exists in one system but not the other (ring closure)
elif index_set.issubset(self._atom_classes['core_atoms']):
_logger.debug(f"\t\thandle_nonbonded: _handle_original_exceptions: {exception_pair} is a core-core exception pair.")
# get the old indices
try:
index1_old = self._topology_proposal.new_to_old_atom_map[index1_new]
index2_old = self._topology_proposal.new_to_old_atom_map[index2_new]
except KeyError:
continue
#see if it's also in the old nonbonded force. if it is, then we don't need to add it.
#but if it's not, we need to interpolate
if not self._find_exception(old_system_nonbonded_force, index1_old, index2_old):
[charge1_old, sigma1_old, epsilon1_old] = old_system_nonbonded_force.getParticleParameters(index1_old)
[charge2_old, sigma2_old, epsilon2_old] = old_system_nonbonded_force.getParticleParameters(index2_old)
chargeProd_old = charge1_old*charge2_old
sigma_old = 0.5 * (sigma1_old + sigma2_old)
epsilon_old = unit.sqrt(epsilon1_old*epsilon2_old)
exception_index = self._hybrid_system_forces['standard_nonbonded_force'].addException(index1_hybrid,
index2_hybrid,
chargeProd_old,
sigma_old,
epsilon_old)
self._hybrid_system_forces['standard_nonbonded_force'].addExceptionParameterOffset(
'lambda_electrostatics_core', exception_index, (chargeProd_new - chargeProd_old), 0, 0)
self._hybrid_system_forces['standard_nonbonded_force'].addExceptionParameterOffset('lambda_sterics_core',
exception_index,
0, (sigma_new - sigma_old),
(epsilon_new - epsilon_old))
self._hybrid_system_forces['core_sterics_force'].addExclusion(index1_hybrid, index2_hybrid)
def handle_old_new_exceptions(self):
"""
Find the exceptions associated with old-old and old-core interactions, as well as new-new and new-core interactions. Theses exceptions will be placed in
CustomBondedForce that will interpolate electrostatics and a softcore potential.
"""
from openmmtools.constants import ONE_4PI_EPS0 # OpenMM constant for Coulomb interactions (implicitly in md_unit_system units)
old_new_nonbonded_exceptions = "U_electrostatics + U_sterics;"
if self._softcore_LJ_v2:
old_new_nonbonded_exceptions += "U_sterics = select(step(r - r_LJ), 4*epsilon*x*(x-1.0), U_sterics_quad);"
old_new_nonbonded_exceptions += f"U_sterics_quad = Force*(((r - r_LJ)^2)/2 - (r - r_LJ)) + U_sterics_cut;"
old_new_nonbonded_exceptions += f"U_sterics_cut = 4*epsilon*((sigma/r_LJ)^6)*(((sigma/r_LJ)^6) - 1.0);"
old_new_nonbonded_exceptions += f"Force = -4*epsilon*((-12*sigma^12)/(r_LJ^13) + (6*sigma^6)/(r_LJ^7));"
old_new_nonbonded_exceptions += f"x = (sigma/r)^6;"
old_new_nonbonded_exceptions += f"r_LJ = softcore_alpha*((26/7)*(sigma^6)*lambda_sterics_deprecated)^(1/6);"
old_new_nonbonded_exceptions += f"lambda_sterics_deprecated = new_interaction*(1.0 - lambda_sterics_insert) + old_interaction*lambda_sterics_delete;"
else:
old_new_nonbonded_exceptions += "U_sterics = 4*epsilon*x*(x-1.0); x = (sigma/reff_sterics)^6;"
old_new_nonbonded_exceptions += "reff_sterics = sigma*((softcore_alpha*lambda_alpha + (r/sigma)^6))^(1/6);"
old_new_nonbonded_exceptions += "reff_sterics = sigma*((softcore_alpha*lambda_alpha + (r/sigma)^6))^(1/6);" # effective softcore distance for sterics
old_new_nonbonded_exceptions += "lambda_alpha = new_interaction*(1-lambda_sterics_insert) + old_interaction*lambda_sterics_delete;"
old_new_nonbonded_exceptions += "U_electrostatics = (lambda_electrostatics_insert * unique_new + unique_old * (1 - lambda_electrostatics_delete)) * ONE_4PI_EPS0*chargeProd/r;"
old_new_nonbonded_exceptions += "ONE_4PI_EPS0 = %f;" % ONE_4PI_EPS0
old_new_nonbonded_exceptions += "epsilon = (1-lambda_sterics)*epsilonA + lambda_sterics*epsilonB;" #interpolation
old_new_nonbonded_exceptions += "sigma = (1-lambda_sterics)*sigmaA + lambda_sterics*sigmaB;"
old_new_nonbonded_exceptions += "lambda_sterics = new_interaction*lambda_sterics_insert + old_interaction*lambda_sterics_delete;"
old_new_nonbonded_exceptions += "new_interaction = delta(1-unique_new); old_interaction = delta(1-unique_old);"
nonbonded_exceptions_force = openmm.CustomBondForce(old_new_nonbonded_exceptions)
self._hybrid_system.addForce(nonbonded_exceptions_force)
_logger.info(f"\thandle_old_new_exceptions: {nonbonded_exceptions_force} added to hybrid system")
#for reference, set name in force dict
self._hybrid_system_forces['old_new_exceptions_force'] = nonbonded_exceptions_force
if self._softcore_LJ_v2:
nonbonded_exceptions_force.addGlobalParameter("softcore_alpha", self._softcore_LJ_v2_alpha)
else:
nonbonded_exceptions_force.addGlobalParameter("softcore_alpha", self.softcore_alpha)
nonbonded_exceptions_force.addGlobalParameter("lambda_electrostatics_insert", 0.0) # electrostatics
nonbonded_exceptions_force.addGlobalParameter("lambda_electrostatics_delete", 0.0) # electrostatics
nonbonded_exceptions_force.addGlobalParameter("lambda_sterics_insert", 0.0) # sterics insert
nonbonded_exceptions_force.addGlobalParameter("lambda_sterics_delete", 0.0) # sterics delete
for parameter in ['chargeProd','sigmaA', 'epsilonA', 'sigmaB', 'epsilonB', 'unique_old', 'unique_new']:
nonbonded_exceptions_force.addPerBondParameter(parameter)
#prepare for exceptions loop by grabbing nonbonded forces, hybrid_to_old/new maps
old_system_nonbonded_force = self._old_system_forces['NonbondedForce']
new_system_nonbonded_force = self._new_system_forces['NonbondedForce']
hybrid_to_old_map = {value: key for key, value in self._old_to_hybrid_map.items()}
hybrid_to_new_map = {value: key for key, value in self._new_to_hybrid_map.items()}
#first, loop through the old system's exceptions and add them to the hybrid appropriately:
for exception_pair, exception_parameters in self._old_system_exceptions.items():
[index1_old, index2_old] = exception_pair
[chargeProd_old, sigma_old, epsilon_old] = exception_parameters
#get hybrid indices:
index1_hybrid = self._old_to_hybrid_map[index1_old]
index2_hybrid = self._old_to_hybrid_map[index2_old]
index_set = {index1_hybrid, index2_hybrid}
#otherwise, check if one of the atoms in the set is in the unique_old_group and the other is not:
if len(index_set.intersection(self._atom_classes['unique_old_atoms'])) > 0 and (chargeProd_old.value_in_unit_system(unit.md_unit_system) != 0.0 or epsilon_old.value_in_unit_system(unit.md_unit_system) != 0.0):
_logger.debug(f"\t\thandle_old_new_exceptions: {exception_pair} is a unique_old exception pair.")
if self._interpolate_14s:
# if we are interpolating 1,4s, then we anneal this term off; otherwise, the exception force is constant and already handled in the standard nonbonded force
nonbonded_exceptions_force.addBond(index1_hybrid, index2_hybrid, [chargeProd_old, sigma_old, epsilon_old, sigma_old, epsilon_old*0.0, 1, 0])
#next, loop through the new system's exceptions and add them to the hybrid appropriately
for exception_pair, exception_parameters in self._new_system_exceptions.items():
[index1_new, index2_new] = exception_pair
[chargeProd_new, sigma_new, epsilon_new] = exception_parameters
#get hybrid indices:
index1_hybrid = self._new_to_hybrid_map[index1_new]
index2_hybrid = self._new_to_hybrid_map[index2_new]
index_set = {index1_hybrid, index2_hybrid}
#look for the final class- interactions between uniquenew-core and uniquenew-environment. They are treated
#similarly: they are simply on and constant the entire time (as a valence term)
if len(index_set.intersection(self._atom_classes['unique_new_atoms'])) > 0 and (chargeProd_new.value_in_unit_system(unit.md_unit_system) != 0.0 or epsilon_new.value_in_unit_system(unit.md_unit_system) != 0.0):
_logger.debug(f"\t\thandle_old_new_exceptions: {exception_pair} is a unique_new exception pair.")
if self._interpolate_14s:
# if we are interpolating 1,4s, then we anneal this term on; otherwise, the exception force is constant and already handled in the standard nonbonded force
nonbonded_exceptions_force.addBond(index1_hybrid, index2_hybrid, [chargeProd_new, sigma_new, epsilon_new*0.0, sigma_new, epsilon_new, 0, 1])
def _find_exception(self, force, index1, index2):
"""
Find the exception that corresponds to the given indices in the given system
Parameters
----------
force : openmm.NonbondedForce object
System containing the exceptions
index1 : int
The index of the first atom (order is unimportant)
index2 : int
The index of the second atom (order is unimportant)
Returns
-------
exception_parameters : list
List of exception parameters
"""
index_set = {index1, index2}
#loop through the exceptions and try to find one matching the criteria
for exception_idx in range(force.getNumExceptions()):
exception_parameters = force.getExceptionParameters(exception_idx)
if index_set==set(exception_parameters[:2]):
return exception_parameters
return []
def _compute_hybrid_positions(self):
"""
The positions of the hybrid system. Dimensionality is (n_environment + n_core + n_old_unique + n_new_unique)
The positions are assigned by first copying all the mapped positions from the old system in, then copying the
mapped positions from the new system. This means that there is an assumption that the positions common to old
and new are the same (which is the case for perses as-is).
Returns
-------
hybrid_positions : np.ndarray [n, 3]
Positions of the hybrid system, in nm
"""
#get unitless positions
old_positions_without_units = np.array(self._old_positions.value_in_unit(unit.nanometer))
new_positions_without_units = np.array(self._new_positions.value_in_unit(unit.nanometer))
#determine the number of particles in the system
n_atoms_hybrid = self._hybrid_system.getNumParticles()
#initialize an array for hybrid positions
hybrid_positions_array = np.zeros([n_atoms_hybrid, 3])
#loop through the old system indices, and assign positions.
for old_index, hybrid_index in self._old_to_hybrid_map.items():
hybrid_positions_array[hybrid_index, :] = old_positions_without_units[old_index, :]
#Do the same for new indices. Note that this overwrites some coordinates, but as stated above, the assumption
#is that these are the same.
for new_index, hybrid_index in self._new_to_hybrid_map.items():
hybrid_positions_array[hybrid_index, :] = new_positions_without_units[new_index, :]
return unit.Quantity(hybrid_positions_array, unit=unit.nanometers)
def _create_topology(self):
"""
Create an mdtraj topology corresponding to the hybrid system.
This is purely for writing out trajectories--it is not expected to be parameterized.
Returns
-------
hybrid_topology : mdtraj.Topology
"""
#first, make an md.Topology of the old system:
old_topology = md.Topology.from_openmm(self._topology_proposal.old_topology)
#now make a copy for the hybrid:
hybrid_topology = copy.deepcopy(old_topology)
#next, make a topology of the new system:
new_topology = md.Topology.from_openmm(self._topology_proposal.new_topology)
added_atoms = dict()
#get the core atoms in the new index system (as opposed to the hybrid index system). We will need this later
core_atoms_new_indices = {self._hybrid_to_new_map[core_atom] for core_atom in self._atom_classes['core_atoms']}
#now, add each unique new atom to the topology (this is the same order as the system)
for particle_idx in self._topology_proposal.unique_new_atoms:
new_particle_hybrid_idx = self._new_to_hybrid_map[particle_idx]
new_system_atom = new_topology.atom(particle_idx)
#first, we get the residue in the new system associated with this atom
new_system_residue = new_system_atom.residue
#next, we have to enumerate the other atoms in that residue to find mapped atoms
new_system_atom_set = {atom.index for atom in new_system_residue.atoms}
#Now, we find the subset of atoms that are mapped. These must be in the "core" category, since they are mapped
#and part of a changing residue
mapped_new_atom_indices = core_atoms_new_indices.intersection(new_system_atom_set)
#Now get the old indices of the above atoms so that we can find the appropriate residue in the old system
#for this we can use the new to old atom map
mapped_old_atom_indices = [self._topology_proposal.new_to_old_atom_map[atom_idx] for atom_idx in mapped_new_atom_indices]
#we can just take the first one--they all have the same residue
first_mapped_old_atom_index = mapped_old_atom_indices[0]
#get the atom object corresponding to this index from the hybrid (which is a deepcopy of the old)
mapped_hybrid_system_atom = hybrid_topology.atom(first_mapped_old_atom_index)
#get the residue that is relevant to this atom
mapped_residue = mapped_hybrid_system_atom.residue
#add the atom using the mapped residue
added_atoms[new_particle_hybrid_idx] = hybrid_topology.add_atom(new_system_atom.name, new_system_atom.element, mapped_residue)
#now loop through the bonds in the new system, and if the bond contains a unique new atom, then add it to the hybrid topology
for (atom1, atom2) in new_topology.bonds:
atom1_index_in_hybrid = self._new_to_hybrid_map[atom1.index]
atom2_index_in_hybrid = self._new_to_hybrid_map[atom2.index]
#if at least one atom is in the unique new class, we need to add it to the hybrid system
if atom1_index_in_hybrid in self._atom_classes['unique_new_atoms'] or atom2_index_in_hybrid in self._atom_classes['unique_new_atoms']:
if atom1.index in self._atom_classes['unique_new_atoms']:
atom1_to_bond = added_atoms[atom1.index]
else:
atom1_to_bond = atom1
if atom2.index in self._atom_classes['unique_new_atoms']:
atom2_to_bond = added_atoms[atom2.index]
else:
atom2_to_bond = atom2
hybrid_topology.add_bond(atom1_to_bond, atom2_to_bond)
return hybrid_topology
def old_positions(self, hybrid_positions):
"""
Get the positions corresponding to the old system
Parameters
----------
hybrid_positions : [n, 3] np.ndarray with unit
The positions of the hybrid system
Returns
-------
old_positions : [m, 3] np.ndarray with unit
The positions of the old system
"""
n_atoms_old = self._topology_proposal.n_atoms_old
old_positions = unit.Quantity(np.zeros([n_atoms_old, 3]), unit=unit.nanometer)
for idx in range(n_atoms_old):
old_positions[idx, :] = hybrid_positions[idx, :]
return old_positions
def new_positions(self, hybrid_positions):
"""
Get the positions corresponding to the new system.
Parameters
----------
hybrid_positions : [n, 3] np.ndarray with unit
The positions of the hybrid system
Returns
-------
new_positions : [m, 3] np.ndarray with unit
The positions of the new system
"""
n_atoms_new = self._topology_proposal.n_atoms_new
new_positions = unit.Quantity(np.zeros([n_atoms_new, 3]), unit=unit.nanometer)
for idx in range(n_atoms_new):
new_positions[idx, :] = hybrid_positions[self._new_to_hybrid_map[idx], :]
return new_positions
@property
def hybrid_system(self):
"""
The hybrid system.
Returns
-------
hybrid_system : openmm.System
The system representing a hybrid between old and new topologies
"""
return self._hybrid_system
@property
def new_to_hybrid_atom_map(self):
"""
Give a dictionary that maps new system atoms to the hybrid system.
Returns
-------
new_to_hybrid_atom_map : dict of {int, int}
The mapping of atoms from the new system to the hybrid
"""
return self._new_to_hybrid_map
@property
def old_to_hybrid_atom_map(self):
"""
Give a dictionary that maps old system atoms to the hybrid system.
Returns
-------
old_to_hybrid_atom_map : dict of {int, int}
The mapping of atoms from the old system to the hybrid
"""
return self._old_to_hybrid_map
@property
def hybrid_positions(self):
"""
The positions of the hybrid system. Dimensionality is (n_environment + n_core + n_old_unique + n_new_unique)
The positions are assigned by first copying all the mapped positions from the old system in, then copying the
mapped positions from the new system.
Returns
-------
hybrid_positions : [n, 3] Quantity nanometers
"""
return self._hybrid_positions
@property
def hybrid_topology(self):
"""
An MDTraj hybrid topology for the purpose of writing out trajectories. Note that we do not expect this to be
able to be parameterized by the openmm forcefield class.
Returns
-------
hybrid_topology : mdtraj.Topology
"""
return self._hybrid_topology
@property
def omm_hybrid_topology(self):
"""
An OpenMM format of the hybrid topology. Also cannot be used to parameterize system, only to write out trajectories.
Returns
-------
hybrid_topology : simtk.openmm.app.Topology
"""
return md.Topology.to_openmm(self._hybrid_topology)
|
\documentclass{beamer}
\usetheme[headernav]{TACC} %%Drop the 'headernav' if you don't like
%%the stuff at the top of your slide
\usepackage{amsmath,amssymb,amsthm}
\usepackage{alltt}
\usepackage{graphicx}
\title{SC15: Lmod Hands on Tutorial}
\author{Robert McLay}
\institute{The Texas Advanced Computing Center}
\date{November 18, 2015} %% Use this if you want to fix the date in
%% stone rather than use \today
\newcommand{\bfnabla}{\mbox{\boldmath$\nabla$}}
\newcommand{\laplacian}[1]{\bfnabla^2 #1}
\newcommand{\grad}[1]{\bfnabla #1}
\newcommand{\tgrad}[1]{\bfnabla^T #1}
\newcommand{\dvg}[1]{\bfnabla \cdot #1}
\newcommand{\curl}[1]{\bfnabla \times #1}
\newcommand{\lap}[1]{\bfnabla^2 #1}
\begin{document}
\begin{frame}
\titlepage
\end{frame}
\section{Introduction}
\begin{frame}{Introduction}
\begin{itemize}
\item Welcome to the 5th annual TACC Booth Talk
\item Guest Speaker: Kenneth Hoste Univ of Ghent.
\item Lmod Hands On Tutorial: Chose your own Topic (Adventure?)
\end{itemize}
\end{frame}
\begin{frame}{Lmod's Big Ideas}
\begin{itemize}
\item A modern replacement for a tried and true concept.
\item The guiding principal: ``Make life easier w/o getting in
the way.''
\end{itemize}
\end{frame}
\begin{frame}{Why You Might Want To Use Lmod}
\begin{itemize}
\item Active Development; Frequent Releases; Bug fixes.
\item Vibrant Community
\item It is used from Norway to Isreal to New Zealand from Stanford to MIT to NASA
\item Enjoy many capabilities w/o changing a single module file
\item Debian and Fedora packages available
\item Many more advantages when you're ready
\item It is what we use every day!
\end{itemize}
\end{frame}
\begin{frame}{Guest Speaker: Kenneth Hoste from Univ. of Ghent, Belgium}
\begin{itemize}
\item Why I like Lmod and why you should too!
\end{itemize}
\end{frame}
\begin{frame}{Lmod Hands on Tutorial}
\begin{itemize}
\item Chose your own Topic(s)!
\item We have create a Virtual Box VM for you to test out
\item The VM runs under Window, Mac OS X, Linux
\item Comes with working Lmod, XALT, Shell Startup Debug, ...
\end{itemize}
\end{frame}
\begin{frame}{Topic Choices}
\begin{enumerate}
\item Using Lmod: An introduction to Lmod
\item Create personal modules for your own software
\item Installing Lmod in your account
\item How to install a system spider cache
\item How to write modulefiles for a system
\end{enumerate}
\end{frame}
\begin{frame}{How to get started}
\begin{itemize}
\item Grab a USB Thumbdrive
\item Install VirtualBox from Drive
\item File $rightarrow$ Import Appliance $rightarrow$
XALT-Lmod.ova
\item Click on XALT-Lmod.ova and then click on start arrow
\item Account name is xalt, password is xalt
\end{itemize}
\end{frame}
\begin{frame}{Hands On Lmod}
\begin{itemize}
\item Please Try out one or more of the Topics
\item Please feel free to ask question of me or my colleagues
\end{itemize}
\end{frame}
\end{document}
|
function allornothing(network::AbstractNetwork,r,trips::Vector,costs::Vector)
#nlinks = numlinks(network)
zoneids = id.(zones(network))
flows = zero(costs)
_, parentvec = dijkstra(network, r, costs)
for j in zoneids
t = trips[j]
if isapprox(t, 0.) | (r == j)
continue
end
# Finding the shortest path
p = pathto(parentvec, j)
# Assigning flows
for l in p
flows[idx(network, l)] += t
end
end
return flows
end
function allornothing(network::AbstractNetwork,
trips::Matrix{U},
costs::Vector{T};
basedon::Symbol = :link) where {T<:Real, U<:Real}
# Initialization
nnodes, nzones = numnodes(network), numzones(network)
nlinks = length(costs)
zonelist = zones(network)
zoneids = id.(zonelist)
flows = (basedon == :link) ? zeros(nlinks) : (basedon == :origin) ? zeros(nlinks, nzones) : error("Invalid input!")
for (i,z) in enumerate(zoneids)
if basedon == :link
flows += allornothing(network, z, trips[z,:], costs)
else
flows[:,i] += allornothing(network, z, trips[z,:], costs)
end
end
return flows
end
allornothing(network::AbstractNetwork, trips::AbstractMatrix{T}, costfn::CostFunction; basedon::Symbol = :link) where {T<:Real} = allornothing(network, trips, costfn(zeros(numlinks(network))).costs; basedon=basedon)
|
C-----------------------------------------------------------------------
SUBROUTINE SPTRAND(IROMB,MAXWV,IDRT,IMAX,JMAX,KMAX,
& IPRIME,ISKIP,JNSKIP,JSSKIP,KWSKIP,KGSKIP,
& JBEG,JEND,JCPU,
& WAVE,GRIDMN,GRIDXN,GRIDXS,GRIDYN,GRIDYS,IDIR)
C$$$ SUBPROGRAM DOCUMENTATION BLOCK
C
C SUBPROGRAM: SPTRAND PERFORM A GRADIENT SPHERICAL TRANSFORM
C PRGMMR: IREDELL ORG: W/NMC23 DATE: 96-02-29
C
C ABSTRACT: THIS SUBPROGRAM PERFORMS A SPHERICAL TRANSFORM
C BETWEEN SPECTRAL COEFFICIENTS OF SCALAR FIELDS
C AND THEIR MEANS AND GRADIENTS ON A GLOBAL CYLINDRICAL GRID.
C THE WAVE-SPACE CAN BE EITHER TRIANGULAR OR RHOMBOIDAL.
C THE GRID-SPACE CAN BE EITHER AN EQUALLY-SPACED GRID
C (WITH OR WITHOUT POLE POINTS) OR A GAUSSIAN GRID.
C THE WAVE AND GRID FIELDS MAY HAVE GENERAL INDEXING,
C BUT EACH WAVE FIELD IS IN SEQUENTIAL 'IBM ORDER',
C I.E. WITH ZONAL WAVENUMBER AS THE SLOWER INDEX.
C TRANSFORMS ARE DONE IN LATITUDE PAIRS FOR EFFICIENCY;
C THUS GRID ARRAYS FOR EACH HEMISPHERE MUST BE PASSED.
C IF SO REQUESTED, JUST A SUBSET OF THE LATITUDE PAIRS
C MAY BE TRANSFORMED IN EACH INVOCATION OF THE SUBPROGRAM.
C THE TRANSFORMS ARE ALL MULTIPROCESSED OVER LATITUDE EXCEPT
C THE TRANSFORM FROM FOURIER TO SPECTRAL IS MULTIPROCESSED
C OVER ZONAL WAVENUMBER TO ENSURE REPRODUCIBILITY.
C TRANSFORM SEVERAL FIELDS AT A TIME TO IMPROVE VECTORIZATION.
C SUBPROGRAM CAN BE CALLED FROM A MULTIPROCESSING ENVIRONMENT.
C
C PROGRAM HISTORY LOG:
C 96-02-29 IREDELL
C 1998-12-15 IREDELL OPENMP DIRECTIVES INSERTED
C
C USAGE: CALL SPTRAND(IROMB,MAXWV,IDRT,IMAX,JMAX,KMAX,
C & IPRIME,ISKIP,JNSKIP,JSSKIP,KWSKIP,KGSKIP,
C & JBEG,JEND,JCPU,
C & WAVE,GRIDMN,GRIDXN,GRIDXS,GRIDYN,GRIDYS,IDIR)
C INPUT ARGUMENTS:
C IROMB - INTEGER SPECTRAL DOMAIN SHAPE
C (0 FOR TRIANGULAR, 1 FOR RHOMBOIDAL)
C MAXWV - INTEGER SPECTRAL TRUNCATION
C IDRT - INTEGER GRID IDENTIFIER
C (IDRT=4 FOR GAUSSIAN GRID,
C IDRT=0 FOR EQUALLY-SPACED GRID INCLUDING POLES,
C IDRT=256 FOR EQUALLY-SPACED GRID EXCLUDING POLES)
C IMAX - INTEGER EVEN NUMBER OF LONGITUDES.
C JMAX - INTEGER NUMBER OF LATITUDES.
C KMAX - INTEGER NUMBER OF FIELDS TO TRANSFORM.
C IPRIME - INTEGER LONGITUDE INDEX FOR THE PRIME MERIDIAN.
C (DEFAULTS TO 1 IF IPRIME=0)
C ISKIP - INTEGER SKIP NUMBER BETWEEN LONGITUDES
C (DEFAULTS TO 1 IF ISKIP=0)
C JNSKIP - INTEGER SKIP NUMBER BETWEEN N.H. LATITUDES FROM NORTH
C (DEFAULTS TO IMAX IF JNSKIP=0)
C JSSKIP - INTEGER SKIP NUMBER BETWEEN S.H. LATITUDES FROM SOUTH
C (DEFAULTS TO -IMAX IF JSSKIP=0)
C KWSKIP - INTEGER SKIP NUMBER BETWEEN WAVE FIELDS
C (DEFAULTS TO (MAXWV+1)*((IROMB+1)*MAXWV+2) IF KWSKIP=0)
C KGSKIP - INTEGER SKIP NUMBER BETWEEN GRID FIELDS
C (DEFAULTS TO IMAX*JMAX IF KGSKIP=0)
C JBEG - INTEGER LATITUDE INDEX (FROM POLE) TO BEGIN TRANSFORM
C (DEFAULTS TO 1 IF JBEG=0)
C (IF JBEG=0 AND IDIR<0, WAVE IS ZEROED BEFORE TRANSFORM)
C JEND - INTEGER LATITUDE INDEX (FROM POLE) TO END TRANSFORM
C (DEFAULTS TO (JMAX+1)/2 IF JEND=0)
C JCPU - INTEGER NUMBER OF CPUS OVER WHICH TO MULTIPROCESS
C WAVE - REAL (*) WAVE FIELDS IF IDIR>0
C GRIDMN - REAL (KMAX) GLOBAL MEANS IF IDIR<0
C GRIDXN - REAL (*) N.H. X-GRADIENTS (STARTING AT JBEG) IF IDIR<0
C GRIDXS - REAL (*) S.H. X-GRADIENTS (STARTING AT JBEG) IF IDIR<0
C GRIDYN - REAL (*) N.H. Y-GRADIENTS (STARTING AT JBEG) IF IDIR<0
C GRIDYS - REAL (*) S.H. Y-GRADIENTS (STARTING AT JBEG) IF IDIR<0
C IDIR - INTEGER TRANSFORM FLAG
C (IDIR>0 FOR WAVE TO GRID, IDIR<0 FOR GRID TO WAVE)
C OUTPUT ARGUMENTS:
C WAVE - REAL (*) WAVE FIELDS IF IDIR<0
C GRIDMN - REAL (KMAX) GLOBAL MEANS IF IDIR>0
C GRIDXN - REAL (*) N.H. X-GRADIENTS (STARTING AT JBEG) IF IDIR>0
C GRIDXS - REAL (*) S.H. X-GRADIENTS (STARTING AT JBEG) IF IDIR>0
C [GRIDX=(D(WAVE)/DLAM)/(CLAT*RERTH)]
C GRIDYN - REAL (*) N.H. Y-GRADIENTS (STARTING AT JBEG) IF IDIR>0
C GRIDYS - REAL (*) S.H. Y-GRADIENTS (STARTING AT JBEG) IF IDIR>0
C [GRIDY=(D(WAVE)/DPHI)/RERTH]
C
C SUBPROGRAMS CALLED:
C SPWGET GET WAVE-SPACE CONSTANTS
C SPLAPLAC COMPUTE LAPLACIAN IN SPECTRAL SPACE
C SPTRANV PERFORM A VECTOR SPHERICAL TRANSFORM
C
C REMARKS: MINIMUM GRID DIMENSIONS FOR UNALIASED TRANSFORMS TO SPECTRAL:
C DIMENSION LINEAR QUADRATIC
C ----------------------- --------- -------------
C IMAX 2*MAXWV+2 3*MAXWV/2*2+2
C JMAX (IDRT=4,IROMB=0) 1*MAXWV+1 3*MAXWV/2+1
C JMAX (IDRT=4,IROMB=1) 2*MAXWV+1 5*MAXWV/2+1
C JMAX (IDRT=0,IROMB=0) 2*MAXWV+3 3*MAXWV/2*2+3
C JMAX (IDRT=0,IROMB=1) 4*MAXWV+3 5*MAXWV/2*2+3
C JMAX (IDRT=256,IROMB=0) 2*MAXWV+1 3*MAXWV/2*2+1
C JMAX (IDRT=256,IROMB=1) 4*MAXWV+1 5*MAXWV/2*2+1
C ----------------------- --------- -------------
C
C ATTRIBUTES:
C LANGUAGE: FORTRAN 77
C
C$$$
REAL WAVE(*),GRIDMN(KMAX),GRIDXN(*),GRIDXS(*),GRIDYN(*),GRIDYS(*)
REAL EPS((MAXWV+1)*((IROMB+1)*MAXWV+2)/2),EPSTOP(MAXWV+1)
REAL ENN1((MAXWV+1)*((IROMB+1)*MAXWV+2)/2)
REAL ELONN1((MAXWV+1)*((IROMB+1)*MAXWV+2)/2)
REAL EON((MAXWV+1)*((IROMB+1)*MAXWV+2)/2),EONTOP(MAXWV+1)
REAL WD((MAXWV+1)*((IROMB+1)*MAXWV+2)/2*2+1,KMAX)
REAL WZ((MAXWV+1)*((IROMB+1)*MAXWV+2)/2*2+1,KMAX)
C - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
C SET PARAMETERS
CALL SPWGET(IROMB,MAXWV,EPS,EPSTOP,ENN1,ELONN1,EON,EONTOP)
MX=(MAXWV+1)*((IROMB+1)*MAXWV+2)/2
MDIM=2*MX+1
KW=KWSKIP
IF(KW.EQ.0) KW=2*MX
C - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
C TRANSFORM WAVE TO GRID
IF(IDIR.GT.0) THEN
C$OMP PARALLEL DO PRIVATE(KWS)
DO K=1,KMAX
KWS=(K-1)*KW
GRIDMN(K)=WAVE(KWS+1)/SQRT(2.)
CALL SPLAPLAC(IROMB,MAXWV,ENN1,WAVE(KWS+1),WD(1,K),1)
WZ(1:2*MX,K)=0.
ENDDO
CALL SPTRANV(IROMB,MAXWV,IDRT,IMAX,JMAX,KMAX,
& IPRIME,ISKIP,JNSKIP,JSSKIP,MDIM,KGSKIP,
& JBEG,JEND,JCPU,
& WD,WZ,GRIDXN,GRIDXS,GRIDYN,GRIDYS,IDIR)
C - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
C TRANSFORM GRID TO WAVE
ELSE
C$OMP PARALLEL DO
DO K=1,KMAX
WD(1:2*MX,K)=0.
WZ(1:2*MX,K)=0.
ENDDO
CALL SPTRANV(IROMB,MAXWV,IDRT,IMAX,JMAX,KMAX,
& IPRIME,ISKIP,JNSKIP,JSSKIP,MDIM,KGSKIP,
& JBEG,JEND,JCPU,
& WD,WZ,GRIDXN,GRIDXS,GRIDYN,GRIDYS,IDIR)
IF(JBEG.EQ.0) THEN
C$OMP PARALLEL DO PRIVATE(KWS)
DO K=1,KMAX
KWS=(K-1)*KW
CALL SPLAPLAC(IROMB,MAXWV,ENN1,WAVE(KWS+1),WD(1,K),-1)
WAVE(KWS+1)=GRIDMN(K)*SQRT(2.)
ENDDO
ELSE
C$OMP PARALLEL DO PRIVATE(KWS)
DO K=1,KMAX
KWS=(K-1)*KW
CALL SPLAPLAC(IROMB,MAXWV,ENN1,WZ(1,K),WD(1,K),-1)
WAVE(KWS+1:KWS+2*MX)=WAVE(KWS+1:KWS+2*MX)+WZ(1:2*MX,K)
WAVE(KWS+1)=GRIDMN(K)*SQRT(2.)
ENDDO
ENDIF
ENDIF
C - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
END
|
lemma pcompose_1: "pcompose 1 p = 1" for p :: "'a::comm_semiring_1 poly"
|
A sequence $f$ converges to a filter $F$ if and only if the sequence of real numbers $f_n$ converges to $F$.
|
\name{print.normalizedMatrix}
\alias{print.normalizedMatrix}
\title{
Print the Normalized Matrix
}
\description{
Print the Normalized Matrix
}
\usage{
\method{print}{normalizedMatrix}(x, ...)
}
\arguments{
\item{x}{The normalized matrix returned by \code{\link{normalizeToMatrix}}.}
\item{...}{Other arguments.}
}
\value{
No value is returned.
}
\author{
Zuguang Gu <[email protected]>
}
\examples{
# There is no example
NULL
}
|
Fixpoint pow m n :=
match n with
| O => 1
| S n' => m * pow m n'
end.
Lemma pow_le : forall n x y,
n >= 1 ->
x <= y <-> pow n x <= pow n y.
Proof.
Admitted.
Lemma pow_plus : forall n x y,
pow n (x + y) = pow n x * pow n y.
Proof.
Admitted.
Infix "^^" := pow (at level 30, right associativity) : nat_scope.
|
/-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Reid Barton, Bhavik Mehta
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.over
import Mathlib.category_theory.limits.preserves.basic
import Mathlib.category_theory.limits.creates
import Mathlib.PostPort
universes u v
namespace Mathlib
/-!
# Limits and colimits in the over and under categories
Show that the forgetful functor `forget X : over X ⥤ C` creates colimits, and hence `over X` has
any colimits that `C` has (as well as the dual that `forget X : under X ⟶ C` creates limits).
Note that the folder `category_theory.limits.shapes.constructions.over` further shows that
`forget X : over X ⥤ C` creates connected limits (so `over X` has connected limits), and that
`over X` has `J`-indexed products if `C` has `J`-indexed wide pullbacks.
TODO: If `C` has binary products, then `forget X : over X ⥤ C` has a right adjoint.
-/
namespace category_theory.functor
/-- We can interpret a functor `F` into the category of arrows with codomain `X` as a cocone over
the diagram given by the domains of the arrows in the image of `F` such that the apex of the
cocone is `X`. -/
@[simp] theorem to_cocone_X {J : Type v} [small_category J] {C : Type u} [category C] {X : C}
(F : J ⥤ over X) : limits.cocone.X (to_cocone F) = X :=
Eq.refl (limits.cocone.X (to_cocone F))
/-- We can interpret a functor `F` into the category of arrows with domain `X` as a cone over the
diagram given by the codomains of the arrows in the image of `F` such that the apex of the cone
is `X`. -/
@[simp] theorem to_cone_X {J : Type v} [small_category J] {C : Type u} [category C] {X : C}
(F : J ⥤ under X) : limits.cone.X (to_cone F) = X :=
Eq.refl (limits.cone.X (to_cone F))
end category_theory.functor
namespace category_theory.over
protected instance forget.category_theory.limits.reflects_colimits {C : Type u} [category C]
{X : C} : limits.reflects_colimits (forget X) :=
limits.reflects_colimits.mk
fun (J : Type v) (𝒥₁ : small_category J) =>
limits.reflects_colimits_of_shape.mk
fun (F : J ⥤ over X) =>
limits.reflects_colimit.mk
fun (c : limits.cocone F) (t : limits.is_colimit (functor.map_cocone (forget X) c)) =>
limits.is_colimit.mk
fun (s : limits.cocone F) =>
hom_mk (limits.is_colimit.desc t (functor.map_cocone (forget X) s))
protected instance forget.category_theory.creates_colimits {C : Type u} [category C] {X : C} :
creates_colimits (forget X) :=
creates_colimits.mk
fun (J : Type v) (𝒥₁ : small_category J) =>
creates_colimits_of_shape.mk
fun (K : J ⥤ over X) =>
creates_colimit.mk
fun (c : limits.cocone (K ⋙ forget X)) (t : limits.is_colimit c) =>
liftable_cocone.mk
(limits.cocone.mk (mk (limits.is_colimit.desc t (functor.to_cocone K)))
(nat_trans.mk fun (j : J) => hom_mk (nat_trans.app (limits.cocone.ι c) j)))
(limits.cocones.ext
(iso.refl
(limits.cocone.X
(functor.map_cocone (forget X)
(limits.cocone.mk (mk (limits.is_colimit.desc t (functor.to_cocone K)))
(nat_trans.mk
fun (j : J) => hom_mk (nat_trans.app (limits.cocone.ι c) j))))))
sorry)
protected instance has_colimit {J : Type v} [small_category J] {C : Type u} [category C] {X : C}
{F : J ⥤ over X} [limits.has_colimit (F ⋙ forget X)] : limits.has_colimit F :=
has_colimit_of_created F (forget X)
protected instance has_colimits_of_shape {J : Type v} [small_category J] {C : Type u} [category C]
{X : C} [limits.has_colimits_of_shape J C] : limits.has_colimits_of_shape J (over X) :=
limits.has_colimits_of_shape.mk fun (F : J ⥤ over X) => over.has_colimit
protected instance has_colimits {C : Type u} [category C] {X : C} [limits.has_colimits C] :
limits.has_colimits (over X) :=
limits.has_colimits.mk fun (J : Type v) (𝒥 : small_category J) => over.has_colimits_of_shape
-- We can automatically infer that the forgetful functor preserves colimits
end category_theory.over
namespace category_theory.under
protected instance forget.category_theory.limits.reflects_limits {C : Type u} [category C] {X : C} :
limits.reflects_limits (forget X) :=
limits.reflects_limits.mk
fun (J : Type v) (𝒥₁ : small_category J) =>
limits.reflects_limits_of_shape.mk
fun (F : J ⥤ under X) =>
limits.reflects_limit.mk
fun (c : limits.cone F) (t : limits.is_limit (functor.map_cone (forget X) c)) =>
limits.is_limit.mk
fun (s : limits.cone F) =>
hom_mk (limits.is_limit.lift t (functor.map_cone (forget X) s))
protected instance forget.category_theory.creates_limits {C : Type u} [category C] {X : C} :
creates_limits (forget X) :=
creates_limits.mk
fun (J : Type v) (𝒥₁ : small_category J) =>
creates_limits_of_shape.mk
fun (K : J ⥤ under X) =>
creates_limit.mk
fun (c : limits.cone (K ⋙ forget X)) (t : limits.is_limit c) =>
liftable_cone.mk
(limits.cone.mk (mk (limits.is_limit.lift t (functor.to_cone K)))
(nat_trans.mk fun (j : J) => hom_mk (nat_trans.app (limits.cone.π c) j)))
(limits.cones.ext
(iso.refl
(limits.cone.X
(functor.map_cone (forget X)
(limits.cone.mk (mk (limits.is_limit.lift t (functor.to_cone K)))
(nat_trans.mk
fun (j : J) => hom_mk (nat_trans.app (limits.cone.π c) j))))))
sorry)
protected instance has_limit {J : Type v} [small_category J] {C : Type u} [category C] {X : C}
{F : J ⥤ under X} [limits.has_limit (F ⋙ forget X)] : limits.has_limit F :=
has_limit_of_created F (forget X)
protected instance has_limits_of_shape {J : Type v} [small_category J] {C : Type u} [category C]
{X : C} [limits.has_limits_of_shape J C] : limits.has_limits_of_shape J (under X) :=
limits.has_limits_of_shape.mk fun (F : J ⥤ under X) => under.has_limit
protected instance has_limits {C : Type u} [category C] {X : C} [limits.has_limits C] :
limits.has_limits (under X) :=
limits.has_limits.mk fun (J : Type v) (𝒥 : small_category J) => under.has_limits_of_shape
end Mathlib
|
[STATEMENT]
lemma dca_run:
"DCA.run (dca UNIV p \<delta> \<alpha>) (to_stream w) p"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. DCA.run (dca UNIV p \<delta> \<alpha>) (to_stream w) p
[PROOF STEP]
unfolding dca.run_alt_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. to_stream w \<in> streams (dca.alphabet (dca UNIV p \<delta> \<alpha>))
[PROOF STEP]
by simp
|
#' Search for and collect taxonomic name data from the USGS Bison API
#' using solr
#'
#' @export
#' @param query Name to search for. Required.
#' @param method The field to query by. See description below for details.
#' @param exact Exact matching or not. See examples. Defaults to FALSE.
#' @param parsed If `TRUE` (default) creates data.frame of names data output.
#' Otherwise, a list.
#' @param callopts Further args passed on to [crul::HttpClient()] for HTTP
#' debugging/inspecting. In `bison`, `bison_providers`, and `bison_stats`,
#' `...` is used instead of callopts, but `...` is used here to pass additional
#' Solr params.
#' @param ... Further solr arguments passed in to the query. See examples below.
#' @return A list.
#' @description
#' See the SOLR documentation here <http://lucene.apache.org/solr/> for other
#' parameters you can use.
#'
#' The following two methods are possible, as far as I know you can only use
#' one at a time:
#' \itemize{
#' \item vernacularName The species specific common names that is searchable
#' in a case insensitive way.
#' \item scientificName The species scientific name that is associated
#' with a common name that is searchable in a case insensitive way.
#' }
#' @seealso [bison_solr()], [bison()]
#' @examples \dontrun{
#' # All taxa
#' bison_tax("*:*")
#'
#' # Some example calls
#' bison_tax(query="*bear")
#' bison_tax(query="Helianthus", method="scientificName")
#'
#' # Exact argument, here nothing found with latter call as '*bear'
#' # doesn't exist, which makes sense
#' bison_tax(query="*bear", exact=FALSE)
#' bison_tax(query="*bear", exact=TRUE)
#'
#' # Using solr arguments (not all Solr arguments work)
#' ## Return a certain number of rows
#' bison_tax(query="*bear", method="vernacularName", rows=3)
#' ## Return certain fields
#' bison_tax(query="*bear", method="vernacularName", fl='vernacularName')
#'
#' # Curl options
#' bison_tax(query='*dolphin', callopts=list(verbose = TRUE))
#' }
bison_tax <- function(query, method='vernacularName', exact=FALSE, parsed=TRUE,
callopts=list(), ...)
{
method <- match.arg(method, choices = c('vernacularName','scientificName'))
if (!length(method) == 1) {
stop("method can only be of length 1")
}
url <- sprintf('%s/solr/%s/select', bison_base(), method)
if (exact) {
qu_ <- paste0('"', query, '"')
} else {
qu_ <- query
}
args <- bs_compact(list(q = qu_, wt = "json", ...))
cli <- crul::HttpClient$new(url = url, opts = c(followlocation = 1, callopts))
out <- cli$get(query = args)
out$raise_for_status()
out <- jsonlite::fromJSON(out$parse("UTF-8"), FALSE)
# tt <- GET(url, query = args, c(config(followlocation = 1), callopts))
# stop_for_status(tt)
# out <- content(tt)
temp <- list(
numFound = out$response$numFound,
names = out$response$docs,
highlight = out$highlighting,
facets = out$facet_counts
)
if (parsed) {
data <- dplyr::bind_rows(lapply(out$response$docs, data.frame,
stringsAsFactors = FALSE))
data$X_version_ <- NULL
temp$names <- data
}
return( temp )
}
|
(* Disable notation conflict warnings *)
Set Warnings "-notation-overridden".
From Coq Require Import ssreflect ssrfun ssrbool.
Require Import Psatz.
Require Import Coq.Lists.List.
Require Import Coq.NArith.BinNat.
Import ListNotations.
Require Import Coq.Classes.RelationClasses.
Require Import Coq.Classes.Morphisms.
Require Import SetoidList.
Require Import GHC.Base.
Require Import Proofs.Prelude.
Require Import CoreFVs.
Require Import Id.
Require Import Core.
Require UniqFM.
Require Import Proofs.Axioms.
Require Import Proofs.ContainerAxioms.
Require Import Proofs.GhcTactics.
Require Import Proofs.Unique.
Require Import Proofs.Var.
Require Import Proofs.VarSetFSet.
Require Import Proofs.Base.
Open Scope Z_scope.
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Set Bullet Behavior "Strict Subproofs".
(* Stephanie's hack. *)
Lemma fold_is_true : forall b, b = true <-> b.
Proof. intros. unfold is_true. reflexivity. Qed.
Lemma false_is_not_true :
forall b, b = false <-> b <> true.
Proof.
destruct b; intuition.
Qed.
(* Why is this not part of ssr? *)
Lemma eqE : forall (a b:bool), a = b <-> (a <-> b).
Proof.
move=> a b.
elim Ea: a;
elim Eb: b;
try tauto.
intuition.
symmetry.
rewrite fold_is_true.
apply H0. auto.
intuition.
Qed.
Lemma andE a b : a && b <-> a /\ b.
Proof.
elim: a; elim: b; try tauto.
split; move=> /andP; try done.
split; move=> /andP; try done.
Qed.
Lemma orE : forall a b, (a || b) <-> a \/ b.
Proof. intros a b. unfold is_true. rewrite orb_true_iff. tauto. Qed.
Lemma notE : forall a, ~~a <-> ~ a.
Proof. move=>a. unfold is_true. rewrite negb_true_iff.
split. move=>h. rewrite h. auto.
apply not_true_is_false.
Qed.
(** ** NOTE: VarSets and equality *)
(* VarSets have several different notions of equality.
In all three definitions, equal varsets must have the same domain.
Now suppose:
lookupVarSet m1 x = Some v1 and
lookupVarSet m2 x = Some v2
The sets are equal when:
- v1 = v2 (i.e. coq equality)
- almostEqual v1 v2
- v1 == v2 (i.e. same uniques ONLY)
The last (coarsest) equality is the one used in the FSet signature,
and denoted by the [=] notation.
The almostEqual equality is denoted by {=}.
Because of this distinction, we have to do some lemmas twice: once
for [=] equality, and once for {=} equality.
*)
(** ** VarSet operations respect GHC.Base.== *)
Lemma elemVarSet_eq : forall v1 v2 vs,
(v1 == v2) ->
elemVarSet v1 vs = elemVarSet v2 vs.
Proof.
intros v1 v2 vs h.
unfold elemVarSet, UniqSet.elementOfUniqSet.
destruct vs.
unfold UniqFM.elemUFM.
destruct getUniqSet'.
move: h.
rewrite eq_unique.
move=> h.
f_equal.
auto.
Qed.
Lemma lookupVarSet_eq :
forall v1 v2 vs,
(v1 == v2) ->
lookupVarSet vs v1 = lookupVarSet vs v2.
Proof.
intros v1 v2 vs.
unfold lookupVarSet.
unfold UniqSet.lookupUniqSet.
destruct vs.
unfold UniqFM.lookupUFM.
destruct getUniqSet'.
intro h.
rewrite -> eq_unique in h.
rewrite h.
reflexivity.
Qed.
Lemma extendVarSet_eq :
forall x y vs, x == y -> extendVarSet vs x [=] extendVarSet vs y.
Proof.
move => x y vs Eq.
set_b_iff.
move: (add_m) => h.
unfold Proper,respectful in h.
apply h.
assumption.
reflexivity.
Qed.
Lemma delVarSet_eq :
forall x y vs, x == y -> delVarSet vs x = delVarSet vs y.
Proof.
move => x y vs Eq.
unfold delVarSet.
move: vs => [i].
move: i => [m].
rewrite -> eq_unique in Eq.
unfold UniqSet.delOneFromUniqSet.
unfold UniqFM.delFromUFM.
rewrite Eq.
reflexivity.
Qed.
(** ** List based operations in terms of folds *)
Lemma extendVarSetList_foldl' : forall x xs,
extendVarSetList x xs = Foldable.foldl' (fun x y => add y x) x xs.
Proof.
intros.
unfold extendVarSetList, UniqSet.addListToUniqSet;
replace UniqSet.addOneToUniqSet with
(fun x y => add y x).
auto.
auto.
Qed.
Lemma delVarSetList_foldl : forall vl vs,
delVarSetList vs vl = Foldable.foldl delVarSet vs vl.
Proof.
induction vl.
- intro vs.
destruct vs. destruct getUniqSet'.
unfold_Foldable_foldl.
simpl.
auto.
- intro vs.
unfold delVarSetList in *.
unfold UniqSet.delListFromUniqSet in *.
destruct vs.
unfold UniqFM.delListFromUFM in *.
revert IHvl.
unfold_Foldable_foldl.
simpl.
intro IHvl.
rewrite (IHvl (UniqSet.Mk_UniqSet (UniqFM.delFromUFM getUniqSet' a))).
auto.
Qed.
Lemma mkVarSet_extendVarSetList : forall xs,
mkVarSet xs = extendVarSetList emptyVarSet xs.
Proof.
reflexivity.
Qed.
Hint Rewrite mkVarSet_extendVarSetList : hs_simpl.
(** ** [lookupVarSet] and [elemVarSet] correspondence *)
Lemma lookupVarSet_In:
forall vs v, (exists v', lookupVarSet vs v = Some v') <-> In v vs.
Proof.
unfold lookupVarSet, UniqSet.lookupUniqSet,
UniqFM.lookupUFM, Unique.getWordKey, Unique.getKey.
intros.
destruct vs.
destruct getUniqSet'.
destruct (Unique.getUnique v) as [n] eqn:Hv.
unfold In, elemVarSet, UniqSet.elementOfUniqSet,
UniqFM.elemUFM, Unique.getKey, Unique.getWordKey,
Unique.getKey.
rewrite Hv.
rewrite <- member_lookup.
reflexivity.
Qed.
Lemma lookupVarSet_elemVarSet :
forall v1 v2 vs, lookupVarSet vs v1 = Some v2 -> elemVarSet v1 vs.
Proof.
intros.
unfold lookupVarSet, elemVarSet in *.
unfold UniqSet.lookupUniqSet, UniqSet.elementOfUniqSet in *.
destruct vs.
unfold UniqFM.lookupUFM, UniqFM.elemUFM in *.
destruct getUniqSet'.
set (key := Unique.getWordKey (Unique.getUnique v1)) in *.
rewrite member_lookup.
exists v2. auto.
Qed.
Lemma lookupVarSet_None_elemVarSet:
forall v1 vs, lookupVarSet vs v1 = None <-> elemVarSet v1 vs = false.
Proof.
intros.
unfold lookupVarSet, elemVarSet in *.
unfold UniqSet.lookupUniqSet, UniqSet.elementOfUniqSet in *.
destruct vs.
unfold UniqFM.lookupUFM, UniqFM.elemUFM in *.
destruct getUniqSet'.
set (key := Unique.getWordKey (Unique.getUnique v1)) in *.
rewrite non_member_lookup.
intuition.
Qed.
Lemma elemVarSet_lookupVarSet :
forall v1 vs, elemVarSet v1 vs -> exists v2, lookupVarSet vs v1 = Some v2.
Proof.
intros.
unfold lookupVarSet, elemVarSet in *.
unfold UniqSet.lookupUniqSet, UniqSet.elementOfUniqSet in *.
destruct vs.
unfold UniqFM.lookupUFM, UniqFM.elemUFM in *.
destruct getUniqSet'.
set (key := Unique.getWordKey (Unique.getUnique v1)) in *.
rewrite <- member_lookup.
auto.
Qed.
(** ** [lookupVarSet] is Proper *)
Instance lookupVarSet_m :
Proper (Equal ==> (fun x y => x == y) ==> (fun x y => x == y)) lookupVarSet.
Proof.
unfold Equal.
intros x y H v1 v2 EV.
erewrite lookupVarSet_eq; eauto.
pose (h1 := H v1).
pose (h2 := H v2).
repeat rewrite -> mem_iff in h1.
repeat rewrite -> mem_iff in h2.
destruct (lookupVarSet x v2) eqn:LX;
destruct (lookupVarSet y v2) eqn:LY;
hs_simpl.
- apply ValidVarSet_Axiom in LX.
apply ValidVarSet_Axiom in LY.
eapply Eq_trans.
rewrite Eq_sym.
eapply LX.
eapply LY.
- apply lookupVarSet_elemVarSet in LX.
rewrite -> lookupVarSet_None_elemVarSet in LY.
set_b_iff.
intuition.
- apply lookupVarSet_elemVarSet in LY.
rewrite -> lookupVarSet_None_elemVarSet in LX.
set_b_iff.
intuition.
- auto.
Qed.
(** ** [lookupVarSet . extendVarSet ] simplification *)
Lemma lookupVarSet_extendVarSet_self:
forall v vs,
lookupVarSet (extendVarSet vs v) v = Some v.
Proof.
intros.
unfold lookupVarSet, extendVarSet in *.
unfold UniqSet.lookupUniqSet, UniqSet.addOneToUniqSet in *.
destruct vs.
unfold UniqFM.lookupUFM, UniqFM.addToUFM in *.
destruct getUniqSet'.
set (key := Unique.getWordKey (Unique.getUnique v)) in *.
apply lookup_insert.
Qed.
Hint Rewrite lookupVarSet_extendVarSet_self : hs_simpl.
Lemma lookupVarSet_extendVarSet_eq :
forall v1 v2 vs,
v1 == v2 ->
lookupVarSet (extendVarSet vs v1) v2 = Some v1.
Proof.
intros v1 v2 vs H.
rewrite Eq_sym in H.
rewrite (lookupVarSet_eq _ H).
unfold lookupVarSet, extendVarSet.
unfold UniqSet.lookupUniqSet, UniqSet.addOneToUniqSet.
destruct vs.
unfold UniqFM.lookupUFM, UniqFM.addToUFM.
destruct getUniqSet'.
set (k1 := Unique.getWordKey (Unique.getUnique v1)).
rewrite lookup_insert.
reflexivity.
Qed.
Lemma lookupVarSet_extendVarSet_neq :
forall v1 v2 vs,
not (v1 == v2) ->
lookupVarSet (extendVarSet vs v1) v2 = lookupVarSet vs v2.
Proof.
intros v1 v2 vs H.
assert (Unique.getWordKey (Unique.getUnique v1) <>
Unique.getWordKey (Unique.getUnique v2)).
{ intro h.
eapply H.
rewrite eq_unique.
auto.
}
unfold lookupVarSet, extendVarSet.
unfold UniqSet.lookupUniqSet, UniqSet.addOneToUniqSet.
destruct vs.
unfold UniqFM.lookupUFM, UniqFM.addToUFM.
destruct getUniqSet'.
eapply lookup_insert_neq.
auto.
Qed.
(* --------------------------------- *)
(* Tactics that don't really work. *)
Local Ltac unfold_VarSet_to_IntMap :=
repeat match goal with
| [vs : VarSet |- _ ] =>
let u := fresh "u" in
destruct vs as [u]; destruct u; simpl
| [ |- UniqSet.Mk_UniqSet _ = UniqSet.Mk_UniqSet _ ] =>
f_equal
| [ |- UniqFM.UFM _ = UniqFM.UFM _ ] =>
f_equal
end.
(*
(* Q: is there a way to do the automatic destructs safely? Sometimes
loses too much information. *)
Ltac unfold_VarSet :=
unfold subVarSet,elemVarSet, isEmptyVarSet,
minusVarSet, extendVarSet, extendVarSetList in *;
unfold UniqSet.elementOfUniqSet,
UniqSet.isEmptyUniqSet,
UniqSet.addOneToUniqSet,
UniqSet.minusUniqSet,
UniqSet.addListToUniqSet in *;
try repeat match goal with
| vs: VarSet, H : context[match ?vs with _ => _ end] |- _ => destruct vs
end;
try repeat match goal with
| vs: VarSet |- context[match ?vs with _ => _ end ] => destruct vs
end;
unfold UniqFM.addToUFM,
UniqFM.minusUFM, UniqFM.isNullUFM,
UniqFM.elemUFM in *;
try repeat match goal with
| u: UniqFM.UniqFM ?a, H : context[match ?u with _ => _ end] |- _ => destruct u
end;
try repeat match goal with
| u: UniqFM.UniqFM ?a |- context[match ?u with _ => _ end] => destruct u
end.
Ltac safe_unfold_VarSet :=
unfold subVarSet,elemVarSet, isEmptyVarSet,
minusVarSet, extendVarSet, extendVarSetList in *;
unfold UniqSet.elementOfUniqSet,
UniqSet.isEmptyUniqSet,
UniqSet.addOneToUniqSet,
UniqSet.minusUniqSet,
UniqSet.addListToUniqSet in *;
unfold UniqFM.addToUFM,
UniqFM.minusUFM, UniqFM.isNullUFM,
UniqFM.elemUFM in *. *)
(**************************************)
(** ** [extendVarSetList] simplifications *)
Lemma extendVarSetList_nil:
forall s,
extendVarSetList s [] = s.
Proof.
intro s.
reflexivity.
Qed.
Lemma extendVarSetList_cons:
forall s v vs,
extendVarSetList s (v :: vs) = extendVarSetList (extendVarSet s v) vs.
Proof.
intros.
rewrite extendVarSetList_foldl'.
autorewrite with hs_simpl.
reflexivity.
Qed.
Lemma extendVarSetList_singleton:
forall vs v, extendVarSetList vs [v] = extendVarSet vs v.
Proof. intros. reflexivity. Qed.
Lemma extendVarSetList_append:
forall s vs1 vs2,
extendVarSetList s (vs1 ++ vs2) = extendVarSetList (extendVarSetList s vs1) vs2.
Proof.
intros.
rewrite extendVarSetList_foldl'.
autorewrite with hs_simpl.
reflexivity.
Qed.
Hint Rewrite extendVarSetList_nil
extendVarSetList_cons
extendVarSetList_singleton
extendVarSetList_append : hs_simpl.
(** ** [delVarSetList] simplification *)
Lemma delVarSetList_nil:
forall e, delVarSetList e [] = e.
Proof.
intros.
rewrite delVarSetList_foldl.
reflexivity.
Qed.
Lemma delVarSetList_single:
forall e a, delVarSetList e [a] = delVarSet e a.
Proof.
intros.
rewrite delVarSetList_foldl.
autorewrite with hs_simpl.
reflexivity.
Qed.
Lemma delVarSetList_cons:
forall e a vs, delVarSetList e (a :: vs) = delVarSetList (delVarSet e a) vs.
Proof.
intros.
repeat rewrite delVarSetList_foldl.
autorewrite with hs_simpl.
reflexivity.
Qed.
Lemma delVarSetList_app:
forall e vs vs', delVarSetList e (vs ++ vs') = delVarSetList (delVarSetList e vs) vs'.
Proof.
intros.
repeat rewrite delVarSetList_foldl.
autorewrite with hs_simpl.
reflexivity.
Qed.
Hint Rewrite delVarSetList_nil
delVarSetList_cons
delVarSetList_single
delVarSetList_app : hs_simpl.
(** ** [elemVarSet] simplification *)
Lemma elemVarSet_emptyVarSet : forall v, (elemVarSet v emptyVarSet) = false.
intro v.
set_b_iff.
fsetdec.
Qed.
Lemma elemVarSet_unionVarSet:
forall v vs1 vs2,
elemVarSet v (unionVarSet vs1 vs2) = elemVarSet v vs1 || elemVarSet v vs2.
Proof.
move => v [[i]] [[i0]] /=.
rewrite member_union.
auto.
Qed.
Hint Rewrite elemVarSet_emptyVarSet elemVarSet_unionVarSet : hs_simpl.
(** ** [extendVarSet] *)
Lemma extendVarSet_elemVarSet_true : forall set v,
elemVarSet v set -> extendVarSet set v [=] set.
Proof.
intros.
apply add_equal.
auto.
Qed.
Lemma elemVarSet_extendVarSet:
forall v vs v',
elemVarSet v (extendVarSet vs v') = (v' == v) || elemVarSet v vs.
Proof.
intros.
rewrite var_eq_realUnique.
replace (realUnique v' == realUnique v)%N with
(F.eqb v' v).
eapply F.add_b.
unfold F.eqb.
cbn.
destruct F.eq_dec.
- unfold Var_as_DT.eq in e.
rewrite <- realUnique_eq in e; auto.
- unfold Var_as_DT.eq in n.
rewrite <- realUnique_eq in n; apply not_true_is_false in n; auto.
Qed.
Hint Rewrite elemVarSet_extendVarSet : hs_simpl.
Lemma elemVarSet_extendVarSetList:
forall v vs vs',
elemVarSet v (extendVarSetList vs vs') = Foldable.elem v vs' || elemVarSet v vs.
Proof.
intros.
generalize vs.
induction vs'.
+ intros vs0. hs_simpl.
simpl.
auto.
+ intros vs0. hs_simpl.
rewrite IHvs'.
hs_simpl.
rewrite Eq_sym.
ssrbool.bool_congr.
reflexivity.
Qed.
Hint Rewrite elemVarSet_extendVarSetList : hs_simpl.
Lemma extendVarSet_commute : forall x y vs,
extendVarSet (extendVarSet vs y) x [=] extendVarSet (extendVarSet vs x) y.
Proof.
intros.
set_b_iff.
fsetdec.
Qed.
(** ** [extendVarSetList] and [delVarSetList] are Proper **)
(* These lemmas show that extendVarSetList respects [=] *)
Lemma extendVarSetList_iff : forall l x vs,
In x (extendVarSetList vs l) <->
In x vs \/ Foldable.elem x l.
Proof.
induction l.
- intros x vs.
hs_simpl.
intuition.
inversion H0.
- intros x vs.
hs_simpl.
rewrite IHl.
set_b_iff.
rewrite add_iff.
unfold Var_as_DT.eqb.
rewrite Eq_sym.
rewrite orE.
intuition.
Qed.
Lemma delVarSetList_iff : forall l x vs,
In x (delVarSetList vs l) <->
In x vs /\ ~ (Foldable.elem x l).
Proof.
induction l.
- intros x vs.
hs_simpl.
intuition.
- intros x vs.
hs_simpl.
rewrite IHl.
rewrite delVarSet_remove. rewrite remove_iff.
unfold Var_as_DT.eqb.
rewrite Eq_sym.
rewrite orE.
intuition.
Qed.
Instance extendVarSetList_m :
Proper (Equal ==> (eqlistA (fun x y => x == y)) ==> Equal) extendVarSetList.
Proof.
unfold Equal.
intros x y H s s' H0 a.
do 2 rewrite extendVarSetList_iff.
rewrite H.
intuition; right.
erewrite <- eqlist_Foldable_elem; eauto.
eapply EqLaws_Var.
erewrite eqlist_Foldable_elem; eauto.
eapply EqLaws_Var.
Qed.
Instance delVarSetList_m :
Proper (Equal ==> (eqlistA (fun x y => x == y)) ==> Equal) delVarSetList.
Proof.
unfold Equal.
intros x y H s s' H0 a.
do 2 rewrite delVarSetList_iff.
rewrite H.
intuition.
apply H3.
erewrite eqlist_Foldable_elem; eauto using EqLaws_Var.
apply H3.
erewrite <- eqlist_Foldable_elem; eauto using EqLaws_Var.
Qed.
(* We can commute the order of addition to varsets.
This is only true for [=] *)
Lemma extendVarSetList_extendVarSet_iff: forall l x vs,
extendVarSetList (extendVarSet vs x) l [=]
extendVarSet (extendVarSetList vs l) x.
Proof.
induction l.
- intros.
hs_simpl.
reflexivity.
- intros.
hs_simpl.
rewrite extendVarSet_commute.
rewrite IHl.
reflexivity.
Qed.
Lemma elemVarSet_extend_add : forall v s vs a,
elemVarSet v (extendVarSetList s vs) ->
elemVarSet v (extendVarSetList (add a s) vs).
Proof.
intros v s vs a.
rewrite InE.
rewrite InE.
rewrite extendVarSetList_iff.
rewrite extendVarSetList_iff.
intuition.
left.
fsetdec.
Qed.
Lemma elemVarSet_extendVarSetList_r:
forall v s vs,
elemVarSet v (mkVarSet vs) ->
elemVarSet v (extendVarSetList s vs) .
Proof.
intros v s vs.
rewrite mkVarSet_extendVarSetList.
rewrite InE.
rewrite InE.
rewrite extendVarSetList_iff.
rewrite extendVarSetList_iff.
intuition.
Qed.
Lemma elemVarSet_mkVarSet_cons:
forall v v' vs,
elemVarSet v (mkVarSet (v' :: vs)) = false
<-> (v' == v) = false /\ elemVarSet v (mkVarSet vs) = false.
Proof.
intros v v' vs.
rewrite mkVarSet_extendVarSetList.
rewrite extendVarSetList_cons.
rewrite mkVarSet_extendVarSetList.
rewrite <- not_mem_iff.
rewrite <- not_mem_iff.
rewrite extendVarSetList_iff.
rewrite extendVarSetList_iff.
set_b_iff.
rewrite add_iff.
unfold Var_as_DT.eqb.
intuition.
apply not_true_is_false.
unfold not. auto.
destruct H.
rewrite H1 in H0.
done.
Qed.
(* ** Properties about [lookupVarSet (extendVarSetList vs vars) v]
Note, we can specify what happens when v is an Foldable.elem of vars with
varying degrees of precision. When we lookup v, we won't get [Some v]
exactly, but we will get something == to v, and that was the most recently
added var in vars.
*)
Lemma lookupVarSet_extendVarSetList_false:
forall (vars:list Var) v vs,
~~ (Foldable.elem v vars ) ->
lookupVarSet (extendVarSetList vs vars) v = lookupVarSet vs v.
Proof.
elim=> [|x xs IH] //. (* // is try done. *)
- move => v vs.
hs_simpl.
rewrite negb_or. (* de morgan law to push ~~ in *)
move => /andP [h1 h2]. (* split && into two hypotheses *)
rewrite IH //.
rewrite lookupVarSet_extendVarSet_neq //.
rewrite Eq_sym. by apply /negP.
Qed.
Lemma lookupVarSet_extendVarSetList_l
v vs vars :
~~ elemVarSet v (mkVarSet vars) ->
lookupVarSet (extendVarSetList vs vars) v = lookupVarSet vs v.
Proof.
hs_simpl.
elim: vars vs => [|a vars IH] vs //.
hs_simpl.
rewrite negb_orb => /andP [? ?].
rewrite lookupVarSet_extendVarSetList_false //.
rewrite lookupVarSet_extendVarSet_neq //.
apply /negP.
rewrite Eq_sym //.
Qed.
Lemma lookupVarSet_extendVarSetList_self_in:
forall (vars:list Var) v vs,
List.In v vars ->
NoDup (map varUnique vars) ->
lookupVarSet (extendVarSetList vs vars) v = Some v.
Proof.
induction vars.
- intros v vs H.
inversion H.
- intros v vs H ND.
hs_simpl.
simpl in ND.
inversion ND. subst.
inversion H; subst.
+ rewrite lookupVarSet_extendVarSetList_false.
by hs_simpl.
apply /negP.
by rewrite -In_varUnique_elem.
+ eauto.
Qed.
Lemma lookupVarSet_extendVarSetList_self:
forall (vars:list Var) v vs,
(Foldable.elem v vars) ->
lookupVarSet (extendVarSetList vs vars) v == Some v.
Proof.
induction vars.
- intros v vs H.
rewrite elem_nil in H.
done.
- intros v vs H.
rewrite elem_cons in H.
hs_simpl.
rewrite -> orE in H.
elim: H.
move => H.
case Hv: (Foldable.elem v vars).
+ specialize (IHvars v (extendVarSet vs a)).
unfold is_true in *.
apply IHvars.
done.
+ rewrite (lookupVarSet_eq _ H).
rewrite lookupVarSet_extendVarSetList_false.
rewrite lookupVarSet_extendVarSet_self.
hs_simpl.
symmetry. done.
setoid_rewrite H in Hv.
rewrite Hv. done.
+ move=> h.
apply IHvars.
auto.
Qed.
Inductive LastIn : Var -> list Var -> Prop :=
| LastIn_head: forall v1 vs,
Foldable.elem v1 vs = false ->
LastIn v1 (v1 :: vs)
| LastIn_tail: forall v1 v2 vs,
LastIn v1 vs ->
LastIn v1 (v2 :: vs).
Lemma LastIn_elem : forall v vs,
LastIn v vs -> Foldable.elem v vs.
Proof.
move => v vs h.
induction h; hs_simpl; apply /orP.
left. reflexivity.
right. assumption.
Qed.
Lemma LastIn_inj : forall v1 v2 vs,
LastIn v1 vs -> v1 == v2 -> LastIn v2 vs -> v1 = v2.
Proof.
move=> v1 v2 vs h. induction h.
- move=> eq FI.
inversion FI. auto.
subst.
move: (LastIn_elem H2) => h.
rewrite -> HSUtil.elem_resp_eq with (a:= v2) in H; try done.
rewrite Eq_sym. done.
- move=> eq FI. inversion FI.
subst.
move: (LastIn_elem h) => h0.
rewrite -> HSUtil.elem_resp_eq with (a:= v1) in H1; try done.
subst. eauto.
Qed.
Lemma lookupVarSet_extendVarSetList_self_exists_LastIn:
forall (vars:list Var) v vs,
(Foldable.elem v vars) ->
exists v', and3 (lookupVarSet (extendVarSetList vs vars) v = Some v')
(v == v')
(LastIn v' vars).
Proof.
elim => // a vars IH. (* Do induction on first var,
then trivially discharge goal. *)
(* Then introduce names for list components *)
move=> v vs.
hs_simpl.
move => /orP [h1 | h1]. (* case analysis on boolean || *)
case IN: (Foldable.elem v vars).
+ unfold is_true in *.
move: (IH v (extendVarSet vs a) IN) => [v' [p q r]].
exists v'; split; eauto.
eapply LastIn_tail. auto.
+ rewrite lookupVarSet_extendVarSetList_false ; try by rewrite IN.
exists a. split; eauto.
rewrite lookupVarSet_extendVarSet_eq //.
symmetry => //.
eapply LastIn_head.
rewrite <- (elem_eq vars _ _ h1).
done.
+ unfold is_true in *.
move: (IH v (extendVarSet vs a) h1) => [v' [p q r]].
exists v'; split; eauto.
eapply LastIn_tail. auto.
Qed.
(*
Lemma lookupVarSet_extendVarSetList_self_exists_in:
forall (vars:list Var) v vs,
(Foldable.elem v vars) ->
exists v', and3 (lookupVarSet (extendVarSetList vs vars) v = Some v')
(v == v')
(List.In v' vars).
Proof.
elim => // a vars IH. (* Do induction on first var,
then trivially discharge goal. *)
(* Then introduce names for list components *)
move=> v vs.
hs_simpl.
move => /orP [h1 | h1]. (* case analysis on boolean || *)
case IN: (Foldable.elem v vars).
all: try ( unfold is_true in * ; match goal with
[ H : Foldable.elem ?v ?vars = true |- _ ] =>
move: (IH v (extendVarSet vs a) H) => [v'[]]* ;
exists v'; split; eauto using in_cons
end ).
+ rewrite lookupVarSet_extendVarSetList_false ; try by rewrite IN.
exists a. split; eauto.
rewrite lookupVarSet_extendVarSet_eq //.
symmetry => //.
eapply in_eq.
Qed.
*)
Lemma extendVarSetList_same v vars : forall vs1 vs2 ,
Foldable.elem v vars ->
lookupVarSet (extendVarSetList vs1 vars) v =
lookupVarSet (extendVarSetList vs2 vars) v.
Proof.
elim: vars => // a vars IHvars.
- move => vs1 vs2.
hs_simpl.
move=> /orP [h1|h2].
+ case h: (Foldable.elem v vars); eauto.
(* ! rewrites one or more times. *)
rewrite !lookupVarSet_extendVarSetList_false; try (rewrite h; done).
rewrite !lookupVarSet_extendVarSet_eq // ; symmetry ; done.
+ auto.
Qed.
(** ** [mkVarSet] *)
Lemma elemVarSet_mkVarset_iff_In:
forall v vs,
elemVarSet v (mkVarSet vs) <-> List.In (varUnique v) (map varUnique vs).
Proof.
intros.
rewrite mkVarSet_extendVarSetList.
induction vs.
- hs_simpl.
simpl.
done.
- hs_simpl.
simpl map.
split.
+ move /orP.
rewrite -> varUnique_iff.
rewrite -In_varUnique_elem //.
move => [h1|h2] //.
rewrite h1.
apply in_eq.
apply in_cons => //.
+ move => h.
apply /orP.
inversion h.
++ left.
rewrite varUnique_iff //.
++ right.
apply In_varUnique_elem => //.
Qed.
(** ** [delVarSet] *)
Lemma delVarSet_elemVarSet_false : forall v set,
elemVarSet v set = false -> delVarSet set v [=] set.
intros.
set_b_iff.
apply remove_equal.
auto.
Qed.
Lemma delVarSet_emptyVarSet x :
delVarSet emptyVarSet x = emptyVarSet.
Proof.
unfold delVarSet, emptyVarSet.
unfold UniqSet.delOneFromUniqSet , UniqSet.emptyUniqSet.
unfold UniqFM.delFromUFM, UniqFM.emptyUFM.
f_equal.
Qed.
Hint Rewrite delVarSet_emptyVarSet : hs_simpl.
Lemma delVarSet_extendVarSet :
forall set v,
elemVarSet v set = false -> (delVarSet (extendVarSet set v) v) [=] set.
Proof.
intros.
set_b_iff.
apply remove_add.
auto.
Qed.
Lemma elemVarSet_delVarSet: forall v1 fvs v2,
elemVarSet v1 (delVarSet fvs v2) = negb (v2 == v1) && elemVarSet v1 fvs.
Proof.
intros.
destruct elemVarSet eqn:EL.
+ symmetry.
apply andb_true_intro.
set_b_iff.
rewrite -> remove_iff in EL.
unfold Var_as_DT.eqb in EL. unfold not in EL.
rewrite negb_true_iff.
intuition.
apply not_true_is_false.
auto.
+ symmetry.
apply not_true_is_false.
intro H.
apply andb_prop in H.
set_b_iff.
rewrite -> remove_iff in EL.
unfold Var_as_DT.eqb in *.
intuition.
rewrite -> negb_true_iff in H0.
apply H2.
intro h.
unfold Var_as_DT.t in *.
rewrite h in H0.
inversion H0.
Qed.
Hint Rewrite elemVarSet_delVarSet : hs_simpl.
Lemma lookupVarSet_delVarSet_neq :
forall v1 v2 vs,
not (v1 == v2) ->
lookupVarSet (delVarSet vs v1) v2 = lookupVarSet vs v2.
Proof.
intros v1 v2 vs H.
unfold lookupVarSet,delVarSet.
unfold UniqSet.lookupUniqSet, UniqSet.delOneFromUniqSet.
destruct vs.
unfold UniqFM.lookupUFM, UniqFM.delFromUFM.
destruct getUniqSet'.
assert (Unique.getWordKey (Unique.getUnique v1) <>
Unique.getWordKey (Unique.getUnique v2)).
{ intro h. apply H. rewrite eq_unique. done. }
rewrite delete_neq.
auto.
auto.
Qed.
Lemma elemVarSet_delVarSet_eq x y vs :
(x == y) -> elemVarSet x (delVarSet vs y) = false.
Proof.
rewrite -> eq_unique.
move => Eq.
unfold elemVarSet, delVarSet.
unfold UniqSet.elementOfUniqSet, UniqSet.delOneFromUniqSet.
move: vs => [i].
move: i => [m].
unfold UniqFM.elemUFM, UniqFM.delFromUFM.
rewrite Eq.
set key := Unique.getWordKey (Unique.getUnique y).
move: (@delete_eq key Var m).
rewrite <- non_member_lookup.
move => h. rewrite h.
done.
Qed.
(** ** [delVarSetList] *)
(* These next two rely on this strong property about the unique
representations of IntMaps. *)
Lemma delVarSet_commute : forall x y vs,
delVarSet (delVarSet vs x) y = delVarSet (delVarSet vs y) x.
Proof.
intros.
unfold delVarSet.
unfold UniqSet.delOneFromUniqSet.
destruct vs.
f_equal.
unfold UniqFM.delFromUFM.
destruct getUniqSet'.
f_equal.
set (kx := Unique.getWordKey (Unique.getUnique x)).
set (ky := Unique.getWordKey (Unique.getUnique y)).
eapply delete_commute; eauto.
Qed.
Lemma delVarSetList_cons2:
forall vs e a, delVarSetList e (a :: vs) = delVarSet (delVarSetList e vs) a.
Proof.
induction vs; intros e a1;
rewrite -> delVarSetList_cons in *.
- set_b_iff.
hs_simpl.
reflexivity.
- rewrite delVarSetList_cons.
rewrite delVarSetList_cons.
rewrite delVarSet_commute.
rewrite <- IHvs.
rewrite delVarSetList_cons.
auto.
Qed.
Lemma delVarSetList_rev:
forall vs1 vs2,
delVarSetList vs1 (rev vs2) = delVarSetList vs1 vs2.
Proof.
induction vs2.
- simpl. auto.
- simpl rev.
rewrite delVarSetList_cons.
rewrite delVarSetList_app.
rewrite IHvs2.
rewrite delVarSetList_cons.
rewrite delVarSetList_nil.
rewrite <- delVarSetList_cons2.
rewrite delVarSetList_cons.
reflexivity.
Qed.
Lemma elemVarSet_delVarSetList_false_l:
forall v vs vs2,
elemVarSet v vs = false ->
elemVarSet v (delVarSetList vs vs2) = false.
Proof.
intros.
revert vs H; induction vs2; intros.
* rewrite delVarSetList_nil.
assumption.
* rewrite delVarSetList_cons.
apply IHvs2.
set_b_iff; fsetdec.
Qed.
Lemma delVarSet_unionVarSet:
forall vs1 vs2 x,
delVarSet (unionVarSet vs1 vs2) x [=]
unionVarSet (delVarSet vs1 x) (delVarSet vs2 x).
Proof.
intros.
set_b_iff.
fsetdec.
Qed.
Lemma delVarSetList_unionVarSet:
forall vs3 vs1 vs2,
delVarSetList (unionVarSet vs1 vs2) vs3 [=]
unionVarSet (delVarSetList vs1 vs3) (delVarSetList vs2 vs3).
Proof.
induction vs3; intros.
- repeat rewrite delVarSetList_nil.
reflexivity.
- repeat rewrite delVarSetList_cons.
rewrite delVarSet_unionVarSet.
rewrite IHvs3.
reflexivity.
Qed.
(**************************************)
(** ** [subVarSet] *)
Lemma subVarSet_refl:
forall vs1,
subVarSet vs1 vs1 .
Proof.
intros.
set_b_iff.
fsetdec.
Qed.
Lemma subVarSet_trans:
forall vs1 vs2 vs3,
subVarSet vs1 vs2 ->
subVarSet vs2 vs3 ->
subVarSet vs1 vs3 .
Proof.
intros.
set_b_iff.
fsetdec.
Qed.
Lemma subVarSet_emptyVarSet:
forall vs,
subVarSet emptyVarSet vs .
Proof.
intros.
set_b_iff.
fsetdec.
Qed.
Lemma subVarSet_unitVarSet:
forall v vs,
subVarSet (unitVarSet v) vs = elemVarSet v vs.
Proof.
intros.
destruct subVarSet eqn:SV; symmetry.
+ set_b_iff.
fsetdec.
+ rewrite -> false_is_not_true in *.
set_b_iff.
intro h.
unfold Subset in SV.
apply SV.
intros.
rewrite In_eq_iff; eauto.
Qed.
Lemma elemVarSet_false_true:
forall v1 fvs v2,
elemVarSet v1 fvs = false ->
elemVarSet v2 fvs ->
varUnique v1 <> varUnique v2.
Proof.
intros v1 fvs v2.
intros.
assert (not (v2 == v1 )).
intro h.
set_b_iff.
rewrite -> In_eq_iff in H0; eauto.
intro h.
rewrite <- varUnique_iff in h.
apply H1.
rewrite Eq_sym.
auto.
Qed.
Lemma subVarSet_elemVarSet_true:
forall v vs vs',
subVarSet vs vs' ->
elemVarSet v vs ->
elemVarSet v vs' .
Proof.
intros v vs vs'.
set_b_iff.
fsetdec.
Qed.
Lemma subVarSet_elemVarSet_false:
forall v vs vs',
subVarSet vs vs' ->
elemVarSet v vs' = false ->
elemVarSet v vs = false.
Proof.
intros v vs vs'.
set_b_iff.
fsetdec.
Qed.
Lemma subVarSet_extendVarSetList_l:
forall vs1 vs2 vs,
subVarSet vs1 vs2 ->
subVarSet vs1 (extendVarSetList vs2 vs) .
Proof.
intros vs1 vs2 vs.
generalize dependent vs2.
induction vs.
- intro vs2. rewrite extendVarSetList_nil. auto.
- intro vs2. intro h.
rewrite extendVarSetList_cons.
rewrite IHvs. auto.
set_b_iff. fsetdec.
Qed.
Lemma subVarSet_extendVarSet_both:
forall vs1 vs2 v,
subVarSet vs1 vs2 ->
subVarSet (extendVarSet vs1 v) (extendVarSet vs2 v) .
Proof.
intros.
set_b_iff.
fsetdec.
Qed.
Lemma subVarSet_extendVarSet:
forall vs1 vs2 v,
subVarSet vs1 vs2 ->
subVarSet vs1 (extendVarSet vs2 v) .
Proof.
intros.
set_b_iff.
fsetdec.
Qed.
Lemma subVarSet_extendVarSetList:
forall vs1 vs2 vs3,
subVarSet vs1 vs2 ->
subVarSet vs1 (extendVarSetList vs2 vs3) .
Proof.
induction vs3; autorewrite with hs_simpl.
- auto.
- intro h.
rewrite extendVarSetList_extendVarSet_iff.
rewrite subVarSet_extendVarSet; auto.
Qed.
Lemma subVarSet_extendVarSet_l:
forall vs1 vs2 v v',
subVarSet vs1 vs2 ->
lookupVarSet vs2 v = Some v' ->
subVarSet (extendVarSet vs1 v) vs2 .
Proof.
intros.
set_b_iff.
apply MP.subset_add_3; try assumption.
apply lookupVarSet_In.
eauto.
Qed.
Lemma extendVarSet_subset: forall v1 v2 x,
v1 [<=] v2 ->
extendVarSet v1 x [<=] extendVarSet v2 x.
Proof.
intros.
set_b_iff.
fsetdec.
Qed.
Lemma extendVarSetList_subset: forall x y vs,
x [<=] y ->
extendVarSetList x vs [<=] extendVarSetList y vs.
Proof.
intros.
induction vs; hs_simpl; [assumption|].
do 2 rewrite extendVarSetList_extendVarSet_iff.
apply extendVarSet_subset.
assumption.
Qed.
Lemma subVarSet_extendVarSetList_r:
forall vs vs1 vs2,
subVarSet vs1 (mkVarSet vs) ->
subVarSet vs1 (extendVarSetList vs2 vs) .
Proof.
intros vs.
rewrite mkVarSet_extendVarSetList.
induction vs; intros vs1 vs2.
- autorewrite with hs_simpl.
set_b_iff.
fsetdec.
- intro h.
autorewrite with hs_simpl in *.
rewrite -> extendVarSetList_extendVarSet_iff in *.
destruct (mem a (extendVarSetList empty vs)) eqn:Hd;
[|destruct (mem a vs1) eqn:Hd'].
+ specialize (IHvs vs1 vs2).
set_b_iff.
assert (Hvs2: In a (extendVarSetList vs2 vs)).
* clear -Hd.
eapply MP.in_subset.
apply Hd. clear Hd a.
apply extendVarSetList_subset.
fsetdec.
* pose proof (subset_equal
(equal_sym (add_equal Hvs2))).
eapply (Subset_trans); [apply IHvs| apply H].
pose proof (subset_equal (add_equal Hd)).
fsetdec.
+ specialize (IHvs (remove a vs1) vs2).
set_b_iff.
apply remove_s_m with (x:= a) (y:=a) in h;
[|fsetdec].
assert (Hs: remove a (add a
(extendVarSetList empty vs))
[<=] (extendVarSetList empty vs)).
{ apply subset_equal.
apply remove_add.
assumption. }
specialize (IHvs (Subset_trans h Hs)).
apply add_s_m with (x:= a) (y:=a) in IHvs;
[|fsetdec].
assert (Hs': vs1 [<=] add a (remove a vs1)).
{ apply subset_equal.
apply equal_sym.
apply add_remove.
assumption. }
eapply Subset_trans.
apply Hs'.
assumption.
+ specialize (IHvs vs1 vs2).
set_b_iff.
apply subset_add_2.
apply IHvs.
eapply remove_s_m with (x:= a) (y:=a) in h;
[|fsetdec].
apply remove_equal in Hd'.
fsetdec.
Qed.
Lemma subVarSet_delVarSet:
forall vs1 v,
subVarSet (delVarSet vs1 v) vs1 .
Proof.
intros.
set_b_iff.
fsetdec.
Qed.
Lemma subVarSet_delVarSetList:
forall vs1 vl,
subVarSet (delVarSetList vs1 vl) vs1 .
Proof.
intros.
set_b_iff.
generalize vs1. clear vs1. induction vl.
- intros vs1. hs_simpl.
fsetdec.
- intros vs1. revert IHvl.
hs_simpl.
simpl.
intro IH.
rewrite -> IH with (vs1 := delVarSet vs1 a).
set_b_iff.
fsetdec.
Qed.
Lemma subVarSet_delVarSetList_both:
forall vs1 vs2 vl,
subVarSet vs1 vs2 ->
subVarSet (delVarSetList vs1 vl) (delVarSetList vs2 vl) .
Proof.
intros.
revert vs1 vs2 H. induction vl; intros.
- rewrite !delVarSetList_nil.
assumption.
- rewrite !delVarSetList_cons.
apply IHvl.
set_b_iff.
fsetdec.
Qed.
Lemma subVarSet_delVarSet_extendVarSet:
forall jps isvs v,
subVarSet jps isvs ->
subVarSet (delVarSet jps v) (extendVarSet isvs v) .
Proof.
intros.
eapply subVarSet_trans.
apply subVarSet_delVarSet.
apply subVarSet_extendVarSet.
assumption.
Qed.
Lemma subVarSet_delVarSetList_extendVarSetList:
forall jps isvs vs,
subVarSet jps isvs ->
subVarSet (delVarSetList jps vs) (extendVarSetList isvs vs) .
Proof.
intros.
eapply subVarSet_trans.
apply subVarSet_delVarSetList.
apply subVarSet_extendVarSetList.
assumption.
Qed.
Lemma subVarSet_delVarSetList_extendVarSetList_dual:
forall jps isvs vs,
subVarSet jps (extendVarSetList isvs vs) ->
subVarSet (delVarSetList jps vs) isvs .
Proof.
intros.
revert jps isvs H.
induction vs; intros.
- rewrite !delVarSetList_nil.
rewrite !extendVarSetList_nil in H.
assumption.
- rewrite delVarSetList_cons2.
revert H.
hs_simpl.
intro H.
apply IHvs in H.
set_b_iff.
fsetdec.
Qed.
Lemma mapUnionVarSet_In_subVarSet:
forall a (x : a) xs f,
List.In x xs ->
subVarSet (f x) (mapUnionVarSet f xs).
Proof.
intros a x xs f H.
generalize dependent x.
induction xs; intros x H.
- inversion H.
-
inversion H as [H'|H'].
+ unfold mapUnionVarSet.
unfold_Foldable_foldr.
subst.
simpl.
set_b_iff.
fsetdec.
+ apply IHxs in H'.
clear H IHxs.
revert H'.
unfold mapUnionVarSet.
unfold_Foldable_foldr.
intros H'.
eapply subVarSet_trans.
apply H'.
clear H'.
set_b_iff.
simpl.
fsetdec.
Qed.
Lemma subVarSet_mapUnionVarSet:
forall a (xs : list a) f vs,
Forall (fun x => subVarSet (f x) vs ) xs ->
subVarSet (mapUnionVarSet f xs) vs.
Proof.
intros a xs f vs H.
induction xs.
- unfold mapUnionVarSet.
unfold_Foldable_foldr.
simpl.
apply subVarSet_emptyVarSet.
- inversion H.
subst.
apply IHxs in H3.
clear IHxs.
revert H3.
unfold mapUnionVarSet.
unfold_Foldable_foldr.
intros H3.
set_b_iff.
simpl.
fsetdec.
Qed.
Lemma subVarSet_unionVarSet:
forall vs1 vs2 vs3,
subVarSet (unionVarSet vs1 vs2) vs3 = subVarSet vs1 vs3 && subVarSet vs2 vs3.
Proof.
intros.
apply eq_iff_eq_true.
rewrite andb_true_iff.
set_b_iff.
split; intro H.
- split; fsetdec.
- destruct H; fsetdec.
Qed.
Axiom null_intersection_eq : forall b (x1 x2 y1 y2 : IntMap.Internal.IntMap b),
(forall a, IntMap.Internal.member a x1 <-> IntMap.Internal.member a y1) ->
(forall a, IntMap.Internal.member a x2 <-> IntMap.Internal.member a y2) ->
IntMap.Internal.null (IntMap.Internal.intersection x1 x2) = IntMap.Internal.null (IntMap.Internal.intersection y1 y2).
(** ** [disjointVarSet] *)
Instance disjointVarSet_m : Proper (Equal ==> Equal ==> Logic.eq) disjointVarSet.
Proof.
move => x1 y1.
move: (@ValidVarSet_Axiom x1).
move: (@ValidVarSet_Axiom y1).
move: x1 => [x1]. move: y1=> [y1].
move: x1 => [x1]. move: y1=> [y1].
move=> vx1 vy1 Eq1.
move=> x2 y2.
move: (@ValidVarSet_Axiom x2). move: (@ValidVarSet_Axiom y2).
move: x2 => [x2]. move: y2=> [y2].
move: x2 => [x2]. move: y2=> [y2].
move=> vx2 vy2 Eq2.
unfold ValidVarSet, disjointVarSet,
UniqFM.disjointUFM,
UniqSet.getUniqSet,
UniqSet.getUniqSet' in *.
unfold lookupVarSet, UniqSet.lookupUniqSet,UniqFM.lookupUFM in *.
unfold Equal, In, elemVarSet, UniqSet.elementOfUniqSet, UniqFM.elemUFM in Eq1.
unfold Equal, In, elemVarSet, UniqSet.elementOfUniqSet, UniqFM.elemUFM in Eq2.
apply null_intersection_eq; eauto.
move=> k1.
split. move=> Ink1.
Admitted.
(*
Lemma foldl'_simplify (a b c :Type) (f:c -> b) (g:b->c) (h:b -> a -> b)
(xb:b) (xs : list a):
(forall x, f (g x) = x) ->
Foldable.foldl' (fun x y => g (h (f x) y)) (g xb) xs =
g (Foldable.foldl' h xb xs).
Proof.
move => eq.
induction xs.
hs_simpl. auto.
hs_simpl.
rewrite eq.
*)
Lemma UniqSet_Mk_UniqSet_eta :
forall a b (x : UniqSet.UniqSet a) (f : UniqSet.UniqSet a -> b),
match x with
| UniqSet.Mk_UniqSet set => f (UniqSet.Mk_UniqSet set)
end = f x.
Proof.
move => a b [set] //.
Qed.
Lemma disjointVarSet_empytVarSet:
forall vs,
disjointVarSet vs emptyVarSet.
Proof.
move => vs1.
elim: vs1 => [i].
unfold disjointVarSet, emptyVarSet, elemVarSet.
simpl.
elim: i => [j].
simpl.
apply intersection_empty.
done.
Qed.
Hint Rewrite disjointVarSet_empytVarSet:hs_simpl.
Lemma disjointVarSet_mkVarSet_nil:
forall vs,
disjointVarSet vs (mkVarSet []).
Proof.
rewrite mkVarSet_extendVarSetList.
hs_simpl.
apply disjointVarSet_empytVarSet.
Qed.
Lemma disjointVarSet_extendVarSet vs1 var vs2 :
disjointVarSet vs1 (extendVarSet vs2 var) <->
elemVarSet var vs1 = false /\ disjointVarSet vs1 vs2.
Proof.
move: vs1 vs2 => [[i1]] [[i2]].
unfold disjointVarSet, elemVarSet, extendVarSet.
unfold UniqSet.getUniqSet,UniqSet.getUniqSet',
UniqSet.elementOfUniqSet, UniqSet.addOneToUniqSet.
unfold UniqFM.disjointUFM, UniqFM.elemUFM, UniqFM.addToUFM.
set k:= (Unique.getWordKey (Unique.getUnique var)).
apply null_intersection_non_member.
Qed.
Lemma disjointVarSet_mkVarSet_cons:
forall v vs1 vs2,
disjointVarSet vs1 (mkVarSet (v :: vs2)) <->
elemVarSet v vs1 = false /\ disjointVarSet vs1 (mkVarSet vs2) .
Proof.
move=> v vs1 vs2.
rewrite mkVarSet_extendVarSetList.
hs_simpl.
rewrite extendVarSetList_extendVarSet_iff.
rewrite disjointVarSet_extendVarSet.
tauto.
Qed.
Lemma disjointVarSet_mkVarSet_append:
forall vs1 vs2 vs3,
disjointVarSet vs1 (mkVarSet (vs2 ++ vs3)) <->
disjointVarSet vs1 (mkVarSet vs2) /\ disjointVarSet vs1 (mkVarSet vs3).
Proof.
move=> vs1 vs2 vs3.
rewrite mkVarSet_extendVarSetList.
hs_simpl.
elim: vs3 => [|var vars IH]; hs_simpl.
+ rewrite mkVarSet_extendVarSetList.
intuition.
+ rewrite disjointVarSet_mkVarSet_cons.
rewrite and_comm.
rewrite and_assoc.
rewrite -> and_comm in IH.
rewrite <- IH.
rewrite extendVarSetList_extendVarSet_iff.
rewrite disjointVarSet_extendVarSet.
tauto.
Qed.
Lemma disjointVarSet_mkVarSet:
forall vs1 vs2,
disjointVarSet vs1 (mkVarSet vs2) <->
Forall (fun v => elemVarSet v vs1 = false) vs2.
Proof.
move => vs1 vs2.
elim: vs2 => [|v vars IH].
rewrite disjointVarSet_mkVarSet_nil. intuition.
rewrite disjointVarSet_mkVarSet_cons. rewrite IH.
intuition.
- inversion H1. auto.
- inversion H1. auto.
Qed.
Lemma disjointVarSet_subVarSet_l:
forall vs1 vs2 vs3,
disjointVarSet vs2 vs3 ->
subVarSet vs1 vs2 ->
disjointVarSet vs1 vs3 .
Proof.
move=> [[i1]][[i2]][[i3]].
unfold disjointVarSet, subVarSet, isEmptyVarSet,minusVarSet.
unfold UniqSet.getUniqSet,UniqSet.getUniqSet',
UniqSet.isEmptyUniqSet, UniqSet.minusUniqSet.
unfold UniqFM.disjointUFM, UniqFM.isNullUFM, UniqFM.minusUFM.
apply disjoint_difference.
Qed.
(** ** [filterVarSet] *)
Lemma filterVarSet_comp : forall f f' vs,
filterVarSet f (filterVarSet f' vs) = filterVarSet (fun v => f v && f' v) vs.
Proof.
intros.
destruct vs; destruct getUniqSet'. simpl. do 2 f_equal.
apply filter_comp.
Qed.
Lemma filterSingletonTrue : forall f x,
RespectsVar f ->
f x = true ->
filterVarSet f (unitVarSet x) [=] unitVarSet x.
Proof.
move=> f x RR TR.
set_b_iff.
replace (singleton x) with (add x empty).
rewrite -> filter_add_1; auto.
fsetdec.
fsetdec.
Qed.
Lemma filterSingletonFalse : forall f x,
RespectsVar f ->
f x = false ->
filterVarSet f (unitVarSet x) [=] emptyVarSet.
Proof.
move=> f x RR TR.
set_b_iff.
replace (singleton x) with (add x empty).
rewrite -> filter_add_2; auto.
fsetdec.
fsetdec.
Qed.
Lemma filterVarSet_emptyVarSet f :
filterVarSet f emptyVarSet = emptyVarSet.
Proof.
set_b_iff.
fsetdec.
Qed.
Hint Rewrite filterVarSet_emptyVarSet : hs_simpl.
Lemma filterVarSet_constTrue vs :
filterVarSet (const true) vs = vs.
Proof.
unfold filterVarSet.
elim: vs => [i].
elim: i => [m].
unfold UniqSet.filterUniqSet.
unfold UniqFM.filterUFM.
f_equal.
f_equal.
rewrite filter_true.
reflexivity.
Qed.
Hint Rewrite filterVarSet_constTrue : hs_simpl.
Lemma elemVarSet_filterVarSet x f vs :
RespectsVar f ->
elemVarSet x (filterVarSet f vs) = f x && elemVarSet x vs.
Proof.
move => h.
rewrite eqE.
set_b_iff.
rewrite andE.
unfold is_true.
set_b_iff.
rewrite and_comm.
apply F.filter_iff.
auto.
Qed.
Lemma filterVarSet_iff (f1 f2 : Var -> bool) vs :
(forall x, (f1 x) <-> (f2 x)) ->
filterVarSet f1 vs [=] filterVarSet f2 vs.
Admitted.
Lemma filterVarSet_equal f vs1 vs2 :
RespectsVar f ->
vs1 [=] vs2 ->
filterVarSet f vs1 [=] filterVarSet f vs2.
Proof.
move => RF EQ.
set_b_iff.
eapply filter_equal; eauto.
Qed.
Lemma filterVarSet_extendVarSet :
forall f v vs,
RespectsVar f ->
filterVarSet f (extendVarSet vs v) [=]
if (f v) then extendVarSet (filterVarSet f vs) v
else (filterVarSet f vs).
Proof.
intros.
set_b_iff.
destruct (f v) eqn:Hfv; auto.
rewrite -> filter_add_1; try done.
rewrite -> filter_add_2; try done.
Qed.
Lemma lookupVarSet_filterVarSet_true : forall f v vs,
RespectsVar f ->
f v = true ->
lookupVarSet (filterVarSet f vs) v = lookupVarSet vs v.
Proof.
intros.
destruct (lookupVarSet (filterVarSet f vs) v) eqn:Hl.
- revert Hl.
unfold_VarSet_to_IntMap.
unfold IntMap.Internal.filter.
symmetry.
erewrite lookup_filterWithKey; eauto.
- apply lookupVarSet_None_elemVarSet in Hl.
symmetry.
apply lookupVarSet_None_elemVarSet.
set_b_iff.
intros Hin.
eapply filter_3 in Hin; eauto.
Qed.
Lemma lookupVarSet_filterVarSet_false : forall f v vs,
RespectsVar f ->
f v = false ->
lookupVarSet (filterVarSet f vs) v = None.
Proof.
intros.
apply lookupVarSet_None_elemVarSet.
set_b_iff.
rewrite filter_iff; [|auto].
intros [H1 H2].
rewrite H0 in H2.
inversion H2.
Qed.
Lemma unionVarSet_filterVarSet f vs1 vs2 :
RespectsVar f ->
unionVarSet (filterVarSet f vs1) (filterVarSet f vs2) [=] filterVarSet f (unionVarSet vs1 vs2).
Proof.
move=> g.
set_b_iff.
rewrite <- filter_union.
reflexivity.
eauto.
Qed.
Lemma filterVarSet_delVarSet f vs v :
RespectsVar f ->
filterVarSet f (delVarSet vs v) [=]
delVarSet (filterVarSet f vs) v.
Proof.
move=> Ff. unfold RespectsVar in Ff.
set_b_iff.
Admitted.
Lemma filterVarSet_delVarSetList:
forall (f : Var -> bool) (vars : list Var) (vs : VarSet),
RespectsVar f ->
filterVarSet f (delVarSetList vs vars) [=] delVarSetList (filterVarSet f vs) vars.
Proof.
induction vars.
- move=> vs h. hs_simpl. reflexivity.
- move=> vs h. hs_simpl.
rewrite IHvars; try done.
rewrite <- filterVarSet_delVarSet; try done.
Qed.
(** ** [unionVarSet] *)
Lemma unionVarSet_sym vs1 vs2 : unionVarSet vs1 vs2 [=] unionVarSet vs2 vs1.
Proof. set_b_iff. fsetdec. Qed.
Lemma unionEmpty_l : forall vs,
unionVarSet emptyVarSet vs [=] vs.
Proof. set_b_iff. fsetdec. Qed.
Lemma unionEmpty_r : forall vs,
unionVarSet vs emptyVarSet [=] vs.
Proof. set_b_iff. fsetdec. Qed.
Lemma unionSingle_l : forall x s,
unionVarSet (unitVarSet x) s [=] extendVarSet s x.
Proof. intros. set_b_iff. fsetdec. Qed.
Lemma unionSingle_r : forall x s,
unionVarSet s (unitVarSet x) [=] extendVarSet s x.
Proof. intros. set_b_iff. fsetdec. Qed.
Hint Rewrite unionEmpty_l unionEmpty_r
unionSingle_l unionSingle_r :
hs_simpl.
(** ** [minusVarSet] *)
Lemma minusVarSet_emptyVarSet vs :
minusVarSet vs emptyVarSet = vs.
Proof.
unfold minusVarSet, emptyVarSet.
unfold UniqSet.minusUniqSet, UniqSet.emptyUniqSet.
elim: vs => [i].
elim: i => [m].
unfold UniqFM.minusUFM, UniqFM.emptyUFM.
f_equal.
f_equal.
unfold IntMap.Internal.empty.
rewrite difference_nil_r.
reflexivity.
Qed.
Hint Rewrite minusVarSet_emptyVarSet : hs_simpl.
Lemma minusVarSet_emptyVarSet_l vs :
minusVarSet emptyVarSet vs = emptyVarSet.
Proof.
unfold minusVarSet, emptyVarSet.
unfold UniqSet.minusUniqSet, UniqSet.emptyUniqSet.
elim: vs => [i].
elim: i => [m].
unfold UniqFM.minusUFM, UniqFM.emptyUFM.
f_equal.
f_equal.
unfold IntMap.Internal.empty.
rewrite difference_nil_l.
reflexivity.
Qed.
Hint Rewrite minusVarSet_emptyVarSet_l : hs_simpl.
Lemma elemVarSet_minusVarSetTrue : forall x s,
elemVarSet x s = true ->
minusVarSet (unitVarSet x) s [=] emptyVarSet.
Proof. intros. set_b_iff.
split; try fsetdec.
move=> h.
move: (diff_1 _ _ _ h) => h1.
move: (diff_2 _ _ _ h) => h2.
inversion h1. clear h1.
rewrite <- var_eq_realUnique in H1.
rewrite -> fold_is_true in H1.
unfold In in H, h2.
rewrite (@elemVarSet_eq a x) in h2.
done.
done.
Qed.
Lemma elemVarSet_minusVarSetFalse : forall x s,
elemVarSet x s = false ->
minusVarSet (unitVarSet x) s [=] unitVarSet x.
Proof.
intros.
set_b_iff.
split; try fsetdec.
move=> h.
apply diff_3; try done.
inversion h.
unfold In, singleton in *.
rewrite (@elemVarSet_eq x a) in H; try done.
rewrite var_eq_realUnique.
rewrite Eq_sym; done.
Qed.
Lemma elemVarSet_minusVarSet x vs1 vs2 :
elemVarSet x (minusVarSet vs1 vs2) = elemVarSet x vs1 && ~~ elemVarSet x vs2.
Proof.
rewrite eqE.
set_b_iff.
rewrite F.diff_iff.
split.
move => [h1 h2]. apply /andP. split. auto.
apply /negPf.
set_b_iff. auto.
move => /andP [h1 h2].
move: h2 => /negPf => h2.
set_b_iff. auto.
Qed.
Lemma unionVarSet_minusVarSet vs1 vs2 vs :
unionVarSet (minusVarSet vs1 vs) (minusVarSet vs2 vs) [=]
minusVarSet (unionVarSet vs1 vs2) vs.
Proof.
unfold Equal.
move=> x.
unfold In.
rewrite! elemVarSet_minusVarSet.
rewrite! elemVarSet_unionVarSet.
rewrite! elemVarSet_minusVarSet.
rewrite! andb_orb_distrib_l.
reflexivity.
Qed.
(** ** Compatibility with [almostEqual] *)
Lemma lookupVarSet_ae :
forall vs v1 v2,
almostEqual v1 v2 ->
lookupVarSet vs v1 = lookupVarSet vs v2.
Proof.
induction 1; simpl; unfold UniqFM.lookupUFM; simpl; auto.
Qed.
Lemma delVarSet_ae:
forall vs v1 v2,
almostEqual v1 v2 ->
delVarSet vs v1 = delVarSet vs v2.
Proof.
induction 1; simpl;
unfold UniqFM.delFromUFM; simpl; auto.
Qed.
Lemma elemVarSet_ae:
forall vs v1 v2,
almostEqual v1 v2 ->
elemVarSet v1 vs = elemVarSet v2 vs.
Proof.
induction 1; simpl;
unfold UniqFM.delFromUFM; simpl; auto.
Qed.
(** ** [StrongSubset] *)
(* A strong subset doesn't just have a subset of the uniques, but
also requires that the variables in common be almostEqual. *)
Definition StrongSubset (vs1 : VarSet) (vs2: VarSet) :=
forall var, match lookupVarSet vs1 var with
| Some v => match lookupVarSet vs2 var with
| Some v' => almostEqual v v'
| None => False
end
| None => True
end.
Notation "s1 {<=} s2" := (StrongSubset s1 s2) (at level 70, no associativity).
Notation "s1 {=} s2" := (StrongSubset s1 s2 /\ StrongSubset s2 s1) (at level 70, no associativity).
Lemma StrongSubset_refl : forall vs,
StrongSubset vs vs.
Proof.
unfold StrongSubset.
move=> vs var.
elim h: (lookupVarSet vs var) => //.
eapply almostEqual_refl.
Qed.
Instance StrongSubset_Reflexive : Reflexive StrongSubset := StrongSubset_refl.
Lemma StrongSubset_trans : forall vs1 vs2 vs3,
StrongSubset vs1 vs2 -> StrongSubset vs2 vs3 -> StrongSubset vs1 vs3.
Proof.
move => vs1 vs2 vs3 h1 h2 var.
specialize (h1 var).
specialize (h2 var).
move: h1 h2.
elim p1: (lookupVarSet vs1 var) => //;
elim p2: (lookupVarSet vs2 var) => //;
elim p3: (lookupVarSet vs3 var) => //.
eapply almostEqual_trans.
Qed.
Instance StrongSubset_Transitive : Transitive StrongSubset := StrongSubset_trans.
Lemma strongSubset_implies_subset :
forall vs1 vs2 ,
StrongSubset vs1 vs2 -> vs1 [<=] vs2.
Proof.
intros vs1 vs2.
unfold StrongSubset, Subset.
intros SS var IN.
unfold In in *.
specialize (SS var).
destruct (lookupVarSet vs1 var) eqn:VS1;
destruct (lookupVarSet vs2 var) eqn:VS2; try contradiction.
- apply lookupVarSet_elemVarSet in VS2.
auto.
- apply elemVarSet_lookupVarSet in IN. destruct IN.
rewrite VS1 in H. discriminate.
- apply elemVarSet_lookupVarSet in IN. destruct IN.
rewrite VS1 in H. discriminate.
Qed.
Lemma StrongSubset_extend_fresh :
forall vs v,
lookupVarSet vs v = None ->
StrongSubset vs (extendVarSet vs v).
Proof.
intros.
unfold StrongSubset.
intros var.
destruct (var == v) eqn:EQV.
rewrite -> lookupVarSet_eq with (v2 := v); auto.
rewrite H. auto.
destruct (lookupVarSet vs var) eqn:Lvar; auto.
rewrite lookupVarSet_extendVarSet_neq.
rewrite Lvar.
apply almostEqual_refl.
unfold CoreBndr in *. intro h. rewrite Base.Eq_sym in h. rewrite h in EQV. discriminate.
Qed.
Lemma elemNegbDisjoint : forall vs vs2,
disjointVarSet vs (mkVarSet vs2) ->
forall v, Foldable.elem v vs2 -> negb (elemVarSet v vs).
Proof.
move=> vs.
elim => [|x xs IHxs].
- move => ? v. hs_simpl. done.
- rewrite disjointVarSet_mkVarSet_cons.
move => [h1 h2] v.
hs_simpl.
move => /orP [h3|h3].
erewrite (@elemVarSet_eq x v) in h1.
rewrite h1. done.
symmetry. done.
apply IHxs; try done.
Qed.
Lemma StrongSubset_extendList_fresh :
forall vs vs2,
disjointVarSet vs (mkVarSet vs2) ->
StrongSubset vs (extendVarSetList vs vs2).
Proof.
intros.
unfold StrongSubset.
intros v.
destruct_match; try trivial.
case in2: (Foldable.elem v vs2).
* eapply elemNegbDisjoint in in2; eauto.
eapply lookupVarSet_elemVarSet in Heq; eauto.
erewrite Heq in in2. done.
* rewrite lookupVarSet_extendVarSetList_false; try done.
rewrite Heq.
eapply almostEqual_refl.
rewrite in2. done.
Qed.
Lemma StrongSubset_extend_ae :
forall vs1 vs2 v1 v2,
StrongSubset vs1 vs2 ->
almostEqual v1 v2 ->
StrongSubset (extendVarSet vs1 v1) (extendVarSet vs2 v2).
Proof.
intros.
unfold StrongSubset in *.
intro var.
destruct (v1 == var) eqn:EQv.
rewrite lookupVarSet_extendVarSet_eq; auto.
rewrite lookupVarSet_extendVarSet_eq.
assumption.
apply almostEqual_eq in H0. eapply Eq_trans; try eassumption; try symmetry; assumption.
rewrite lookupVarSet_extendVarSet_neq; auto.
rewrite lookupVarSet_extendVarSet_neq; auto.
eapply H.
rewrite <- not_true_iff_false in EQv. contradict EQv.
apply almostEqual_eq in H0. eapply Eq_trans; try eassumption; try symmetry; assumption.
rewrite not_true_iff_false. assumption.
Qed.
Lemma StrongSubset_extend :
forall vs1 vs2 v,
StrongSubset vs1 vs2 ->
StrongSubset (extendVarSet vs1 v) (extendVarSet vs2 v).
Proof.
intros.
apply StrongSubset_extend_ae.
* assumption.
* apply almostEqual_refl.
Qed.
Lemma StrongSubset_extendVarSetList_ae :
forall l1 l2 vs1 vs2,
Forall2 almostEqual l1 l2 ->
StrongSubset vs1 vs2 ->
StrongSubset (extendVarSetList vs1 l1) (extendVarSetList vs2 l2).
Proof.
intros.
revert vs1 vs2 H0. induction H; intros.
* apply H0.
* rewrite extendVarSetList_cons.
apply IHForall2.
apply StrongSubset_extend_ae; assumption.
Qed.
Lemma Forall2_diag:
forall a P (xs: list a),
Forall2 P xs xs <-> Forall (fun x => P x x) xs.
Proof.
intros.
induction xs.
* split; intro; constructor.
* split; intro H; constructor; inversion H; intuition.
Qed.
Lemma StrongSubset_extendVarSetList :
forall l vs1 vs2,
StrongSubset vs1 vs2 ->
StrongSubset (extendVarSetList vs1 l) (extendVarSetList vs2 l).
Proof.
intros.
apply StrongSubset_extendVarSetList_ae; only 2: assumption.
apply Forall2_diag.
rewrite Forall_forall. intros. apply almostEqual_refl.
Qed.
Lemma lookupVarSet_delVarSet_None:
forall v vs, lookupVarSet (delVarSet vs v) v = None.
Proof.
intros.
unfold lookupVarSet,
UniqSet.lookupUniqSet,
UniqFM.lookupUFM.
unfold delVarSet,
UniqSet.delOneFromUniqSet,
UniqFM.delFromUFM.
destruct vs.
destruct getUniqSet'.
simpl.
apply delete_eq.
Qed.
Lemma StrongSubset_delVarSet :
forall vs1 vs2 v,
StrongSubset vs1 vs2 ->
StrongSubset (delVarSet vs1 v) (delVarSet vs2 v).
Proof.
intros.
unfold StrongSubset in *.
intro var.
specialize (H var).
destruct (v == var) eqn:EQv.
- rewrite Base.Eq_sym in EQv.
erewrite lookupVarSet_eq;
[|eassumption].
rewrite lookupVarSet_delVarSet_None.
trivial.
- rewrite lookupVarSet_delVarSet_neq;
[|rewrite EQv; auto].
destruct (lookupVarSet vs1 var) eqn:Hl; auto.
rewrite lookupVarSet_delVarSet_neq;
[|rewrite EQv; auto].
auto.
Qed.
Lemma StrongSubset_delete_fresh :
forall vs v,
lookupVarSet vs v = None ->
StrongSubset vs (delVarSet vs v).
Proof.
intros.
unfold StrongSubset in *.
intro var.
destruct (v == var) eqn:EQv.
- rewrite Base.Eq_sym in EQv.
erewrite lookupVarSet_eq;
[|eassumption].
rewrite H.
trivial.
- rewrite lookupVarSet_delVarSet_neq;
[|rewrite EQv; auto].
destruct (lookupVarSet vs var) eqn:Hl; auto.
apply almostEqual_refl.
Qed.
Lemma StrongSubset_delVarSetList:
forall vs1 vs2 vs,
StrongSubset vs1 vs2 ->
StrongSubset (delVarSetList vs1 vs) (delVarSetList vs2 vs).
Proof.
intros vs1 vs2 vs.
generalize dependent vs2.
generalize dependent vs1.
induction vs;
intros vs1 vs2 H; hs_simpl;
[assumption|].
eapply StrongSubset_delVarSet in H.
eauto.
Qed.
(* Respects_StrongSubset *)
Definition Respects_StrongSubset (P : VarSet -> Prop) : Prop :=
forall (vs1 vs2 : VarSet),
StrongSubset vs1 vs2 ->
P vs1 -> P vs2.
Existing Class Respects_StrongSubset.
Require Import Coq.Classes.Morphisms.
Global Instance Respects_StrongSubset_iff_morphism:
Proper (pointwise_relation VarSet iff ==> iff) Respects_StrongSubset.
Proof.
intros ???.
split; intros ?????;
unfold pointwise_relation in H;
firstorder.
Qed.
Lemma Respects_StrongSubset_const:
forall P, Respects_StrongSubset (fun _ => P).
Proof. intros ?????. assumption. Qed.
Lemma Respects_StrongSubset_and:
forall P Q,
Respects_StrongSubset P ->
Respects_StrongSubset Q ->
Respects_StrongSubset (fun x => P x /\ Q x).
Proof.
unfold Respects_StrongSubset in *.
intros ????????.
firstorder.
Qed.
Lemma Respects_StrongSubset_andb:
forall (P Q : VarSet -> bool),
Respects_StrongSubset (fun x => P x = true) ->
Respects_StrongSubset (fun x => Q x = true) ->
Respects_StrongSubset (fun x => P x && Q x = true).
Proof.
unfold Respects_StrongSubset in *.
intros ????????.
simpl_bool.
firstorder.
Qed.
Lemma Respects_StrongSubset_forall:
forall a (xs : list a) P,
Forall (fun x => Respects_StrongSubset (fun vs => P vs x)) xs ->
Respects_StrongSubset (fun vs => Forall (P vs) xs).
Proof.
unfold Respects_StrongSubset in *.
intros.
rewrite -> Forall_forall in *.
firstorder.
Qed.
Lemma Respects_StrongSubset_forallb:
forall a (xs : list a) P,
Forall (fun x => Respects_StrongSubset (fun vs => P vs x = true)) xs ->
Respects_StrongSubset (fun vs => forallb (P vs) xs = true).
Proof.
unfold Respects_StrongSubset in *.
intros.
rewrite -> forallb_forall in *.
rewrite -> Forall_forall in *.
firstorder.
Qed.
Lemma Respects_StrongSubset_elemVarSet:
forall v,
Respects_StrongSubset (fun vs => elemVarSet v vs = true).
Proof.
intros ????.
simpl_bool; intuition.
apply strongSubset_implies_subset in H.
set_b_iff; fsetdec.
Qed.
Lemma Respects_StrongSubset_delVarSet:
forall v P,
Respects_StrongSubset (fun vs : VarSet => P vs) ->
Respects_StrongSubset (fun vs : VarSet => P (delVarSet vs v)).
Proof.
intros v P H vs1 vs2 Hs Hvs1.
apply StrongSubset_delVarSet with (v:=v) in Hs.
unfold Respects_StrongSubset in H.
apply H in Hs; auto.
Qed.
Lemma Respects_StrongSubset_delVarSetList:
forall vs2 P,
Respects_StrongSubset (fun vs : VarSet => P vs) ->
Respects_StrongSubset (fun vs : VarSet => P (delVarSetList vs vs2)).
Proof.
intros vs2 P H vs vs' Hs Hvs2.
apply StrongSubset_delVarSetList with (vs:=vs2) in Hs.
unfold Respects_StrongSubset in H.
apply H in Hs; auto.
Qed.
Lemma Respects_StrongSubset_extendVarSet:
forall v P,
Respects_StrongSubset (fun vs : VarSet => P vs) ->
Respects_StrongSubset (fun vs : VarSet => P (extendVarSet vs v)).
Proof.
intros v P H vs vs' Hs Hvs.
apply StrongSubset_extend with (v:=v) in Hs.
unfold Respects_StrongSubset in H.
apply H in Hs; auto.
Qed.
Lemma Respects_StrongSubset_extendVarSetList:
forall vs' P,
Respects_StrongSubset (fun vs : VarSet => P vs) ->
Respects_StrongSubset (fun vs : VarSet => P (extendVarSetList vs vs')).
Proof.
intros vs P H vs1 vs2 Hs Hvs1.
eapply StrongSubset_extendVarSetList with (l:=vs) in Hs.
unfold Respects_StrongSubset in H.
apply H in Hs; auto.
Qed.
Lemma StrongSubset_filterVarSet:
forall f1 f2 vs,
RespectsVar f1 -> RespectsVar f2 ->
(forall v, f1 v = true -> f2 v = true) ->
filterVarSet f1 vs {<=} filterVarSet f2 vs.
Proof.
intros.
unfold StrongSubset.
intros var.
destruct (f1 var) eqn:Heq1.
- rewrite lookupVarSet_filterVarSet_true; auto.
destruct (lookupVarSet vs var) eqn:Hl; [|trivial].
rewrite lookupVarSet_filterVarSet_true; auto.
rewrite Hl.
apply almostEqual_refl.
- rewrite lookupVarSet_filterVarSet_false; auto.
Qed.
(* Is this weakening? *)
Lemma weaken:
forall {P : VarSet -> Prop} {R : Respects_StrongSubset P},
forall {vs1} {vs2},
StrongSubset vs1 vs2 ->
P vs1 -> P vs2.
Proof. intros. unfold Respects_StrongSubset in R. eapply R; eassumption. Qed.
Lemma weakenb:
forall {P : VarSet -> bool} {R : Respects_StrongSubset (fun x => P x )},
forall {vs1} {vs2},
StrongSubset vs1 vs2 ->
P vs1 -> P vs2 .
Proof. intros. unfold Respects_StrongSubset in R. eapply R; eassumption. Qed.
Lemma Respects_StrongSubset_extendVarSet_ae:
forall {P : VarSet -> Prop} {R : Respects_StrongSubset P},
forall vs v1 v2,
almostEqual v1 v2 ->
P (extendVarSet vs v1) <-> P (extendVarSet vs v2).
Proof.
intros.
split; apply R; (apply StrongSubset_extend_ae;
[ reflexivity | assumption + (apply almostEqual_sym; assumption) ]).
Qed.
Lemma Respects_StrongSubset_extendVarSetList_ae:
forall {P : VarSet -> Prop} {R : Respects_StrongSubset P},
forall vs vs1 vs2,
Forall2 almostEqual vs1 vs2 ->
P (extendVarSetList vs vs1) <-> P (extendVarSetList vs vs2).
Proof.
split; apply R; apply StrongSubset_extendVarSetList_ae.
* assumption.
* reflexivity.
* clear -H.
induction H; constructor.
+ apply almostEqual_sym; assumption.
+ assumption.
* reflexivity.
Qed.
(* A list of variables is fresh for a given varset when
any variable with a unique found in the list is not found
in the set. i.e. this is list membership using GHC.Base.==
for vars.
*)
Definition freshList (vars: list Var) (vs :VarSet) :=
(forall (v:Var), Foldable.elem v vars ->
lookupVarSet vs v = None).
Lemma freshList_nil : forall v, freshList nil v.
Proof.
unfold freshList. intros v v0 H. inversion H.
Qed.
Lemma freshList_cons : forall (x:Var) l (v:VarSet),
lookupVarSet v x = None /\ freshList l v <-> freshList (x :: l) v.
Proof.
unfold freshList. intros.
split.
+ intros [? ?] ? ?.
rewrite elem_cons in H1.
destruct (orb_prop _ _ H1) as [EQ|IN].
rewrite -> lookupVarSet_eq with (v2 := x); auto.
eauto.
+ intros. split.
eapply H.
rewrite elem_cons.
eapply orb_true_intro.
left. eapply Base.Eq_refl.
intros.
eapply H.
rewrite elem_cons.
eapply orb_true_intro.
right. auto.
Qed.
Lemma freshList_app :
forall v l1 l2, freshList (l1 ++ l2) v <-> freshList l1 v /\ freshList l2 v.
Proof.
intros.
induction l1; simpl.
split.
intros. split. apply freshList_nil. auto.
tauto.
split.
+ intros.
rewrite <- freshList_cons in *. tauto.
+ intros.
rewrite <- freshList_cons in *. tauto.
Qed.
Lemma StrongSubset_extendVarSet_fresh :
forall vs var, lookupVarSet vs var = None ->
StrongSubset vs (extendVarSet vs var).
Proof.
apply StrongSubset_extend_fresh.
Qed.
Lemma StrongSubset_extendVarSetList_fresh :
forall vs vars, freshList vars vs ->
StrongSubset vs (extendVarSetList vs vars).
Proof.
intros.
apply StrongSubset_extendList_fresh.
apply disjointVarSet_mkVarSet.
induction vars; auto.
apply freshList_cons in H as [H1 H2].
apply Forall_cons; auto.
apply lookupVarSet_None_elemVarSet.
assumption.
Qed.
|
/-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot
-/
import algebra.order.ring.defs
import algebra.ring.pi
import tactic.positivity
/-!
# Pi instances for ordered groups and monoids
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines instances for ordered group, monoid, and related structures on Pi types.
-/
universes u v w
variables {ι α β : Type*}
variable {I : Type u} -- The indexing type
variable {f : I → Type v} -- The family of types already equipped with instances
variables (x y : Π i, f i) (i : I)
namespace pi
/-- The product of a family of ordered commutative monoids is an ordered commutative monoid. -/
@[to_additive "The product of a family of ordered additive commutative monoids is
an ordered additive commutative monoid."]
instance ordered_comm_monoid {ι : Type*} {Z : ι → Type*} [∀ i, ordered_comm_monoid (Z i)] :
ordered_comm_monoid (Π i, Z i) :=
{ mul_le_mul_left := λ f g w h i, mul_le_mul_left' (w i) _,
..pi.partial_order,
..pi.comm_monoid, }
@[to_additive] instance {ι : Type*} {α : ι → Type*} [Π i, has_le (α i)] [Π i, has_mul (α i)]
[Π i, has_exists_mul_of_le (α i)] :
has_exists_mul_of_le (Π i, α i) :=
⟨λ a b h, ⟨λ i, (exists_mul_of_le $ h i).some, funext $ λ i, (exists_mul_of_le $ h i).some_spec⟩⟩
/-- The product of a family of canonically ordered monoids is a canonically ordered monoid. -/
@[to_additive "The product of a family of canonically ordered additive monoids is
a canonically ordered additive monoid."]
instance {ι : Type*} {Z : ι → Type*} [∀ i, canonically_ordered_monoid (Z i)] :
canonically_ordered_monoid (Π i, Z i) :=
{ le_self_mul := λ f g i, le_self_mul,
..pi.order_bot, ..pi.ordered_comm_monoid, ..pi.has_exists_mul_of_le }
@[to_additive]
instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_comm_monoid $ f i] :
ordered_cancel_comm_monoid (Π i : I, f i) :=
by refine_struct { mul := (*), one := (1 : Π i, f i), le := (≤), lt := (<),
npow := monoid.npow, .. pi.partial_order, .. pi.monoid };
tactic.pi_instance_derive_field
@[to_additive]
instance ordered_comm_group [∀ i, ordered_comm_group $ f i] :
ordered_comm_group (Π i : I, f i) :=
{ mul := (*), one := (1 : Π i, f i), le := (≤), lt := (<),
npow := monoid.npow,
..pi.comm_group,
..pi.ordered_comm_monoid, }
instance [Π i, ordered_semiring (f i)] : ordered_semiring (Π i, f i) :=
{ add_le_add_left := λ a b hab c i, add_le_add_left (hab _) _,
zero_le_one := λ _, zero_le_one,
mul_le_mul_of_nonneg_left := λ a b c hab hc i, mul_le_mul_of_nonneg_left (hab _) $ hc _,
mul_le_mul_of_nonneg_right := λ a b c hab hc i, mul_le_mul_of_nonneg_right (hab _) $ hc _,
..pi.semiring, ..pi.partial_order }
instance [Π i, ordered_comm_semiring (f i)] : ordered_comm_semiring (Π i, f i) :=
{ ..pi.comm_semiring, ..pi.ordered_semiring }
instance [Π i, ordered_ring (f i)] : ordered_ring (Π i, f i) :=
{ mul_nonneg := λ a b ha hb i, mul_nonneg (ha _) (hb _),
..pi.ring, ..pi.ordered_semiring }
instance [Π i, ordered_comm_ring (f i)] : ordered_comm_ring (Π i, f i) :=
{ ..pi.comm_ring, ..pi.ordered_ring }
end pi
namespace function
variables (β) [has_one α] [preorder α] {a : α}
@[to_additive const_nonneg_of_nonneg]
lemma one_le_const_of_one_le (ha : 1 ≤ a) : 1 ≤ const β a := λ _, ha
@[to_additive] lemma const_le_one_of_le_one (ha : a ≤ 1) : const β a ≤ 1 := λ _, ha
variables {β} [nonempty β]
@[simp, to_additive const_nonneg]
lemma one_le_const : 1 ≤ const β a ↔ 1 ≤ a := @const_le_const _ _ _ _ 1 _
@[simp, to_additive const_pos]
lemma one_lt_const : 1 < const β a ↔ 1 < a := @const_lt_const _ _ _ _ 1 a
@[simp, to_additive] lemma const_le_one : const β a ≤ 1 ↔ a ≤ 1 := @const_le_const _ _ _ _ _ 1
@[simp, to_additive] lemma const_lt_one : const β a < 1 ↔ a < 1 := @const_lt_const _ _ _ _ _ 1
end function
namespace tactic
open function positivity
variables (ι) [has_zero α] {a : α}
private lemma function_const_nonneg_of_pos [preorder α] (ha : 0 < a) : 0 ≤ const ι a :=
const_nonneg_of_nonneg _ ha.le
variables [nonempty ι]
private lemma function_const_ne_zero : a ≠ 0 → const ι a ≠ 0 := const_ne_zero.2
private
/-- Extension for the `positivity` tactic: `function.const` is positive/nonnegative/nonzero if its
input is. -/
@[positivity]
meta def positivity_const : expr → tactic strictness
| `(function.const %%ι %%a) := do
strict_a ← core a,
match strict_a with
| positive p := positive <$> to_expr ``(function_const_pos %%ι %%p)
<|> nonnegative <$> to_expr ``(function_const_nonneg_of_pos %%ι %%p)
| nonnegative p := nonnegative <$> to_expr ``(const_nonneg_of_nonneg %%ι %%p)
| nonzero p := nonzero <$> to_expr ``(function_const_ne_zero %%ι %%p)
end
| e := pp e >>= fail ∘ format.bracket "The expression `" "` is not of the form `function.const ι a`"
end tactic
|
#!/usr/bin/env python
import glob
import numpy as np
import os
import pandas as pd
import random
import tqdm
import termite as trmt
random.seed(42)
def delta(column):
return (column.shift(1) - column) ** 2
class Termite:
def __init__(self, caste, number):
self.caste = caste
self.number = number
self.color = (random.randint(1,256), random.randint(1,256),
random.randint(1,256))
self.trail = []
self.tracker = None
def __repr__(self):
return f'{self.label}'
@property
def label(self):
return f'{self.caste}{self.number}'
def to_dataframe(self):
self.trail = pd.DataFrame(self.trail)
self.trail = self.trail.set_index('frame')
def to_csv(self, output_path):
self.trail.to_csv(f'{output_path}/{self.label}-trail.csv',
float_format='%.1f', na_rep='NaN')
def from_csv(self, source_path):
self.trail = pd.read_csv(source_path, index_col=0)
def normalize(self):
self.trail['x'] = self.trail['x'] + self.trail['xoffset']//2
self.trail['y'] = self.trail['y'] + self.trail['yoffset']//2
class Experiment():
def __init__(self, source_folder):
self.termites = []
self.load_termites(source_folder)
def load_termites(self, source_folder):
data_files = glob.glob(f'{source_folder}*.csv')
for data_file in data_files:
label = os.path.basename(data_file).split('-')[0]
termite = trmt.Termite(caste=label[0], number=int(label[1:]))
termite.from_csv(data_file)
self.termites.append(termite)
def normalize(self):
for termite in self.termites:
termite.normalize()
termite.trail = termite.trail.drop(columns=['xoffset', 'yoffset'])
def compute_displacements(self):
for termite in self.termites:
deltas = termite.trail[['x', 'y']].apply(delta)
displacement = np.sqrt(deltas['x'] + deltas['y'])
termite.trail['displacement'] = displacement
def compute_mean_velocities(self, movie_fps):
for termite in self.termites:
termite.trail['mean_velocity'] = termite.trail.groupby('time')['displacement'].transform(sum)/movie_fps
def compute_nestmates_distances(self):
for termite in self.termites:
for other in self.termites:
if termite != other:
distance = np.sqrt((((termite.trail['x']-other.trail['x'])**2) +
((termite.trail['y']-other.trail['y'])**2)))
termite.trail[f'distance_to_{other.label}'] = distance
def compute_encounters(self, threshold):
for termite in self.termites:
for other in self.termites:
if termite != other:
encounters = termite.trail[f'distance_to_{other.label}'] < threshold
termite.trail[f'encountering_{other.label}'] = encounters
def save(self, output_path):
output_path = os.path.join(output_path, 'Expanded')
if not os.path.exists(output_path):
os.makedirs(output_path)
for termite in self.termites:
termite.to_csv(output_path)
if __name__ == '__main__':
base_folder = '/media/dmrib/dmrib-flash/Trails/sample-dataset/'
nest = Experiment(base_folder)
nest.normalize()
nest.compute_displacements()
nest.compute_mean_velocities(movie_fps=31.125)
nest.compute_nestmates_distances()
nest.compute_encounters(40)
nest.save('/media/dmrib/dmrib-flash/Trails/sample-dataset/')
|
module Data.Map
%default total
export
data Map : (key : Type) -> (VF : key -> Type) -> Type where
MNil : .{VF : key -> Type} -> Map key VF
MBranch : (DecEq key, Ord key) =>
.{VF : key -> Type}
-> (k : key)
-> (val : VF k )
-> (l : Map key VF)
-> (r : Map key VF)
-> Map key VF
%name Map map, map2, map3
empty : Map k p
empty = MNil
insert : (DecEq key, Ord key) => (k : key) -> p k -> Map key p -> Map key p
insert k x MNil = MBranch k x MNil MNil
insert k x (MBranch kr val l r) =
case compare k kr of
LT => MBranch kr val (insert k x l) r
EQ => MBranch k x l r
GT => MBranch kr val l (insert k x r)
lookup : (DecEq key, Ord key) => (k : key) -> Map key p -> Maybe (p k)
lookup _ MNil = Nothing
lookup k (MBranch kr val l r) =
case decEq k kr of
Yes prf => rewrite prf in Just val
No _ => case compare k kr of
LT => lookup k l
_ => lookup k r
insertWith : (DecEq key, Ord key) => (k : key) -> p k -> (p k -> p k -> p k) -> Map key p -> Map key p
insertWith k x f m =
case lookup k m of
Just v => insert k (f x v) m
Nothing => insert k x m
-- it would be nice to implement this with one traversal,
-- but having a hard time rewriting some types
-- insertWith k x f MNil = MBranch k x MNil MNil
-- insertWith {p} k x f (MBranch kr val l r) =
-- case decEq kr k of
-- Yes prf => MBranch k (f x val) l r
-- No _ => case compare k kr of
-- LT => insertWith k x f l
-- _ => insertWith k x f r
fromList : (DecEq key, Ord key) => List (k : key ** p k) -> Map key p
fromList [] = MNil
fromList ((k ** v) :: xs) = insert k v $ fromList xs
|
[STATEMENT]
lemma lQuot_diff[simp]: "lQuot c (A - B) = lQuot c A - lQuot c B"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. lQuot c (A - B) = lQuot c A - lQuot c B
[PROOF STEP]
by(auto simp add: lQuot_def)
|
= = Economy and infrastructure = =
|
module ProofColDivSeqPostulate
import ProofColDivSeqBase
%default total
-- %language ElabReflection
%access export
%hide Language.Reflection.P
-- from ProofColDivSeqBase
-- ########################################
-- 無限降下法(の変形) Isabelleで証明した
postulate infiniteDescent :
((n:Nat) -> P (S n) 2 -> (m ** (LTE (S m) (S n), P m 2)))
-> All Limited $ allDivSeq Z 2
-> All Limited $ allDivSeq (n+n+n) 2
-- BaseLog0.txtより、保証される
postulate base0 : All Limited $ allDivSeq Z 2
-- ########################################
-- from ProofColDivSeqLvDown
-- ########################################
any2Sub : {pp : a -> Type} -> (x : a) -> (xs, ys : List a)
-> Either (Any pp xs) (Any pp ys) -> Either (Any pp (x :: xs)) (Any pp ys)
any2Sub x [] ys (Left anL) = absurd anL
any2Sub x (x2::xs) ys (Left anL) = Left (There anL)
any2Sub x xs ys (Right anR) = Right anR
-- これが肝
any2 : {pp : a -> Type} -> (xs, ys : List a)
-> Any pp (xs ++ ys) -> Either (Any pp xs) (Any pp ys)
any2 [] ys an = Right an
any2 (x::xs) ys (Here he) = Left (Here he)
any2 (x::xs) ys (There th) =
let foo = any2 xs ys th in any2Sub x xs ys foo
any3 : {pp : a -> Type} -> (xs1, xs2, xs3 : List a)
-> Either (Any pp xs1) (Any pp (xs2++xs3))
-> Either (Any pp xs1) (Either (Any pp xs2) (Any pp xs3))
any3 xs1 xs2 xs3 (Left prfL) = Left prfL
any3 xs1 xs2 xs3 (Right prfR) = Right (any2 xs2 xs3 prfR)
any4 : {pp : a -> Type} -> (xs1, xs2, xs3, xs4 : List a)
-> Either (Any pp xs1) (Either (Any pp xs2) (Any pp (xs3++xs4)))
-> Either (Any pp xs1) (Either (Any pp xs2) (Either (Any pp xs3) (Any pp xs4)))
any4 xs1 xs2 xs3 xs4 (Left prfL) = Left prfL
any4 xs1 xs2 xs3 xs4 (Right (Left prfRL)) = Right (Left prfRL)
any4 xs1 xs2 xs3 xs4 (Right (Right prfRR)) = Right (Right (any2 xs3 xs4 prfRR))
any5 : {pp : a -> Type} -> (xs1, xs2, xs3, xs4, xs5 : List a)
-> Either (Any pp xs1) (Either (Any pp xs2) (Either (Any pp xs3) (Any pp (xs4++xs5))))
-> Either (Any pp xs1) (Either (Any pp xs2) (Either (Any pp xs3) (Either (Any pp xs4) (Any pp xs5))))
any5 xs1 xs2 xs3 xs4 xs5 (Left prfL) = Left prfL
any5 xs1 xs2 xs3 xs4 xs5 (Right (Left prfRL)) = Right (Left prfRL)
any5 xs1 xs2 xs3 xs4 xs5 (Right (Right (Left prfRRL))) = Right (Right (Left prfRRL))
any5 xs1 xs2 xs3 xs4 xs5 (Right (Right (Right prfRRR))) = Right (Right (Right (any2 xs4 xs5 prfRRR)))
any6 : {pp : a -> Type} -> (xs1, xs2, xs3, xs4, xs5, xs6 : List a)
-> Either (Any pp xs1) (Either (Any pp xs2) (Either (Any pp xs3) (Either (Any pp xs4) (Any pp (xs5++xs6)))))
-> Either (Any pp xs1) (Either (Any pp xs2) (Either (Any pp xs3) (Either (Any pp xs4) (Either (Any pp xs5) (Any pp xs6)))))
any6 xs1 xs2 xs3 xs4 xs5 xs6 (Left prfL) = Left prfL
any6 xs1 xs2 xs3 xs4 xs5 xs6 (Right (Left prfRL)) = Right (Left prfRL)
any6 xs1 xs2 xs3 xs4 xs5 xs6 (Right (Right (Left prfRRL))) = Right (Right (Left prfRRL))
any6 xs1 xs2 xs3 xs4 xs5 xs6 (Right (Right (Right (Left prfRRRL)))) = Right (Right (Right (Left prfRRRL)))
any6 xs1 xs2 xs3 xs4 xs5 xs6 (Right (Right (Right (Right prfRRRR)))) = Right (Right (Right (Right (any2 xs5 xs6 prfRRRR))))
any7 : {pp : a -> Type} -> (xs1, xs2, xs3, xs4, xs5, xs6, xs7 : List a)
-> Either (Any pp xs1) (Either (Any pp xs2) (Either (Any pp xs3) (Either (Any pp xs4) (Either (Any pp xs5) (Any pp (xs6++xs7))))))
-> Either (Any pp xs1) (Either (Any pp xs2) (Either (Any pp xs3) (Either (Any pp xs4) (Either (Any pp xs5) (Either (Any pp xs6) (Any pp xs7))))))
any7 xs1 xs2 xs3 xs4 xs5 xs6 xs7 (Left prfL) = Left prfL
any7 xs1 xs2 xs3 xs4 xs5 xs6 xs7 (Right (Left prfRL)) = Right (Left prfRL)
any7 xs1 xs2 xs3 xs4 xs5 xs6 xs7 (Right (Right (Left prfRRL))) = Right (Right (Left prfRRL))
any7 xs1 xs2 xs3 xs4 xs5 xs6 xs7 (Right (Right (Right (Left prfRRRL)))) = Right (Right (Right (Left prfRRRL)))
any7 xs1 xs2 xs3 xs4 xs5 xs6 xs7 (Right (Right (Right (Right (Left prfRRRRL))))) = Right (Right (Right (Right (Left prfRRRRL))))
any7 xs1 xs2 xs3 xs4 xs5 xs6 xs7 (Right (Right (Right (Right (Right prfRRRRR))))) = Right (Right (Right (Right (Right (any2 xs6 xs7 prfRRRRR)))))
any8 : {pp : a -> Type} -> (xs1, xs2, xs3, xs4, xs5, xs6, xs7, xs8 : List a)
-> Either (Any pp xs1) (Either (Any pp xs2) (Either (Any pp xs3) (Either (Any pp xs4) (Either (Any pp xs5) (Either (Any pp xs6) (Any pp (xs7++xs8)))))))
-> Either (Any pp xs1) (Either (Any pp xs2) (Either (Any pp xs3) (Either (Any pp xs4) (Either (Any pp xs5) (Either (Any pp xs6) (Either (Any pp xs7) (Any pp xs8)))))))
any8 xs1 xs2 xs3 xs4 xs5 xs6 xs7 xs8 (Left prfL) = Left prfL
any8 xs1 xs2 xs3 xs4 xs5 xs6 xs7 xs8 (Right (Left prfRL)) = Right (Left prfRL)
any8 xs1 xs2 xs3 xs4 xs5 xs6 xs7 xs8 (Right (Right (Left prfRRL))) = Right (Right (Left prfRRL))
any8 xs1 xs2 xs3 xs4 xs5 xs6 xs7 xs8 (Right (Right (Right (Left prfRRRL)))) = Right (Right (Right (Left prfRRRL)))
any8 xs1 xs2 xs3 xs4 xs5 xs6 xs7 xs8 (Right (Right (Right (Right (Left prfRRRRL))))) = Right (Right (Right (Right (Left prfRRRRL))))
any8 xs1 xs2 xs3 xs4 xs5 xs6 xs7 xs8 (Right (Right (Right (Right (Right (Left prfRRRRRL)))))) = Right (Right (Right (Right (Right (Left prfRRRRRL)))))
any8 xs1 xs2 xs3 xs4 xs5 xs6 xs7 xs8 (Right (Right (Right (Right (Right (Right prfRRRRRR)))))) = Right (Right (Right (Right (Right (Right (any2 xs7 xs8 prfRRRRRR))))))
anyFinal : {pp : a -> Type} -> (xs1, xs2, xs3, xs4, xs5, xs6, xs7, xs8 : List a)
-> Any pp (xs1 ++ xs2 ++ xs3 ++ xs4 ++ xs5 ++ xs6 ++ xs7 ++ xs8)
-> Either (Any pp xs1) (Either (Any pp xs2) (Either (Any pp xs3) (Either (Any pp xs4) (Either (Any pp xs5) (Either (Any pp xs6) (Either (Any pp xs7) (Any pp xs8)))))))
anyFinal xs1 xs2 xs3 xs4 xs5 xs6 xs7 xs8 prf =
let prf2 = any2 xs1 (xs2 ++ xs3 ++ xs4 ++ xs5 ++ xs6 ++ xs7 ++ xs8) prf in
let prf3 = any3 xs1 xs2 (xs3 ++ xs4 ++ xs5 ++ xs6 ++ xs7 ++ xs8) prf2 in
let prf4 = any4 xs1 xs2 xs3 (xs4 ++ xs5 ++ xs6 ++ xs7 ++ xs8) prf3 in
let prf5 = any5 xs1 xs2 xs3 xs4 (xs5 ++ xs6 ++ xs7 ++ xs8) prf4 in
let prf6 = any6 xs1 xs2 xs3 xs4 xs5 (xs6 ++ xs7 ++ xs8) prf5 in
let prf7 = any7 xs1 xs2 xs3 xs4 xs5 xs6 (xs7 ++ xs8) prf6 in
let prf8 = any8 xs1 xs2 xs3 xs4 xs5 xs6 xs7 xs8 prf7 in prf8
-- 前方を削っているのは、(有限or無限を判定する)末尾に影響を与えないから
postulate dspCut : Any (Not . Limited) (map ([a,b] `dsp`) xs)
-> Any (Not . Limited) xs
postulate dsp2Cut : Any (Not . Limited) (map ([a] `dsp2`) xs)
-> Any (Not . Limited) xs
changeA' : (x, lv:Nat)
-> Any (Not . Limited)
(if (modNatNZ (x+7) 4 SIsNotZ) == 0
then map ([6,-4] `dsp`) $ allDivSeq (divNatNZ ((x+7)*3) 4 SIsNotZ) (S lv)
else [])
-> Any (Not . Limited) (allDivSeq (divNatNZ ((x+7)*3) 4 SIsNotZ) (S lv))
changeA' x lv prf with ((modNatNZ (x+7) 4 SIsNotZ) == 0) proof p
changeA' x lv prf | False = absurd prf
changeA' x lv prf | True = dspCut prf
changeA : (x, lv:Nat) -> Any (Not . Limited) (allDivSeqA x (S lv))
-> Any (Not . Limited) (allDivSeq (divNatNZ ((x+7)*3) 4 SIsNotZ) (S lv))
changeA x lv prf = changeA' x lv $ replace (definiA x lv) prf
changeA0' : (x : Nat)
-> Any (Not . Limited)
(if (modNatNZ (x+7) 4 SIsNotZ) == 0 && (modNatNZ (modNatNZ (x+7) 4 SIsNotZ) 2 SIsNotZ) == 1
then [[6,-4] `dsp` (Just (divSeq (divNatNZ ((x+7)*3) 4 SIsNotZ)))]
else [])
-> Any (Not . Limited) [Just (divSeq (divNatNZ ((x+7)*3) 4 SIsNotZ))]
changeA0' x prf with ((modNatNZ (x+7) 4 SIsNotZ) == 0 && (modNatNZ (modNatNZ (x+7) 4 SIsNotZ) 2 SIsNotZ) == 1) proof p
changeA0' x prf | False = absurd prf
changeA0' x prf | True = dspCut prf
changeA0 : (x:Nat) -> Any (Not . Limited) (allDivSeqA x 0)
-> Any (Not . Limited) [Just (divSeq (divNatNZ ((x+7)*3) 4 SIsNotZ))]
changeA0 x prf = changeA0' x $ replace (definiA0 x) prf
changeB : (x, lv:Nat) -> Any (Not . Limited) (allDivSeqB x (S lv))
-> Any (Not . Limited) (allDivSeq (x*6+3) (S lv))
changeB x lv prf = dspCut $ replace (definiB x lv) prf
changeB0' : (x : Nat)
-> Any (Not . Limited)
(if (modNatNZ (x*6+3) 2 SIsNotZ) == 1
then [[1,-2] `dsp` (Just (divSeq (x*6+3)))]
else [])
-> Any (Not . Limited) [Just (divSeq (x*6+3))]
changeB0' x prf with ((modNatNZ (x*6+3) 2 SIsNotZ) == 1) proof p
changeB0' x prf | False = absurd prf
changeB0' x prf | True = dspCut prf
changeB0 : (x:Nat) -> Any (Not . Limited) (allDivSeqB x 0)
-> Any (Not . Limited) [Just (divSeq (x*6+3))]
changeB0 x prf = changeB0' x $ replace (definiB0 x) prf
changeC : (x, lv:Nat) -> Any (Not . Limited) (allDivSeqC x (S lv))
-> Any (Not . Limited) (allDivSeq (x*3+6) (S lv))
changeC x lv prf = dspCut $ replace (definiC x lv) prf
changeC0' : (x : Nat)
-> Any (Not . Limited)
(if (modNatNZ (x*3+6) 2 SIsNotZ) == 1
then [[4,-4] `dsp` (Just (divSeq (x*3+6)))]
else [])
-> Any (Not . Limited) [Just (divSeq (x*3+6))]
changeC0' x prf with ((modNatNZ (x*3+6) 2 SIsNotZ) == 1) proof p
changeC0' x prf | False = absurd prf
changeC0' x prf | True = dspCut prf
changeC0 : (x:Nat) -> Any (Not . Limited) (allDivSeqC x 0)
-> Any (Not . Limited) [Just (divSeq (x*3+6))]
changeC0 x prf = changeC0' x $ replace (definiC0 x) prf
changeD' : (x, lv:Nat)
-> Any (Not . Limited)
(if (modNatNZ (x+1) 2 SIsNotZ) == 0
then map ([3,-2] `dsp`) $ allDivSeq (divNatNZ ((x+1)*3) 2 SIsNotZ) (S lv)
else [])
-> Any (Not . Limited) (allDivSeq (divNatNZ ((x+1)*3) 2 SIsNotZ) (S lv))
changeD' x lv prf with ((modNatNZ (x+1) 2 SIsNotZ) == 0) proof p
changeD' x lv prf | False = absurd prf
changeD' x lv prf | True = dspCut prf
changeD : (x, lv:Nat) -> Any (Not . Limited) (allDivSeqD x (S lv))
-> Any (Not . Limited) (allDivSeq (divNatNZ ((x+1)*3) 2 SIsNotZ) (S lv))
changeD x lv prf = changeD' x lv $ replace (definiD x lv) prf
changeD0' : (x : Nat)
-> Any (Not . Limited)
(if (modNatNZ (x+1) 2 SIsNotZ) == 0 && (modNatNZ (modNatNZ (x+1) 2 SIsNotZ) 2 SIsNotZ) == 1
then [[3,-2] `dsp` (Just (divSeq (divNatNZ ((x+1)*3) 2 SIsNotZ)))]
else [])
-> Any (Not . Limited) [Just (divSeq (divNatNZ ((x+1)*3) 2 SIsNotZ))]
changeD0' x prf with ((modNatNZ (x+1) 2 SIsNotZ) == 0 && (modNatNZ (modNatNZ (x+1) 2 SIsNotZ) 2 SIsNotZ) == 1) proof p
changeD0' x prf | False = absurd prf
changeD0' x prf | True = dspCut prf
changeD0 : (x:Nat) -> Any (Not . Limited) (allDivSeqD x 0)
-> Any (Not . Limited) [Just (divSeq (divNatNZ ((x+1)*3) 2 SIsNotZ))]
changeD0 x prf = changeD0' x $ replace (definiD0 x) prf
changeE : (x, lv:Nat) -> Any (Not . Limited) (allDivSeqE x (S lv))
-> Any (Not . Limited) (allDivSeq (x*12+9) (S lv))
changeE x lv prf = dspCut $ replace (definiE x lv) prf
changeE0' : (x : Nat)
-> Any (Not . Limited)
(if (modNatNZ (x*12+9) 2 SIsNotZ) == 1
then [[2,-4] `dsp` (Just (divSeq (x*12+9)))]
else [])
-> Any (Not . Limited) [Just (divSeq (x*12+9))]
changeE0' x prf with ((modNatNZ (x*12+9) 2 SIsNotZ) == 1) proof p
changeE0' x prf | False = absurd prf
changeE0' x prf | True = dspCut prf
changeE0 : (x:Nat) -> Any (Not . Limited) (allDivSeqE x 0)
-> Any (Not . Limited) [Just (divSeq (x*12+9))]
changeE0 x prf = changeE0' x $ replace (definiE0 x) prf
changeF' : (x, lv:Nat)
-> Any (Not . Limited)
(if (modNatNZ (x+3) 8 SIsNotZ) == 0
then map ([5,-2] `dsp`) $ allDivSeq (divNatNZ ((x+3)*3) 8 SIsNotZ) (S lv)
else [])
-> Any (Not . Limited) (allDivSeq (divNatNZ ((x+3)*3) 8 SIsNotZ) (S lv))
changeF' x lv prf with ((modNatNZ (x+3) 8 SIsNotZ) == 0) proof p
changeF' x lv prf | False = absurd prf
changeF' x lv prf | True = dspCut prf
changeF : (x, lv:Nat) -> Any (Not . Limited) (allDivSeqF x (S lv))
-> Any (Not . Limited) (allDivSeq (divNatNZ ((x+3)*3) 8 SIsNotZ) (S lv))
changeF x lv prf = changeF' x lv $ replace (definiF x lv) prf
changeF0' : (x : Nat)
-> Any (Not . Limited)
(if (modNatNZ (x+3) 8 SIsNotZ) == 0 && (modNatNZ (modNatNZ (x+3) 8 SIsNotZ) 2 SIsNotZ) == 1
then [[5,-2] `dsp` (Just (divSeq (divNatNZ ((x+3)*3) 8 SIsNotZ)))]
else [])
-> Any (Not . Limited) [Just (divSeq (divNatNZ ((x+3)*3) 8 SIsNotZ))]
changeF0' x prf with ((modNatNZ (x+3) 8 SIsNotZ) == 0 && (modNatNZ (modNatNZ (x+3) 8 SIsNotZ) 2 SIsNotZ) == 1) proof p
changeF0' x prf | False = absurd prf
changeF0' x prf | True = dspCut prf
changeF0 : (x:Nat) -> Any (Not . Limited) (allDivSeqF x 0)
-> Any (Not . Limited) [Just (divSeq (divNatNZ ((x+3)*3) 8 SIsNotZ))]
changeF0 x prf = changeF0' x $ replace (definiF0 x) prf
changeG' : (x, lv:Nat)
-> Any (Not . Limited)
(if (modNatNZ (x `minus` 21) 64 SIsNotZ) == 0 && x > 21
then map ([6] `dsp2`) $ allDivSeq (divNatNZ (x `minus` 21) 64 SIsNotZ) (S lv)
else [])
-> Any (Not . Limited) (allDivSeq (divNatNZ (x `minus` 21) 64 SIsNotZ) (S lv))
changeG' x lv prf with ((modNatNZ (x `minus` 21) 64 SIsNotZ) == 0 && x > 21) proof p
changeG' x lv prf | False = absurd prf
changeG' x lv prf | True = dsp2Cut prf
changeG : (x, lv:Nat) -> Any (Not . Limited) (allDivSeqG x (S lv))
-> Any (Not . Limited) (allDivSeq (divNatNZ (x `minus` 21) 64 SIsNotZ) (S lv))
changeG x lv prf = changeG' x lv $ replace (definiG x lv) prf
changeG0' : (x : Nat)
-> Any (Not . Limited)
(if (modNatNZ (x `minus` 21) 64 SIsNotZ) == 0 && x > 21 && (modNatNZ (modNatNZ (x `minus` 21) 64 SIsNotZ) 2 SIsNotZ) == 1
then [[6] `dsp2` (Just (divSeq (divNatNZ (x `minus` 21) 64 SIsNotZ)))]
else [])
-> Any (Not . Limited) [Just (divSeq (divNatNZ (x `minus` 21) 64 SIsNotZ))]
changeG0' x prf with ((modNatNZ (x `minus` 21) 64 SIsNotZ) == 0 && x > 21 && (modNatNZ (modNatNZ (x `minus` 21) 64 SIsNotZ) 2 SIsNotZ) == 1) proof p
changeG0' x prf | False = absurd prf
changeG0' x prf | True = dsp2Cut prf
changeG0 : (x:Nat) -> Any (Not . Limited) (allDivSeqG x 0)
-> Any (Not . Limited) [Just (divSeq (divNatNZ (x `minus` 21) 64 SIsNotZ))]
changeG0 x prf = changeG0' x $ replace (definiG0 x) prf
postulate defini3 : (x, lv:Nat)
-> Either (Any (Not . Limited) $ allDivSeq x lv)
(Either (Any (Not . Limited) $ allDivSeq (divNatNZ ((x+7)*3) 4 SIsNotZ) lv)
(Either (Any (Not . Limited) $ allDivSeq (x*6+3) lv)
(Either (Any (Not . Limited) $ allDivSeq (x*3+6) lv)
(Either (Any (Not . Limited) $ allDivSeq (divNatNZ ((x+1)*3) 2 SIsNotZ) lv)
(Either (Any (Not . Limited) $ allDivSeq (x*12+9) lv)
(Either (Any (Not . Limited) $ allDivSeq (divNatNZ ((x+3)*3) 8 SIsNotZ) lv)
(Any (Not . Limited) $ allDivSeq (divNatNZ (x `minus` 21) 64 SIsNotZ) lv)))))))
-> (Any (Not . Limited) $ allDivSeq x (S lv))
postulate defini0 : (x:Nat)
-> Either (Any (Not . Limited) $ [Just (divSeq x)])
(Either (Any (Not . Limited) $ [Just (divSeq (divNatNZ ((x+7)*3) 4 SIsNotZ))])
(Either (Any (Not . Limited) $ [Just (divSeq (x*6+3))])
(Either (Any (Not . Limited) $ [Just (divSeq (x*3+6))])
(Either (Any (Not . Limited) $ [Just (divSeq (divNatNZ ((x+1)*3) 2 SIsNotZ))])
(Either (Any (Not . Limited) $ [Just (divSeq (x*12+9))])
(Either (Any (Not . Limited) $ [Just (divSeq (divNatNZ ((x+3)*3) 8 SIsNotZ))])
(Any (Not . Limited) $ [Just (divSeq (divNatNZ (x `minus` 21) 64 SIsNotZ))])))))))
-> (Any (Not . Limited) $ allDivSeq x 0)
-- ProofColDivSeqLvDown.idrでlvDown'を証明したからOK
postulate lvDown : (n, lv:Nat) -> P n lv -> P n (pred lv)
-- ########################################
-- from sub0xxxxx
-- ########################################
-- 01 3(6x+1) --B[1,-2]--> 3x
postulate b18x3To3x' :
(k:Nat) -> P (S (plus (plus (plus k k) (plus k k)) (plus k k))) 1 -> P k 2
-- 02 3(18x+4) --A[6,-4]->E[2,-4]--> 3(2x)
postulate ae54x12To6x' :
(l:Nat) -> P (S (S (plus (plus (plus (plus (plus l l) l) (plus (plus l l) l))
(S (plus (plus (plus l l) l) (plus (plus l l) l))))
(S (plus (plus (plus l l) l) (plus (plus l l) l)))))) 1
-> P (plus l l) 3
-- 03 3(18x+10) --A[6,-4]->C[4,-4]--> 3(8x+3)
postulate ac54x30To24x9' :
(l:Nat) -> P (S (S (S (plus (plus (plus (plus (plus l l) l) (S (plus (plus l l) l))) (S (S (plus (plus (plus l l) l) (S (plus (plus l l) l))))))
(S (S (plus (plus (plus l l) l) (S (plus (plus l l) l))))))))) 1
-> P (S (S (S (plus (plus (plus l l) (plus l l)) (plus (plus l l) (plus l l)))))) 3
-- 04 3(18x+16) --A[6,-4]->B[1,-2]--> 3(4x+3)
postulate ab54x30To12x9' :
(l:Nat) -> P (S (S (S (S (plus (plus (plus (plus (plus l l) l) (S (S (plus (plus l l) l))))
(S (S (S (plus (plus (plus l l) l) (S (S (plus (plus l l) l))))))))
(S (S (S (plus (plus (plus l l) l) (S (S (plus (plus l l) l)))))))))))) 1
-> P (S (S (S (plus (plus l l) (plus l l))))) 3
-- 二重否定除去
postulate dne : ((a -> Void) -> Void) = a
-- 対偶
postulate contraposition2 :
{A, B : Nat -> Type} -> (x : Nat) -> (Not $ B x -> Not $ A x) -> (A x -> B x)
-- 05 3(3x+2) --C[4,-4]--> 3x
postulate contraC9x6To3x' :
(j:Nat) -> Not $ P j 2 -> Not $ P (S (S (plus (plus j j) j))) 1
{-
contraC9x6To3x' j =
rewrite definiP j 2 in
rewrite definiP (S (S (plus (plus j j) j))) 1 in
rewrite dne {a = All Limited (allDivSeq (plus (plus j j) j) 2)} in
rewrite dne {a = All Limited (allDivSeq (S (S (plus (plus (plus (plus j j) j) (S (S (plus (plus j j) j)))) (S (S (plus (plus j j) j)))))) 1)} in ?rhs
-}
c9x6To3x' :
(j:Nat) -> P (S (S (plus (plus j j) j))) 1 -> P j 2
c9x6To3x' j = contraposition2 j $ contraC9x6To3x' j
-- 06 3(12x+3) --E[2,-4]--> 3x
postulate e36x9To3x' :
(l:Nat) -> P (S (S (S (plus (plus (plus (plus l l) (plus l l)) (plus (plus l l) (plus l l))) (plus (plus l l) (plus l l)))))) 1 -> P l 2
-- 07 3(36x+9) --F[5,-2]->C[4,-4]--> 3(32x+7)
postulate fc108x27To96x21' :
(o:Nat) -> P (S (S (S (S (plus (plus (plus (plus (plus (plus o o) o) (plus (plus o o) o)) (S (plus (plus (plus o o) o) (plus (plus o o) o))))
(S (plus (plus (plus (plus o o) o) (plus (plus o o) o)) (S (plus (plus (plus o o) o) (plus (plus o o) o))))))
(S (plus (plus (plus (plus o o) o) (plus (plus o o) o)) (S (plus (plus (plus o o) o) (plus (plus o o) o)))))))))) 1
-> P (S (S (S (S (S (S (S (plus (plus (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o))) (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o))))
(plus (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o))) (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o)))))))))))) 3
-- 08 3(36x+21) --F[5,-2]->B[1,-2]--> 3(16x+9)
postulate fb108x63To48x27' :
(o:Nat) -> P (S (S (S (S (S (plus (plus (plus (plus (plus (plus o o) o) (S (plus (plus o o) o)))
(S (S (plus (plus (plus o o) o) (S (plus (plus o o) o))))))
(S (S (plus (plus (plus (plus o o) o) (S (plus (plus o o) o))) (S (S (plus (plus (plus o o) o) (S (plus (plus o o) o)))))))))
(S (S (plus (plus (plus (plus o o) o) (S (plus (plus o o) o))) (S (S (plus (plus (plus o o) o) (S (plus (plus o o) o)))))))))))))) 1
-> P (S (S (S (S (S (S (S (S (S (plus (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o))) (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o))))))))))))) 3
-- 09 3(36x+33) --F[5,-2]->E[2,-4]--> 3(8x+7)
postulate fe108x99To24x21' :
(o:Nat) -> P (S (S (S (S (S (S (plus (plus (plus (plus (plus (plus o o) o) (S (S (plus (plus o o) o))))
(S (S (S (plus (plus (plus o o) o) (S (S (plus (plus o o) o))))))))
(S (S (S (plus (plus (plus (plus o o) o) (S (S (plus (plus o o) o))))
(S (S (S (plus (plus (plus o o) o) (S (S (plus (plus o o) o))))))))))))
(S (S (S (plus (plus (plus (plus o o) o) (S (S (plus (plus o o) o))))
(S (S (S (plus (plus (plus o o) o) (S (S (plus (plus o o) o)))))))))))))))))) 1
-> P (S (S (S (S (S (S (S (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o)))))))))) 3
-- 10 3(36x+6) --F[5,-2]->E[2,-4]--> 3(8x+1)
postulate fe108x18To24x3' :
(o:Nat) -> P (S (S (S (S (plus (plus (plus (plus (plus (plus o o) o) (plus (plus o o) o)) (plus (plus (plus o o) o) (plus (plus o o) o)))
(S (plus (plus (plus (plus o o) o) (plus (plus o o) o)) (plus (plus (plus o o) o) (plus (plus o o) o)))))
(S (plus (plus (plus (plus o o) o) (plus (plus o o) o)) (plus (plus (plus o o) o) (plus (plus o o) o))))))))) 1
-> P (S (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o)))) 3
-- 11 3(36x+18) --F[5,-2]->C[4,-4]--> 3(32x+15)
postulate fc108x54To96x45' :
(o:Nat) -> P (S (S (S (S (S (plus (plus (plus (plus (plus (plus o o) o) (S (plus (plus o o) o)))
(S (plus (plus (plus o o) o) (S (plus (plus o o) o)))))
(S (S (plus (plus (plus (plus o o) o) (S (plus (plus o o) o))) (S (plus (plus (plus o o) o) (S (plus (plus o o) o))))))))
(S (S (plus (plus (plus (plus o o) o) (S (plus (plus o o) o))) (S (plus (plus (plus o o) o) (S (plus (plus o o) o))))))))))))) 1
-> P (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (plus (plus (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o))) (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o))))
(plus (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o))) (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o)))))))))))))))))))) 3
-- 12 3(36x+30) --F[5,-2]->B[1,-2]--> 3(16x+13)
postulate fb108x90To48x39' :
(o:Nat) -> P (S (S (S (S (S (S (plus (plus (plus (plus (plus (plus o o) o) (S (S (plus (plus o o) o))))
(S (S (plus (plus (plus o o) o) (S (S (plus (plus o o) o)))))))
(S (S (S (plus (plus (plus (plus o o) o) (S (S (plus (plus o o) o)))) (S (S (plus (plus (plus o o) o) (S (S (plus (plus o o) o))))))))))) (S (S (S (plus (plus (plus (plus o o) o) (S (S (plus (plus o o) o))))
(S (S (plus (plus (plus o o) o) (S (S (plus (plus o o) o))))))))))))))))) 1
-> P (S (S (S (S (S (S (S (S (S (S (S (S (S (plus (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o))) (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o))))))))))))))))) 3
-- 13 3(36x+12) --F[5,-2]->B[1,-2]--> 3(16x+5)
postulate fb108x36To48x15' :
(o:Nat) -> P (S (S (S (S (S (plus (plus (plus (plus (plus (plus o o) o) (plus (plus o o) o)) (S (plus (plus (plus o o) o) (plus (plus o o) o))))
(S (S (plus (plus (plus (plus o o) o) (plus (plus o o) o)) (S (plus (plus (plus o o) o) (plus (plus o o) o)))))))
(S (S (plus (plus (plus (plus o o) o) (plus (plus o o) o)) (S (plus (plus (plus o o) o) (plus (plus o o) o)))))))))))) 1
-> P (S (S (S (S (S (plus (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o))) (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o))))))))) 3
-- 14 3(36x+24) --F[5,-2]->E[2,-4]--> 3(8x+5)
postulate fe108x72To24x15' :
(o:Nat) -> P (S (S (S (S (S (S (plus (plus (plus (plus (plus (plus o o) o) (S (plus (plus o o) o)))
(S (S (plus (plus (plus o o) o) (S (plus (plus o o) o))))))
(S (S (S (plus (plus (plus (plus o o) o) (S (plus (plus o o) o))) (S (S (plus (plus (plus o o) o) (S (plus (plus o o) o))))))))))
(S (S (S (plus (plus (plus (plus o o) o) (S (plus (plus o o) o))) (S (S (plus (plus (plus o o) o) (S (plus (plus o o) o)))))))))))))))) 1
-> P (S (S (S (S (S (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o)))))))) 3
-- 15 3(36x+36) --F[5,-2]->C[4,-4]--> 3(32x+31)
postulate fc108x108To96x93' :
(o:Nat) -> P (S (S (S (S (S (S (S (plus (plus (plus (plus (plus (plus o o) o) (S (S (plus (plus o o) o))))
(S (S (S (plus (plus (plus o o) o) (S (S (plus (plus o o) o))))))))
(S (S (S (S (plus (plus (plus (plus o o) o) (S (S (plus (plus o o) o))))
(S (S (S (plus (plus (plus o o) o) (S (S (plus (plus o o) o)))))))))))))
(S (S (S (S (plus (plus (plus (plus o o) o) (S (S (plus (plus o o) o))))
(S (S (S (plus (plus (plus o o) o) (S (S (plus (plus o o) o)))))))))))))))))))) 1
-> P (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (plus (plus (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o))) (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o))))
(plus (plus (plus (plus o o) (plus o o)) (plus (plus o o) (plus o o))) (plus (plus (plus o o) (plus o o)) (plus (plus o o)
(plus o o)))))))))))))))))))))))))))))))))))) 3
-- ########################################
-- from ProofColDivSeqMain
-- ########################################
all2Sub : {pp : a -> Type} -> (xs, ys : List a)
-> All pp ((x::xs) ++ ys) -> (pp x, All pp (xs ++ ys))
all2Sub xs ys (Cons p ps) = (p, ps)
-- これが肝
all2 : {pp : a -> Type} -> (xs, ys : List a)
-> All pp (xs ++ ys) -> All pp xs
all2 [] ys _ = NilA
all2 (x::xs) ys prf =
let (prf2, prf3) = all2Sub xs ys prf
in Cons prf2 (all2 xs ys prf3)
-- ########################################
|
(* Title: Fast_Dice_Roll.thy
Author: Andreas Lochbihler, ETH Zurich *)
subsection \<open>Arbitrary uniform distributions\<close>
theory Fast_Dice_Roll imports
Bernoulli
While_SPMF
begin
text \<open>This formalisation follows the ideas by J\'er\'emie Lumbroso \cite{Lumbroso2013arxiv}.\<close>
lemma sample_bits_fusion:
fixes v :: nat
assumes "0 < v"
shows
"bind_pmf (pmf_of_set {..<v}) (\<lambda>c. bind_pmf (pmf_of_set UNIV) (\<lambda>b. f (2 * c + (if b then 1 else 0)))) =
bind_pmf (pmf_of_set {..<2 * v}) f"
(is "?lhs = ?rhs")
proof -
have "?lhs = bind_pmf (map_pmf (\<lambda>(c, b). (2 * c + (if b then 1 else 0))) (pair_pmf (pmf_of_set {..<v}) (pmf_of_set UNIV))) f"
(is "_ = bind_pmf (map_pmf ?f _) _")
by(simp add: pair_pmf_def bind_map_pmf bind_assoc_pmf bind_return_pmf)
also have "map_pmf ?f (pair_pmf (pmf_of_set {..<v}) (pmf_of_set UNIV)) = pmf_of_set {..<2 * v}"
(is "?l = ?r" is "map_pmf ?f ?p = _")
proof(rule pmf_eqI)
fix i :: nat
have [simp]: "inj ?f" by(auto simp add: inj_on_def) arith+
define i' where "i' \<equiv> i div 2"
define b where "b \<equiv> odd i"
have i: "i = ?f (i', b)" by(simp add: i'_def b_def)
show "pmf ?l i = pmf ?r i"
by(subst i; subst pmf_map_inj')(simp_all add: pmf_pair i'_def assms lessThan_empty_iff split: split_indicator)
qed
finally show ?thesis .
qed
lemma sample_bits_fusion2:
fixes v :: nat
assumes "0 < v"
shows
"bind_pmf (pmf_of_set UNIV) (\<lambda>b. bind_pmf (pmf_of_set {..<v}) (\<lambda>c. f (c + v * (if b then 1 else 0)))) =
bind_pmf (pmf_of_set {..<2 * v}) f"
(is "?lhs = ?rhs")
proof -
have "?lhs = bind_pmf (map_pmf (\<lambda>(c, b). (c + v * (if b then 1 else 0))) (pair_pmf (pmf_of_set {..<v}) (pmf_of_set UNIV))) f"
(is "_ = bind_pmf (map_pmf ?f _) _")
unfolding pair_pmf_def by(subst bind_commute_pmf)(simp add: bind_map_pmf bind_assoc_pmf bind_return_pmf)
also have "map_pmf ?f (pair_pmf (pmf_of_set {..<v}) (pmf_of_set UNIV)) = pmf_of_set {..<2 * v}"
(is "?l = ?r" is "map_pmf ?f ?p = _")
proof(rule pmf_eqI)
fix i :: nat
have [simp]: "inj_on ?f ({..<v} \<times> UNIV)" by(auto simp add: inj_on_def)
define i' where "i' \<equiv> if i \<ge> v then i - v else i"
define b where "b \<equiv> i \<ge> v"
have i: "i = ?f (i', b)" by(simp add: i'_def b_def)
show "pmf ?l i = pmf ?r i"
proof(cases "i < 2 * v")
case True
thus ?thesis
by(subst i; subst pmf_map_inj)(auto simp add: pmf_pair i'_def assms lessThan_empty_iff split: split_indicator)
next
case False
hence "i \<notin> set_pmf ?l" "i \<notin> set_pmf ?r"
using assms by(auto simp add: lessThan_empty_iff split: if_split_asm)
thus ?thesis by(simp add: set_pmf_iff del: set_map_pmf)
qed
qed
finally show ?thesis .
qed
context fixes n :: nat notes [[function_internals]] begin
text \<open>
The check for @{term "v >= n"} should be done already at the start of the loop.
Otherwise we do not see why this algorithm should be optimal (when we start with @{term "v = n"}
and @{term "c = n - 1"}, then it can go round a few loops before it returns something).
We define the algorithm as a least fixpoint. To prove termination, we later show that it is
equivalent to a while loop which samples bitstrings of a given length, which could in turn
be implemented as a loop. The fixpoint formulation is more elegant because we do not need to
nest any loops.
\<close>
partial_function (spmf) fast_dice_roll :: "nat \<Rightarrow> nat \<Rightarrow> nat spmf"
where
"fast_dice_roll v c =
(if v \<ge> n then if c < n then return_spmf c else fast_dice_roll (v - n) (c - n)
else do {
b \<leftarrow> coin_spmf;
fast_dice_roll (2 * v) (2 * c + (if b then 1 else 0)) } )"
lemma fast_dice_roll_fixp_induct [case_names adm bottom step]:
assumes "spmf.admissible (\<lambda>fast_dice_roll. P (curry fast_dice_roll))"
and "P (\<lambda>v c. return_pmf None)"
and "\<And>fdr. P fdr \<Longrightarrow> P (\<lambda>v c. if v \<ge> n then if c < n then return_spmf c else fdr (v - n) (c - n)
else bind_spmf coin_spmf (\<lambda>b. fdr (2 * v) (2 * c + (if b then 1 else 0))))"
shows "P fast_dice_roll"
using assms by(rule fast_dice_roll.fixp_induct)
definition fast_uniform :: "nat spmf"
where "fast_uniform = fast_dice_roll 1 0"
lemma spmf_fast_dice_roll_ub:
assumes "0 < v"
shows "spmf (bind_pmf (pmf_of_set {..<v}) (fast_dice_roll v)) x \<le> (if x < n then 1 / n else 0)"
(is "?lhs \<le> ?rhs")
proof -
have "ennreal ?lhs \<le> ennreal ?rhs" using assms
proof(induction arbitrary: v x rule: fast_dice_roll_fixp_induct)
case adm thus ?case
by(rule cont_intro ccpo_class.admissible_leI)+ simp_all
case bottom thus ?case by simp
case (step fdr)
show ?case (is "?lhs \<le> ?rhs")
proof(cases "n \<le> v")
case le: True
then have "?lhs = spmf (bind_pmf (pmf_of_set {..<v}) (\<lambda>c. if c < n then return_spmf c else fdr (v - n) (c - n))) x"
by simp
also have "\<dots> = (\<integral>\<^sup>+ c'. indicator (if x < n then {x} else {}) c' \<partial>measure_pmf (pmf_of_set {..<v})) +
(\<integral>\<^sup>+ c'. indicator {n ..< v} c' * spmf (fdr (v - n) (c' - n)) x \<partial>measure_pmf (pmf_of_set {..<v}))"
(is "?then = ?found + ?continue") using step.prems
by(subst nn_integral_add[symmetric])(auto simp add: ennreal_pmf_bind AE_measure_pmf_iff lessThan_empty_iff split: split_indicator intro!: nn_integral_cong_AE)
also have "?found = (if x < n then 1 else 0) / v" using step.prems le
by(auto simp add: measure_pmf.emeasure_eq_measure measure_pmf_of_set lessThan_empty_iff Iio_Int_singleton)
also have "?continue = (\<integral>\<^sup>+ c'. indicator {n ..< v} c' * 1 / v * spmf (fdr (v - n) (c' - n)) x \<partial>count_space UNIV)"
using step.prems by(auto simp add: nn_integral_measure_pmf lessThan_empty_iff ennreal_mult[symmetric] intro!: nn_integral_cong split: split_indicator)
also have "\<dots> = (if v = n then 0 else ennreal ((v - n) / v) * spmf (bind_pmf (pmf_of_set {n..<v}) (\<lambda>c'. fdr (v - n) (c' - n))) x)"
using le step.prems
by(subst ennreal_pmf_bind)(auto simp add: ennreal_mult[symmetric] nn_integral_measure_pmf nn_integral_0_iff_AE AE_count_space nn_integral_cmult[symmetric] split: split_indicator)
also {
assume *: "n < v"
then have "pmf_of_set {n..<v} = map_pmf ((+) n) (pmf_of_set {..<v - n})"
by(subst map_pmf_of_set_inj)(auto 4 3 simp add: inj_on_def lessThan_empty_iff intro!: arg_cong[where f=pmf_of_set] intro: rev_image_eqI[where x="_ - n"] diff_less_mono)
also have "bind_pmf \<dots> (\<lambda>c'. fdr (v - n) (c' - n)) = bind_pmf (pmf_of_set {..<v - n}) (fdr (v - n))"
by(simp add: bind_map_pmf)
also have "ennreal (spmf \<dots> x) \<le> (if x < n then 1 / n else 0)"
by(rule step.IH)(simp add: *)
also note calculation }
then have "\<dots> \<le> ennreal ((v - n) / v) * (if x < n then 1 / n else 0)" using le
by(cases "v = n")(auto split del: if_split intro: divide_right_mono mult_left_mono)
also have "\<dots> = (v - n) / v * (if x < n then 1 / n else 0)" by(simp add: ennreal_mult[symmetric])
finally show ?thesis using le by(auto simp add: add_mono field_simps of_nat_diff ennreal_plus[symmetric] simp del: ennreal_plus)
next
case False
then have "?lhs = spmf (bind_pmf (pmf_of_set {..<v}) (\<lambda>c. bind_pmf (pmf_of_set UNIV) (\<lambda>b. fdr (2 * v) (2 * c + (if b then 1 else 0))))) x"
by(simp add: bind_spmf_spmf_of_set)
also have "\<dots> = spmf (bind_pmf (pmf_of_set {..<2 * v}) (fdr (2 * v))) x" using step.prems
by(simp add: sample_bits_fusion[symmetric])
also have "\<dots> \<le> ?rhs" using step.prems by(intro step.IH) simp
finally show ?thesis .
qed
qed
thus ?thesis by simp
qed
lemma spmf_fast_uniform_ub:
"spmf fast_uniform x \<le> (if x < n then 1 / n else 0)"
proof -
have "{..<Suc 0} = {0}" by auto
then show ?thesis using spmf_fast_dice_roll_ub[of 1 x]
by(simp add: fast_uniform_def pmf_of_set_singleton bind_return_pmf split: if_split_asm)
qed
lemma fast_dice_roll_0 [simp]: "fast_dice_roll 0 c = return_pmf None"
by(induction arbitrary: c rule: fast_dice_roll_fixp_induct)(simp_all add: bind_eq_return_pmf_None)
text \<open>To prove termination, we fold all the iterations that only double into one big step\<close>
definition fdr_step :: "nat \<Rightarrow> nat \<Rightarrow> (nat \<times> nat) spmf"
where
"fdr_step v c =
(if v = 0 then return_pmf None
else let x = 2 ^ (nat \<lceil>log 2 (max 1 n) - log 2 v\<rceil>) in
map_spmf (\<lambda>bs. (x * v, x * c + bs)) (spmf_of_set {..<x}))"
lemma fdr_step_unfold:
"fdr_step v c =
(if v = 0 then return_pmf None
else if n \<le> v then return_spmf (v, c)
else do {
b \<leftarrow> coin_spmf;
fdr_step (2 * v) (2 * c + (if b then 1 else 0)) })"
(is "?lhs = ?rhs" is "_ = (if _ then _ else ?else)")
proof(cases "v = 0")
case v: False
define x where "x \<equiv> \<lambda>v :: nat. 2 ^ (nat \<lceil>log 2 (max 1 n) - log 2 v\<rceil>) :: nat"
have x_pos: "x v > 0" by(simp add: x_def)
show ?thesis
proof(cases "n \<le> v")
case le: True
hence "x v = 1" using v by(simp add: x_def log_le)
moreover have "{..<1} = {0 :: nat}" by auto
ultimately show ?thesis using le v by(simp add: fdr_step_def spmf_of_set_singleton)
next
case less: False
hence even: "even (x v)" using v by(simp add: x_def)
with x_pos have x_ge_1: "x v > 1" by(cases "x v = 1") auto
have *: "x (2 * v) = x v div 2" using v less unfolding x_def
apply(simp add: log_mult diff_add_eq_diff_diff_swap)
apply(rewrite in "_ = 2 ^ \<hole> div _" le_add_diff_inverse2[symmetric, where b=1])
apply (simp add: Suc_leI)
apply(simp del: Suc_pred)
done
have "?lhs = map_spmf (\<lambda>bs. (x v * v, x v * c + bs)) (spmf_of_set {..<x v})"
using v by(simp add: fdr_step_def x_def Let_def)
also from even have "\<dots> = bind_pmf (pmf_of_set {..<2 * (x v div 2)}) (\<lambda>bs. return_spmf (x v * v, x v * c + bs))"
by(simp add: map_spmf_conv_bind_spmf bind_spmf_spmf_of_set x_pos lessThan_empty_iff)
also have "\<dots> = bind_spmf coin_spmf (\<lambda>b. bind_spmf (spmf_of_set {..<x v div 2})
(\<lambda>c'. return_spmf (x v * v, x v * c + c' + (x v div 2) * (if b then 1 else 0))))"
using x_ge_1
by(simp add: sample_bits_fusion2[symmetric] bind_spmf_spmf_of_set lessThan_empty_iff add.assoc)
also have "\<dots> = bind_spmf coin_spmf (\<lambda>b. map_spmf (\<lambda>bs. (x (2 * v) * (2 * v), x (2 * v) * (2 * c + (if b then 1 else 0)) + bs)) (spmf_of_set {..<x (2 * v)}))"
using * even by(simp add: map_spmf_conv_bind_spmf algebra_simps)
also have "\<dots> = ?rhs" using v less by(simp add: fdr_step_def Let_def x_def)
finally show ?thesis .
qed
qed(simp add: fdr_step_def)
lemma fdr_step_induct [case_names fdr_step]:
"(\<And>v c. (\<And>b. \<lbrakk>v \<noteq> 0; v < n\<rbrakk> \<Longrightarrow> P (2 * v) (2 * c + (if b then 1 else 0))) \<Longrightarrow> P v c)
\<Longrightarrow> P v c"
apply induction_schema
apply pat_completeness
apply(relation "Wellfounded.measure (\<lambda>(v, c). n - v)")
apply simp_all
done
partial_function (spmf) fdr_alt :: "nat \<Rightarrow> nat \<Rightarrow> nat spmf"
where
"fdr_alt v c = do {
(v', c') \<leftarrow> fdr_step v c;
if c' < n then return_spmf c' else fdr_alt (v' - n) (c' - n) }"
lemma fast_dice_roll_alt: "fdr_alt = fast_dice_roll"
proof(intro ext)
show "fdr_alt v c = fast_dice_roll v c" for v c
proof(rule spmf.leq_antisym)
show "ord_spmf (=) (fdr_alt v c) (fast_dice_roll v c)"
proof(induction arbitrary: v c rule: fdr_alt.fixp_induct[case_names adm bottom step])
case adm show ?case by simp
case bottom show ?case by simp
case (step fdra)
show ?case
proof(induction v c rule: fdr_step_induct)
case inner: (fdr_step v c)
show ?case
apply(rewrite fdr_step_unfold)
apply(rewrite fast_dice_roll.simps)
apply(auto intro!: ord_spmf_bind_reflI simp add: Let_def inner.IH step.IH)
done
qed
qed
have "ord_spmf (=) (fast_dice_roll v c) (fdr_alt v c)"
and "fast_dice_roll 0 c = return_pmf None"
proof(induction arbitrary: v c rule: fast_dice_roll_fixp_induct)
case adm thus ?case by simp
case bottom case 1 thus ?case by simp
case bottom case 2 thus ?case by simp
case (step fdr) case 1 show ?case
apply(rewrite fdr_alt.simps)
apply(rewrite fdr_step_unfold)
apply(clarsimp simp add: Let_def)
apply(auto intro!: ord_spmf_bind_reflI simp add: fdr_alt.simps[symmetric] step.IH rel_pmf_return_pmf2 set_pmf_bind_spmf o_def set_pmf_spmf_of_set split: if_split_asm)
done
case step case 2 from step.IH show ?case by(simp add: Let_def bind_eq_return_pmf_None)
qed
then show "ord_spmf (=) (fast_dice_roll v c) (fdr_alt v c)" by -
qed
qed
lemma lossless_fdr_step [simp]: "lossless_spmf (fdr_step v c) \<longleftrightarrow> v > 0"
by(simp add: fdr_step_def Let_def lessThan_empty_iff)
lemma lossless_fast_dice_roll:
assumes "c < v" "v \<le> n"
shows "lossless_spmf (fast_dice_roll v c)"
proof(cases "v < n")
case True
let ?I = "\<lambda>(v, c). c < v \<and> n \<le> v \<and> v < 2 * n"
let ?f = "\<lambda>(v, c). if n \<le> c then n + c - v + 1 else 0"
have invar: "?I (v', c')" if step: "(v', c') \<in> set_spmf (fdr_step (v - n) (c - n))"
and I: "c < v" "n \<le> v" "v < 2 * n" and c: "n \<le> c" for v' c' v c
proof(clarsimp; safe)
define x where "x = nat \<lceil>log 2 (max 1 n) - log 2 (v - n)\<rceil>"
have **: "-1 < log 2 (real n / real (v - n))" by(rule less_le_trans[where y=0])(use I c in \<open>auto\<close>)
from I c step obtain bs where v': "v' = 2 ^ x * (v - n)"
and c': "c' = 2 ^ x * (c - n) + bs"
and bs: "bs < 2 ^ x"
unfolding fdr_step_def x_def[symmetric] by(auto simp add: Let_def)
have "2 ^ x * (c - n) + bs < 2 ^ x * (c - n + 1)" unfolding distrib_left using bs
by(intro add_strict_left_mono) simp
also have "\<dots> \<le> 2 ^ x * (v - n)" using I c by(intro mult_left_mono) auto
finally show "c' < v'" using c' v' by simp
have "v' = 2 powr x * (v - n)" by(simp add: powr_realpow v')
also have "\<dots> < 2 powr (log 2 (max 1 n) - log 2 (v - n) + 1) * (v - n)"
using ** I c by(intro mult_strict_right_mono)(auto simp add: x_def log_divide)
also have "\<dots> \<le> 2 * n" unfolding powr_add using I c
by(simp add: log_divide[symmetric] max_def)
finally show "v' < 2 * n" using c' by(simp del: of_nat_add)
have "log 2 (n / (v - n)) \<le> x" using I c ** by(auto simp add: x_def log_divide max_def)
hence "2 powr log 2 (n / (v - n)) \<le> 2 powr x" by(rule powr_mono) simp
also have "2 powr log 2 (n / (v - n)) = n / (v - n)" using I c by(simp)
finally have "n \<le> real (2 ^ x * (v - n))" using I c by(simp add: field_simps powr_realpow)
then show "n \<le> v'" by(simp add: v' del: of_nat_mult)
qed
have loop: "lossless_spmf (loop_spmf.while (\<lambda>(v, c). n \<le> c) (\<lambda>(v, c). fdr_step (v - n) (c - n)) (v, c))"
if "c < 2 * n" and "n \<le> v" and "c < v" and "v < 2 * n"
for v c
proof(rule termination_variant_invar; clarify?)
fix v c
assume I: "?I (v, c)" and c: "n \<le> c"
show "?f (v, c) \<le> n" using I c by auto
define x where "x = nat \<lceil>log 2 (max 1 n) - log 2 (v - n)\<rceil>"
define p :: real where "p \<equiv> 1 / (2 * n)"
from I c have n: "0 < n" and v: "n < v" by auto
from I c v n have x_pos: "x > 0" by(auto simp add: x_def max_def)
have **: "-1 < log 2 (real n / real (v - n))" by(rule less_le_trans[where y=0])(use I c in \<open>auto\<close>)
then have "x \<le> log 2 (real n) + 1" using v n
by(auto simp add: x_def log_divide[symmetric] max_def field_simps intro: order_trans[OF of_int_ceiling_le_add_one])
hence "2 powr x \<le> 2 powr \<dots>" by(rule powr_mono) simp
hence "p \<le> 1 / 2 ^ x" unfolding powr_add using n
by(subst (asm) powr_realpow, simp)(subst (asm) powr_log_cancel; simp_all add: p_def field_simps)
also
let ?X = "{c'. n \<le> 2 ^ x * (c - n) + c' \<longrightarrow> n + (2 ^ x * (c - n) + c') - 2 ^ x * (v - n) < n + c - v}"
have "n + c * 2 ^ x - v * 2 ^ x < c + n - v" using I c
proof(cases "n + c * 2 ^ x \<ge> v * 2 ^ x")
case True
have "(int c - v) * 2 ^ x < (int c - v) * 1"
using x_pos I c by(intro mult_strict_left_mono_neg) simp_all
then have "int n + c * 2 ^ x - v * 2 ^ x < c + int n - v" by(simp add: algebra_simps)
also have "\<dots> = int (c + n - v)" using I c by auto
also have "int n + c * 2 ^ x - v * 2 ^ x = int (n + c * 2 ^ x - v * 2 ^ x)"
using True that by(simp add: of_nat_diff)
finally show ?thesis by simp
qed auto
then have "{..<2 ^ x} \<inter> ?X \<noteq> {}" using that n v
by(auto simp add: disjoint_eq_subset_Compl Collect_neg_eq[symmetric] lessThan_subset_Collect algebra_simps intro: exI[where x=0])
then have "0 < card ({..<2 ^ x} \<inter> ?X)" by(simp add: card_gt_0_iff)
hence "1 / 2 ^ x \<le> \<dots> / 2 ^ x" by(simp add: field_simps)
finally show "p \<le> spmf (map_spmf (\<lambda>s'. ?f s' < ?f (v, c)) (fdr_step (v - n) (c - n))) True"
using I c unfolding fdr_step_def x_def[symmetric]
by(clarsimp simp add: Let_def spmf.map_comp o_def spmf_map measure_spmf_of_set vimage_def p_def)
show "lossless_spmf (fdr_step (v - n) (c - n))" using I c by simp
show "?I (v', c')" if step: "(v', c') \<in> set_spmf (fdr_step (v - n) (c - n))" for v' c'
using that by(rule invar)(use I c in auto)
next
show "(0 :: real) < 1 / (2 * n)" using that by(simp)
show "?I (v, c)" using that by simp
qed
show ?thesis using assms True
by(auto simp add: fast_dice_roll_alt[symmetric] fast_dice_roll_alt_conv_while intro!: loop dest: invar[of _ _ "n + v" "n + c", simplified])
next
case False
with assms have "v = n" by simp
thus ?thesis using assms by(subst fast_dice_roll.simps) simp
qed
lemma fast_dice_roll_n0:
assumes "n = 0"
shows "fast_dice_roll v c = return_pmf None"
by(induction arbitrary: v c rule: fast_dice_roll_fixp_induct)(simp_all add: assms)
lemma lossless_fast_uniform [simp]: "lossless_spmf fast_uniform \<longleftrightarrow> n > 0"
proof(cases "n = 0")
case True
then show ?thesis using fast_dice_roll_n0 unfolding fast_uniform_def by(simp)
next
case False
then show ?thesis by(simp add: fast_uniform_def lossless_fast_dice_roll)
qed
lemma spmf_fast_uniform: "spmf fast_uniform x = (if x < n then 1 / n else 0)"
proof(cases "n > 0")
case n: True
show ?thesis using spmf_fast_uniform_ub
proof(rule spmf_ub_tight)
have "(\<Sum>\<^sup>+ x. ennreal (if x < n then 1 / n else 0)) = (\<Sum>\<^sup>+ x\<in>{..<n}. 1 / n)"
by(auto simp add: nn_integral_count_space_indicator simp del: nn_integral_const intro: nn_integral_cong)
also have "\<dots> = 1" using n by(simp add: field_simps ennreal_of_nat_eq_real_of_nat ennreal_mult[symmetric])
also have "\<dots> = weight_spmf fast_uniform" using lossless_fast_uniform n unfolding lossless_spmf_def by simp
finally show "(\<Sum>\<^sup>+ x. ennreal (if x < n then 1 / n else 0)) = \<dots>" .
qed
next
case False
with fast_dice_roll_n0[of 1 0] show ?thesis unfolding fast_uniform_def by(simp)
qed
end
lemma fast_uniform_conv_uniform: "fast_uniform n = spmf_of_set {..<n}"
by(rule spmf_eqI)(simp add: spmf_fast_uniform spmf_of_set)
end
|
[STATEMENT]
lemma apath_Cons_iff:
"apath u (e # es) w \<longleftrightarrow> e \<in> arcs G \<and> tail G e = u \<and> apath (head G e) es w
\<and> tail G e \<notin> set (awalk_verts (head G e) es)" (is "?L \<longleftrightarrow> ?R")
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. apath u (e # es) w = (e \<in> arcs G \<and> tail G e = u \<and> apath (head G e) es w \<and> tail G e \<notin> set (awalk_verts (head G e) es))
[PROOF STEP]
by (auto simp: apath_def awalk_Cons_iff)
|
Formal statement is: corollary connected_convex_diff_countable: fixes U :: "'a::euclidean_space set" assumes "convex U" "\<not> collinear U" "countable S" shows "connected(U - S)" Informal statement is: If $U$ is a convex set in $\mathbb{R}^n$ that is not contained in a hyperplane, and $S$ is a countable set, then $U - S$ is connected.
|
lemma eventually_ceiling_eq: 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. ceiling (f x) = ceiling l"
|
theory TopoS_Stateful_Policy_impl
imports TopoS_Composition_Theory_impl TopoS_Stateful_Policy_Algorithm
begin
section{*Stateful Policy -- List Implementaion*}
record 'v stateful_list_policy =
hostsL :: "'v list"
flows_fixL :: "('v \<times>'v) list"
flows_stateL :: "('v \<times>'v) list"
definition stateful_list_policy_to_list_graph :: "'v stateful_list_policy \<Rightarrow> 'v list_graph" where
"stateful_list_policy_to_list_graph \<T> = \<lparr> nodesL = hostsL \<T>, edgesL = (flows_fixL \<T>) @ [e \<leftarrow> flows_stateL \<T>. e \<notin> set (flows_fixL \<T>)] @ [e \<leftarrow> backlinks (flows_stateL \<T>). e \<notin> set (flows_fixL \<T>)] \<rparr>"
lemma stateful_list_policy_to_list_graph_complies:
"list_graph_to_graph (stateful_list_policy_to_list_graph \<lparr> hostsL = V, flows_fixL = E\<^sub>f, flows_stateL = E\<^sub>\<sigma> \<rparr>) =
stateful_policy_to_network_graph \<lparr> hosts = set V, flows_fix = set E\<^sub>f, flows_state = set E\<^sub>\<sigma> \<rparr>"
by(simp add: stateful_list_policy_to_list_graph_def stateful_policy_to_network_graph_def all_flows_def list_graph_to_graph_def backlinks_correct, blast)
lemma valid_list_graph_stateful_list_policy_to_list_graph:
"valid_list_graph G \<Longrightarrow> distinct E \<Longrightarrow> set E \<subseteq> set (edgesL G) \<Longrightarrow> valid_list_graph (stateful_list_policy_to_list_graph \<lparr>hostsL = nodesL G, flows_fixL = edgesL G, flows_stateL = E\<rparr>)"
apply(simp add: valid_list_graph_def stateful_list_policy_to_list_graph_def)
apply(rule conjI)
apply(simp add: backlinks_distinct)
apply(rule conjI)
apply(simp add: backlinks_set)
apply(blast)
apply(rule conjI)
apply(simp add: backlinks_set)
apply(blast)
apply(simp add: valid_list_graph_axioms_def)
apply(rule conjI)
apply(simp add: backlinks_set)
apply(force)
apply(simp add: backlinks_set)
apply(clarsimp)
apply(erule disjE)
apply(auto)[1]
apply(erule disjE)
apply(auto)[1]
by force
subsection{*Algorithms*}
fun filter_IFS_no_violations_accu :: "'v list_graph \<Rightarrow> 'v SecurityInvariant list \<Rightarrow> ('v \<times> 'v) list \<Rightarrow> ('v \<times> 'v) list \<Rightarrow> ('v \<times> 'v) list" where
"filter_IFS_no_violations_accu G M accu [] = accu" |
"filter_IFS_no_violations_accu G M accu (e#Es) = (if
all_security_requirements_fulfilled (TopoS_Composition_Theory_impl.get_IFS M) (stateful_list_policy_to_list_graph \<lparr> hostsL = nodesL G, flows_fixL = edgesL G, flows_stateL = (e#accu) \<rparr>)
then filter_IFS_no_violations_accu G M (e#accu) Es
else filter_IFS_no_violations_accu G M accu Es)"
definition filter_IFS_no_violations :: "'v list_graph \<Rightarrow> 'v SecurityInvariant list \<Rightarrow> ('v \<times> 'v) list" where
"filter_IFS_no_violations G M = filter_IFS_no_violations_accu G M [] (edgesL G)"
lemma filter_IFS_no_violations_accu_distinct: "\<lbrakk> distinct (Es@accu) \<rbrakk> \<Longrightarrow> distinct (filter_IFS_no_violations_accu G M accu Es)"
apply(induction Es arbitrary: accu)
by(simp_all)
lemma filter_IFS_no_violations_accu_complies:
"\<lbrakk>\<forall> (m_impl, m_spec) \<in> set M. SecurityInvariant_complies_formal_def m_impl m_spec;
valid_list_graph G; set Es \<subseteq> set (edgesL G); set accu \<subseteq> set (edgesL G); distinct (Es@accu) \<rbrakk> \<Longrightarrow>
filter_IFS_no_violations_accu G (get_impl M) accu Es = TopoS_Stateful_Policy_Algorithm.filter_IFS_no_violations_accu (list_graph_to_graph G) (get_spec M) accu Es"
proof(induction Es arbitrary: accu)
case Nil
thus ?case by(simp add: get_impl_def get_spec_def)
next
case (Cons e Es)
-- "@{thm Cons.IH[OF Cons.prems(1) Cons.prems(2)]}"
let ?caseDistinction = "all_security_requirements_fulfilled (TopoS_Composition_Theory_impl.get_IFS (get_impl M)) (stateful_list_policy_to_list_graph \<lparr> hostsL = nodesL G, flows_fixL = edgesL G, flows_stateL = (e#accu) \<rparr>)"
from get_IFS_get_ACS_select_simps(2)[OF Cons.prems(1)] have get_impl_zip_simp: "(get_impl (zip (TopoS_Composition_Theory_impl.get_IFS (get_impl M)) (TopoS_Composition_Theory.get_IFS (get_spec M)))) = TopoS_Composition_Theory_impl.get_IFS (get_impl M)" by simp
from get_IFS_get_ACS_select_simps(3)[OF Cons.prems(1)] have get_spec_zip_simp: "(get_spec (zip (TopoS_Composition_Theory_impl.get_IFS (get_impl M)) (TopoS_Composition_Theory.get_IFS (get_spec M)))) = TopoS_Composition_Theory.get_IFS (get_spec M)" by simp
from Cons.prems(3) Cons.prems(4) have "set (e # accu) \<subseteq> set (edgesL G)" by simp
from Cons.prems(4) have "set (accu) \<subseteq> set (edgesL G)" by simp
from Cons.prems(5) have "distinct (e # accu)" by simp
from Cons.prems(3) have "set Es \<subseteq> set (edgesL G)" by simp
from Cons.prems(5) have "distinct (Es @ accu)" by simp
from Cons.prems(5) have "distinct (Es @ (e # accu))" by simp
from Cons.prems(2) have validLG: "valid_list_graph (stateful_list_policy_to_list_graph \<lparr>hostsL = nodesL G, flows_fixL = edgesL G, flows_stateL = e # accu\<rparr>)"
apply(rule valid_list_graph_stateful_list_policy_to_list_graph)
apply(fact `distinct (e # accu)`)
apply(fact `set (e # accu) \<subseteq> set (edgesL G)`)
done
from get_IFS_get_ACS_select_simps(1)[OF Cons.prems(1)]
have "\<forall> (m_impl, m_spec) \<in> set (zip (get_IFS (get_impl M)) (TopoS_Composition_Theory.get_IFS (get_spec M))). SecurityInvariant_complies_formal_def m_impl m_spec" .
from all_security_requirements_fulfilled_complies[OF this] have all_security_requirements_fulfilled_eq_rule:
"\<And>G. valid_list_graph G \<Longrightarrow>
TopoS_Composition_Theory_impl.all_security_requirements_fulfilled (TopoS_Composition_Theory_impl.get_IFS (get_impl M)) G =
TopoS_Composition_Theory.all_security_requirements_fulfilled (TopoS_Composition_Theory.get_IFS (get_spec M)) (list_graph_to_graph G)"
by(simp add: get_impl_zip_simp get_spec_zip_simp)
have case_impl_spec: "?caseDistinction <-> TopoS_Composition_Theory.all_security_requirements_fulfilled (TopoS_Composition_Theory.get_IFS (get_spec M)) (stateful_policy_to_network_graph \<lparr> hosts = set (nodesL G), flows_fix = set (edgesL G), flows_state = set (e#accu) \<rparr>)"
apply(subst all_security_requirements_fulfilled_eq_rule[OF validLG])
by(simp add: stateful_list_policy_to_list_graph_complies)
show ?case
proof(case_tac ?caseDistinction)
assume cTrue: ?caseDistinction
from cTrue have g1: "TopoS_Stateful_Policy_impl.filter_IFS_no_violations_accu G (get_impl M) accu (e # Es) = TopoS_Stateful_Policy_impl.filter_IFS_no_violations_accu G (get_impl M) (e # accu) Es" by simp
from cTrue[simplified case_impl_spec] have g2: "TopoS_Stateful_Policy_Algorithm.filter_IFS_no_violations_accu (list_graph_to_graph G) (get_spec M) accu (e # Es) =
TopoS_Stateful_Policy_Algorithm.filter_IFS_no_violations_accu (list_graph_to_graph G) (get_spec M) (e#accu)Es"
by(simp add: list_graph_to_graph_def)
show ?case
apply(simp only: g1 g2)
using Cons.IH[OF Cons.prems(1) Cons.prems(2) `set Es \<subseteq> set (edgesL G)` `set (e # accu) \<subseteq> set (edgesL G)` `distinct (Es @ (e # accu))`] by simp
next
assume cFalse: "\<not> ?caseDistinction"
from cFalse have g1: "TopoS_Stateful_Policy_impl.filter_IFS_no_violations_accu G (get_impl M) accu (e # Es) = TopoS_Stateful_Policy_impl.filter_IFS_no_violations_accu G (get_impl M) accu Es" by simp
from cFalse[simplified case_impl_spec] have g2: "TopoS_Stateful_Policy_Algorithm.filter_IFS_no_violations_accu (list_graph_to_graph G) (get_spec M) accu (e # Es) =
TopoS_Stateful_Policy_Algorithm.filter_IFS_no_violations_accu (list_graph_to_graph G) (get_spec M) accu Es"
by(simp add: list_graph_to_graph_def)
show ?case
apply(simp only: g1 g2)
using Cons.IH[OF Cons.prems(1) Cons.prems(2) `set Es \<subseteq> set (edgesL G)` `set accu \<subseteq> set (edgesL G)` `distinct (Es @ accu)`] by simp
qed
qed
lemma filter_IFS_no_violations_complies:
"\<lbrakk> \<forall> (m_impl, m_spec) \<in> set M. SecurityInvariant_complies_formal_def m_impl m_spec; valid_list_graph G \<rbrakk> \<Longrightarrow>
filter_IFS_no_violations G (get_impl M) = TopoS_Stateful_Policy_Algorithm.filter_IFS_no_violations (list_graph_to_graph G) (get_spec M) (edgesL G)"
apply(unfold filter_IFS_no_violations_def TopoS_Stateful_Policy_Algorithm.filter_IFS_no_violations_def)
apply(rule filter_IFS_no_violations_accu_complies)
apply(simp_all)
apply(simp add: valid_list_graph_def)
done
fun filter_compliant_stateful_ACS_accu :: "'v list_graph \<Rightarrow> 'v SecurityInvariant list \<Rightarrow> ('v \<times> 'v) list \<Rightarrow> ('v \<times> 'v) list \<Rightarrow> ('v \<times> 'v) list" where
"filter_compliant_stateful_ACS_accu G M accu [] = accu" |
"filter_compliant_stateful_ACS_accu G M accu (e#Es) = (if
e \<notin> set (backlinks (edgesL G)) \<and> (\<forall>F \<in> set (implc_get_offending_flows (get_ACS M) (stateful_list_policy_to_list_graph \<lparr> hostsL = nodesL G, flows_fixL = edgesL G, flows_stateL = (e#accu) \<rparr>)). set F \<subseteq> set (backlinks (e#accu)))
then filter_compliant_stateful_ACS_accu G M (e#accu) Es
else filter_compliant_stateful_ACS_accu G M accu Es)"
definition filter_compliant_stateful_ACS :: "'v list_graph \<Rightarrow> 'v SecurityInvariant list \<Rightarrow> ('v \<times> 'v) list" where
"filter_compliant_stateful_ACS G M = filter_compliant_stateful_ACS_accu G M [] (edgesL G)"
lemma filter_compliant_stateful_ACS_accu_complies:
"\<lbrakk>\<forall> (m_impl, m_spec) \<in> set M. SecurityInvariant_complies_formal_def m_impl m_spec;
valid_list_graph G; set Es \<subseteq> set (edgesL G); set accu \<subseteq> set (edgesL G); distinct (Es@accu) \<rbrakk> \<Longrightarrow>
filter_compliant_stateful_ACS_accu G (get_impl M) accu Es = TopoS_Stateful_Policy_Algorithm.filter_compliant_stateful_ACS_accu (list_graph_to_graph G) (get_spec M) accu Es"
proof(induction Es arbitrary: accu)
case Nil
thus ?case by(simp add: get_impl_def get_spec_def)
next
case (Cons e Es)
-- "@{thm Cons.IH[OF Cons.prems(1) Cons.prems(2)]}"
let ?caseDistinction = "e \<notin> set (backlinks (edgesL G)) \<and> (\<forall>F \<in> set (implc_get_offending_flows (get_ACS (get_impl M)) (stateful_list_policy_to_list_graph \<lparr> hostsL = nodesL G, flows_fixL = edgesL G, flows_stateL = (e#accu) \<rparr>)). set F \<subseteq> set (backlinks (e#accu)))"
have backlinks_simp: "(e \<notin> set (backlinks (edgesL G))) <-> (e \<notin> backflows (set (edgesL G)))"
by(simp add: backlinks_correct)
have "\<And> G X. (\<forall>F\<in>set (implc_get_offending_flows (TopoS_Composition_Theory_impl.get_ACS (get_impl M)) G). set F \<subseteq> X) =
(\<forall>F\<in>set ` set (implc_get_offending_flows (TopoS_Composition_Theory_impl.get_ACS (get_impl M)) G). F \<subseteq> X)" by blast
also have "\<And> G X. valid_list_graph G \<Longrightarrow> (\<forall>F\<in>set ` set (implc_get_offending_flows (TopoS_Composition_Theory_impl.get_ACS (get_impl M)) G). F \<subseteq> X) =
(\<forall>F\<in>get_offending_flows (TopoS_Composition_Theory.get_ACS (get_spec M)) (list_graph_to_graph G). F \<subseteq> X)"
using implc_get_offending_flows_complies[OF get_IFS_get_ACS_select_simps(4)[OF Cons.prems(1)], simplified get_IFS_get_ACS_select_simps[OF Cons.prems(1)]] by simp
finally have implc_get_offending_flows_simp_rule: "\<And>G X. valid_list_graph G \<Longrightarrow>
(\<forall>F\<in>set (implc_get_offending_flows (TopoS_Composition_Theory_impl.get_ACS (get_impl M)) G). set F \<subseteq> X) = (\<forall>F\<in>get_offending_flows (TopoS_Composition_Theory.get_ACS (get_spec M)) (list_graph_to_graph G). F \<subseteq> X)" .
from Cons.prems(3) Cons.prems(4) have "set (e # accu) \<subseteq> set (edgesL G)" by simp
from Cons.prems(4) have "set (accu) \<subseteq> set (edgesL G)" by simp
from Cons.prems(5) have "distinct (e # accu)" by simp
from Cons.prems(3) have "set Es \<subseteq> set (edgesL G)" by simp
from Cons.prems(5) have "distinct (Es @ accu)" by simp
from Cons.prems(5) have "distinct (Es @ (e # accu))" by simp
from Cons.prems(2) have validLG: "valid_list_graph (stateful_list_policy_to_list_graph \<lparr>hostsL = nodesL G, flows_fixL = edgesL G, flows_stateL = e # accu\<rparr>)"
apply(rule valid_list_graph_stateful_list_policy_to_list_graph)
apply(fact `distinct (e # accu)`)
apply(fact `set (e # accu) \<subseteq> set (edgesL G)`)
done
have "set (backlinks (e # accu)) = backflows (insert e (set accu))"
by(simp add: backlinks_set backflows_def)
-- "@{thm implc_get_offending_flows_simp_rule[OF validLG]}"
have case_impl_spec: "?caseDistinction <-> (
e \<notin> backflows (set (edgesL G)) \<and> (\<forall>F \<in> get_offending_flows (TopoS_Composition_Theory.get_ACS (get_spec M)) (stateful_policy_to_network_graph \<lparr> hosts = set (nodesL G), flows_fix = set (edgesL G), flows_state = set (e#accu) \<rparr>). F \<subseteq> (backflows (set (e#accu)))))"
apply(simp add: backlinks_simp)
apply(simp add: implc_get_offending_flows_simp_rule[OF validLG])
apply(simp add: stateful_list_policy_to_list_graph_complies)
by(simp add: `set (backlinks (e # accu)) = backflows (insert e (set accu))`)
show ?case
proof(case_tac ?caseDistinction)
assume cTrue: ?caseDistinction
from cTrue have g1: "TopoS_Stateful_Policy_impl.filter_compliant_stateful_ACS_accu G (get_impl M) accu (e # Es) = TopoS_Stateful_Policy_impl.filter_compliant_stateful_ACS_accu G (get_impl M) (e#accu) Es" by simp
from cTrue[simplified case_impl_spec] have g2: "TopoS_Stateful_Policy_Algorithm.filter_compliant_stateful_ACS_accu (list_graph_to_graph G) (get_spec M) accu (e # Es) =
TopoS_Stateful_Policy_Algorithm.filter_compliant_stateful_ACS_accu (list_graph_to_graph G) (get_spec M) (e#accu) Es"
by(simp add: list_graph_to_graph_def)
show ?case
apply(simp only: g1 g2)
using Cons.IH[OF Cons.prems(1) Cons.prems(2) `set Es \<subseteq> set (edgesL G)` `set (e # accu) \<subseteq> set (edgesL G)` `distinct (Es @ (e # accu))`] by simp
next
assume cFalse: "\<not> (?caseDistinction)"
from cFalse have g1: "TopoS_Stateful_Policy_impl.filter_compliant_stateful_ACS_accu G (get_impl M) accu (e # Es) = TopoS_Stateful_Policy_impl.filter_compliant_stateful_ACS_accu G (get_impl M) accu Es" by force
from cFalse[simplified case_impl_spec] have g2: "TopoS_Stateful_Policy_Algorithm.filter_compliant_stateful_ACS_accu (list_graph_to_graph G) (get_spec M) accu (e # Es) =
TopoS_Stateful_Policy_Algorithm.filter_compliant_stateful_ACS_accu (list_graph_to_graph G) (get_spec M) accu Es"
apply(simp add: list_graph_to_graph_def) by fast
show ?case
apply(simp only: g1 g2)
using Cons.IH[OF Cons.prems(1) Cons.prems(2) `set Es \<subseteq> set (edgesL G)` `set accu \<subseteq> set (edgesL G)` `distinct (Es @ accu)`] by simp
qed
qed
lemma filter_compliant_stateful_ACS_cont_complies:
"\<lbrakk> \<forall> (m_impl, m_spec) \<in> set M. SecurityInvariant_complies_formal_def m_impl m_spec; valid_list_graph G; set Es \<subseteq> set (edgesL G); distinct Es \<rbrakk> \<Longrightarrow>
filter_compliant_stateful_ACS_accu G (get_impl M) [] Es = TopoS_Stateful_Policy_Algorithm.filter_compliant_stateful_ACS (list_graph_to_graph G) (get_spec M) Es"
apply(unfold filter_compliant_stateful_ACS_def TopoS_Stateful_Policy_Algorithm.filter_compliant_stateful_ACS_def)
apply(rule filter_compliant_stateful_ACS_accu_complies)
apply(simp_all)
done
lemma filter_compliant_stateful_ACS_complies:
"\<lbrakk> \<forall> (m_impl, m_spec) \<in> set M. SecurityInvariant_complies_formal_def m_impl m_spec; valid_list_graph G \<rbrakk> \<Longrightarrow>
filter_compliant_stateful_ACS G (get_impl M) = TopoS_Stateful_Policy_Algorithm.filter_compliant_stateful_ACS (list_graph_to_graph G) (get_spec M) (edgesL G)"
apply(unfold filter_compliant_stateful_ACS_def TopoS_Stateful_Policy_Algorithm.filter_compliant_stateful_ACS_def)
apply(rule filter_compliant_stateful_ACS_accu_complies)
apply(simp_all)
apply(simp add: valid_list_graph_def)
done
(*TODO: show valid_stateful_policy and distinctness and valid_list_graph, ...*)
definition generate_valid_stateful_policy_IFSACS :: "'v list_graph \<Rightarrow> 'v SecurityInvariant list \<Rightarrow> 'v stateful_list_policy" where
"generate_valid_stateful_policy_IFSACS G M = (let filterIFS = filter_IFS_no_violations G M in
(let filterACS = filter_compliant_stateful_ACS_accu G M [] filterIFS in \<lparr> hostsL = nodesL G, flows_fixL = edgesL G, flows_stateL = filterACS \<rparr>))"
fun inefficient_list_intersect :: "'a list \<Rightarrow> 'a list \<Rightarrow> 'a list" where
"inefficient_list_intersect [] bs = []" |
"inefficient_list_intersect (a#as) bs = (if a \<in> set bs then a#(inefficient_list_intersect as bs) else inefficient_list_intersect as bs)"
lemma inefficient_list_intersect_correct: "set (inefficient_list_intersect a b) = (set a) \<inter> (set b)"
apply(induction a)
by(simp_all)
definition generate_valid_stateful_policy_IFSACS_2 :: "'v list_graph \<Rightarrow> 'v SecurityInvariant list \<Rightarrow> 'v stateful_list_policy" where
"generate_valid_stateful_policy_IFSACS_2 G M =
\<lparr> hostsL = nodesL G, flows_fixL = edgesL G, flows_stateL = inefficient_list_intersect (filter_IFS_no_violations G M) (filter_compliant_stateful_ACS G M) \<rparr>"
lemma generate_valid_stateful_policy_IFSACS_2_complies: "\<lbrakk>\<forall> (m_impl, m_spec) \<in> set M. SecurityInvariant_complies_formal_def m_impl m_spec;
valid_list_graph G;
valid_reqs (get_spec M);
TopoS_Composition_Theory.all_security_requirements_fulfilled (get_spec M) (list_graph_to_graph G);
\<T> = (generate_valid_stateful_policy_IFSACS_2 G (get_impl M))\<rbrakk> \<Longrightarrow>
stateful_policy_compliance \<lparr>hosts = set (hostsL \<T>), flows_fix = set (flows_fixL \<T>), flows_state = set (flows_stateL \<T>) \<rparr> (list_graph_to_graph G) (get_spec M)"
apply(rule_tac edgesList="edgesL G" in generate_valid_stateful_policy_IFSACS_2_stateful_policy_compliance)
apply(simp)
apply (metis valid_list_graph_def valid_list_graph_iff_valid_graph)
apply(simp)
apply(simp add: list_graph_to_graph_def)
apply(simp add: TopoS_Stateful_Policy_Algorithm.generate_valid_stateful_policy_IFSACS_2_def TopoS_Stateful_Policy_impl.generate_valid_stateful_policy_IFSACS_2_def)
apply(simp add: list_graph_to_graph_def inefficient_list_intersect_correct)
apply(thin_tac "\<T> = ?x")
apply(frule(1) filter_compliant_stateful_ACS_complies)
apply(frule(1) filter_IFS_no_violations_complies)
apply(thin_tac "?a")
apply(thin_tac "?a")
apply(thin_tac "?a")
apply(thin_tac "?a")
apply(simp)
by (metis list_graph_to_graph_def)
end
|
/***********************************************************************
* mexeigPartial.c : C mex file for the routine DSYEVX in LAPACK
*
* mex -O -largeArrayDims -lmwlapack -lmwblas mexeigPartial.c
*
* [V,D,nv] = mexeigPartial(A, vl, vu, options);
*
* options.jobz = 1 (default), compute both eigenvectors and eigenvalues;
* = 2, compute only eigenvalues.
* options.range = 1 (default), compute all;
* = 2, compute eigenvalues between [vl, vu].
* = 3, compute vl-th to vu-th eigenvalues.
* options.abstol = tolerance (default = 1e-8)
***********************************************************************/
#include <math.h>
#include <mex.h>
#include <matrix.h>
#include <blas.h>
#include <lapack.h>
#include <string.h> /* needed for memcpy() */
#if !defined(_WIN32)
#define dsyevd dsyevd_
#define dsyevx dsyevx_
#define dgesdd dgesdd_
#endif
/**********************************************************
*
***********************************************************/
void mexFunction(
int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{ double *A, *AA, *nV, *V, *D, VL, VU, abstol, *work, *work2, *tmp;
ptrdiff_t m, n, IL, IU, lwork, *iwork, *ifail, info, options;
char *jobz="V";
char *uplo="U";
char *range="A";
/* CHECK FOR PROPER NUMBER OF ARGUMENTS */
if (nrhs > 4){
mexErrMsgTxt("mexeigPartial: requires at most 4 input arguments."); }
if (nlhs > 3){
mexErrMsgTxt("mexeigPartial: requires at most 3 output argument."); }
/* CHECK THE DIMENSIONS */
m = mxGetM(prhs[0]);
n = mxGetN(prhs[0]);
if (m != n) {
mexErrMsgTxt("mexeigPartial: matrix must be square."); }
if (mxIsSparse(prhs[0])) {
mexErrMsgTxt("mexeigPartial: sparse matrix not allowed."); }
A = mxGetPr(prhs[0]);
options = 1;
abstol = 1e-8;
/*Get fields from options */
tmp = mxGetPr(mxGetField(prhs[3], 0, "abstol")); abstol = *tmp;
tmp = mxGetPr(mxGetField(prhs[3], 0, "jobz")); options = (ptrdiff_t)*tmp;
tmp = mxGetPr(mxGetField(prhs[3], 0, "range")); options = (ptrdiff_t)*tmp;
if (options==1) {
range="A"; }
else if (options==2) {
range="V"; VL = *mxGetPr(prhs[1]); VU = *mxGetPr(prhs[2]); }
else if (options == 3) {
range="I";
IL = (ptrdiff_t)*mxGetPr(prhs[1]);
IU = (ptrdiff_t)*mxGetPr(prhs[2]);
}
/***** create return argument *****/
plhs[0] = mxCreateDoubleMatrix(n,n,mxREAL);
V = mxGetPr(plhs[0]);
plhs[1] = mxCreateDoubleMatrix(n,1,mxREAL);
D = mxGetPr(plhs[1]);
plhs[2] = mxCreateDoubleMatrix(1,1,mxREAL);
nV = mxGetPr(plhs[2]);
/***** Do the computations in a subroutine *****/
lwork = 8*n;
work = mxCalloc(lwork,sizeof(double));
iwork = mxCalloc(5*n, sizeof(ptrdiff_t));
ifail = mxCalloc(n, sizeof(ptrdiff_t));
AA = mxCalloc(n*n,sizeof(double));
memcpy(AA,mxGetPr(prhs[0]),(n*n)*sizeof(double));
dsyevx(jobz, range, uplo, &n, AA, &n, &VL, &VU, &IL, &IU,
&abstol, &m, D, V, &n, work, &lwork, iwork, ifail, &info);
*nV = m;
return;
}
/**********************************************************/
|
\section{Two body problem}
The problem of motion of bodies relative to each other has long been studied. However it's only until recently that researchers have been able to use the full power of computers to research on these problems. In this project we will leverage on the research that has been done on n-body problems specifically the two-body problems. The two body problem is able to be solved exactly reproducing the Kepler laws.
Johannes Kepler 1571 to 1630 was able to formulate laws that described the data gathered by Tycho Brahe. These laws were largely empirical. Isaac newton who came after him was able to formulate the laws that govern motion. Joseph lagrange was able to make these equations more detailed. For this project we will focus on the two body problem. The two body problem states that given two bodies with velocities and masses at a given time,t, seperated by a distance, r, find consecutive values for the v and r henceforth.
|
\chapter{Implementation} \label{IMPLEMENTATION}
\section{Firebase Configuration} \label{FIREBASECONFIGURATION}
\subsection{Firestore Structure} \label{DATAIMPLEMENTATION}
Each of the 4 data classes in this application is represented by a JSON file in the file structure of the Firestore. The 4 data classes are represented in the application by either a Kotlin Data Class \cite{KOTLINDATACLASS}, or a data class like a class with some additional methods for Parcelable functionality. The files are set up in a certain structure for the data to be retrievable using these classes. The idea is that each of the fields in the JSON files is represented by 1 variable in the data classes if the JSON file has a string, then a string with the same name as the JSON variables key is used in the data class. For example, a JSON file that looks like this:
\begin{verbatim}
{
"name": "MyName"
"age": "MyAge"
"location": "Location"
}
\end{verbatim}
Is accessible as a data object in Kotlin formulated like this:
\begin{verbatim}
data class user(
var name: String? = "",
var age: String? = "",
var location: String? = ""
)
\end{verbatim}
Data class examples can be found in the Appendix Section \ref{DATACLASSEXAMPLE}, while only one is strictly a Data Class this is due to the limitations; however, the outwards API of the classes shown the in the Appendix Section \ref{DATACLASSEXAMPLE} are the same when interacting with them as a Data Class.
The Firestore consist of collections, each collection consists of documents, each document can have a field which contains a collection so that the Firestore can hold nested file structures. The top-level collections for this app are:
\begin{itemize}
\item adoptionProcesses
\item cats
\item feedback
\item users
\end{itemize}
\subsubsection{AdoptionProcesses Collection}
The documents in the adoptionProcesses collection are named after the UID of the user that is adopting the cats. Each document then has a collection inside of it called adoptionProcesses. The nested field collection of adoptionProcessed contains documents named the catId of the cat the user wants to adopt, each document in this nested collection contains DocumentReferences (A Firestore data type) that point to the user's document in the user's collection (Section \ref{USERSCOLLECTION}) and the cat's document in the cat's collection (Section \ref{CATSCOLLECTION}), and the status of the current adoption. The status of the adoption is in the form of a key-value pair map object, which contains 5 fields, accepted (Boolean), rejected (Boolean), pending (Boolean), pendingReason (String), and rejectedReason (String). To see what it would look like, look at Figure \ref{fig:adoptionProcessFileStructure} which describes the adoptionProcesses collection using UML Class diagram as a basis for the JSON files.
\begin{figure} [htbp!]
\centering
\includegraphics[width=\textwidth]{Images/adoptionProcesses file relations.png}
\caption{Adoption Processes collection structure}
\label{fig:adoptionProcessFileStructure}
\end{figure}
\subsubsection{Cats Collection} \label{CATSCOLLECTION}
The documents in the cat's collection are named after the Cat ID by concatenating the word cat with the id. This is to avoid it just being numbers and being harder to read. The contents of the documents are all of the information the application requires for the cat information displays, and all information is displayed in the app that is stored in these documents. An example of the file structure is given in the form of a UML class diagram representing the JSON files in Figure \ref{fig:catsCollectionFileStructure}
\begin{figure} [htbp!]
\centering
\includegraphics[width=\textwidth]{Images/CatsCollectionFileStructure.png}
\caption{Cats Collection File Structure}
\label{fig:catsCollectionFileStructure}
\end{figure}
\subsubsection{Feedback Collection}
The feedback collection is a collection of the feedback given by users from the app. The feedback documents are small; they contain the date, developerReplyRequested, the feedback, and a reference to the user's document. The feedback document names are a concatenation of their user Ids and the date-time. An example of feedback collection JSON structure is shown in Figure \ref{fig:feedbackCollectionFileStructure} as a UML Class diagram.
\begin{figure} [htbp!]
\centering
\includegraphics[width=\textwidth]{Images/FeedbackCollectionFileStructure.png}
\caption{Feedback collection file structure}
\label{fig:feedbackCollectionFileStructure}
\end{figure}
\subsubsection{Users Collection} \label{USERSCOLLECTION}
The user's collection is the collection of user data, and each document has the name of the user's ID; the user ID is gained from the Firebase Authentication implementation (Section \ref{FIREBASEAUTHENTICATION}). The user documents contain the user's address, county, favouritedCats, mobileNumber, name, and postCode. An example of the users collection JSON file structure is found in Figure \ref{fig:usersCollectionFileStructure} as a UML Class diagram.
\begin{figure} [htbp!]
\centering
\includegraphics{Images/UserCollectionFileStructure.png}
\caption{Users collection file structure}
\label{fig:usersCollectionFileStructure}
\end{figure}
\subsection{Security Rules}
The rules have been implemented in a way that restricts access to the database, for everything to some degree. A user must provide an authenticated user id for read or write operations in the user's collection. It is not possible to write to the cat collection, but anyone using a correctly connected application can read cat data. adoptionProcesses data can only be written or read by a correctly authenticated user liked user data. Feedback is unreadable by applications but writable by technically any authenticated application, but the app requires a login.
When a collection is un-readable, or un-writeable by an application connected to the Firestore, this does not include the Firebase console, which allows administrator access to change any values, and read anything.
Security rules for Firebase are easy to update and propagate within 5 minutes across all of the Firebase servers. It provides heavy adaptability at a moments notice so temporary changes could be done if needed like when the Server Scripts are run.
The security rules in use by the Firestore are as follows:
\begin{verbatim}
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth.uid == userId
}
match /cats/{documents=*}{
allow read: if true;
allow write: if false;
}
match /adoptionProcesses/{userId}/adoptionProcesses/
{documents=**}{
allow read, write: if request.auth.uid == userId
}
match /feedback/{documents=**}{
allow write: if true
allow read: if false
}
}
}
\end{verbatim}
\subsection{Server Scripts} \label{SERVERSCRIPTS}
The Server Scripts were created when I need to generate a lot of data fast, and I used them with some made-up data in JSON files to create 90 new cat objects. The script for creation was made with the intention to be scale-able, for example, if there was a need for 1 or 1000 extra cats that could be done, the script might get repetitive due to the lack of extra data, but if extra data were added to the JSON files, then it would use it accordingly.
The second script that was made to interact with the server is the remove a certain number of cats script. After the first version of my creates a cat script was created, I realised that 90 cats had been generated incorrectly. The script deletes the cats between 2 numbers input into it in this scenario 10 and 90 was required.
Both scripts required API keys for the Firestore, and these are not available to the public as they are privately linked to my Firestore account. The code in Appendix Sections \ref{CREATECATSCRIPT} and \ref{REMOVECATSSCRIPT}.
Both scripts also use the Cat Class (Appendix Section \ref{CATCLASSSCRIPT}). It makes sense to separate shared code between the scripts, to reduce code duplication, increase stability, and maintainability.
\section{Technologies Used}
This section will talk about how the technologies that have been chosen are implemented in this project. The technologies in question are, Firebase Authentication, Firebase Firestore, Firebase File Storage, Firebase UI Integration Tests, Picasso, Kotlin, Material Design, Android X
\subsection{Firebase}
Google Firebase is a set of tools for application developers to integrate into their applications, that are easy to plug in and can quickly implement significant functionality with little effort. While, some features of Firebase make a lot of sense to be implemented on an application going to an audience, since this application is not destined for that path I did not add them, these features include Analytics and Cloud Messaging. This subsection talks about the libraries from Google Firebase that were used and go into detail about their implementation.
\subsubsection{Authentication and Authentication UI} \label{FIREBASEAUTHENTICATION}
Firebase Authentication is crucial to the functionality of the application; a large portion of the app is locked behind a login screen. Adoption, Feedback, My Account, and Cat Saving all require correct authentication for all or partial functionality. Authentication can be completed using many 3rd party authentication methods, including Google, Facebook, Twitter, Apple ID and more \cite{FIREBASEAUTHTYPES}. The application only allows for the use of google sign in, which is incredibly easy on Android and most users will have this, and an application-specific email and password. The mentality behind only using the two authentication methods is because it keeps things simple, it reduces chances for users to become confused as to what they signed in with, and it was the two easiest methods to implement.
Firebase Authentication has a support library called Firebase Authentication UI which allows an application to drop in an activity which handles authentication. To do this you "build" the methods that you want to use and pass it to the Activity, when the Activity returns it will return either success or not, with success you are logged in. Firebase Authentication UI is a very nice and easy to use implementation of a login screen, with minimal implementation requirement.
Firebase Authentication UI launch code for Google and Email/password logins:
\begin{verbatim}
// Choose authentication providers
val providers = arrayListOf(
AuthUI.IdpConfig.EmailBuilder().build(),
AuthUI.IdpConfig.GoogleBuilder().build()
)
// Create and launch sign-in intent
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.setIsSmartLockEnabled(false, true)
.build(),
RC_SIGN_IN
)
\end{verbatim}
It is possible to check the Activity results another way, by calling checking if \newline "FirebaseAuth.getInstance().currentUser" returns a FirebaseUser object, if so there was a successful login for this application, and it has yet to be logged out (This includes if you have just started the application and had previously been logged in), or null if a login has not been performed or the user logged out.
\subsubsection{Firestore}
Firebase Firestore is google's latest attempt at providing real-time database support for application development, and it replaced their earlier attempt called Realtime Database, it has simplified security rules and more straightforward implementation on the firebase console. Firestore represents a scalable database implementation in the form of a NoSQL file structure utilising JSON files. Firestore can be interacted with in many ways in multiple languages including, JavaScript, Swift, Objective-C, Java, Java Android, Kotlin Android, Python, C++, Node-JS, GO, PHP, Unity, C\#, and Ruby.
Most of the Firestore configuration and implementation is discussed in section \ref{FIREBASECONFIGURATION}.
\subsubsection{File Storage}
Google Firebase Storage is a cheap, scalable, secure, and easy to use storage medium in the cloud. In the aspect of this project, it is used to provide storage for cat images. The cat images are easily accessible where anyone can read them from a given URL, these URLs are used in the Firestore (Section \ref{FIREBASECONFIGURATION}) cats collection.
The security rules are much more basic, this time it is true for all read, and false of all write on all paths in the storage, as it is only storing the cat pictures:
\begin{verbatim}
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read: if true;
allow write: if false;
}
}
}
\end{verbatim}
\subsubsection{UI Integration Tests}
Google Firebase offers UI Instrumentation tests, which have been used in this project as Integration tests. The project does not make direct use of the Firebase functionality but rather indirectly via Bitrise. The way these tests work is via compiling a test APK using the Android Instrumentation tests and sending it to Firebase to be run on a matrix of testing devices, and the APK can then be run on many types of devices and all Android API levels.
\subsubsection{Firestore Recycler Adapter}
The FirestoreRecyclerAdapter is used with the RecyclerAdapter, it works using a Firestore query. It will asynchronously populate the RecyclerView and bind the data retrieved by the query to the RecyclerView.ItemHolder. It has been used for all adoption statuses, cat finder tools, and saved cat scrollables. An example of the adapter being setup and given to a RecyclerView is as follows, the adapter needs a FirestoreRecyclerOptions object which first is constructed using the query:
\begin{verbatim}
val query = FirebaseFirestore.getInstance()
.collection("adoptionProcesses")
.document(DataService.INSTANCE.user!!.uid)
.collection("adoptionProcesses")
.limit(10)
val options = FirestoreRecyclerOptions
.Builder<AdoptionProcess>()
.setQuery(query, AdoptionProcess::class.java)
.setLifecycleOwner(this)
.build()
val adapter =
object : FirestoreRecyclerAdapter<
AdoptionProcess, AdoptionStatusCard>(options) {
override fun onCreateViewHolder
(parent: ViewGroup, viewType: Int):
AdoptionStatusCard {
val localView = LayoutInflater.from(parent.context)
.inflate(R.layout.adoption_status_card,
parent,
false)
return AdoptionStatusCard(localView)
}
override fun onBindViewHolder(
holder: AdoptionStatusCard,
position: Int,
model: AdoptionProcess
) {
holder.bind(model)
}
}
\end{verbatim}
\subsubsection{Filter Functionality using Queries}
A key part of the function of the application's cat finder fragment is the implementation of the Firestore query. You can use a Firestore query to filter only specific types of data. This was used to great effect for the cat finder filter functionality, and it boils down to checking if the user wants to filter certain aspects, it is also possible to sort the list in a specific way in reverse orders based on how a user wants. The filter and sort functionality are supported directly by the queries. The cat finder implementation for the query generation is available in Appendix Section \ref{FIRESTOREQUERYIMPLEMENTATION}.
\subsubsection{Adding Packaged APK UID to Firestore}
In the firebase console, you need to add the SHA Certificate fingerprint, that relates to the bundled APK so that it can send requests to Google Firebase, in order to achieved this, inside Android Studio, you need to run
\begin{verbatim}
keytool -exportcert -list -v -alias <your-key-name> /
-keystore <path-to-production-keystore>
\end{verbatim}
According to the Firebase Documentation \cite{CLIENTAUTH}, you must add the SHA-1 or SHA256 key that is printed to the terminal to your firebase project settings for the application to interact correctly, this includes the debug, and release versions of the application made on each computer used to compile it unless the key is transferred between each.
\subsection{Picasso}
Picasso is a Library for Android, to load pictures into an ImageView from a URL, for example over the internet or on the local file system. It is straightforward to use, one line: Picasso.get().load("www.imageUrl.com/image").into(imageView). Picasso asynchronously downloads and inserts the image into the URL, it will cache the images for some time, meaning loading is much faster next time. Every image in the application that is not a Material Design icon is loaded using Picasso. Picasso allows other features such as transformation, use of placeholders, and Debug indicators.
\subsection{Kotlin}
Kotlin is a development language that works interchangeably with Java on the Java Virtual Machine. Its main features involve providing concise and easier development in a Java environment. It is the sole language in use for Android development in this project. Kotlin changes the classes and adds subsets such as the Data Classes which are used in this application.
Throughout development, I made heavy usage of the lack of requirement for strong typing for local variables and instance variables that can have their type discerned before compile time. Kotlin boasts heavy co-routine support, and I was unable to utilise this in my project, as most asynchronous parts of the project are handled by 3rd-party libraries, as there is no use to reinvent the wheel.
There are a few features of Kotlin that became very valuable when producing easy and concise code, these are Safe Call and Elvis Call operators. These were used to great effect in the following code excerpt:
\begin{verbatim}
val user = document.toObject<User>()
name.setText(user?.name ?: this.user!!.displayName)
addressLineOne.setText(user?.addressLineOne ?: "")
addressLineTwo.setText(user?.addressLineTwo ?: "")
addressLineThree.setText(user?.addressLineThree ?: "")
postCode.setText(user?.postCode ?: "")
county.setText(user?.county ?: "")
phone.setText(user?.mobileNumber ?: this.user!!.phoneNumber)
\end{verbatim}
\subsection{Material Design}
While most of Material Design's point, is the guidelines, to assist with the implementation of these guidelines, many of the functionalities suggested have a respective implementation for Android. While some of the guidelines have no implementations, and this application utilises the Material Design implementation of the \gls{Bottom Navigation Bar}, \gls{Card}, \gls{Up Button}, Switches, Text fields, Button, and Navigation Drawer. Material design components are implemented throughout my application, and I believe that they all improve the functionality, look, and general feel of the application.
\subsection{AndroidX and Jetpack}
AndroidX is the successor to AndroidCompat as a library, and it aims to support modern features in legacy APIs. Even though features may be in the Android Standard now, that doesn't mean they were previously, and to support these features in earlier APIs we use AndroidX. AndroidX is used so commonly throughout this application that the list would be too long to put in, but some features include ConstraintLayouts, GridLayouts, and the NestedScrollViews.
Android Jetpack is a suite of libraries and tools that are aimed at helping developers write quick and high development applications. Jetpack aims to improve the way developers implement best practices. Android Jetpack is in the namespace of AndroidX; therefore, as a part of AndroidX, Jetpack is discussed as part of the same section.
\subsubsection{NavigationUI} \label{NAVUI}
NavigationUI is a relatively new methodology for navigation implementation inside of an Android Application. It utilises a Navigation Graph; the one used in the project is available in Appendix Section \ref{NAVIGATIONGRAPH}. The Navigation graph shows the hierarchy of the application; however since the navigation through this application is relatively simple, it requires only a flat hierarchy of navigation, with HomeFragment being the base of all navigation.
NavigationUI offers the ability to add transition animations, and this application does not currently use them. The reason behind not using them is due to the lack of time, and the idea was to get navigation working before polishing the application later. NavigationUI also handles the animations and up to stack navigation in the app bar between Navigation Draw. NavigationUI is usable throughout the application by calling "findNavController().navigate(fragmentId)".
When you navigate somewhere, it adds this destination to the navigation stack, and when the \gls{Up Button} is pressed then it navigates up the navigation stack to where you previously were in the program.
\subsubsection{Legacy Support for UI Elements} \label{LEGACYUI}
Grid Layout is a layout that provides an easy to use the grid, and it often is not clear that a grid is used because these items can easily. It's a feature of AndroidX and the current modern Android API, but older versions of the Android SDK do not work with the Grid Layout as it was not implemented, in the case of this application 21-23 did not support Grid Layout, so the AndroidX version was used instead.
Constraint Layout is a performance-friendly easy to use layout for simple and slightly more advanced layouts. It utilises constraints to reduce time spent determining layout sizes dynamically by the CPU, each element or component is placed within relation to another element or the parent using constraints based on their current positions, working from the top of the file downwards, Constraint Layouts are used throughout the project for simple screens that can easily be made as a Constraint Layout, for example, the settings, home, and adoption info view fragment all use the Constraint Layout.
\section{Notable Bugs}
In this section, the notable bugs are discussed as they have significantly impacted development or extra time was needed to source the problem looking at older APIs or discovering the issues, especially with the continuous integration.
\subsection{Gridlayout - AndroidX}
As discussed in section \ref{LEGACYUI}, the Grid Layout is not supported in earlier versions of Android. Some functionality used in the My Account screen and user information update screens, are not available in Android 21, 22 or 23. This was evident from the Continuous Integration UI tests, but it was hard to discover precisely what the issue was as it was stating Grid Layout did not inflate as it couldn't be found correctly. The functionality required was the "layout\_columnWeight" and "layout\_rowWeight" which is not supported on these lower APIs.
\subsection{writeBoolean and readBoolean pre API 29}
Parcelable is an interface implementation that allows a developer to implement it, and it is used quite extensively by the Data Classes in the application (Appendix Section \ref{DATACLASSEXAMPLE}). The data classes required these to be passed between fragments using the NavigationUI navigate methods (Section \ref{NAVUI}). Early on these methods were implemented using a rather new feature writeBoolean and readBoolean, in the UI Integration tests that were running every single device one test ran on, failed except API 29, this was because these two methods had not been implemented until very recently and were not available in a legacy package, so some alternate implementation had to be used.
The alternate implementation was translating a Boolean into a String and back. These are my implementations to facilitate this:
\begin{verbatim}
fun boolToString(bool: Boolean) : String{
return if (bool) "true" else "false"
}
fun stringToBool(string: String) : Boolean {
// If not true then assumed false
return string == "true"
}
\end{verbatim}
\subsection{Large Image Files Over the Internet}
When the Cat \gls{Card}s were first added to the cat finder tool, it was noticed there was extreme lag, I was concerned this could have been caused by the database being slow or the FirebaseRecyclerAdapter having inefficiencies. However, it ended up being caused by the loading of images; this was because these images were rather large in resolution but being crammed into small ImageViews and processing and download times were causing stuttering and lag. The fix for this was to format and compress the images from their current state without diminishing their quality. I utilised a program called jpegoptim \cite{JPEGOPTIM}, to perform compression, optimisations, and resizing to drop the size of the image from multiple megabytes to below 50 kilobytes, yet still keeping a good enough quality for display on mobile phones.
\subsection{Infinitely Adding to the Navigation Stack in Settings}
When navigating to the settings screen it was possible to navigate to that screen infinitely from inside of the settings screen, this means that you could in theory infinitely navigate to the settings screen increasing the size of the navigation stack. Whilst not strictly a major problem, it did make it hard to use the \gls{Up Button} to navigate up the navigation stack. The settings navigation button was added to the application's app bar, which means that it is present on every screen, it is possible to remove but required more work to fix correctly than was left in the project. The way this was fixed was by disallowing navigation to the settings destination if already at the settings destination. This code is given in the example:
\begin{verbatim}
when (item.itemId) {
R.id.actionSettingsButton -> {
if (navController.currentDestination?.id
!= R.id.settingsFragment){
navController.navigate(R.id.settingsFragment)
true
}
else
super.onOptionsItemSelected(item)
}
else -> {
super.onOptionsItemSelected(item)
}
}
\end{verbatim}
|
"""Discontinued - generate optics in POV ray tracer using Vapory library.
In mid-2019 I experimented with using POV-Ray to generate pretty renderings of optical setups. I started off using
https://github.com/Zulko/vapory, but realised it was too limited and switched to generating POV-Ray files directly using
the pov module.
"""
import numpy as np
import vapory as vp
from . import functions, trains
def make_circular_spherical_lens(roc1, roc2, thickness, radius, n, *args):
sag1 = functions.calc_sphere_sag(roc1, radius)
sag2 = functions.calc_sphere_sag(roc2, radius)
sections = []
surface1 = vp.Sphere([0, 0, roc1], abs(roc1))
if roc1 > 0:
sections.append(vp.Intersection(surface1, vp.Cylinder([0, 0, 0], [0, 0, sag1], radius)))
elif roc1 < 0:
sections.append(vp.Difference(vp.Cylinder([0, 0, sag1], [0, 0, 0], radius), surface1))
sections.append(vp.Cylinder([0, 0, max(sag1, 0)], [0, 0, thickness + min(sag2, 0)], radius))
surface2 = vp.Sphere([0, 0, thickness + roc2], abs(roc2))
if roc2 < 0:
sections.append(vp.Intersection(surface2, vp.Cylinder([0, 0, thickness + sag2], [0, 0, thickness], radius)))
elif roc2 > 0:
sections.append(vp.Difference(vp.Cylinder([0, 0, thickness], [0, 0, thickness+sag2], radius), surface2))
lens = vp.Union(*sections, vp.Texture('T_Glass3'), vp.Interior('ior', n), *args)
return lens
def make_square_spherical_lens(roc1: float, roc2: float, thickness: float, side_length: float, n: float, *args):
radius = side_length/2**0.5
sag1 = functions.calc_sphere_sag(roc1, radius)
sag2 = functions.calc_sphere_sag(roc2, radius)
hsl = side_length/2
sections = []
if np.isfinite(roc1):
surface1 = vp.Sphere([0, 0, roc1], abs(roc1))
if roc1 > 0:
sections.append(vp.Intersection(surface1, vp.Box([-hsl, -hsl, 0], [hsl, hsl, sag1])))
elif roc1 < 0:
sections.append(vp.Difference(vp.Box([-hsl, -hsl, sag1], [hsl, hsl, 0]), surface1))
sections.append(vp.Box([-hsl, -hsl, max(sag1, 0)], [hsl, hsl, thickness + min(sag2, 0)]))
surface2 = vp.Sphere([0, 0, thickness + roc2], abs(roc2))
if np.isfinite(roc2):
if roc2 < 0:
sections.append(vp.Intersection(surface2, vp.Box([-hsl, -hsl, thickness + sag2], [hsl, hsl, thickness])))
elif roc2 > 0:
sections.append(vp.Difference(vp.Box([-hsl, -hsl, thickness], [hsl, hsl, thickness+sag2]), surface2))
lens = vp.Union(*sections, vp.Texture('T_Glass2'), vp.Interior('ior', n), *args)# , *args) vp.Texture( vp.Pigment( 'color', [1,0,1] ))
return lens
def make_singlet(singlet: trains.Singlet, shape: str, lamb: float = None, *args):
if shape == 'square':
return make_square_spherical_lens(singlet.surfaces[0].roc, singlet.surfaces[1].roc, singlet.thickness, singlet.radius*2**0.5, singlet.n(lamb), *args)
def make_singlet_sequence(sequence: trains.SingletSequence, shape: str, lamb: float=None, *args):
z = sequence.spaces[0]
objects = []
for singlet, space in zip(sequence.singlets, sequence.spaces[1:]):
objects.append(make_singlet(singlet, shape, lamb, 'translate', [0, 0, z]))
z += space
return vp.Union(*objects, *args)
def make_train(train: trains.Train, shape: str, radii='equal', lamb: float=None, *args):
objs = []
z = train.spaces[0]
for i1, i2, thickness in zip(train.interfaces[:-1], train.interfaces[1:], train.spaces[1:]):
if radii == 'equal':
radius = i1.radius
assert i2.radius == radius
elif radii == 'max':
radius = max((i1.radius, i2.radius))
else:
radius = radii
if shape == 'square':
obj = make_square_spherical_lens(i1.roc, i2.roc, thickness, radius*2**0.5, i1.n2(lamb))
objs.append(obj)
z += thickness
return vp.Union(*objs, *args)
|
r=359.60
https://sandbox.dams.library.ucdavis.edu/fcrepo/rest/collection/sherry-lehmann/catalogs/d7wk5x/media/images/d7wk5x-020/svc:tesseract/full/full/359.60/default.jpg Accept:application/hocr+xml
|
(*
* Copyright 2014, NICTA
*
* This software may be distributed and modified according to the terms of
* the GNU General Public License version 2. Note that NO WARRANTY is provided.
* See "LICENSE_GPLv2.txt" for details.
*
* @TAG(NICTA_GPL)
*)
theory Example_Valid_State
imports
"Noninterference"
"../../lib/Distinct_Cmd"
begin
section {* Example *}
(* This example is a classic 'one way information flow'
example, where information is allowed to flow from Low to High,
but not the reverse. We consider a typical scenario where
shared memory and an notification for notifications are used to
implement a ring-buffer. We consider the NTFN to be in the domain of High,
and the shared memory to be in the domain of Low. *)
(* basic machine-level declarations that need to happen outside the locale *)
consts s0_context :: user_context
(* define the irqs to come regularly every 10 *)
axiomatization where
irq_oracle_def: "ARM.irq_oracle \<equiv> \<lambda>pos. if pos mod 10 = 0 then 10 else 0"
context begin interpretation Arch . (*FIXME: arch_split*)
subsection {* We show that the authority graph does not let
information flow from High to Low *}
datatype auth_graph_label = High | Low | IRQ0
abbreviation partition_label where
"partition_label x \<equiv> OrdinaryLabel x"
definition Sys1AuthGraph :: "(auth_graph_label subject_label) auth_graph" where
"Sys1AuthGraph \<equiv>
{ (partition_label High,Read,partition_label Low),
(partition_label Low,Notify,partition_label High),
(partition_label Low,Reset,partition_label High),
(SilcLabel,Notify,partition_label High),
(SilcLabel,Reset,partition_label High)
} \<union> {(x, a, y). x = y}"
lemma subjectReads_Low: "subjectReads Sys1AuthGraph (partition_label Low) = {partition_label Low}"
apply(rule equalityI)
apply(rule subsetI)
apply(erule subjectReads.induct, (fastforce simp: Sys1AuthGraph_def)+)
apply (auto intro: reads_lrefl reads_read)
done
lemma Low_in_subjectReads_High:
"partition_label Low \<in> subjectReads Sys1AuthGraph (partition_label High)"
apply (simp add: Sys1AuthGraph_def reads_read)
done
lemma subjectReads_High: "subjectReads Sys1AuthGraph (partition_label High) = {partition_label High,partition_label Low}"
apply(rule equalityI)
apply(rule subsetI)
apply(erule subjectReads.induct, (fastforce simp: Sys1AuthGraph_def)+)
apply(auto intro: reads_lrefl Low_in_subjectReads_High)
done
lemma subjectReads_IRQ0: "subjectReads Sys1AuthGraph (partition_label IRQ0) = {partition_label IRQ0}"
apply(rule equalityI)
apply(rule subsetI)
apply(erule subjectReads.induct, (fastforce simp: Sys1AuthGraph_def)+)
apply(auto intro: reads_lrefl Low_in_subjectReads_High)
done
lemma High_in_subjectAffects_Low:
"partition_label High \<in> subjectAffects Sys1AuthGraph (partition_label Low)"
apply(rule affects_ep)
apply (simp add: Sys1AuthGraph_def)
apply (rule disjI1, simp+)
done
lemma subjectAffects_Low: "subjectAffects Sys1AuthGraph (partition_label Low) = {partition_label Low, partition_label High}"
apply(rule equalityI)
apply(rule subsetI)
apply(erule subjectAffects.induct, (fastforce simp: Sys1AuthGraph_def)+)
apply(auto intro: affects_lrefl High_in_subjectAffects_Low)
done
lemma subjectAffects_High: "subjectAffects Sys1AuthGraph (partition_label High) = {partition_label High}"
apply(rule equalityI)
apply(rule subsetI)
apply(erule subjectAffects.induct, (fastforce simp: Sys1AuthGraph_def)+)
apply(auto intro: affects_lrefl)
done
lemma subjectAffects_IRQ0: "subjectAffects Sys1AuthGraph (partition_label IRQ0) = {partition_label IRQ0}"
apply(rule equalityI)
apply(rule subsetI)
apply(erule subjectAffects.induct, (fastforce simp: Sys1AuthGraph_def)+)
apply(auto intro: affects_lrefl)
done
lemmas subjectReads = subjectReads_High subjectReads_Low subjectReads_IRQ0
lemma partsSubjectAffects_Low: "partsSubjectAffects Sys1AuthGraph Low = {Partition Low, Partition High}"
apply(auto simp: partsSubjectAffects_def image_def label_can_affect_partition_def subjectReads subjectAffects_Low | case_tac xa, rename_tac xa)+
done
lemma partsSubjectAffects_High: "partsSubjectAffects Sys1AuthGraph High = {Partition High}"
apply(auto simp: partsSubjectAffects_def image_def label_can_affect_partition_def subjectReads subjectAffects_High | rename_tac xa, case_tac xa)+
done
lemma partsSubjectAffects_IRQ0: "partsSubjectAffects Sys1AuthGraph IRQ0 = {Partition IRQ0}"
apply(auto simp: partsSubjectAffects_def image_def label_can_affect_partition_def subjectReads subjectAffects_IRQ0 | rename_tac xa, case_tac xa)+
done
lemmas partsSubjectAffects =
partsSubjectAffects_High partsSubjectAffects_Low partsSubjectAffects_IRQ0
definition example_policy where
"example_policy \<equiv> {(PSched, d)|d. True} \<union>
{(d,e). d = e} \<union>
{(Partition Low, Partition High)}"
lemma "policyFlows Sys1AuthGraph = example_policy"
apply(rule equalityI)
apply(rule subsetI)
apply(clarsimp simp: example_policy_def)
apply(erule policyFlows.cases)
apply(case_tac l, auto simp: partsSubjectAffects)[1]
apply assumption
apply(rule subsetI)
apply(clarsimp simp: example_policy_def)
apply(elim disjE)
apply(fastforce simp: partsSubjectAffects intro: policy_affects)
apply(fastforce intro: policy_scheduler)
apply(fastforce intro: policyFlows_refl refl_onD)
done
subsection {* We show there exists a valid initial state associated to the
above authority graph *}
text {*
This example (modified from ../access-control/ExampleSystem) is a system Sys1 made
of 2 main components Low and High, connected through an notification NTFN.
Both Low and High contains:
. one TCB
. one vspace made up of one page directory
. each pd contains a single page table, with access to a shared page in memory
Low can read/write to this page, High can only read
. one cspace made up of one cnode
. each cspace contains 4 caps:
one to the tcb
one to the cnode itself
one to the vspace
one to the ntfn
Low can send to the ntfn while High can receive from it.
Attempt to ASCII art:
-------- ---- ---- --------
| | | | | | | |
V | | V S R | V | V
Low_tcb(3079)-->Low_cnode(6)--->ntfn(9)<---High_cnode(7)<--High_tcb(3080)
| | | |
V | | V
Low_pd(3063)<----- -------> High_pd(3065)
| |
V R/W R V
Low_pt(3072)---------------->shared_page<-----------------High_pt(3077)
(the references are derived from the dump of the SAC system)
The aim is to be able to prove
valid_initial_state s0_internal Sys1PAS timer_irq utf
where Sys1PAS is the label graph defining the AC policy for Sys1 using
the authority graph defined above and s0 is the state of Sys1 described above.
*}
subsubsection {* Defining the State *}
definition "ntfn_ptr \<equiv> kernel_base + 0x10"
definition "Low_tcb_ptr \<equiv> kernel_base + 0x200"
definition "High_tcb_ptr = kernel_base + 0x400"
definition "idle_tcb_ptr = kernel_base + 0x1000"
definition "Low_pt_ptr = kernel_base + 0x800"
definition "High_pt_ptr = kernel_base + 0xC00"
(* init_globals_frame \<equiv> {kernel_base + 0x5000,... kernel_base + 0x5FFF} *)
definition "shared_page_ptr = kernel_base + 0x6000"
definition "Low_pd_ptr = kernel_base + 0x20000"
definition "High_pd_ptr = kernel_base + 0x24000"
definition "Low_cnode_ptr = kernel_base + 0x10000"
definition "High_cnode_ptr = kernel_base + 0x14000"
definition "Silc_cnode_ptr = kernel_base + 0x18000"
definition "irq_cnode_ptr = kernel_base + 0x1C000"
(* init_global_pd \<equiv> {kernel_base + 0x60000,... kernel_base + 0x603555} *)
definition "timer_irq \<equiv> 10" (* not sure exactly how this fits in *)
definition "Low_mcp \<equiv> 5 :: word8"
definition "Low_prio \<equiv> 5 :: word8"
definition "High_mcp \<equiv> 5 :: word8"
definition "High_prio \<equiv> 5 :: word8"
definition "Low_time_slice \<equiv> 0 :: nat"
definition "High_time_slice \<equiv> 5 :: nat"
definition "Low_domain \<equiv> 0 :: word8"
definition "High_domain \<equiv> 1 :: word8"
lemmas s0_ptr_defs =
Low_cnode_ptr_def High_cnode_ptr_def Silc_cnode_ptr_def ntfn_ptr_def irq_cnode_ptr_def
Low_pd_ptr_def High_pd_ptr_def Low_pt_ptr_def High_pt_ptr_def Low_tcb_ptr_def
High_tcb_ptr_def idle_tcb_ptr_def timer_irq_def Low_prio_def High_prio_def Low_time_slice_def
Low_domain_def High_domain_def init_irq_node_ptr_def init_globals_frame_def init_global_pd_def
kernel_base_def shared_page_ptr_def
(* Distinctness proof of kernel pointers. *)
distinct ptrs_distinct [simp]:
Low_tcb_ptr High_tcb_ptr idle_tcb_ptr
Low_pt_ptr High_pt_ptr
shared_page_ptr ntfn_ptr
Low_pd_ptr High_pd_ptr
Low_cnode_ptr High_cnode_ptr Silc_cnode_ptr irq_cnode_ptr
init_globals_frame init_global_pd
by (auto simp: s0_ptr_defs)
text {* We need to define the asids of each pd and pt to ensure that
the object is included in the right ASID-label *}
text {* Low's ASID *}
definition
Low_asid :: machine_word
where
"Low_asid \<equiv> 1<<asid_low_bits"
text {* High's ASID *}
definition
High_asid :: machine_word
where
"High_asid \<equiv> 2<<asid_low_bits"
lemma "asid_high_bits_of High_asid \<noteq> asid_high_bits_of Low_asid"
by (simp add: Low_asid_def asid_high_bits_of_def High_asid_def asid_low_bits_def)
text {* converting a nat to a bool list of size 10 - for the cnodes *}
definition
nat_to_bl :: "nat \<Rightarrow> nat \<Rightarrow> bool list option"
where
"nat_to_bl bits n \<equiv>
if n \<ge> 2^bits then
None
else
Some $ bin_to_bl bits (of_nat n)"
lemma nat_to_bl_id [simp]: "nat_to_bl (size (x :: (('a::len) word))) (unat x) = Some (to_bl x)"
apply (clarsimp simp: nat_to_bl_def to_bl_def)
apply (auto simp: uint_nat le_def word_size)
done
definition
the_nat_to_bl :: "nat \<Rightarrow> nat \<Rightarrow> bool list"
where
"the_nat_to_bl sz n \<equiv>
the (nat_to_bl sz (n mod 2^sz))"
abbreviation (input)
the_nat_to_bl_10 :: "nat \<Rightarrow> bool list"
where
"the_nat_to_bl_10 n \<equiv> the_nat_to_bl 10 n"
lemma len_the_nat_to_bl [simp]:
"length (the_nat_to_bl x y) = x"
apply (clarsimp simp: the_nat_to_bl_def nat_to_bl_def)
apply safe
apply (metis le_def mod_less_divisor nat_zero_less_power_iff zero_less_numeral)
apply (clarsimp simp: len_bin_to_bl_aux not_le)
done
lemma tcb_cnode_index_nat_to_bl [simp]:
"the_nat_to_bl_10 n \<noteq> tcb_cnode_index n"
by (clarsimp simp: tcb_cnode_index_def intro!: length_neq)
lemma mod_less_self [simp]:
"a \<le> b mod a \<longleftrightarrow> ((a :: nat) = 0)"
by (metis mod_less_divisor nat_neq_iff not_less not_less0)
lemma split_div_mod:
"a = (b::nat) \<longleftrightarrow> (a div k = b div k \<and> a mod k = b mod k)"
by (metis mult_div_mod_eq)
lemma nat_to_bl_eq:
assumes "a < 2 ^ n \<or> b < 2 ^ n"
shows "nat_to_bl n a = nat_to_bl n b \<longleftrightarrow> a = b"
using assms
apply -
apply (erule disjE_R)
apply (clarsimp simp: nat_to_bl_def)
apply (case_tac "a \<ge> 2 ^ n")
apply (clarsimp simp: nat_to_bl_def)
apply (clarsimp simp: not_le)
apply (induct n arbitrary: a b)
apply (clarsimp simp: nat_to_bl_def)
apply atomize
apply (clarsimp simp: nat_to_bl_def)
apply (erule_tac x="a div 2" in allE)
apply (erule_tac x="b div 2" in allE)
apply (erule impE)
apply (metis power_commutes td_gal_lt zero_less_numeral)
apply (clarsimp simp: bin_rest_def bin_last_def zdiv_int)
apply (rule iffI [rotated], clarsimp)
apply (subst (asm) (1 2 3 4) bin_to_bl_aux_alt)
apply (clarsimp simp: zmod_eq_dvd_iff)
apply (subst split_div_mod [where k=2])
apply clarsimp
apply (metis of_nat_numeral mod_2_not_eq_zero_eq_one_nat of_nat_1 of_nat_eq_iff zmod_int)
done
lemma nat_to_bl_mod_n_eq [simp]:
"nat_to_bl n a = nat_to_bl n b \<longleftrightarrow> ((a = b \<and> a < 2 ^ n) \<or> (a \<ge> 2 ^ n \<and> b \<ge> 2 ^ n))"
apply (rule iffI)
apply (clarsimp simp: not_le)
apply (subst (asm) nat_to_bl_eq, simp)
apply clarsimp
apply (erule disjE)
apply clarsimp
apply (clarsimp simp: nat_to_bl_def)
done
lemma the_the_eq:
"\<lbrakk> x \<noteq> None; y \<noteq> None \<rbrakk> \<Longrightarrow> (the x = the y) = (x = y)"
by auto
lemma the_nat_to_bl_eq [simp]:
"(the_nat_to_bl n a = the_nat_to_bl m b) \<longleftrightarrow> (n = m \<and> (a mod 2 ^ n = b mod 2 ^ n))"
apply (case_tac "n = m")
apply (clarsimp simp: the_nat_to_bl_def)
apply (subst the_the_eq)
apply (clarsimp simp: nat_to_bl_def)
apply (clarsimp simp: nat_to_bl_def)
apply simp
apply simp
apply (metis len_the_nat_to_bl)
done
lemma empty_cnode_eq_Some [simp]:
"(empty_cnode n x = Some y) = (length x = n \<and> y = NullCap)"
by (clarsimp simp: empty_cnode_def, metis)
lemma empty_cnode_eq_None [simp]:
"(empty_cnode n x = None) = (length x \<noteq> n)"
by (clarsimp simp: empty_cnode_def)
text {* Low's CSpace *}
definition
Low_caps :: cnode_contents
where
"Low_caps \<equiv>
(empty_cnode 10)
( (the_nat_to_bl_10 1)
\<mapsto> ThreadCap Low_tcb_ptr,
(the_nat_to_bl_10 2)
\<mapsto> CNodeCap Low_cnode_ptr 10 (the_nat_to_bl_10 2),
(the_nat_to_bl_10 3)
\<mapsto> ArchObjectCap (PageDirectoryCap Low_pd_ptr
(Some Low_asid)),
(the_nat_to_bl_10 318)
\<mapsto> NotificationCap ntfn_ptr 0 {AllowSend} )"
definition
Low_cnode :: kernel_object
where
"Low_cnode \<equiv> CNode 10 Low_caps"
lemma ran_empty_cnode [simp]:
"ran (empty_cnode C) = {NullCap}"
by (auto simp: empty_cnode_def ran_def Ex_list_of_length intro: set_eqI)
lemma empty_cnode_app [simp]:
"length x = n \<Longrightarrow> empty_cnode n x = Some NullCap"
by (auto simp: empty_cnode_def)
lemma in_ran_If [simp]:
"(x \<in> ran (\<lambda>n. if P n then A n else B n))
\<longleftrightarrow> (\<exists>n. P n \<and> A n = Some x) \<or> (\<exists>n. \<not> P n \<and> B n = Some x)"
by (auto simp: ran_def)
lemma Low_caps_ran:
"ran Low_caps = {ThreadCap Low_tcb_ptr,
CNodeCap Low_cnode_ptr 10 (the_nat_to_bl_10 2),
ArchObjectCap (PageDirectoryCap Low_pd_ptr
(Some Low_asid)),
NotificationCap ntfn_ptr 0 {AllowSend},
NullCap}"
apply (rule equalityI)
apply (clarsimp simp: Low_caps_def fun_upd_def empty_cnode_def split: if_split_asm)
apply (clarsimp simp: Low_caps_def fun_upd_def empty_cnode_def split: if_split_asm
cong: conj_cong)
apply (rule exI [where x="the_nat_to_bl_10 0"])
apply simp
done
text {* High's Cspace *}
definition
High_caps :: cnode_contents
where
"High_caps \<equiv>
(empty_cnode 10)
( (the_nat_to_bl_10 1)
\<mapsto> ThreadCap High_tcb_ptr,
(the_nat_to_bl_10 2)
\<mapsto> CNodeCap High_cnode_ptr 10 (the_nat_to_bl_10 2),
(the_nat_to_bl_10 3)
\<mapsto> ArchObjectCap (PageDirectoryCap High_pd_ptr
(Some High_asid)),
(the_nat_to_bl_10 318)
\<mapsto> NotificationCap ntfn_ptr 0 {AllowRecv}) "
definition
High_cnode :: kernel_object
where
"High_cnode \<equiv> CNode 10 High_caps"
lemma High_caps_ran:
"ran High_caps = {ThreadCap High_tcb_ptr,
CNodeCap High_cnode_ptr 10 (the_nat_to_bl_10 2),
ArchObjectCap (PageDirectoryCap High_pd_ptr
(Some High_asid)),
NotificationCap ntfn_ptr 0 {AllowRecv},
NullCap}"
apply (rule equalityI)
apply (clarsimp simp: High_caps_def ran_def empty_cnode_def split: if_split_asm)
apply (clarsimp simp: High_caps_def ran_def empty_cnode_def split: if_split_asm
cong: conj_cong)
apply (rule exI [where x="the_nat_to_bl_10 0"])
apply simp
done
text {* We need a copy of boundary crossing caps owned by SilcLabel.
The only such cap is Low's cap to the notification *}
definition
Silc_caps :: cnode_contents
where
"Silc_caps \<equiv>
(empty_cnode 10)
( (the_nat_to_bl_10 2)
\<mapsto> CNodeCap Silc_cnode_ptr 10 (the_nat_to_bl_10 2),
(the_nat_to_bl_10 318)
\<mapsto> NotificationCap ntfn_ptr 0 {AllowSend} )"
definition
Silc_cnode :: kernel_object
where
"Silc_cnode \<equiv> CNode 10 Silc_caps"
lemma Silc_caps_ran:
"ran Silc_caps = {CNodeCap Silc_cnode_ptr 10 (the_nat_to_bl_10 2),
NotificationCap ntfn_ptr 0 {AllowSend},
NullCap}"
apply (rule equalityI)
apply (clarsimp simp: Silc_caps_def ran_def empty_cnode_def)
apply (clarsimp simp: ran_def Silc_caps_def empty_cnode_def cong: conj_cong)
apply (rule_tac x="the_nat_to_bl_10 0" in exI)
apply simp
done
text {* notification between Low and High *}
definition
ntfn :: kernel_object
where
"ntfn \<equiv> Notification \<lparr>ntfn_obj = WaitingNtfn [High_tcb_ptr], ntfn_bound_tcb=None\<rparr>"
text {* Low's VSpace (PageDirectory)*}
definition
Low_pt' :: "word8 \<Rightarrow> pte "
where
"Low_pt' \<equiv> (\<lambda>_. InvalidPTE)
(0 := SmallPagePTE shared_page_ptr {} vm_read_write)"
definition
Low_pt :: kernel_object
where
"Low_pt \<equiv> ArchObj (PageTable Low_pt')"
definition
Low_pd' :: "12 word \<Rightarrow> pde "
where
"Low_pd' \<equiv>
global_pd
(0 := PageTablePDE
(addrFromPPtr Low_pt_ptr)
{}
undefined )"
(* used addrFromPPtr because proof gives me ptrFromAddr.. TODO: check
if it's right *)
definition
Low_pd :: kernel_object
where
"Low_pd \<equiv> ArchObj (PageDirectory Low_pd')"
text {* High's VSpace (PageDirectory)*}
definition
High_pt' :: "word8 \<Rightarrow> pte "
where
"High_pt' \<equiv>
(\<lambda>_. InvalidPTE)
(0 := SmallPagePTE shared_page_ptr {} vm_read_only)"
definition
High_pt :: kernel_object
where
"High_pt \<equiv> ArchObj (PageTable High_pt')"
definition
High_pd' :: "12 word \<Rightarrow> pde "
where
"High_pd' \<equiv>
global_pd
(0 := PageTablePDE
(addrFromPPtr High_pt_ptr)
{}
undefined )"
(* used addrFromPPtr because proof gives me ptrFromAddr.. TODO: check
if it's right *)
definition
High_pd :: kernel_object
where
"High_pd \<equiv> ArchObj (PageDirectory High_pd')"
text {* Low's tcb *}
definition
Low_tcb :: kernel_object
where
"Low_tcb \<equiv>
TCB \<lparr>
tcb_ctable = CNodeCap Low_cnode_ptr 10 (the_nat_to_bl_10 2),
tcb_vtable = ArchObjectCap
(PageDirectoryCap Low_pd_ptr (Some Low_asid)),
tcb_reply = ReplyCap Low_tcb_ptr True, (* master reply cap to itself *)
tcb_caller = NullCap,
tcb_ipcframe = NullCap,
tcb_state = Running,
tcb_fault_handler = replicate word_bits False,
tcb_ipc_buffer = 0,
tcb_fault = None,
tcb_bound_notification = None,
tcb_mcpriority = Low_mcp,
tcb_arch = \<lparr> tcb_context = undefined \<rparr>\<rparr>"
definition
Low_etcb :: etcb
where
"Low_etcb \<equiv> \<lparr>tcb_priority = Low_prio,
tcb_time_slice = Low_time_slice,
tcb_domain = Low_domain\<rparr>"
text {* High's tcb *}
definition
High_tcb :: kernel_object
where
"High_tcb \<equiv>
TCB \<lparr>
tcb_ctable = CNodeCap High_cnode_ptr 10 (the_nat_to_bl_10 2) ,
tcb_vtable = ArchObjectCap
(PageDirectoryCap High_pd_ptr (Some High_asid)),
tcb_reply = ReplyCap High_tcb_ptr True, (* master reply cap to itself *)
tcb_caller = NullCap,
tcb_ipcframe = NullCap,
tcb_state = BlockedOnNotification ntfn_ptr,
tcb_fault_handler = replicate word_bits False,
tcb_ipc_buffer = 0,
tcb_fault = None,
tcb_bound_notification = None,
tcb_mcpriority = High_mcp,
tcb_arch = \<lparr> tcb_context = undefined \<rparr>\<rparr>"
definition
High_etcb :: etcb
where
"High_etcb \<equiv> \<lparr>tcb_priority = High_prio,
tcb_time_slice = High_time_slice,
tcb_domain = High_domain\<rparr>"
text {* idle's tcb *}
definition
idle_tcb :: kernel_object
where
"idle_tcb \<equiv>
TCB \<lparr>
tcb_ctable = NullCap,
tcb_vtable = NullCap,
tcb_reply = NullCap,
tcb_caller = NullCap,
tcb_ipcframe = NullCap,
tcb_state = IdleThreadState,
tcb_fault_handler = replicate word_bits False,
tcb_ipc_buffer = 0,
tcb_fault = None,
tcb_bound_notification = None,
tcb_mcpriority = default_priority,
tcb_arch = \<lparr> tcb_context = empty_context \<rparr>\<rparr>"
definition
"irq_cnode \<equiv> CNode 0 (Map.empty([] \<mapsto> cap.NullCap))"
definition
kh0 :: kheap
where
"kh0 \<equiv> (\<lambda>x. if \<exists>irq::10 word. init_irq_node_ptr + (ucast irq << cte_level_bits) = x
then Some (CNode 0 (empty_cnode 0)) else None)
(Low_cnode_ptr \<mapsto> Low_cnode,
High_cnode_ptr \<mapsto> High_cnode,
Silc_cnode_ptr \<mapsto> Silc_cnode,
ntfn_ptr \<mapsto> ntfn,
irq_cnode_ptr \<mapsto> irq_cnode,
Low_pd_ptr \<mapsto> Low_pd,
High_pd_ptr \<mapsto> High_pd,
Low_pt_ptr \<mapsto> Low_pt,
High_pt_ptr \<mapsto> High_pt,
Low_tcb_ptr \<mapsto> Low_tcb,
High_tcb_ptr \<mapsto> High_tcb,
idle_tcb_ptr \<mapsto> idle_tcb,
init_globals_frame \<mapsto> ArchObj (DataPage False ARMSmallPage),
init_global_pd \<mapsto> ArchObj (PageDirectory global_pd))"
lemma irq_node_offs_min:
"init_irq_node_ptr \<le> init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits)"
apply (rule_tac sz=28 in machine_word_plus_mono_right_split)
apply (simp add: unat_word_ariths mask_def shiftl_t2n s0_ptr_defs cte_level_bits_def)
apply (cut_tac x=irq and 'a=32 in ucast_less)
apply simp
apply (simp add: word_less_nat_alt)
apply (simp add: word_bits_def)
done
lemma irq_node_offs_max:
"init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) < init_irq_node_ptr + 0x4000"
apply (simp add: s0_ptr_defs cte_level_bits_def shiftl_t2n)
apply (cut_tac x=irq and 'a=32 in ucast_less)
apply simp
apply (simp add: word_less_nat_alt unat_word_ariths)
done
definition irq_node_offs_range where
"irq_node_offs_range \<equiv> {x. init_irq_node_ptr \<le> x \<and> x < init_irq_node_ptr + 0x4000}
\<inter> {x. is_aligned x cte_level_bits}"
lemma irq_node_offs_in_range:
"init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits)
\<in> irq_node_offs_range"
apply (clarsimp simp: irq_node_offs_min irq_node_offs_max irq_node_offs_range_def)
apply (rule is_aligned_add[OF _ is_aligned_shift])
apply (simp add: is_aligned_def s0_ptr_defs cte_level_bits_def)
done
lemma irq_node_offs_range_correct:
"x \<in> irq_node_offs_range
\<Longrightarrow> \<exists>irq. x = init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits)"
apply (clarsimp simp: irq_node_offs_min irq_node_offs_max irq_node_offs_range_def
s0_ptr_defs cte_level_bits_def)
apply (rule_tac x="ucast ((x - 0xE0008000) >> 4)" in exI)
apply (clarsimp simp: ucast_ucast_mask)
apply (subst aligned_shiftr_mask_shiftl)
apply (rule aligned_sub_aligned)
apply assumption
apply (simp add: is_aligned_def)
apply simp
apply simp
apply (rule_tac n=14 in mask_eqI)
apply (subst mask_add_aligned)
apply (simp add: is_aligned_def)
apply (simp add: mask_twice)
apply (simp add: diff_conv_add_uminus del: add_uminus_conv_diff)
apply (subst add.commute[symmetric])
apply (subst mask_add_aligned)
apply (simp add: is_aligned_def)
apply simp
apply (simp add: diff_conv_add_uminus del: add_uminus_conv_diff)
apply (subst add_mask_lower_bits)
apply (simp add: is_aligned_def)
apply clarsimp
apply (cut_tac x=x and y="0xE000BFFF" and n=14 in neg_mask_mono_le)
apply (force dest: word_less_sub_1)
apply (drule_tac n=14 in aligned_le_sharp)
apply (simp add: is_aligned_def)
apply (simp add: mask_def)
done
lemma irq_node_offs_range_distinct[simp]:
"Low_cnode_ptr \<notin> irq_node_offs_range"
"High_cnode_ptr \<notin> irq_node_offs_range"
"Silc_cnode_ptr \<notin> irq_node_offs_range"
"ntfn_ptr \<notin> irq_node_offs_range"
"irq_cnode_ptr \<notin> irq_node_offs_range"
"Low_pd_ptr \<notin> irq_node_offs_range"
"High_pd_ptr \<notin> irq_node_offs_range"
"Low_pt_ptr \<notin> irq_node_offs_range"
"High_pt_ptr \<notin> irq_node_offs_range"
"Low_tcb_ptr \<notin> irq_node_offs_range"
"High_tcb_ptr \<notin> irq_node_offs_range"
"idle_tcb_ptr \<notin> irq_node_offs_range"
"init_globals_frame \<notin> irq_node_offs_range"
"init_global_pd \<notin> irq_node_offs_range"
by(simp add:irq_node_offs_range_def s0_ptr_defs)+
lemma irq_node_offs_distinct[simp]:
"init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> Low_cnode_ptr"
"init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> High_cnode_ptr"
"init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> Silc_cnode_ptr"
"init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> ntfn_ptr"
"init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> irq_cnode_ptr"
"init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> Low_pd_ptr"
"init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> High_pd_ptr"
"init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> Low_pt_ptr"
"init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> High_pt_ptr"
"init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> Low_tcb_ptr"
"init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> High_tcb_ptr"
"init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> idle_tcb_ptr"
"init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> init_globals_frame"
"init_irq_node_ptr + (ucast (irq:: 10 word) << cte_level_bits) \<noteq> init_global_pd"
by (simp add:not_inD[symmetric, OF _ irq_node_offs_in_range])+
lemma kh0_dom:
"dom kh0 = {init_globals_frame, init_global_pd, idle_tcb_ptr, High_tcb_ptr, Low_tcb_ptr,
High_pt_ptr, Low_pt_ptr, High_pd_ptr, Low_pd_ptr, irq_cnode_ptr, ntfn_ptr,
Silc_cnode_ptr, High_cnode_ptr, Low_cnode_ptr} \<union>
irq_node_offs_range"
apply (rule equalityI)
apply (simp add: kh0_def dom_def)
apply (clarsimp simp: irq_node_offs_in_range)
apply (clarsimp simp: dom_def)
apply (rule conjI, clarsimp simp: kh0_def)+
apply (force simp: kh0_def cte_level_bits_def dest: irq_node_offs_range_correct)
done
lemmas kh0_SomeD' = set_mp[OF equalityD1[OF kh0_dom[simplified dom_def]], OF CollectI, simplified, OF exI]
lemma kh0_SomeD:
"kh0 x = Some y \<Longrightarrow>
x = init_globals_frame \<and> y = ArchObj (DataPage False ARMSmallPage) \<or>
x = init_global_pd \<and> y = ArchObj (PageDirectory global_pd) \<or>
x = idle_tcb_ptr \<and> y = idle_tcb \<or>
x = High_tcb_ptr \<and> y = High_tcb \<or>
x = Low_tcb_ptr \<and> y = Low_tcb \<or>
x = High_pt_ptr \<and> y = High_pt \<or>
x = Low_pt_ptr \<and> y = Low_pt \<or>
x = High_pd_ptr \<and> y = High_pd \<or>
x = Low_pd_ptr \<and> y = Low_pd \<or>
x = irq_cnode_ptr \<and> y = irq_cnode \<or>
x = ntfn_ptr \<and> y = ntfn \<or>
x = Silc_cnode_ptr \<and> y = Silc_cnode \<or>
x = High_cnode_ptr \<and> y = High_cnode \<or>
x = Low_cnode_ptr \<and> y = Low_cnode \<or>
x \<in> irq_node_offs_range \<and> y = CNode 0 (empty_cnode 0)"
apply (frule kh0_SomeD')
apply (erule disjE, simp add: kh0_def
| force simp: kh0_def split: if_split_asm)+
done
lemmas kh0_obj_def =
Low_cnode_def High_cnode_def Silc_cnode_def ntfn_def irq_cnode_def Low_pd_def
High_pd_def Low_pt_def High_pt_def Low_tcb_def High_tcb_def idle_tcb_def
definition exst0 :: "det_ext" where
"exst0 \<equiv> \<lparr>work_units_completed_internal = undefined,
scheduler_action_internal = resume_cur_thread,
ekheap_internal = [Low_tcb_ptr \<mapsto> Low_etcb,
High_tcb_ptr \<mapsto> High_etcb,
idle_tcb_ptr \<mapsto> default_etcb],
domain_list_internal = [(0, 10), (1, 10)],
domain_index_internal = 0,
cur_domain_internal = 0,
domain_time_internal = 5,
ready_queues_internal = (const (const [])),
cdt_list_internal = const []\<rparr>"
lemmas ekh0_obj_def =
Low_etcb_def High_etcb_def default_etcb_def
definition machine_state0 :: "machine_state" where
"machine_state0 \<equiv> \<lparr>irq_masks = (\<lambda>irq. if irq = timer_irq then False else True),
irq_state = 0,
underlying_memory = const 0,
device_state = empty,
exclusive_state = undefined,
machine_state_rest = undefined \<rparr>"
definition arch_state0 :: "arch_state" where
"arch_state0 \<equiv> \<lparr>arm_asid_table = Map.empty,
arm_hwasid_table = Map.empty, arm_next_asid = 0, arm_asid_map = Map.empty,
arm_global_pd = init_global_pd, arm_global_pts = [],
arm_kernel_vspace =
\<lambda>ref. if ref \<in> {kernel_base..kernel_base + mask 20} then ArmVSpaceKernelWindow
else ArmVSpaceInvalidRegion\<rparr>"
definition
s0_internal :: "det_ext state"
where
"s0_internal \<equiv> \<lparr>
kheap = kh0,
cdt = empty,
is_original_cap = (\<lambda>_. False) ((Low_tcb_ptr, tcb_cnode_index 2) := True,
(High_tcb_ptr, tcb_cnode_index 2) := True),
cur_thread = Low_tcb_ptr,
idle_thread = idle_tcb_ptr,
machine_state = machine_state0,
interrupt_irq_node = (\<lambda>irq. init_irq_node_ptr + (ucast irq << cte_level_bits)),
interrupt_states = (\<lambda>_. irq_state.IRQInactive) (timer_irq := irq_state.IRQTimer),
arch_state = arch_state0,
exst = exst0
\<rparr>"
subsubsection {* Defining the policy graph *}
(* FIXME: should incorporate SharedPage above *)
(* There is an NTFN in the High label, a SharedPage in the Low label *)
definition
Sys1AgentMap :: "(auth_graph_label subject_label) agent_map"
where
"Sys1AgentMap \<equiv>
(\<lambda>p. if ptrFromPAddr shared_page_ptr \<le> p \<and> p < ptrFromPAddr shared_page_ptr + 0x1000
then partition_label Low else partition_label IRQ0)
(* set the range of the shared_page to Low, default everything else to IRQ0 *)
(Low_cnode_ptr := partition_label Low,
High_cnode_ptr := partition_label High,
ntfn_ptr := partition_label High,
irq_cnode_ptr := partition_label IRQ0,
Silc_cnode_ptr := SilcLabel,
Low_pd_ptr := partition_label Low,
High_pd_ptr := partition_label High,
Low_pt_ptr := partition_label Low,
High_pt_ptr := partition_label High,
Low_tcb_ptr := partition_label Low,
High_tcb_ptr := partition_label High,
idle_tcb_ptr := partition_label Low)"
lemma Sys1AgentMap_simps:
"Sys1AgentMap Low_cnode_ptr = partition_label Low"
"Sys1AgentMap High_cnode_ptr = partition_label High"
"Sys1AgentMap ntfn_ptr = partition_label High"
"Sys1AgentMap irq_cnode_ptr = partition_label IRQ0"
"Sys1AgentMap Silc_cnode_ptr = SilcLabel"
"Sys1AgentMap Low_pd_ptr = partition_label Low"
"Sys1AgentMap High_pd_ptr = partition_label High"
"Sys1AgentMap Low_pt_ptr = partition_label Low"
"Sys1AgentMap High_pt_ptr = partition_label High"
"Sys1AgentMap Low_tcb_ptr = partition_label Low"
"Sys1AgentMap High_tcb_ptr = partition_label High"
"Sys1AgentMap idle_tcb_ptr = partition_label Low"
"\<And>p. \<lbrakk>ptrFromPAddr shared_page_ptr \<le> p; p < ptrFromPAddr shared_page_ptr + 0x1000\<rbrakk>
\<Longrightarrow> Sys1AgentMap p = partition_label Low"
unfolding Sys1AgentMap_def
apply simp_all
by (auto simp: ptrFromPAddr_def physMappingOffset_def
kernelBase_addr_def physBase_def s0_ptr_defs)
definition
Sys1ASIDMap :: "(auth_graph_label subject_label) agent_asid_map"
where
"Sys1ASIDMap \<equiv>
(\<lambda>x. if (asid_high_bits_of x = asid_high_bits_of Low_asid)
then partition_label Low
else if (asid_high_bits_of x = asid_high_bits_of High_asid)
then partition_label High else undefined)"
(* We include 2 domains, Low is associated to domain 0, High to domain 1, we default the rest of the possible domains to High *)
definition Sys1PAS :: "(auth_graph_label subject_label) PAS" where
"Sys1PAS \<equiv> \<lparr> pasObjectAbs = Sys1AgentMap, pasASIDAbs = Sys1ASIDMap, pasIRQAbs = (\<lambda>_. partition_label IRQ0),
pasPolicy = Sys1AuthGraph, pasSubject = partition_label Low, pasMayActivate = True,
pasMayEditReadyQueues = True, pasMaySendIrqs = False, pasDomainAbs = (\<lambda>_. partition_label High) (0 := partition_label Low) \<rparr>"
subsubsection {* Proof of pas_refined for Sys1 *}
lemma High_caps_well_formed: "well_formed_cnode_n 10 High_caps"
by (auto simp: High_caps_def well_formed_cnode_n_def split: if_split_asm)
lemma Low_caps_well_formed: "well_formed_cnode_n 10 Low_caps"
by (auto simp: Low_caps_def well_formed_cnode_n_def split: if_split_asm)
lemma Silc_caps_well_formed: "well_formed_cnode_n 10 Silc_caps"
by (auto simp: Silc_caps_def well_formed_cnode_n_def split: if_split_asm)
lemma s0_caps_of_state :
"caps_of_state s0_internal p = Some cap \<Longrightarrow>
cap = NullCap \<or>
(p,cap) \<in>
{ ((Low_cnode_ptr::obj_ref,(the_nat_to_bl_10 1)), ThreadCap Low_tcb_ptr),
((Low_cnode_ptr::obj_ref,(the_nat_to_bl_10 2)), CNodeCap Low_cnode_ptr 10 (the_nat_to_bl_10 2)),
((Low_cnode_ptr::obj_ref,(the_nat_to_bl_10 3)), ArchObjectCap (PageDirectoryCap Low_pd_ptr (Some Low_asid))),
((Low_cnode_ptr::obj_ref,(the_nat_to_bl_10 318)),NotificationCap ntfn_ptr 0 {AllowSend}),
((High_cnode_ptr::obj_ref,(the_nat_to_bl_10 1)), ThreadCap High_tcb_ptr),
((High_cnode_ptr::obj_ref,(the_nat_to_bl_10 2)), CNodeCap High_cnode_ptr 10 (the_nat_to_bl_10 2)),
((High_cnode_ptr::obj_ref,(the_nat_to_bl_10 3)), ArchObjectCap (PageDirectoryCap High_pd_ptr (Some High_asid))),
((High_cnode_ptr::obj_ref,(the_nat_to_bl_10 318)),NotificationCap ntfn_ptr 0 {AllowRecv}) ,
((Silc_cnode_ptr::obj_ref,(the_nat_to_bl_10 2)),CNodeCap Silc_cnode_ptr 10 (the_nat_to_bl_10 2)),
((Silc_cnode_ptr::obj_ref,(the_nat_to_bl_10 318)),NotificationCap ntfn_ptr 0 {AllowSend}),
((Low_tcb_ptr::obj_ref, (tcb_cnode_index 0)), CNodeCap Low_cnode_ptr 10 (the_nat_to_bl_10 2)),
((Low_tcb_ptr::obj_ref, (tcb_cnode_index 1)), ArchObjectCap (PageDirectoryCap Low_pd_ptr (Some Low_asid))),
((Low_tcb_ptr::obj_ref, (tcb_cnode_index 2)), ReplyCap Low_tcb_ptr True),
((Low_tcb_ptr::obj_ref, (tcb_cnode_index 3)), NullCap),
((Low_tcb_ptr::obj_ref, (tcb_cnode_index 4)), NullCap),
((High_tcb_ptr::obj_ref, (tcb_cnode_index 0)), CNodeCap High_cnode_ptr 10 (the_nat_to_bl_10 2)),
((High_tcb_ptr::obj_ref, (tcb_cnode_index 1)), ArchObjectCap (PageDirectoryCap High_pd_ptr (Some High_asid))),
((High_tcb_ptr::obj_ref, (tcb_cnode_index 2)), ReplyCap High_tcb_ptr True),
((High_tcb_ptr::obj_ref, (tcb_cnode_index 3)), NullCap),
((High_tcb_ptr::obj_ref, (tcb_cnode_index 4)), NullCap)} "
apply (insert High_caps_well_formed)
apply (insert Low_caps_well_formed)
apply (insert Silc_caps_well_formed)
apply (simp add: caps_of_state_cte_wp_at cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def)
apply (case_tac p, clarsimp)
apply (clarsimp split: if_splits)
apply (clarsimp simp: cte_wp_at_cases tcb_cap_cases_def
split: if_split_asm)+
apply (clarsimp simp: Silc_caps_def split: if_splits)
apply (clarsimp simp: High_caps_def split: if_splits)
apply (clarsimp simp: Low_caps_def cte_wp_at_cases split: if_splits)
done
lemma tcb_states_of_state_s0:
"tcb_states_of_state s0_internal = [High_tcb_ptr \<mapsto> thread_state.BlockedOnNotification ntfn_ptr, Low_tcb_ptr \<mapsto> thread_state.Running, idle_tcb_ptr \<mapsto> thread_state.IdleThreadState ]"
unfolding s0_internal_def tcb_states_of_state_def
apply (rule ext)
apply (simp add: get_tcb_def)
apply (simp add: kh0_def kh0_obj_def)
done
lemma thread_bounds_of_state_s0:
"thread_bound_ntfns s0_internal = Map.empty"
unfolding s0_internal_def thread_bound_ntfns_def
apply (rule ext)
apply (simp add: get_tcb_def)
apply (simp add: kh0_def kh0_obj_def)
done
lemma Sys1_wellformed:
"x \<in> range (pasObjectAbs Sys1PAS) - {SilcLabel} \<Longrightarrow> policy_wellformed (pasPolicy Sys1PAS) False irqs x"
apply (clarsimp simp: Sys1PAS_def Sys1AgentMap_simps policy_wellformed_def
Sys1AuthGraph_def)
done
lemma Sys1_pas_wellformed:
"pas_wellformed Sys1PAS"
apply (clarsimp simp: Sys1PAS_def Sys1AgentMap_simps policy_wellformed_def
Sys1AuthGraph_def)
done
lemma domains_of_state_s0[simp]:
"domains_of_state s0_internal = {(High_tcb_ptr, High_domain), (Low_tcb_ptr, Low_domain), (idle_tcb_ptr, default_domain)}"
apply(rule equalityI)
apply(rule subsetI)
apply clarsimp
apply (erule domains_of_state_aux.cases)
apply (clarsimp simp: s0_internal_def exst0_def ekh0_obj_def split: if_split_asm)
apply clarsimp
apply (force simp: s0_internal_def exst0_def ekh0_obj_def intro: domains_of_state_aux.domtcbs)+
done
lemma Sys1_pas_refined:
"pas_refined Sys1PAS s0_internal"
apply (clarsimp simp: pas_refined_def)
apply (intro conjI)
apply (simp add: Sys1_pas_wellformed)
apply (clarsimp simp: irq_map_wellformed_aux_def s0_internal_def Sys1AgentMap_simps Sys1PAS_def)
apply (clarsimp simp: Sys1AgentMap_def)
apply (clarsimp simp: ptrFromPAddr_def s0_ptr_defs cte_level_bits_def
physMappingOffset_def kernelBase_addr_def physBase_def)
apply (drule le_less_trans[OF irq_node_offs_min[simplified s0_ptr_defs cte_level_bits_def, simplified]])
apply simp
apply (clarsimp simp: tcb_domain_map_wellformed_aux_def
Sys1PAS_def Sys1AgentMap_def
default_domain_def minBound_word
High_domain_def Low_domain_def cte_level_bits_def)
apply (clarsimp simp: auth_graph_map_def
Sys1PAS_def
state_objs_to_policy_def
state_bits_to_policy_def)
apply (erule state_bits_to_policyp.cases, simp_all, clarsimp)
apply (drule s0_caps_of_state, clarsimp)
apply (simp add: Sys1AuthGraph_def)
apply (elim disjE conjE, auto simp: Sys1AgentMap_simps cap_auth_conferred_def cap_rights_to_auth_def)[1]
apply (drule s0_caps_of_state, clarsimp)
apply (elim disjE, simp_all)[1]
apply (clarsimp simp: state_refs_of_def thread_states_def tcb_states_of_state_s0
Sys1AuthGraph_def Sys1AgentMap_simps split: if_splits)
apply (clarsimp simp: state_refs_of_def thread_states_def thread_bounds_of_state_s0)
apply (simp add: s0_internal_def) (* this is OK because cdt is empty..*)
apply (clarsimp simp: state_vrefs_def
vs_refs_no_global_pts_def
s0_internal_def kh0_def Sys1AgentMap_simps
kh0_obj_def comp_def Low_pt'_def High_pt'_def
pte_ref_def pde_ref2_def Low_pd'_def High_pd'_def
Sys1AuthGraph_def ptr_range_def vspace_cap_rights_to_auth_def
vm_read_only_def vm_read_write_def
dest!: graph_ofD
split: if_splits)
apply (rule Sys1AgentMap_simps(13))
apply simp
apply (drule_tac x=ac in plus_one_helper2)
apply (simp add: ptrFromPAddr_def physMappingOffset_def kernelBase_addr_def physBase_def
shared_page_ptr_def kernel_base_def)
apply (simp add: add.commute)
apply (erule notE)
apply (rule Sys1AgentMap_simps(13)[symmetric])
apply simp
apply (drule_tac x=ac in plus_one_helper2)
apply (simp add: ptrFromPAddr_def physMappingOffset_def kernelBase_addr_def physBase_def
s0_ptr_defs)
apply (simp add: add.commute)
apply (rule subsetI, clarsimp)
apply (erule state_asids_to_policy_aux.cases)
apply clarsimp
apply (drule s0_caps_of_state, clarsimp)
apply (simp add: Sys1AuthGraph_def Sys1PAS_def Sys1ASIDMap_def)
apply (elim disjE conjE, simp_all add: Sys1AgentMap_simps cap_auth_conferred_def
cap_rights_to_auth_def Low_asid_def High_asid_def
asid_low_bits_def asid_high_bits_of_def )[1]
apply (clarsimp simp: state_vrefs_def
vs_refs_no_global_pts_def
s0_internal_def kh0_def Sys1AgentMap_simps
kh0_obj_def comp_def Low_pt'_def High_pt'_def
pte_ref_def pde_ref2_def Low_pd'_def High_pd'_def
Sys1AuthGraph_def ptr_range_def
dest!: graph_ofD
split: if_splits)
apply (clarsimp simp: s0_internal_def arch_state0_def)
apply (rule subsetI, clarsimp)
apply (erule state_irqs_to_policy_aux.cases)
apply (simp add: Sys1AuthGraph_def Sys1PAS_def Sys1ASIDMap_def)
apply (drule s0_caps_of_state)
apply (simp add: Sys1AuthGraph_def Sys1PAS_def Sys1ASIDMap_def)
apply (elim disjE conjE, simp_all add: Sys1AgentMap_simps cap_auth_conferred_def cap_rights_to_auth_def Low_asid_def High_asid_def
asid_low_bits_def asid_high_bits_of_def )[1]
done
lemma Sys1_pas_cur_domain:
"pas_cur_domain Sys1PAS s0_internal"
by (simp add: s0_internal_def exst0_def Sys1PAS_def)
lemma pasMaySendIrqs_Sys1PAS[simp]:
"pasMaySendIrqs Sys1PAS = False"
by(auto simp: Sys1PAS_def)
lemma Sys1_pas_wellformed_noninterference:
"pas_wellformed_noninterference Sys1PAS"
apply (simp add: pas_wellformed_noninterference_def)
apply (intro conjI ballI allI)
apply (simp add: Sys1_wellformed)
apply (simp add: policy_wellformed_def)
apply (clarsimp simp: Sys1PAS_def policy_wellformed_def Sys1AuthGraph_def)
apply (simp add: Sys1PAS_def)
done
lemma silc_inv_s0:
"silc_inv Sys1PAS s0_internal s0_internal"
apply (clarsimp simp: silc_inv_def)
apply (rule conjI, simp add: Sys1PAS_def)
apply (rule conjI)
apply (clarsimp simp: Sys1PAS_def Sys1AgentMap_def
s0_internal_def kh0_def obj_at_def kh0_obj_def
is_cap_table_def Silc_caps_well_formed split: if_split_asm)
apply (rule conjI)
apply (clarsimp simp: Sys1PAS_def Sys1AuthGraph_def)
apply (rule conjI)
apply clarsimp
apply (rule_tac x=Silc_cnode_ptr in exI)
apply (rule conjI)
apply (rule_tac x="the_nat_to_bl_10 318" in exI)
apply (clarsimp simp: slots_holding_overlapping_caps_def2)
apply (case_tac "cap = NullCap")
apply clarsimp
apply (simp add: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def)
apply (case_tac a, clarsimp)
apply (clarsimp split: if_splits)
apply ((clarsimp simp: intra_label_cap_def cte_wp_at_cases tcb_cap_cases_def
cap_points_to_label_def split: if_split_asm)+)[8]
apply (clarsimp simp: intra_label_cap_def cap_points_to_label_def)
apply (drule cte_wp_at_caps_of_state' s0_caps_of_state)+
apply ((erule disjE |
clarsimp simp: Sys1PAS_def Sys1AgentMap_simps
the_nat_to_bl_def nat_to_bl_def ctes_wp_at_def cte_wp_at_cases
s0_internal_def kh0_def kh0_obj_def Silc_caps_well_formed obj_refs_def
| simp add: Silc_caps_def)+)[1]
apply (simp add: Sys1PAS_def Sys1AgentMap_simps)
apply (clarsimp simp: all_children_def s0_internal_def silc_dom_equiv_def equiv_for_refl)
done
lemma only_timer_irq_s0:
"only_timer_irq timer_irq s0_internal"
apply (clarsimp simp: only_timer_irq_def s0_internal_def irq_is_recurring_def is_irq_at_def
irq_at_def Let_def irq_oracle_def machine_state0_def timer_irq_def)
apply presburger
done
lemma domain_sep_inv_s0:
"domain_sep_inv False s0_internal s0_internal"
apply (clarsimp simp: domain_sep_inv_def)
apply (force dest: cte_wp_at_caps_of_state' s0_caps_of_state
| rule conjI allI | clarsimp simp: s0_internal_def)+
done
lemma only_timer_irq_inv_s0:
"only_timer_irq_inv timer_irq s0_internal s0_internal"
by (simp add: only_timer_irq_inv_def only_timer_irq_s0 domain_sep_inv_s0)
lemma Sys1_guarded_pas_domain:
"guarded_pas_domain Sys1PAS s0_internal"
by (clarsimp simp: guarded_pas_domain_def Sys1PAS_def s0_internal_def
exst0_def Sys1AgentMap_simps)
lemma s0_valid_domain_list:
"valid_domain_list s0_internal"
by (clarsimp simp: valid_domain_list_2_def s0_internal_def exst0_def)
definition
"s0 \<equiv> ((if ct_idle s0_internal then idle_context s0_internal else s0_context,s0_internal),KernelExit)"
subsubsection {* einvs *}
lemma well_formed_cnode_n_s0_caps[simp]:
"well_formed_cnode_n 10 High_caps"
"well_formed_cnode_n 10 Low_caps"
"well_formed_cnode_n 10 Silc_caps"
"\<not> well_formed_cnode_n 10 [[] \<mapsto> NullCap]"
apply ((force simp: High_caps_def Low_caps_def Silc_caps_def well_formed_cnode_n_def
the_nat_to_bl_def nat_to_bl_def dom_empty_cnode)+)[3]
apply (clarsimp simp: well_formed_cnode_n_def)
apply (drule eqset_imp_iff[where x="[]"])
apply simp
done
lemma valid_caps_s0[simp]:
"s0_internal \<turnstile> ThreadCap Low_tcb_ptr"
"s0_internal \<turnstile> ThreadCap High_tcb_ptr"
"s0_internal \<turnstile> CNodeCap Low_cnode_ptr 10 (the_nat_to_bl_10 2)"
"s0_internal \<turnstile> CNodeCap High_cnode_ptr 10 (the_nat_to_bl_10 2)"
"s0_internal \<turnstile> CNodeCap Silc_cnode_ptr 10 (the_nat_to_bl_10 2)"
"s0_internal \<turnstile> ArchObjectCap (PageDirectoryCap Low_pd_ptr (Some Low_asid))"
"s0_internal \<turnstile> ArchObjectCap (PageDirectoryCap High_pd_ptr (Some High_asid))"
"s0_internal \<turnstile> NotificationCap ntfn_ptr 0 {AllowWrite}"
"s0_internal \<turnstile> NotificationCap ntfn_ptr 0 {AllowRead}"
"s0_internal \<turnstile> ReplyCap Low_tcb_ptr True"
"s0_internal \<turnstile> ReplyCap High_tcb_ptr True"
by (simp_all add: valid_cap_def s0_internal_def s0_ptr_defs cap_aligned_def is_aligned_def
word_bits_def cte_level_bits_def the_nat_to_bl_def
nat_to_bl_def Low_asid_def High_asid_def asid_low_bits_def asid_bits_def
obj_at_def kh0_def kh0_obj_def is_tcb_def is_cap_table_def a_type_def
is_ntfn_def)
lemma valid_obj_s0[simp]:
"valid_obj Low_cnode_ptr Low_cnode s0_internal"
"valid_obj High_cnode_ptr High_cnode s0_internal"
"valid_obj Silc_cnode_ptr Silc_cnode s0_internal"
"valid_obj ntfn_ptr ntfn s0_internal"
"valid_obj irq_cnode_ptr irq_cnode s0_internal"
"valid_obj Low_pd_ptr Low_pd s0_internal"
"valid_obj High_pd_ptr High_pd s0_internal"
"valid_obj Low_pt_ptr Low_pt s0_internal"
"valid_obj High_pt_ptr High_pt s0_internal"
"valid_obj Low_tcb_ptr Low_tcb s0_internal"
"valid_obj High_tcb_ptr High_tcb s0_internal"
"valid_obj idle_tcb_ptr idle_tcb s0_internal"
"valid_obj init_global_pd (ArchObj (PageDirectory ((\<lambda>_. InvalidPDE)
(ucast (kernel_base >> 20) := SectionPDE (addrFromPPtr kernel_base) {} 0 {}))))
s0_internal"
"valid_obj init_globals_frame (ArchObj (DataPage False ARMSmallPage)) s0_internal"
apply (simp_all add: valid_obj_def kh0_obj_def)
apply (simp add: valid_cs_def Low_caps_ran High_caps_ran Silc_caps_ran
valid_cs_size_def word_bits_def cte_level_bits_def)+
apply (simp add: valid_ntfn_def obj_at_def s0_internal_def kh0_def
High_tcb_def is_tcb_def)
apply (simp add: valid_cs_def valid_cs_size_def word_bits_def cte_level_bits_def)
apply (simp add: well_formed_cnode_n_def)
apply (clarsimp simp: Low_pd'_def High_pd'_def Low_pt'_def High_pt'_def
valid_vm_rights_def vm_kernel_only_def)+
apply (clarsimp simp: valid_tcb_def tcb_cap_cases_def is_master_reply_cap_def
valid_ipc_buffer_cap_def valid_tcb_state_def
| simp add: obj_at_def s0_internal_def kh0_def kh0_obj_def is_ntfn_def)+
apply (simp add: valid_vm_rights_def vm_kernel_only_def)
done
lemma valid_objs_s0:
"valid_objs s0_internal"
apply (clarsimp simp: valid_objs_def)
apply (subst(asm) s0_internal_def kh0_def)+
apply (simp split: if_split_asm)
apply force+
apply (clarsimp simp: valid_obj_def valid_cs_def empty_cnode_def valid_cs_size_def ran_def
cte_level_bits_def word_bits_def well_formed_cnode_n_def dom_def)
done
lemma pspace_aligned_s0:
"pspace_aligned s0_internal"
apply (clarsimp simp: pspace_aligned_def s0_internal_def)
apply (drule kh0_SomeD)
apply (erule disjE
| (subst is_aligned_def,
fastforce simp: s0_ptr_defs cte_level_bits_def kh0_def kh0_obj_def))+
apply (clarsimp simp: cte_level_bits_def)
apply (drule irq_node_offs_range_correct)
apply (clarsimp simp: s0_ptr_defs cte_level_bits_def)
apply (rule is_aligned_add[OF _ is_aligned_shift])
apply (simp add: is_aligned_def s0_ptr_defs cte_level_bits_def)
done
lemma pspace_distinct_s0:
"pspace_distinct s0_internal"
apply (clarsimp simp: pspace_distinct_def s0_internal_def)
apply (drule kh0_SomeD)+
apply (case_tac "x \<in> irq_node_offs_range \<and> y \<in> irq_node_offs_range")
apply clarsimp
apply (drule irq_node_offs_range_correct)+
apply clarsimp
apply (clarsimp simp: s0_ptr_defs cte_level_bits_def)
apply (case_tac "(ucast irq << 4) < (ucast irqa << 4)")
apply (frule udvd_decr'[where K="0x10::32 word" and ua=0, simplified])
apply (simp add: shiftl_t2n uint_word_ariths)
apply (subst mod_mult_mult1[where c="2^4" and b="2^28", simplified])
apply simp
apply (simp add: shiftl_t2n uint_word_ariths)
apply (subst mod_mult_mult1[where c="2^4" and b="2^28", simplified])
apply simp
apply (frule_tac y="ucast irq << 4" in word_plus_mono_right[where x="0xE000800F"])
apply (simp add: shiftl_t2n)
apply (case_tac "(1::32 word) \<le> ucast irqa")
apply (drule_tac i=1 and k="0x10" in word_mult_le_mono1)
apply simp
apply (cut_tac x=irqa and 'a=32 in ucast_less)
apply simp
apply (simp add: word_less_nat_alt)
apply (simp add: mult.commute)
apply (drule_tac y="0x10" and x="0xE0007FFF" in word_plus_mono_right)
apply (rule_tac sz=28 in machine_word_plus_mono_right_split)
apply (simp add: unat_word_ariths mask_def)
apply (cut_tac x=irqa and 'a=32 in ucast_less)
apply simp
apply (simp add: word_less_nat_alt)
apply (simp add: word_bits_def)
apply simp
apply (simp add: lt1_neq0)
apply (drule(1) order_trans_rules(23))
apply clarsimp
apply (drule_tac a="0xE0008000 + (ucast irqa << 4)" and b="ucast irqa << 4"
and c="0xE0007FFF + (ucast irqa << 4)" and d="ucast irqa << 4" in word_sub_mono)
apply simp
apply simp
apply (rule_tac sz=28 in machine_word_plus_mono_right_split)
apply (simp add: unat_word_ariths mask_def shiftl_t2n)
apply (cut_tac x=irqa and 'a=32 in ucast_less)
apply simp
apply (simp add: word_less_nat_alt)
apply (simp add: word_bits_def)
apply simp
apply (rule_tac sz=28 in machine_word_plus_mono_right_split)
apply (simp add: unat_word_ariths mask_def shiftl_t2n)
apply (cut_tac x=irqa and 'a=32 in ucast_less)
apply simp
apply (simp add: word_less_nat_alt)
apply (simp add: word_bits_def)
apply simp
apply (case_tac "(ucast irq << 4) > (ucast irqa << 4)")
apply (frule udvd_decr'[where K="0x10::32 word" and ua=0, simplified])
apply (simp add: shiftl_t2n uint_word_ariths)
apply (subst mod_mult_mult1[where c="2^4" and b="2^28", simplified])
apply simp
apply (simp add: shiftl_t2n uint_word_ariths)
apply (subst mod_mult_mult1[where c="2^4" and b="2^28", simplified])
apply simp
apply (frule_tac y="ucast irqa << 4" in word_plus_mono_right[where x="0xE000800F"])
apply (simp add: shiftl_t2n)
apply (case_tac "(1::32 word) \<le> ucast irq")
apply (drule_tac i=1 and k="0x10" in word_mult_le_mono1)
apply simp
apply (cut_tac x=irq and 'a=32 in ucast_less)
apply simp
apply (simp add: word_less_nat_alt)
apply (simp add: mult.commute)
apply (drule_tac y="0x10" and x="0xE0007FFF" in word_plus_mono_right)
apply (rule_tac sz=28 in machine_word_plus_mono_right_split)
apply (simp add: unat_word_ariths mask_def)
apply (cut_tac x=irq and 'a=32 in ucast_less)
apply simp
apply (simp add: word_less_nat_alt)
apply (simp add: word_bits_def)
apply simp
apply (simp add: lt1_neq0)
apply (drule(1) order_trans_rules(23))
apply clarsimp
apply (drule_tac a="0xE0008000 + (ucast irq << 4)" and b="ucast irq << 4"
and c="0xE0007FFF + (ucast irq << 4)" and d="ucast irq << 4" in word_sub_mono)
apply simp
apply simp
apply (rule_tac sz=28 in machine_word_plus_mono_right_split)
apply (simp add: unat_word_ariths mask_def shiftl_t2n)
apply (cut_tac x=irq and 'a=32 in ucast_less)
apply simp
apply (simp add: word_less_nat_alt)
apply (simp add: word_bits_def)
apply simp
apply (rule_tac sz=28 in machine_word_plus_mono_right_split)
apply (simp add: unat_word_ariths mask_def shiftl_t2n)
apply (cut_tac x=irq and 'a=32 in ucast_less)
apply simp
apply (simp add: word_less_nat_alt)
apply (simp add: word_bits_def)
apply simp
apply simp
by ((simp | erule disjE | clarsimp simp: kh0_obj_def cte_level_bits_def s0_ptr_defs
| clarsimp simp: irq_node_offs_range_def s0_ptr_defs,
drule_tac x="0xF" in word_plus_strict_mono_right, simp, simp add: add.commute,
drule(1) notE[rotated, OF less_trans, OF _ _ leD, rotated 2] |
drule(1) notE[rotated, OF le_less_trans, OF _ _ leD, rotated 2], simp, assumption)+)
lemma valid_pspace_s0[simp]:
"valid_pspace s0_internal"
apply (simp add: valid_pspace_def pspace_distinct_s0 pspace_aligned_s0 valid_objs_s0)
apply (rule conjI)
apply (clarsimp simp: if_live_then_nonz_cap_def)
apply (subst(asm) s0_internal_def)
apply (clarsimp simp: obj_at_def kh0_def kh0_obj_def s0_ptr_defs split: if_split_asm)
apply (clarsimp simp: ex_nonz_cap_to_def)
apply (rule_tac x="High_cnode_ptr" in exI)
apply (rule_tac x="the_nat_to_bl_10 1" in exI)
apply (force simp: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def s0_ptr_defs tcb_cap_cases_def High_caps_def the_nat_to_bl_def nat_to_bl_def well_formed_cnode_n_def dom_empty_cnode)
apply (clarsimp simp: ex_nonz_cap_to_def)
apply (rule_tac x="Low_cnode_ptr" in exI)
apply (rule_tac x="the_nat_to_bl_10 1" in exI)
apply (force simp: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def s0_ptr_defs tcb_cap_cases_def Low_caps_def the_nat_to_bl_def nat_to_bl_def well_formed_cnode_n_def dom_empty_cnode)
apply (clarsimp simp: ex_nonz_cap_to_def)
apply (rule_tac x="High_cnode_ptr" in exI)
apply (rule_tac x="the_nat_to_bl_10 318" in exI)
apply (force simp: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def s0_ptr_defs tcb_cap_cases_def High_caps_def the_nat_to_bl_def nat_to_bl_def well_formed_cnode_n_def dom_empty_cnode)
apply (rule conjI)
apply (simp add: Invariants_AI.cte_wp_at_caps_of_state zombies_final_def)
apply (force dest: s0_caps_of_state simp: is_zombie_def)
apply (clarsimp simp: sym_refs_def state_refs_of_def s0_internal_def)
apply (subst(asm) kh0_def)
apply (clarsimp split: if_split_asm)
by (simp add: refs_of_def kh0_def s0_ptr_defs kh0_obj_def)+
lemma descendants_s0[simp]:
"descendants_of (a, b) (cdt s0_internal) = {}"
apply (rule set_eqI)
apply clarsimp
apply (drule descendants_of_NoneD[rotated])
apply (simp add: s0_internal_def)+
done
lemma valid_mdb_s0[simp]:
"valid_mdb s0_internal"
apply (simp add: valid_mdb_def reply_mdb_def)
apply (intro conjI)
apply (clarsimp simp: mdb_cte_at_def s0_internal_def)
apply (force dest: s0_caps_of_state simp: untyped_mdb_def)
apply (clarsimp simp: descendants_inc_def)
apply (clarsimp simp: no_mloop_def s0_internal_def cdt_parent_defs)
apply (clarsimp simp: untyped_inc_def)
apply (drule s0_caps_of_state)+
apply ((simp | erule disjE)+)[1]
apply (force dest: s0_caps_of_state simp: ut_revocable_def)
apply (force dest: s0_caps_of_state simp: irq_revocable_def)
apply (clarsimp simp: reply_master_revocable_def)
apply (drule s0_caps_of_state)
apply ((simp add: is_master_reply_cap_def s0_internal_def s0_ptr_defs | erule disjE)+)[1]
apply (force dest: s0_caps_of_state simp: reply_caps_mdb_def)
apply (clarsimp simp: reply_masters_mdb_def)
apply (simp add: s0_internal_def)
done
lemma valid_ioc_s0[simp]:
"valid_ioc s0_internal"
by (clarsimp simp: cte_wp_at_cases tcb_cap_cases_def valid_ioc_def
s0_internal_def kh0_def kh0_obj_def split: if_split_asm)+
lemma valid_idle_s0[simp]:
"valid_idle s0_internal"
apply (clarsimp simp: valid_idle_def st_tcb_at_tcb_states_of_state_eq
thread_bounds_of_state_s0
identity_eq[symmetric] tcb_states_of_state_s0)
by (simp add: s0_ptr_defs s0_internal_def idle_thread_ptr_def pred_tcb_at_def obj_at_def kh0_def idle_tcb_def)
lemma only_idle_s0[simp]:
"only_idle s0_internal"
apply (clarsimp simp: only_idle_def st_tcb_at_tcb_states_of_state_eq
identity_eq[symmetric] tcb_states_of_state_s0)
apply (simp add: s0_ptr_defs s0_internal_def)
done
lemma if_unsafe_then_cap_s0[simp]:
"if_unsafe_then_cap s0_internal"
apply (clarsimp simp: if_unsafe_then_cap_def ex_cte_cap_wp_to_def)
apply (drule s0_caps_of_state)
apply (case_tac "a=Low_cnode_ptr")
apply (rule_tac x=Low_tcb_ptr in exI, rule_tac x="tcb_cnode_index 0" in exI)
apply ((clarsimp simp: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def
tcb_cap_cases_def the_nat_to_bl_def nat_to_bl_def
Low_caps_def | erule disjE)+)[1]
apply (case_tac "a=High_cnode_ptr")
apply (rule_tac x=High_tcb_ptr in exI, rule_tac x="tcb_cnode_index 0" in exI)
apply ((clarsimp simp: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def
tcb_cap_cases_def the_nat_to_bl_def nat_to_bl_def
High_caps_def | erule disjE)+)[1]
apply (case_tac "a=Low_tcb_ptr")
apply (rule_tac x=Low_cnode_ptr in exI, rule_tac x="the_nat_to_bl_10 1" in exI)
apply ((clarsimp simp: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def
tcb_cap_cases_def the_nat_to_bl_def nat_to_bl_def
Low_caps_def well_formed_cnode_n_def dom_empty_cnode
| erule disjE | force)+)[1]
apply (case_tac "a=High_tcb_ptr")
apply (rule_tac x=High_cnode_ptr in exI, rule_tac x="the_nat_to_bl_10 1" in exI)
apply ((clarsimp simp: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def
tcb_cap_cases_def the_nat_to_bl_def nat_to_bl_def
High_caps_def well_formed_cnode_n_def dom_empty_cnode
| erule disjE | force)+)[1]
apply (rule_tac x=Silc_cnode_ptr in exI, rule_tac x="the_nat_to_bl_10 2" in exI)
apply ((clarsimp simp: cte_wp_at_cases s0_internal_def kh0_def kh0_obj_def
tcb_cap_cases_def the_nat_to_bl_def nat_to_bl_def
Silc_caps_def well_formed_cnode_n_def dom_empty_cnode
| erule disjE | force)+)[1]
done
lemma valid_reply_caps_s0[simp]:
"valid_reply_caps s0_internal"
apply (clarsimp simp: valid_reply_caps_def)
apply (rule conjI)
apply (force dest: cte_wp_at_caps_of_state' s0_caps_of_state simp: has_reply_cap_def)
apply (clarsimp simp: unique_reply_caps_def)
apply (drule s0_caps_of_state)+
apply (erule disjE | simp add: is_reply_cap_def)+
done
lemma valid_reply_masters_s0[simp]:
"valid_reply_masters s0_internal"
apply (clarsimp simp: valid_reply_masters_def)
apply (force dest: cte_wp_at_caps_of_state' s0_caps_of_state)
done
lemma valid_global_refs_s0[simp]:
"valid_global_refs s0_internal"
apply (clarsimp simp: valid_global_refs_def valid_refs_def)
apply (simp add: Invariants_AI.cte_wp_at_caps_of_state)
apply clarsimp
apply (drule s0_caps_of_state)
apply (clarsimp simp: global_refs_def s0_internal_def arch_state0_def)
apply (erule disjE | simp add: cap_range_def
| clarsimp simp: irq_node_offs_distinct[symmetric]
| simp only: s0_ptr_defs, force)+
done
lemma valid_arch_state_s0[simp]:
"valid_arch_state s0_internal"
apply (clarsimp simp: valid_arch_state_def s0_internal_def arch_state0_def)
apply (intro conjI)
apply (clarsimp simp: obj_at_def kh0_def a_type_def)
apply (simp add: valid_asid_table_def)
apply (clarsimp simp: obj_at_def kh0_def a_type_def)
apply (simp add: valid_global_pts_def)
apply (simp add: is_inv_def)
done
lemma valid_irq_node_s0[simp]:
"valid_irq_node s0_internal"
apply (clarsimp simp: valid_irq_node_def)
apply (rule conjI)
apply (simp add: s0_internal_def)
apply (rule injI)
apply simp
apply (rule ccontr)
apply (rule_tac bnd="0x400" and 'a=32 in shift_distinct_helper[rotated 3])
apply assumption
apply (simp add: cte_level_bits_def)
apply (simp add: cte_level_bits_def)
apply (rule ucast_less[where 'b=10, simplified])
apply simp
apply (rule ucast_less[where 'b=10, simplified])
apply simp
apply (rule notI)
apply (drule ucast_up_inj)
apply simp
apply simp
apply (clarsimp simp: obj_at_def s0_internal_def)
apply (force simp: kh0_def is_cap_table_def well_formed_cnode_n_def dom_empty_cnode)
done
lemma valid_irq_handlers_s0[simp]:
"valid_irq_handlers s0_internal"
apply (clarsimp simp: valid_irq_handlers_def ran_def)
apply (force dest: s0_caps_of_state)
done
lemma valid_irq_state_s0[simp]:
"valid_irq_states s0_internal"
apply (clarsimp simp: valid_irq_states_def valid_irq_masks_def s0_internal_def machine_state0_def)
done
lemma valid_machine_state_s0[simp]:
"valid_machine_state s0_internal"
apply (clarsimp simp: valid_machine_state_def s0_internal_def machine_state0_def in_user_frame_def obj_at_def const_def)
done
lemma valid_arch_objs_s0[simp]:
"valid_arch_objs s0_internal"
apply (clarsimp simp: valid_arch_objs_def obj_at_def s0_internal_def)
apply (drule kh0_SomeD)
apply (erule disjE | clarsimp simp: pageBits_def addrFromPPtr_def
physMappingOffset_def kernelBase_addr_def physBase_def is_aligned_def
obj_at_def kh0_def kh0_obj_def a_type_def kernel_mapping_slots_def
High_pt'_def Low_pt'_def High_pd'_def Low_pd'_def ptrFromPAddr_def
| erule vs_lookupE, force simp: vs_lookup_def arch_state0_def vs_asid_refs_def)+
done
lemma valid_arch_caps_s0[simp]:
"valid_arch_caps s0_internal"
apply (clarsimp simp: valid_arch_caps_def)
apply (intro conjI)
apply (clarsimp simp: valid_vs_lookup_def vs_lookup_pages_def vs_asid_refs_def
s0_internal_def arch_state0_def)
apply (clarsimp simp: valid_table_caps_def is_pd_cap_def is_pt_cap_def)
apply (drule s0_caps_of_state)
apply (erule disjE | simp)+
apply (clarsimp simp: unique_table_caps_def is_pd_cap_def is_pt_cap_def)
apply (drule s0_caps_of_state)+
apply (erule disjE | simp)+
apply (clarsimp simp: unique_table_refs_def table_cap_ref_def)
apply (drule s0_caps_of_state)+
by auto
lemma valid_global_objs_s0[simp]:
"valid_global_objs s0_internal"
apply (clarsimp simp: valid_global_objs_def s0_internal_def arch_state0_def)
by (force simp: valid_ao_at_def obj_at_def kh0_def kh0_obj_def s0_ptr_defs
addrFromPPtr_def physMappingOffset_def kernelBase_addr_def
physBase_def is_aligned_def a_type_def pageBits_def
kernel_mapping_slots_def empty_table_def pde_ref_def
valid_pde_mappings_def)+
lemma valid_kernel_mappings_s0[simp]:
"valid_kernel_mappings s0_internal"
apply (clarsimp simp: valid_kernel_mappings_def s0_internal_def ran_def
valid_kernel_mappings_if_pd_def split: kernel_object.splits
arch_kernel_obj.splits)
apply (drule kh0_SomeD)
apply (clarsimp simp: arch_state0_def kernel_mapping_slots_def)
apply (erule disjE | simp add: pde_ref_def s0_ptr_defs kh0_obj_def High_pd'_def Low_pd'_def
split: if_split_asm pde.splits)+
done
lemma equal_kernel_mappings_s0[simp]:
"equal_kernel_mappings s0_internal"
apply (clarsimp simp: equal_kernel_mappings_def obj_at_def s0_internal_def)
apply (drule kh0_SomeD)+
by (erule disjE | force simp: kh0_obj_def High_pd'_def Low_pd'_def s0_ptr_defs kernel_mapping_slots_def addrFromPPtr_def physMappingOffset_def kernelBase_addr_def physBase_def)+
lemma valid_asid_map_s0[simp]:
"valid_asid_map s0_internal"
apply (clarsimp simp: valid_asid_map_def s0_internal_def arch_state0_def)
done
lemma valid_global_pd_mappings_s0[simp]:
"valid_global_vspace_mappings s0_internal"
apply (clarsimp simp: valid_global_vspace_mappings_def s0_internal_def arch_state0_def
obj_at_def kh0_def kh0_obj_def s0_ptr_defs valid_pd_kernel_mappings_def
valid_pde_kernel_mappings_def pde_mapping_bits_def mask_def)
apply (rule conjI)
apply force
apply clarsimp
apply (subgoal_tac "xa - 0xFFFFF \<le> ucast x << 20")
apply (case_tac "ucast x << 20 > (0xE0000000::32 word)")
apply (subgoal_tac "(0xE0100000::32 word) \<le> ucast x << 20")
apply ((drule(1) order_trans_rules(23))+, force)
apply (simp add: shiftl_t2n)
apply (cut_tac p="0xE0000000::32 word" and n=20 and m=20 and q="0x100000 * ucast x" in word_plus_power_2_offset_le)
apply (simp add: is_aligned_def)
apply (simp add: is_aligned_def unat_word_ariths)
apply (subst mod_mult_mult1[where c="2^20" and b="2^12", simplified])
apply simp
apply simp
apply simp
apply simp
apply simp
apply (case_tac "ucast x << 20 < (0xE0000000::32 word)")
apply (subgoal_tac "(0xE0000000::32 word) - 0x100000 \<ge> ucast x << 20")
apply (subgoal_tac "0xFFFFF + (ucast x << 20) \<le> 0xDFFFFFFF")
apply (drule_tac y="0xFFFFF + (ucast x << 20)" and z="0xDFFFFFFF::32 word" in order_trans_rules(23))
apply simp
apply ((drule(1) order_trans_rules(23))+, force)
apply (simp add: add.commute
word_plus_mono_left[where x="0xFFFFF" and z="0xDFF00000", simplified])
apply (simp add: shiftl_t2n)
apply (rule udvd_decr'[where K="0x100000" and q="0xE0000000" and ua=0, simplified])
apply simp
apply (simp add: uint_word_ariths)
apply (subst mod_mult_mult1[where c="2^20" and b="2^12", simplified])
apply simp
apply simp
apply simp
apply (erule notE)
apply (cut_tac x="ucast x::32 word" and n=20 in shiftl_shiftr_id)
apply simp
apply (simp add: ucast_less[where 'b=12, simplified])
apply simp
apply (rule ucast_up_inj[where 'b=32])
apply simp
apply simp
apply (drule_tac c="0xFFFFF + (ucast x << 20)" and d="0xFFFFF" and b="0xFFFFF" in word_sub_mono)
apply simp
apply (rule word_sub_le)
apply (rule order_trans_rules(23)[rotated], assumption)
apply simp
apply (simp add: add.commute)
apply (rule no_plus_overflow_neg)
apply simp
apply (drule_tac x="ucast x << 20" in order_trans_rules(23), assumption)
apply (simp add: le_less_trans)
apply simp
done
lemma pspace_in_kernel_window_s0[simp]:
"pspace_in_kernel_window s0_internal"
apply (clarsimp simp: pspace_in_kernel_window_def s0_internal_def)
apply (drule kh0_SomeD)
apply (erule disjE | simp add: arch_state0_def kh0_obj_def s0_ptr_defs mask_def
irq_node_offs_range_def cte_level_bits_def | rule conjI
| rule order_trans_rules(23)[rotated] order_trans_rules(23), force, force)+
apply (force intro: order_trans_rules(23)[rotated])
apply clarsimp
apply (drule_tac x=y in le_less_trans)
apply (rule neq_le_trans[rotated])
apply (rule word_plus_mono_right)
apply (rule less_imp_le)
apply simp+
apply (force intro: less_imp_le less_le_trans)
done
lemma cap_refs_in_kernel_window_s0[simp]:
"cap_refs_in_kernel_window s0_internal"
apply (clarsimp simp: cap_refs_in_kernel_window_def valid_refs_def cap_range_def
Invariants_AI.cte_wp_at_caps_of_state)
apply (drule s0_caps_of_state)
apply (erule disjE | simp add: arch_state0_def s0_internal_def s0_ptr_defs mask_def)+
done
lemma cur_tcb_s0[simp]:
"cur_tcb s0_internal"
by (simp add: cur_tcb_def s0_ptr_defs s0_internal_def kh0_def kh0_obj_def obj_at_def is_tcb_def)
lemma valid_list_s0[simp]:
"valid_list s0_internal"
apply (simp add: valid_list_2_def s0_internal_def exst0_def const_def)
done
lemma valid_sched_s0[simp]:
"valid_sched s0_internal"
apply (simp add: valid_sched_def s0_internal_def exst0_def)
apply (intro conjI)
apply (clarsimp simp: valid_etcbs_def s0_ptr_defs kh0_def kh0_obj_def is_etcb_at'_def
st_tcb_at_kh_def obj_at_kh_def obj_at_def)
apply (clarsimp simp: const_def)
apply (clarsimp simp: const_def)
apply (clarsimp simp: valid_sched_action_def is_activatable_def st_tcb_at_kh_def
obj_at_kh_def obj_at_def kh0_def kh0_obj_def s0_ptr_defs)
apply (clarsimp simp: ct_in_cur_domain_def in_cur_domain_def etcb_at'_def ekh0_obj_def
s0_ptr_defs)
apply (clarsimp simp: const_def valid_blocked_def st_tcb_at_kh_def obj_at_kh_def obj_at_def
kh0_def kh0_obj_def split: if_split_asm)
apply (clarsimp simp: valid_idle_etcb_def etcb_at'_def ekh0_obj_def s0_ptr_defs idle_thread_ptr_def)
done
lemma respects_device_trivial:
"pspace_respects_device_region s0_internal"
"cap_refs_respects_device_region s0_internal"
apply (clarsimp simp: s0_internal_def pspace_respects_device_region_def machine_state0_def device_mem_def
in_device_frame_def kh0_obj_def obj_at_kh_def obj_at_def kh0_def a_type_def
split: if_splits)[1]
apply fastforce
apply (clarsimp simp: cap_refs_respects_device_region_def Invariants_AI.cte_wp_at_caps_of_state
cap_range_respects_device_region_def machine_state0_def)
apply (intro conjI impI)
apply (drule s0_caps_of_state)
apply fastforce
apply (clarsimp simp: s0_internal_def machine_state0_def)
done
lemma einvs_s0:
"einvs s0_internal"
apply (simp add: valid_state_def invs_def respects_device_trivial)
done
lemma obj_valid_pdpt_kh0:
"x \<in> ran kh0 \<Longrightarrow> obj_valid_pdpt x"
by (auto simp: kh0_def valid_entries_def obj_valid_pdpt_def idle_tcb_def High_tcb_def Low_tcb_def
High_pt_def High_pt'_def entries_align_def Low_pt_def High_pd_def Low_pt'_def High_pd'_def
Low_pd_def irq_cnode_def ntfn_def Silc_cnode_def High_cnode_def Low_cnode_def Low_pd'_def)
subsubsection {* Haskell state *}
text {* One invariant we need on s0 is that there exists
an associated Haskell state satisfying the invariants.
This does not yet exist. *}
lemma Sys1_valid_initial_state_noenabled:
assumes extras_s0: "step_restrict s0"
assumes utf_det: "\<forall>pl pr pxn tc um ds es s. det_inv InUserMode tc s \<and> einvs s \<and> context_matches_state pl pr pxn um ds es s \<and> ct_running s
\<longrightarrow> (\<exists>x. utf (cur_thread s) pl pr pxn (tc, um, ds, es) = {x})"
assumes utf_non_empty: "\<forall>t pl pr pxn tc um ds es. utf t pl pr pxn (tc, um, ds, es) \<noteq> {}"
assumes utf_non_interrupt: "\<forall>t pl pr pxn tc um ds es e f g. (e,f,g) \<in> utf t pl pr pxn (tc, um, ds, es) \<longrightarrow> e \<noteq> Some Interrupt"
assumes det_inv_invariant: "invariant_over_ADT_if det_inv utf"
assumes det_inv_s0: "det_inv KernelExit (cur_context s0_internal) s0_internal"
shows "valid_initial_state_noenabled det_inv utf s0_internal Sys1PAS timer_irq s0_context"
apply (unfold_locales, simp_all only: pasMaySendIrqs_Sys1PAS)
apply (insert det_inv_invariant)[9]
apply (erule(2) invariant_over_ADT_if.det_inv_abs_state)
apply (erule invariant_over_ADT_if.det_inv_abs_state
invariant_over_ADT_if.check_active_irq_if_Idle_det_inv
invariant_over_ADT_if.check_active_irq_if_User_det_inv
invariant_over_ADT_if.do_user_op_if_det_inv
invariant_over_ADT_if.handle_preemption_if_det_inv
invariant_over_ADT_if.kernel_entry_if_Interrupt_det_inv
invariant_over_ADT_if.kernel_entry_if_det_inv
invariant_over_ADT_if.kernel_exit_if_det_inv
invariant_over_ADT_if.schedule_if_det_inv)+
apply (simp add: Sys1_pas_cur_domain)
apply (simp add: Sys1_pas_wellformed_noninterference)
apply (simp only: einvs_s0)
apply (simp add: only_timer_irq_inv_s0 silc_inv_s0 Sys1_pas_cur_domain
domain_sep_inv_s0 Sys1_pas_refined Sys1_guarded_pas_domain
idle_equiv_refl)
apply (clarsimp simp: obj_valid_pdpt_kh0 valid_domain_list_2_def s0_internal_def exst0_def)
apply (simp add: det_inv_s0)
apply (simp add: s0_internal_def exst0_def)
apply (simp add: ct_in_state_def st_tcb_at_tcb_states_of_state_eq
identity_eq[symmetric] tcb_states_of_state_s0)
apply (simp add: s0_ptr_defs s0_internal_def)
apply (simp add: s0_internal_def exst0_def)
apply (simp add: num_domains_def)
apply (rule utf_det)
apply (rule utf_non_empty)
apply (rule utf_non_interrupt)
apply (simp add: extras_s0[simplified s0_def])
done
text {* the extra assumptions in valid_initial_state of being enabled,
and a serial system, follow from ADT_IF_Refine *}
end
end
|
The first publication to address cytogenetics and prognosis was the MRC trial of 1998 :
|
# To load a matlab data
using MAT
function load_data()
#=
This function loads the training, validation and test datas.
Finally it returns all the needed data for traing and test datas
Here are the dimensions:
train_input = <number_of_futures:256> by <number of training cases>
train_target = sparse vector for each training case <10> by <number of training cases>
test_input = <number_of_futures:256> by <number of test cases>
test_target = <10> by <number of training cases>
----
=#
file = matopen("data.mat")
data = read(file, "data")
# Load the training data
train_input = data["training"]["inputs"]
train_target = data["training"]["targets"]
# Load the validation data
valid_input = data["validation"]["inputs"]
valid_target = data["validation"]["targets"]
# Load the test data
test_input = data["test"]["inputs"]
test_target = data["test"]["targets"]
return (train_input,
train_target,
valid_input,
valid_target,
test_input,
test_target)
end
|
Be the first to receive new content and special promotions.
© Copyright 2018, Caroline Wright. All Rights Reserved. Images and text may not be reproduced without permission.
on New Work, Shows, Sales & Musings!
and get a super-deal on your first paper print!
Enter your email below I'll email your coupon right now!
|
(* Title: HOL/Auth/n_g2kAbsAfter_lemma_on_inv__54.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_g2kAbsAfter Protocol Case Study*}
theory n_g2kAbsAfter_lemma_on_inv__54 imports n_g2kAbsAfter_base
begin
section{*All lemmas on causal relation between inv__54 and some rule r*}
lemma n_n_SendInvE_i1Vsinv__54:
assumes a1: "(r=n_n_SendInvE_i1 )" and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P3 s"
apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Ident ''InvSet_1'')) (Const true)) (eqn (IVar (Field (Ident ''AChan2_1'') ''Cmd'')) (Const GntE))))" in exI, auto) done
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_SendInvS_i1Vsinv__54:
assumes a1: "(r=n_n_SendInvS_i1 )" and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P3 s"
apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Ident ''InvSet_1'')) (Const true)) (eqn (IVar (Field (Ident ''AChan2_1'') ''Cmd'')) (Const GntE))))" in exI, auto) done
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_SendInvAck_i1Vsinv__54:
assumes a1: "(r=n_n_SendInvAck_i1 )" and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_SendGntS_i1Vsinv__54:
assumes a1: "(r=n_n_SendGntS_i1 )" and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_SendGntE_i1Vsinv__54:
assumes a1: "(r=n_n_SendGntE_i1 )" and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_RecvGntS_i1Vsinv__54:
assumes a1: "(r=n_n_RecvGntS_i1 )" and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_RecvGntE_i1Vsinv__54:
assumes a1: "(r=n_n_RecvGntE_i1 )" and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_ASendInvE_i1Vsinv__54:
assumes a1: "(r=n_n_ASendInvE_i1 )" and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_ASendInvS_i1Vsinv__54:
assumes a1: "(r=n_n_ASendInvS_i1 )" and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_ASendInvAck_i1Vsinv__54:
assumes a1: "(r=n_n_ASendInvAck_i1 )" and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_ASendGntS_i1Vsinv__54:
assumes a1: "(r=n_n_ASendGntS_i1 )" and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_ASendGntE_i1Vsinv__54:
assumes a1: "(r=n_n_ASendGntE_i1 )" and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P3 s"
apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Ident ''Chan2_1'') ''Cmd'')) (Const Inv)) (eqn (IVar (Ident ''ShrSet_1'')) (Const false))))" in exI, auto) done
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_ARecvGntS_i1Vsinv__54:
assumes a1: "(r=n_n_ARecvGntS_i1 )" and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_ARecvGntE_i1Vsinv__54:
assumes a1: "(r=n_n_ARecvGntE_i1 )" and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_RecvReq_i1Vsinv__54:
assumes a1: "r=n_n_RecvReq_i1 " and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_SendReqEI_i1Vsinv__54:
assumes a1: "r=n_n_SendReqEI_i1 " and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_ASendReqEI_i1Vsinv__54:
assumes a1: "r=n_n_ASendReqEI_i1 " and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_ASendReqIS_j1Vsinv__54:
assumes a1: "r=n_n_ASendReqIS_j1 " and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_ASendReqES_i1Vsinv__54:
assumes a1: "r=n_n_ASendReqES_i1 " and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_SendReqES_i1Vsinv__54:
assumes a1: "r=n_n_SendReqES_i1 " and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_ASendReqSE_j1Vsinv__54:
assumes a1: "r=n_n_ASendReqSE_j1 " and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_SendReqEE_i1Vsinv__54:
assumes a1: "r=n_n_SendReqEE_i1 " and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_RecvInvAck_i1Vsinv__54:
assumes a1: "r=n_n_RecvInvAck_i1 " and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_ARecvReq_i1Vsinv__54:
assumes a1: "r=n_n_ARecvReq_i1 " and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_Store_i1Vsinv__54:
assumes a1: "\<exists> d. d\<le>N\<and>r=n_n_Store_i1 d" and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_AStore_i1Vsinv__54:
assumes a1: "\<exists> d. d\<le>N\<and>r=n_n_AStore_i1 d" and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_SendReqS_j1Vsinv__54:
assumes a1: "r=n_n_SendReqS_j1 " and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_ARecvInvAck_i1Vsinv__54:
assumes a1: "r=n_n_ARecvInvAck_i1 " and
a2: "(f=inv__54 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
```python
import sympy as sym
from scipy import integrate
import numpy as np
import matplotlib.pyplot as plt
```
```python
S, I, R = sym.Function("S"), sym.Function("I"), sym.Function("V")
N, mu, alpha, beta, t = sym.symbols("N, mu, alpha, beta, t")
```
```python
eq1 = sym.Derivative(S(t), t) - (- alpha * S(t) * I(t) - mu * R(t))
eq2 = sym.Derivative(I(t), t) - (alpha * I(t) * S(t) / N - beta * I(t))
eq3 = sym.Derivative(R(t), t) - (beta * I(t) + mu * R(t))
```
```python
sym.dsolve((eq1, eq2, eq3))
```
Further investigation shows that an exact solution to this system of differential equations is difficult. Let us do this numerically:
```python
def dx(x, t, alpha, beta, mu):
return (- alpha * x[1] * x[0] - mu * x[0],
alpha * x[1] * x[0] - beta * x[1],
beta * x[1] + mu * x[0])
```
```python
alpha = 1 / 1000 # Every 1000 interactions leads to infection
beta = 1 / 5 # take 5 time units to recover
N = 10 ** 4 # Population of 10 thousand people
mu = 0 # 0 vaccination percentage
ts = np.linspace(0, 10, 5000)
xs = integrate.odeint(func=dx, y0=np.array([N - 1, 1, 0]), t=ts, args=(alpha, beta, mu))
S, I, R = xs.T
plt.figure()
plt.plot(ts, S, label="Susceptibles")
plt.plot(ts, I, label="Infected")
plt.plot(ts, R, label="Recovered")
plt.legend()
plt.title(f"$\max(I)={round(max(I))}$ ($\\alpha={alpha}$, $\\beta={beta}$, $\mu={mu}$)")
plt.savefig("base_scenario.pdf");
```
```python
mu = 1 / 2 # Vaccinate half the population
ts = np.linspace(0, 10, 5000)
xs = integrate.odeint(func=dx, y0=np.array([N - 1, 1, 0]), t=ts, args=(alpha, beta, mu))
S, I, R = xs.T
plt.figure()
plt.plot(ts, S, label="Susceptibles")
plt.plot(ts, I, label="Infected")
plt.plot(ts, R, label="Recovered")
plt.legend()
plt.title(f"$\max(I)={round(max(I))}$ ($\\alpha={alpha}$, $\\beta={beta}$, $\mu={mu}$)")
plt.savefig("moderate_vaccination_rate.pdf");
```
```python
mu = 99 / 100 # Vaccinate 99% of the population
ts = np.linspace(0, 10, 5000)
xs = integrate.odeint(func=dx, y0=np.array([N - 1, 1, 0]), t=ts, args=(alpha, beta, mu))
S, I, R = xs.T
plt.figure()
plt.plot(ts, S, label="Susceptibles")
plt.plot(ts, I, label="Infected")
plt.plot(ts, R, label="Recovered")
plt.legend()
plt.title(f"$\max(I)={round(max(I))}$ ($\\alpha={alpha}$, $\\beta={beta}$, $\mu={mu}$)")
plt.savefig("high_vaccination_rate.pdf");
```
```python
vaccination_rates = np.linspace(0, 1, 500)
max_percent_of_infected = []
for mu in vaccination_rates:
xs = integrate.odeint(func=dx, y0=np.array([N - 1, 1, 0]), t=ts, args=(alpha, beta, mu))
S, I, R = xs.T
max_percent_of_infected.append(max(I) / N)
plt.figure()
plt.plot(vaccination_rates, max_percent_of_infected)
plt.xlabel("$\mu$")
plt.ylabel("% of population infected")
plt.savefig("effect_of_vaccination_rate.pdf");
```
|
Formal statement is: lemma closure_bounded_linear_image: fixes f :: "'a::euclidean_space \<Rightarrow> 'b::euclidean_space" shows "\<lbrakk>linear f; bounded S\<rbrakk> \<Longrightarrow> f ` (closure S) = closure (f ` S)" Informal statement is: If $f$ is a linear map and $S$ is a bounded set, then the image of the closure of $S$ under $f$ is the closure of the image of $S$ under $f$.
|
||| Courtesy of @z-snails
module Core.Ord
import Core.CompileExpr
import Core.Name
import Core.TT
import Data.Vect
infixl 5 `thenCmp`
thenCmp : Ordering -> Lazy Ordering -> Ordering
thenCmp LT _ = LT
thenCmp EQ o = o
thenCmp GT _ = GT
export
Ord Constant where
I x `compare` I y = compare x y
I8 x `compare` I8 y = compare x y
I16 x `compare` I16 y = compare x y
I32 x `compare` I32 y = compare x y
I64 x `compare` I64 y = compare x y
BI x `compare` BI y = compare x y
B8 x `compare` B8 y = compare x y
B16 x `compare` B16 y = compare x y
B32 x `compare` B32 y = compare x y
B64 x `compare` B64 y = compare x y
Str x `compare` Str y = compare x y
Ch x `compare` Ch y = compare x y
Db x `compare` Db y = compare x y
compare x y = compare (tag x) (tag y)
where
tag : Constant -> Int
tag (I _) = 0
tag (I8 _) = 1
tag (I16 _) = 2
tag (I32 _) = 3
tag (I64 _) = 4
tag (BI _) = 5
tag (B8 _) = 6
tag (B16 _) = 7
tag (B32 _) = 8
tag (B64 _) = 9
tag (Str _) = 10
tag (Ch _) = 11
tag (Db _) = 12
tag WorldVal = 13
tag IntType = 14
tag Int8Type = 15
tag Int16Type = 16
tag Int32Type = 17
tag Int64Type = 18
tag IntegerType = 19
tag Bits8Type = 20
tag Bits16Type = 21
tag Bits32Type = 22
tag Bits64Type = 23
tag StringType = 24
tag CharType = 25
tag DoubleType = 26
tag WorldType = 27
primFnEq : PrimFn a1 -> PrimFn a2 -> Maybe (a1 = a2)
primFnEq (Add t1) (Add t2) = if t1 == t2 then Just Refl else Nothing
primFnEq (Sub t1) (Sub t2) = if t1 == t2 then Just Refl else Nothing
primFnEq (Mul t1) (Mul t2) = if t1 == t2 then Just Refl else Nothing
primFnEq (Div t1) (Div t2) = if t1 == t2 then Just Refl else Nothing
primFnEq (Mod t1) (Mod t2) = if t1 == t2 then Just Refl else Nothing
primFnEq (Neg t1) (Neg t2) = if t1 == t2 then Just Refl else Nothing
primFnEq (ShiftL t1) (ShiftL t2) = if t1 == t2 then Just Refl else Nothing
primFnEq (ShiftR t1) (ShiftR t2) = if t1 == t2 then Just Refl else Nothing
primFnEq (BAnd t1) (BAnd t2) = if t1 == t2 then Just Refl else Nothing
primFnEq (BOr t1) (BOr t2) = if t1 == t2 then Just Refl else Nothing
primFnEq (BXOr t1) (BXOr t2) = if t1 == t2 then Just Refl else Nothing
primFnEq (LT t1) (LT t2) = if t1 == t2 then Just Refl else Nothing
primFnEq (LTE t1) (LTE t2) = if t1 == t2 then Just Refl else Nothing
primFnEq (EQ t1) (EQ t2) = if t1 == t2 then Just Refl else Nothing
primFnEq (GTE t1) (GTE t2) = if t1 == t2 then Just Refl else Nothing
primFnEq (GT t1) (GT t2) = if t1 == t2 then Just Refl else Nothing
primFnEq StrLength StrLength = Just Refl
primFnEq StrHead StrHead = Just Refl
primFnEq StrTail StrTail = Just Refl
primFnEq StrIndex StrIndex = Just Refl
primFnEq StrCons StrCons = Just Refl
primFnEq StrAppend StrAppend = Just Refl
primFnEq StrReverse StrReverse = Just Refl
primFnEq StrSubstr StrSubstr = Just Refl
primFnEq DoubleExp DoubleExp = Just Refl
primFnEq DoubleLog DoubleLog = Just Refl
primFnEq DoublePow DoublePow = Just Refl
primFnEq DoubleSin DoubleSin = Just Refl
primFnEq DoubleCos DoubleCos = Just Refl
primFnEq DoubleTan DoubleTan = Just Refl
primFnEq DoubleASin DoubleASin = Just Refl
primFnEq DoubleACos DoubleACos = Just Refl
primFnEq DoubleATan DoubleATan = Just Refl
primFnEq DoubleSqrt DoubleSqrt = Just Refl
primFnEq DoubleFloor DoubleFloor = Just Refl
primFnEq DoubleCeiling DoubleCeiling = Just Refl
primFnEq (Cast f1 t1) (Cast f2 t2) = if f1 == f2 && t1 == t2 then Just Refl else Nothing
primFnEq BelieveMe BelieveMe = Just Refl
primFnEq Crash Crash = Just Refl
primFnEq _ _ = Nothing
primFnCmp : PrimFn a1 -> PrimFn a2 -> Ordering
primFnCmp (Add t1) (Add t2) = compare t1 t2
primFnCmp (Sub t1) (Sub t2) = compare t1 t2
primFnCmp (Mul t1) (Mul t2) = compare t1 t2
primFnCmp (Div t1) (Div t2) = compare t1 t2
primFnCmp (Mod t1) (Mod t2) = compare t1 t2
primFnCmp (Neg t1) (Neg t2) = compare t1 t2
primFnCmp (ShiftL t1) (ShiftL t2) = compare t1 t2
primFnCmp (ShiftR t1) (ShiftR t2) = compare t1 t2
primFnCmp (BAnd t1) (BAnd t2) = compare t1 t2
primFnCmp (BOr t1) (BOr t2) = compare t1 t2
primFnCmp (BXOr t1) (BXOr t2) = compare t1 t2
primFnCmp (LT t1) (LT t2) = compare t1 t2
primFnCmp (LTE t1) (LTE t2) = compare t1 t2
primFnCmp (EQ t1) (EQ t2) = compare t1 t2
primFnCmp (GTE t1) (GTE t2) = compare t1 t2
primFnCmp (GT t1) (GT t2) = compare t1 t2
primFnCmp (Cast f1 t1) (Cast f2 t2) = compare f1 f2 `thenCmp` compare t1 t2
primFnCmp f1 f2 = compare (tag f1) (tag f2)
where
tag : forall ar. PrimFn ar -> Int
tag (Add _) = 0
tag (Sub _) = 1
tag (Mul _) = 2
tag (Div _) = 3
tag (Mod _) = 4
tag (Neg _) = 5
tag (ShiftL _) = 6
tag (ShiftR _) = 7
tag (BAnd _) = 8
tag (BOr _) = 9
tag (BXOr _) = 10
tag (LT _) = 11
tag (LTE _) = 12
tag (EQ _) = 13
tag (GTE _) = 14
tag (GT _) = 15
tag StrLength = 16
tag StrHead = 17
tag StrTail = 18
tag StrIndex = 19
tag StrCons = 20
tag StrAppend = 21
tag StrReverse = 22
tag StrSubstr = 23
tag DoubleExp = 24
tag DoubleLog = 25
tag DoublePow = 26
tag DoubleSin = 27
tag DoubleCos = 28
tag DoubleTan = 29
tag DoubleASin = 30
tag DoubleACos = 31
tag DoubleATan = 32
tag DoubleSqrt = 33
tag DoubleFloor = 34
tag DoubleCeiling = 35
tag (Cast _ _) = 36
tag BelieveMe = 37
tag Crash = 38
lrTag : LazyReason -> Int
lrTag LInf = 0
lrTag LLazy = 1
lrTag LUnknown = 2
export
Ord LazyReason where
compare l1 l2 = compare (lrTag l1) (lrTag l2)
export
Eq (Var vars) where
MkVar {i=i1} _ == MkVar {i=i2} _ = i1 == i2
export
Ord (Var vars) where
MkVar {i=i1} _ `compare` MkVar {i=i2} _ = compare i1 i2
mutual
export
Eq (CExp vars) where
CLocal {idx=x1} _ _ == CLocal {idx=x2} _ _ = x1 == x2
CRef _ n1 == CRef _ n2 = n1 == n2
CLam _ n1 e1 == CLam _ n2 e2 = case nameEq n1 n2 of
Just Refl => e1 == e2
Nothing => False
CLet _ n1 _ val1 sc1 == CLet _ n2 _ val2 sc2 = case nameEq n1 n2 of
Just Refl => val1 == val2 && sc1 == sc2
Nothing => False
CApp _ f1 a1 == CApp _ f2 a2 = f1 == f2 && a1 == a2
CCon _ n1 _ t1 a1 == CCon _ n2 _ t2 a2 = t1 == t2 && n1 == n2 && a1 == a2
COp _ f1 a1 == COp _ f2 a2 = case primFnEq f1 f2 of
Just Refl => a1 == a2
Nothing => False
CExtPrim _ f1 a1 == CExtPrim _ f2 a2 = f1 == f2 && a1 == a2
CForce _ l1 e1 == CForce _ l2 e2 = l1 == l2 && e1 == e2
CDelay _ l1 e1 == CDelay _ l2 e2 = l1 == l2 && e1 == e2
CConCase _ s1 a1 d1 == CConCase _ s2 a2 d2 = s1 == s2 && a1 == a2 && d1 == d2
CConstCase _ s1 a1 d1 == CConstCase _ s2 a2 d2 = s1 == s2 && a1 == a2 && d1 == d2
CPrimVal _ c1 == CPrimVal _ c2 = c1 == c2
CErased _ == CErased _ = True
CCrash _ m1 == CCrash _ m2 = m1 == m2
_ == _ = False
export
Eq (CConAlt vars) where
MkConAlt n1 _ t1 a1 e1 == MkConAlt n2 _ t2 a2 e2 = t1 == t2 && n1 == n2 && case namesEq a1 a2 of
Just Refl => e1 == e2
Nothing => False
export
Eq (CConstAlt vars) where
MkConstAlt c1 e1 == MkConstAlt c2 e2 = c1 == c2 && e1 == e2
mutual
export
Ord (CExp vars) where
CLocal {idx=x1} _ _ `compare` CLocal {idx=x2} _ _ = x1 `compare` x2
CRef _ n1 `compare` CRef _ n2 = n1 `compare` n2
CLam _ n1 e1 `compare` CLam _ n2 e2 = case nameEq n1 n2 of
Just Refl => compare e1 e2
Nothing => compare n1 n2
CLet _ n1 _ val1 sc1 `compare` CLet _ n2 _ val2 sc2 = case nameEq n1 n2 of
Just Refl => compare val1 val2 `thenCmp` compare sc1 sc2
Nothing => compare n1 n2
CApp _ f1 a1 `compare` CApp _ f2 a2 = compare f1 f2 `thenCmp` compare a1 a2
CCon _ n1 _ t1 a1 `compare` CCon _ n2 _ t2 a2 = compare t1 t2 `thenCmp` compare n1 n2 `thenCmp` compare a1 a2
COp _ f1 a1 `compare` COp _ f2 a2 = case primFnEq f1 f2 of
Just Refl => compare a1 a2
Nothing => primFnCmp f1 f2
CExtPrim _ f1 a1 `compare` CExtPrim _ f2 a2 = compare f1 f2 `thenCmp` compare a1 a2
CForce _ l1 e1 `compare` CForce _ l2 e2 = compare l1 l2 `thenCmp` compare e1 e2
CDelay _ l1 e1 `compare` CDelay _ l2 e2 = compare l1 l2 `thenCmp` compare e1 e2
CConCase _ s1 a1 d1 `compare` CConCase _ s2 a2 d2 = compare s1 s2 `thenCmp` compare a1 a2 `thenCmp` compare d1 d2
CConstCase _ s1 a1 d1 `compare` CConstCase _ s2 a2 d2 = compare s1 s2 `thenCmp` compare a1 a2 `thenCmp` compare d1 d2
CPrimVal _ c1 `compare` CPrimVal _ c2 = compare c1 c2
CErased _ `compare` CErased _ = EQ
CCrash _ m1 `compare` CCrash _ m2 = compare m1 m2
e1 `compare` e2 = compare (tag e1) (tag e2)
where
tag : forall vars . CExp vars -> Int
tag (CLocal _ _) = 0
tag (CRef _ _) = 1
tag (CLam _ _ _) = 2
tag (CLet _ _ _ _ _) = 3
tag (CApp _ _ _) = 4
tag (CCon _ _ _ _ _) = 5
tag (COp _ _ _) = 6
tag (CExtPrim _ _ _) = 7
tag (CForce _ _ _) = 8
tag (CDelay _ _ _) = 9
tag (CConCase _ _ _ _) = 10
tag (CConstCase _ _ _ _) = 11
tag (CPrimVal _ _) = 12
tag (CErased _) = 13
tag (CCrash _ _) = 14
export
Ord (CConAlt vars) where
MkConAlt n1 _ t1 a1 e1 `compare` MkConAlt n2 _ t2 a2 e2 =
compare t1 t2 `thenCmp` compare n1 n2 `thenCmp` case namesEq a1 a2 of
Just Refl => compare e1 e2
Nothing => compare a1 a2
export
Ord (CConstAlt vars) where
MkConstAlt c1 e1 `compare` MkConstAlt c2 e2 = compare c1 c2 `thenCmp` compare e1 e2
|
Hi loves! We cant wait to share this inspire-board! It has Awesoneness written all over it! We just can't help it - we thought these charteuse green and white are the perfect palette season for your wedding! So brides - never think green as dull as you can always mix few tones of similar palette in a theme. Green are amongst the nicest (easy to pull it off) user friendly and flexible color. See how pretty these colors altogether? It creates a simple vintage theme; check out the rustic barn to a modern loft.
WOW! I`m speechless! Great photos!
|
// Copyright (c) 2016 Klemens D. Morgenstern
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_PROCESS_DETAIL_POSIX_HANDLER_HPP_
#define BOOST_PROCESS_DETAIL_POSIX_HANDLER_HPP_
#include <boost/process/detail/handler_base.hpp>
namespace boost { namespace process { namespace detail { namespace posix {
//does not extend anything.
struct handler_base_ext : handler_base
{
template<typename Executor>
void on_fork_error (Executor &, const std::error_code&) const {}
template<typename Executor>
void on_exec_setup (Executor &) const {}
template<typename Executor>
void on_exec_error (Executor &, const std::error_code&) const {}
};
template <class Handler>
struct on_fork_error_ : handler_base_ext
{
explicit on_fork_error_(Handler handler) : handler_(handler) {}
template <class Executor>
void on_fork_error(Executor &e, const std::error_code &ec) const
{
handler_(e, ec);
}
private:
Handler handler_;
};
template <class Handler>
struct on_exec_setup_ : handler_base_ext
{
explicit on_exec_setup_(Handler handler) : handler_(handler) {}
template <class Executor>
void on_exec_setup(Executor &e) const
{
handler_(e);
}
private:
Handler handler_;
};
template <class Handler>
struct on_exec_error_ : handler_base_ext
{
explicit on_exec_error_(Handler handler) : handler_(handler) {}
template <class Executor>
void on_exec_error(Executor &e, const std::error_code &ec) const
{
handler_(e, ec);
}
private:
Handler handler_;
};
}}}}
#endif /* BOOST_PROCESS_DETAIL_POSIX_HANDLER_HPP_ */
|
C$Procedure SPHSD ( Spherical surface distance )
DOUBLE PRECISION FUNCTION SPHSD ( RADIUS, LONG1, LAT1,
. LONG2, LAT2 )
C$ Abstract
C
C Return the distance between two points on a sphere, measured
C along the shortest great circle arc connecting them.
C
C$ Disclaimer
C
C THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE
C CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S.
C GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE
C ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE
C PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS"
C TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY
C WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A
C PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC
C SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE
C SOFTWARE AND RELATED MATERIALS, HOWEVER USED.
C
C IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA
C BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT
C LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND,
C INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS,
C REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE
C REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY.
C
C RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF
C THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY
C CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE
C ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE.
C
C$ Required_Reading
C
C None.
C
C$ Keywords
C
C GEOMETRY
C
C$ Declarations
DOUBLE PRECISION RADIUS
DOUBLE PRECISION LONG1
DOUBLE PRECISION LAT1
DOUBLE PRECISION LONG2
DOUBLE PRECISION LAT2
C$ Brief_I/O
C
C VARIABLE I/O DESCRIPTION
C -------- --- --------------------------------------------------
C RADIUS I Radius of sphere.
C LONG1,
C LAT1 I Longitude and latitude of first point in radians.
C LONG2,
C LAT2 I Longitude and latitude of second point in radians.
C
C The function returns the distance between the two input points,
C measured along the shortest great circle arc connecting them.
C
C$ Detailed_Input
C
C RADIUS Radius of the sphere on which the points are
C located.
C
C LONG1,
C LAT1 Longitude and latitude of the first point. The
C units are radians.
C
C LONG2,
C LAT2 Longitude and latitude of the second point. The
C units are radians.
C
C$ Detailed_Output
C
C The function returns the distance between the two input points,
C measured along the shortest great circle arc connecting them.
C
C$ Parameters
C
C None.
C
C$ Exceptions
C
C 1) If RADIUS is negative, the error SPICE(INPUTOUTOFRANGE)
C is signalled. SPHSD is set to zero. RADIUS may be zero;
C this case is not treated as an exception.
C
C 2) Latitudes out of the range [-pi/2, pi/2] are NOT treated
C as errors, although they are not valid in the latitudinal
C coordinate system and so may be considered to be exceptional
C inputs. All latitude values are used in the same way in the
C computation, regardless of whether or not they are in range.
C See the code for the equation used.
C
C 3) Longitudes out of the range (-pi, pi] are NOT treated
C as errors, although they are not valid in the latitudinal
C coordinate system and so may be considered to be exceptional
C inputs. All longitude values are used in the same way in the
C computation, regardless of whether or not they are in range.
C See the code for the equation used.
C
C$ Files
C
C None.
C
C$ Particulars
C
C You may need to consider whether a spherical model is adequate
C for your application; some bodies may be more accurately modelled
C by an oblate or prolate spheroid, or by a triaxial ellipsoid.
C
C$ Examples
C
C 1) To find the distance along a sphere of radius 1000 km between
C the points at
C
C longitude = 1.570796326794897D0 (pi/2) radians,
C latitude = 7.853981633974483D-1 (pi/4) radians
C
C and
C
C longitude = 0.0D0 radians,
C latitude = 7.853981633974483D-1 (pi/4) radians,
C
C we could make the function call:
C
C DIST = SPHSD ( 1.0D3,
C . 1.570796326794897D0, 7.853981633974483D-1,
C . 0.D0, 7.853981633974483D-1 )
C
C The value of DIST should be
C
C 1.047197551196598D3,
C
C which is (very, very close to) 1000 * pi/3.
C
C The exact numbers used in this example were obtained using
C VAX Fortran 77 on a VAX 11/780; different compilers and
C systems may yield different results.
C
C$ Restrictions
C
C None.
C
C$ Literature_References
C
C None.
C
C$ Author_and_Institution
C
C H.A. Neilan (JPL)
C N.J. Bachman (JPL)
C
C$ Version
C
C- SPICELIB Version 1.1.0, 17-MAY-1994 (HAN)
C
C If the value of the function RETURN is TRUE upon execution of
C this module, this function is assigned a default value of
C either 0, 0.0D0, .FALSE., or blank depending on the type of
C the function.
C
C- SPICELIB Version 1.0.1, 10-MAR-1992 (WLT)
C
C Comment section for permuted index source lines was added
C following the header.
C
C- SPICELIB Version 1.0.0, 01-NOV-1990 (NJB)
C
C-&
C$ Index_Entries
C
C spherical surface distance
C
C-&
C
C SPICELIB functions
C
DOUBLE PRECISION BRCKTD
LOGICAL RETURN
C
C Local variables
C
DOUBLE PRECISION SL1SL2
DOUBLE PRECISION COSANG
C
C Check RETURN but do not check in unless an error is detected.
C
IF ( RETURN() ) THEN
SPHSD = 0.0D0
RETURN
END IF
C
C Make sure that RADIUS is ok; check in only if it isn't.
C
IF ( RADIUS .LT. 0 ) THEN
SPHSD = 0.D0
CALL CHKIN ( 'SPHSD' )
CALL SETMSG ( 'Radius was #.' )
CALL ERRDP ( '#', RADIUS )
CALL SIGERR ( 'SPICE(VALUEOUTOFRANGE)' )
CALL CHKOUT ( 'SPHSD' )
RETURN
END IF
C
C The usual equation for the distance between points, measured
C along a great circle, is:
C
C -1
C DIST = COS ( ( COS(LONG1-LONG2) * COS(LAT1) * COS(LAT2) )
C + ( SIN(LAT1) * SIN(LAT2) ) )
C
C * RADIUS
C
C To arrive at this equation, we find the cartesian coordinates of
C the input surface points and take the dot product of the two
C points.
C
C To save a trig function reference, however, we implement this
C calculation slightly differently.
C
C
C COSANG is the cosine of the angle between the two position
C vectors. We bracket COSANG 'tween -1 and 1 to make sure
C round-off error doesn't take it out of the domain of arc
C cosine...
C
SL1SL2 = SIN ( LAT1 ) * SIN ( LAT2 )
COSANG = COS ( LONG1 - LONG2 )
. * ( COS ( LAT1 - LAT2 ) - SL1SL2 )
. + SL1SL2
SPHSD = RADIUS * ACOS ( BRCKTD ( COSANG, -1.D0, 1.D0 ) )
RETURN
END
|
function φmin(u::Point{d},v::Point{d}) where d
sq = sqrt.(u.^2+v.^2)
# p = (u+v-sq)/2
# J_u = (1 .- u./sq)/2
# J_v = (1 .- v./sq)/2
p = SVector{d}( (v[i]<Inf ? (u[i]+v[i]-sq[i])/2 : u[i]) for i=1:d )
J_u = SVector{d}( (v[i]<Inf ? (1.0 - u[i]./sq[i])/2 : 1) for i=1:d )
J_v = SVector{d}( (v[i]<Inf ? (1.0 - v[i]./sq[i])/2 : 0) for i=1:d )
return p, SDiagonal(J_u), SDiagonal(J_v)
end
function φmax(u::Point{d},v::Point{d}) where d
sq = sqrt.(u.^2+v.^2)
# p = (u+v+sq)/2
# J_u = (1 .+ u./sq)/2
# J_v = (1 .+ v./sq)/2
p = SVector{d}( (v[i]>-Inf ? (u[i]+v[i]+sq[i])/2 : u[i]) for i=1:d )
J_u = SVector{d}( (v[i]>-Inf ? (1.0 + u[i]./sq[i])/2 : 1) for i=1:d )
J_v = SVector{d}( (v[i]>-Inf ? (1.0 + v[i]./sq[i])/2 : 0) for i=1:d )
return p, SDiagonal(J_u), SDiagonal(J_v)
end
function PhiPhi(f::Point{d}, x::Point{d}, a::Point{d}, b::Point{d}) where d
y, y_f, y_x = φmin(f,x-a)
z, z_y, z_x = φmax(y,x-b)
return z, (z_y*y_f), (z_y*y_x + z_x)
end
function PhiPhi0(f::Point{d}, x::Point{d}, a::Point{d}, b::Point{d}) where d
y = φmin(f,x-a)[1]
z = φmax(y,x-b)[1]
return z
end
function PhiPhi(f::Point{d}, D::SMatrix{d,d,Float64,q}, x::Point{d}, a::Point{d}, b::Point{d}) where d where q
z, z_f, z_x = PhiPhi(f,x,a,b)
z, z_f*D + z_x
end
function PhiPhi!(F::Vector{Vector{Point{d}}},
X::Vector{Vector{Point{d}}},
A::Vector{Vector{Point{d}}},
B::Vector{Vector{Point{d}}},
D::Vector{v},
J::Matrix{w}) where v<:AbstractVector{SMatrix{d,d,Float64,q}} where w<:AbstractVector{SMatrix{d,d,Float64,q}} where d where q
n_m, n_M = size(J)
N = length(F[1])
for i=1:n_m
for n=1:N
f = F[i][n]
x = X[i][n]
a = A[i][n]
b = B[i][n]
z, z_f, z_x = PhiPhi(f,x,a,b)
F[i][n] = z
D[i][n] = z_f*D[i][n] + z_x
for j=1:n_M
J[i,j][n] = z_f*J[i,j][n]
end
end
end
end
function PhiPhi!(F::Vector{<:AbstractVector{Point{d}}},
X::Vector{<:AbstractVector{Point{d}}},
A::Vector{<:AbstractVector{Point{d}}},
B::Vector{<:AbstractVector{Point{d}}},
J::Matrix{w}) where w<:AbstractVector{SMatrix{d,d,Float64,q}} where d where q
n_m, n_M = size(J)
N = length(F[1])
for i=1:n_m
for n=1:N
f = F[i][n]
x = X[i][n]
a = A[i][n]
b = B[i][n]
z, z_f, z_x = PhiPhi(f,x,a,b)
F[i][n] = z
for j=1:n_M
J[i,j][n] = z_f*J[i,j][n]
end
end
end
end
function PhiPhi!(F::Vector{Vector{Point{d}}},
X::Vector{Vector{Point{d}}},
A::Vector{Vector{Point{d}}},
B::Vector{Vector{Point{d}}},
D::Vector{v}) where v<:AbstractVector{SMatrix{d,d,Float64,q}} where d where q
n_m = size(D,1)
N = length(F[1])
for i=1:n_m
for n=1:N
f = F[i][n]
x = X[i][n]
a = A[i][n]
b = B[i][n]
z, z_f, z_x = PhiPhi(f,x,a,b)
F[i][n] = z
D[i][n] = z_f*D[i][n] + z_x
end
end
end
function PhiPhi(F::Vector{Vector{Point{d}}},X::Vector{Vector{Point{d}}},A::Vector{Vector{Point{d}}},B::Vector{Vector{Point{d}}},D::Vector{Vector{SMatrix{d,d,Float64,q}}}, J::Matrix{Vector{SMatrix{d,d,Float64,q}}}) where d where q
FF = deepcopy(F)
DD = deepcopy(D)
JJ = deepcopy(J)
PhiPhi!(FF,X,A,B,DD,JJ)
return FF,DD,JJ
end
|
[GOAL]
α : Type u
β : Type v
f fa g : α → α
x✝ y : α
fb : β → β
m n k : ℕ
e : Perm α
x : α
hx : IsFixedPt f x
⊢ IsFixedPt f (f x)
[PROOFSTEP]
convert hx
[GOAL]
α : Type u
β : Type v
f fa g : α → α
x y : α
fb : β → β
m n✝ k : ℕ
e : Perm α
s : Set α
h : IsFixedPt (Set.preimage f) s
n : ℕ
⊢ IsFixedPt (Set.preimage f^[n]) s
[PROOFSTEP]
rw [Set.preimage_iterate_eq]
[GOAL]
α : Type u
β : Type v
f fa g : α → α
x y : α
fb : β → β
m n✝ k : ℕ
e : Perm α
s : Set α
h : IsFixedPt (Set.preimage f) s
n : ℕ
⊢ IsFixedPt (Set.preimage f)^[n] s
[PROOFSTEP]
exact h.iterate n
[GOAL]
α : Type u
β : Type v
f fa g : α → α
x y : α
fb : β → β
m n✝ k : ℕ
e : Perm α
h : IsFixedPt (↑e) x
n : ℕ
⊢ IsFixedPt (↑(e ^ n)) x
[PROOFSTEP]
rw [Equiv.Perm.coe_pow]
[GOAL]
α : Type u
β : Type v
f fa g : α → α
x y : α
fb : β → β
m n✝ k : ℕ
e : Perm α
h : IsFixedPt (↑e) x
n : ℕ
⊢ IsFixedPt (↑e)^[n] x
[PROOFSTEP]
exact h.iterate _
[GOAL]
α✝ : Type u
β : Type v
f✝ fa g : α✝ → α✝
x✝ y : α✝
fb : β → β
m n k : ℕ
e : Perm α✝
α : Type u_1
f : α → α
x : α
⊢ x ∈ fixedPoints f ↔ f x = x
[PROOFSTEP]
rfl
[GOAL]
α : Type u
β : Type v
f fa g : α → α
x y : α
fb : β → β
m n k : ℕ
e : Perm α
x✝ : α
⊢ x✝ ∈ fixedPoints id ↔ x✝ ∈ Set.univ
[PROOFSTEP]
simpa using isFixedPt_id _
[GOAL]
α : Type u
β : Type v
f fa g : α → α
x y : α
fb : β → β
m n k : ℕ
e : Perm α
h : Function.Commute f g
⊢ Set.InvOn f g (fixedPoints (f ∘ g)) (fixedPoints (f ∘ g))
[PROOFSTEP]
simpa only [h.comp_eq] using Function.invOn_fixedPoints_comp f g
[GOAL]
α : Type u
β : Type v
f fa g : α → α
x y : α
fb : β → β
m n k : ℕ
e : Perm α
h : Function.Commute f g
⊢ Set.BijOn f (fixedPoints (f ∘ g)) (fixedPoints (f ∘ g))
[PROOFSTEP]
simpa only [h.comp_eq] using bijOn_fixedPoints_comp g f
[GOAL]
α : Type u
β : Type v
f fa g : α → α
x y : α
fb : β → β
m n k : ℕ
e : Perm α
h : Function.Commute f g
⊢ Set.BijOn g (fixedPoints (f ∘ g)) (fixedPoints (f ∘ g))
[PROOFSTEP]
simpa only [h.comp_eq] using bijOn_fixedPoints_comp f g
|
function planC = calculateGRE(baseScanNum,movScanNum,planC)
% function planC = calculateGRE(baseScanNum,movScanNum,planC)
%
% APA, 03/21/2017
if ~exist('planC','var')
global planC
end
indexS = planC{end};
% Absolute Difference between two scans
siz = size(planC{indexS.scan}(baseScanNum).scanArray);
baseMask3M = logical(maskByThresh3D(planC{indexS.scan}(baseScanNum).scanArray));
movMask3M = logical(maskByThresh3D(planC{indexS.scan}(movScanNum).scanArray));
sA1 = zeros(siz,'single');
meanSa1 = mean(single(planC{indexS.scan}(baseScanNum).scanArray(baseMask3M)));
sdSa1 = std(single(planC{indexS.scan}(baseScanNum).scanArray(baseMask3M)));
sA1(baseMask3M) = (single(planC{indexS.scan}(baseScanNum).scanArray(baseMask3M)) - meanSa1)/sdSa1;
sA2 = zeros(siz,'single');
meanSa2 = mean(single(planC{indexS.scan}(movScanNum).scanArray(movMask3M)));
sdSa2 = std(single(planC{indexS.scan}(movScanNum).scanArray(movMask3M)));
sA2(movMask3M) = (single(planC{indexS.scan}(movScanNum).scanArray(movMask3M)) - meanSa2)/sdSa2;
diff3M = abs(sA1 - sA2);
% Window size
slcWindow = 5;
rowWindow = 5;
colWindow = 5;
% Number of levels for histogram
numLevels = 16;
% Create initial imM with dimension of slcWindow
imM = [];
for slc = 1:slcWindow
imTmpM = im2col(diff3M(:,:,slc),[rowWindow colWindow],'sliding');
imM = [imM;imTmpM];
end
numNeighbors = rowWindow*colWindow;
numSlcs = size(diff3M,3);
numRows = size(diff3M,1);
numCols = size(diff3M,2);
entropy3M = zeros(siz,'single');
mean3M = zeros(siz,'single');
var3M = zeros(siz,'single');
for slc = 1:numSlcs
disp(['-------------------', num2str(slc)])
if slc > floor(slcWindow/2) && slc <= (numSlcs-floor(slcWindow/2))
imM(1:numNeighbors,:) = [];
imTmpM = im2col(diff3M(:,:,slc),[rowWindow colWindow],'sliding');
imM = [imM;imTmpM];
end
countsM = hist(imM,numLevels);
countsM = countsM/numNeighbors/colWindow;
entrpy2M = col2im(-sum(countsM.*log2(countsM+eps)),[rowWindow colWindow],[numRows numCols],'sliding');
mean2M = col2im(mean(imM),[rowWindow colWindow],[numRows numCols],'sliding');
var2M = col2im(var(imM),[rowWindow colWindow],[numRows numCols],'sliding');
for i = 1:floor(slcWindow/2)
entrpy2M = [entrpy2M(:,1), entrpy2M, entrpy2M(:,end)];
entrpy2M = [entrpy2M(1,:); entrpy2M; entrpy2M(end,:)];
mean2M = [mean2M(:,1), mean2M, mean2M(:,end)];
mean2M = [mean2M(1,:); mean2M; mean2M(end,:)];
var2M = [var2M(:,1), var2M, var2M(:,end)];
var2M = [var2M(1,:); var2M; var2M(end,:)];
end
entropy3M(:,:,slc) = entrpy2M;
mean3M(:,:,slc) = mean2M;
var3M(:,:,slc) = var2M;
end
gre3M = entropy3M/median(entropy3M(baseMask3M)) + mean3M/median(mean3M(baseMask3M)) + var3M/median(var3M(baseMask3M));
gre3M = gre3M / 3;
%
% showIMDose(diff3M,'Diff',1);
% showIMDose(entropy3M,'Entropy',1);
% showIMDose(mean3M,'Mean',1);
% showIMDose(var3M,'Variance',1);
% showIMDose(gre3M,'GRE',1);
register = 'UniformCT'; %Currently only option supported. Dose has the same shape as the uniformized CT scan.
doseError = [];
doseEdition = 'Generalized Registration Error';
overWrite = 'no'; %Overwrite the last CERR dose?
if ~exist('assocScanNum','var')
assocScanNum = 1;
end
fractionGroupID = 'GRE';
assocScanUID = planC{indexS.scan}(assocScanNum).scanUID;
description = '';
planC = dose2CERR(gre3M,doseError,fractionGroupID,doseEdition,description,register,[],overWrite,assocScanUID,planC);
|
section "Collecting Semantics of Commands"
theory Collecting
imports Complete_Lattice_ix ACom
begin
subsection "Annotated commands as a complete lattice"
(* Orderings could also be lifted generically (thus subsuming the
instantiation for preord and order), but then less_eq_acom would need to
become a definition, eg less_eq_acom = lift2 less_eq, and then proofs would
need to unfold this defn first. *)
instantiation acom :: (order) order
begin
fun less_eq_acom :: "('a::order)acom \<Rightarrow> 'a acom \<Rightarrow> bool" where
"(SKIP {S}) \<le> (SKIP {S'}) = (S \<le> S')" |
"(x ::= e {S}) \<le> (x' ::= e' {S'}) = (x=x' \<and> e=e' \<and> S \<le> S')" |
"(c1;;c2) \<le> (c1';;c2') = (c1 \<le> c1' \<and> c2 \<le> c2')" |
"(IF b THEN c1 ELSE c2 {S}) \<le> (IF b' THEN c1' ELSE c2' {S'}) =
(b=b' \<and> c1 \<le> c1' \<and> c2 \<le> c2' \<and> S \<le> S')" |
"({Inv} WHILE b DO c {P}) \<le> ({Inv'} WHILE b' DO c' {P'}) =
(b=b' \<and> c \<le> c' \<and> Inv \<le> Inv' \<and> P \<le> P')" |
"less_eq_acom _ _ = False"
lemma SKIP_le: "SKIP {S} \<le> c \<longleftrightarrow> (\<exists>S'. c = SKIP {S'} \<and> S \<le> S')"
by (cases c) auto
lemma Assign_le: "x ::= e {S} \<le> c \<longleftrightarrow> (\<exists>S'. c = x ::= e {S'} \<and> S \<le> S')"
by (cases c) auto
lemma Seq_le: "c1;;c2 \<le> c \<longleftrightarrow> (\<exists>c1' c2'. c = c1';;c2' \<and> c1 \<le> c1' \<and> c2 \<le> c2')"
by (cases c) auto
lemma If_le: "IF b THEN c1 ELSE c2 {S} \<le> c \<longleftrightarrow>
(\<exists>c1' c2' S'. c= IF b THEN c1' ELSE c2' {S'} \<and> c1 \<le> c1' \<and> c2 \<le> c2' \<and> S \<le> S')"
by (cases c) auto
lemma While_le: "{Inv} WHILE b DO c {P} \<le> w \<longleftrightarrow>
(\<exists>Inv' c' P'. w = {Inv'} WHILE b DO c' {P'} \<and> c \<le> c' \<and> Inv \<le> Inv' \<and> P \<le> P')"
by (cases w) auto
definition less_acom :: "'a acom \<Rightarrow> 'a acom \<Rightarrow> bool" where
"less_acom x y = (x \<le> y \<and> \<not> y \<le> x)"
instance
proof (standard,goal_cases)
case 1 show ?case by(simp add: less_acom_def)
next
case (2 x) thus ?case by (induct x) auto
next
case (3 x y z) thus ?case
apply(induct x y arbitrary: z rule: less_eq_acom.induct)
apply (auto intro: le_trans simp: SKIP_le Assign_le Seq_le If_le While_le)
done
next
case (4 x y) thus ?case
apply(induct x y rule: less_eq_acom.induct)
apply (auto intro: le_antisym)
done
qed
end
fun sub\<^sub>1 :: "'a acom \<Rightarrow> 'a acom" where
"sub\<^sub>1(c1;;c2) = c1" |
"sub\<^sub>1(IF b THEN c1 ELSE c2 {S}) = c1" |
"sub\<^sub>1({I} WHILE b DO c {P}) = c"
fun sub\<^sub>2 :: "'a acom \<Rightarrow> 'a acom" where
"sub\<^sub>2(c1;;c2) = c2" |
"sub\<^sub>2(IF b THEN c1 ELSE c2 {S}) = c2"
fun invar :: "'a acom \<Rightarrow> 'a" where
"invar({I} WHILE b DO c {P}) = I"
fun lift :: "('a set \<Rightarrow> 'b) \<Rightarrow> com \<Rightarrow> 'a acom set \<Rightarrow> 'b acom"
where
"lift F com.SKIP M = (SKIP {F (post ` M)})" |
"lift F (x ::= a) M = (x ::= a {F (post ` M)})" |
"lift F (c1;;c2) M =
lift F c1 (sub\<^sub>1 ` M);; lift F c2 (sub\<^sub>2 ` M)" |
"lift F (IF b THEN c1 ELSE c2) M =
IF b THEN lift F c1 (sub\<^sub>1 ` M) ELSE lift F c2 (sub\<^sub>2 ` M)
{F (post ` M)}" |
"lift F (WHILE b DO c) M =
{F (invar ` M)}
WHILE b DO lift F c (sub\<^sub>1 ` M)
{F (post ` M)}"
global_interpretation Complete_Lattice_ix "%c. {c'. strip c' = c}" "lift Inter"
proof (standard,goal_cases)
case (1 A _ a)
have "a:A \<Longrightarrow> lift Inter (strip a) A \<le> a"
proof(induction a arbitrary: A)
case Seq from Seq.prems show ?case by(force intro!: Seq.IH)
next
case If from If.prems show ?case by(force intro!: If.IH)
next
case While from While.prems show ?case by(force intro!: While.IH)
qed force+
with 1 show ?case by auto
next
case (2 b i A)
thus ?case
proof(induction b arbitrary: i A)
case SKIP thus ?case by (force simp:SKIP_le)
next
case Assign thus ?case by (force simp:Assign_le)
next
case Seq from Seq.prems show ?case
by (force intro!: Seq.IH simp:Seq_le)
next
case If from If.prems show ?case by (force simp: If_le intro!: If.IH)
next
case While from While.prems show ?case
by(fastforce simp: While_le intro: While.IH)
qed
next
case (3 A i)
have "strip(lift Inter i A) = i"
proof(induction i arbitrary: A)
case Seq from Seq.prems show ?case
by (fastforce simp: strip_eq_Seq subset_iff intro!: Seq.IH)
next
case If from If.prems show ?case
by (fastforce intro!: If.IH simp: strip_eq_If)
next
case While from While.prems show ?case
by(fastforce intro: While.IH simp: strip_eq_While)
qed auto
thus ?case by auto
qed
lemma le_post: "c \<le> d \<Longrightarrow> post c \<le> post d"
by(induction c d rule: less_eq_acom.induct) auto
subsection "Collecting semantics"
fun step :: "state set \<Rightarrow> state set acom \<Rightarrow> state set acom" where
"step S (SKIP {P}) = (SKIP {S})" |
"step S (x ::= e {P}) =
(x ::= e {{s'. \<exists>s\<in>S. s' = s(x := aval e s)}})" |
"step S (c1;; c2) = step S c1;; step (post c1) c2" |
"step S (IF b THEN c1 ELSE c2 {P}) =
IF b THEN step {s:S. bval b s} c1 ELSE step {s:S. \<not> bval b s} c2
{post c1 \<union> post c2}" |
"step S ({Inv} WHILE b DO c {P}) =
{S \<union> post c} WHILE b DO (step {s:Inv. bval b s} c) {{s:Inv. \<not> bval b s}}"
definition CS :: "com \<Rightarrow> state set acom" where
"CS c = lfp (step UNIV) c"
lemma mono2_step: "c1 \<le> c2 \<Longrightarrow> S1 \<subseteq> S2 \<Longrightarrow> step S1 c1 \<le> step S2 c2"
proof(induction c1 c2 arbitrary: S1 S2 rule: less_eq_acom.induct)
case 2 thus ?case by fastforce
next
case 3 thus ?case by(simp add: le_post)
next
case 4 thus ?case by(simp add: subset_iff)(metis le_post subsetD)+
next
case 5 thus ?case by(simp add: subset_iff) (metis le_post subsetD)
qed auto
lemma mono_step: "mono (step S)"
by(blast intro: monoI mono2_step)
lemma strip_step: "strip(step S c) = strip c"
by (induction c arbitrary: S) auto
lemma lfp_cs_unfold: "lfp (step S) c = step S (lfp (step S) c)"
apply(rule lfp_unfold[OF _ mono_step])
apply(simp add: strip_step)
done
lemma CS_unfold: "CS c = step UNIV (CS c)"
by (metis CS_def lfp_cs_unfold)
lemma strip_CS[simp]: "strip(CS c) = c"
by(simp add: CS_def index_lfp[simplified])
end
|
# Copyright (c) 2018-2021, Carnegie Mellon University
# See LICENSE for details
DimLength := (l) -> When(IsList(l), Length(l), 1);
Class(CrossBase, BaseOperation, rec(
abbrevs := [ arg -> [Flat(arg)] ],
new := meth(self, L)
if Length(L)=1 then return L[1]; fi;
return SPL(WithBases(self, rec(_children:=L, dimensions := TransposedMat(List(L, e -> e.dims())))));
end,
area := self >> Sum(self.children(), x->x.area()),
normalizedArithCost := self >> Sum(self.children(), x -> x.normalizedArithCost()),
));
Declare(Cross);
Class(Cross, CrossBase, rec(
codeletName:="C",
isPermutation := self >> false,
dmn:=self>>let(li:=[],Flat(List(self._children, x-> x.dmn()))),
rng:=self>>let(li:=[],Flat(List(self._children, x-> x.rng()))),
sums:= self>>ObjId(self)(List(self.rChildren(),x->x.sums())),
transpose := self >> self,
isIdentity := self >> ForAll(self._children, IsIdentitySPL),
isBlockTransitive := true,
));
Declare(fCross);
Class(fCross, FuncClassOper, rec(
_perm := true,
isFunction := true,
skipOneChild := true,
range := (self) >> StripList(List(self.rChildren(), (x) -> x.range())),
advrange := (self) >> List(self.rChildren(), (x) -> x.advrange()[1]),
domain := (self) >> StripList(List(self.rChildren(), (x) -> x.domain())),
advdomain := (self) >> List(self.rChildren(), (x) -> x.advdomain()[1]),
toSpl := (self, allinds, cols) >>
fCross(List([1..Length(self.rChildren())],
i -> self.rChildren()[i].toSpl(allinds,cols[i]))),
downRank := (self, loopid, ind) >>
fCross(List(self.rChildren(),
c -> c.downRank(loopid, ind))),
downRankFull := (self, allinds) >>
fCross(List(self.rChildren(),
c -> c.downRankFull(allinds))),
isIdentity := self >> ForAll(self._children, IsIdentity),
transpose := self >> ObjId(self)(List(self._children, e -> e.transpose())),
));
Class(ExplicitGath, Gath);
Class(ExplicitCross, Cross);
Class(ExplicitOLRuleset, RuleSet);
RewriteRules(ExplicitOLRuleset, rec(
Gath_f2DTrExpR := Rule([Gath, [@(2,fCompose), @(3,f2DTrExplicitR), ...]],
e-> Gath(fCompose(Drop(@(2).val.rChildren(),1)))*ExplicitGath(ApplyFunc(f2DTr,@(3).val.rChildren()))),
Gath_f2DTrExpLR := Rule([Gath, [@(2,fCompose), @(3,f2DTrExplicitL), @(4,f2DTrExplicitR), ...]],
e-> Gath(fCompose([ApplyFunc(f2DTr,@(4).val.rChildren())]::Drop(@(2).val.rChildren(),2)))
*ExplicitGath(ApplyFunc(f2DTr,@(3).val.rChildren()))),
Cross_Compose_ExplicitGath_1 := Rule([Cross, [@(1,Compose), ..., @(2,ExplicitGath)], @(3) ],
e ->
Compose(Cross(Compose(DropLast(@(1).val.rChildren(),1)), @(3).val),
ExplicitCross(ApplyFunc(Gath, @(2).val.rChildren()), ApplyFunc(2DI, @(3).val.advdims()[2][1])))),
Cross_Compose_ExplicitGath_2 := Rule([Cross, @(3), [@(1,Compose), ..., @(2,ExplicitGath)] ],
e ->
Compose(Cross(@(3).val, Compose(DropLast(@(1).val.rChildren(),1))),
ExplicitCross(ApplyFunc(2DI, @(3).val.advdims()[2][1]), ApplyFunc(Gath, @(2).val.rChildren())))),
));
Class(FinalOLRuleset, RuleSet);
RewriteRules(FinalOLRuleset, rec(
ExplicitCross := Rule(@(1,ExplicitCross),
e -> ApplyFunc(Cross, @(1).val.rChildren()))
));
|
#include <boost/mpl/aux_/config/adl.hpp>
|
When you have a family issue, there are many benefits to choosing a local family lawyer. In addition to supporting a member of your Folly Beach community, you are also choosing a lawyer that is more convenient to travel to, being local to Folly Beach, than if you were to choose a lawyer outside of the Folly Beach area.
By hiring a reputable Folly Beach family lawyer, you can ensure that your case will be handled in the most professional manner possible. And finding a good, experienced local Folly Beach family lawyer will give you the comfort of knowing that if you should have another family issue in the future, your lawyer is right around the corner.
|
using IncrementalInference
using Test
@testset "test default userdata::FactorMetadata..." begin
fgt = initfg()
addVariable!(fgt, :x1, ContinuousScalar)
addFactor!(fgt, [:x1], Prior(Normal()))
addVariable!(fgt, :x2, ContinuousScalar)
addFactor!(fgt, [:x1;:x2], LinearConditional(Normal(10,1)))
fc = solverData(getFactor(fgt, :x1x2f1))
@test length(fc.fnc.cpt[1].factormetadata.variableuserdata) == 2
@test fc.fnc.cpt[1].factormetadata.solvefor == :null
end
#
|
[GOAL]
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a b : α
h : MonotoneOn f s
hl : BddBelow (f '' s)
hu : BddAbove (f '' s)
⊢ ∃ g, Monotone g ∧ EqOn f g s
[PROOFSTEP]
classical
/- The extension is defined by `f x = f a` for `x ≤ a`, and `f x` is the supremum of the values
of `f` to the left of `x` for `x ≥ a`. -/
rcases hl with ⟨a, ha⟩
have hu' : ∀ x, BddAbove (f '' (Iic x ∩ s)) := fun x => hu.mono (image_subset _ (inter_subset_right _ _))
let g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
have hgs : EqOn f g s := by
intro x hx
simp only []
have : IsGreatest (Iic x ∩ s) x := ⟨⟨right_mem_Iic, hx⟩, fun y hy => hy.1⟩
rw [if_neg this.nonempty.not_disjoint, ((h.mono <| inter_subset_right _ _).map_isGreatest this).csSup_eq]
refine' ⟨g, fun x y hxy => _, hgs⟩
by_cases hx : Disjoint (Iic x) s <;> by_cases hy : Disjoint (Iic y) s <;>
simp only [if_pos, if_neg, not_false_iff, *, refl]
· rcases not_disjoint_iff_nonempty_inter.1 hy with ⟨z, hz⟩
exact le_csSup_of_le (hu' _) (mem_image_of_mem _ hz) (ha <| mem_image_of_mem _ hz.2)
· exact (hx <| hy.mono_left <| Iic_subset_Iic.2 hxy).elim
· rw [not_disjoint_iff_nonempty_inter] at hx hy
refine' csSup_le_csSup (hu' _) (hx.image _) (image_subset _ _)
exact inter_subset_inter_left _ (Iic_subset_Iic.2 hxy)
[GOAL]
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a b : α
h : MonotoneOn f s
hl : BddBelow (f '' s)
hu : BddAbove (f '' s)
⊢ ∃ g, Monotone g ∧ EqOn f g s
[PROOFSTEP]
rcases hl with ⟨a, ha⟩
[GOAL]
case intro
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
⊢ ∃ g, Monotone g ∧ EqOn f g s
[PROOFSTEP]
have hu' : ∀ x, BddAbove (f '' (Iic x ∩ s)) := fun x => hu.mono (image_subset _ (inter_subset_right _ _))
[GOAL]
case intro
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
⊢ ∃ g, Monotone g ∧ EqOn f g s
[PROOFSTEP]
let g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
[GOAL]
case intro
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
⊢ ∃ g, Monotone g ∧ EqOn f g s
[PROOFSTEP]
have hgs : EqOn f g s := by
intro x hx
simp only []
have : IsGreatest (Iic x ∩ s) x := ⟨⟨right_mem_Iic, hx⟩, fun y hy => hy.1⟩
rw [if_neg this.nonempty.not_disjoint, ((h.mono <| inter_subset_right _ _).map_isGreatest this).csSup_eq]
[GOAL]
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
⊢ EqOn f g s
[PROOFSTEP]
intro x hx
[GOAL]
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
x : α
hx : x ∈ s
⊢ f x = g x
[PROOFSTEP]
simp only []
[GOAL]
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
x : α
hx : x ∈ s
⊢ f x = if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
[PROOFSTEP]
have : IsGreatest (Iic x ∩ s) x := ⟨⟨right_mem_Iic, hx⟩, fun y hy => hy.1⟩
[GOAL]
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
x : α
hx : x ∈ s
this : IsGreatest (Iic x ∩ s) x
⊢ f x = if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
[PROOFSTEP]
rw [if_neg this.nonempty.not_disjoint, ((h.mono <| inter_subset_right _ _).map_isGreatest this).csSup_eq]
[GOAL]
case intro
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
hgs : EqOn f g s
⊢ ∃ g, Monotone g ∧ EqOn f g s
[PROOFSTEP]
refine' ⟨g, fun x y hxy => _, hgs⟩
[GOAL]
case intro
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
hgs : EqOn f g s
x y : α
hxy : x ≤ y
⊢ g x ≤ g y
[PROOFSTEP]
by_cases hx : Disjoint (Iic x) s
[GOAL]
case pos
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
hgs : EqOn f g s
x y : α
hxy : x ≤ y
hx : Disjoint (Iic x) s
⊢ g x ≤ g y
[PROOFSTEP]
by_cases hy : Disjoint (Iic y) s
[GOAL]
case neg
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
hgs : EqOn f g s
x y : α
hxy : x ≤ y
hx : ¬Disjoint (Iic x) s
⊢ g x ≤ g y
[PROOFSTEP]
by_cases hy : Disjoint (Iic y) s
[GOAL]
case pos
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
hgs : EqOn f g s
x y : α
hxy : x ≤ y
hx : Disjoint (Iic x) s
hy : Disjoint (Iic y) s
⊢ g x ≤ g y
[PROOFSTEP]
simp only [if_pos, if_neg, not_false_iff, *, refl]
[GOAL]
case neg
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
hgs : EqOn f g s
x y : α
hxy : x ≤ y
hx : Disjoint (Iic x) s
hy : ¬Disjoint (Iic y) s
⊢ g x ≤ g y
[PROOFSTEP]
simp only [if_pos, if_neg, not_false_iff, *, refl]
[GOAL]
case pos
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
hgs : EqOn f g s
x y : α
hxy : x ≤ y
hx : ¬Disjoint (Iic x) s
hy : Disjoint (Iic y) s
⊢ g x ≤ g y
[PROOFSTEP]
simp only [if_pos, if_neg, not_false_iff, *, refl]
[GOAL]
case neg
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
hgs : EqOn f g s
x y : α
hxy : x ≤ y
hx : ¬Disjoint (Iic x) s
hy : ¬Disjoint (Iic y) s
⊢ g x ≤ g y
[PROOFSTEP]
simp only [if_pos, if_neg, not_false_iff, *, refl]
[GOAL]
case neg
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
hgs : EqOn f g s
x y : α
hxy : x ≤ y
hx : Disjoint (Iic x) s
hy : ¬Disjoint (Iic y) s
⊢ a ≤ sSup (f '' (Iic y ∩ s))
[PROOFSTEP]
rcases not_disjoint_iff_nonempty_inter.1 hy with ⟨z, hz⟩
[GOAL]
case neg.intro
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
hgs : EqOn f g s
x y : α
hxy : x ≤ y
hx : Disjoint (Iic x) s
hy : ¬Disjoint (Iic y) s
z : α
hz : z ∈ Iic y ∩ s
⊢ a ≤ sSup (f '' (Iic y ∩ s))
[PROOFSTEP]
exact le_csSup_of_le (hu' _) (mem_image_of_mem _ hz) (ha <| mem_image_of_mem _ hz.2)
[GOAL]
case pos
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
hgs : EqOn f g s
x y : α
hxy : x ≤ y
hx : ¬Disjoint (Iic x) s
hy : Disjoint (Iic y) s
⊢ sSup (f '' (Iic x ∩ s)) ≤ a
[PROOFSTEP]
exact (hx <| hy.mono_left <| Iic_subset_Iic.2 hxy).elim
[GOAL]
case neg
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
hgs : EqOn f g s
x y : α
hxy : x ≤ y
hx : ¬Disjoint (Iic x) s
hy : ¬Disjoint (Iic y) s
⊢ sSup (f '' (Iic x ∩ s)) ≤ sSup (f '' (Iic y ∩ s))
[PROOFSTEP]
rw [not_disjoint_iff_nonempty_inter] at hx hy
[GOAL]
case neg
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
hgs : EqOn f g s
x y : α
hxy : x ≤ y
hx : Set.Nonempty (Iic x ∩ s)
hy : Set.Nonempty (Iic y ∩ s)
⊢ sSup (f '' (Iic x ∩ s)) ≤ sSup (f '' (Iic y ∩ s))
[PROOFSTEP]
refine' csSup_le_csSup (hu' _) (hx.image _) (image_subset _ _)
[GOAL]
case neg
α : Type u_1
β : Type u_2
inst✝¹ : LinearOrder α
inst✝ : ConditionallyCompleteLinearOrder β
f : α → β
s : Set α
a✝ b : α
h : MonotoneOn f s
hu : BddAbove (f '' s)
a : β
ha : a ∈ lowerBounds (f '' s)
hu' : ∀ (x : α), BddAbove (f '' (Iic x ∩ s))
g : α → β := fun x => if Disjoint (Iic x) s then a else sSup (f '' (Iic x ∩ s))
hgs : EqOn f g s
x y : α
hxy : x ≤ y
hx : Set.Nonempty (Iic x ∩ s)
hy : Set.Nonempty (Iic y ∩ s)
⊢ Iic x ∩ s ⊆ Iic y ∩ s
[PROOFSTEP]
exact inter_subset_inter_left _ (Iic_subset_Iic.2 hxy)
|
using LinearAlgebra, ProgressMeter
import KitBase
function KitBase.write_vtk(ps, ctr)
cdata = zeros(length(ctr))
for i in eachindex(cdata)
cdata[i] = ctr[i].w
end
KitBase.write_vtk(ps.points, ps.cellid, cdata)
end
begin
cd(@__DIR__)
# time
tspan = (0.0, 0.2)
cfl = 0.7
# quadrature
quadratureorder = 6
points, triangulation = KitBase.octa_quadrature(quadratureorder)
weights = KitBase.quadrature_weights(points, triangulation)
nq = size(points, 1)
vs = KitBase.UnstructVSpace(-1.0, 1.0, nq, points, weights)
# geometry
cells, points = KitBase.read_mesh("../assets/mesh/pointsource.su2")
cellid = KitBase.extract_cell(cells)
edgePoints, edgeCells, cellNeighbors = KitBase.mesh_connectivity_2D(cellid)
cellType = KitBase.mesh_cell_type(cellNeighbors)
cellArea = KitBase.mesh_area_2D(points, cellid)
cellCenter = KitBase.mesh_center_2D(points, cellid)
edgeCenter = KitBase.mesh_edge_center(points, edgePoints)
cellEdges = KitBase.mesh_cell_edge(cellid, edgeCells)
ps = KitBase.UnstructPSpace(
cells,
points,
cellid,
cellType,
cellNeighbors,
cellEdges,
cellCenter,
cellArea,
edgePoints,
edgeCells,
edgeCenter,
)
# particle
SigmaS = ones(size(cellid, 1))
SigmaA = zeros(size(cellid, 1))
SigmaT = SigmaS + SigmaA
end
ctr = Array{KitBase.ControlVolumeUS1F}(undef, size(ps.cellid, 1))
for i in eachindex(ctr)
n = Vector{Float64}[]
for j = 1:3
push!(
n,
KitBase.unit_normal(
ps.points[edgePoints[cellEdges[i, j], 1], :],
ps.points[edgePoints[cellEdges[i, j], 2], :],
),
)
if dot(ps.edgeCenter[ps.cellEdges[i, j], :] .- ps.cellCenter[i, :], n[j]) < 0
n[j] .= -n[j]
end
end
phi = ones(nq) .* 1e-4
if 0.49 <= ps.cellCenter[i, 1] <= 0.51 && 0.49 <= ps.cellCenter[i, 2] <= 0.51
phi .= 10.0
end
#s2 = 0.03^2
#phi .= max(1e-4, 1.0 / (4.0 * π * s2) * exp(-((ps.cellCenter[i, 1]-0.5)^2 + (ps.cellCenter[i, 2]-0.5)^2) / 4.0 / s2))
w = sum(weights .* phi)
dx = [
KitBase.point_distance(
cellCenter[i, :],
ps.points[ps.cellid[i, 1], :],
ps.points[ps.cellid[i, 2], :],
),
KitBase.point_distance(
cellCenter[i, :],
ps.points[ps.cellid[i, 2], :],
ps.points[ps.cellid[i, 3], :],
),
KitBase.point_distance(
cellCenter[i, :],
ps.points[ps.cellid[i, 3], :],
ps.points[ps.cellid[i, 1], :],
),
]
ctr[i] = KitBase.ControlVolumeUS1F(n, cellCenter[i, :], dx, w, w, phi)
end
face = Array{KitBase.Interface2D1F}(undef, size(ps.edgePoints, 1))
for i in eachindex(face)
len = norm(ps.points[edgePoints[i, 1], :] .- ps.points[edgePoints[i, 2], :])
n = KitBase.unit_normal(ps.points[edgePoints[i, 1], :], ps.points[edgePoints[i, 2], :])
if !(-1 in ps.edgeCells[i, :])
n0 = ps.cellCenter[ps.edgeCells[i, 2], :] .- ps.cellCenter[ps.edgeCells[i, 1], :]
else
n0 = zero(n)
end
if dot(n, n0) < 0
n .= -n
end
fw = 0.0
ff = zeros(nq)
face[i] = KitBase.Interface2D1F(len, n[1], n[2], fw, ff)
end
dt = 1.0 / 200 * cfl
nt = tspan[2] ÷ dt |> Int
@showprogress for iter = 1:20#nt
@inbounds Threads.@threads for i in eachindex(face)
velo = vs.u[:, 1] .* face[i].n[1] + vs.u[:, 2] .* face[i].n[2]
if !(-1 in ps.edgeCells[i, :])
KitBase.flux_kfvs!(
face[i].ff,
ctr[ps.edgeCells[i, 1]].f,
ctr[ps.edgeCells[i, 2]].f,
velo,
dt,
)
end
end
@inbounds Threads.@threads for i in eachindex(ctr)
if ps.cellType[i] == 0
for j = 1:3
dirc = sign(dot(ctr[i].n[j], face[ps.cellEdges[i, j]].n))
@. ctr[i].f -=
dirc * face[ps.cellEdges[i, j]].ff * face[ps.cellEdges[i, j]].len /
ps.cellArea[i]
end
#integral = KitBase.discrete_moments(ctr[i].f, vs.weights)
#integral /= 4.0 * π
#@. ctr[i].f += (integral - ctr[i].f) * dt
ctr[i].w = sum(ctr[i].f .* vs.weights)
end
end
end
KitBase.write_vtk(ps, ctr)
@inbounds Threads.@threads for i in eachindex(face)
velo = vs.u[:, 1] .* face[i].n[1] + vs.u[:, 2] .* face[i].n[2]
if !(-1 in ps.edgeCells[i, :])
KitBase.flux_kfvs!(
face[i].ff,
ctr[ps.edgeCells[i, 1]].f,
ctr[ps.edgeCells[i, 2]].f,
velo,
dt,
)
end
end
@inbounds Threads.@threads for i in eachindex(ctr)
if ps.cellType[i] == 0
for j = 1:3
dirc = sign(dot(ctr[i].n[j], face[ps.cellEdges[i, j]].n))
@. ctr[i].f -=
dirc * face[ps.cellEdges[i, j]].ff * face[ps.cellEdges[i, j]].len /
ps.cellArea[i]
end
#integral = KitBase.discrete_moments(ctr[i].f, vs.weights)
#integral /= 4.0 * π
#@. ctr[i].f += (integral - ctr[i].f) * dt
ctr[i].w = sum(ctr[i].f .* vs.weights)
end
end
|
/-
Copyright © 2021 Nicolò Cavalleri. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nicolò Cavalleri, Heather Macbeth
-/
import geometry.manifold.smooth_manifold_with_corners
import analysis.normed_space.units
/-!
# Units of a normed algebra
This file is a stub, containing a construction of the charted space structure on the group of units
of a complete normed ring `R`, and of the smooth manifold structure on the group of units of a
complete normed `𝕜`-algebra `R`.
This manifold is actually a Lie group, which eventually should be the main result of this file.
An important special case of this construction is the general linear group. For a normed space `V`
over a field `𝕜`, the `𝕜`-linear endomorphisms of `V` are a normed `𝕜`-algebra (see
`continuous_linear_map.to_normed_algebra`), so this construction provides a Lie group structure on
its group of units, the general linear group GL(`𝕜`, `V`).
## TODO
The Lie group instance requires the following fields:
```
instance : lie_group 𝓘(𝕜, R) Rˣ :=
{ smooth_mul := sorry,
smooth_inv := sorry,
..units.smooth_manifold_with_corners }
```
The ingredients needed for the construction are
* smoothness of multiplication and inversion in the charts, i.e. as functions on the normed
`𝕜`-space `R`: see `times_cont_diff_at_ring_inverse` for the inversion result, and
`times_cont_diff_mul` (needs to be generalized from field to algebra) for the multiplication
result
* for an open embedding `f`, whose domain is equipped with the induced manifold structure
`f.singleton_smooth_manifold_with_corners`, characterization of smoothness of functions to/from
this manifold in terms of smoothness in the target space. See the pair of lemmas
`times_cont_mdiff_coe_sphere` and `times_cont_mdiff.cod_restrict_sphere` for a model.
None of this should be particularly difficult.
-/
noncomputable theory
open_locale manifold
namespace units
variables {R : Type*} [normed_ring R] [complete_space R]
instance : charted_space R Rˣ := open_embedding_coe.singleton_charted_space
lemma chart_at_apply {a : Rˣ} {b : Rˣ} : chart_at R a b = b := rfl
lemma chart_at_source {a : Rˣ} : (chart_at R a).source = set.univ := rfl
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [normed_algebra 𝕜 R]
instance : smooth_manifold_with_corners 𝓘(𝕜, R) Rˣ :=
open_embedding_coe.singleton_smooth_manifold_with_corners 𝓘(𝕜, R)
end units
|
context("irepeat iterator")
test_that("Indefinite irepeat of integer", {
it <- irepeat(42)
i <- nextElem(it)
expect_equal(i, 42)
i <- nextElem(it)
expect_equal(i, 42)
i <- nextElem(it)
expect_equal(i, 42)
i <- nextElem(it)
expect_equal(i, 42)
i <- nextElem(it)
expect_equal(i, 42)
i <- nextElem(it)
expect_equal(i, 42)
i <- nextElem(it)
expect_equal(i, 42)
})
test_that("irepeat repeats integer fixed number of times", {
it <- irepeat(42, times=4)
i <- nextElem(it)
expect_equal(i, 42)
i <- nextElem(it)
expect_equal(i, 42)
i <- nextElem(it)
expect_equal(i, 42)
i <- nextElem(it)
expect_equal(i, 42)
expect_error(nextElem(it), "StopIteration")
})
test_that("irepeat repeats data.frame fixed number of times", {
it <- irepeat(iris, times=5)
i <- nextElem(it)
expect_equal(i, iris)
i <- nextElem(it)
expect_equal(i, iris)
i <- nextElem(it)
expect_equal(i, iris)
i <- nextElem(it)
expect_equal(i, iris)
i <- nextElem(it)
expect_equal(i, iris)
expect_error(nextElem(it), "StopIteration")
})
|
State Before: R : Type u
M : Type v
K : Type u₁
V : Type u₂
ι : Type w
inst✝⁴ : CommRing R
inst✝³ : AddCommGroup M
inst✝² : Module R M
inst✝¹ : DecidableEq ι
b : Basis ι R M
inst✝ : _root_.Finite ι
⊢ LinearMap.comp (toDual (dualBasis b)) (toDual b) = Dual.eval R M State After: R : Type u
M : Type v
K : Type u₁
V : Type u₂
ι : Type w
inst✝⁴ : CommRing R
inst✝³ : AddCommGroup M
inst✝² : Module R M
inst✝¹ : DecidableEq ι
b : Basis ι R M
inst✝ : _root_.Finite ι
i j : ι
⊢ ↑(↑(LinearMap.comp (toDual (dualBasis b)) (toDual b)) (↑b i)) (↑(dualBasis b) j) =
↑(↑(Dual.eval R M) (↑b i)) (↑(dualBasis b) j) Tactic: refine' b.ext fun i => b.dualBasis.ext fun j => _ State Before: R : Type u
M : Type v
K : Type u₁
V : Type u₂
ι : Type w
inst✝⁴ : CommRing R
inst✝³ : AddCommGroup M
inst✝² : Module R M
inst✝¹ : DecidableEq ι
b : Basis ι R M
inst✝ : _root_.Finite ι
i j : ι
⊢ ↑(↑(LinearMap.comp (toDual (dualBasis b)) (toDual b)) (↑b i)) (↑(dualBasis b) j) =
↑(↑(Dual.eval R M) (↑b i)) (↑(dualBasis b) j) State After: no goals Tactic: rw [LinearMap.comp_apply, toDual_apply_left, coe_toDual_self, ← coe_dualBasis,
Dual.eval_apply, Basis.repr_self, Finsupp.single_apply, dualBasis_apply_self]
|
theory Read_Write_Ref
imports Address_Translate_Ref
begin
lemma mmu_write_rel:
"\<lbrakk>mmu_write_size (val,va, sz) s = ((), s')\<rbrakk> \<Longrightarrow> s' = s \<lparr> non_det_tlb := non_det_tlb s' , MEM:= MEM s' , exception:= exception s' \<rparr>"
apply (clarsimp simp: mmu_write_size_non_det_tlb_state_ext_def Let_def, cases "mmu_translate va s", clarsimp split: if_split_asm)
apply (drule write_mem_rel, cases "mmu_translate va s" , clarsimp)
apply (drule mmu_rel, cases s, cases s', case_tac b, clarsimp)
apply (clarsimp simp: mmu_translate_non_det_tlb_state_ext_def Let_def split: lookup_type.splits)
by (clarsimp simp: Let_def raise'exception_def split:if_split_asm)+
lemma mmu_write_tlb_disj:
"\<lbrakk> mmu_write_size (val,va, sz) s = ((), s') \<rbrakk> \<Longrightarrow>
non_det_tlb s' = non_det_tlb s - tlb_evict (typ_non_det_tlb s) \<or> non_det_tlb s' = non_det_tlb s - tlb_evict (typ_non_det_tlb s) \<union> {the (pt_walk () (MEM s) (TTBR0 s) va)}"
apply (clarsimp simp: mmu_write_size_non_det_tlb_state_ext_def mmu_translate_non_det_tlb_state_ext_def split_def Let_def write_mem_eq_TLB raise'exception_def
split: lookup_type.splits split: if_split_asm)
apply (drule write_mem_eq_TLB state.defs)
apply (cases s , cases s' ; clarsimp)
apply (drule write_mem_eq_TLB state.defs)
by(cases s , cases s' ; clarsimp)
lemma mmu_write_det_rel:
"\<lbrakk>mmu_write_size (val,va, sz) s = ((), s')\<rbrakk> \<Longrightarrow> s' = s \<lparr> det_tlb := det_tlb s' , MEM:= MEM s' , exception:= exception s' \<rparr>"
apply (clarsimp simp: mmu_write_size_det_tlb_state_ext_def Let_def, cases "mmu_translate va s", clarsimp split: if_split_asm)
apply (drule write_mem_rel, cases "mmu_translate va s" , clarsimp)
apply (drule mmu_det_rel, cases s, cases s', case_tac b, clarsimp)
apply (clarsimp simp: mmu_translate_det_tlb_state_ext_def Let_def split: lookup_type.splits)
by (clarsimp simp: Let_def raise'exception_def split:if_split_asm)+
lemma mmu_write_tlb_disj_det:
"\<lbrakk> mmu_write_size (val,va, sz) s = ((), s') \<rbrakk> \<Longrightarrow>
det_tlb s' = det_tlb s \<or> det_tlb s' = det_tlb s \<union> {the (pt_walk () (MEM s) (TTBR0 s) va)}"
apply (clarsimp simp: mmu_write_size_det_tlb_state_ext_def mmu_translate_det_tlb_state_ext_def split_def Let_def write_mem_eq_TLB raise'exception_def
split: lookup_type.splits split: if_split_asm)
apply (drule write_mem_eq_TLB state.defs)
apply (cases s , cases s' ; clarsimp)
apply (drule write_mem_eq_TLB state.defs)
by(cases s , cases s' ; clarsimp)
(**************************************************************)
lemma mmu_write_tlb_subset_non_det_det:
"\<lbrakk> mmu_write_size (val,va, sz) s = ((), s'); tlb_rel_det (typ_non_det_tlb s) (typ_det_tlb t); consistent (typ_det_tlb t) va;
mmu_write_size (val,va, sz) t = ((), t') \<rbrakk> \<Longrightarrow> non_det_tlb s' \<subseteq> det_tlb t'"
apply (frule tlb_rel_detD)
apply (subgoal_tac "lookup' (non_det_tlb s - tlb_evict (typ_non_det_tlb s)) va \<le> lookup' (det_tlb t) va")
prefer 2
apply (simp add: sup.absorb1 tlb_mono tlb_rel_det_def)
apply (meson Diff_subset order_trans tlb_mono)
apply (frule mmu_write_tlb_disj)
apply (frule mmu_write_tlb_disj_det)
apply (erule disjE)
apply (clarsimp simp: )
apply blast
apply (erule disjE)
apply clarsimp
apply (rule conjI)
prefer 2
apply blast
apply (clarsimp simp: mmu_write_size_det_tlb_state_ext_def , cases "mmu_translate va t" , clarsimp split: if_split_asm)
apply (clarsimp simp: mmu_translate_det_tlb_state_ext_def)
apply (case_tac "lookup' (det_tlb t) va"; clarsimp simp: Let_def consistent0_def)
apply (clarsimp simp: raise'exception_def split: if_split_asm)
apply (clarsimp simp: write'mem1_def split: if_split_asm)
apply (cases t, cases t', clarsimp simp: state.defs) apply force
apply (cases t, cases t', clarsimp simp: state.defs) apply force
apply (cases t, cases t', clarsimp simp: state.defs) apply force
apply (cases t, cases t', clarsimp simp: state.defs) apply force
apply (clarsimp simp: raise'exception_def split: if_split_asm)
apply (cases t, cases t', clarsimp simp: state.defs) apply force
using lookup_in_tlb apply blast
apply (clarsimp simp: mmu_translate_det_tlb_state_ext_def)
apply (case_tac "lookup' (det_tlb t) va")
apply (subgoal_tac "lookup' (non_det_tlb s - tlb_evict (typ_non_det_tlb s)) va = Miss")
prefer 2
apply force
apply (clarsimp simp: mmu_write_size_non_det_tlb_state_ext_def)
apply (case_tac "mmu_translate va s", clarsimp)
apply (clarsimp simp: mmu_translate_non_det_tlb_state_ext_def)
apply (clarsimp simp: Let_def split: if_split_asm)
apply (case_tac "exception s = NoException")
apply (clarsimp simp: raise'exception_def split: if_split_asm)
apply (thin_tac "raise'exception (PAGE_FAULT ''more info'') t = (a, t')")
apply (clarsimp simp: raise'exception_def split: if_split_asm)
apply (thin_tac "raise'exception (PAGE_FAULT ''more info'') t = (a, t')")
apply (clarsimp simp: raise'exception_def split: if_split_asm)
apply force
apply force
apply force
apply (clarsimp simp: consistent0_def)
apply (simp only: consistent0_def)
apply (metis UnE inf_sup_ord(4) lookup_in_tlb lookup_type.inject lookup_type.simps(5) subset_eq)
apply clarsimp
by blast
lemma write_mem_non_det_det_MEM:
"\<lbrakk> mmu_write_size (val,va, sz) s = ((), s'); tlb_rel_det (typ_non_det_tlb s) (typ_det_tlb t) ; consistent (typ_det_tlb t) va;
mmu_write_size (val,va, sz) t = ((), t') \<rbrakk> \<Longrightarrow> MEM s' = MEM t'"
apply (frule tlb_rel_detD)
apply (clarsimp simp: mmu_write_size_non_det_tlb_state_ext_def , cases "mmu_translate va s" , clarsimp)
apply (clarsimp simp: mmu_write_size_det_tlb_state_ext_def , cases "mmu_translate va t" , clarsimp)
apply (clarsimp split: if_split_asm)
apply (case_tac "write'mem1 (val, aa, sz) ba" , clarsimp)
apply (subgoal_tac "MEM b = MEM ba \<and> aa = a")
using write_same_mem apply blast
apply (rule conjI)
apply (clarsimp simp: mmu_eq_asid_root_mem mmu_det_eq_asid_root_mem)
apply (frule_tac s= "(typ_non_det_tlb s)" and va= "va" in tlb_rel_det_consistent, clarsimp)
apply (subgoal_tac "non_det_tlb s - tlb_evict (typ_non_det_tlb s) \<subseteq> non_det_tlb s")
prefer 2
apply blast
apply (subgoal_tac "lookup' (non_det_tlb s - tlb_evict (typ_non_det_tlb s)) va \<le> lookup' (det_tlb t) va")
prefer 2
apply (simp add: sup.absorb1 tlb_mono tlb_rel_det_def)
apply (clarsimp simp: mmu_translate_non_det_tlb_state_ext_def mmu_translate_det_tlb_state_ext_def split_def Let_def)
apply (cases "lookup' (det_tlb t) va"; clarsimp)
apply (clarsimp simp: tlb_rel_det_def Let_def raise'exception_def state.defs split: if_split_asm)
apply (clarsimp simp: consistent0_def)
apply (subgoal_tac "x3 = the (pt_walk () (MEM s) (TTBR0 s) va)")
prefer 2
apply (clarsimp simp: consistent0_def)
apply (cases "lookup' (non_det_tlb s - tlb_evict (typ_non_det_tlb s)) va"; clarsimp)
apply (clarsimp simp: Let_def)
apply (cases "\<not>is_fault (pt_walk () (MEM s) (TTBR0 s) va)")
apply (clarsimp simp: tlb_rel_det_def typ_det_tlb_def typ_non_det_tlb_def state.defs lookup_in_tlb raise'exception_def split: if_split_asm)
apply (clarsimp simp: tlb_rel_det_def typ_det_tlb_def typ_non_det_tlb_def state.defs lookup_in_tlb raise'exception_def split: if_split_asm)
using mmu_translate_non_det_det_excp mmu_translate_non_det_det_pa apply fastforce
using mmu_translate_non_det_det_excp mmu_translate_non_det_det_pa apply fastforce
by (simp add: mmu_det_eq_asid_root_mem mmu_eq_asid_root_mem)
lemma mmu_write_size_det_non_det_state_trun:
"\<lbrakk>mmu_write_size (val,va, sz) s = ((), s'); tlb_rel_det(typ_non_det_tlb s) (typ_det_tlb t) ; consistent (typ_det_tlb t) va;
mmu_write_size (val,va, sz) t = ((), t')\<rbrakk> \<Longrightarrow> state.truncate t' = state.truncate s'"
apply (frule (3) write_mem_non_det_det_MEM)
apply (frule tlb_rel_detD, clarsimp)
apply (frule mmu_write_rel)
apply (rotate_tac)
apply (frule mmu_write_det_rel)
apply (clarsimp simp: tlb_rel_det_def)
apply (subgoal_tac "exception s' = exception t'")
apply (cases s, cases t, cases s' , cases t')
apply (clarsimp simp: state.defs det_tlb_state.defs)
apply (clarsimp simp: mmu_write_size_non_det_tlb_state_ext_def mmu_write_size_det_tlb_state_ext_def Let_def)
apply (case_tac "mmu_translate va t" , case_tac "write'mem1 (val, a, sz) b" , clarsimp)
apply (case_tac "mmu_translate va s" , clarsimp)
apply (subgoal_tac "exception b = exception bb \<and> a = aa")
apply (clarsimp split: if_split_asm)
apply (subgoal_tac "MEM b = MEM bb ")
apply (frule_tac s="bb" and s'="s'" and t = b and t' = t' in write_same_mem_excep ; clarsimp)
apply (frule_tac s="s" and s'="bb" and t = t and t' = b and p' = aa in mmu_translate_non_det_det_mem_excp ; clarsimp simp: consistent0_def tlb_rel_det_def)
apply (rule conjI)
apply (frule_tac t= t and pa' = a and t' = b in mmu_translate_non_det_det_pa)
apply (clarsimp simp: tlb_rel_det_def)
apply (clarsimp simp: consistent0_def)
apply (clarsimp simp: tlb_rel_det_def)
apply (frule_tac s = "s" and s' = "bb" and t = "t" and t' = "b" in mmu_translate_non_det_det_excp ; clarsimp simp: tlb_rel_det_def)
apply (subgoal_tac "non_det_tlb s - tlb_evict (typ_non_det_tlb s) \<subseteq> non_det_tlb s")
prefer 2
apply blast
apply (subgoal_tac "lookup' (non_det_tlb s - tlb_evict (typ_non_det_tlb s)) va \<le> lookup' (det_tlb t) va")
prefer 2
apply (simp add: sup.absorb1 tlb_mono tlb_rel_det_def)
apply (clarsimp simp: mmu_translate_non_det_tlb_state_ext_def mmu_translate_det_tlb_state_ext_def split_def Let_def)
apply (cases "lookup' (det_tlb t) va")
apply clarsimp
prefer 2
apply (clarsimp simp: consistent0_def)
apply (clarsimp simp: tlb_rel_det_def Let_def)
apply (cases "(is_fault (pt_walk () (MEM s) (TTBR0 s) va))")
apply (clarsimp simp: raise'exception_def state.defs split: if_split_asm)
apply (clarsimp simp: lookup_def entry_set_def split: if_split_asm)
apply clarsimp
apply (subgoal_tac "x3 = the (pt_walk () (MEM s) (TTBR0 s) va)")
prefer 2
apply (clarsimp simp: consistent0_def)
apply (cases "lookup' (non_det_tlb s - tlb_evict (typ_non_det_tlb s)) va"; clarsimp)
by (clarsimp simp: Let_def consistent0_def)
lemma mmu_write_non_det_det_refine:
"\<lbrakk> mmu_write_size (val,va, sz) s = ((), s'); tlb_rel_det (typ_non_det_tlb s) (typ_det_tlb t) ; consistent (typ_det_tlb t) va;
mmu_write_size (val,va, sz) t = ((), t') \<rbrakk> \<Longrightarrow> tlb_rel_det (typ_non_det_tlb s') (typ_det_tlb t') "
apply (clarsimp simp: tlb_rel_det_def)
apply (rule conjI)
prefer 2
apply (frule_tac s = s and s' = s' and t = t and t' = t' in mmu_write_tlb_subset_non_det_det; clarsimp simp: tlb_rel_det_def)
apply (frule_tac s="s" and s'="s'" and t="t" and t'="t'" in mmu_write_size_det_non_det_state_trun; clarsimp simp: tlb_rel_det_def)
done
lemma mmu_write_saturated_state:
"\<lbrakk>mmu_write_size (val,va,sz) s = ((), t) \<rbrakk> \<Longrightarrow> saturated (typ_sat_tlb t)"
apply (clarsimp simp: mmu_write_size_sat_tlb_state_ext_def Let_def)
apply (case_tac "mmu_translate va s" , clarsimp)
apply (clarsimp split: if_split_asm)
apply (case_tac "write'mem1 (val, a, sz) b" , clarsimp)
apply (subgoal_tac " TTBR0 s = TTBR0 ba ")
apply (clarsimp simp: saturated_def)
apply (subgoal_tac " TTBR0 s = TTBR0 b")
apply clarsimp
apply (clarsimp simp: write'mem1_def Let_def)
apply (clarsimp split: if_split_asm)
apply (clarsimp simp: raise'exception_def)
apply (clarsimp simp: mmu_translate_sat_tlb_state_ext_def Let_def raise'exception_def split:lookup_type.splits if_split_asm)
using mmu_translate_saturated_state surjective_pairing by blast
lemma mmu_wrtie_sat_rel:
"\<lbrakk>mmu_write_size (val,va, sz) s = ((), s')\<rbrakk> \<Longrightarrow>
s' = s \<lparr> sat_tlb := sat_tlb s' , MEM:= MEM s' , exception:= exception s' \<rparr>"
apply (clarsimp simp: mmu_write_size_sat_tlb_state_ext_def Let_def)
apply (cases "mmu_translate va s" , clarsimp)
apply (clarsimp split: if_split_asm)
apply (case_tac " write'mem1 (val, a, sz) b", clarsimp)
apply (drule write_mem_rel)
apply (drule mmu_sat_rel)
apply (cases s, cases s', case_tac a, case_tac b, case_tac ba)
apply clarsimp
apply (clarsimp simp: mmu_translate_sat_tlb_state_ext_def Let_def split: lookup_type.splits)
apply (clarsimp simp: raise'exception_def split:if_split_asm)
by (clarsimp simp: raise'exception_def split:if_split_asm)
lemma wrtie_mem_sat_tlbs:
"\<lbrakk>mmu_write_size (val,va, sz) s = ((), s') \<rbrakk> \<Longrightarrow>
sat_tlb s' = sat_tlb s \<union> the `{e\<in>pt_walk () (MEM s) (TTBR0 s) ` UNIV. \<not> is_fault e} \<or>
sat_tlb s' = sat_tlb s \<union> the `{e\<in>pt_walk () (MEM s) (TTBR0 s) ` UNIV. \<not> is_fault e} \<union> the `{e\<in>pt_walk () (MEM s') (TTBR0 s') ` UNIV. \<not> is_fault e}"
apply (cases "exception (snd (mmu_translate va s)) \<noteq> NoException")
apply (rule disjI1)
apply (clarsimp simp: mmu_write_size_sat_tlb_state_ext_def Let_def)
apply (case_tac "mmu_translate va s" , clarsimp)
apply (clarsimp simp: mmu_translate_sat_tlb_union)
apply (clarsimp simp: mmu_write_size_sat_tlb_state_ext_def Let_def)
apply (case_tac "mmu_translate va s " , clarsimp)
apply (case_tac "write'mem1 (val, a, sz) b" , clarsimp)
apply (subgoal_tac "sat_tlb ba = sat_tlb b")
apply (subgoal_tac "sat_tlb b = sat_tlb s \<union> the `{e\<in>pt_walk () (MEM s) (TTBR0 s) ` UNIV. \<not> is_fault e}")
apply (subgoal_tac " TTBR0 ba = TTBR0 s")
apply clarsimp
apply (subgoal_tac " TTBR0 b = TTBR0 s")
apply (simp add: write_mem1_eq_ASID_TTBR0)
apply (simp add: mmu_sat_eq_asid_root_mem)
apply (clarsimp simp: mmu_translate_sat_tlb_union)
apply (drule write_mem_eq_TLB)
apply (case_tac ba , case_tac b ; clarsimp)
done
lemma mmu_write_tlb_subset:
"\<lbrakk> mmu_write_size (val,va, sz) s = ((), s'); tlb_rel_sat (typ_det_tlb s) (typ_sat_tlb t) ; consistent (typ_sat_tlb t) va ;
mmu_write_size (val,va, sz) t = ((), t') \<rbrakk> \<Longrightarrow>
det_tlb s' \<subseteq> sat_tlb t'"
apply (frule tlb_rel_satD)
apply (clarsimp simp: mmu_write_size_det_tlb_state_ext_def , cases "mmu_translate va s" , clarsimp)
apply (clarsimp simp: mmu_write_size_sat_tlb_state_ext_def , cases "mmu_translate va t" , clarsimp)
apply (frule_tac t' = ba and s' = b and t = t and s = s and pa' = aa in mmu_translate_det_sat_subset_rel; simp?)
apply (subgoal_tac "det_tlb b = det_tlb s'", clarsimp split: if_split_asm)
apply (case_tac "write'mem1 (val, aa, sz) ba", clarsimp simp:)
apply (subgoal_tac "state.more bb = state.more ba")
apply force
apply (drule write_mem_eq_TLB)
apply (drule write_mem_eq_TLB)
apply (clarsimp simp: typ_sat_tlb_def) apply force
apply (case_tac "write'mem1 (val, aa, sz) ba", simp)
apply (subgoal_tac "state.more ba = state.more b")
apply force
apply (drule write_mem_eq_TLB)
apply (clarsimp simp: typ_sat_tlb_def)
apply (clarsimp simp: typ_sat_tlb_def) apply force
apply (clarsimp split: if_split_asm)
apply (drule write_mem_eq_TLB)
apply (cases s' , case_tac b, clarsimp simp:)
apply (drule write_mem_eq_TLB)
by (cases s' , case_tac b, clarsimp simp:)
lemma mmu_write_det_sat_mem:
"\<lbrakk> mmu_write_size (val,va, sz) s = ((), s'); tlb_rel_sat (typ_det_tlb s) (typ_sat_tlb t) ; consistent (typ_sat_tlb t) va;
mmu_write_size (val,va, sz) t = ((), t') \<rbrakk> \<Longrightarrow> MEM s' = MEM t'"
apply (frule tlb_rel_satD)
apply (clarsimp simp: mmu_write_size_det_tlb_state_ext_def , cases "mmu_translate va s" , clarsimp)
apply (clarsimp simp: mmu_write_size_sat_tlb_state_ext_def , cases "mmu_translate va t" , clarsimp)
apply (subgoal_tac "MEM ba = MEM b \<and> exception ba = exception b")
prefer 2
apply (frule_tac t = t and t' = ba in mmu_translate_non_det_sat_mem_excp; simp?)
apply (subgoal_tac "a = aa")
prefer 2
apply (frule mmu_translate_non_det_sat_pa; simp)
apply simp
apply (clarsimp split: if_split_asm)
apply (case_tac "write'mem1 (val, aa, sz) ba", simp)
apply (frule_tac t = ba and t' = bb in write_same_mem, simp, simp)
by (case_tac bb, cases t', simp)
lemma mmu_write_size_det_sat_state_trunc:
"\<lbrakk>mmu_write_size (val,va, sz) s = ((), s'); tlb_rel_sat (typ_det_tlb s) (typ_sat_tlb t) ; consistent (typ_sat_tlb t) va;
mmu_write_size (val,va, sz) t = ((), t')\<rbrakk> \<Longrightarrow> state.truncate t' = state.truncate s'"
apply (frule (3) mmu_write_det_sat_mem)
apply (frule tlb_rel_satD, clarsimp)
apply (frule mmu_write_det_rel)
apply (rotate_tac)
apply (frule mmu_wrtie_sat_rel)
apply (clarsimp simp: tlb_rel_sat_def)
apply (subgoal_tac "exception s' = exception t'")
apply (cases s, cases t, cases s' , cases t')
apply (clarsimp simp: state.defs)
apply (clarsimp simp: mmu_write_size_sat_tlb_state_ext_def mmu_write_size_det_tlb_state_ext_def Let_def)
apply (case_tac "mmu_translate va t" , case_tac "write'mem1 (val, a, sz) b" , clarsimp)
apply (case_tac "mmu_translate va s" , clarsimp?)
apply (subgoal_tac "exception b = exception bb \<and> a = aa")
apply (clarsimp split: if_split_asm)
apply (subgoal_tac "MEM b = MEM bb ")
apply (frule_tac s="bb" and s'="s'" and t = b and t' = ba in write_same_mem_excep ; clarsimp?)
apply (frule_tac s="s" and s'="bb" and t = t and t' = b and p' = aa in mmu_translate_non_det_sat_mem_excp ; clarsimp simp: consistent0_def tlb_rel_sat_def)
apply (rule conjI)
apply (frule_tac s = "s" and s' = "bb" and t = "t" and t' = "b" in mmu_translate_non_det_sat_excp ; clarsimp simp: tlb_rel_sat_def)
by (frule_tac t= t and pa' = a and t' = b in mmu_translate_non_det_sat_pa ; clarsimp simp: tlb_rel_sat_def) +
lemma mmu_write_det_sat_refine:
"\<lbrakk> mmu_write_size (val,va, sz) s = ((), s'); tlb_rel_sat (typ_det_tlb s) (typ_sat_tlb t) ; consistent (typ_sat_tlb t) va;
mmu_write_size (val,va, sz) t = ((), t') \<rbrakk> \<Longrightarrow> tlb_rel_sat (typ_det_tlb s') (typ_sat_tlb t') "
apply (clarsimp simp: tlb_rel_sat_def)
apply (clarsimp simp: mmu_write_saturated_state )
apply (rule conjI)
prefer 2
apply (frule_tac s="s" and s'="s'" and t="t" and t'="t'" in mmu_write_tlb_subset; clarsimp simp: tlb_rel_sat_def)
apply (frule_tac s="s" and s'="s'" and t="t" and t'="t'" in mmu_write_size_det_sat_state_trunc; clarsimp simp: tlb_rel_sat_def)
done
(* refinement between saturated and second abstracted model *)
(*lemma pt_walk_new_equal_pt_walk:
"pt_walk_pair a m rt v = pt_walk_pair a' m' rt' v \<Longrightarrow> pt_walk () a m rt v = pt_walk () a' m' rt' v"
by (cases "pt_walk_pair a m rt v"; cases "pt_walk_pair a' m' rt' v";
clarsimp simp: pt_walk_new_fault_pt_walk_fault' pt_walk_new_par_fault_pt_walk_fault'
pt_walk_new_no_fault_pt_walk)
*)
lemma not_elem_rewrite':
"bb
\<notin>
{va. \<not> is_fault (pt_walk () (MEM b) (TTBR0 b) va) \<and> \<not> is_fault (pt_walk () (MEM bc) (TTBR0 b) va) \<and> pt_walk () (MEM b) (TTBR0 b) va \<noteq> pt_walk () (MEM bc) (TTBR0 b) va \<or>
\<not> is_fault (pt_walk () (MEM b) (TTBR0 b) va) \<and> is_fault (pt_walk () (MEM bc) (TTBR0 b) va)} \<Longrightarrow>
(is_fault (pt_walk () (MEM b) (TTBR0 b) bb) \<or> is_fault (pt_walk () (MEM bc) (TTBR0 b) bb) \<or> pt_walk () (MEM b) (TTBR0 b) bb = pt_walk () (MEM bc) (TTBR0 b) bb) \<and>
(is_fault (pt_walk () (MEM b) (TTBR0 b) bb) \<or> \<not> is_fault (pt_walk () (MEM bc) (TTBR0 b) bb)) "
by force
lemma mmu_write_incon_set_rel:
"\<lbrakk> saturated (typ_sat_tlb s) ;
inconsistent_vaddrs (typ_sat_tlb s) \<subseteq> set_tlb t ; incoherrent_vaddrs (typ_sat_tlb s) \<subseteq> set_tlb t ; TTBR0 s = TTBR0 r\<rbrakk> \<Longrightarrow>
inconsistent_vaddrs (typ_sat_tlb (r\<lparr>sat_tlb := sat_tlb s \<union> the ` {e \<in> range (pt_walk () (MEM q) (TTBR0 r)). \<not> is_fault e}\<rparr>))
\<subseteq> set_tlb t \<union> incon_comp (MEM s) (MEM q) (TTBR0 r) (TTBR0 r)"
apply (clarsimp)
apply (clarsimp simp: inconsistent_vaddrs_def incon_comp_def ptable_comp_def incoherrent_vaddrs_def)
apply (erule disjE)
apply (erule disjE)
apply (drule union_incon_cases)
apply (erule disjE, clarsimp simp: lookup_range_pt_walk_not_incon)
apply (erule disjE, blast)
apply (erule disjE, blast)
apply (erule disjE, blast)
apply (erule disjE, clarsimp simp: lookup_range_pt_walk_not_incon)
apply blast
apply (drule union_incon_cases)
apply (erule disjE, clarsimp simp: lookup_range_pt_walk_not_incon)
apply (erule disjE, blast)
apply (erule disjE, blast)
apply (erule disjE, blast)
apply (erule disjE, clarsimp simp: lookup_range_pt_walk_not_incon)
apply blast
apply (erule disjE)
apply (erule disjE)
apply (drule union_incon_cases)
apply (erule disjE, clarsimp simp: lookup_range_pt_walk_not_incon)
apply (erule disjE, blast)
apply (erule disjE, blast)
apply (erule disjE, blast)
apply (erule disjE, clarsimp simp: lookup_range_pt_walk_not_incon)
apply blast
apply (drule union_incon_cases)
apply (erule disjE, clarsimp simp: lookup_range_pt_walk_not_incon)
apply (erule disjE, blast)
apply (erule disjE, blast)
apply (erule disjE, blast)
apply (erule disjE, clarsimp simp: lookup_range_pt_walk_not_incon)
apply blast
apply (drule union_incon_cases)
apply (erule disjE, clarsimp simp: lookup_range_pt_walk_not_incon)
apply (erule disjE, blast)
apply (erule disjE, clarsimp)
apply (subgoal_tac "the (pt_walk () (MEM q) (TTBR0 r) xc) = the (pt_walk () (MEM q) (TTBR0 r) x)")
apply clarsimp
using saturatd_lookup_hit_no_fault apply fastforce
apply (frule lookup_range_fault_pt_walk)
apply (drule_tac x = x in bspec)
using lookup_hit_entry_range_asid_tags apply blast
apply clarsimp
using lookup_range_pt_walk_not_incon by blast
lemma mmu_write_asid_ptcomp_rel:
"\<lbrakk>saturated (typ_sat_tlb s) ; MEM t = MEM r; TTBR0 t = TTBR0 s ;
inconsistent_vaddrs (typ_sat_tlb s) \<subseteq> set_tlb q ; incoherrent_vaddrs (typ_sat_tlb s) \<subseteq> set_tlb q\<rbrakk> \<Longrightarrow>
incoherrent_vaddrs (typ_sat_tlb (t\<lparr>sat_tlb := sat_tlb s \<union> the ` {e \<in> range (pt_walk () (MEM r) (TTBR0 t)). \<not> is_fault e}\<rparr>)) \<subseteq> set_tlb q \<union>
incon_comp (MEM s) (MEM r) (TTBR0 t) (TTBR0 t)"
apply rule
apply (clarsimp simp: incoherrent_vaddrs_def inconsistent_vaddrs_def )
apply (drule lookup_hit_union_cases')
apply (erule disjE)
apply (clarsimp simp: incon_comp_def ptable_comp_def Let_def)
apply (subgoal_tac "is_fault (pt_walk () (MEM s) (TTBR0 s) x)")
apply blast
apply blast
by (clarsimp simp: lookup_miss_is_fault_intro)
lemma mmu_write_sat_incon_refine:
"\<lbrakk> mmu_write_size (val,va, sz) s = ((), s'); mmu_write_size (val,va, sz) t = ((), t'); va \<notin> set_tlb t;
tlb_rel_abs (typ_sat_tlb s) (typ_set_tlb t) \<rbrakk> \<Longrightarrow>
tlb_rel_abs (typ_sat_tlb s') (typ_set_tlb t')"
apply (frule_tac s = s in tlb_rel_abs_consistent ; clarsimp )
apply (frule tlb_rel_absD , clarsimp)
apply (clarsimp simp: mmu_write_size_sat_tlb_state_ext_def mmu_write_size_set_tlb_state_ext_def)
apply (cases "mmu_translate va s", cases "mmu_translate va t" , clarsimp)
apply (frule_tac t= t and pa'= aa and t' = ba in mmu_translate_sat_incon_refine; clarsimp)
apply (clarsimp simp: tlb_rel_abs_def)
apply (subgoal_tac "exception b = exception ba")
prefer 2 apply (case_tac b , case_tac ba , clarsimp simp: state.defs)
apply (clarsimp split: if_split_asm)
apply (case_tac "write'mem1 (val, aa, sz) b " , case_tac "write'mem1 (val, aa, sz) ba" , clarsimp simp: Let_def)
apply (subgoal_tac "state.truncate bb = state.truncate bc")
prefer 2
using write_mem_state_trun_equal apply blast
apply (rule conjI , clarsimp simp: state.defs)
apply (subgoal_tac "MEM bb = MEM bc \<and> MEM s = MEM b" , simp)
apply (subgoal_tac " TTBR0 s = TTBR0 b" , simp)
apply (subgoal_tac "saturated (typ_sat_tlb b)")
prefer 2 apply blast
prefer 2 using mmu_sat_eq_asid_root_mem apply blast
prefer 2
apply (rule conjI)
apply (clarsimp simp: state.defs)
using mmu_sat_eq_asid_root_mem
apply blast
apply (subgoal_tac "TTBR0 b = TTBR0 bb")
apply (simp only: incon_addrs_def)
apply simp
apply (rule conjI)
apply (drule_tac s = b and t = ba and q = bc and r = bb in mmu_write_incon_set_rel; clarsimp)
apply (rule conjI)
apply (frule_tac t = bb and r = bc and q = ba and s = b in mmu_write_asid_ptcomp_rel ; clarsimp simp: )
apply (clarsimp simp: saturated_def)
by (simp add: write_mem1_eq_ASID_TTBR0)
(* refinement for read theroems *)
lemma mem_read1_consistent_tlb_rel_non_det_det:
" \<lbrakk>mem_read1 (a, sz) s = (val, s'); mem_read1 (a, sz) t = (val', t');
consistent0 (lookup' (det_tlb t)) (pt_walk () (MEM t) (TTBR0 t)) va; tlb_rel_det (typ_non_det_tlb s) (typ_det_tlb t)\<rbrakk>
\<Longrightarrow> consistent0 (lookup' (det_tlb t')) (pt_walk () (MEM t') (TTBR0 t')) va \<and> tlb_rel_det (typ_non_det_tlb s') (typ_det_tlb t')"
apply (rule conjI)
apply (subgoal_tac "MEM t = MEM t' \<and> TTBR0 t = TTBR0 t' \<and> det_tlb t = det_tlb t'")
apply (clarsimp simp: consistent0_def)
prefer 2
apply (subgoal_tac " exception s' = exception t'")
apply (drule mem1_read_exception)
apply (drule mem1_read_exception)
apply (clarsimp simp: tlb_rel_det_def)
apply (clarsimp simp: saturated_def state.truncate_def)
apply (cases s', cases t')
apply clarsimp
apply (subgoal_tac "MEM s = MEM t \<and> exception s = exception t")
apply (thin_tac "tlb_rel_det (typ_non_det_tlb s) (typ_det_tlb t)")
apply (clarsimp simp: mem_read1_def)
apply (clarsimp split: if_split_asm)
apply (clarsimp simp: mem1_def raise'exception_def split: option.splits if_split_asm)
apply (clarsimp simp: mem1_def raise'exception_def split: option.splits if_split_asm)
apply (clarsimp simp: mem1_def raise'exception_def split: option.splits if_split_asm)
subgoal
by (clarsimp simp: mem1_def raise'exception_def split: option.splits if_split_asm)
apply (clarsimp simp: raise'exception_def split: option.splits if_split_asm)
apply (clarsimp simp: tlb_rel_det_def state.defs)
apply (drule mem1_read_exception)
apply (drule mem1_read_exception)
apply (cases t, cases t' , clarsimp)
done
lemma mem_read1_consistent_tlb_rel_det_sat:
" \<lbrakk>mem_read1 (a, sz) s = (val, s'); mem_read1 (a, sz) t = (val', t');
consistent0 (lookup' (sat_tlb t)) (pt_walk () (MEM t) (TTBR0 t)) va; tlb_rel_sat (typ_det_tlb s) (typ_sat_tlb t)\<rbrakk>
\<Longrightarrow> consistent0 (lookup' (sat_tlb t')) (pt_walk () (MEM t') (TTBR0 t')) va \<and> tlb_rel_sat (typ_det_tlb s') (typ_sat_tlb t')"
apply (rule conjI)
apply (subgoal_tac "MEM t = MEM t' \<and> TTBR0 t = TTBR0 t' \<and> sat_tlb t = sat_tlb t'")
apply (clarsimp simp: consistent0_def)
prefer 2
apply (subgoal_tac " exception s' = exception t'")
apply (drule mem1_read_exception)
apply (drule mem1_read_exception)
apply (clarsimp simp: tlb_rel_sat_def)
apply (clarsimp simp: saturated_def state.truncate_def)
apply (cases s', cases t')
apply clarsimp
apply (subgoal_tac "MEM s = MEM t \<and> exception s = exception t")
apply (thin_tac "tlb_rel_sat (typ_det_tlb s) (typ_sat_tlb t)")
apply (clarsimp simp: mem_read1_def)
apply (clarsimp split: if_split_asm)
apply (clarsimp simp: mem1_def raise'exception_def split: option.splits if_split_asm)
apply (clarsimp simp: mem1_def raise'exception_def split: option.splits if_split_asm)
apply (clarsimp simp: mem1_def raise'exception_def split: option.splits if_split_asm)
subgoal
by (clarsimp simp: mem1_def raise'exception_def split: option.splits if_split_asm)
apply (clarsimp simp: raise'exception_def split: option.splits if_split_asm)
apply (clarsimp simp: tlb_rel_sat_def state.defs)
apply (drule mem1_read_exception)
apply (drule mem1_read_exception)
apply (cases t, cases t' , clarsimp)
done
lemma mmu_read_non_det_det_rel_cons:
"\<lbrakk> mmu_read_size (va, sz) s = (val, s'); tlb_rel_det (typ_non_det_tlb s) (typ_det_tlb t);
consistent (typ_det_tlb t) va; mmu_read_size (va, sz) t = (val', t') \<rbrakk> \<Longrightarrow>
consistent (typ_det_tlb t') va \<and> tlb_rel_det (typ_non_det_tlb s') (typ_det_tlb t') "
apply (clarsimp simp: mmu_read_size_det_tlb_state_ext_def mmu_read_size_non_det_tlb_state_ext_def Let_def)
apply (cases "mmu_translate va s", cases "mmu_translate va t", clarsimp)
apply (drule_tac t = t in mmu_translate_non_det_det_refine ; clarsimp simp: Let_def mem_read1_consistent_tlb_rel_non_det_det)
done
lemma mmu_read_det_sat_rel_cons:
"\<lbrakk> mmu_read_size (va, sz) s = (val, s'); tlb_rel_sat (typ_det_tlb s) (typ_sat_tlb t);
consistent (typ_sat_tlb t) va; mmu_read_size (va, sz) t = (val', t') \<rbrakk> \<Longrightarrow>
consistent (typ_sat_tlb t') va \<and> tlb_rel_sat (typ_det_tlb s') (typ_sat_tlb t') "
apply (clarsimp simp: mmu_read_size_sat_tlb_state_ext_def mmu_read_size_det_tlb_state_ext_def Let_def)
apply (cases "mmu_translate va s", cases "mmu_translate va t", clarsimp)
apply (drule_tac t = t in mmu_translate_det_sat_refine ; clarsimp simp: Let_def mem_read1_consistent_tlb_rel_det_sat)
done
lemma same_mem_read_equal:
"\<lbrakk>MEM s = MEM t; mem_read1 (pa, sz) s = (val, s'); mem_read1 (pa, sz) t = (val', t') \<rbrakk> \<Longrightarrow> val = val'"
apply (clarsimp simp: mem_read1_def)
apply (clarsimp split: if_split_asm)
apply (clarsimp simp: mem1_def raise'exception_def split: option.splits if_split_asm)
apply (clarsimp simp: mem1_def raise'exception_def split: option.splits if_split_asm)
apply (clarsimp simp: mem1_def raise'exception_def split: option.splits if_split_asm)
subgoal
by (clarsimp simp: mem1_def raise'exception_def split: option.splits if_split_asm)
apply (clarsimp simp: raise'exception_def split: option.splits if_split_asm)
done
lemma mmu_read_non_det_det_refine:
"\<lbrakk>mmu_read_size (va, sz) s = (val, s'); mmu_read_size (va, sz) t = (val', t');
tlb_rel_det (typ_non_det_tlb s) (typ_det_tlb t); consistent (typ_det_tlb t) va\<rbrakk> \<Longrightarrow>
val = val' \<and> tlb_rel_det (typ_non_det_tlb s') (typ_det_tlb t') \<and> consistent (typ_det_tlb t') va "
apply (rule conjI)
apply (clarsimp simp: mmu_read_size_det_tlb_state_ext_def mmu_read_size_non_det_tlb_state_ext_def Let_def)
apply (cases "mmu_translate va s", cases "mmu_translate va t", clarsimp)
apply (rename_tac pa s'' pa' t'')
apply (subgoal_tac "pa = pa'", clarsimp)
apply (subgoal_tac "MEM s'' = MEM t''")
apply (clarsimp simp: same_mem_read_equal)
using mmu_det_eq_asid_root_mem mmu_eq_asid_root_mem tlb_rel_detD apply fastforce
apply (metis (mono_tags, lifting) case_prodD det_tlb_more mmu_translate_non_det_det_refine tlb_rel_det_def typ_det_prim_parameter)
apply (frule_tac t = t and t' =t' in mmu_read_non_det_det_rel_cons; simp?)
done
lemma mmu_read_non_det_sat_refine:
"\<lbrakk>mmu_read_size (va, sz) s = (val, s'); mmu_read_size (va, sz) t = (val', t');
tlb_rel_sat (typ_det_tlb s) (typ_sat_tlb t); consistent (typ_sat_tlb t) va\<rbrakk> \<Longrightarrow>
val = val' \<and> tlb_rel_sat (typ_det_tlb s') (typ_sat_tlb t') \<and> consistent (typ_sat_tlb t') va "
apply (rule conjI)
apply (clarsimp simp: mmu_read_size_det_tlb_state_ext_def mmu_read_size_sat_tlb_state_ext_def Let_def)
apply (cases "mmu_translate va s", cases "mmu_translate va t", clarsimp)
apply (rename_tac pa s'' pa' t'')
apply (subgoal_tac "pa = pa'", clarsimp)
apply (subgoal_tac "MEM s'' = MEM t''")
apply (clarsimp simp: same_mem_read_equal)
using mmu_det_eq_asid_root_mem mmu_sat_eq_asid_root_mem tlb_rel_satD apply fastforce
apply (simp add: mmu_translate_non_det_sat_pa)
apply (frule_tac t = t and t' =t' in mmu_read_det_sat_rel_cons; simp?)
done
lemma mmu_read_sat_const_inter [simp]:
"saturated (typ_sat_tlb s) \<Longrightarrow> sat_tlb (snd (mmu_read_size v s)) = sat_tlb s "
by (clarsimp simp: mmu_read_size_sat_tlb_state_ext_def split_def Let_def
mem_read1_def raise'exception_def split: if_split_asm)
lemma mem_read1_consistent_tlb_rel_incon:
"\<lbrakk>mem_read1 (a, sz) s = (val, s'); mem_read1 (a, sz) t = (val', t');
va \<notin> set_tlb t; tlb_rel_abs (typ_sat_tlb s) (typ_set_tlb t)\<rbrakk>
\<Longrightarrow> va \<notin> set_tlb t' \<and> tlb_rel_abs (typ_sat_tlb s') (typ_set_tlb t')"
apply (rule conjI)
apply (subgoal_tac "set_tlb t = set_tlb t'")
apply clarsimp
apply (drule mem1_read_exception)
apply (drule mem1_read_exception)
apply (cases t, cases t')
apply clarsimp
apply (subgoal_tac "exception s' = exception t'")
apply (drule mem1_read_exception)
apply (drule mem1_read_exception)
apply (clarsimp simp: tlb_rel_abs_def)
apply (rule conjI)
apply (clarsimp simp: state.defs)
apply (cases s', cases t')
apply clarsimp
apply (rule conjI)
apply (clarsimp simp: incon_addrs_def inconsistent_vaddrs_def incoherrent_vaddrs_def)
apply (cases s', cases t')
apply clarsimp
apply (clarsimp simp: saturated_def)
apply (subgoal_tac "MEM s = MEM t \<and> exception s = exception t")
apply (thin_tac " va \<notin> set_tlb t")
apply (thin_tac " tlb_rel_abs (typ_sat_tlb s) (typ_set_tlb t)")
apply (clarsimp simp: mem_read1_def)
apply (clarsimp split: if_split_asm)
apply (clarsimp simp: mem1_def raise'exception_def split: option.splits if_split_asm)
apply (clarsimp simp: mem1_def raise'exception_def split: option.splits if_split_asm)
apply (clarsimp simp: mem1_def raise'exception_def split: option.splits if_split_asm)
subgoal
by (clarsimp simp: mem1_def raise'exception_def split: option.splits if_split_asm)
apply (clarsimp simp: raise'exception_def split: option.splits if_split_asm)
apply (clarsimp simp: tlb_rel_abs_def state.defs)
done
lemma mmu_read_sat_incon_rel_con:
"\<lbrakk> mmu_read_size (va, sz) s = (val, s'); tlb_rel_abs (typ_sat_tlb s) (typ_set_tlb t);
va \<notin> set_tlb t; mmu_read_size (va, sz) t = (val', t') \<rbrakk> \<Longrightarrow>
va \<notin> set_tlb t' \<and> tlb_rel_abs (typ_sat_tlb s') (typ_set_tlb t') "
apply (clarsimp simp: mmu_read_size_sat_tlb_state_ext_def mmu_read_size_set_tlb_state_ext_def Let_def)
apply (cases "mmu_translate va s", cases "mmu_translate va t", clarsimp)
apply (drule_tac t = t and pa' = aa and t' = ba in mmu_translate_sat_incon_refine ; clarsimp simp: Let_def mem_read1_consistent_tlb_rel_incon)
done
lemma mmu_read_sat_incon_refine:
"\<lbrakk> mmu_read_size (va, sz) s = (val, s'); mmu_read_size (va, sz) t = (val', t');
tlb_rel_abs (typ_sat_tlb s) (typ_set_tlb t); va \<notin> set_tlb t \<rbrakk> \<Longrightarrow>
val = val' \<and> tlb_rel_abs (typ_sat_tlb s') (typ_set_tlb t') \<and> va \<notin> set_tlb t'"
apply (rule conjI)
apply (clarsimp simp: mmu_read_size_sat_tlb_state_ext_def mmu_read_size_set_tlb_state_ext_def Let_def)
apply (cases "mmu_translate va s", cases "mmu_translate va t", clarsimp)
apply (rename_tac pa s'' pa' t'')
apply (subgoal_tac "pa = pa'", clarsimp)
apply (subgoal_tac "MEM s'' = MEM t''")
apply (clarsimp simp: same_mem_read_equal)
using mmu_translate_sat_incon_mem_excp apply force
using mmu_translate_sat_incon_refine apply force
by (frule_tac t = t and t' =t' in mmu_read_sat_incon_rel_con; simp)
end
|
Logo of the company is the most essential visual representation of the company. Logo is the soul of the company. It is something through which people identify and relate the company. Today, the corporate logos design is not only used as a trademark of the company, but also for promotional factor for the company. The biggest challenge of a new business is to enter the market; create customers, gain profit, and launch their own shares. A logo design which is strong, appealing, creating an impact on people’s mind is a powerful tool for company’s promotion. People will distinguish your company from other company and services through your corporate logo design.
Creating a professional logo design is a creative and innovative work. You can either design it yourself or select a good logo design services to create your logo. You should do a proper study of your company’s past record and future marketing planning before finalizing on your logo as logo will be an inseparable part of your marketing campaign.
With the continuous advancement of the new technologies everyday, logo designing has also improved and advanced. Many digital tools are utilized in creating magnificent logos. It has created a new job opportunity and a new career. The 3D Logo design is one of the popular digital designing tools. Adobe is on the most popular software that enables the 3D logo design. Adobe illustrator is a multimedia used for developing graphics, photo editing, animation, and designing. It is the software used in 3D logo design. The 3-dimensional logo looks more realistic and eye catching than regular logos. It is also difficult field due to complex designs and structure to create from your own imagination and creativity.
Before developing the company’s logo, which could be the name of company or name along with some symbol, the designer has to consider the values and basic principle of the company because the logo should represent that. Always go for original idea. You must have come across the companies who get involved in legal issues due to their logo trademark. It could happen due to the resemblance of logo to the logo of other company, it could be unintentional, but still the competitor can challenge your trademark. Even the tag line along with the logo could be the matter of hassle. So be original and creative to avoid this bad publicity.
Myself webmaster of 3dlogoonline.com we provide services like 3d logo design.we provide designing services which help you to give brand name to your business.Grow your business with our 3dlogo services.
|
// ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2018 www.open3d.org
//
// 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.
// ----------------------------------------------------------------------------
#include <Eigen/Dense>
#include <Eigen/Geometry>
#include "Open3D/IO/ClassIO/PinholeCameraTrajectoryIO.h"
#include "Open3D/Utility/Console.h"
// The TUM format for camera trajectories as used in
// "A Benchmark for the Evaluation of RGB-D SLAM Systems" by
// J. Sturm and N. Engelhard and F. Endres and W. Burgard and D. Cremers
// (IROS 2012)
// See these pages for details:
// https://vision.in.tum.de/data/datasets/rgbd-dataset/file_formats
// https://vision.in.tum.de/data/datasets/rgbd-dataset
namespace open3d {
namespace io {
bool ReadPinholeCameraTrajectoryFromTUM(
const std::string &filename,
camera::PinholeCameraTrajectory &trajectory) {
camera::PinholeCameraIntrinsic intrinsic;
if (trajectory.parameters_.size() >= 1 &&
trajectory.parameters_[0].intrinsic_.IsValid()) {
intrinsic = trajectory.parameters_[0].intrinsic_;
} else {
intrinsic = camera::PinholeCameraIntrinsic(
camera::PinholeCameraIntrinsicParameters::PrimeSenseDefault);
}
trajectory.parameters_.clear();
FILE *f = fopen(filename.c_str(), "r");
if (f == NULL) {
utility::PrintWarning("Read TUM failed: unable to open file: %s\n",
filename.c_str());
return false;
}
char line_buffer[DEFAULT_IO_BUFFER_SIZE];
double ts, x, y, z, qx, qy, qz, qw;
Eigen::Matrix4d transform;
while (fgets(line_buffer, DEFAULT_IO_BUFFER_SIZE, f)) {
if (strlen(line_buffer) > 0 && line_buffer[0] != '#') {
if (sscanf(line_buffer, "%lf %lf %lf %lf %lf %lf %lf %lf", &ts, &x,
&y, &z, &qx, &qy, &qz, &qw) != 8) {
utility::PrintWarning(
"Read TUM failed: unrecognized format.\n");
fclose(f);
return false;
}
transform.setIdentity();
transform.topLeftCorner<3, 3>() =
Eigen::Quaterniond(qw, qx, qy, qz).toRotationMatrix();
transform.topRightCorner<3, 1>() = Eigen::Vector3d(x, y, z);
auto param = camera::PinholeCameraParameters();
param.intrinsic_ = intrinsic;
param.extrinsic_ = transform.inverse();
trajectory.parameters_.push_back(param);
}
}
fclose(f);
return true;
}
bool WritePinholeCameraTrajectoryToTUM(
const std::string &filename,
const camera::PinholeCameraTrajectory &trajectory) {
FILE *f = fopen(filename.c_str(), "w");
if (f == NULL) {
utility::PrintWarning("Write TUM failed: unable to open file: %s\n",
filename.c_str());
return false;
}
Eigen::Quaterniond q;
fprintf(f, "# TUM trajectory, format: <t> <x> <y> <z> <qx> <qy> <qz> <qw>");
for (size_t i = 0; i < trajectory.parameters_.size(); i++) {
const Eigen::Matrix4d transform =
trajectory.parameters_[i].extrinsic_.inverse();
q = transform.topLeftCorner<3, 3>();
fprintf(f, "%zu %lf %lf %lf %lf %lf %lf %lf\n", i, transform(0, 3),
transform(1, 3), transform(2, 3), q.x(), q.y(), q.z(), q.w());
}
fclose(f);
return true;
}
} // namespace io
} // namespace open3d
|
\subsection{Properties of matrix multiplication}
We have already seen that matrix multiplication is not in general
commutative, i.e., $AB$ and $BA$ may be different, even if they are
both defined. Sometimes it can happen that $AB=BA$ for specific
matrices $A$ and $B$. In this case, we say that $A$ and $B$
\textbf{commute}%
\index{matrix!commuting matrices}%
\index{commuting matrices}.
The following are some properties of matrix multiplication. Notice
that these properties hold only when the size of matrices are such
that the products are defined.
\begin{proposition}{Properties of matrix multiplication}{properties-of-matrix-multiplication}
The following properties hold%
\index{matrix!properties of multiplication}%
\index{matrix!multiplication!properties}%
\index{properties of multiplication!matrices} for matrices $A,B,C$
of appropriate dimensions and for scalars $r$.
\begin{itemize}
\item The associative law of multiplication
\begin{equation*}
(AB)C ~=~ A(BC).
\end{equation*}
\item The existence of multiplicative units
\begin{equation*}
I_mA ~=~ A ~=~ AI_n,
\end{equation*}
where $A$ is an $m\times n$-matrix.
\item Compatibility with scalar multiplication
\begin{equation*}
(rA)B ~=~ r(AB) ~=~ A(rB).
\end{equation*}
\item The distributive laws of multiplication over addition
\begin{eqnarray*}
A(B+C) &=& AB + AC, \\
(B+C)A &=& BA + CA.
\end{eqnarray*}
\end{itemize}
\end{proposition}
\begin{proof}
First, we will prove the associative law. In the proof, it will be
useful to use {\em summation notation}%
\index{summation notation}. We write
\begin{equation*}
\sum_{i=1}^n x_i ~=~ x_1 + x_2 + \ldots + x_n
\end{equation*}
for the sum of the $n$ numbers $x_1,\ldots,x_n$. Assume $A$ is an
$m\times n$-matrix, $B$ is an $n\times p$-matrix, and $C$ is a
$p\times q$-matrix. Then both $(AB)C$ and $A(BC)$ are
$n\times q$-matrices. We must show that they have the same
entries. The $(i,\ell)$-entry of the matrix $(AB)C$ is
\begin{equation*}
((AB)C)_{i\ell} = \sum_{k=1}^p (AB)_{ik}c_{k\ell}
= \sum_{k=1}^p (\sum_{j=1}^n a_{ij}b_{jk})c_{k\ell}
= \sum_{k=1}^p\sum_{j=1}^n a_{ij}b_{jk}c_{k\ell}.
\end{equation*}
On the other hand, the $(i,\ell)$-entry of the matrix $A(BC)$ is
\begin{equation*}
(A(BC))_{i\ell} = \sum_{j=1}^n a_{ij}(BC)_{j\ell}
= \sum_{j=1}^n a_{ij} (\sum_{k=1}^p b_{jk} c_{k\ell})
= \sum_{j=1}^n\sum_{k=1}^p a_{ij} b_{jk} c_{k\ell}.
\end{equation*}
Both sums are equal, since they are both summing over all the terms
where $j=1,\ldots,n$ and $k=1,\ldots,p$. Therefore, $(AB)C=A(BC)$.
The fact that identity matrices act as multiplicative units was
already mentioned in Proposition~\ref{prop:identity-matrix}. We
leave compatibility with scalar multiplication as an exercise.
To prove the first distributive law, assume $A$ is an
$m\times n$-matrix, and $B$ and $C$ are $n\times p$-matrices. Then
both $A(B+C)$ and $AB+AC$ are $m\times p$-matrices. We have
\begin{equation*}
(A(B+C))_{ik} = \sum_{j=1}^n a_{ij}(B+C)_{jk}
= \sum_{j=1}^n a_{ij}(b_{jk}+c_{jk})
= \sum_{j=1}^n a_{ij}b_{jk} + \sum_{j=1}^n a_{ij}c_{jk}
= (AB+AC)_{ik}.
\end{equation*}
Thus $A(B+C) =AB+AC$ as claimed. The proof of the other distributive
law is similar.
\end{proof}
|
According to their website, Campus Planning and Community Resources integrates campus planning with the operations that directly affect peoples experience of the campus environment on a daily basis. Planning is combined with units responsible for landscape management, visitor services, transportation and parking, and the marketing and communications of UC Davis as a welcoming destination.
CPCR is a part of Administrative and Resource Management.
Campus units within this department include:
Arboretum The Arboretum
Conference and Event Services
Grounds Division
Repro Graphics
Putah Creek Riparian Reserve The Putah Creek Riparian Reserve
Transportation And Parking Services a really welcoming unit!
|
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Copyright (c) 2005-2006 Dan Marsden
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(BOOST_FUSION_ADAPTED_30122005_1420)
#define BOOST_FUSION_ADAPTED_30122005_1420
#include <boost/fusion/adapted/adt.hpp>
#include <boost/fusion/adapted/array.hpp>
#include <boost/fusion/adapted/boost_array.hpp>
#include <boost/fusion/adapted/boost_tuple.hpp>
#include <boost/fusion/adapted/mpl.hpp>
#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/fusion/adapted/struct.hpp>
// The std_tuple_iterator adaptor only supports implementations
// using variadic templates
#if !defined(BOOST_NO_VARIADIC_TEMPLATES)
#include <boost/fusion/adapted/std_tuple.hpp>
#endif
#endif
|
```python
import math
π = math.pi; x=20.1234; y=-4.56789
print("Jupyter notebooks combine the flexibility of an interactive notebook with the power of Python")
print(f"Python can work with Unicode characters directly. π is equal to {str(π)}")
print('Python can format output multiple ways.')
print('x is ' + '{:+.2f}'.format(x) + ' and y is ' + '{:+.2f}'.format(y))
```
Jupyter notebooks combine the flexibility of an interactive notebook with the power of Python
Python can work with Unicode characters directly. π is equal to 3.141592653589793
Python can format output multiple ways.
x is +20.12 and y is -4.57
Notebooks can have embedded latex equations
\begin{equation}
f(t)=\frac{f_{end}-f_{start}}{T_c}t + f_{start}
\Delta\phi(t) = 2\pi f(t)\Delta t
\end{equation}
and images such as this software defined radio
```python
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
#Scatter plot with line
fig = plt.figure(figsize=(5,3.5))
ax=fig.add_subplot(1,1,1)
color='r'
N=256
x=4*np.random.randn(N,1)
y=np.random.randn(N,1)
ax.plot(x,y,color + '.', label='points')
ax.plot(np.linspace(np.min(x), np.max(x), num=N),np.linspace(np.min(y), np.max(y), num=N),'b',label='line')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
ax.set_title('Scatter plot and line')
```
|
# ------------------------------------------------------------------
# Licensed under the MIT License. See LICENSE in the project root.
# ------------------------------------------------------------------
"""
localanisotropies(Gradients, grid, propname, w)
Extract `LocalAnisotropy` from a reference scenario. The `propname` variable
from the cartesian `grid` object is scanned and local gradients are extracted
from it. These gradients are smoothed within a squared/cubic window sized
2`w` x 2`w` (x 2`w`) in order to return an ellipse/ellipsoid along the
directions with more/less variability (`w` must be an `Int` value and corresponds
to the number of grid cells). A preliminar magnitude is also extracted from it
and can be later rescaled to proper limits using [`rescale_magnitude`](@ref)
function.
## Example
```julia
lpars = localanisotropies(Gradients, grid, :CO2, 5)
```
"""
function localanisotropies(::Type{Gradients}, obj, prop, window)
# get dimensions
dims = domain(obj).dims
N = length(dims)
propv = Tables.getcolumn(Tables.columns(values(obj)), prop)
# extract gradients (maybe need an extra method to deal with big datasets)
factor = maximum(propv) - minimum(propv)
factor = factor < 1000 ? 100 : 1
img = round.(Int,(factor .* reshape(propv, Size(dims)) )) # temp solution
g = imgradients(img, KernelFactors.sobel, "replicate")
quat = Array{Quaternion}(undef,size(img)) # make some better way to store it
m = Array{Vector}(undef,size(img)) # make some better way to store it
Threads.@threads for i in CartesianIndices(img)
tensor = zeros(Float64,N,N)
for ng in gridneighbors(img, i, window)
for j in CartesianIndices((1:N,1:N))
tensor[j] += g[j[1]][ng]*g[j[2]][ng]
end
end
T = eigen(Symmetric(SMatrix{N,N}(tensor)))
V = T.vectors[:, sortperm(T.values)]'
if N==3
eigv = V
det(V) < 0 && (eigv = Diagonal(SVector{3}([-1,1,1])) * eigv)
else
eigv = zeros(Float64,3,3)
eigv[1:2,1:2] = V
eigv[1,1] ≉ eigv[2,2] && (eigv[1,:] .*= -1)
eigv[3,3] = 1.0
eigv = SMatrix{3,3}(eigv)
end
q = dcm_to_quat(eigv)
λ = sort(T.values, rev=true)
quat[i] = q
m[i] = λ/λ[1]
end
LocalAnisotropy(vec(quat), reduce(hcat,vec(m)))
end
|
module ScoreAD
using ForwardDiff: Dual, value, partials
"""
score_AD(p)
When `p` is real, return `1` (with the same type).
When `p` is a primitive for automatic differentiation, return ``log ∂p``, ie the
score function.
This function can be used for gradient estimation using simulation. See the
references in the README.
"""
score_AD(p::Real) = one(p)
score_AD(p::Dual{T,V}) where {T,V} = Dual{T}(one(V), partials(log(p)))
"""
score_AD_log(ℓ)
Similar to [`score_AD`](@ref), but uses the log likelihood, ie
```julia
score_AD(p) == score_AD_log(log(p))
```
"""
score_AD_log(ℓ::Real) = one(ℓ)
score_AD_log(ℓ::Dual{T,V}) where {T,V} = Dual{T}(one(V), partials(ℓ))
"""
reject_nonfinite(ℓ)
When the likelihood `ℓ` (or its derivative, when applicable) is not finite,
replace the value with `-Inf`.
Always return the same type as `ℓ`.
# Usage
This useful when calculations using automatic differentiation of a score
function in a (finite) sample, which may deliver non-finite derivatives for
extreme values. In this case, reject the parameter.
"""
@inline reject_nonfinite(ℓ::V) where {V <: Real} =
ifelse(isfinite(ℓ), ℓ, V(-Inf))
@inline function reject_nonfinite(ℓ::Dual{T,V}) where {T,V}
p = partials(ℓ)
if isfinite(value(ℓ)) && all(isfinite, p)
ℓ
else
Dual{T}(V(-Inf), p)
end
end
end # module
|
Spring has Sprung - Get Decked Inc.
NEW! 1″x8″ Azek wide boards available in the 1st quarter of 2019!
We Work in Chester County Pa, New Castle, Kent Counties in Delaware…as far south as Dover!
©2019 Get Decked | Catalyst Visuals, LLC Catalyst Visuals is a boutique Wilmington, Delaware – based visual communications studio that specializes in Delaware Web Design, as well as print & internet marketing.
|
module DataStore
import Data.List
import Data.Strings
import Data.Vect
import System.REPL
%default total
infixr 5 .+.
data Schema = SChar
| SString
| SInt
| (.+.) Schema Schema
SchemaType : Schema -> Type
SchemaType SChar = Char
SchemaType SString = String
SchemaType SInt = Int
SchemaType (x .+. y) = (SchemaType x, SchemaType y)
parsePrefix : (schema : Schema) -> (inp : String) -> Maybe (SchemaType schema, String)
parsePrefix SChar inp = getSingleQuoted (unpack inp)
where
getSingleQuoted : List Char -> Maybe (Char, String)
getSingleQuoted ('\'' :: xs) = case xs of
(c :: '\'' :: rest) => Just (c, ltrim (pack rest))
_ => Nothing
getSingleQuoted _ = Nothing
parsePrefix SString inp = getQuoted (unpack inp)
where
getQuoted : List Char -> Maybe (String, String)
getQuoted ('"' :: xs) = case span (/= '"') xs of
(quoted, '"' :: rest) => Just (pack quoted, ltrim (pack rest))
_ => Nothing
getQuoted _ = Nothing
parsePrefix SInt inp = case span isDigit inp of
("", rest) => Nothing
(num, rest) => Just (cast num, ltrim rest)
parsePrefix (schemal .+. schemar) inp =
do (lval, inp') <- parsePrefix schemal inp
(rval, inp'') <- parsePrefix schemar inp'
Just ((lval, rval), inp'')
stringToSchema : (schema : Schema) -> (inp : String) -> Maybe (SchemaType schema)
stringToSchema schema inp =
case parsePrefix schema inp of
Just (res, "") => Just res
Just _ => Nothing
Nothing => Nothing
schemaToString : { schema : Schema } -> SchemaType schema -> String
schemaToString {schema = SChar} item = show item
schemaToString {schema = SString} item = show item
schemaToString {schema = SInt} item = show item
schemaToString {schema = (x .+. y)} (itemx, itemy) =
schemaToString itemx ++ ", " ++ schemaToString itemy
record DataStore where
constructor MkData
schema : Schema
size : Nat
items : Vect size (SchemaType schema)
addToStore : (store : DataStore) -> (item : SchemaType (schema store)) -> DataStore
addToStore (MkData schema size items) newItem = MkData _ _ (addItem items)
where
addItem : Vect oldsize (SchemaType schema) -> Vect (S oldsize) (SchemaType schema)
addItem [] = [newItem]
addItem (item :: items) = item :: addItem items
getEntry : (store : DataStore) -> (idx : Integer) -> String
getEntry (MkData _ size items) idx = case integerToFin idx size of
Nothing => "invalid index: " ++ show idx
Just idx' => schemaToString (index idx' items)
getAllEntries : (store : DataStore) -> String
getAllEntries store = getAllEntriesHelper (size store) ""
where
getAllEntriesHelper : (idx : Nat) -> (results : String) -> String
getAllEntriesHelper Z results = results
getAllEntriesHelper (S idx') results = getAllEntriesHelper idx' results ++ "\n" ++ getEntry store (cast idx')
data Command : Schema -> Type where
SetSchema : (newschema : Schema) -> Command schema
Add : SchemaType schema -> Command schema
Get : Maybe Integer -> Command schema
Size : Command schema
Quit : Command schema
parseSchema : List String -> Maybe Schema
parseSchema ("Char" :: xs) =
case xs of
[] => Just SChar
_ => case parseSchema xs of
Nothing => Nothing
Just schema' => Just (SChar .+. schema')
parseSchema ("String" :: xs) =
case xs of
[] => Just SString
_ => case parseSchema xs of
Nothing => Nothing
Just schema' => Just (SString .+. schema')
parseSchema ("Int" :: xs) =
case xs of
[] => Just SInt
_ => case parseSchema xs of
Nothing => Nothing
Just schema' => Just (SInt .+. schema')
parseSchema _ = Nothing
parseCommand : (schema : Schema) -> (cmd : String) -> (args : String) -> Maybe (Command schema)
parseCommand schema "add" item = case stringToSchema schema item of
Nothing => Nothing
Just item' => Just (Add item')
parseCommand schema "get" idxStr =
if idxStr == ""
then Just (Get Nothing)
else case all isDigit (unpack idxStr) of
False => Nothing
True => Just $ Get (Just (cast idxStr))
parseCommand schema "size" "" = Just Size
parseCommand schema "setschema" newschema =
case parseSchema (words newschema) of
Nothing => Nothing
Just schema => Just (SetSchema schema)
parseCommand schema "quit" "" = Just Quit
parseCommand _ _ _ = Nothing
parse : (schema : Schema) -> (inp : String) -> Maybe (Command schema)
parse schema inp = let (cmd, args) = span (/= ' ') inp in
parseCommand schema cmd (ltrim args)
setSchema : (store : DataStore) -> (newschema : Schema) -> Maybe DataStore
setSchema store newschema = case size store of
Z => Just (MkData newschema 0 [])
_ => Nothing
processCommand : (store : DataStore) -> (cmd : Command (schema store)) -> Maybe (String, DataStore)
processCommand store (Add item) = Just ("ID" ++ show (size store) ++ "\n", addToStore store item)
processCommand store (Get idx) =
case idx of
Nothing => Just (getAllEntries store ++ "\n", store)
Just idx' => Just (getEntry store idx' ++ "\n", store)
processCommand store Size = Just (show (size store) ++ "\n", store)
processCommand store (SetSchema schema) =
case setSchema store schema of
Nothing => Just ("Cannot update schema - store is possibly not empty\n", store)
Just store' => Just ("updated schema\n", store')
processCommand store Quit = Nothing
processInput : (store : DataStore) -> (inp : String) -> Maybe (String, DataStore)
processInput store inp =
case parse (schema store) inp of
Nothing => Just ("invalid command\n", store)
Just cmd => processCommand store cmd
partial
main : HasIO io => io ()
main = replWith (MkData (SString .+. SString .+. SInt) 0 []) "Command: " processInput
|
using SpkCore
include("./GLMBasis.jl")
using .GLMBasis
# ============================================================================ #
abstract type AbstractBasis end
# ============================================================================ #
struct NullBasis <: AbstractBasis
bin_size::Float64
end
NullBasis() = NullBasis(1.0)
nbasis(n::NullBasis) = 1
project(n::NullBasis, ts::Vector{Float64}, evt::Vector{Float64}) = evt
# ============================================================================ #
mutable struct DefaultBasis <: AbstractBasis
length::Int
offset::Int
bin_size::Float64
changed::Bool
end
function DefaultBasis(;length::Integer=0, offset::Integer=0, bin_size::Real=0.001)
@assert(length > 0, "Required length argument must be > 0")
return DefaultBasis(length, offset, bin_size, false)
end
# ---------------------------------------------------------------------------- #
nbasis(b::DefaultBasis) = b.length
# ---------------------------------------------------------------------------- #
function project(x::DefaultBasis, ts::Vector{Float64}, evt::Vector{Float64})
k = x.offset
return permutedims(psth(ts, evt, -(x.length + k - 1):-k, x.bin_size)[1], (2,1))
end
# ============================================================================ #
# CosineBasis(length=100, n=4, b=4, ortho=false, bin_size=0.001)
mutable struct CosineBasis <: AbstractBasis
length::Int
offset::Int
nbasis::Int
b::Float64
ortho::Bool
bin_size::Float64
basis::Matrix{Float64}
changed::Bool
end
function CosineBasis(;length::Int=0, offset::Integer=0, nbasis::Int=8, b::Real=4.0, ortho::Bool=false, bin_size::Real=0.001)
@assert(length > 0, "Required length argument must be > 0")
return CosineBasis(length, offset, nbasis, b, ortho, bin_size, Matrix{Float64}(undef, 0, 0), true)
end
# ---------------------------------------------------------------------------- #
nbasis(x::CosineBasis) = x.nbasis
# ---------------------------------------------------------------------------- #
function generate(x::CosineBasis)
if x.changed
xpeaks = [0, round(Int, x.length * (1 - 1.5 / x.nbasis))]
basis, ortho_basis = make_stim_basis(0, x.nbasis, xpeaks, x.b, x.length)
if size(basis) == size(x.basis)
x.basis .= x.ortho ? ortho_basis : basis
else
x.basis = x.ortho ? ortho_basis : basis
end
if any(isnan, x.basis)
error("NaN detected in basis!!!")
end
x.changed = false
end
return x.basis
end
# ---------------------------------------------------------------------------- #
function project(x::CosineBasis, ts::Vector{Float64}, evt::Vector{Float64})
idx = ts2idx.(ts, x.bin_size)
if ts === evt
evt_idx = idx
else
evt_idx = ts2idx.(evt, x.bin_size)
end
tidx = evt_idx .- x.offset
if tidx[1] < 1
filter!(>(0), tidx)
end
return spikefilter(idx, reverse(generate(x), dims=1), (1, evt_idx[end]))[tidx, :]
end
# ============================================================================ #
function Base.setproperty!(b::AbstractBasis, k::Symbol, v)
setfield!(b, k, v)
setfield!(b, :changed, true)
return b
end
# ============================================================================ #
function set_parameter!(x::T; args...) where T <: AbstractBasis
for (k,v) in args
if hasfield(T, k)
setfield!(x, k, v)
x.changed = true
end
end
end
# ============================================================================ #
function Base.:*(a::Vector{<:Real}, x::CosineBasis)
return (x.basis' * x.basis) \ (x.basis' * a)
end
Base.:*(x::CosineBasis, a::Vector{<:Real}) = x.basis * a
@inline Base.:*(a::Vector{<:Real}, x::AbstractBasis) = a
@inline Base.:*(x::AbstractBasis, a::Vector{<:Real}) = a
# ============================================================================ #
|
[STATEMENT]
lemma indep_and_equiv_implies_ief:
assumes "wb_lens x" "x \<bowtie> y" "x \<approx>\<^sub>L y"
shows "ief_lens x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ief_lens x
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. ief_lens x
[PROOF STEP]
have "x \<bowtie> x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. x \<bowtie> x
[PROOF STEP]
using assms(2) assms(3) lens_equiv_pres_indep'
[PROOF STATE]
proof (prove)
using this:
x \<bowtie> y
x \<approx>\<^sub>L y
\<lbrakk>?X \<approx>\<^sub>L ?Y; ?Z \<bowtie> ?Y\<rbrakk> \<Longrightarrow> ?Z \<bowtie> ?X
goal (1 subgoal):
1. x \<bowtie> x
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
x \<bowtie> x
goal (1 subgoal):
1. ief_lens x
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
x \<bowtie> x
goal (1 subgoal):
1. ief_lens x
[PROOF STEP]
using assms(1) lens_indep_quasi_irrefl vwb_lens_wb wb_lens_weak
[PROOF STATE]
proof (prove)
using this:
x \<bowtie> x
wb_lens x
\<lbrakk>wb_lens ?x; eff_lens ?x\<rbrakk> \<Longrightarrow> \<not> ?x \<bowtie> ?x
vwb_lens ?x \<Longrightarrow> wb_lens ?x
wb_lens ?x \<Longrightarrow> weak_lens ?x
goal (1 subgoal):
1. ief_lens x
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
ief_lens x
goal:
No subgoals!
[PROOF STEP]
qed
|
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import division, print_function, unicode_literals, \
absolute_import
import os
import unittest
from collections import OrderedDict
import numpy as np
from pymatgen.io.lammps.data import LammpsForceFieldData
from pymatgen.io.lammps.force_field import ForceField
from pymatgen.io.lammps.topology import Topology
from pymatgen.core.structure import Molecule
__author__ = 'Kiran Mathew'
__email__ = '[email protected]'
test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..",
"test_files", "lammps")
class TestLammpsForceFieldData(unittest.TestCase):
@classmethod
def setUpClass(cls):
polymer_chain = Molecule.from_file(os.path.join(test_dir,"polymer_chain.xyz"))
polymer_linear = Molecule.from_file(os.path.join(test_dir,"polymer_linear.xyz"))
cls.polymer_matrix = Molecule.from_file(os.path.join(test_dir,"polymer_matrix.xyz"))
charges = [-0.1187, 0.0861, 0.0861, 0.0861, -0.2792, -0.0326, 0.0861,
0.0861, -0.0326, 0.0861, 0.0861, -0.2792, -0.0326, 0.0861,
0.0861, -0.0326, 0.0861, 0.0861, -0.2792, -0.0326, 0.0861,
0.0861, -0.0326, 0.0861, 0.0861, -0.2792, -0.0326, 0.0861,
0.0861, -0.0326, 0.0861, 0.0861, -0.2792, -0.0326, 0.0861,
0.0861, -0.0326, 0.0861, 0.0861, -0.2792, -0.0326, 0.0861,
0.0861, -0.0326, 0.0861, 0.0861, -0.2792, -0.1187, 0.0861,
0.0861, 0.0861]
polymer_linear.add_site_property("charge", charges)
topology = Topology.from_molecule(polymer_linear)
atoms = OrderedDict([("C","C"), ("H","H"), ("O", "O")])
bonds = OrderedDict([((u'C', u'O'), [1000, 1.4115]),
((u'C', u'H'), [1000, 1.1041]),
((u'C', u'C'), [1000, 1.5075])])
pairs = OrderedDict([((u'O', u'O'), [75844.8, 0.2461, 396.9]),
((u'H', u'H'), [2649.6, 0.2674, 27.22]),
((u'C', u'C'), [14976.0, 0.3236, 637.6])])
angles = OrderedDict([((u'C', u'C', u'H'), [42.9, 110.1]),
((u'H', u'C', u'H'), [38.5, 109.47]),
((u'H', u'C', u'O'), [56.0, 109.48]),
((u'C', u'C', u'O'), [86.0, 108.54]),
((u'C', u'O', u'C'), [74.5, 108.05])])
dihedrals = OrderedDict([((u'H', u'C', u'O', u'C'), [0.0, 0.0, -0.73, 0.0]),
((u'H', u'C', u'C', u'H'), [0.0, 0.0, 0.28, 0.0]),
((u'C', u'C', u'O', u'C'), [1.76, 0.67, 0.04, 0.0]),
((u'H', u'C', u'C', u'O'), [0.0, 0.0, 0.28, 0.0]),
((u'O', u'C', u'C', u'O'), [0.41, -2.1, -0.6, -0.82])])
forcefield =ForceField(atoms, bonds, angles, dihedrals=dihedrals, pairs=pairs)
cls.molecules = [polymer_chain] * 3
cls.mols_number = [7, 3, 1]
box_size = [[0.0, 50], [0.0, 50], [0.0, 50]]
cls.topologies = [topology] * len(cls.molecules)
cls.lammps_ff_data_1 = LammpsForceFieldData.from_forcefield_and_topology(
cls.molecules, cls.mols_number, box_size, cls.polymer_matrix,
forcefield, cls.topologies)
def test_system_info(self):
# check te molecule ids
mol_ids = np.array(self.lammps_ff_data_1.atoms_data)[:, 1]
mol_ids_ans = [i + 1 for i in range(sum(self.mols_number))]
self.assertEqual(set(mol_ids.tolist()), set(mol_ids_ans))
# check the size consistency of the polymer matrix
self.assertEqual(len(self.polymer_matrix),
sum([len(mol) * self.mols_number[i]
for i, mol in enumerate(self.molecules)]))
for top in self.topologies:
self.assertEqual(len(self.lammps_ff_data_1.atoms_data),
sum([len(top.atoms)*mol_number
for mol_number in self.mols_number]))
self.assertEqual(len(self.lammps_ff_data_1.bonds_data),
sum([len(top.bonds) * mol_number
for mol_number in self.mols_number]))
self.assertEqual(len(self.lammps_ff_data_1.angles_data),
sum([len(top.angles) * mol_number
for mol_number in self.mols_number]))
self.assertEqual(len(self.lammps_ff_data_1.dihedrals_data),
sum([len(top.dihedrals) * mol_number
for mol_number in self.mols_number]))
def test_to_and_from_file(self):
self.lammps_ff_data_1.write_data_file(
os.path.join(test_dir,"lammps_ff_data.dat"))
lammps_ff_data_2 = LammpsForceFieldData.from_file(
os.path.join(test_dir,"lammps_ff_data.dat"))
np.testing.assert_almost_equal(self.lammps_ff_data_1.bond_coeffs,
lammps_ff_data_2.bond_coeffs)
np.testing.assert_almost_equal(self.lammps_ff_data_1.pair_coeffs,
lammps_ff_data_2.pair_coeffs)
np.testing.assert_almost_equal(self.lammps_ff_data_1.angle_coeffs,
lammps_ff_data_2.angle_coeffs)
np.testing.assert_almost_equal(self.lammps_ff_data_1.dihedral_coeffs,
lammps_ff_data_2.dihedral_coeffs)
np.testing.assert_almost_equal(self.lammps_ff_data_1.atoms_data,
lammps_ff_data_2.atoms_data, decimal=10)
self.assertEqual(self.lammps_ff_data_1.bonds_data,
lammps_ff_data_2.bonds_data)
self.assertEqual(self.lammps_ff_data_1.angles_data,
lammps_ff_data_2.angles_data)
self.assertEqual(self.lammps_ff_data_1.dihedrals_data,
lammps_ff_data_2.dihedrals_data)
def tearDown(self):
for x in ["lammps_ff_data.dat"]:
if os.path.exists(os.path.join(test_dir, x)):
os.remove(os.path.join(test_dir, x))
if __name__ == "__main__":
unittest.main()
|
#include <algorithm>
#include <memory>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <climits>
#include <numeric>
#include <Eigen/Dense>
#undef N_DEBUG
#include <assert.h>
#define loop(x,n) for(std::size_t (x) = 0; (x) < (n); ++(x))
using namespace std;
using UInt = uint64_t;
using Int = int64_t;
using Vector3d = Eigen::Matrix<double, 3, 1>;
struct Asteroid
{
using Ptr = std::shared_ptr<Asteroid>;
using ConstPtr = std::shared_ptr<const Asteroid>;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
Asteroid() {}
Asteroid(Vector3d pos, Vector3d vel)
: position(pos)
, velocity(vel)
{}
Vector3d position;
Vector3d velocity;
};
double getMinDistance(Asteroid::ConstPtr a, Asteroid::ConstPtr b)
{
const auto w = a->position - b->position;
const auto v = a->velocity - b->velocity;
const auto t_cpa = -w.dot(v) / v.squaredNorm();
const auto p_a = a->position + t_cpa * a->velocity;
const auto p_b = b->position + t_cpa * b->velocity;
return (p_a - p_b).norm();
}
double getMinDistanceWithin(Asteroid::ConstPtr a, Asteroid::ConstPtr b, double t_min, double t_max)
{
const auto w = a->position - b->position;
const auto v = a->velocity - b->velocity;
const auto t_cpa = -w.dot(v) / v.squaredNorm();
double t;
if (t_cpa < t_min)
t = t_min;
else if (t_cpa > t_max)
t = t_max;
else
t = t_cpa;
const auto p_a = a->position + t * a->velocity;
const auto p_b = b->position + t * b->velocity;
return (p_a - p_b).norm();
}
struct Edge
{
Edge(size_t first, size_t second, double weight)
: first_vertex(first)
, second_vertex(second)
, weight(weight)
{}
size_t first_vertex;
size_t second_vertex;
double weight;
bool operator <(const Edge& other) const
{
if (weight != other.weight)
return weight < other.weight;
if (first_vertex != other.first_vertex)
return first_vertex < other.first_vertex;
return second_vertex < other.second_vertex;
}
bool contains(size_t vertex) const { return first_vertex == vertex || second_vertex == vertex; }
size_t getOther(size_t vertex) const
{
if (first_vertex == vertex)
return second_vertex;
return first_vertex;
}
};
struct Cluster
{
Cluster() {}
Cluster(const auto& asteroids, auto velocity)
: asteroids(asteroids)
, velocity(velocity)
{}
Cluster(const auto& asteroid)
: asteroids({asteroid})
, velocity(asteroid->velocity)
{}
double getMaxJumpDistance(Asteroid::ConstPtr start, Asteroid::ConstPtr end) const
{
const auto s = find(asteroids.cbegin(), asteroids.cend(), start);
if (s == asteroids.cend())
throw (int)1;
size_t index_start = std::distance(asteroids.cbegin(), s);
const auto e = find(asteroids.cbegin(), asteroids.cend(), end);
if (e == asteroids.cend())
throw (int)2;
size_t index_end = std::distance(asteroids.cbegin(), e);
auto unexplored = edges;
set<size_t> explored;
explored.insert(index_start);
double max_jump = 0.0;
size_t added = 0;
do
{
for (auto it = unexplored.begin(); it != unexplored.end(); it++)
{
const auto first_it = explored.find(it->first_vertex);
const auto second_it = explored.find(it->second_vertex);
auto ex = explored.cend();
if (first_it != explored.cend())
ex = first_it;
else if (second_it != explored.cend())
ex = second_it;
else
continue;
added = it->getOther(*ex);
explored.insert(added);
if (it->weight > max_jump)
max_jump = it->weight;
unexplored.erase(it);
break;
}
}
while (added != index_end);
return sqrt(max_jump);
}
const vector<Asteroid::ConstPtr> getAllReachedAsteroids(Asteroid::ConstPtr start, double max_jump)
{
max_jump = max_jump*max_jump;
const auto s = find(asteroids.cbegin(), asteroids.cend(), start);
if (s == asteroids.cend())
throw (int)3;
vector<Asteroid::ConstPtr> reached({start});
size_t index_start = std::distance(asteroids.cbegin(), s);
vector<bool> explored(asteroids.size(), false);
explored[index_start] = true;
size_t added;
do
{
added = asteroids.size();
loop(ex, explored.size())
{
if (!explored[ex])
continue;
loop(unex, explored.size())
{
if (explored[unex])
continue;
if (getWeight(ex, unex) <= max_jump)
{
added = unex;
explored[unex] = true;
break;
}
}
if (added != asteroids.size())
break;
}
reached.push_back(asteroids[added]);
}
while (added < asteroids.size());
return reached;
}
vector<Asteroid::Ptr> asteroids;
Vector3d velocity;
double getWeight(size_t first, size_t second) const
{
assert(first != second);
const auto min_index = min(first, second);
const auto max_index = max(first, second);
return weights[min_index][max_index-min_index-1];
}
void calcWeights()
{
weights.resize(asteroids.size() - 1);
loop(ii, asteroids.size() - 1)
{
weights[ii].reserve(asteroids.size() - ii - 1);
for (size_t jj = ii + 1; jj < asteroids.size(); ++jj)
{
weights[ii].push_back((asteroids[ii]->position - asteroids[jj]->position).squaredNorm());
edges.emplace(ii, jj, weights[ii].back());
}
}
}
vector<vector<double>> weights;
set<Edge> edges;
};
int main()
{
size_t num_test_cases;
cin >> num_test_cases;
for (size_t i = 0; i < num_test_cases; i++)
{
size_t N, S;
cin >> N >> S;
vector<Asteroid::Ptr> asteroids;
asteroids.reserve(N);
loop(ii, N)
{
Vector3d pos;
Vector3d vel;
cin >> pos[0] >> pos[1] >> pos[2]
>> vel[0] >> vel[1] >> vel[2];
Asteroid a;
a.position = pos;
a.velocity = vel;
asteroids.emplace_back(make_shared<Asteroid>(pos, vel));
}
// sort into clusters
vector<Cluster> clusters;
for (const auto& a : asteroids)
{
const auto it = std::find_if(clusters.begin(), clusters.end(), [&a](const vector<Cluster>::value_type& c){
return c.velocity == a->velocity;});
if (it == clusters.end())
{
clusters.emplace_back(a);
}
else
{
it->asteroids.push_back(a);
}
}
//cout <<"Number of clusters: " <<clusters.size() <<endl;
for (auto& a : clusters)
a.calcWeights();
double res = 0.0;
if (clusters.size() == 1)
{
res = clusters.front().getMaxJumpDistance(asteroids[0], asteroids[1]);
std::cout <<"Case #" <<(i+1) <<": " <<setprecision(10) <<res <<endl;
}
else
{
if (asteroids[0]->velocity != asteroids[1]->velocity)
res = getMinDistanceWithin(asteroids[0], asteroids[1], 0.0, S);
else
res = -1.0;
std::cout <<"Case #" <<(i+1) <<": " <<setprecision(10) <<res <<endl;
}
}
return 0;
}
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Memo
% LaTeX Template
% Version 1.0 (30/12/13)
%
% This template has been downloaded from:
% http://www.LaTeXTemplates.com O Original author:
% Rob Oakes (http://www.oak-tree.us) with modifications by:
% Vel ([email protected])
%
% License:
% CC BY-NC-SA 3.0 (http://creativecommons.org/licenses/by-nc-sa/3.0/)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass[a4paper,12pt]{texMemo} % Set the paper size (letterpaper, a4paper, etc) and font size (10pt, 11pt or 12pt)
\usepackage{setspace}
\usepackage{parskip} % Adds spacing between paragraphs
\usepackage{graphicx}
\usepackage{geometry}
\setlength{\parindent}{15pt} % Indent paragraphs
%----------------------------------------------------------------------------------------
% MEMO INFORMATION
%----------------------------------------------------------------------------------------
\memoto{Decision Maker about Privacy} % Recipient(s)
\memofrom{MCM 2018 Team} % Sender(s)
\memosubject{Private Information: The Emergence of a New Asset} % Memo subject
\memodate{Monday, February 12, 2018} % Date, set to \today for automatically printing todays date
%\logo{\includegraphics[width=0.3\textwidth]{logo.png}} % Institution logo at the top right of the memo, comment out this line for no logo
%----------------------------------------------------------------------------------------
\begin{document}
\maketitle % Print the memo header information
%----------------------------------------------------------------------------------------
% MEMO CONTENT
%----------------------------------------------------------------------------------------
\section{Introduction}
In the era of "anywhere, anytime", people now produce more data than ever before. The variety and volume of digital records that can be created, processed and analyzed will continue to increase dramatically. By 2020, International Data Corporation (IDC) estimates that the global amount of digital records will increase more than 40-fold.
The problem is to quantify the cost of privacy. That is, to establish a metric to evaluate the monetary value of keeping PI protected and the fees it would cost for others to possess or utilize PI. We consider private information (PI) as record of "everything a person makes and does". To make the problem clearer, several concepts need to be explained.
%\begin{spacing}{0.8}
\textbf{Domain of Private Information.} An initial list of types of private information includes:
Digital identity (e.g., names, addresses, phone numbers, demographic information, social network profile information, etc.); Relationships to other people and organization (social media, contact list and profiles); Communication data and logs (emails, SMS, phone calls, IM and social network posts); Media produced, consumed and shared (in-text, audio, photo, video and other forms of media); Financial data (financial transactions, accounts, credit scores, physical assets and virtual goods); Health data (health/medical records, medical history, medical device logs, prescriptions and health insurance coverage); Institutional data (government, academic and employment data).
%\end{spacing}
\textbf{Subgroup of Individuals.} E.g. citizenship, professional profiles, age, education level, occupation, etc.
\textbf{Risks.} The risks involve loss of safety, money, valuable items, intellectual property (IP), the person's electronic identity, professional embarrassment , loss of a position or job, social loss (friendships), social stigmatization, or marginalization.
\section{Solutions and Conclusions}
\begin{figure}
\begin{center}
\includegraphics[width=0.7\linewidth]{fig/demand_surface.pdf}
\caption{Demand Surface: the influence of data volumn and information entropy}
\end{center}
\end{figure}
Private information will continue to increase dramatically in both quality and diversity, and has the potential to unlock significant economic and societal value.
To some extend, Private Information (PI) is similar to personal property (PP) and intellectual property (IP). However, there are also discrepancies among them. PI differs from PP and IP in that it can be sold or given to others who then have the right to use it without ownership, and it needs to be regulated by government. These information and privacy issues should be protected not only by the individuals but also by the agencies. Based on our model, the private data should not be trackable by the government for national security concerns.
%Potential gains from keeping data private include a greater level of security, especially for larger businesses. Potential losses from keeping data private include slowing down the pace of technological development. Notably, currently the development of \emph{Artificial Intelligence} can not make such a big achievement without big data, e.g. ImageNet. Also, public sectors can trace the spread of disease in order to prevent further outbreak with shared private information, which is a welfare for most people. Commercial agencies can provide personalized service for different groups.
Building a harmonious ecosystem around personal data will require significant commitment from all stakeholders. Our model proposes four critical solutions to deal with the problem:
\begin{itemize}
\item An expanded role for government, such that governments can use their purchasing power to help shape commercially available products and solutions that the private sector can then leverage;
\item Mechanisms for enhancing trust among all parts in private information transaction;
%\item Greater interoperability among existing data silos;
%\item An easy-to-understand user-centric approach to the design of systems, tools and policies, with an emphasis on transparency, trust, control and value distribution.
\item Integrate principles surrounding and user trust and data protection into the development of new services and platforms;
%\item Engage with leading innovators and end user advocacy groups to explore the further applications for, and development of, trust framework;
\item Policy makers and agencies should launch an international dialog, which should encompass governments, international bodies such as the World Trade Organization, end user privacy rights groups and representation from the private sector. It should include not only US and European Union members, but interested parties from the Asia-Pacific region and emerging countries;
%\item In the United States: Agencies should closely watch developments of the National Strategy for Trusted Identities in Cyberspace program and the privacy bill. Agencies need to be in constant dialog with the US Department of Commerce, the Federal Trade Commission and other bodies to help shape future legislation and policies; In the European Union: Agencies should collaborate with the European Commission in its move to revise the EU privacy directive. In other regions that differ from the US or the EU in cultural or social norms, very different paths in adopting policy frameworks will be required. One initial step in making progress could be to seek ways to harmonize fragmented national privacy policies.
\end{itemize}
%----------------------------------------------------------------------------------------
\end{document}
|
% !TeX program = pdfLaTeX
\documentclass[smallextended]{svjour3} % onecolumn (second format)
%\documentclass[twocolumn]{svjour3} % twocolumn
%
\smartqed % flush right qed marks, e.g. at end of proof
%
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage[utf8]{inputenc}
\usepackage[hyphens]{url} % not crucial - just used below for the URL
\usepackage{hyperref}
%
% \usepackage{mathptmx} % use Times fonts if available on your TeX system
%
% insert here the call for the packages your document requires
%\usepackage{latexsym}
% etc.
%
% please place your own definitions here and don't use \def but
% \newcommand{}{}
%
% Insert the name of "your journal" with
% \journalname{myjournal}
%
%% load any required packages here
% Pandoc syntax highlighting
\usepackage{color}
\usepackage{fancyvrb}
\newcommand{\VerbBar}{|}
\newcommand{\VERB}{\Verb[commandchars=\\\{\}]}
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
% Add ',fontsize=\small' for more characters per line
\usepackage{framed}
\definecolor{shadecolor}{RGB}{248,248,248}
\newenvironment{Shaded}{\begin{snugshade}}{\end{snugshade}}
\newcommand{\AlertTok}[1]{\textcolor[rgb]{0.94,0.16,0.16}{#1}}
\newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.77,0.63,0.00}{#1}}
\newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\BuiltInTok}[1]{#1}
\newcommand{\CharTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\CommentTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}}
\newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}}
\newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{#1}}
\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\ErrorTok}[1]{\textcolor[rgb]{0.64,0.00,0.00}{\textbf{#1}}}
\newcommand{\ExtensionTok}[1]{#1}
\newcommand{\FloatTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\ImportTok}[1]{#1}
\newcommand{\InformationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}}
\newcommand{\NormalTok}[1]{#1}
\newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.81,0.36,0.00}{\textbf{#1}}}
\newcommand{\OtherTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{#1}}
\newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}}
\newcommand{\RegionMarkerTok}[1]{#1}
\newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\StringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\VariableTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\WarningTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
% tightlist command for lists without linebreak
\providecommand{\tightlist}{%
\setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
% From pandoc table feature
\usepackage{longtable,booktabs,array}
\usepackage{calc} % for calculating minipage widths
% Correct order of tables after \paragraph or \subparagraph
\usepackage{etoolbox}
\makeatletter
\patchcmd\longtable{\par}{\if@noskipsec\mbox{}\fi\par}{}{}
\makeatother
% Allow footnotes in longtable head/foot
\IfFileExists{footnotehyper.sty}{\usepackage{footnotehyper}}{\usepackage{footnote}}
\makesavenoteenv{longtable}
% Pandoc citation processing
\newlength{\cslhangindent}
\setlength{\cslhangindent}{1.5em}
\newlength{\csllabelwidth}
\setlength{\csllabelwidth}{3em}
\newlength{\cslentryspacingunit} % times entry-spacing
\setlength{\cslentryspacingunit}{\parskip}
% for Pandoc 2.8 to 2.10.1
\newenvironment{cslreferences}%
{}%
{\par}
% For Pandoc 2.11+
\newenvironment{CSLReferences}[2] % #1 hanging-ident, #2 entry spacing
{% don't indent paragraphs
\setlength{\parindent}{0pt}
% turn on hanging indent if param 1 is 1
\ifodd #1
\let\oldpar\par
\def\par{\hangindent=\cslhangindent\oldpar}
\fi
% set entry spacing
\setlength{\parskip}{#2\cslentryspacingunit}
}%
{}
\usepackage{calc}
\newcommand{\CSLBlock}[1]{#1\hfill\break}
\newcommand{\CSLLeftMargin}[1]{\parbox[t]{\csllabelwidth}{#1}}
\newcommand{\CSLRightInline}[1]{\parbox[t]{\linewidth - \csllabelwidth}{#1}\break}
\newcommand{\CSLIndent}[1]{\hspace{\cslhangindent}#1}
\usepackage{booktabs}
\begin{document}
\title{My Example Computed Manuscript }
\subtitle{Created in Rmarkdown}
\titlerunning{Example computed manuscript}
\author{ Jeffrey M. Perkel \and }
\institute{
Jeffrey M. Perkel \at
Springer Nature, 1 New York Plaza, New York, NY \\
\email{\href{mailto:[email protected]}{\nolinkurl{[email protected]}}} % \\
% \emph{Present address:} of F. Author % if needed
\and
}
\date{Received: date / Accepted: date}
% The correct dates will be entered by the editor
\maketitle
\begin{abstract}
A mock computed manuscript created in RStudio using \{Rmarkdown\}. The \{Bookdown\} and \{Rticles\} packages were used to output the text in Springer Nature's desired manuscript format.
\\
\keywords{
}
\end{abstract}
\def\spacingset#1{\renewcommand{\baselinestretch}%
{#1}\small\normalsize} \spacingset{1}
\hypertarget{intro}{%
\section{Introduction}\label{intro}}
``Literate programming'' is a style of programming that uses computational notebooks to weave together code, explanatory text, data and results into a single document, enhancing scientific communication and computational reproducibility.\textsuperscript{1--3} (These references were added into the document using RStudio's integration with the open-source Zotero reference manager\textsuperscript{4} plus the \href{https://retorque.re/zotero-better-bibtex/}{Better BibTeX} Zotero plugin.)
Several platforms for creating such documents exist.\textsuperscript{5} Typically, these documents interleave code and text `blocks' to build a computational narrative. But some, including \href{https://rmarkdown.rstudio.com/}{R Markdown}, \href{https://www.observablehq.com}{Observable}, and the \href{https://jupyterbook.org/intro.html}{Jupyter Book} extension to the Jupyter ecosystem, also allow authors to include and execute code ``inline'' -- that is, within the text itself.
This makes it possible to create fully executable manuscripts in which the document itself computes and inserts values and figures into the text rather than requiring authors to input them manually. This is in many ways the `killer feature' of computed manuscripts: it circumvents the possibility that the author will enter an incorrect number, or forget to update a figure or value should new data arise. Among other uses, that allows authors to automatically time-stamp their documents, or insert the current version number of the software they use into their methods. For instance, this document was built at \textbf{24 Feb 2022 17:39:18 MST} and calls the following R packages: \texttt{\{tidyverse\}} ver. \textbf{1.3.0}, \texttt{\{ggbeeswarm\}} ver. \textbf{0.6.0} and \texttt{\{bookdown\}} ver. \textbf{0.24}.
In this manuscript, created in RStudio using the R Markdown language, we will demonstrate a more practical example. (An Observable version is \href{https://observablehq.com/@jperkel/example-executable-observable-notebook}{also available}.)
\hypertarget{results}{%
\section{Results}\label{results}}
\hypertarget{sec:1}{%
\subsection{Inline computation}\label{sec:1}}
Imagine we are analyzing data from a clinical trial. We have grouped subjects in three bins and measured the concentration of some metabolite. (These data are simulated.)
Rather than analyzing those data and then copying the results into our manuscript, we can use the programming language \texttt{R} to do that in the manuscript itself. Simply enclose the code inside backticks, with the letter \texttt{r}. For instance, we could calculate the circumference and area of a circle:
\[A = \pi r^2, C = 2 \pi r\]
You could write ``A = \texttt{\textasciigrave{}r\ pi\ *\ r\^{}2\textasciigrave{}} and C = \texttt{\textasciigrave{}r\ 2\ *\ pi\ *\ r\textasciigrave{}}''. Plugging in the radius \emph{r} = \textbf{10}, that evaluates to ``A = \textbf{314.16} and C = \textbf{62.83}''.
Returning to our dataset, we can count the rows in our table to determine the number of samples, and insert that into the text. Thus, we have \textbf{99} (simulated) subjects in our study (see Table \ref{tab:show-table-1}; see \href{https://github.com/jperkel/computed_manuscript/blob/main/R/mock_data.R}{\texttt{R/mock\_data.R}} in the GitHub repository for code to generate a mock dataset). Note that the tables, figures and sections in this document are numbered automatically thanks to the \texttt{\{bookdown\}} package.
The average metabolite concentration in this dataset is \textbf{185.36} (range: \textbf{78 to 298}). We have \textbf{32} subjects in Group 1, \textbf{43} subjects in Group 2, and \textbf{24} in Group 3. (The numbers in \textbf{bold face type} throughout this document are computed values.)
\hypertarget{sec:2}{%
\subsection{Incorporating new data}\label{sec:2}}
Now suppose we get another tranche of data (Table \ref{tab:show-table-2}). There are \textbf{60} subjects in this new dataset, with an average concentration of \textbf{185.13} (range: \textbf{77 to 299}).
Combining the two datasets, we have a total of \textbf{159} subjects with an average metabolite concentration of \textbf{185.28} (range: \textbf{77 to 299}). We now have \textbf{55} subjects in Group 1, \textbf{60} in Group 2, and \textbf{44} in Group 3. The concentration distribution for each group in this joint dataset is shown graphically in Figure \ref{fig:plot-data-1}.
\begin{figure}
\centering
\includegraphics{computed_manuscript_files/figure-latex/plot-data-1-1.pdf}
\caption{\label{fig:plot-data-1}Metabolite concentration of clinical trial subjects}
\end{figure}
\hypertarget{importing-a-child-document}{%
\subsection{Importing a child document}\label{importing-a-child-document}}
Authors can break long manuscripts into more manageable pieces by placing each chapter or section in their own Markdown file and using the R Markdown \texttt{child} option. Though most of the text (and code) in this document is contained in the file \texttt{computed\_manuscript.Rmd}, the text for this section comes from \texttt{child\_doc.Rmd}. Citations that are created in the child automatically get inserted into the final document, making it possible to create a single, unified bibliography. For instance, here's a reference for the \href{https://bookdown.org/yihui/rmarkdown-cookbook/}{R Markdown Cookbook}.\textsuperscript{6}
In this child document, we'll add a third set of numbers to our growing dataset (Table \ref{tab:show-table-3}; note that the table, figure and section numbering in this child document matches that of the larger manuscript).
The new dataset describes \textbf{50} samples. Folding them into our existing data gives us \textbf{209} subjects, with \textbf{69} in Group 1, \textbf{74} in Group 2, and \textbf{66} in Group 3. The new concentration distribution is shown graphically in Figure \ref{fig:plot-data-2}.
\begin{figure}
\centering
\includegraphics{computed_manuscript_files/figure-latex/plot-data-2-1.pdf}
\caption{\label{fig:plot-data-2}Metabolite concentration of final clinical trial dataset}
\end{figure}
\hypertarget{code}{%
\section{Code}\label{code}}
The following code was used to load, merge, and plot the (simulated) clinical trial data in Figure \ref{fig:plot-data-1}:
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# load libraries}
\FunctionTok{library}\NormalTok{(tidyverse)}
\FunctionTok{library}\NormalTok{(ggbeeswarm)}
\FunctionTok{library}\NormalTok{(bookdown)}
\end{Highlighting}
\end{Shaded}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# read in some initial data}
\NormalTok{df1 }\OtherTok{\textless{}{-}} \FunctionTok{read\_csv}\NormalTok{(}\StringTok{\textquotesingle{}data/example{-}data{-}1.csv\textquotesingle{}}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# read new dataset}
\NormalTok{df2 }\OtherTok{\textless{}{-}} \FunctionTok{read\_csv}\NormalTok{(}\StringTok{\textquotesingle{}data/example{-}data{-}2.csv\textquotesingle{}}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# merge datasets}
\NormalTok{final\_data }\OtherTok{\textless{}{-}} \FunctionTok{rbind}\NormalTok{(df1, df2)}
\end{Highlighting}
\end{Shaded}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# create a box{-}plot with overlaid points}
\NormalTok{create\_plot }\OtherTok{\textless{}{-}} \ControlFlowTok{function}\NormalTok{(mytable) \{}
\NormalTok{ p }\OtherTok{\textless{}{-}}\NormalTok{ mytable }\SpecialCharTok{\%\textgreater{}\%}
\FunctionTok{ggplot}\NormalTok{(}\FunctionTok{aes}\NormalTok{(}\AttributeTok{x =}\NormalTok{ class, }\AttributeTok{y =}\NormalTok{ conc, }\AttributeTok{fill =}\NormalTok{ class, }\AttributeTok{color =}\NormalTok{ class)) }\SpecialCharTok{+}
\FunctionTok{geom\_boxplot}\NormalTok{(}\AttributeTok{outlier.shape =} \ConstantTok{NA}\NormalTok{, }\AttributeTok{alpha =} \FloatTok{0.2}\NormalTok{) }\SpecialCharTok{+}
\NormalTok{ ggbeeswarm}\SpecialCharTok{::}\FunctionTok{geom\_quasirandom}\NormalTok{(}\AttributeTok{width =} \FloatTok{0.25}\NormalTok{) }\SpecialCharTok{+}
\FunctionTok{xlab}\NormalTok{(}\StringTok{""}\NormalTok{) }\SpecialCharTok{+}
\FunctionTok{ylab}\NormalTok{(}\StringTok{"Metabolite concentration"}\NormalTok{) }\SpecialCharTok{+}
\FunctionTok{theme\_minimal}\NormalTok{() }\SpecialCharTok{+}
\FunctionTok{theme}\NormalTok{(}\AttributeTok{legend.position =} \StringTok{"none"}\NormalTok{)}
\NormalTok{ p}
\NormalTok{\}}
\end{Highlighting}
\end{Shaded}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# plot the data}
\FunctionTok{create\_plot}\NormalTok{(final\_data)}
\end{Highlighting}
\end{Shaded}
\begin{table}
\caption{\label{tab:show-table-1}Initial subject data}
\centering
\begin{tabular}[t]{llrlllrlllr}
\toprule
ID & Class & Conc & | & ID & Class & Conc & | & ID & Class & Conc\\
\midrule
ID\_1 & Group 2 & 153 & | & ID\_34 & Group 2 & 221 & | & ID\_67 & Group 3 & 148\\
ID\_2 & Group 1 & 224 & | & ID\_35 & Group 1 & 112 & | & ID\_68 & Group 1 & 281\\
ID\_3 & Group 2 & 127 & | & ID\_36 & Group 3 & 246 & | & ID\_69 & Group 3 & 295\\
ID\_4 & Group 2 & 194 & | & ID\_37 & Group 2 & 190 & | & ID\_70 & Group 2 & 111\\
ID\_5 & Group 1 & 251 & | & ID\_38 & Group 1 & 177 & | & ID\_71 & Group 2 & 132\\
\addlinespace
ID\_6 & Group 1 & 81 & | & ID\_39 & Group 1 & 148 & | & ID\_72 & Group 2 & 261\\
ID\_7 & Group 2 & 100 & | & ID\_40 & Group 2 & 290 & | & ID\_73 & Group 1 & 122\\
ID\_8 & Group 1 & 270 & | & ID\_41 & Group 2 & 151 & | & ID\_74 & Group 2 & 124\\
ID\_9 & Group 2 & 100 & | & ID\_42 & Group 2 & 159 & | & ID\_75 & Group 1 & 234\\
ID\_10 & Group 1 & 161 & | & ID\_43 & Group 2 & 113 & | & ID\_76 & Group 2 & 184\\
\addlinespace
ID\_11 & Group 3 & 158 & | & ID\_44 & Group 1 & 249 & | & ID\_77 & Group 3 & 272\\
ID\_12 & Group 3 & 118 & | & ID\_45 & Group 1 & 124 & | & ID\_78 & Group 1 & 242\\
ID\_13 & Group 2 & 143 & | & ID\_46 & Group 3 & 87 & | & ID\_79 & Group 2 & 277\\
ID\_14 & Group 2 & 258 & | & ID\_47 & Group 1 & 166 & | & ID\_80 & Group 3 & 236\\
ID\_15 & Group 3 & 224 & | & ID\_48 & Group 1 & 196 & | & ID\_81 & Group 1 & 101\\
\addlinespace
ID\_16 & Group 3 & 254 & | & ID\_49 & Group 1 & 112 & | & ID\_82 & Group 3 & 218\\
ID\_17 & Group 3 & 190 & | & ID\_50 & Group 1 & 289 & | & ID\_83 & Group 2 & 130\\
ID\_18 & Group 2 & 148 & | & ID\_51 & Group 2 & 161 & | & ID\_84 & Group 1 & 128\\
ID\_19 & Group 1 & 89 & | & ID\_52 & Group 3 & 270 & | & ID\_85 & Group 3 & 252\\
ID\_20 & Group 2 & 89 & | & ID\_53 & Group 2 & 237 & | & ID\_86 & Group 1 & 198\\
\addlinespace
ID\_21 & Group 3 & 253 & | & ID\_54 & Group 2 & 280 & | & ID\_87 & Group 1 & 169\\
ID\_22 & Group 3 & 231 & | & ID\_55 & Group 2 & 175 & | & ID\_88 & Group 2 & 185\\
ID\_23 & Group 1 & 112 & | & ID\_56 & Group 2 & 223 & | & ID\_89 & Group 1 & 216\\
ID\_24 & Group 2 & 277 & | & ID\_57 & Group 3 & 295 & | & ID\_90 & Group 2 & 185\\
ID\_25 & Group 2 & 197 & | & ID\_58 & Group 1 & 275 & | & ID\_91 & Group 2 & 97\\
\addlinespace
ID\_26 & Group 2 & 208 & | & ID\_59 & Group 2 & 120 & | & ID\_92 & Group 2 & 165\\
ID\_27 & Group 2 & 193 & | & ID\_60 & Group 1 & 78 & | & ID\_93 & Group 3 & 89\\
ID\_28 & Group 3 & 141 & | & ID\_61 & Group 3 & 78 & | & ID\_94 & Group 2 & 221\\
ID\_29 & Group 1 & 206 & | & ID\_62 & Group 3 & 140 & | & ID\_95 & Group 1 & 162\\
ID\_30 & Group 2 & 168 & | & ID\_63 & Group 3 & 294 & | & ID\_96 & Group 1 & 131\\
\addlinespace
ID\_31 & Group 2 & 298 & | & ID\_64 & Group 3 & 295 & | & ID\_97 & Group 1 & 93\\
ID\_32 & Group 1 & 144 & | & ID\_65 & Group 3 & 285 & | & ID\_98 & Group 2 & 240\\
ID\_33 & Group 2 & 241 & | & ID\_66 & Group 2 & 129 & | & ID\_99 & Group 2 & 86\\
\bottomrule
\end{tabular}
\end{table}
\begin{table}
\caption{\label{tab:show-table-2}Second batch of subject data}
\centering
\begin{tabular}[t]{llrlllrlllr}
\toprule
ID & Class & Conc & | & ID & Class & Conc & | & ID & Class & Conc\\
\midrule
ID\_100 & Group 2 & 219 & | & ID\_120 & Group 2 & 85 & | & ID\_140 & Group 2 & 77\\
ID\_101 & Group 2 & 243 & | & ID\_121 & Group 3 & 181 & | & ID\_141 & Group 1 & 299\\
ID\_102 & Group 2 & 213 & | & ID\_122 & Group 3 & 216 & | & ID\_142 & Group 3 & 222\\
ID\_103 & Group 1 & 177 & | & ID\_123 & Group 1 & 222 & | & ID\_143 & Group 1 & 85\\
ID\_104 & Group 3 & 197 & | & ID\_124 & Group 3 & 252 & | & ID\_144 & Group 1 & 273\\
\addlinespace
ID\_105 & Group 2 & 198 & | & ID\_125 & Group 1 & 166 & | & ID\_145 & Group 3 & 115\\
ID\_106 & Group 1 & 120 & | & ID\_126 & Group 2 & 204 & | & ID\_146 & Group 1 & 290\\
ID\_107 & Group 3 & 170 & | & ID\_127 & Group 2 & 243 & | & ID\_147 & Group 2 & 269\\
ID\_108 & Group 3 & 78 & | & ID\_128 & Group 3 & 198 & | & ID\_148 & Group 2 & 97\\
ID\_109 & Group 1 & 129 & | & ID\_129 & Group 1 & 119 & | & ID\_149 & Group 1 & 229\\
\addlinespace
ID\_110 & Group 1 & 137 & | & ID\_130 & Group 1 & 198 & | & ID\_150 & Group 3 & 176\\
ID\_111 & Group 3 & 217 & | & ID\_131 & Group 3 & 151 & | & ID\_151 & Group 2 & 164\\
ID\_112 & Group 1 & 227 & | & ID\_132 & Group 3 & 115 & | & ID\_152 & Group 3 & 172\\
ID\_113 & Group 3 & 81 & | & ID\_133 & Group 3 & 237 & | & ID\_153 & Group 1 & 222\\
ID\_114 & Group 2 & 248 & | & ID\_134 & Group 2 & 178 & | & ID\_154 & Group 1 & 285\\
\addlinespace
ID\_115 & Group 1 & 211 & | & ID\_135 & Group 1 & 275 & | & ID\_155 & Group 2 & 153\\
ID\_116 & Group 1 & 113 & | & ID\_136 & Group 2 & 178 & | & ID\_156 & Group 3 & 132\\
ID\_117 & Group 1 & 216 & | & ID\_137 & Group 3 & 267 & | & ID\_157 & Group 2 & 156\\
ID\_118 & Group 3 & 91 & | & ID\_138 & Group 1 & 95 & | & ID\_158 & Group 1 & 260\\
ID\_119 & Group 3 & 258 & | & ID\_139 & Group 1 & 108 & | & ID\_159 & Group 2 & 201\\
\bottomrule
\end{tabular}
\end{table}
\begin{table}
\caption{\label{tab:show-table-3}Third batch of subject data}
\centering
\begin{tabular}[t]{lllllllllll}
\toprule
ID & Class & Conc & | & ID & Class & Conc & | & ID & Class & Conc\\
\midrule
ID\_160 & Group 2 & 210 & | & ID\_177 & Group 2 & 288 & | & ID\_194 & Group 3 & 123\\
ID\_161 & Group 3 & 107 & | & ID\_178 & Group 1 & 262 & | & ID\_195 & Group 2 & 212\\
ID\_162 & Group 2 & 262 & | & ID\_179 & Group 2 & 217 & | & ID\_196 & Group 1 & 99\\
ID\_163 & Group 1 & 215 & | & ID\_180 & Group 3 & 87 & | & ID\_197 & Group 3 & 264\\
ID\_164 & Group 1 & 220 & | & ID\_181 & Group 3 & 266 & | & ID\_198 & Group 2 & 279\\
\addlinespace
ID\_165 & Group 3 & 288 & | & ID\_182 & Group 3 & 79 & | & ID\_199 & Group 2 & 126\\
ID\_166 & Group 3 & 287 & | & ID\_183 & Group 1 & 152 & | & ID\_200 & Group 1 & 276\\
ID\_167 & Group 3 & 213 & | & ID\_184 & Group 3 & 223 & | & ID\_201 & Group 3 & 213\\
ID\_168 & Group 1 & 84 & | & ID\_185 & Group 3 & 118 & | & ID\_202 & Group 2 & 212\\
ID\_169 & Group 3 & 160 & | & ID\_186 & Group 1 & 214 & | & ID\_203 & Group 1 & 104\\
\addlinespace
ID\_170 & Group 2 & 194 & | & ID\_187 & Group 3 & 200 & | & ID\_204 & Group 1 & 199\\
ID\_171 & Group 1 & 119 & | & ID\_188 & Group 1 & 271 & | & ID\_205 & Group 1 & 272\\
ID\_172 & Group 3 & 218 & | & ID\_189 & Group 3 & 237 & | & ID\_206 & Group 1 & 86\\
ID\_173 & Group 2 & 217 & | & ID\_190 & Group 3 & 170 & | & ID\_207 & Group 2 & 181\\
ID\_174 & Group 3 & 103 & | & ID\_191 & Group 2 & 156 & | & ID\_208 & Group 3 & 114\\
\addlinespace
ID\_175 & Group 3 & 94 & | & ID\_192 & Group 2 & 288 & | & ID\_209 & Group 2 & 248\\
ID\_176 & Group 3 & 270 & | & ID\_193 & Group 3 & 193 & | & & & \\
\bottomrule
\end{tabular}
\end{table}
\hypertarget{colophon}{%
\section{Colophon}\label{colophon}}
This manuscript was built at \textbf{24 Feb 2022 17:39:19 MST} using the following computational environment and dependencies:
\begin{verbatim}
## R version 4.0.4 (2021-02-15)
## Platform: x86_64-apple-darwin17.0 (64-bit)
## Running under: macOS Big Sur 10.16
##
## Matrix products: default
## BLAS: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib
##
## locale:
## [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] bookdown_0.24 ggbeeswarm_0.6.0 forcats_0.5.1 stringr_1.4.0
## [5] dplyr_1.0.5 purrr_0.3.4 readr_2.1.1 tidyr_1.1.3
## [9] tibble_3.1.6 ggplot2_3.3.3 tidyverse_1.3.0
##
## loaded via a namespace (and not attached):
## [1] Rcpp_1.0.7 lubridate_1.8.0 assertthat_0.2.1 digest_0.6.29
## [5] utf8_1.2.2 R6_2.5.1 cellranger_1.1.0 backports_1.2.1
## [9] reprex_2.0.1 evaluate_0.14 highr_0.9 httr_1.4.2
## [13] pillar_1.6.4 rlang_0.4.12 readxl_1.3.1 rstudioapi_0.13
## [17] rticles_0.22 rmarkdown_2.11 labeling_0.4.2 bit_4.0.4
## [21] munsell_0.5.0 broom_0.7.6 compiler_4.0.4 vipor_0.4.5
## [25] modelr_0.1.8 xfun_0.29 pkgconfig_2.0.3 htmltools_0.5.2
## [29] tidyselect_1.1.1 fansi_1.0.0 crayon_1.4.2 tzdb_0.2.0
## [33] dbplyr_2.1.0 withr_2.4.3 grid_4.0.4 jsonlite_1.7.2
## [37] gtable_0.3.0 lifecycle_1.0.1 DBI_1.1.1 magrittr_2.0.1
## [41] scales_1.1.1 cli_3.1.0 stringi_1.7.6 vroom_1.5.7
## [45] farver_2.1.0 fs_1.5.2 xml2_1.3.3 ellipsis_0.3.2
## [49] generics_0.1.1 vctrs_0.3.8 tools_4.0.4 bit64_4.0.5
## [53] glue_1.6.0 beeswarm_0.4.0 hms_1.1.1 parallel_4.0.4
## [57] fastmap_1.1.0 yaml_2.2.1 colorspace_2.0-0 rvest_1.0.2
## [61] knitr_1.37 haven_2.3.1
\end{verbatim}
The current Git commit details are:
\begin{verbatim}
## [9906399] 2022-02-25: Fix link to Observable example.
\end{verbatim}
\hypertarget{references}{%
\section*{References}\label{references}}
\addcontentsline{toc}{section}{References}
\hypertarget{refs}{}
\begin{CSLReferences}{0}{0}
\leavevmode\vadjust pre{\hypertarget{ref-shen2014}{}}%
\CSLLeftMargin{1. }
\CSLRightInline{Shen, H. \href{https://doi.org/10.1038/515151a}{Interactive notebooks: Sharing the code}. \emph{Nature} \textbf{515}, 151--152 (2014).}
\leavevmode\vadjust pre{\hypertarget{ref-perkel2018a}{}}%
\CSLLeftMargin{2. }
\CSLRightInline{Perkel, J. M. \href{https://doi.org/10.1038/d41586-018-05990-5}{A toolkit for data transparency takes shape}. \emph{Nature} \textbf{560}, 513--515 (2018).}
\leavevmode\vadjust pre{\hypertarget{ref-perkel2018}{}}%
\CSLLeftMargin{3. }
\CSLRightInline{Perkel, J. M. \href{https://doi.org/10.1038/d41586-018-07196-1}{Why Jupyter is data scientists{'} computational notebook of choice}. \emph{Nature} \textbf{563}, 145--146 (2018).}
\leavevmode\vadjust pre{\hypertarget{ref-perkel2020}{}}%
\CSLLeftMargin{4. }
\CSLRightInline{Perkel, J. M. \href{https://doi.org/10.1038/d41586-020-02491-2}{Streamline your writing {\textemdash} and collaborations {\textemdash} with these reference managers}. \emph{Nature} \textbf{585}, 149--150 (2020).}
\leavevmode\vadjust pre{\hypertarget{ref-perkel2021}{}}%
\CSLLeftMargin{5. }
\CSLRightInline{Perkel, J. M. \href{https://doi.org/10.1038/d41586-021-01174-w}{Reactive, reproducible, collaborative: computational notebooks evolve}. \emph{Nature} \textbf{593}, 156--157 (2021).}
\leavevmode\vadjust pre{\hypertarget{ref-xieMarkdownCookbook2020}{}}%
\CSLLeftMargin{6. }
\CSLRightInline{Xie, Y., Dervieux, C. \& Riederer, E. \emph{R {Markdown Cookbook}}. ({Chapman and Hall/CRC}, 2020).}
\end{CSLReferences}
\bibliographystyle{spbasic}
\bibliography{bibliography.bib}
\end{document}
|
import re
import sys
import time
import numpy as np
def render(pos):
min_x = min(pos, key=lambda x: x[0])[0]
max_x = max(pos, key=lambda x: x[0])[0]
min_y = min(pos, key=lambda x: x[1])[1]
max_y = max(pos, key=lambda x: x[1])[1]
dx = 1 + max_x - min_x
dy = 1 + max_y - min_y
area = dx*dy
if area < 1000:
out = np.zeros((dy,dx))
for (x,y) in pos:
out[y - min_y,x - min_x] = 1
return '\n'.join([''.join('#' if j else '.' for j in i) for i in out])
# return out
def main():
regex = re.compile('position=<(.*)> velocity=<(.*)>')
pos = []
vel = []
for i in sys.stdin:
a,b = regex.search(i).groups()
x,y = a.strip().split(',')
pos.append((int(x),int(y)))
x,y = b.strip().split(',')
vel.append((int(x),int(y)))
for i in range(21000):
r = render(pos)
if r is not None:
print('='*30)
print('After', i, 'seconds')
print('='*30)
print(r)
break
pos = [(p[0] + v[0], p[1] + v[1]) for p,v in zip(pos, vel)]
if __name__ == '__main__':
main()
|
Phumlani Msibi comes from Kwa Zulu Natal and started singing when he was 7 years old. He was encouraged by his parents who also sing, and he grew up singing in Church and School Choirs.
He was a member of the Abequlusi Community Choir as a tenor soloist. While at school Phumlani also participated in Latin American and Ballroom dancing.
In 2004 he started studying sound engineering at Gallo Studios which he continues today.
Phumlani looks forward to further studies in Music to further his career.
|
#include <Eigen/Eigen>
#include <boost/python/numpy.hpp>
namespace bp = boost::python;
namespace np = boost::python::numpy;
#define EIGEN_ARRAY_CONVERTER(Type, N) \
EigenFromPython<Type, N>(); \
bp::to_python_converter<Eigen::Ref<Type>, EigenToPython<Type>>(); \
EigenFromPython<const Type, N>(); \
bp::to_python_converter<Eigen::Ref<const Type>, EigenToPython<const Type>>();
template <typename T>
struct EigenToPython
{
static PyObject *convert(const Eigen::Ref<T> &m)
{
double *data = const_cast<double *>(m.data());
bp::object capsule(
bp::handle<>(PyCapsule_New(new Eigen::Map<T>(data, m.rows(), m.cols()), nullptr, [](PyObject *ptr) {
delete (Eigen::Map<T> *)PyCapsule_GetPointer(ptr, nullptr);
})));
return boost::python::incref(
np::from_data(data, np::dtype::get_builtin<double>(), bp::make_tuple(m.rows(), m.cols()),
bp::make_tuple(m.rowStride() * sizeof(double), m.colStride() * sizeof(double)), capsule)
.ptr());
}
};
template <>
PyObject *EigenToPython<Eigen::VectorXd>::convert(const Eigen::Ref<Eigen::VectorXd> &v)
{
double *data = const_cast<double *>(v.data());
bp::object capsule(
bp::handle<>(PyCapsule_New(new Eigen::Map<Eigen::VectorXd>(data, v.rows()), nullptr, [](PyObject *ptr) {
delete (Eigen::Map<Eigen::VectorXd> *)PyCapsule_GetPointer(ptr, nullptr);
})));
return boost::python::incref(np::from_data(data, np::dtype::get_builtin<double>(), bp::make_tuple(v.rows()),
bp::make_tuple(v.innerStride() * sizeof(double)), capsule)
.ptr());
}
template <>
PyObject *EigenToPython<const Eigen::VectorXd>::convert(const Eigen::Ref<const Eigen::VectorXd> &v)
{
double *data = const_cast<double *>(v.data());
bp::object capsule(
bp::handle<>(PyCapsule_New(new Eigen::Map<Eigen::VectorXd>(data, v.rows()), nullptr, [](PyObject *ptr) {
delete (Eigen::Map<Eigen::VectorXd> *)PyCapsule_GetPointer(ptr, nullptr);
})));
return boost::python::incref(np::from_data(data, np::dtype::get_builtin<double>(), bp::make_tuple(v.rows()),
bp::make_tuple(v.innerStride() * sizeof(double)), capsule)
.ptr());
}
template <typename T>
void copy_ndarray(const np::ndarray &array, void *storage)
{
new (storage) Eigen::Ref<T>(Eigen::Map<T, 0, Eigen::OuterStride<>>(reinterpret_cast<double *>(array.get_data()),
array.shape(0), array.shape(1),
Eigen::OuterStride<>(array.strides(1))));
}
template <>
void copy_ndarray<Eigen::VectorXd>(const np::ndarray &array, void *storage)
{
new (storage) Eigen::Ref<Eigen::VectorXd>(
Eigen::Map<Eigen::VectorXd>(reinterpret_cast<double *>(array.get_data()), array.shape(0)));
}
template <>
void copy_ndarray<const Eigen::VectorXd>(const np::ndarray &array, void *storage)
{
new (storage) Eigen::Ref<const Eigen::VectorXd>(
Eigen::Map<const Eigen::VectorXd>(reinterpret_cast<double *>(array.get_data()), array.shape(0)));
}
template <typename T, int N>
struct EigenFromPython
{
EigenFromPython()
{
bp::converter::registry::push_back(&convertible, &construct, bp::type_id<Eigen::Ref<T>>());
}
static void *convertible(PyObject *p)
{
try
{
bp::object obj(bp::handle<>(bp::borrowed(p)));
std::unique_ptr<np::ndarray> array(new np::ndarray(
np::from_object(obj, np::dtype::get_builtin<double>(), N, N, np::ndarray::C_CONTIGUOUS)));
return array.release();
}
catch (bp::error_already_set &err)
{
bp::handle_exception();
return nullptr;
}
}
static void construct(PyObject *objPtr, bp::converter::rvalue_from_python_stage1_data *data)
{
std::unique_ptr<np::ndarray> array(reinterpret_cast<np::ndarray *>(data->convertible));
void *storage =
reinterpret_cast<bp::converter::rvalue_from_python_storage<Eigen::Ref<T>> *>(data)->storage.bytes;
copy_ndarray<T>(*array, storage);
data->convertible = storage;
}
};
|
subroutine intcrv( npts, nsd, s, b, t, sint, r, dr, mpts )
implicit real*8 (a-h,o-z)
dimension s(mpts), b(mpts,nsd), t(mpts,nsd), r(nsd), dr(nsd)
klo = 1
khi = npts
10 if ( khi-klo .gt. 1 ) then
k = (khi+klo)/2
if (s(k) .gt. sint) then
khi=k
else
klo=k
end if
goto 10
end if
u = (sint - s(klo))
ub = (s(khi) - s(klo))
do j = 1, nsd
ba = b(klo,j)
bb = b(khi,j)
ta = t(klo,j)
tb = t(khi,j)
c1 = -(2.0*ub*(bb-ta*ub-ba) - ub**2*(tb-ta))/ub**4
c2 = -(ub**3*(tb-ta) - 3.0*ub**2*(bb-ta*ub-ba))/ub**4
r(j) = c1 * u**3 + c2 * u**2 + u*ta + ba
dr(j) = 3.0 * c1 * u**2 + 2.0 * c2 * u + ta
end do
return
end
|
import combinatorics.simple_graph.basic
import combinatorics.simple_graph.degree_sum
import data.finset.basic
import data.nat.basic
import tactic.core
import algebra.big_operators
--local
import misc_finset
open finset nat
open_locale big_operators
namespace simple_graph
-- When counting edges in graphs we often want to consider subgraphs induced by a set of vertices
-- or subgraphs between two (possibly disjoint) sets of vertices
-- For this purpose we introduce the restricted neighbourhood a vertex to a finset.
-- this is G.nbhd_res v A = A ∩ G.neighbor_finset v
-- the restricted nbhd of a set of vertices
section nbhd_res
variables {t n : ℕ}
variables {α : Type*} (G : simple_graph α) [fintype α][nonempty α]{s : finset α}[decidable_eq α][decidable_rel G.adj]
-- restricted nbhd is the part of nbhd in A
include G
@[ext]
def nbhd_res (v : α) (A : finset α) : finset α := A ∩ G.neighbor_finset v
-- restriction of degree to A
def deg_res (v : α) (A : finset α) : ℕ:= (G.nbhd_res v A).card
-- restricting to univ is no restriction at all
lemma deg_res_univ (v : α) : G.deg_res v univ = G.degree v:=
begin
rw [deg_res,degree], congr, rw [nbhd_res,univ_inter],
end
-- we only define this over A restricted to A (could be broader)
-- max deg res is zero if A is empty
-- could replace this with (G.ind A).max_degree
def max_deg_res (A :finset α) : ℕ :=option.get_or_else (A.image (λ v, G.deg_res v A)).max 0
-- if A.nonempty then there is a vertex of max_deg_res A
lemma exists_max_res_deg_vertex {A :finset α} (hA: A.nonempty) :
∃ v∈A, G.max_deg_res A = G.deg_res v A :=
begin
have neim: (A.image (λ v, G.deg_res v A)).nonempty:=nonempty.image hA _,
obtain ⟨t, ht⟩ := max_of_nonempty neim,
have ht₂ := mem_of_max ht,
simp only [pi.coe_nat, nat.cast_id, exists_prop, nonempty.image_iff, mem_image] at *,
rcases ht₂ with ⟨a,ha1, ha2⟩,
refine ⟨a, _⟩,
rw [max_deg_res, ht,option.get_or_else_coe],
exact ⟨ha1,ha2.symm⟩,
end
-- The max_deg_res over A is at least the deg_res of any particular vertex in A.
lemma deg_res_le_max_deg_res {v : α} {A : finset α} (hvA: v ∈ A) : G.deg_res v A ≤ G.max_deg_res A :=
begin
have hA: A.nonempty:=⟨v,hvA⟩,
obtain ⟨t, ht : _ = _⟩ := finset.max_of_mem (mem_image_of_mem (λ v, G.deg_res v A) hvA),
have := finset.le_max_of_mem (mem_image_of_mem _ hvA) ht,
rwa [max_deg_res,ht],
end
-- bound on sum of deg_res given max deg_res (also a bound on e(C) for C ⊆ A)
-- or equiv if C ⊆ A then 2*e(G[C])+e(G[C,A\C])≤ (G.ind A).max_degree * |C|
lemma max_deg_res_sum_le {A C : finset α} (hC: C ⊆ A) : ∑ v in C, G.deg_res v A ≤ (G.max_deg_res A)*(C.card):=
begin
rw [card_eq_sum_ones, mul_sum, mul_one],
apply sum_le_sum _, intros i hi, exact G.deg_res_le_max_deg_res (hC hi),
end
-- restricted degree to A is sum of ones over each neighbour of v in A
lemma deg_res_ones (v : α) (A : finset α) : G.deg_res v A = ∑ x in G.nbhd_res v A, 1:=card_eq_sum_ones _
--- if the restricted nbhd is non-empty then v has a neighbor in A
lemma exists_mem_nempty {v :α} {A : finset α} (hA: ¬(G.nbhd_res v A) = ∅ ): ∃ w∈A, G.adj v w :=
begin
rw nbhd_res at hA, contrapose! hA,
rw eq_empty_iff_forall_not_mem,
intros x hx, rw [mem_inter, mem_neighbor_finset] at hx,
exact hA x hx.1 hx.2,
end
-- member of the restricted nhd iff in nbhd and in A
lemma mem_res_nbhd (v w : α) (A : finset α) : w ∈ G.nbhd_res v A ↔ w ∈ A ∧ w ∈ G.neighbor_finset v
:=by rwa [nbhd_res,mem_inter]
-- v is not a neighbor of itself
lemma not_mem_nbhd (v : α) : v ∉ G.neighbor_finset v :=
begin
rw mem_neighbor_finset, exact G.loopless v,
end
-- nor is v a restricted neighbor of itself
lemma not_mem_res_nbhd (v : α) (A :finset α) : v ∉ G.nbhd_res v A :=
begin
rw mem_res_nbhd,push_neg,intro h, exact G.not_mem_nbhd v,
end
-- restricted nbhd is contained in A
lemma sub_res_nbhd_A (v : α) (A : finset α) : G.nbhd_res v A ⊆ A:=
begin
intro x, rw mem_res_nbhd,intro h, exact h.1,
end
-- restricted nbhd of member is stictly contained in A
lemma ssub_res_nbhd_of_mem {v : α} {A : finset α} (h: v ∈ A) : G.nbhd_res v A ⊂ A
:=(ssubset_iff_of_subset (G.sub_res_nbhd_A v A)).mpr ⟨v,h,G.not_mem_res_nbhd v A⟩
-- restricted nbhd contained in nbhd
lemma sub_res_nbhd_N (v : α)(A : finset α) : G.nbhd_res v A ⊆ G.neighbor_finset v:=
begin
intro _, rw mem_res_nbhd, intro h, exact h.2,
end
-- restricted degree additive over partition of A into B ∪ A\B
-- this is daft, it would work for any function defined on A
lemma sum_sdf {A B: finset α} (hB: B ⊆ A) (C: finset α):
∑ v in A, G.deg_res v C = ∑v in B, G.deg_res v C + ∑ v in A\B, G.deg_res v C:=
begin
nth_rewrite 0 ← union_sdiff_of_subset hB, exact sum_union (disjoint_sdiff),
end
-- restricted deg over A = restricted deg over B + restricted deg over A\B
lemma deg_res_add {v : α} {A B : finset α} (hB: B ⊆ A): G.deg_res v A= G.deg_res v B + G.deg_res v (A\B):=
begin
simp [deg_res,nbhd_res], nth_rewrite 0 ← union_sdiff_of_subset hB,
rw inter_distrib_right B (A\B) _,
exact card_disjoint_union (sdiff_inter_disj A B _),
end
-- sum version of previous lemma
lemma deg_res_add_sum {A B C : finset α} (hB: B ⊆ A) : ∑ v in C, G.deg_res v A= ∑ v in C, G.deg_res v B+ ∑ v in C,G.deg_res v (A\B):=
begin
rw ← sum_add_distrib, exact sum_congr rfl (λ _ _ , G.deg_res_add hB),
end
-- if A and B are disjoint then for any vertex v the deg_res add
lemma deg_res_add' {v : α} {A B : finset α} (h: disjoint A B): G.deg_res v (A∪B)= G.deg_res v A + G.deg_res v B:=
begin
simp [deg_res,nbhd_res], rw inter_distrib_right,
exact card_disjoint_union (disj_of_inter_disj _ _ h),
end
-- sum version of previous lemma
lemma deg_res_add_sum' {A B C: finset α} (h: disjoint A B) : ∑ v in C, G.deg_res v (A ∪ B) = ∑ v in C, G.deg_res v A +∑ v in C, G.deg_res v B:=
begin
rw ← sum_add_distrib, exact sum_congr rfl (λ _ _ , G.deg_res_add' h),
end
-- counting edges exiting B via ite helper, really just counting edges in e(B,A\B)
lemma bip_count_help {A B : finset α} (hB: B ⊆ A) : ∑ v in B, G.deg_res v (A\B) = ∑ v in B, ∑ w in A\B, ite (G.adj v w) 1 0:=
begin
simp only [deg_res_ones], congr,ext x, simp only [sum_const, algebra.id.smul_eq_mul, mul_one, sum_boole, cast_id],
congr, ext, rwa [mem_res_nbhd,mem_filter,mem_neighbor_finset],
end
-- edges from B to A\B equals edges from A\B to B
lemma bip_count {A B : finset α} (hB: B ⊆ A) : ∑ v in B, G.deg_res v (A\B) = ∑ v in A\B, G.deg_res v B:=
begin
rw G.bip_count_help hB,
have:=sdiff_sdiff_eq_self hB,
conv { to_rhs,congr, skip,rw ← this,},
rw [G.bip_count_help (sdiff_subset A B),this,sum_comm],
congr, ext y, congr,ext x,
split_ifs,{refl},{exfalso, rw adj_comm at h, exact h_1 h},
{exfalso, rw adj_comm at h, exact h h_1},{refl},
end
-- same but between any pair of disjoint sets rather tha B⊆A and A\B
lemma bip_count_help' {A B : finset α} (hB: disjoint A B ) : ∑ v in B, G.deg_res v A = ∑ v in B, ∑ w in A, ite (G.adj v w) 1 0:=
begin
simp only [deg_res_ones], congr,ext x, simp only [sum_const, algebra.id.smul_eq_mul, mul_one, sum_boole, cast_id],
congr, ext, rwa [mem_res_nbhd,mem_filter,mem_neighbor_finset],
end
-- edges from A to B (disjoint) equals edges from B to A
lemma bip_count' {A B : finset α} (hB: disjoint A B ) : ∑ v in B, G.deg_res v A = ∑ v in A, G.deg_res v B:=
begin
rw G.bip_count_help' hB, rw G.bip_count_help' hB.symm,rw sum_comm, congr,
ext y, congr,ext x,
split_ifs,{refl},{exfalso, rw adj_comm at h, exact h_1 h},
{exfalso, rw adj_comm at h, exact h h_1},{refl},
end
-- sum of res_res_deg ≤ sum of res_deg
lemma sum_res_le {A B C: finset α} (hB: B ⊆ A) (hC: C ⊆ A): ∑ v in C, G.deg_res v B ≤ ∑ v in C, G.deg_res v A :=
begin
apply sum_le_sum _,
intros i hi,
rw [deg_res,deg_res], apply card_le_of_subset _,
intros x hx, rw [mem_res_nbhd] at *,
exact ⟨hB hx.1, hx.2⟩,
end
end nbhd_res
#lint
end simple_graph
|
module Rationals
data NotZero : Integer -> Type where --Proof that a number is not zero, needed to construct Q
OneNotZero : NotZero 1
NegativeNotZero : ( n: Integer ) -> NotZero n -> NotZero (-n)
PositiveNotZero : ( m: Integer ) -> LTE 1 (fromIntegerNat m) -> NotZero m
isNotZero : Nat -> Bool
isNotZero Z = False
isNotZero (S k) = True
rational : (p: Nat) -> (q: Integer) -> NotZero q -> (Integer, Integer)
rational Z q x = (toIntegerNat(0), q)
rational (S k) q x = (toIntegerNat(S k), q)
{-
-- snd x can be used instead
SecondPart : (Integer, Integer) -> Integer
SecondPart x = (snd x)
-}
--To simplify rationals to coprime factors, Euclid's algo
gccd : (Integer, Integer) -> Integer
gccd (a, b) = if (isNotZero (toNat b)) then next else a where
next = gccd (b, toIntegerNat (modNat (toNat a) (toNat b)))
--Lots of casts required to divide by GCD
simplifyRational : (Integer, Integer) -> (Integer, Integer)
simplifyRational (a, b) = (sa, sb) where
sa = cast {from=Double} {to=Integer} (da / g) where
da = cast {from=Integer} {to=Double} a
g = cast {from=Integer} {to=Double} (gccd (a,b))
sb = cast {from=Double} {to=Integer} (db / g) where
db = cast {from=Integer} {to=Double} b
g = cast {from=Integer} {to=Double} (gccd (a,b))
InclusionMap : (n : Nat) -> (Integer, Integer) --Includes the naturals in Q
InclusionMap n = rational n 1 OneNotZero
AddRationals : (Integer, Integer) -> (Integer, Integer) -> (Integer, Integer) --Need to implement proof checking for nonzero denominators
AddRationals x y = simplifyRational ((fst x)*(snd y) + (snd x)*(fst y), (snd x)*(snd y))
MultiplyRationals : (Integer, Integer) -> (Integer, Integer) -> (Integer, Integer) --Need to implement proof checking for nonzero denominators
MultiplyRationals x y = simplifyRational ((fst x)*(fst y), (snd x)*(snd y))
--Equality of two rationals, needs to be made as a type instead of a bool
eqRat : (Integer, Integer) -> (Integer, Integer) -> Bool
eqRat x y = if ((fst x)*(snd y) == (snd x)*(fst y)) then True else False
--Inverse of a rational (requires proof that denom != 0)
inverseRat : (Integer, Integer) -> (Integer, Integer)
inverseRat x = simplifyRational ((snd x), (fst x))
--To do : Inverses are unique, except for equality (if b1 and b2 are inverses of a, b1 = b2)
--A GCD function with proof that it is the GCD would be useful to reduce rationals into simplified form
|
{-# OPTIONS --sized-types #-}
module SNat.Log where
open import Size
open import SNat
open import SNat.Order
open import SNat.Order.Properties
open import SNat.Properties
open import SNat.Sum
lemma-≅-log : {ι ι' : Size}{m : SNat {ι}}{n : SNat {ι'}} → m ≅ n → log₂ m ≅ log₂ n
lemma-≅-log z≅z = z≅z
lemma-≅-log (s≅s z≅z) = z≅z
lemma-≅-log (s≅s (s≅s m≅n)) = s≅s (lemma-≅-log (s≅s (lemma-≅-/2 m≅n)))
mutual
lemma-logn≤′logsn : {ι : Size}(n : SNat {ι}) → log₂ n ≤′ log₂ (succ n)
lemma-logn≤′logsn zero = ≤′-eq z≅z
lemma-logn≤′logsn (succ zero) = ≤′-step (≤′-eq z≅z)
lemma-logn≤′logsn (succ (succ n)) = lemma-s≤′s (lemma-≤′-log (lemma-s≤′s (lemma-n/2≤′sn/2 n)))
lemma-≤′-log : {ι ι' : Size}{m : SNat {ι}}{n : SNat {ι'}} → m ≤′ n → log₂ m ≤′ log₂ n
lemma-≤′-log (≤′-eq m≅n) = ≤′-eq (lemma-≅-log m≅n)
lemma-≤′-log (≤′-step {n = n} m≤′n) = trans≤′ (lemma-≤′-log m≤′n) (lemma-logn≤′logsn n)
lemma-1+logn≤′log2n : (n : SNat) → succ (log₂ (succ n)) ≤′ log₂ (succ n + succ n)
lemma-1+logn≤′log2n zero = refl≤′
lemma-1+logn≤′log2n (succ n) rewrite +-assoc-succ (succ (succ n)) (succ n) | +-assoc-succ n (succ n) | +-assoc-succ n n = lemma-s≤′s (lemma-≤′-log (lemma-s≤′s (lemma-n+1≤′2n+2/2 n)))
lemma-log2n≤′1+logn : (n : SNat) → log₂ (n + n) ≤′ succ (log₂ n)
lemma-log2n≤′1+logn zero = ≤′-step refl≤′
lemma-log2n≤′1+logn (succ n) rewrite +-assoc-succ (succ n) n = lemma-s≤′s (lemma-≤′-log (lemma-s≤′s (lemma-2n/2≤′n n)))
|
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include <gsl/span>
namespace terminal_editor {
/// Returns name of passed control character, or nullptr if given byte was not recognized.
/// ISO 30112 defines POSIX control characters as Unicode characters U+0000..U+001F, U+007F..U+009F, U+2028, and U+2029 (Unicode classes Cc, Zl, and Zp) "
/// See also: https://en.wikipedia.org/wiki/C0_and_C1_control_codes
/// @param codePoint Code point for which name to return.
const char* controlCharacterName(uint32_t codePoint);
/// Describes return value of getFirstCodePoint() function.
struct CodePointInfo {
bool valid; ///< True if valid code point was decoded. False otherwise.
gsl::span<const char> consumedInput; ///< Bytes consumed from the input data. Length will be from 1 to 6.
std::string info; ///< Arbitrary information about consumed bytes. If 'valid' is false will contain error information.
uint32_t codePoint; ///< Decoded code point. Valid only if 'valid' is true.
};
/// Figures out what grapeheme is at the begining of data and returns it.
/// See: https://pl.wikipedia.org/wiki/UTF-8#Spos%C3%B3b_kodowania
/// @note All invalid byte sequences will be rendered as hex representations, with detailed explanation why it is invalid.
/// All control characters will be rendered as symbolic replacements.
/// Tab characters will be rendered as symbolic replacement.
/// @param data Input string. It is assumed to be in UTF-8, but can contain invalid characters (which will be rendered as special Graphemes).
/// @param Returns number of bytes from input consumed.
CodePointInfo getFirstCodePoint(gsl::span<const char> data);
/// Parses a line of text into a list of CodePointInfos.
std::vector<CodePointInfo> parseLine(gsl::span<const char> inputData);
/// Analyzes given input data.
/// @param inputData Input string. It is assumed to be in UTF-8, but can contain invalid characters (which will be annotated specially).
/// @return Valid UTF-8 string that describes what original string contains.
std::string analyzeData(gsl::span<const char> inputData);
/// Appends UTF-8 representation of given code point to a string.
/// @todo Move to some string utilities.
/// @param text Text to append code point to.
/// @param codePoint UTF-32 code point to append.
void appendCodePoint(std::string& text, uint32_t codePoint);
/// Appends UTF-8 representation of given code point to an output stream.
/// @todo Move to some string utilities.
/// @param os Output stream to append code point to.
/// @param codePoint UTF-32 code point to append.
void appendCodePoint(std::ostream& os, uint32_t codePoint);
} // namespace terminal_editor
|
\lab{Applications}{SVD-based Image Compression}{SVD}
\objective{Explore the SVD as a method of image compression}
The singular value decomposition is very useful. In this lab, we are going to explore how the SVD can be used to compress image data. Recall that the SVD is a decomposition of an $m \times n$ matrix $A$
of rank $r$ into the product $A = U \Sigma V^H$, where $U$ and $V$
are unitary matrices having dimensions $m \times m$ and $n \times n$,
respectively, and $\Sigma$ is an $m \times n$ diagonal matrix
\begin{equation*}
\Sigma = \mbox{diag}(\sigma_1,\sigma_2,\ldots,\sigma_r,0,\ldots,0)
\end{equation*}
where $\sigma_1 \geq \sigma_2 \geq \ldots \geq \sigma_r > 0$ are the
singular values of $A$. Upon closer inspection, we can write
\begin{equation*}
U = \begin{pmatrix}U_1 & U_2\end{pmatrix}, \quad \Sigma =
\begin{pmatrix}\Sigma_r & 0\\0 & 0\end{pmatrix}, \quad V =
\begin{pmatrix}V_1 & V_2\end{pmatrix},
\end{equation*}
where $U_1$ and $V_1$ have dimensions $m\times r$ and $n\times r$
respectively and $\Sigma_r$ is the $r\times r$ diagonal matrix of
(nonzero) singular values. Multiplying this out yields the reduced
form of the SVD
\begin{equation*}
A =
\begin{pmatrix}U_1 & U_2\end{pmatrix}
\begin{pmatrix}\Sigma_r & 0\\0 & 0\end{pmatrix}
\begin{pmatrix}V^H_1 \\ V^H_2\end{pmatrix} =
U_1 \Sigma_r V_1^H
\end{equation*}
\subsection*{Low rank data storage}
If the rank of a given matrix is significantly smaller than its
dimensions, the reduced form of the SVD offers a way to store $A$ with less memory.
Without the SVD, an $m\times n$ matrix requires storing $m*n$ values.
By decomposing the original matrix into the SVD reduced form, $U_1$, $\Sigma_r$ and $V_1$ together require $(m*r)+r+(n*r)$ values.
Thus if $r$ is much smaller than both $m$ and $n$,
we can obtain considerable efficiency. For example, suppose
$m=100$, $n=200$ and $r=20$.
Then the original matrix would require storing $20,000$ values whereas the reduces form of the SVD only requires storing $6020$ values.
\subsection*{Low rank approximation}
The reduced form of the SVD also provides a way to approximate a
matrix with another one of lower rank. This idea is used in many areas of applied
mathematics including signal processing, statistics, semantic
indexing (search engines), and control theory. If we are given a matrix $A$ of rank $r$,
we can find an approximate matrix $\widehat A$ of rank $s<r$ by taking
the SVD of $A$ and setting all of its singular values after
$\sigma_s$ to zero, that is,
\begin{equation*}
\Sigma_{\widehat A} = \sigma_1, \sigma_2, \ldots, \sigma_s,\sigma_{s+1}=0,\ldots,\sigma_r=0
\end{equation*}
and then multiplying the matrix back together again. The more singular values we keep, the closer our approximation is to $A$.
The number of singular values we decide to preserve depends on how close of an approximation we need and what our size requirements are for $U_1$, $\Sigma_{\widehat A}$, and $V_1$.
Try plotting the the singular values. We have plotted the singular values to the image below. Matrix rank is on the x-axis and the eigenvalues are the y-axis. Note that SVD orders the singluar values from greatest to least. The greatest eigenvalues contribute most to the image while the smallest eigenvalues hardly contribute anything to the final approximation. By looking at the graph we can have a rough idea of how many singular values we need to preserve to have a good approximation of $A$. The matrix rank of the image below is $670$. However, as the plot shows, we could easily approximate the image using only the first half of the singular values.
\begin{center}
\includegraphics[scale=.2]{hubble_red.png}
\includegraphics[scale=.4]{hubble_svals.pdf}
\end{center}
\begin{lstlisting}[style=python]
: import scipy as sp
: import numpy.linalg as nla
: A = sp.array([[1,1,3,4],[5,4,3,7],[9,10,10,12],[13,14,15,16],[17,18,19,20]])
: nla.matrix_rank(A)
: U,s,Vt = nla.svd(A)
: S = sp.diag(s)
: Ahat = sp.dot(sp.dot(U[:,0:3], S[0:3,0:3]), Vt[0:3,:])
: nla.matrix_rank(Ahat)
: nla.norm(A)-nla.norm(Ahat)
\end{lstlisting}
% We can compute the rank of a matrix by looking at the number of nonzero singular values in the SVD decompositon. The following function will compute the rank of a matrix. The \li{sp.finfo(float).eps} gives us the smallest representable postitive number such that $1.0+\mbox{eps} \neq 1.0$ Anything smaller than the eps value is numerically zero to the computer.
% \begin{lstlisting}[style=python]
% : def matrix_rank(X):
% :.... S = nla.svd(X, compute_uv=False)
% :.... tol = S.max()*sp.finfo(S.dtype).eps
% :.... return sum(S>tol)
% : matrix_rank(Ahat)
% \end{lstlisting}
Note that $\widehat A$ is ``close'' to the original matrix $A$, but
that its rank is 3 instead of 4.
\subsection*{Application to Imaging}
Enter the following into IPython (note that any image you might have will work):
\begin{lstlisting}
: import matplotlib.pyplot as plt
: X = sp.misc.imread('fingerprint.png')[:,:,0].astype(float)
: X.nbytes #number of bytes needed to store X
: sp.misc.imshow(X)
\end{lstlisting}
Computing the SVD of your image is simple. Remember to make the singluar values a diagonal matrix before multiplying.
\begin{lstlisting}
: U,s,Vt = la.svd(X)
: S = sp.diag(s)
\end{lstlisting}
In the next code block, $n$ repsents the desired rank of the output.
\begin{lstlisting}
: n=50
: u1, s1, vt1 = U[:,0:n], S[0:n,0:n], Vt[0:n,:]
: Xhat = sp.dot(sp.dot(u1, s1), vt1)
: (u1.nbytes+sp.diag(s1).nbytes+vt1.nbytes) - X.nbytes #should be negative
: sp.misc.imshow(Xhat)
\end{lstlisting}
%write code that will caluculate final image column by column in rank 1 approximations. It is actually smaller to transmit the matrix col by col than chunks of cols. We only send 70% of the data if we send col by col than entire matices. 1017856bytes vs 1445888 bytes.
\begin{problem}
A law enforcement agency has been needing to efficiently store over 50,000 fingerprints. They have decided to use an SVD based compression algorithm. Your job is to try several parameters for the SVD algorithm and recommend those parameters that retain the highest quality but compress the most. There should be no smearing or blocking in reconstructed final image and fingerprint detail must be retained (otherwise the fingerprint is worthless). As part of your recommendation, calculate how much memory would be needed on average to store each compressed fingerprint. Expand your results to say how much space could be saved if the entire database of fingerprints were compressed using your algorithm.
\end{problem}
% \begin{problem}
% Explore the clown picture for several different values of rank.
% Conduct the experiments described above. Note that the original
% image takes 64,000 integers to store. Compare this with the storage
% needs for various lower-rank SVD approximations. What conclusions
% can you draw? Expirement with other images we've used in this book.
% \end{problem}
|
function Acc = bssfo_off2on(CNT,general_initparam,bssfo_param)
opt = opt_cellToStruct(general_initparam);
bssfo_opt = opt_cellToStruct(bssfo_param);
% Pre-processing
%Train
CNT_off = prep_selectChannels(CNT{1}, {'Index', opt.channel_index});
CNT_off =prep_filter(CNT_off , {'frequency', bssfo_opt.init_band});
SMT_off = prep_segmentation(CNT_off, {'interval', opt.time_interval});
%Test
CNT_on= prep_selectChannels(CNT{2}, {'Index', opt.channel_index});
CNT_on =prep_filter(CNT_on , {'frequency', bssfo_opt.init_band});
SMT_on = prep_segmentation(CNT_on, {'interval', opt.time_interval});
%% BSSFO - optimal band and weight
[FilterBand]=func_bssfo(SMT_off, {'classes', {'right', 'left'}; ...
'frequency', {bssfo_opt.mu_band,bssfo_opt.beta_band}; 'std', {5, 25}; 'numBands', bssfo_opt.numBands; ...
'numCSPPatterns', opt.CSPFilter; 'numIteration', bssfo_opt.numIteration});
%% BSSFO - CSP filter from optimal band
for iii=1:bssfo_opt.numIteration
CNTtr=prep_filter(CNT{1}, {'frequency', FilterBand.sample(:,iii)'});
CNTtr= prep_selectChannels(CNTtr, {'Index', opt.channel_index});
SMT=prep_segmentation(CNTtr, {'interval', opt.time_interval});
[SMT, CSP_W, CSP_D]=func_csp(SMT,{'nPatterns', opt.CSPFilter});
FT=func_featureExtraction(SMT, {'feature','logvar'});
[CF_PARAM]=func_train(FT,{'classifier','LDA'});
clear CNTclass CNTtr SMT FT CSP_D
CNTte=prep_filter(CNT{2}, {'frequency', FilterBand.sample(:,iii)'});
CNTte= prep_selectChannels(CNTte, {'Index', opt.channel_index});
SMTte=prep_segmentation(CNTte, {'interval', opt.time_interval});
SMTfb=func_projection(SMTte, CSP_W);
FTfb=func_featureExtraction(SMTfb, {'feature','logvar'});
[cf_out]=func_predict(FTfb, CF_PARAM);
ensemble(:,iii)=cf_out.*FilterBand.weight(iii); %
clear CNTte SMTte FTfb CSP_W
end
sum_ensemble = sum(ensemble,2); %
%%
[loss out]=eval_calLoss(CNT{2}.y_dec, sum_ensemble); %
Acc=1-loss;
end
|
# Simple Example
With tributary we can easily construct a forward-propagating reactive graph
```python
from display_helper import clean
clean()
from perspective import Plugin
import tributary.streaming as ts
import random, time
```
```python
def foo():
return random.random()
def long():
print('long called!')
time.sleep(1)
return 5
# A timer calls the given function every interval up to count times
test = ts.Timer(foo, {}, interval=.5, count=5)
test2 = ts.Negate(test)
res2 = test + test2
p2 = ts.Print(res2)
```
```python
ts.GraphViz(p2)
```
```python
x = ts.run(p2)
```
0.0
0.0
0.0
0.0
0.0
```python
x.result()
```
# More Complex Example
Let's construct a slightly more complex graph
```python
import asyncio
def foo():
return random.random()
async def long():
await asyncio.sleep(1)
return 5
rand = ts.Timer(foo, interval=0, count=5)
five = ts.Timer(long, interval=0, count=5)
one = ts.Const(1)
five2 = ts.Const(5)
neg_rand = ts.Negate(rand)
x1 = rand + five # 5 + rand
x2 = x1 - five2 # rand
x3 = x2 + neg_rand # 0
res = x3 + one # 1
p = ts.Print(res)
```
```python
p.graphviz()
```
```python
x = ts.run(p)
```
0.9999999999999999
0.9999999999999998
1.0000000000000004
0.9999999999999997
0.9999999999999998
```python
x.result()
```
# Rolling Mean
```python
def stream():
for _ in range(10):
yield _
f = ts.Foo(stream)
s = f.rollingSum()
c = f.rollingCount()
f3 = ts.Div(s, c)
p = ts.Print(f3)
```
```python
p.graphviz()
```
```python
x = ts.run(p)
```
0.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
```python
x.result()
```
# Custom Calculations and Window Functions
```python
def myfoo(ds):
for d in ds:
vals = d.values()
d['HIGH'] = max(vals)
d['LOW'] = min(vals)
d['MID'] = sum(vals)/len(vals)
avgs = [x['MID'] for x in ds]
ds[-1]['SMA'] = sum(avgs)/len(avgs)
return [ds[-1]]
```
```python
vals = ts.Random(100)
w = ts.Window(vals, size=5)
n = ts.Apply(w, myfoo)
psp1 = ts.Perspective(n, schema={'HIGH': float, 'LOW': float, 'MID': float, 'SMA': float}, plugin=Plugin.YLINE)
x = ts.run(ts.Perspective(psp1, schema={'HIGH': float, 'LOW': float, 'MID': float, 'SMA': float}))
# This will only display in the notebook, not on Github
# it uses https://perspective.finos.org/
```
PerspectiveWidget(columns=['HIGH', 'LOW', 'MID', 'SMA'], plugin=Plugin.YLINE)
PerspectiveWidget(columns=['HIGH', 'LOW', 'MID', 'SMA'])
# Symbolic - Simple Example
Using tributary's sympy functionality, we can construct relatively complicated graphs. Here we will construct as simple lazy graph
```python
import tributary.symbolic as ts
import tributary.streaming as tss
# Parse sympy expression
expr = ts.parse_expression("10sin**2 x**2 + 3xyz + tan theta")
# Generate a new class representing the graph
clz = ts.construct_streaming(expr)
# A function to use as an input
def foo(*args):
for _ in range(5):
yield _
# Construct with inputs
x = clz(x=tss.Const(1), y=tss.Foo(foo), z=tss.Timer(lambda: 1, count=0), theta=tss.Const(4))
```
```python
# View the graph
x.graphviz()
```
```python
# Run the graph
y = x.run()
y
```
<Task pending coro=<_run() running at /Users/theocean154/Programs/projects/tributary/tributary/examples/tributary/streaming/__init__.py:11>>
```python
y.result()
```
# Symbolic - More Complicated Example
Here we will construct a streaming pricer for a vanilla european option
```python
import numpy as np
import sympy as sy
from IPython.display import display, HTML
from sympy.stats import Normal as syNormal, cdf
sy.init_printing()
# adapted from https://gist.github.com/raddy/bd0e977dc8437a4f8276
#spot, strike, vol, days till expiry, interest rate, call or put (1,-1)
spot, strike, vol, dte, rate, cp = sy.symbols('spot strike vol dte rate cp')
T = dte / 260.
N = syNormal('N', 0.0, 1.0)
d1 = (sy.ln(spot / strike) + (0.5 * vol ** 2) * T) / (vol * sy.sqrt(T))
d2 = d1 - vol * sy.sqrt(T)
TimeValueExpr = sy.exp(-rate * T) * (cp * spot * cdf(N)(cp * d1) - cp * strike * cdf(N)(cp * d2))
```
```python
TimeValueExpr
```
```python
import tributary.symbolic as ts
PriceClass = ts.construct_streaming(TimeValueExpr)
def strikes():
strike = 205
while strike < 220:
yield strike
strike += 2.5
price = PriceClass(spot=tss.Const(210.59),
strike=tss.Foo(strikes),
vol=tss.Const(14.04),
dte=tss.Const(4),
rate=tss.Const(.2175),
cp=tss.Const(-1))
price.graphviz()
```
Our function `strikes` will stream in strike prices, and we will see our price output change accordingly
```python
x = tss.run(tss.Print(price._node))
```
124.8198933249367
126.82508170405075
128.83501237227932
130.8496010565144
132.86876573965452
134.8924265789232
```python
x.result()
```
```python
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.