Datasets:
AI4M
/

text
stringlengths
0
3.34M
import numpy as np import matplotlib.pyplot as plt import nyles as nyles_module import parameters nh = 2 nz = 64 ny = 32 nx = 32 Lz = nz Ly = ny Lx = nx # Get the default parameters, then modify them as needed param = parameters.UserParameters() param.model["modelname"] = "advection" param.model["geometry"] = "perio_x" param.model["Lx"] = Lx param.model["Ly"] = Ly param.model["Lz"] = Lz param.IO["datadir"] = "~/data/Nyles" param.IO["expname"] = "jetx" param.IO["mode"] = "overwrite" param.IO["variables_in_history"] = ['u', 'b'] param.IO["timestep_history"] = 1. param.time["timestepping"] = "LFAM3" param.time["tend"] = 30.0 param.time["auto_dt"] = True # parameter if auto_dt is False param.time["dt"] = .05 # parameters if auto_dt is True param.time["cfl"] = 0.8 param.time["dt_max"] = 1.0 param.discretization["global_nx"] = nx param.discretization["global_ny"] = ny param.discretization["global_nz"] = nz param.discretization["orderVF"] = 5 # upwind-order for vortex-force term param.discretization["orderA"] = 3 # upwind-order for advection term param.MPI["nh"] = nh param.MPI["npx"] = 1 param.MPI["npy"] = 1 param.MPI["npz"] = 1 param.physics['diff_coef'] = {'b': 1e-1} nyles = nyles_module.Nyles(param) state = nyles.model.state grid = nyles.grid b = state.b.view('i') u = state.u['i'].view('i') z = grid.z_b.view('i')/Lz y = grid.y_b.view('i')/Ly x = grid.x_b.view('i')/Lx i1 = nx//3 i2 = 2*nx//3 j1 = ny//3 j2 = 2*ny//3 u[...] = z-0.5 b[:] = np.round(x*6) % 2 + np.round(y*6) % 2 + np.round(z*6) % 2 b *= 0.1 nyles.model.make_u_divergentfree() nyles.model.diagnose_var(state) nyles.run()
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.num.lemmas import Mathlib.data.nat.prime import Mathlib.tactic.ring import Mathlib.PostPort namespace Mathlib /-! # Primality for binary natural numbers This file defines versions of `nat.min_fac` and `nat.prime` for `num` and `pos_num`. As with other `num` definitions, they are not intended for general use (`nat` should be used instead of `num` in most cases) but they can be used in contexts where kernel computation is required, such as proofs by `rfl` and `dec_trivial`, as well as in `#reduce`. The default decidable instance for `nat.prime` is optimized for VM evaluation, so it should be preferred within `#eval` or in tactic execution, while for proofs the `norm_num` tactic can be used to construct primality and non-primality proofs more efficiently than kernel computation. Nevertheless, sometimes proof by computational reflection requires natural number computations, and `num` implements algorithms directly on binary natural numbers for this purpose. -/ namespace pos_num /-- Auxiliary function for computing the smallest prime factor of a `pos_num`. Unlike `nat.min_fac_aux`, we use a natural number `fuel` variable that is set to an upper bound on the number of iterations. It is initialized to the number `n` we are determining primality for. Even though this is exponential in the input (since it is a `nat`, not a `num`), it will get lazily evaluated during kernel reduction, so we will only require about `sqrt n` unfoldings, for the `sqrt n` iterations of the loop. -/ def min_fac_aux (n : pos_num) : ℕ → pos_num → pos_num := sorry theorem min_fac_aux_to_nat {fuel : ℕ} {n : pos_num} {k : pos_num} (h : nat.sqrt ↑n < fuel + ↑(bit1 k)) : ↑(min_fac_aux n fuel k) = nat.min_fac_aux ↑n ↑(bit1 k) := sorry /-- Returns the smallest prime factor of `n ≠ 1`. -/ def min_fac : pos_num → pos_num := sorry @[simp] theorem min_fac_to_nat (n : pos_num) : ↑(min_fac n) = nat.min_fac ↑n := sorry /-- Primality predicate for a `pos_num`. -/ @[simp] def prime (n : pos_num) := nat.prime ↑n protected instance decidable_prime : decidable_pred prime := sorry end pos_num namespace num /-- Returns the smallest prime factor of `n ≠ 1`. -/ def min_fac : num → pos_num := sorry @[simp] theorem min_fac_to_nat (n : num) : ↑(min_fac n) = nat.min_fac ↑n := num.cases_on n (idRhs (↑(min_fac 0) = ↑(min_fac 0)) rfl) fun (n : pos_num) => idRhs (↑(pos_num.min_fac n) = nat.min_fac ↑n) (pos_num.min_fac_to_nat n) /-- Primality predicate for a `num`. -/ @[simp] def prime (n : num) := nat.prime ↑n protected instance decidable_prime : decidable_pred prime := sorry
\lab{Compressed Sensing}{Compressed Sensing} \label{lab:compressed_sensing} \objective{Learn About Techniques in Compressed Sensing.} One of the more important and fundamental problems in mathematics and science is solving a system of linear equations \[ Ax = b. \] Depending on the properties of the matrix $A$ (such as its dimensions and rank), there may be exactly one solution, infinitely many solutions, or no solution at all. In the case where $A$ is a square invertible matrix, there is of course one unique solution, given by $A^{-1}b$. There are various computational methods for inverting $A$, and we have studied many of them previously. When $b$ does not lie in the range of $A$, there is no exact solution. We can still hope to find approximate solutions, and techniques such as least squares and least absolute deviations provide ways to do this. The final case is when there are infinitely many vectors $x$ that satisfy $Ax = b$. How do we decide which vector to choose? A common approach is to choose a vector $x$ of minimal norm satisfying $Ax = b$. This can be stated as an optimization problem: \begin{align*} \text{minimize}\qquad &\|x\|\\ \text{subject to} \qquad &Ax = b. \end{align*} When we use the standard Euclidean $2$-norm, the problem is equivalent to the quadratic program \begin{align*} \text{minimize}\qquad &x^Tx\\ \text{subject to} \qquad &Ax = b, \end{align*} which we can solve using an iterative procedure. Alternatively, the solution is given directly by $A^\dagger b$, where $A^\dagger$ is the Moore-Penrose pseudoinverse of $A$. If instead of the $2$-norm we use the $1$-norm, our problem can be restated as a linear program, and solved efficiently using the Simplex Algorithm or an Interior Point method. Of course we can use any norm whatsoever, but finding the solution may be much more difficult. The basic problem in the field of Compressed Sensing is to recover or reconstruct certain types of signals from a small set of measurements. For example, we might have measurements of the frequency spectrum of an audio signal, and we wish to recover the original audio signal as nearly as possible. Mathematically, this problem can be viewed as solving the under-determined system of equations $Ax = b$, where $b$ is a vector of measurements and $A$ is called the measurement matrix. The crucial idea that Compressed Sensing brings to the table is the concept of \emph{sparsity}, which we address now. \section*{Sparsity and the $l_0$ Pseudonorm} \emph{Sparsity} is a property of vectors in $\mathbb{R}^n$ related to how compactly and concisely they can be represented in a given basis. Stated more concretely, the sparsity of a vector $x$ (expressed in some given basis) refers to how many nonzero entries are in $x$. A vector having at most $k$ nonzero entries is said to be $k$-sparse. This concept can be extended to time series (such as an audio signal) and to images. Figure 32.1 shows examples of both sparse and non-sparse signals. \begin{figure} \centering \includegraphics[width=\textwidth]{sparse.pdf} \caption{A sparse signal and a non-sparse signal.} \label{fig:sparse} \end{figure} As a convenient way of measuring sparsity, we define the so-called $l_0$ pseudonorm, notated $\|\cdot\|_0$, that simply counts the number of nonzero entries in a vector. For example, if we have \[ x = \begin{bmatrix} 1&0&0&-4&0 \end{bmatrix}^T \] and \[ y = \begin{bmatrix} .5&.2&-.01&3&0 \end{bmatrix}^T, \] we then have \[ \|x\|_0 = 2 \] and \[ \|y\|_0 = 4. \] Despite our choice of notation, $\|\cdot\|_0$ is not truly a norm (which properties does it fail to satisfy?). Keep this in mind, even if we refer to it as the $l_0$ norm. As mentioned earlier, sparsity is of central importance in Compressed Sensing, for it provides a way for us to select from the infinite possibilities a single vector $x$ satisfying $Ax = b$. In particular, we require $x$ to be as sparse as possible, i.e. to have minimal $l_0$ norm. Stated explicitly as an optimization problem, Compressed Sensing boils down \begin{align*} \text{minimize}\qquad &\|x\|_0\\ \text{subject to} \qquad &Ax = b. \end{align*} \section*{Sparse Reconstruction} How does the Compressed Sensing framework laid out above help us recover a signal from a set of measurements? If we know nothing about the signal that we are trying to reconstruct, anything but a complete set of measurements (or \emph{samples}) of the signal will be insufficient to fully recover the signal without any error. However, we can often make certain assumptions about the unknown signal, such as setting an upper bound for its highest frequency. Given this prior knowledge about the frequency of the signal, we \emph{are} able to perfectly or nearly perfectly reconstruct the signal from an incomplete set of measurements, provided that the sampling rate of the measurements is more than twice that of the largest frequency. This classic result in signal processing theory is known as the \emph{Nyquist-Shannon sampling theorem}. What if, instead of having prior knowledge about the frequency of the signal, we have prior knowledge about its sparsity? Recent research asserts that it is possible to recover sparse signals to great accuracy from just a few measurements. This matches intuition: sparse signals do not contain much information, and so it ought to be possible to recover that information from just a few samples. Stated more precisely, if $\hat{x} \in \mathbb{R}^n$ is sufficiently sparse and an $m \times n$ matrix $A$ ($m < n$) satisfies certain properties (to be described later), with $A\hat{x} = b$, then the solution of the optimization problem \begin{align*} \text{minimize}\qquad &\|x\|_0\\ \text{subject to}\qquad &Ax = b \end{align*} yields $\hat{x}$. The matrix $A$ above must satisfy a technical condition called the \emph{Restricted Isometry Principle}. Most random matrices obtained from standard distributions (such as the Gaussian or Bernoulli distributions) satisfy this condition, as do transformation matrices into the Fourier and Wavelet domains. Generally speaking, the measurement matrix $A$ represents a change of basis from the \emph{sparse} basis to the \emph{measurement} basis, followed by an under-sampling of the signal. The Restricted Isometry Principle guarantees that the measurement basis is incoherent with the sparse basis; that is, a sparse signal in the sparse basis is diffuse in the measurement basis, and vice versa (see Figure \ref{fig:incoherent}). This ensures that the information contained in the few nonzero coefficients in the sparse domain is spread out randomly and roughly evenly among the coefficients in the measurement domain. We can then obtain a small random subset of these measurement coefficients, solve the above optimization problem, and recover the original signal. \begin{figure} \centering \includegraphics[width=\textwidth]{incoherent.pdf} \caption{A sparse image (left) and its Fourier transform (right). The Fourier domain is incoherent with the standard domain, so the Fourier transform of the spare image is quite diffuse.} \label{fig:incoherent} \end{figure} Fortunately, many types of signals that we wish to measure are sparse in some domain. For example, many images are sparse in the Wavelet domain. It turns out that the Fourier domain is incoherent with the Wavelet domain, so if we take measurements of the image in the Fourier domain, we are able to recover the image with high fidelity from relatively few measurements. This has been particularly useful in magnetic resonance imaging (MRI), a medical process that obtains pictures of tissues and organs in the body by taking measurements in the Fourier domain. Collecting these measurements can in some cases be harmful. Compressed sensing allows for fewer measurements and therefore a shorter, safer MRI experience. \section*{Solving the $l_0$ Minimization Problem} Now that we have become familiar with the mathematical underpinnings of compressed sensing, let us now turn to actually solving the problem. Unfortunately, the $l_0$ minimization problem stated above is NP hard and thus computationally intractable in its current form. Another key result in compressed sensing states that we can replace the $l_0$ norm with the $l_1$ norm and with high probability still recover the original signal, provided it is sufficiently sparse. Since the $l_1$ minimization problem can be solved efficiently, we have a viable computational approach to compressed sensing. Recall that we can convert the $l_1$ minimization problem into a linear program by introducing an additional vector $u$ of length $n$, and then solving \begin{align*} \text{minimize}\qquad &\begin{bmatrix} \mathbf{1} & 0 \end{bmatrix} \begin{bmatrix} u \\ x \end{bmatrix}\\ \text{subject to}\qquad &\begin{bmatrix} -I & I\\ -I & -I \end{bmatrix} \begin{bmatrix} u \\ x \end{bmatrix} \leq \begin{bmatrix} 0\\ 0 \end{bmatrix},\\ &\begin{bmatrix} 0 & A \end{bmatrix} \begin{bmatrix} u \\ x \end{bmatrix} = b. \end{align*} Of course, solving this gives values for the optimal $u$ and the optimal $x$, but we only care about the optimal $x$. \begin{problem} Write a function \li{l1Min} that takes a matrix $A$ and vector $b$ as inputs, and returns the solution to the optimization problem \begin{align*} \text{minimize}\qquad &\|x\|_1\\ \text{subject to} \qquad &Ax = b. \end{align*} Formulate the problem as a linear program, and use CVXOPT to obtain the solution. \end{problem} Let's reconstruct a sparse image using different numbers of measurements, and compare results. Load the image contained in the file \li{ACME.png} into Python as follows: \begin{lstlisting} >>> import numpy as np >>> from matplotlib import pyplot as plt >>> acme = 1 - plt.imread('ACME.png')[:,:,0] >>> acme.shape (32L, 32L) \end{lstlisting} The image contains $32^2$ pixels, and so viewed as a flat vector, it has $32^2$ entries. Now build a random measurement matrix based on $m$ samples as follows: \begin{lstlisting} >>> # assume the variable m has been initialized >>> np.random.seed(1337) >>> A = np.random.randint(0,high=2,size=(m,32**2)) \end{lstlisting} Next, calculate the $m$ measurements: \begin{lstlisting} >>> b = A.dot(acme.flatten()) \end{lstlisting} We are now ready to reconstruct the image using our function \li{l1Min}: \begin{lstlisting} >>> rec_acme = l1Min(A,b) \end{lstlisting} \begin{problem} Following the example above, reconstruct the ACME image using 200, 250, and 270 measurements. Be sure to execute the code \li{np.random.seed(1337)} prior to each time you initialize your measurement matrix, so that you will obtain consistent answers. Report the $2$-norm distance between the each reconstructed image and the original ACME image. \end{problem} Figure \ref{fig:reconstruct} shows the results of reconstructing a similar sparse image using both the $1$-norm and the $2$-norm. \begin{figure} \centering \includegraphics[width=\textwidth]{reconstruct.pdf} \caption{A sparse image (left), perfect reconstruction using $l_1$ minimization (middle), and imperfect reconstruction using $l_2$ minimization (right).} \label{fig:reconstruct} \end{figure} \section*{Tesselated Surfaces and the Single Pixel Camera} We now generalize our discussion to reconstructing functions defined on surfaces. Such a function might give a color at each point on the surface, or the temperature, or some other property. The surface may be a sphere (to model the surface of the earth), a cube, or some other desired form. To make the problem tractable, we must break the surface up into a set of discrete polygonal faces, called a tessellation. See Figure \ref{Fig:Earth} for an example of a tessellated sphere. Now that we have a tessellation, our function can be represented by a vector, consisting of the function value for each facet (element of the tessellation). We are thus in a position to apply the techniques of compressed sensing to recover the function. How do we go about acquiring color measurements on a tessellated surface? One cheap method is to use a \emph{single-pixel camera}. Such a camera can only measure color value at a time. The camera points to a specific spot on the surface, and records a weighted average of the colors near that spot. By taking measurements at random spots across the surface, the single-pixel camera provides us with a vector of measurements, which we can then use to reconstruct the color value for each facet of the tessellation. See Figure \ref{Fig:Earth} for the results of a single-pixel camera taking measurements of the earth. \begin{figure} \begin{center} $\begin{array}{cc} \includegraphics[scale = .6]{OriginalCropped} & \includegraphics[scale = .6]{EstimatedCropped} \\ \includegraphics[scale = .5]{Original2Cropped} & \includegraphics[scale = .5]{Estimated2Cropped} \\ \mbox{\bf (a)} & \mbox{\bf (b)} \end{array}$ \end{center} \caption{A 3-D model of the earth, with 5120 faces. $(a)$ shows two views of the model drawn directly from satellite imagery. $(b)$ shows two views of the reconstruction based upon 2500 single-pixel measurements.} \label{Fig:Earth} \end{figure} The single-pixel camera measurement process can be modeled as matrix multiplication by a measurement matrix $A$, which fortunately has the Restricted Isometry Property. In the following, we provide you with code to take single pixel measurements. It works as follows \begin{lstlisting} run camera.py myCamera=Camera(faces,vertices,colors) \end{lstlisting} Where faces, verticies and colors are given by the tesselation. To take a picture you use \begin{lstlisting} myCamera.add_pic(theta,phi,r) \end{lstlisting} Where theta, phi, and r are the spherical coordinates of the camera. Recall to change spherical coordinates to rectangular the formula is \[ (r\sin(\phi)\cos(\theta),r\sin(\phi)\sin(\theta),r\cos(\phi)) \] Where $\theta \in [0,2\pi),\phi \in [0,\pi), r \in [0,\infty)$ Calling \li{add_pic} many times at different places on a sphere (constant $r$ value, varying $\theta$ and $\phi$) will build the measurement matrix as well as the measurements. You can return these by \begin{lstlisting} A,b=myCamera.returnData() \end{lstlisting} In this applications signals are only sparse in some appropriate representation (such as Fourier or wavelet). This method generally can still be applied in such cases. Let $V$ represent the transformation under which $s$ is sparse, or in other words: \begin{equation} s = V p \end{equation} $V$ is the inverse Fourier. We can then recast $A s=b$ as \begin{equation} A V p = b \end{equation} This then allows us to find $p$ using Compressed Sensing, which in turn allows us to reconstruct $s$ by using $V$. In the the following problem $V$ will be given to you. You must reconstruct the color functions for the tesselated surfaces, and then plot these surfaces using the code we provide you. %\begin{problem} %We will perform compressed sensing on a Rubik's cube. The Rubik's cube has a natural tessellation, with each facet %being a square having one color. Each color can be represented as a vector of length 3, where we have split the %color into three color channels (red, green, and blue). The set of colors for the entire Rubik's cube is fairly %sparse in each color channel, so we can reconstruct the color values in each color channel separately. % %In the file \li{StudentRubiksData.npz}, we have given you the measurement matrices for each color channel %(accessed by the keys \li{'A1', 'A2', 'A3'}) along with the respective measurements in each color channel %(accessed by the keys \li{'b1', 'b2', 'b3'}). Reconstruct the colors in each color channel, obtaining %three arrays. Then stack these arrays row-wise into an array with three rows. Report this final array. % %To visualize your result, we have provided code in the file \li{visualize.py} that you can call. %You also need to load in the array corresponding to the key \li{'centers'} in the data archive %\li{StudentRubiksData.npz}. We assume the variable holding this array is named \li{c}. %Execute the following (assuming that the variable holding the array %you obtained above containing the reconstructed colors is named \li{r}): %\begin{lstlisting} %>>> from visualize import visualizeSurface %>>> visualizeSurface(r.clip(0,1), c, 3) %\end{lstlisting} %You should see a plot showing the Rubik's cube. %\end{problem} \begin{problem} We will reconstruct the surface of the earth from sparse satellite imagery. The earth is modeled by a sphere, which can be tessellated into triangular faces, each having a color value. There are three color channels, and the colors are sparse in each channel in the appropriate basis. In the file \li{StudentEarthData.npz}, we have given you the faces, vertices, colors, and the inverse fourier matrix, (accessed by the key \li{'faces'}, \li{'vertices'}, \li{'C'}, and \li{'V'} respectively), Take pictures with the single pixel camera code (using $r=3$) and then reconstruct the colors in each color channel, obtaining three arrays. Then stack these arrays column-wise into an array with three columns. Report this final array. To visualize your result, we have provided code in the file \li{visualize2.py} that you can call. Execute the following (assuming that the variable holding the array you obtained above containing the reconstructed colors is named \li{s}): \begin{lstlisting} >>> from visualize2 import visualizeEarth >>> visualizeEarth(faces, vertices, s.clip(0,1)) \end{lstlisting} You should see a plot showing the reconstructed earth. We could have reconstructed a more detailed earth by choosing a finer tessellation, but you should be able to make out the shapes of the major continents. You can compare this to the original by running \begin{lstlisting} >>> visualizeEarth(faces, vertices, colors) \end{lstlisting} Try the reconstruction with 450, 550, 650 measurements and report the absolute difference between the reconstruction and the actual colors. \end{problem}
# Copyright (c) 2018-2021, Carnegie Mellon University # See LICENSE for details TempArrayType := (child, y, x, index) -> When( IsBound(child.a.t_in), child.a.t_in[index], let( X := Flat([x])[1], # without type unification everything has same type When(X.t.t=TComplex or Flat([y])[1].t.t=TComplex, TComplex, X.t.t) )); TempArray := (y, x, child) -> let( cols := Flat([Cols(child)]), StripList( List( [1..Length(cols)], i -> TempVec( TArray( TempArrayType(child, y, x, i), cols[i])) ))); # HACKed in. This should just be rolled into TempArray or otherwise be handled cleanly. TempArraySeq := function(y, x, child) local dims, P; if ObjId(child)=BB then dims := child.child(1).dims(); P := child.child(1).P; else dims := child.dims(); P := child.P; fi; return( StripList(List( Flat([ dims[2]/P ]), z -> TempVec( #TArray(TempArrayType(child, Flat([y])[1], Flat([x])[1]), z)) TArray(TempArrayType(child, y, x, 1), z)) ))); end; #F _CodeSums(<sums-spl>, <y-output-var>, <x-input-var>) #F #F Generates unoptimize loop code for <sums-spl> #F _CodeSums := function(sums, y, x) local code; code := sums.code(y,x); code.dimensions := sums.dimensions; code.root := sums; return code; end; #CodeSums := _CodeSums; _CodeSumsAcc := function(sums, y, x) local code; code := _CodeSums(sums, y, x); code := SubstTopDownNR(code, [assign, [@(0,nth), @(1, var, e->Same(e,y)), ...], @(3)], e -> assign_acc(@(0).val, @(3).val)); return code; end; # ======================================================================================= # Code generation templates # [ Data, Blk, Blk1, Prm, R, W, SUM, ISum, Compose ] # ======================================================================================= Formula.code := (self,y,x) >> self.child(1).code(y, x); BB.code := (self,y,x) >> MarkForUnrolling(_CodeSums(self.child(1), y, x)); Buf.code := (self,y,x) >> _CodeSums(self.child(1), y, x); COND.code := (self,y,x) >> IF(self.cond, _CodeSums(self.child(1), y, x), _CodeSums(self.child(2), y, x)); Data.code := meth(self, y, x) local val, t; if self.inline then # we set live_out to prevent copy propagation # self.var.setAttr("live_out") return decl(self.var, chain( assign(self.var, self.value.tolist()), _CodeSums(self.child(1), y, x))); else val := self.value; if IsBound(val.tolist) then if IsBound(val.range) and val.range() <> false then t := TArray(val.range(), val.domain()); val := t.value(val.tolist()); else val := V(val.tolist()); fi; else val := Cond(IsSPL(val), V(MatSPL(val)), val); fi; return data(self.var, val, _CodeSums(self.child(1), y, x)); fi; end; Diag.code := meth(self, y, x) local i, elt; i := Ind(); elt := self.element.lambda().at(i); return loop(i, self.element.domain(), assign(nth(y,i), elt * nth(x,i))); end; RCDiag.code := meth(self, y, x) local i, elt, re, im; i := Ind(); elt := self.element.lambda(); re := elt.at(2*i); im := elt.at(2*i+1); return loop(i, self.element.domain()/2, chain( assign(nth(y,2*i), re * nth(x,2*i) - im * nth(x,2*i+1)), assign(nth(y,2*i+1), im * nth(x,2*i) + re * nth(x,2*i+1)))); end; ColVec.code := meth(self, y, x) local i, datavar, diag, func; i := Ind(); func := self.element; if IsBound(self.inline) and self.inline then return loop(i, Rows(self), assign(nth(y,i), mul(func.lambda().at(i), nth(x,0)))); else diag := V(func.lambda().tolist()); datavar := Dat(diag.t); return data(datavar, diag, loop(i, Rows(self), assign(nth(y,i), mul(nth(datavar,i), nth(x,0))))); fi; end; RowVec.code := meth(self, y, x) local i, datavar, diag, func, t; i := Ind(); t := TempVar(x.t.t); func := self.element; if IsBound(self.inline) and self.inline then return chain( assign(t,0), loop(i, Cols(self), assign(t, add(t, mul(func.lambda().at(i), nth(x,i))))), assign(nth(y,0), t)); else diag := V(func.lambda().tolist()); datavar := Dat(diag.t); return data(datavar, diag, chain( assign(t,0), loop(i, Cols(self), assign(t, add(t, mul(nth(datavar,i), nth(x,i))))), assign(nth(y,0), t))); fi; end; Scale.code := (self, y, x) >> let(i := Ind(), chain( _CodeSums(self.child(1), y, x), loop(i, Rows(self), assign(nth(y,i), mul(self.scalar, nth(y,i)))))); I.code := (self, y, x) >> let(i := Ind(), loop(i, Rows(self), assign(nth(y,i), nth(x,i)))); Blk2code := (blk, y, x) -> let(b := V(blk.element).v, t0 := TempVar(x.t.t), t1 := TempVar(x.t.t), decl([t0, t1], chain( assign(t0, mul(b[1].v[1], nth(x,0)) + mul(b[1].v[2], nth(x,1))), assign(t1, mul(b[2].v[1], nth(x,0)) + mul(b[2].v[2], nth(x,1))), assign(nth(y,0), t0), assign(nth(y,1), t1) ))); Blk4code := (blk, y, x) -> let(b := V(blk.element).v, t0 := TempVar(x.t.t), t1 := TempVar(x.t.t), t2 := TempVar(x.t.t), t3 := TempVar(x.t.t), x0 := TempVar(x.t.t), x1 := TempVar(x.t.t), x2 := TempVar(x.t.t), x3 := TempVar(x.t.t), decl([x0,x1,x2,x3, t0, t1, t2, t3], chain( assign(x0, nth(x,0)), assign(x1, nth(x,1)), assign(x2, nth(x,2)), assign(x3, nth(x,3)), assign(t0, mul(b[1].v[1], x0) + mul(b[1].v[2], x1) + mul(b[1].v[3], x2) + mul(b[1].v[4], x3)), assign(t1, mul(b[2].v[1], x0) + mul(b[2].v[2], x1) + mul(b[2].v[3], x2) + mul(b[2].v[4], x3)), assign(t2, mul(b[3].v[1], x0) + mul(b[3].v[2], x1) + mul(b[3].v[3], x2) + mul(b[3].v[4], x3)), assign(t3, mul(b[4].v[1], x0) + mul(b[4].v[2], x1) + mul(b[4].v[3], x2) + mul(b[4].v[4], x3)), assign(nth(y,0), t0), assign(nth(y,1), t1), assign(nth(y,2), t2), assign(nth(y,3), t3) ))); Blk.code := meth(self, y, x) local i, j, t, datavar, matval; if Rows(self)=2 and Cols(self)=2 then return Blk2code(self, y, x); fi; if Rows(self)=4 and Cols(self)=4 then return Blk4code(self, y, x); fi; j := Ind(); i := Ind(); t := TempVar(x.t.t); matval := V(self.element); datavar := Dat(matval.t); return data(datavar, matval, loop(j, Rows(self), decl(t, chain( assign(t, 0), loop(i, Cols(self), assign(t, add(t, mul(nth(nth(datavar, j), i), nth(x, i))))), assign(nth(y,j), t))))); end; toeplitz.code := meth(self, y, x) local i, j, t, datavar, matval, dataload; j := Ind(); i := Ind(); t := TempVar(x.t.t); matval := V(self.obj.element); datavar := Dat(matval.t); dataload := TempVec(TArray(TDouble, Rows(self)*Cols(self))); return data(datavar, matval, decl(dataload, chain( loop(j, Rows(self), loop(i, Cols(self), assign(nth(dataload, j*Cols(self)+i), nth(nth(datavar,j),i)))), loop(j, Rows(self), decl(t, chain( assign(t, 0), loop(i, Cols(self), assign(t, add(t, mul(nth(dataload, j*Cols(self)+i), nth(x, i))))), assign(nth(y,j), t))))))); end; Blk1.code := (self, y, x) >> assign(nth(y,0), mul(toExpArg(self.element), nth(x,0))); BlkConj.code := (self, y, x) >> assign(nth(y,0), conj(nth(x,0))); Prm.code := (self, y, x) >> let(i := Ind(), func := self.func.lambda(), loop(i, Rows(self), assign(nth(y, i), nth(x, func.at(i))))); Z.code := (self, y, x) >> let(i := Ind(), ii := Ind(), z := self.params[2], chain( loop(i, Rows(self)-z, assign(nth(y, i), nth(x, i+z))), loop(i, z, assign(nth(y, i+(Rows(self)-z)), nth(x, i))))); O.code := (self, y, x) >> let(i := Ind(), loop(i, self.params[1], assign(nth(y, i), V(0)))); Gath.code := meth(self, y, x) local i, func, rfunc, ix; i := Ind(); func := self.func.lambda(); if IsBound(self.func.rlambda) then rfunc := self.func.rlambda(); ix := var.fresh_t("ix", TInt); return chain( assign(ix, func.at(0)), assign(nth(y, 0), nth(x, ix)), loop(i, self.func.domain()-1, chain(assign(ix, rfunc.at(ix)), assign(nth(y, i+1), nth(x, ix))))); else return loop(i, self.func.domain(), assign(nth(y,i), nth(x, func.at(i)))); fi; end; Scat.code := meth(self, y, x) local i, func, rfunc, ix; i := Ind(); func := self.func.lambda(); if IsBound(self.func.rlambda) then rfunc := self.func.rlambda(); ix := var.fresh_t("ix", TInt); return chain( assign(ix, func.at(0)), assign(nth(y, ix), nth(x, 0)), loop(i, self.func.domain()-1, chain(assign(ix, rfunc.at(ix)), assign(nth(y, ix), nth(x, i+1))))); else return loop(i, self.func.domain(), assign(nth(y,func.at(i)), nth(x, i))); fi; end; SUM.code := (self, y, x) >> chain(List(self.children(), c -> _CodeSums(c, y, x))); SUMAcc.code := (self, y, x) >> let(ii := Ind(), When(not Same(ObjId(self.child(1)), Gath), # NOTE: come up with a general condition chain( loop(ii, Rows(self), assign(nth(y, ii), V(0))), List(self.children(), c -> _CodeSumsAcc(c, y, x))), chain( _CodeSums(self.child(1), y, x), List(Drop(self.children(), 1), c -> _CodeSumsAcc(c, y, x))))); ISum.code := (self, y, x) >> let(myloop := When(IsSymbolic(self.domain), loopn, loop), myloop(self.var, self.domain, _CodeSums(self.child(1), y, x))); ISumAcc.code := (self, y, x) >> let(ii := Ind(), chain( loop(ii, Rows(self), assign(nth(y, ii), V(0))), loop(self.var, self.domain, _CodeSumsAcc(self.child(1), y, x)))); Compose.code := meth(self,y,x) local ch, numch, vecs, allow, i; #VIENNA filtering DMPGath, DMPScat out here because they do not generate code # ch := self.children(); ch := Filtered(self.children(), i-> not i.name in ["DMPGath","DMPScat"]); numch := Length(ch); vecs := [y]; allow := (x<>y); for i in [1..numch-1] do if allow and ObjId(ch[i])=Inplace then vecs[i+1] := vecs[i]; else vecs[i+1] := TempVec(TArray(TempArrayType(y, x), Cols(ch[i]))); fi; od; vecs[numch+1] := x; for i in Reversed([1..numch]) do if allow and ObjId(ch[i])=Inplace then vecs[i] := vecs[i+1]; fi; od; #Print(vecs, "\n"); if vecs[1] = vecs[numch+1] then # everything was inplace vecs[1] := y; fi; if vecs[1] = vecs[numch+1] then # everything was inplace vecs[numch+1] := x; fi; #Print(vecs, "\n"); vecs := Reversed(vecs); ch := Reversed(ch); return decl( Difference(vecs{[2..Length(vecs)-1]}, [x,y]), chain( List([1..numch], i -> When(vecs[i+1]=vecs[i], compiler._IPCodeSums(ch[i], vecs[i]), _CodeSums(ch[i], vecs[i+1], vecs[i]))))); end; ICompose.code := (self, y, x) >> #DoneSpiralHelp - How to make this work for any datatype (var t) #Look into Compose.code for tempvec chain([let( t := Dat1d(x.t.t, Rows(self)), newind := Ind(self.domain), decl([t], chain( When(IsOddInt(self.domain), SubstVars(Copy(_CodeSums(self.child(1), y, x)), tab((self.var.id) := (V(0)))), skip() ), When(IsEvenInt(self.domain), chain( SubstVars(Copy(_CodeSums(self.child(1), t, x)), tab((self.var.id) := (V(0)))), SubstVars(Copy(_CodeSums(self.child(1), y, t)), tab((self.var.id) := (V(1)))) ), skip() ), loop(newind, (self.domain/2), chain([ SubstVars(Copy(_CodeSums(self.child(1), x, y)), tab((self.var.id) := (2*newind)+2)), SubstVars(Copy(_CodeSums(self.child(1), y, x)), tab((self.var.id) := (2*newind)+3)) ]) ) )) )]);
Formal statement is: lemma bounded_linear_cnj: "bounded_linear cnj" Informal statement is: The complex conjugation map is a bounded linear operator.
```python import numpy as np import sympy as sym import pydae.build as db ``` ```python params_dict = {'R_w':0.316,'G':9.81,'M':1200.0,'K_w':1.0,'C_rr':0.03,'Rho':1.225,'S_f':2.13,'C_x':0.32,'K_sign':100} u_ini_dict = {'tau_r':0.0,'beta':0.0} # for the initialization problem u_run_dict = {'tau_r':0.0,'beta':0.0} # for the running problem (here initialization and running problem are the same) x_list = ['nu','x_pos'] # [inductor current, PI integrator] y_ini_list = ['omega_r','snu'] # for the initialization problem y_run_list = ['omega_r','snu'] # for the running problem (here initialization and running problem are the same) sys_vars = {'params':params_dict, 'u_list':u_run_dict, 'x_list':x_list, 'y_list':y_run_list} exec(db.sym_gen_str()) # exec to generate the required symbolic varables and constants ``` ```python tau_w = tau_r/K_w f_w = tau_w/R_w f_b = G*M*sym.sin(beta) f_d = 0.5*Rho*S_f*C_x*nu**2*snu f_r = C_rr*G*M*snu p_r = tau_r*omega_r eq_snu = -snu + (1/(1+sym.exp(-nu*K_sign)))*2-1 eq_omega_r =-omega_r + nu/(K_w*R_w) dnu = 1/M*(f_w - f_d - f_r - f_b) dx_pos = nu ``` ```python f_list = [dnu,dx_pos] g_list = [eq_snu,eq_omega_r] h_dict = {'f_w':f_w,'f_d':f_d,'f_r':f_r,'tau_r':tau_r,'p_r':p_r} sys = {'name':f"mech", 'params_dict':params_dict, 'f_list':f_list, 'g_list':g_list, 'x_list':x_list, 'y_ini_list':y_list, 'y_run_list':y_list, 'u_run_dict':u_run_dict, 'u_ini_dict':u_ini_dict, 'h_dict':h_dict } sys = db.system(sys) db.sys2num(sys) ``` ```python eq_snu ``` $\displaystyle - snu - 1 + \frac{2}{1 + e^{- K_{sign} \nu}}$ ```python ```
% Finite phase difference and Kay frequency estimation % % Estimates the instantaneous frequency of the input signal using % General Phase Difference (FFD, CFD, 4th, 6th) and Kay Frequency % Estimation % % Usage: % % ife = pde( signal, order [, window_length]); % % Inputs % % signal % % Input one dimensional signal to be analysed. % % order % % Order of the finite phase difference estimator. Available % estimator orders are: 1, 2, 4, 6. % % window_length % % Kay smoothing window length in the case of weighted phase % difference estimator. NB Set order = 1 for Kay's method. % % % For General Phase Difference: % % window_length:0; % order:1, 2, 4 or 6; % % e.g. ife = pdeIF( signal, order); % % for Kay smoothing weighted phase difference: % % window_length: desired window length; % order=1; % % e.g. ife = pde( signal, 0, window_length ); % % % TFSAP 7.0 % Copyright Prof. B. Boashash % Qatar University, Doha % email: [email protected]
/*gcc poisson.c /usr/lib/libgsl.a /usr/lib/libm.a -o poisson.exe */ #include <stdio.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> #include <math.h> int main (int argc, char *argv[]) { if(argc < 2){ printf("print probability of obtaining N from poisson distribution\n"); printf("usage: poisson.exe mean N\n"); return 1; } const gsl_rng_type * T; gsl_rng * r; int billion = 1000000000; int i, n = billion; double mean = atof(argv[1]); unsigned int found = atoi(argv[2]); double prob = gsl_ran_poisson_pdf(found,mean); printf("probability %f of getting %d from mean %f\n",prob,found,mean); double totalprob = 0.0; for(i=0; i<found; i++){ totalprob += gsl_ran_poisson_pdf(i,mean); } printf("probability %f of getting < %d from mean %f\n", totalprob,found,mean); printf("probability %f of getting >= %d from mean %f\n", 1.0-totalprob,found,mean); /* gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); for (i = 0; i < n; i++) { double u = gsl_rng_uniform (r); if(i > billion-5) printf("%.5f\n", u); } gsl_rng_free (r); */ return 0; }
using NeuralQuantum using Test using NeuralQuantum: LdagLSparseSuperopProblem, LRhoSparseOpProblem, LRhoKLocalOpProblem Nsites = 4 T = Float64 lind = quantum_ising_lind(SquareLattice([Nsites],PBC=true), g=1.3, V=2.0, γ=1.0) function test_ldagl_op(T, Nsites, net, lind) prob = LRhoSparseOpProblem(T, lind); probL = LRhoKLocalOpProblem(T, lind); v = state(prob, net) vL = state(probL, net) L=liouvillian(lind) LdagL = L.data'*L.data rho = dm(net, prob, false).data rhov = vec(rho) Clocs_ex = abs.((L.data*rhov)./rhov).^2 ic = NeuralQuantum.MCMCSRLEvaluationCache(net, prob); zero!(ic) icL_fb = NeuralQuantum.MCMCSRLEvaluationCache(net, prob); zero!(icL_fb) icL = NeuralQuantum.MCMCSRLEvaluationCache(net, probL); zero!(icL) for i=1:spacedimension(v) set_index!(v, i) set_index!(vL, i) NeuralQuantum.sample_network!(ic, prob, net, v); NeuralQuantum.sample_network!(icL_fb, probL, net, v); NeuralQuantum.sample_network!(icL, probL, net, vL); end SREval = EvaluatedNetwork(SR(), net) SREvalL = EvaluatedNetwork(SR(), net) SREvalL_fb = EvaluatedNetwork(SR(), net) evaluation_post_sampling!(SREval, ic) evaluation_post_sampling!(SREvalL, icL) evaluation_post_sampling!(SREvalL_fb, icL_fb) @test Clocs_ex ≈ ic.Evalues @testset "LookUp table evaluation" begin @test Clocs_ex ≈ icL.Evalues @test SREval.L ≈ SREvalL.L @test ic.Evalues ≈ icL.Evalues @test all([l≈r for (l,r)=zip(SREval.F, SREvalL.F)]) @test all([l≈r for (l,r)=zip(SREval.S, SREvalL.S)]) end @testset "Fallback (no LUT)" begin @test Clocs_ex ≈ icL_fb.Evalues @test SREval.L ≈ SREvalL_fb.L @test ic.Evalues ≈ icL_fb.Evalues @test all([l≈r for (l,r)=zip(SREval.F, SREvalL_fb.F)]) @test all([l≈r for (l,r)=zip(SREval.S, SREvalL_fb.S)]) end end @testset "LdagL (operator) problem" begin @testset "RBMSplit $netT" for netT=[T, Complex{T}] net = cached(RBMSplit(netT, Nsites, 2)) test_ldagl_op(T, Nsites, net, lind) end @testset "NDM $T" for T=[T] net = cached(NDM(T, Nsites, 2, 1)) test_ldagl_op(T, Nsites, net, lind) end end
# Copyright (c) 2018-2021, Carnegie Mellon University # See LICENSE for details rSetChildFields := arg -> Checked(IsList(arg), Subst( meth(self, n, newChild) if not n in [1..numfields] then Error("<n> must be in ", [1..numfields]); else self.(RecName(fields[n])) := newChild; fi; end, numfields => Length(arg), fields => arg) ); rSetChildFieldsCh := arg -> Checked(IsList(arg), Subst( meth(self, n, newChild) if not n in [1..chCount+numfields] then Error("<n> must be in ", [1..chCount+numfields]); elif n in [1..chCount] then self._children[n] := newChild; else self.(RecName(fields[n-chCount])) := newChild; fi; end, numfields => Length(arg)-1, chCount => arg[1], fields => Drop(arg, 1)) ); # rChildrenFieldsCh: gives rChildren method where rChildren is self.children() :: [self.field1, self.field2, ... ], # arg[1] is "field1", arg[2] is "field2" etc. # ex: rChildren := rChildrenFieldsCh("stride", "v") # rChildrenFieldsCh := arg -> Checked(IsList(arg), Subst( (self) >> self._children :: List([1..numfields], i -> self.(RecName(fields[i]))), numfields => Length(arg), fields => arg ) ); rSetChildFieldsF := arg -> Checked(IsList(arg), Length(arg)>1, Subst( meth(self, n, newChild) if not n in [1..numfields] then Error("<n> must be in ", [1..numfields]); else self.(RecName(fields[n])) := func(newChild); fi; end, numfields => Length(arg)-1, fields => Drop(arg, 1), func => arg[1]) ); Local._print := function(arg) local a; for a in arg do if IsRec(a) and IsBound(a.__bases__) then Print(a.__bases__[1]); else Print(a); fi; od; end; Local._children := function(obj) if IsRec(obj) then if not IsBound(obj.rChildren) then return []; else return obj.rChildren(); fi; elif BagType(obj) in [T_STRING, T_RANGE] then return []; elif IsList(obj) then return obj; else return []; fi; end; Local._setChild := function(obj, n, newchild) if IsRec(obj) then if not IsBound(obj.rSetChild) then Error("<obj> must have rSetChild(<n>, <newChild>) method"); fi; obj.rSetChild(n, newchild); elif IsList(obj) then obj[n] := newchild; else Error("<obj> must be a record or a list"); fi; end; Local._fromChildren := function(obj, newchildren) if IsRec(obj) then if not IsBound(obj.from_rChildren) then Error("<obj> must have from_rChildren(<newChildren>) method"); fi; return obj.from_rChildren(newchildren); elif BagType(obj) in [T_STRING, T_RANGE] then return obj; elif IsList(obj) then return newchildren; elif newchildren=[] then return obj; else return Error("<obj> must be a record or a list"); fi; end; _PrintShape := function(obj, maxDepth, printCutoff, info, i, is) if maxDepth > 0 then Print(Blanks(i)); _print(obj, " ", info(obj), "\n"); DoForAll(_children(obj), c -> _PrintShape(c, maxDepth-1, printCutoff, info, i+is, is)); elif printCutoff then Print(Blanks(i)); Print("...\n"); fi; end; PrintShape := (obj, maxDepth) -> Checked(IsInt(maxDepth) and maxDepth >= 0, _PrintShape(obj, maxDepth, true, x->"", 0, 4)); # info is a function : obj -> what to print PrintShapeInfo := (obj, maxDepth, info) -> Checked(IsInt(maxDepth) and maxDepth >= 0, _PrintShape(obj, maxDepth, true, info, 0, 4)); PrintShape2 := (obj, maxDepth) -> Checked(IsInt(maxDepth) and maxDepth >= 0, _PrintShape(obj, maxDepth, false, x->"", 0, 4)); Local.id := ObjId; # ObjId now handles lists #F ShapeObject(<obj>) #F Convert an object to a list-based pattern, #F i.e. add(X, Y) becomes [add, var, var] #F ShapeObject := obj -> Cond( BagType(obj) in [T_STRING,T_RANGE], obj, IsRec(obj) or IsList(obj), let( res := Concatenation([ObjId(obj)], List(_children(obj), ShapeObject)), When(Length(res)=1, res[1], res)), obj ); #F ShapeObject@(<obj>, <func>) #F #F Same as ShapeObject(obj) but takes a boolean function <func>, and objects #F for which <func> returns true are replaced by @. #F ShapeObject@ := (obj, func_replace_by_wildcard) -> Cond( BagType(obj) in [T_STRING,T_RANGE], obj, func_replace_by_wildcard(obj), @, IsRec(obj) or IsList(obj), let( res := Concatenation([ObjId(obj)], List(_children(obj), x -> ShapeObject@(x, func_replace_by_wildcard))), When(Length(res)=1, res[1], res)), obj ); Class(..., rec( left := false, right := false )); Left := z -> z.left; Right := z -> z.right; # @ : basic pattern object # .parent is the pointer to the unique object in @.table # That table does not store any precondition functions # Class(@, rec( is@ := true, table := WeakRef(tab()), __call__ := meth(arg) local res, self, num, target, precond; if Length(arg) < 2 or Length(arg) > 4 then Error("Usage: @(<num>, [<target>], [<cond>])"); fi; self := arg[1]; num := arg[2]; if Length(arg) >= 3 then target := arg[3]; fi; if Length(arg) = 4 then precond := arg[4]; fi; if not IsBound(self.table.(num)) then res := self.new(num); self.table.(num) := res; if IsBound(target) then res := res.target(target); fi; if IsBound(precond) then res := res.cond(precond); fi; return res; else res := self.table.(num); Unbind(res._target); Unbind(res._precond); if IsBound(target) then res := res.target(target); fi; if IsBound(precond) then res := res.cond(precond); fi; return res; fi; end, new := (self, num) >> CantCopy( WithBases(self, rec(num := num, operations := PrintOps))), match := meth(self, obj, cx) if (not IsBound(self._target) or ObjId(obj) in self._target) and (not IsBound(self._precond) or self._precond(obj)) then if IsBound(self.parent) then self.parent.val := obj; else self.val := obj; fi; return true; else return false; fi; end, cond := (self, precond_func) >> Checked(IsCallableN(precond_func, 1), CantCopy( WithBases(self, rec(_precond := precond_func, parent := When(IsBound(self.parent), self.parent, self))))), target := (self, target_id) >> CantCopy( WithBases(self, rec(#_taddr := When(IsList(target_id), List(target_id,BagAddr), [BagAddr(target_id)]), _target := When(IsList(target_id), target_id, [target_id]), parent := When(IsBound(self.parent), self.parent, self)))), val := false, print := self >> Print("@(", self.num, ")", When(IsBound(self._target), Print(".target(", self._target, ")"), ""), When(IsBound(self._precond), Print(".cond(", self._precond, ")"), "")), clear := meth(self) local e, l; l := TabToList(self.table); for e in l do if IsRec(e) and IsBound(e.val) then e.val := false; fi; od; if IsBound(self.val) then self.val := false; fi; end )); # @@ : basic pattern object for context sensitive matching # @@ has its own table. # It still uses a .parent to point into @@.table where matches are stored # That table does not store any precondition functions. # Both lhs and rhs of rewrite rules must use either @ or @@. Otherwise wrong # table will be used. Class(@@, @, rec( table := WeakRef(tab()), match := meth(self, obj, cx) local base_match; base_match := @.match; if not IsBound(self._cxcond) then return base_match(self, obj, cx); else return base_match(self, obj, cx) and self._cxcond(obj, cx); fi; end, cond := (self, cxcond_func) >> CantCopy(Checked(IsCallableN(cxcond_func, 2), WithBases(self, rec(_cxcond := cxcond_func, parent := When(IsBound(self.parent), self.parent, self))))), print := self >> Print("@@(", self.num, ")", When(IsBound(self._target), Print(".target(", self._target, ")"), ""), When(IsBound(self._cxcond), Print(".cond(", self._cxcond, ")"), "")) )); Is@ := x -> IsRec(x) and IsBound(x.is@) and x.is@; Local._midmatch := arg->false; Local._normalmatch := arg->false; Local._match_id := (obj, shape, cx) -> Cond( IsRec(shape) and IsBound(shape.is@), shape.match(obj, cx), BagType(shape) < T_FUNCTION or BagType(shape) in [T_STRING,T_RANGE], BagType(shape) = BagType(obj) and shape=obj, Same(obj, shape) or Same(ObjId(obj), shape)); ## Declare(cx_enter, cx_leave, empty_cx, apply_rules_ni, _SubstBottomUp, _SubstTopDown); ## # PatternMatch(<obj>, <shape>, <cx>) # Returns true if <obj> matches the given <shape> in a given context <cx>. # For plain matches use empty context table empty_cx(). # PatternMatch := function(obj, shape, cx) local ch, numch, shlen, res; if not IsList(shape) or BagType(shape) in [T_STRING,T_RANGE] then return _match_id(obj, shape, cx); elif shape = [] then return false; elif not _match_id(obj, shape[1], cx) then return false; else shlen := Length(shape); ch := _children(obj); numch := Length(ch); if shlen = 1 then return numch = 0; else cx_enter(cx, obj); if shape[2] = ... then if shape[shlen] = ... then res := _midmatch(ch, shape{[3..shlen-1]}, cx); elif numch < shlen-2 then res := false; else ....left := numch-shlen+2; ....right := numch+1; res := _normalmatch(ch, numch-shlen+3, shlen-2, shape, 3, shlen-2, cx); fi; elif Last(shape) = ... then if numch < shlen-2 then res := false; else ....left := 0; ....right := shlen-1; res := _normalmatch(ch, 1, shlen-2, shape, 2, shlen-2, cx); fi; else ....left := false; ....right := false; res := _normalmatch(ch, 1, numch, shape, 2, shlen-1, cx); fi; cx_leave(cx, obj); return res; fi; fi; end; _normalmatch := function(lst, lstart, llen, shape, sstart, slen, cx) local i, ch; if llen <> slen then return false; else for i in [0..slen-1] do if not PatternMatch(lst[lstart+i], shape[sstart+i], cx) then return false; fi; od; return true; fi; end; _midmatch := function(lst, shape, cx) local i, ch, shlen, res, llen; shlen := Length(shape); llen := Length(lst); if llen < shlen then return false; elif llen = shlen then res := _normalmatch(lst, 1, llen, shape, 1, shlen, cx); if res then ....left := 0; ....right := llen + 1; fi; return res; else for i in [1 .. llen - shlen + 1] do if PatternMatch(lst[i], shape[1], cx) then if shlen = 1 then ....left := i-1; ....right := i+shlen; return true; else if _normalmatch(lst, i+1, shlen-1, shape, 2, shlen-1, cx) then ....left := i-1; ....right := i+shlen; return true; fi; fi; fi; od; return false; fi; end; #F AlternativesRewrite( <expr>, <from>, <to_func> ) #F #F Creates all alternatives for substitution of an expression tree. #F <expr> - expression to substitute in #F <from> - shape to substitute #F <to_func> - a substitution function of the form e->f(e), where #F as <e> will be passed the subtree matching <from> #F Declare(_AlternativesRewrite, _ConditionalAlternativesRewrite); AlternativesRewrite := (expr, from, to_func) -> _AlternativesRewrite(expr, from, to_func, empty_cx(), []); _AlternativesRewrite := function(expr, from, to_func, cx, list) local ch, i, clist; ch := _children(expr); if Length(ch) <> 0 then # not a leaf cx_enter(cx, expr); for i in [1..Length(ch)] do clist := _AlternativesRewrite(ch[i], from, to_func, cx, []); Append(list, List(clist, function(x) local a; a:=Copy(expr); _setChild(a, i, x); return a; end)); od; cx_leave(cx, expr); fi; if PatternMatch(expr, from, cx) then Add(list, When(NumArgs(to_func)=2, to_func(cx, expr), to_func(expr))); fi; return list; end; ConditionalAlternativesRewrite := (expr, from, condition_to_func, rewrite_to_func) -> _ConditionalAlternativesRewrite(expr, from, condition_to_func, rewrite_to_func, empty_cx(), []); _ConditionalAlternativesRewrite := function(expr, from, condition_to_func, rewrite_to_func, cx, list) local ch, i, clist; ch := _children(expr); if Length(ch) <> 0 then # not a leaf cx_enter(cx, expr); for i in [1..Length(ch)] do clist := _ConditionalAlternativesRewrite(ch[i], from, condition_to_func, rewrite_to_func, cx, []); Append(list, List(clist, function(x) local a; a:=Copy(expr); _setChild(a, i, x[2]); return [x[1], a]; end)); od; cx_leave(cx, expr); fi; if PatternMatch(expr, from, cx) then Add(list, [When(NumArgs(condition_to_func)=2, condition_to_func(cx, expr), condition_to_func(expr)), When(NumArgs(rewrite_to_func)=2, rewrite_to_func(cx, expr), rewrite_to_func(expr))]); fi; return list; end; # Return a list of rewrite rule objects, from either a list of a record # passing in a record has the advantage of clean rule naming # _parseRuleSet := rset -> Cond( IsList(rset), List(rset, Rule), IsRec(rset), List(UserRecFields(rset), function(fld) local r; r := Rule(rset.(fld)); r.name := fld; return r; end), Error("<rset> must be a list of rules, or a record rec(rule1 := Rule(...), ...)") ); #F SubstBottomUp( <expr>, <from>, <to_func> ) #F #F Destructive bottom up substitution on an expression tree. #F <expr> - expression to substitute in #F <from> - shape to substitute #F <to_func> - a substitution function of the form e->f(e), where #F as <e> will be passed the subtree matching <from> #F SubstBottomUp := (expr, from, to_func) -> _SubstBottomUp(expr, [ Rule(from, to_func, "unnamed(SubstBottomUp)") ], empty_cx()); SubstBottomUpRules := (expr, ruleset) -> _SubstBottomUp(expr, _parseRuleSet(ruleset), empty_cx()); _SubstBottomUp := function(expr, rules, cx) local ch, i; ch := _children(expr); if ch <> [] then cx_enter(cx, expr); for i in [1..Length(ch)] do _setChild(expr, i, _SubstBottomUp(ch[i], rules, cx)); od; cx_leave(cx, expr); fi; return apply_rules_ni(rules, expr, cx); end; _SubstLeaves := function(expr, from, to_func, cx) local ch, i; ch := _children(expr); if Length(ch) <> 0 then # not a leaf cx_enter(cx, expr); for i in [1..Length(ch)] do _setChild(expr, i, _SubstLeaves(ch[i], from, to_func, cx)); od; cx_leave(cx, expr); return expr; else # a leaf if PatternMatch(expr, from, cx) then return When(NumArgs(to_func)=2, to_func(cx, expr), to_func(expr)); else return expr; fi; fi; end; SubstLeaves := (expr, from, to_func) -> _SubstLeaves(expr, from, to_func, empty_cx()); SubstChildren := function(expr, from, to_func) local ch, i; ch := _children(expr); #expr := map_children_safe(expr, c -> When(PatternMatch(c,from,empty_cx()), to_func(c), c)); for i in [1..Length(ch)] do _setChild(expr, i, When(PatternMatch(ch[i],from,empty_cx()), to_func(ch[i]), ch[i])); od; return expr; end; SubstTopDown := (expr, from, to_func) -> _SubstTopDown(expr, [ Rule(from, to_func, "unnamed(SubstTopDown)") ], empty_cx()); SubstTopDown_named := (expr, from, to_func, name) -> _SubstTopDown(expr, [ Rule(from, to_func, name) ], empty_cx()); SubstTopDownRules := (expr, ruleset) -> _SubstTopDown(expr, _parseRuleSet(ruleset), empty_cx()); _SubstTopDown := function(expr, rules, cx) local ch, newch, res; expr := apply_rules_ni(rules, expr, cx); ch := _children(expr); if ch <> [] then cx_enter(cx, expr); newch := List(ch, c -> _SubstTopDown(c, rules, cx)); res := _fromChildren(expr, newch); cx_leave(cx, expr); else res := expr; fi; return res; end; Declare(_SubstTopDownNR); # same as SubstTopDown but doesn't recurse on the substitution SubstTopDownNR := (expr, from, to_func) -> _SubstTopDownNR(expr, [ Rule(from, to_func, "unnamed(SubstTopDownNR)") ], empty_cx()); SubstTopDownNR_named := (expr, from, to_func, name) -> _SubstTopDownNR(expr, [ Rule(from, to_func, name) ], empty_cx()); SubstTopDownRulesNR := (expr, ruleset) -> _SubstTopDownNR(expr, _parseRuleSet(ruleset), empty_cx()); _SubstTopDownNR := function(expr, rules, cx) local ch, newch, res, n_applied; n_applied := cx.applied; cx.rlimit := 1; expr := apply_rules_ni(rules, expr, cx); if cx.applied > n_applied then return expr; fi; ch := _children(expr); if ch <> [] then cx_enter(cx, expr); newch := List(ch, c -> _SubstTopDownNR(c, rules, cx)); res := _fromChildren(expr, newch); cx_leave(cx, expr); else res := expr; fi; return res; end; #F MatchSubst(<expr>, <rulelist>) #F #F Attempts matching 1 of the rules from the list to <expr> if it #F succeeds the transformation is applied, otherwise original #F expression is returned. #F #F MatchSubst is similar to SubstTopDown, but it does not recurse #F on children. #F MatchSubst := function(expr, rules) local ch, i, r, cx; cx := empty_cx(); for r in _parseRuleSet(rules) do if PatternMatch(expr, r.from, cx) then RuleTrace(r); return r.to(expr); fi; od; return expr; end; Declare(_Collect); #F Collect(<expr>, <shape>) #F #F Returns a list of all subtrees of <expr> that match <shape> #F Collect := (expr, shape) -> _Collect(expr, shape, empty_cx(), true); #F Contains(<expr>, <shape>) #F #F Returns 'true' if <expr> contains <shape> #F NOTE: optimize this Contains := (expr, shape) -> _Collect(expr, shape, empty_cx(), false)<>[]; #F CollectNR(<expr>, <shape>) #F #F Returns a list of all subtrees of <expr> that match <shape>. #F Unlike 'Collect', once 'CollectNR' finds an object matching <shape>, #F it does not search inside its children. #F CollectNR := (expr, shape) -> _Collect(expr, shape, empty_cx(), false); _Collect := function(expr, shape, cx, do_recurse) local res, ch, c; if PatternMatch(expr, shape, cx) then if not do_recurse then return [expr]; else cx_enter(cx, expr); res := Concatenation(List(_children(expr), c -> _Collect(c, shape, cx, do_recurse))); cx_leave(cx, expr); return Concatenation([expr], res); fi; else cx_enter(cx, expr); res := Concatenation(List(_children(expr), c -> _Collect(c, shape, cx, do_recurse))); cx_leave(cx, expr); return res; fi; end; Declare(_Pull); #F Pull(<expr>, <shape>, <to_func>, <pull_func>) #F #F Pull is a hybrid of Collect and SubstBottomUp. First three parameters #F specify substitution, and the last one collection: #F #F <expr> - expression to substitute in #F <from> - shape to substitute #F <to_func> - a substitution function of the form e->f(e), where #F as <e> will be passed the subtree matching <from> #F <pull_func> - applied to matching subtree <e> to collect data #F #F Pull retuns a tuple [<data>, <newtree>], where <data> is a list #F of all matched subtrees (before substitutions) with <pull_func> #F applied, and <newtree> is a tree obtained by substitution. #F ## Note: This is Top-down recursive Pull, same as PullTD Pull := (expr, shape, to_func, pull_func) -> _Pull(expr, shape, to_func, pull_func, empty_cx(), true, true); # Top-down recursive Pull PullTD := (expr, shape, to_func, pull_func) -> _Pull(expr, shape, to_func, pull_func, empty_cx(), true, true); # Bottom-up recursive Pull (non-recursive bottom up does not exist) PullBU := (expr, shape, to_func, pull_func) -> _Pull(expr, shape, to_func, pull_func, empty_cx(), true, false); # Top-down non-recursive Pull PullNR := (expr, shape, to_func, pull_func) -> _Pull(expr, shape, to_func, pull_func, empty_cx(), false, true); _Pull := function(expr, shape, to_func, pull_func, cx, do_recurse, top_down) local ch, i, t, data, newdata, newexpr; data := []; if top_down then if PatternMatch(expr, shape, cx) then Add(data, When(NumArgs(pull_func)=2, pull_func(cx, expr), pull_func(expr))); expr := When(NumArgs(to_func)=2, to_func(cx, expr), to_func(expr)); if not do_recurse then return [ data, expr ]; fi; fi; fi; cx_enter(cx, expr); ch := _children(expr); for i in [1..Length(ch)] do t := _Pull(ch[i], shape, to_func, pull_func, cx, do_recurse, top_down); Append(data, t[1]); _setChild(expr, i, t[2]); od; cx_leave(cx, expr); if not top_down then if PatternMatch(expr, shape, cx) then Add(data, When(NumArgs(pull_func)=2, pull_func(cx, expr), pull_func(expr))); expr := When(NumArgs(to_func)=2, to_func(cx, expr), to_func(expr)); if not do_recurse then return [ data, expr ]; fi; fi; fi; return [data, expr]; end; #F Harvest( <expr>, <shape-func-list> ) #F #F Harvest is a generalization of Collect( <expr>, <shape> ). #F It returns concatenated list of <func>(child) for all children #F of <expr> that match <shape>, for each <shape>-<func> pair. Harvest := function( expr, shape_func_list ) local res, sf, c; res := []; for sf in shape_func_list do Append(res, List(Collect(expr, sf[1]), sf[2])); od; return res; end; #F SubstObj(<expr>, <obj>, <new_obj> #F replacing all occurences of <obj> by <new_obj> SubstObj := (expr, obj, new_obj) -> SubstTopDownNR_named(expr, @.cond(x -> x=obj), e -> new_obj, "SubstObj");
(* Copyright (C) 2017 M.A.L. Marques This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: gga_exc *) (* prefix: gga_k_dk_params *params; assert(p->params != NULL); params = (gga_k_dk_params * )(p->params); *) dk_f := x -> add(params_a_aa[i]*x^(2*(i-1)), i=1..5) / add(params_a_bb[i]*x^(2*(i-1)), i=1..5): f := (rs, zeta, xt, xs0, xs1) -> gga_kinetic(dk_f, rs, zeta, xs0, xs1):
Require Import Arith. (* some useful bindings *) Definition peirce := forall P Q:Prop, ((P->Q)->P)->P. Definition classic := forall P:Prop, ~~P -> P. Definition lem := forall P:Prop, P \/ ~P. Definition and_to_or := forall P Q:Prop, ~(~P /\ ~Q) -> P \/ Q. Definition imp_to_or := forall P Q:Prop, (P -> Q) -> (~P \/ Q). Definition ex_to_all := forall (A:Type) (P: A -> Prop), ~(exists x:A, ~P x) -> (forall x:A, P x). Inductive isZero : nat -> Prop := | IsZero : isZero 0 . Inductive Even : nat -> Prop := | EvenO : Even 0 | EvenSS : forall (n:nat), Even n -> Even (S (S n)) . (* discriminate tactic*) Lemma true_neq_false1 : true <> false. Proof. intros H. discriminate. Qed. Definition toProp (b:bool) : Prop := if b then True else False. (* change tactic *) Lemma true_neq_false2 : true <> false. Proof. intros H. change (toProp false). rewrite <- H. simpl. exact I. Qed. (* congruence tactic *) Lemma true_neq_false3 : true <> false. Proof. congruence. Qed. (* injection tactic *) Lemma S_inj1 : forall (n m:nat), S n = S m -> n = m. Proof. intros n m H. injection H. intros. assumption. Qed. (* change tactic *) Lemma S_inj2 : forall (n m:nat), S n = S m -> n = m. Proof. intros n m H. change (pred (S n) = pred (S m)). rewrite H. reflexivity. Qed. (* apply tactic *) Lemma obvious1 : True. Proof. apply I. Qed. (* constructor tactic *) Lemma obvious2 : True. Proof. constructor. Qed. (* destruct tactic *) Lemma False_imp1: False -> 2 + 2 = 5. Proof. intros H. destruct H. Qed. (* exfalso tactic *) Lemma False_imp2: False -> 2 + 2 = 5. Proof. intros H. exfalso. assumption. Qed. (* discriminate tactic *) Lemma not1 : ~(2 + 2 = 5). Proof. intros H. discriminate H. Qed. Fixpoint even (n:nat) : bool := match n with | 0 => true | S p => negb (even p) end. (* change tactic *) Lemma not2 : ~(2 + 2 = 5). Proof. intros H. change (toProp (even 5)). rewrite <- H. simpl. apply I. Qed. (* split tactic *) Lemma and_comm1 : forall (A B:Prop), A /\ B -> B /\ A. Proof. intros A B [H1 H2]. split; assumption. Qed. (* left and right tactics *) Lemma or_comm1 : forall (A B:Prop), A \/ B -> B \/ A. Proof. intros A B [H1|H2]. - right. assumption. - left . assumption. Qed. (* tauto tactic *) Lemma and_comm2 : forall (A B:Prop), A /\ B -> B /\ A. Proof. tauto. Qed. (* tauto tactic *) Lemma or_comm2 : forall (A B:Prop), A \/ B -> B \/ A. Proof. tauto. Qed. (* exists tactic *) Lemma exist1 : exists (n:nat), n + 3 = 5. Proof. exists 2. reflexivity. Qed. (* firstorder tactic *) Lemma firstorder1 : forall (A:Type) (P: A->Prop), (forall x:A, P x) -> ~(exists x:A, ~P x). Proof. firstorder. Qed. (* intuition tactic *) Lemma intuition1 : peirce -> classic. Proof. unfold peirce. unfold classic. intuition. apply H with False. intros H1. exfalso. apply H0. assumption. Qed. (* firstorder tactic *) Lemma firstorder2 : peirce -> classic. Proof. unfold peirce. unfold classic. firstorder. apply H with False. intros H1. exfalso. apply H0. assumption. Qed. (* cut tactic *) Lemma cut1: 1 + 1 = 2. Proof. cut (2 + 2 = 4). - intros E. reflexivity. - reflexivity. Qed. (* assert tactic *) Lemma assert1: 1 + 1 = 2. Proof. assert (2 + 2 = 4) as E. - reflexivity. - reflexivity. Qed. (* remember tactic *) Lemma remember1 : 1 + 1 = 2. remember 1 as x eqn:E. rewrite E. reflexivity. Qed. (* inversion tactic *) Lemma not_isZero_1 : ~ isZero 1. Proof. intros H. inversion H. Qed. (* tactic auto *) Hint Constructors Even. Lemma Even_4 : Even 4. Proof. auto. Qed. (* tactic ring*) Lemma fact_basic: forall (n:nat), (S n) * fact n = fact (S n). Proof. induction n as [|n IH]. - reflexivity. - simpl. ring. Qed. (* refine tactic *) Definition refine_test : forall (n m:nat), {n = m} + {n <> m}. refine (fix f (n m:nat) : {n = m} + {n <> m} := match n,m with | 0,0 => left _ (* leaving a hole *) | S n, S m => if f n m then left _ else right _ (* two more holes *) | _, _ => right _ (* one last hole *) end). (* getting 5 goals though, not four, probably a good reason to this *) (* could factorize with a single 'congruence' *) - reflexivity. - congruence. - congruence. - congruence. - congruence. Defined. (* rather than 'Qed' so proof term is not opaque *) (* decide tactic *) Definition decide_test : forall (n m:nat), {n = m} + {n <> m}. decide equality. Defined. (* Print decide_test. *)
//================================================================================================== /** Copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) **/ //================================================================================================== #ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_TOUINT_S_HPP_INCLUDED #define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_TOUINT_S_HPP_INCLUDED #include <boost/simd/detail/overload.hpp> #include <boost/simd/detail/traits.hpp> #include <boost/simd/constant/valmax.hpp> #include <boost/simd/function/bitwise_cast.hpp> #include <boost/simd/function/if_else.hpp> #include <boost/simd/function/if_zero_else.hpp> #include <boost/simd/function/is_greater_equal.hpp> #include <boost/simd/function/is_ngez.hpp> #include <boost/simd/function/saturate.hpp> #include <boost/simd/function/splat.hpp> #include <boost/simd/function/touint.hpp> #include <boost/simd/detail/dispatch/meta/as_integer.hpp> namespace boost { namespace simd { namespace ext { namespace bd = boost::dispatch; namespace bs = boost::simd; BOOST_DISPATCH_OVERLOAD_IF( touint_ , (typename A0, typename X) , (detail::is_native<X>) , bd::cpu_ , bs::saturated_tag , bs::pack_<bd::int_<A0>, X> ) { using result = bd::as_integer_t<A0, unsigned>; BOOST_FORCEINLINE result operator()(const saturated_tag &, A0 const& a0) const { return bitwise_cast<result>(saturate<result>(a0)); } }; BOOST_DISPATCH_OVERLOAD( touint_ , (typename A0, typename X) , bd::cpu_ , bs::saturated_tag , bs::pack_<bd::uint_<A0>, X> ) { BOOST_FORCEINLINE A0 operator()(const saturated_tag &, A0 const& a0) const { return a0; } }; BOOST_DISPATCH_OVERLOAD_IF( touint_ , (typename A0, typename X) , (detail::is_native<X>) , bd::cpu_ , bs::saturated_tag , bs::pack_<bd::floating_<A0>, X> ) { using result = bd::as_integer_t<A0, unsigned>; BOOST_FORCEINLINE result operator()(const saturated_tag &, const A0& a0) const BOOST_NOEXCEPT { using sr_t = bd::scalar_of_t<result>; static const A0 Vax = splat<A0>(bs::Valmax<sr_t>()); return if_zero_else(bs::is_ngez(a0), if_else(bs::is_greater_equal(a0, Vax), Valmax<result>(), touint(a0) ) ); } }; } } } #endif
(* Title: Jinja/J/WellType.thy Author: Tobias Nipkow Copyright 2003 Technische Universitaet Muenchen *) section \<open>Well-typedness of Jinja expressions\<close> theory WellType imports "../Common/Objects" Expr begin type_synonym env = "vname \<rightharpoonup> ty" inductive WT :: "[J_prog,env, expr , ty ] \<Rightarrow> bool" ("_,_ \<turnstile> _ :: _" [51,51,51]50) and WTs :: "[J_prog,env, expr list, ty list] \<Rightarrow> bool" ("_,_ \<turnstile> _ [::] _" [51,51,51]50) for P :: J_prog where WTNew: "is_class P C \<Longrightarrow> P,E \<turnstile> new C :: Class C" | WTCast: "\<lbrakk> P,E \<turnstile> e :: Class D; is_class P C; P \<turnstile> C \<preceq>\<^sup>* D \<or> P \<turnstile> D \<preceq>\<^sup>* C \<rbrakk> \<Longrightarrow> P,E \<turnstile> Cast C e :: Class C" | WTVal: "typeof v = Some T \<Longrightarrow> P,E \<turnstile> Val v :: T" | WTVar: "E V = Some T \<Longrightarrow> P,E \<turnstile> Var V :: T" (* WTBinOp: "\<lbrakk> P,E \<turnstile> e\<^sub>1 :: T\<^sub>1; P,E \<turnstile> e\<^sub>2 :: T\<^sub>2; case bop of Eq \<Rightarrow> (P \<turnstile> T\<^sub>1 \<le> T\<^sub>2 \<or> P \<turnstile> T\<^sub>2 \<le> T\<^sub>1) \<and> T = Boolean | Add \<Rightarrow> T\<^sub>1 = Integer \<and> T\<^sub>2 = Integer \<and> T = Integer \<rbrakk> \<Longrightarrow> P,E \<turnstile> e\<^sub>1 \<guillemotleft>bop\<guillemotright> e\<^sub>2 :: T" *) | WTBinOpEq: "\<lbrakk> P,E \<turnstile> e\<^sub>1 :: T\<^sub>1; P,E \<turnstile> e\<^sub>2 :: T\<^sub>2; P \<turnstile> T\<^sub>1 \<le> T\<^sub>2 \<or> P \<turnstile> T\<^sub>2 \<le> T\<^sub>1 \<rbrakk> \<Longrightarrow> P,E \<turnstile> e\<^sub>1 \<guillemotleft>Eq\<guillemotright> e\<^sub>2 :: Boolean" | WTBinOpAdd: "\<lbrakk> P,E \<turnstile> e\<^sub>1 :: Integer; P,E \<turnstile> e\<^sub>2 :: Integer \<rbrakk> \<Longrightarrow> P,E \<turnstile> e\<^sub>1 \<guillemotleft>Add\<guillemotright> e\<^sub>2 :: Integer" | WTLAss: "\<lbrakk> E V = Some T; P,E \<turnstile> e :: T'; P \<turnstile> T' \<le> T; V \<noteq> this \<rbrakk> \<Longrightarrow> P,E \<turnstile> V:=e :: Void" | WTFAcc: "\<lbrakk> P,E \<turnstile> e :: Class C; P \<turnstile> C sees F:T in D \<rbrakk> \<Longrightarrow> P,E \<turnstile> e\<bullet>F{D} :: T" | WTFAss: "\<lbrakk> P,E \<turnstile> e\<^sub>1 :: Class C; P \<turnstile> C sees F:T in D; P,E \<turnstile> e\<^sub>2 :: T'; P \<turnstile> T' \<le> T \<rbrakk> \<Longrightarrow> P,E \<turnstile> e\<^sub>1\<bullet>F{D}:=e\<^sub>2 :: Void" | WTCall: "\<lbrakk> P,E \<turnstile> e :: Class C; P \<turnstile> C sees M:Ts \<rightarrow> T = (pns,body) in D; P,E \<turnstile> es [::] Ts'; P \<turnstile> Ts' [\<le>] Ts \<rbrakk> \<Longrightarrow> P,E \<turnstile> e\<bullet>M(es) :: T" | WTBlock: "\<lbrakk> is_type P T; P,E(V \<mapsto> T) \<turnstile> e :: T' \<rbrakk> \<Longrightarrow> P,E \<turnstile> {V:T; e} :: T'" | WTSeq: "\<lbrakk> P,E \<turnstile> e\<^sub>1::T\<^sub>1; P,E \<turnstile> e\<^sub>2::T\<^sub>2 \<rbrakk> \<Longrightarrow> P,E \<turnstile> e\<^sub>1;;e\<^sub>2 :: T\<^sub>2" | WTCond: "\<lbrakk> P,E \<turnstile> e :: Boolean; P,E \<turnstile> e\<^sub>1::T\<^sub>1; P,E \<turnstile> e\<^sub>2::T\<^sub>2; P \<turnstile> T\<^sub>1 \<le> T\<^sub>2 \<or> P \<turnstile> T\<^sub>2 \<le> T\<^sub>1; P \<turnstile> T\<^sub>1 \<le> T\<^sub>2 \<longrightarrow> T = T\<^sub>2; P \<turnstile> T\<^sub>2 \<le> T\<^sub>1 \<longrightarrow> T = T\<^sub>1 \<rbrakk> \<Longrightarrow> P,E \<turnstile> if (e) e\<^sub>1 else e\<^sub>2 :: T" | WTWhile: "\<lbrakk> P,E \<turnstile> e :: Boolean; P,E \<turnstile> c::T \<rbrakk> \<Longrightarrow> P,E \<turnstile> while (e) c :: Void" | WTThrow: "P,E \<turnstile> e :: Class C \<Longrightarrow> P,E \<turnstile> throw e :: Void" | WTTry: "\<lbrakk> P,E \<turnstile> e\<^sub>1 :: T; P,E(V \<mapsto> Class C) \<turnstile> e\<^sub>2 :: T; is_class P C \<rbrakk> \<Longrightarrow> P,E \<turnstile> try e\<^sub>1 catch(C V) e\<^sub>2 :: T" \<comment> \<open>well-typed expression lists\<close> | WTNil: "P,E \<turnstile> [] [::] []" | WTCons: "\<lbrakk> P,E \<turnstile> e :: T; P,E \<turnstile> es [::] Ts \<rbrakk> \<Longrightarrow> P,E \<turnstile> e#es [::] T#Ts" (*<*) (* lemmas [intro!] = WTNew WTCast WTVal WTVar WTBinOp WTLAss WTFAcc WTFAss WTCall WTBlock WTSeq WTWhile WTThrow WTTry WTNil WTCons lemmas [intro] = WTCond1 WTCond2 *) declare WT_WTs.intros[intro!] (* WTNil[iff] *) lemmas WT_WTs_induct = WT_WTs.induct [split_format (complete)] and WT_WTs_inducts = WT_WTs.inducts [split_format (complete)] (*>*) lemma [iff]: "(P,E \<turnstile> e#es [::] T#Ts) = (P,E \<turnstile> e :: T \<and> P,E \<turnstile> es [::] Ts)" (*<*) apply(rule iffI) apply (auto elim: WTs.cases) done (*>*) lemma [iff]: "(P,E \<turnstile> (e#es) [::] Ts) = (\<exists>U Us. Ts = U#Us \<and> P,E \<turnstile> e :: U \<and> P,E \<turnstile> es [::] Us)" (*<*) apply(rule iffI) apply (auto elim: WTs.cases) done (*>*) lemma [iff]: "\<And>Ts. (P,E \<turnstile> es\<^sub>1 @ es\<^sub>2 [::] Ts) = (\<exists>Ts\<^sub>1 Ts\<^sub>2. Ts = Ts\<^sub>1 @ Ts\<^sub>2 \<and> P,E \<turnstile> es\<^sub>1 [::] Ts\<^sub>1 \<and> P,E \<turnstile> es\<^sub>2[::]Ts\<^sub>2)" (*<*) apply(induct es\<^sub>1 type:list) apply simp apply clarsimp apply(erule thin_rl) apply (rule iffI) apply clarsimp apply(rule exI)+ apply(rule conjI) prefer 2 apply blast apply simp apply fastforce done (*>*) lemma [iff]: "P,E \<turnstile> Val v :: T = (typeof v = Some T)" (*<*) apply(rule iffI) apply (auto elim: WT.cases) done (*>*) lemma [iff]: "P,E \<turnstile> Var V :: T = (E V = Some T)" (*<*) apply(rule iffI) apply (auto elim: WT.cases) done (*>*) lemma [iff]: "P,E \<turnstile> e\<^sub>1;;e\<^sub>2 :: T\<^sub>2 = (\<exists>T\<^sub>1. P,E \<turnstile> e\<^sub>1::T\<^sub>1 \<and> P,E \<turnstile> e\<^sub>2::T\<^sub>2)" (*<*) apply(rule iffI) apply (auto elim: WT.cases) done (*>*) lemma [iff]: "(P,E \<turnstile> {V:T; e} :: T') = (is_type P T \<and> P,E(V\<mapsto>T) \<turnstile> e :: T')" (*<*) apply(rule iffI) apply (auto elim: WT.cases) done (*>*) (*<*) inductive_cases WT_elim_cases[elim!]: "P,E \<turnstile> V :=e :: T" "P,E \<turnstile> if (e) e\<^sub>1 else e\<^sub>2 :: T" "P,E \<turnstile> while (e) c :: T" "P,E \<turnstile> throw e :: T" "P,E \<turnstile> try e\<^sub>1 catch(C V) e\<^sub>2 :: T" "P,E \<turnstile> Cast D e :: T" "P,E \<turnstile> a\<bullet>F{D} :: T" "P,E \<turnstile> a\<bullet>F{D} := v :: T" "P,E \<turnstile> e\<^sub>1 \<guillemotleft>bop\<guillemotright> e\<^sub>2 :: T" "P,E \<turnstile> new C :: T" "P,E \<turnstile> e\<bullet>M(ps) :: T" (*>*) lemma wt_env_mono: "P,E \<turnstile> e :: T \<Longrightarrow> (\<And>E'. E \<subseteq>\<^sub>m E' \<Longrightarrow> P,E' \<turnstile> e :: T)" and "P,E \<turnstile> es [::] Ts \<Longrightarrow> (\<And>E'. E \<subseteq>\<^sub>m E' \<Longrightarrow> P,E' \<turnstile> es [::] Ts)" (*<*) apply(induct rule: WT_WTs_inducts) apply(simp add: WTNew) apply(fastforce simp: WTCast) apply(fastforce simp: WTVal) apply(simp add: WTVar map_le_def dom_def) apply(fastforce simp: WTBinOpEq) apply(fastforce simp: WTBinOpAdd) apply(force simp:map_le_def) apply(fastforce simp: WTFAcc) apply(fastforce simp: WTFAss del:WT_WTs.intros WT_elim_cases) apply(fastforce simp: WTCall) apply(fastforce simp: map_le_def WTBlock) apply(fastforce simp: WTSeq) apply(fastforce simp: WTCond) apply(fastforce simp: WTWhile) apply(fastforce simp: WTThrow) apply(fastforce simp: WTTry map_le_def dom_def) apply(simp add: WTNil) apply(simp add: WTCons) done (*>*) lemma WT_fv: "P,E \<turnstile> e :: T \<Longrightarrow> fv e \<subseteq> dom E" and "P,E \<turnstile> es [::] Ts \<Longrightarrow> fvs es \<subseteq> dom E" (*<*) apply(induct rule:WT_WTs.inducts) apply(simp_all del: fun_upd_apply) apply fast+ done end (*>*)
Formal statement is: lemma continuous_snd[continuous_intros]: "continuous F f \<Longrightarrow> continuous F (\<lambda>x. snd (f x))" Informal statement is: If $f$ is a continuous function from a topological space $X$ to a topological space $Y$, then the function $g$ defined by $g(x) = f(x)_2$ is also continuous.
If $N$ is a set of measure zero, then almost every element of $N$ satisfies the property $P$.
State Before: α : Type ?u.22238 β : Type ?u.22241 R : Type u_1 R' : Type ?u.22247 S : Type u_3 S' : Type ?u.22253 T : Type u_2 T' : Type ?u.22259 inst✝² : NonUnitalNonAssocSemiring R inst✝¹ : NonUnitalNonAssocSemiring S inst✝ : NonUnitalNonAssocSemiring T f✝ : R →ₙ+* S g : R →ₙ+* T f : R →ₙ+* S × T x : R ⊢ ↑(NonUnitalRingHom.prod (comp (fst S T) f) (comp (snd S T) f)) x = ↑f x State After: no goals Tactic: simp only [prod_apply, coe_fst, coe_snd, comp_apply, Prod.mk.eta]
Formal statement is: lemma Zfun_zero: "Zfun (\<lambda>x. 0) F" Informal statement is: The zero function is a Z-function.
# For loop - To iterate over the List. - for **int** in range(): - range(end no) - range(start no.,end no.) - range(start no.,end no.,step) ```python d=[1,2,3,4,5] ``` ```python d.append(108) d ``` [1, 2, 3, 4, 5, 108] ```python L = [] for i in range (10): L.append(i) L ``` [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ```python L = [] for i in range(20): L.append(i) L ``` [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] ```python a = [] for k in range(2,10): a.append(k) a ``` [2, 3, 4, 5, 6, 7, 8, 9] ```python b = [] for i in range(2,21,2): b.append(i) b ``` [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] ```python sum(b) ``` 110 ```python a+b ``` [2, 3, 4, 5, 6, 7, 8, 9, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] ```python sum(a+b) ``` 154 ```python D = [] for i in range(1,5): for j in range(1,5): D.append(i+2*j) print(D) ``` [3] [3, 5] [3, 5, 7] [3, 5, 7, 9] [3, 5, 7, 9, 4] [3, 5, 7, 9, 4, 6] [3, 5, 7, 9, 4, 6, 8] [3, 5, 7, 9, 4, 6, 8, 10] [3, 5, 7, 9, 4, 6, 8, 10, 5] [3, 5, 7, 9, 4, 6, 8, 10, 5, 7] [3, 5, 7, 9, 4, 6, 8, 10, 5, 7, 9] [3, 5, 7, 9, 4, 6, 8, 10, 5, 7, 9, 11] [3, 5, 7, 9, 4, 6, 8, 10, 5, 7, 9, 11, 6] [3, 5, 7, 9, 4, 6, 8, 10, 5, 7, 9, 11, 6, 8] [3, 5, 7, 9, 4, 6, 8, 10, 5, 7, 9, 11, 6, 8, 10] [3, 5, 7, 9, 4, 6, 8, 10, 5, 7, 9, 11, 6, 8, 10, 12] ```python D = [] for i in range(1,5): print(D) for j in range(1,5): D.append(i+2*j) ``` [] [3, 5, 7, 9] [3, 5, 7, 9, 4, 6, 8, 10] [3, 5, 7, 9, 4, 6, 8, 10, 5, 7, 9, 11] ```python D = [] for i in range(1,5): for j in range(1,5): D.append(i+2*j) D ``` [3, 5, 7, 9, 4, 6, 8, 10, 5, 7, 9, 11, 6, 8, 10, 12] ```python p = [] # empty list l for i in range(1,5): for j in range(1,5): p.append(i+2*j) print('í=',i,'j=',j,'p=',p) ``` í= 1 j= 1 p= [3] í= 1 j= 2 p= [3, 5] í= 1 j= 3 p= [3, 5, 7] í= 1 j= 4 p= [3, 5, 7, 9] í= 2 j= 1 p= [3, 5, 7, 9, 4] í= 2 j= 2 p= [3, 5, 7, 9, 4, 6] í= 2 j= 3 p= [3, 5, 7, 9, 4, 6, 8] í= 2 j= 4 p= [3, 5, 7, 9, 4, 6, 8, 10] í= 3 j= 1 p= [3, 5, 7, 9, 4, 6, 8, 10, 5] í= 3 j= 2 p= [3, 5, 7, 9, 4, 6, 8, 10, 5, 7] í= 3 j= 3 p= [3, 5, 7, 9, 4, 6, 8, 10, 5, 7, 9] í= 3 j= 4 p= [3, 5, 7, 9, 4, 6, 8, 10, 5, 7, 9, 11] í= 4 j= 1 p= [3, 5, 7, 9, 4, 6, 8, 10, 5, 7, 9, 11, 6] í= 4 j= 2 p= [3, 5, 7, 9, 4, 6, 8, 10, 5, 7, 9, 11, 6, 8] í= 4 j= 3 p= [3, 5, 7, 9, 4, 6, 8, 10, 5, 7, 9, 11, 6, 8, 10] í= 4 j= 4 p= [3, 5, 7, 9, 4, 6, 8, 10, 5, 7, 9, 11, 6, 8, 10, 12] ```python A = [10*k for k in range(10)] print(A) ``` [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] ```python AA = [[10*x+y for x in range(4)] for y in range(3)] print(AA) ``` [[0, 10, 20, 30], [1, 11, 21, 31], [2, 12, 22, 32]] ```python summ = 0 for i in range(1,11): summ = summ+i print(summ) ``` 55 ```python product = 1 for i in range(1,11): product = product*i print(product) ``` 1 2 6 24 120 720 5040 40320 362880 3628800 ### Projectile - Range \begin{equation} R=\frac{u^2\sin2\theta}{2g} \end{equation} - Max.Height \begin{equation} H=\frac{u^2\sin^2\theta}{2g} \end{equation} - using list ```python import numpy as np u=100 g=9.8 angle=[] Range=[] PI=np.pi for i in range(0,90): angle.append(i) Range.append(u**2*np.sin(2*PI*i/180)/(2*g)) ``` - import matplotlib.pyplot as plt - %matplotlib inline - plt.plot(x,y) ```python import matplotlib.pyplot as plt %matplotlib inline plt.plot(angle,Range) plt.xlabel('Angle') plt.ylabel('Range') plt.title('Projectile') ``` - using dictionary ```python angle = np.arange(1,90) M = {"Range": [u**2*np.sin(2*PI*x/180)/(2*g) for x in angle],\ "Max.height": [u**2*np.sin(PI*x/180)**2/(2*g) for x in angle]} ``` ```python import pandas as pd DF = pd.DataFrame(M) DF ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>Range</th> <th>Max.height</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>17.805866</td> <td>0.155401</td> </tr> <tr> <th>1</th> <td>35.590038</td> <td>0.621416</td> </tr> <tr> <th>2</th> <td>53.330849</td> <td>1.397476</td> </tr> <tr> <th>3</th> <td>71.006684</td> <td>2.482636</td> </tr> <tr> <th>4</th> <td>88.596009</td> <td>3.875573</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> </tr> <tr> <th>84</th> <td>88.596009</td> <td>506.328508</td> </tr> <tr> <th>85</th> <td>71.006684</td> <td>507.721446</td> </tr> <tr> <th>86</th> <td>53.330849</td> <td>508.806606</td> </tr> <tr> <th>87</th> <td>35.590038</td> <td>509.582666</td> </tr> <tr> <th>88</th> <td>17.805866</td> <td>510.048680</td> </tr> </tbody> </table> <p>89 rows × 2 columns</p> </div> ```python DF.plot() plt.xlabel('Angle(degree)') plt.ylabel('Distance(m)') plt.title('Projectile') ``` ```python ```
import tactic set_option pp.structure_projections false theorem binom : ∀ x y : ℕ, (x + y)^2 = x^2 + 2*x*y + y^2 := begin assume a b, ring, end set_option pp.structure_projections false open nat --multiplication def mul : ℕ → ℕ → ℕ | m 0 := 0 | m (succ n) := (mul m n) + m -- m * 0 = n -- m * (n + 1) = m * n + m local notation m * n := mul m n #reduce mul 5 3 ----ring --semi ring /-- A semiring is a set together with two binary operators S(+,*) satisfying the following conditions: 1. Additive associativity: For all a,b,c in S, (a+b)+c=a+(b+c), 2. Additive commutativity: For all a,b in S, a+b=b+a, --left and right neutral 3. Multiplicative associativity: For all a,b,c in S, (a*b)*c=a*(b*c), 4. Left and right distributivity: For all a,b,c in S, a*(b+c)=(a*b)+(a*c) and (b+c)*a=(b*a)+(c*a). --/ --ring with 4. Additive inverse: For every a in S there exists -a in S such that a+(-a)=(-a)+a=0, /-- The field axioms are generally written in additive and multiplicative pairs. name addition multiplication associativity (a+b)+c=a+(b+c) (ab)c=a(bc) commutativity a+b=b+a ab=ba distributivity a(b+c)=ab+ac (a+b)c=ac+bc identity a+0=a=0+a a·1=a=1·a inverses a+(-a)=0=(-a)+a aa^(-1)=1=a^(-1)a if a!=0 --/ /-- Natural numbers (ℕ) Semiring Integers (ℤ) Ring Rational numbers (ℚ) Field Real numbers (ℝ) Complete Field Complex numbers (ℂ) Algebraically complete Field --/ def exp : ℕ → ℕ → ℕ | n zero := 1 | n (succ m) := exp n m * n --order ≤ , m ≤ n def le (m n : ℕ) : Prop := ∃ k : ℕ , k + m = n local notation x ≤ y := le x y local notation x ≥ y := le x y theorem le_refll : ∀ x : ℕ , x ≤ x := begin assume x, dsimp[(≤),le], existsi 0, ring, end theorem le_transs : ∀ x y z : ℕ , x ≤ y → y ≤ z → x ≤ z := begin assume x y z , assume xy yz, dsimp[(≤ ),le], dsimp[(≤ ),le] at xy, dsimp[(≤ ),le] at yz, cases xy with k p, -- ≤ is an exist statement cases yz with l q, existsi (k+l), rewrite← q, rewrite← p, ring, end --partial order: a partial order is a relation which is reflexive, transitive and antisymmetric. --reflexive (∀ x : A, x≤x), --transitive (∀ x y z : A, x≤y → y≤z → x≤z) --antisymmetry (∀ x y : ℕ , x ≤ y → y ≤ x → x = y) -- decidability -- x,y : ℕ -- x = y : Prop set_option pp.structure_projections false example: 3=3 := begin reflexivity, end example : ¬ (3 = 5) := begin assume n, have h : 2=4, injection n, have k : 1=3, injection h, have l : 0 = 2, injection k, contradiction, end example : ¬ (3 = 5) := begin assume n, cases n, end open nat def eq_nat : ℕ → ℕ → bool | zero zero := tt | zero (succ n) := ff | (succ m) zero := ff | (succ m) (succ n) := eq_nat m n #reduce eq_nat 3 3 #reduce eq_nat 3 5 lemma eq_nat_1 : ∀ m : ℕ, eq_nat m m = tt := begin assume m, induction m with n' ih, dsimp [eq_nat], reflexivity, dsimp [eq_nat], exact ih, end lemma eq_nat_2 : ∀ m n : ℕ, eq_nat m n = tt → m = n := begin assume m, induction m with m' ih_m, assume n, cases n, -- n be 0 and succ n assume h, reflexivity, assume h, dsimp [eq_nat] at h, contradiction, assume n h, cases n, dsimp [eq_nat] at h, contradiction, have g : m'=n, apply ih_m, dsimp [eq_nat] at h, exact h, rewrite g, end theorem eq_nat_dec : ∀ m n : ℕ, m=n ↔ eq_nat m n = tt := begin assume m n, constructor, assume e, rewrite e, apply eq_nat_1, apply eq_nat_2, end -- ok equality for natural numbers is decidable -- are all relations decidable, are all equalities decidable? /-- Certainly not all relations or predicates are decidable. An example for an undecidable relation is equality of functions that is given f g : ℕ → ℕ is f = g? Two functions are equal iff they agree on all arguments f = g ↔ ∀ n :ℕ,f n = g n. It is clear that we cannot decide this, i.e. define a function into bool, because we would have to check infinitely many inputs. --/ -- there are undecidable predicates -- TM : Set -- Halts : TM → Prop -- halts : TM → bool -- there is no such function, see Halting problem -- f g : ℕ → ℕ -- f = g ? -- ∀ n : ℕ, f n = g n -- eq_fun : (ℕ → ℕ) → (ℕ → ℕ) → bool -- is undecidable -- halts_after_n_steps : TM → ℕ → bool -- is definable -- Halts tm := ¬ (halts_after_n_step = λ x, ff) -- h : succ m = succ n -- ⊢ m = n -- injection h, -- a = b -- calc -- a = c : by .. -- ... = d : by .. -- ... = b : by ..
function second () double precision second real*4 t(2) second = etime(t) return end
\section{\sys\ Design} \label{sec:clio:design} This section presents the design challenges of building a hardware-based \md\ system and our solutions. \subsection{Design Challenges and Principles} Building a hardware-based \md\ platform is a previously unexplored area and introduces new challenges mainly because of restrictions of hardware and the unique requirements of \md. %Below, we discuss these challenges and our design principles. \boldpara{Challenge 1: The hardware should avoid maintaining or processing complex data structures}, because unlike software, hardware has limited resources such as on-chip memory and logic cells. For example, Linux and many other software systems use trees (\eg, the vma tree) for allocation. Maintaining and searching a big tree data structure in hardware, however, would require huge on-chip memory and many logic cells to perform the look up operation (or alternatively use fewer resources but suffer from performance loss). \boldpara{Challenge 2: Data buffers and metadata that the hardware uses should be minimal and have bounded sizes}, so that they can be statically planned and fit into the on-chip memory. Unfortunately, traditional software approaches % (usually unawaringly) involve various data buffers and metadata that are large and grow with increasing scale. %; they thus cannot meet our goal. For example, today's reliable network transports maintain per-connection sequence numbers and buffer unacknowledged packets for packet ordering and retransmission, and they grow with the number of connections. Although swapping between on-chip and off-chip memory is possible, doing so would increase both tail latency and hardware logic complexity, especially under large scale. %Thus, it is desirable to resort as little as possible to swapping. %Achieving the bounded buffer/state goal is even harder when we simultaneously need to meet our scalability goals. \boldpara{Challenge 3: The hardware pipeline should be deterministic and smooth}, \ie, it uses a bounded, known number of cycles to process a data unit, and for each cycle, the pipeline can take in one new data unit (from the network). The former would ensure low tail latency, while the latter would guarantee a throughput that could match network line rate. Another subtle benefit of a deterministic pipeline is that we can know the maximum time a data unit stays at \MN, which could help bound the size of certain buffers (\eg, \S\ref{sec:clio:ordering}). However, many traditional hardware solutions are not designed to be deterministic or smooth, and we cannot directly adapt their approaches. For example, traditional CPU pipelines could have stalls because of data hazards and have non-deterministic latency to handle memory instructions. To confront these challenges, we took a clean-slate approach by designing \sys's virtual memory system and network system with the following principles that all aim to eliminate state in hardware or bound their performance and space overhead. \boldpara{Principle 1: Avoid state whenever possible.} Not all state in server-based solutions is necessary if we could redesign the hardware. For example, we get rid of RDMA's MR indirection and its metadata altogether by directly mapping application process' \rspace\ VAs to PAs (instead of to MRs then to PAs). %Another type of states that we get rid of is network connections. \boldpara{Principle 2: Moving non-critical operations and state to software and making the hardware fast path deterministic.} If an operation is non-critical and it involves complex processing logic and/or metadata, our idea is to move it to the software slow path running in an ARM processor. For example, VA allocation (\alloc) is expected to be a rare operation because applications know the disaggregated nature and would typically have only a few large allocations during the execution. Handling \alloc, however, would involve dealing with complex allocation trees. We thus handle \alloc\ and \sysfree\ in the software slow path. Furthermore, in order to make the fast path performance deterministic, we {\em decouple} all slow-path tasks from the performance-critical path by {\em asynchronously} performing them in the background. %Note that page fault is a relatively critical operation, as all first accesses to allocated virtual pages will cause a fault, and applications like serverless computing could access large amounts of (new) memory in a short period of time. \boldpara{Principle 3: Shifting functionalities and state to \CN{}s.} While hardware resources are scarce at \MN{}s, \CN{}s have sufficient memory and processing power, and it is faster to develop functionalities in \CN\ software. A viable solution is to shift state and functionalities from \MN{}s to \CN{}s. The key question here is how much and what to shift. %; shifting too much would make \sys\ similar to \pdm\ and suffer from various performance and security issues of \pdm. Our strategy is to shift functionalities to \CN{}s only if doing so 1) could largely reduce hardware resource consumption at \MN{}s, 2) does not slow down common-case foreground data operations, 3) does not sacrifice security guarantees, and 4) adds bounded memory space and CPU cycle overheads to \CN{}s. As a tradeoff, the shift may result in certain uncommon operations (\eg, handling a failed request) being slower. %Our insight here is that we can if a shift results in performance tradeoff only for uncommon cases %For example, traditional reliable network stacks require maintaining \boldpara{Principle 4: Making off-chip data structures efficient and scalable.} Principles 1 to 3 allow us to reduce \MN\ hardware to only the most essential functionalities and state. We store the remaining state in off-chip memory and cache a fixed amount of them in on-chip memory. Different from most caching solutions, our focus is to make the access to off-chip data structure fast and scalable, \ie, all cache misses have bounded latency regardless of the number of client processes accessing an \MN\ or the amount of physical memory the \MN\ hosts. \boldpara{Principle 5: Making the hardware fast path smooth by treating each data unit independently at \MN.} If data units have dependencies (\eg, must be executed in a certain order), then the fast path cannot always execute a data unit when receiving it. To handle one data unit per cycle and reach network line rate, we make each data unit independent by including all the information needed to process a unit in it and by allowing \MN{}s to execute data units in any order that they arrive. %there is no dependency check across data units at \MN{}s. To deliver our consistency guarantees, we opt for enforcing request ordering at \CN{}s before sending them out. The rest of this section presents how we follow these principles to design \sys's three main functionalities: memory address translation and protection, page fault handling, and networking. We also briefly discuss our offloading support. \subsection{Scalable, Fast Address Translation} \label{sec:clio:addr-trans} %Similar to traditional virtual memory addressing, we use fix-size pages as VA/PA allocation and address translation unit, while data accesses are in the unit of byte. Similar to traditional virtual memory systems, we use fix-size pages as address allocation and translation unit, while data accesses are in the granularity of byte. Despite the similarity in the goal of address translation, %(\ie, translating a virtual page to a physical page number), the radix-tree-style, per-address space page table design used by all current architectures~\cite{ecuckoo-asplos20} does not fit \md\ for two reasons. First, each request from the network could be from a different client process. If each process has its own page table, \MN\ would need to cache and look up many page table roots, causing additional overhead. Second, a multi-level page table design requires multiple DRAM accesses when there is a translation lookaside buffer (TLB) miss~\cite{hashpgtable-sigmetrics16}. TLB misses will be much more common in a \md\ environment, since with more applications sharing an \MN, the total working set size is much bigger than that in a single-server setting, while the TLB size in an \MN\ will be similar or even smaller than a single server's TLB (for cost concerns). To make matters worse, each DRAM access is more costly for systems like RDMA NIC which has to cross the PCIe bus to access the page table in main memory~\cite{Pythia,pcie-sigcomm}. \ulinebfpara{Flat, single page table design (Principle 4).}~~ We propose a new {\em overflow-free} hash-based page table design that sets the total page table size according to the physical memory size and bounds \textit{address translation to at most one DRAM access}. Specifically, we store {\em all} page table entries (PTEs) from {\em all} processes in a single hash table whose size is proportional to the physical memory size of an \MN. The location of this page table is fixed in the off-chip DRAM and is known by the fast path address translation unit, thus avoiding any lookups. %We create the page table to always have enough entries to cover the entire physical memory. As we anticipate applications to allocate big chunks of VAs in their \rspace, we use huge pages and support a configurable set of page sizes. %Each PTE is 8 bytes, With the default 4\MB\ page size, the hash table consumes only 0.4\%\ of the physical memory. %For example, for 1\TB\ physical memory and 4\MB\ page size, the whole page table is only 4\MB\ (each PTE is 8 bytes). \input{clio/fig-board} The hash value of a VA and its PID is used as the index to determine which hash bucket the corresponding PTE goes to. Each hash bucket has a fixed number of ($K$) slots. To access the page table, we always fetch the entire bucket including all $K$ slots in a single DRAM access. %Normally, a hash table with fixed slots will have an overflow problem because of hash conflicts (\eg, when more than $K$ VA+PID combinations have the same hash value). A well-known problem with hash-based page table design is hash collisions that could overflow a bucket. Existing hash-based page table designs rely on collision chaining~\cite{TransCache-isca10} or open addressing~\cite{hashpgtable-sigmetrics16} to handle overflows, both require multiple DRAM accesses or even costly software intervention. In order to bound address translation to at most one DRAM access, we use a novel technique to avoid hash overflows at \textit{VA allocation time}. \ulinebfpara{VA allocation (Principle 2).}~~ The slow path software handles \alloc\ requests and allocates VA. The software allocator maintains a per-process VA allocation tree that records allocated VA ranges and permissions, similar to the Linux vma tree~\cite{linux-rb-vma}. To allocate size $k$ of VAs, it first finds an available address range of size $k$ in the tree. It then calculates the hash values of the virtual pages in this address range and checks if inserting them to the page table would cause any hash overflow. If so, it %marks the failed virtual pages in the tree as ``unusable'' and does another search for available VAs. These steps repeat until it finds a valid VA range that does not cause hash overflow. %It then send these VA page numbers (VPN) to the hardware fast path, which inserts the corresponding PTEs (invalid PTEs without PAs) to the page table. The last step is crucial for fast page fault handling in the hardware. %It then send these VA page numbers and their permissions to the hardware fast path, which establishes the corresponding PTEs (with invalid state, \ie, with permission set up but no PAs). %The last step is crucial for fast page fault handling in the hardware as it enables in-line VA permission checking. Our design trades potential retry overhead at allocation time (at the slow path) for better run-time performance and simpler hardware design (at the fast path). % core-memory implementation. This overhead is manageable because 1) each retry takes only a few microseconds with our implementation (\S\ref{sec:clio:impl}), %is fast even when running at ARM processor (\mus\ level), 2) we employ huge pages, which means fewer pages need to be allocated, 3) we choose a hash function that has very low collision rate~\cite{lookup3-wiki}, and 4) we set the page table to have extra slots (2\x\ by default) which absorbs most overflows. %and 5) the \sys\ 64-bit virtual address space is huge. %In fact, none of our evaluated application's \alloc\ requests ever require retry, even when the \alloc\ size is as huge as 1\TB. We find no conflicts when memory is below half utilized and has only up to 60 retries when memory is close to full (Figure~\ref{fig-alloc-conflict}). \ulinebfpara{TLB.}~~ %and its consistency with the page table.} \sys\ implements a TLB in a fix-sized on-chip memory area and looks it up using content-addressable-memory in the fast path. %and use LRU for replacement, On a TLB miss, the fast path fetches the PTE from off-chip memory and inserts it to the TLB by replacing an existing TLB entry with the LRU policy. When updating a PTE, the fast path also updates the TLB, in a way that ensures the consistency of inflight operations. % %As with traditional TLB, \sys\ also faces a consistency problem between TLB and the page table. %Traditionally, the OS needs to shootdown TLBs after modifying PTEs~\cite{tlbshootdown-eurosys20}. %\sys's software slow path is the party that modifies a PTE, \eg, deleting a PTE when handling \sysfree. %With our separate fast- and slow-path design, there could be potential %consistency problems when both paths try to access/modify the page table. %The first consistency problem happens when the slow path needs to update the %page table (\eg, when handling a \sysfree). %between slow-path generated PTE changes (update or delete) and fast-path TLB. %Instead of letting the slow path change the page table in DRAM and shootdown the TLB in the on-chip memory, %we let the hardware fast path pipeline handle all page table {\em and} TLB modifications. %With the latter, it is easier to ensure the consistency of inflight fast-path operations, as they are in the same pipeline as the TLB/page-table modification logic. %\zhiyuan{Is the above correct?} %If it directly applies the change to the page table in DRAM, then the TLB will be inconsistent. %Today's computer relies on the OS to perform costly~\cite{XXX} TLB shootdowns for TLB consistency. %Following our design of only having the fast path managing TLB, %To solve this problem, we adopt a simple principle: the fast path is the only unit accessing and changing TLB {\em and} the page table. %We use a different approach where %Thus, the slow path hands over its PTE change requests to the fast path, %which performs both the TLB change and the PTE change in its pipeline in a way that is consistent for inflight fast-path operations. \ulinebfpara{Limitation.}~~ A downside of our overflow-free VA allocation design is that it cannot guarantee that a specific VA can be inserted into the page table. This is not a problem for regular VA allocation but could be problematic for allocations that require a fixed VA (\eg, \texttt{mmap(MAP\_FIXED})). Currently, \sys\ finds a new VA range if the user-specified range cannot be inserted into the page table. Applications that must map at fixed VAs (\eg, libraries) will need to use \CN-local memory. \subsection{Low-Tail-Latency Page Fault Handling} A key reason to disaggregate memory is to consolidate memory usages on less DRAM so that memory utilization is higher and the total monetary cost is lower (\textbf{R1}). Thus, remote memory space is desired to run close to full capacity, and we allow memory over-commitment at an \MN, necessitating page fault handling. Meanwhile, applications like JVM-based ones allocate a large heap memory space at the startup time and then slowly use it to allocate smaller objects. Similarly, many existing far-memory systems~\cite{Tsai20-ATC,AIFM,FaRM} allocate a big chunk of remote memory and then use different parts of it for smaller objects to avoid frequently triggering the slow remote allocation operation. In these cases, it is desirable for a \md\ system to delay the allocation of physical memory to when the memory is actually used (\ie, {\em on-demand} allocation) or to ``reshape'' memory~\cite{cliquemap-sigcomm21} during runtime, necessitating page fault handling. Page faults are traditionally signaled by the hardware and handled by the OS. %, and they can happen when a PTE is invalid (VA created, PA not allocated) %or when there is a permission violation. %A common case of page faults are {\em first-time accesses}, which requires on-demand physical memory allocation. %While the latter is uncommon, the former happens at every initial access to a VA and could be common %First-time accesses can be common in applications like serverless computing and microservices which frequently start many short running processes and incur many initial-access page faults. %Unfortunately, today's page fault handling mechanism is slow because of the costly interrupt and trap-to-kernel process. This is a slow process because of the costly interrupt and kernel-trapping flow. For example, a remote page fault via RDMA costs 16.8\ms\ from our experiments using Mellanox ConnectX-4. To avoid page faults, most RDMA-based systems pre-allocate big chunks of physical memory and pin them physically. However, doing so results in memory wastes and makes it hard for an \MN\ to pack more applications, violating \textbf{R1} and \textbf{R2}. %\boldpara{Decoupling PA allocation from page fault handling.} %To meet \textbf{R2}, \textbf{R3}, and \textbf{R6}, We propose to {\em handle page faults in hardware and with bounded latency}\textemdash a {\em constant three cycles} to be more specific with our implementation of \sysboard. %Achieving this performance is not easy. %While handling permission-violation faults in hardware is easy (just by sending an error message as the request response), %Particularly, Handling initial-access faults in hardware is challenging, as initial accesses require PA allocation, which is a slow operation that involves manipulating complex data structures. Thus, we handle PA allocation in the slow path (\textbf{Challenge 1}). However, if the fast-path page fault handler has to wait for the slow path to generate a PA for each page fault, it will slow down the data plane. %As allocation is performed by ARM, fetching the allocation results via the slow path between FPGA and ARM would hugely affect foreground performance. To solve this problem, we propose an asynchronous design to shift PA allocation off the performance-critical path (\textbf{Principle 2}). Specifically, we maintain a set of {\em free physical page numbers} in an {\em async buffer}, which the ARM continuously fulfills by finding free physical page addresses and reserving them without actually using the pages. % actual allocation. During a page fault, the page fault handler simply fetches a pre-allocated physical page address. % of the corresponding page size. %This asynchronous design enables us to avoid the long wait for ARM to do an allocation on the fly. Note that even though a single PA allocation operation has a non-trivial delay, the throughput of generating PAs and filling the async buffer is higher than network line rate. %the throughput of generating PAs and filling the async buffer is higher than page fault rate. Thus, the fast path can always find free PAs in the async buffer in time. After getting a PA from the async buffer and establishing a valid PTE, %(promoted from the specially marked invalid state), the page fault handler performs three tasks in parallel: writing the PTE to the off-chip page table, inserting the PTE to the TLB, and continuing the original faulting request. This parallel design hides the performance overhead of the first two tasks, allowing foreground requests to proceed immediately. A recent work~\cite{lee-isca20} also handles page faults in hardware. %Its goal, however, is to accelerate data fetching from storage and focuses Its focus is on the complex interaction with kernel and storage devices, and it is a simulation-only work. \sys\ uses a different design for handling page faults in hardware with the goal of low tail latency, and we built it in FPGA. \ulinebfpara{Putting the virtual memory system together.}~~ We illustrate how \sysboard{}'s virtual memory system works using a simple example of allocating some memory and writing to it. The first step (\alloc) is handled by the slow path, which allocates a VA range by finding an available set of slots in the hash page table. The slow path forwards the new PTEs to the fast path, which inserts them to the page table. At this point, the PTEs are invalid. This VA range is returned to the client. When the client performs the first write, the request goes to the fast path. There will be a TLB miss, followed by a fetch of the PTE. Since the PTE is invalid, the page fault handler will be triggered, which fetches a free PA from the async buffer and establishes the valid PTE. It will then execute the write, update the page table, and insert the PTE to TLB. \subsection{Asymmetric Network Tailored for \md} \label{sec:clio:network} With large amounts of research and development efforts, today's data-center network systems are highly optimized in their performance. Our goal of \sys's network system is unique and fits \md's requirements\textemdash minimizing the network stack's hardware resource consumption at \MN{}s and achieving great scalability while maintaining similar performance as today's fast network. Traditional software-based reliable transports like Linux TCP incurs high performance overhead. Today's hardware-based reliable transports like RDMA are fast, but they require a fair amount of on-chip memory to maintain state, \eg, per-connection sequence numbers, congestion state~\cite{TONIC}, and bitmaps~\cite{IRN,MELO-APNet}, not meeting our low-cost goal. %and buffers (\eg, the unacknowledged packet buffer, packet reorder buffer) %Maintaining them in on-chip memory is not a viable solution because of \textbf{Challenge 2} (cost). Our insight is that different from general-purpose network communication where each endpoint can be both the sender (requester) and the receiver (responder) that exchange general-purpose messages, \MN{}s only respond to requests sent by \CN{}s (except for memory migration from one \MN\ to another \MN\ (\S\ref{sec:clio:dist}), in which case we use another simple protocol to achieve the similar goal). Moreover, these requests are all memory-related operations that have their specific properties. With these insights, we design a new network system with two main ideas. %and does so without the need to change any existing data-center network infrastructure. Our first idea is to maintain transport logic, state, and data buffers only at \CN{}s, essentially making \MN{}s ``transportless'' (\textbf{Principle 3}). %\footnote{1RMA~\cite{1RMA}, a recent server-based remote memory system, onloads most of its retransmission and congestion logic from the NIC to the host CPU. As a result, 1RMA's NIC is simple. %and connectionless. %However, 1RMA relies on a companion host to function, violating the ``server-less'' goal of \MN{}s.}. Our second idea is to relax the reliability of the transport and instead enforce ordering and loss recovery at the memory request level, so that \MN{}s' hardware pipeline can process data units as soon as they arrive (\textbf{Principle 5}). With these ideas, we implemented a transport in \syslib\ at \CN{}s. \syslib\ bypasses the kernel to directly issue raw Ethernet requests to an Ethernet NIC. \CN{}s use regular, commodity Ethernet NICs and regular Ethernet switches to connect to \MN{}s. \MN{}s include only standard Ethernet physical, link, and network layers and a slim layer for handling corner-case requests (\S\ref{sec:clio:ordering}). %\yizhou{We use lossless Ethernet enabled by Priority Flow Control (PFC) as it reduces packet loss and retry rate. PFC comes with a set of issues~\cite{DCQCN-sigcomm15,hpcc-sigcomm19}. Hence we design our protocol to avoid triggering it as much as possible.} We now describe our detailed design. %Both \CN{}s and \MN{}s only need standard Ethernet physical and link layers in the hardware. %Thus, \CN{} servers can continue using regular Ethernet-based NICs, and \MN{}s can be built with low cost. \ulinebfpara{Removing connections with request-response semantics.} Connections (\ie, QPs) are a major scalability issue with RDMA. Similar to recent works~\cite{Homa,1RMA}, we make our network system connection-less using request-response pairs. Applications running at \CN{}s directly initiate \sys\ APIs to an \MN\ without any connections. %Since all \sys\ operations are in the RPC style initiated by client servers, \ie, sending read/write requests and getting data/response back, %Similar to Homa~\cite{Homa}, \syslib\ assigns a unique request ID to each request. The \MN\ attaches the same request ID when sending the response back. \syslib\ uses responses as ACKs and matches a response with an outstanding request using the request ID. Neither \CN{}s nor \MN{}s send ACKs. %the response of each \sys\ request as the ACK and matches it to the request using a request ID. \ulinebfpara{Lifting reliability to the memory request level.} Instead of triggering a retransmission protocol for every lost/corrupted packet at the transport layer, \syslib\ retries the entire memory request if any packet is lost or corrupted in the sending or the receiving direction. On the receiving path, \MN{}'s network stack only checks a packet's integrity at the link layer. If a packet is corrupted, the \MN\ immediately sends a NACK to the sender \CN. %, otherwise the packet is delivered to the address translation module. \syslib\ retries a memory request if one of three situations happens: a NACK is received, the response from \MN\ is corrupted, or no response is received within a \texttt{TIMEOUT} period. %dynamic retransmission timeout (RTO) period. The RTO is computed %on a per-path basis %using the moving average of prior end-to-end RTTs. %We also avoid complex logic/states to detect lost packets and simply determine the failure of a request if no response is received in a \texttt{TIMEOUT} period. %We rely on standard link-layer mechanisms to correct packet corruptions and report uncorrectable ones~\cite{FEC}. In addition to lifting retransmission from transport to the request level, we also lift ordering to the memory request level and allow out-of-order packet delivery (see details in \S\ref{sec:clio:ordering}). %\boldpara{\CN-controlled congestion and incast.} \ulinebfpara{\CN-managed congestion and incast control.} Our goal of controlling congestion in the network and handling incast that can happen both at a \CN\ and an \MN\ is to minimize state at \MN. To this end, we build the entire congestion and incast control at the \CN\ in the \syslib. %\sys\ performs congestion control (CC) at \syslib\ to 1) keep \MN{}s stateless, and 2) make it easy for users to change the CC policy. %Our current CC policy exploits the fact that \CN{}s know the sizes of both requests and expected responses to control congestion on both the outgoing and incoming directions at \CN{}s. To control congestion, \syslib\ adopts a simple delay-based, reactive policy that uses end-to-end RTT delay as the congestion signal, similar to recent sender-managed, delay-based mechanisms~\cite{mittal2015timely,swift-sigcomm,1RMA}. %We onload CC and implement it using software to keep it flexible and easier to adopt new policies. To this end, we use a simple delay-based, reactive CC mechanism at \syslib. %End-to-end RTT delay is our primary congestion signal. %Delay has been shown to be an effective and robust signal in the heterogeneous datacenter environments~\cite{mittal2015timely,swift-sigcomm,1RMA}. %It requires no special switch features such as ECN~\cite{DCQCN} or INT~\cite{HPCC}. Each \CN\ maintains one congestion window, \textit{cwnd}, per \MN\ %which is shared by all processes accessing the \MN. %It that controls the maximum number of outstanding requests that can be made to the \MN\ from this \CN. We adjust \textit{cwnd} based on measured delay using a standard Additive Increase Multiplicative Decrease (AIMD) algorithm. To handle incast to a \CN, we exploit the fact that the \CN{} knows the sizes of expected responses for the requests that it sends out and that responses are the major incoming traffic to it. Each \syslib\ maintains one incast window, \textit{iwnd}, which controls the maximum bytes of expected responses. \syslib\ sends a request only when both \textit{cwnd} and \textit{iwnd} have room. Handling incast to an \MN\ is more challenging, as we cannot throttle incoming traffic at the \MN\ side or would otherwise maintain state at \MN{}s. To have \CN{}s handle incast to \MN{}s, we draw inspiration from Swift~\cite{swift-sigcomm} by allowing \textit{cwnd} to fall below one packet when long delay is observed at a \CN. For example, a \textit{cwnd} of 0.1 means that the \CN\ can only send a packet within 10 RTTs. Essentially, this situation happens when the network between a \CN\ and an \MN\ is really congested, and the only way is to slow the sending speed. \subsection{Request Ordering and Data Consistency} \label{sec:clio:ordering} As explained in \S\ref{sec:clio:abstraction}, \sys\ supports both synchronous and asynchronous remote memory APIs, with the former following a sequential, one-at-a-time order in a thread and the latter following a release order in a thread. Furthermore, \sys\ provides synchronization primitives for inter-thread consistency. We now discuss how \sys\ achieves these correctness guarantees by presenting our mechanisms for handling intra-request intra-thread ordering, inter-request intra-thread ordering, inter-thread consistency, and retries. At the end, we will provide the rationales behind our design. One difficulty in designing the request ordering and consistency mechanisms is our relaxed network ordering guarantees, which we adopt to minimize the hardware resource consumption for the network layer at \MN{}s (\S\ref{sec:clio:network}). On an asynchronous network, it is generally hard to guarantee any type of request ordering when there can be multiple outstanding requests (either multiple threads accessing shared memory or a single thread issuing multiple asynchronous APIs). It is even harder for \sys\ because we aim to make \MN\ stateless as much as possible. %Allowing memory requests to be asynchronous Ensuring even a weaker consistency level like release consistency is hard when the network can reorder and drop packets and when we aim to minimize states at \MN{}s. Our general approaches are 1) using \CN{}s to ensure that no two concurrently outstanding requests are dependent on each other, and 2) using \MN{}s to ensure that every user request is only executed once even in the event of retries. %\zhiyuan{We design our consistency model based on the requirements of disaggregation and the efficiency of hardware design. %Most desegregation use cases (e.g. with local caches) rarely send out memory access requests with dependency, so strict ordering can be an overkill; This allows us to apply released consistency model and simplify hardware design} %\zhiyuan{We apply an released consistency similar to ARMv8, which allows %which dependent requests in Clio only includes memory fences and requests that operates on the same address. We also provide synchronization primitives, \syslock and \fence between threads. The execution order of other requests and request from different threads. can be reordered at \CN{}, network or \MN{}.} %\zhiyuan{We apply two rules to implement our consistency model. First, for a client, all committed but not completed requests must not have dependency; Second, At MN side, all request must be executed and only executed once. The rules ensures the correctness of the implementation.} \ulinebfpara{Allowing intra-request packet re-ordering (T1).} %\zhiyuan{We use client side libraries to ensure first rule.} %Packet reordering can happen in the network, \eg, due to data-center multipath routing~\cite{ECMP}. %which can happen at the link layer. A request or a response in \sys\ can contain multiple link-layer packets. Enforcing packet ordering above the link layer normally requires maintaining state (\eg, packet sequence ID) at both the sender and the receiver. To avoid maintaining such state at \MN{}s, our approach is to deal with packet reordering only at \CN{}s in \syslib\ (\textbf{Principle 3}). Specifically, \syslib\ splits a request that is bigger than link-layer maximum transmission unit (MTU) into several link-layer packets and attaches a \sys\ header to each packet, which includes sender-receiver addresses, a request ID, and request type. This enables the \MN{} to treat each packet independently (\textbf{Principle 5}). It executes packets as soon as they arrive, even if they are not in the sending order. This out-of-order data placement semantic is in line with RDMA specification~\cite{IRN}. Note that only write requests will be bigger than MTU, and the order of data writing within a write request does not affect correctness as long as proper {\em inter-request} ordering is followed. When a \CN\ receives multiple link-layer packets belonging to the same request response, \syslib\ reassembles them before delivering them to the application. \ulinebfpara{Enforcing intra-thread inter-request ordering at \CN\ (T2).} Since only one synchronous request can be outstanding in a thread, there cannot be any inter-request reordering problem. %Synchronous requests follow strict program order with only at most one outstanding request. %and we do not need to take any special measurement for synchronous request ordering. On the other hand, there can be multiple outstanding asynchronous requests. Our provided consistency level disallows concurrent asynchronous requests that are dependent on each other (WAW, RAW, or WAR). In addition, all requests must complete before \release. We enforce these ordering requirements at \CN{}s in \syslib\ instead of at \MN{}s (\textbf{Principle 3}) for two reasons. First, enforcing ordering at \MN{}s requires more on-chip memory and complex logic in hardware. Second, even if we enforce ordering at \MN{}s, network reordering would still break end-to-end ordering guarantees. %To enforce ordering for asynchronous operations at the client side, Specifically, \syslib\ keeps track of all inflight requests and matches every new request's virtual page number (VPN) to the inflight ones'. If a WAR, RAW, or WAW dependency is detected, \syslib\ blocks the new request until the conflicting request finishes. When \syslib\ sees a \release\ operation, it waits until all inflight requests return or time out. We currently track dependencies at the page granularity mainly to reduce tracking complexity and metadata overhead. The downside is that false dependencies could happen (\eg, two accesses to the same page but different addresses). False dependencies could be reduced by dynamically adapting the tracking granularity if application access patterns are tracked\textemdash we leave this improvement for future work. %tailored for application needs. %In reality, this is not a problem, as with a low-latency system like \sys, the amount of outstanding requests is small and the chance of two outstanding requests accessing the same page is extremely rare. %, which largely depends on application usage. %Intuitively, it is problematic for data structure systems~\cite{AIFM} with small granularity access, but works well for others with larger accesses. We leave this optimization for future work. %For synchronous operations, \syslib\ only returns when a request gets a response, effectively achieving strict ordering. \ulinebfpara{Inter-thread/process consistency (T3).} %\zhiyuan{At the \MN{} side, we ensures the semantic of execute once.} %\zhiyuan{Move the retry to earlier position?} Multi-threaded or multi-process concurrent programming on \sys\ could use the synchronization primitives \sys\ provides to ensure data consistency (\S\ref{sec:clio:abstraction}). %, \eg, by protecting a critical section using \syslock. We implemented all synchronization primitives like \syslock\ and \fence\ at \MN, because they need to work across threads and processes that possibly reside on different \CN{}s. Before a request enters either the fast or the slow paths, \MN\ checks if it is a synchronization primitive. %an atomic operation or a \fence. For primitives like \syslock\ that internally is implemented using atomic operations like \texttt{TAS}, \MN\ blocks future atomic operations until the current one completes. For \fence, \MN\ blocks all future requests until all inflight ones complete. Synchronization primitives are one of the only two cases where \MN\ needs to maintain state. %As these operations operation executes in bounded time, the hardware resources for states are bounded. As these operations are infrequent and each of these operations executes in bounded time, the hardware resources for maintaining their state are minimal and bounded. \ulinebfpara{Handling retries (T4).} \syslib\ retries a request after a \texttt{TIMEOUT} period without receiving any response. Potential consistency problems could happen as \sysboard\ could execute a retried write after the data is written by another write request thus undoing this other request's write. Such situations could happen when the original request's response is lost or delayed and/or when the network reorders packets. %Such situation would violate \sys's consistency guarantees. %Such situations could happen because the network could reorder packets and because we support multiple concurrent processes sharing the same data. % We use two techniques to solve this problem. First, \syslib\ attaches a new request ID to each retry, essentially making it a new request with its own matching response. Together with \syslib's ordering enforcement, it ensures that there is only one outstanding request (or a retry) at any time. Second, we maintain a small buffer at \MN\ to record the request IDs of recently executed writes and atomic APIs and the results of the atomic APIs. A retry attaches its own request ID and the ID of the failed request. If \MN\ finds a match of the latter in the buffer, it will not execute the request. For atomic APIs, it sends the cached result as the response. We set this buffer's size to be 3$\times$\texttt{TIMEOUT}$\times$\textit{bandwidth}, which is 30\KB\ in our setting. It is one of the only two types of state \MN\ maintains and does not affect the scalability of \MN, since its size is statically associated with the link bandwidth and the \texttt{TIMEOUT} value. With this size, the \MN\ can ``remember'' an operation long enough for two retries from the \CN. Only when both retries and the original request all fail, the \MN\ will fail to properly handle a future retry. This case is extremely rare~\cite{Homa}, and we report the error to the application, similar to \cite{Kalia14-RDMAKV,1RMA}. \ulinebfpara{Why T1 to T4?} We now briefly discuss the rationale behind why we need all T1 to T4 to properly deliver our consistency guarantees. First, assume that there is no packet loss or corruption (\ie, no retry) but the network can reorder packets. In this case, using T1 and T2 alone is enough to guarantee the proper ordering of \sys\ memory operations, since they guarantee that network reordering will only affect either packets within the same request or requests that are not dependent on each other. T3 guarantees the correctness of synchronization primitives since the \MN\ is the serialization point and is where these primitives are executed. Now, consider the case where there are retries. Because of the asynchronous network, a timed-out request could just be slow and still reach the \MN, either before or after the execution of the retried request. If another request is executed in between the original and the retried requests, inconsistency could happen (\eg, losing the data of this other request if it is a write). The root cause of this problem is that one request can be executed twice when it is retried. T4 solves this problem by ensuring that the \MN\ only executes a request once even if it is retried. \subsection{Extension and Offloading Support} \label{sec:clio:extended} To avoid network round trips when working with complex data structures and/or performing data-intensive operations, we extend the core \MN\ to support application computation offloading in the extend path. %which includes an FPGA chip and the ARM processor. %We only have space to give a high-level overview of the extend path, leaving details to a follow-on paper. Users can write and deploy application offloads both in FPGA and in software (run in the ARM). %An offload can either be the handler of a high-level API (\eg, pointer chasing) or an entire function (\eg, data filtering). To ease the development of offloads, \sys\ offers the same virtual memory interface as the one to applications running at \CN{}s. Each offload has its own PID and virtual memory address space, and they use the same virtual memory APIs (\S\ref{sec:clio:abstraction}) to access on-board memory. It could also share data with processes running at \CN{}s in the same way that two \CN\ processes share memory. %Developing offloads is thus closer to traditional multi-threaded programming (in terms of memory accesses). Finally, an offload’s data and control paths could be split to FPGA and ARM and use the same async-buffer mechanism for communication between them. These unique designs made developing computation offloads easier and closer to traditional multi-threaded software programming. \subsection{Distributed \MN{}s} \label{sec:clio:dist} Our discussion so far focused on a single \MN\ (\sysboard). To more efficiently use remote memory space and to allow one application to use more memory than what one \sysboard\ can offer, we extend the single-\MN\ design to a distributed one with multiple \MN{}s. Specifically, an application process' \rspace\ can span multiple \MN{}s, and one \MN\ can host multiple \rspace{}s. We adopt LegoOS' two-level distributed virtual memory management approach to manage distributed \MN{}s in \sys. A global controller manages \rspace{}s in coarse granularity (assigning 1\GB\ virtual memory regions to different \MN{}s). Each \MN\ then manages the assigned regions at fine granularity. The main difference between LegoOS and \sys's distributed memory system is that in \sys, each \MN\ can be over-committed (\ie, allocating more virtual memory than its physical memory size), and when an \MN\ is under memory pressure, it migrates data to another \MN\ that is less pressured (coordinated by the global controller). The traditional way of providing memory over-commitment is through memory swapping, which could be potentially implemented by swapping memory between \MN{}s. However, swapping would cause performance impact on the data path and add complexity to the hardware implementation. Instead of swapping, we \textit{proactively} migrate a rarely accessed memory region to another \MN\ when an \MN\ is under memory pressure (its free physical memory space is below a threshold). During migration, we pause all client requests to the region being migrated. With our 10\Gbps\ experimental board, migrating a 1\GB\ region takes 1.3 second. Migration happens rarely and, unlike swapping, happens in the background. Thus, it has little disturbance to foreground application performance.
module varsteal use params_array ! variables shared between steal, como and etl real*8, dimension(NFLDIM) :: phi, pweight integer, allocatable, dimension(:) :: levelpl, nfedge, itne, iwarn real*8, allocatable, dimension(:) :: en real*8, allocatable, dimension(:) :: opa, eta real*8, allocatable, dimension(:) :: thomson, tauthom real*8, allocatable, dimension(:) :: opac, etac real*8, allocatable, dimension(:) :: dopa, deta real*8, allocatable, dimension(:) :: expfac real*8, allocatable, dimension(:, :) :: sigmaki, depart end module
If $s$ is a complete metric space and $(f_n)$ is a Cauchy sequence in $s$, then there exists $l \in s$ such that $f_n \to l$.
= = Early life and World War I = =
[STATEMENT] lemma trans_mat_rep_block_size_sym: "j < dim_col M \<Longrightarrow> mat_block_size M j = mat_rep_num M\<^sup>T j" "i < dim_row M \<Longrightarrow> mat_rep_num M i = mat_block_size M\<^sup>T i" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (j < dim_col M \<Longrightarrow> mat_block_size M j = mat_rep_num M\<^sup>T j) &&& (i < dim_row M \<Longrightarrow> mat_rep_num M i = mat_block_size M\<^sup>T i) [PROOF STEP] unfolding mat_block_size_def mat_rep_num_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. (j < dim_col M \<Longrightarrow> count_vec (col M j) (1::'a) = count_vec (row M\<^sup>T j) (1::'a)) &&& (i < dim_row M \<Longrightarrow> count_vec (row M i) (1::'a) = count_vec (col M\<^sup>T i) (1::'a)) [PROOF STEP] by simp_all
Formal statement is: lemma lipschitz_on_cmult_upper [lipschitz_intros]: fixes f::"'a::metric_space \<Rightarrow> 'b::real_normed_vector" assumes "C-lipschitz_on U f" "abs(a) \<le> D" shows "(D * C)-lipschitz_on U (\<lambda>x. a *\<^sub>R f x)" Informal statement is: If $f$ is $C$-Lipschitz on $U$, then $a f$ is $(D C)$-Lipschitz on $U$, where $|a| \leq D$.
# Cerebellar Model Articulation Controller(CMAC) ## 概论 小脑模型的初始设想很简单,希望设计一个这样的模型: 1. **足够快** 2. **拟合** ### 足够快 对于第一点,传统的神经网络均是使用浮点数进行计算,使用浮点数显然存在两个缺点:其一是占用空间大,其二是运算不够快。但也存在非常明显的优点:计算精度高。 若为了在不太降低精度的条件下尽可能提高模型运算效率,显然有两个角度:其一是改进模型,其二是改变数值存储方式。 量化技术就是这样一类通过改变数值存储方式提高模型运算效率的方式。对于现代神经网络,训练通常采用32位浮点数,推理时则可以选用16位浮点数以提高精度,而当部署到边缘设备上时则可以进一步采用**int8量化技术**。 对于CMAC,同样的,为了提升运算效率,初始数据输入时会进行量化。此外,为了进一步提升效率,CMAC还引入了**哈希散列**,通过查表的方式将相近的输入映射到相似的地址上。 哈希散列同时也引入了不确定的因素。哈希散列是一种压缩映射,其很有可能将不同的输入映射到同一个地址,即导致了**碰撞**。从另一个角度讲,这也引入了非线性变换,即在原空间可能相隔非常远的两个输入,在映射后可能十分相近甚至发生**碰撞**。 ### 拟合 为了实现拟合,CMAC在查表后建立了一个自适应线性层,实现地址到输出的线性估计 由于采用了哈希,实际上建立了输入与地址的映射表。在不考虑碰撞的情况下,一个特定的输入会激活特定的地址,而特定的地址会激活特定的自适应线性层的输入单元,这些单元则会连接到输出。 不同于传统的神经网络,进行推理时同层所有的神经元均会参与运算,CMAC中仅有被激活的输入单元才会参与运算,这显然也加速了CMAC的运算速度。 ## 符号定义 ### 空间 |符号|含义| |:-:|:-:| |$S$|输入空间| |$M$|扩充地址空间| |$MC$|扩充地址空间长度| |$A_c$|虚拟存储空间| |$A_p$|实际存储空间| |$F$|输出空间| ### 数据 |符号|含义| |:-:|:-:| |$\bm{s}$|输入向量| |$\bm{m}$|扩充后矩阵| |$\bm{a}$|虚拟存储空间向量| |$\bm{d}$|实际存储空间向量| |$\hat{y}$|预测输出| |$y$|真实输出| ### 参数 |符号|含义| |:-:|:-:| |s|输入空间维度| |q|量化级| |c|扩充地址维度| |$N_p$|用于Hash运算的质数| |$\bm{W}$|权矩阵| ## 正向运算 CMAC的整体流程如下: * 输入空间$S$离散化 * 输入空间$S$ $\rightarrow$ 扩充地址空间$M$ * 扩充地址空间$M$ $\rightarrow$ 虚拟存储空间$A_c$ * 虚拟存储空间$A_c$ $\rightarrow$ 实际存储空间$A_p$ * 实际存储空间$A_p$ $\rightarrow$ 输出空间$F$ 第零步为离散化。一方面是加速运算,另一方面也是配合后续的Hash 第一步是在进行升维 第二步是将第一步中升维到高维的多个分量组合为一个向量 第三步为Hash 第四步为自适应线性拟合 ### 离散化 输入为$\bm{s}=[s_1, s_2, \cdots, s_s]$ 设定第n个维度的取值范围为$[n_{min}, n_{max}]$,量化级为q_n 则第n个维度的离散值为 $$ \begin{equation} s_n = \lceil\frac{(s_n-n_{min})}{(n_{max}-n_{min})}*(q_n-1)\rceil + 1 \end{equation} $$ ### 输入空间到扩充地址空间 每一个输入分量均扩充到c维 对于一个特定的输入分量$s_n$,有对应的扩充后向量$\bm{m_n}$ 扩充后向量按照如下的方式进行运算 定义如下的取余运算 $$ \begin{equation} \Psi(s_n) = mod(\frac{s_n-1}{c})+1 \end{equation} $$ 则$\bm{m_n}$的第$\Psi(s_n)$位为$s_n$,其他位依次推出 |$\bm{m_{n1}}$|$\bm{m_{n2}}$|$\cdots$|$\bm{m_{n\Psi(s_n)}}$|$\cdots$|$\bm{m_{nc}}$| |:-:|:-:|:-:|:-:|:-:|:-:| |$s_n+(c-\Psi(s_n)+1)$|$s_n+(c-\Psi(s_n)+2)$|$\cdots$|$s_n$|$\cdots$|$s_n+(c-\Psi(s_n))$| ### 扩充地址空间到虚拟存储空间 扩充地址空间为一个$s\times c$的矩阵,转换到虚拟存储空间后进行纵向连接,即进行如下操作 $$ \begin{equation} \bm{m} = \left[\begin{array}{cc} m_{11}&m_{12}&\cdots&m_{1c} \\ \vdots&\ddots&\ddots&\vdots \\ m_{s1}&m_{s2}&\cdots&m_{sc} \end{array}\right] \end{equation} $$ $$ \begin{equation} \begin{split} \bm{a} &= [a_1, a_2, \cdots, a_c]^T \\ &= [m_{11}m_{21}\cdots m_{s1}, m_{12}m_{22}\cdots m_{s2}, \cdots, m_{1c}m_{2c}\cdots m_{sc}]^T \end{split} \end{equation} $$ ### 虚拟存储空间到实际存储空间 这一步即为Hash,在这里采用取余运算的方式,类似于式2有: $$ \begin{equation} \Psi(a_n) = mod(\frac{a_n-1}{N_p})+1 \end{equation} $$ $$ \begin{equation} \begin{split} \bm{d} &= [d_1, d_2, \cdots, d_c]^T \\ &= [\Psi(a_1), \Psi(a_2), \cdots, \Psi(a_c)]^T \end{split} \end{equation} $$ ### 实际存储空间到输出空间 这一步采用简单的线性变换 上述得到的是地址,在CMAC中,为了加速运算,最终一步是通过查询实现的, 权矩阵$\bm{W}\in\mathcal{R}^{c \times N_p}$ 其中$c$为地址的维度,$N_p$为取余运算的除数,对于以$N_p$为底的除法,显然得到的余数不可能大于$N_p$ 输出即为对应地址位置的权值之和 $$ \begin{equation} \hat{y} = \sum_{i=0}^{c}W[i, \Psi(a_i)] \end{equation} $$ 上述方法均是在从1开始计数的背景下讨论的,在具体实现中将从0开始计数 ## 参数学习 定义损失函数 $$ \begin{equation} \mathcal{L} = ||\hat{y}-y||_2^2 \end{equation} $$ 对权值求偏导 $$ \begin{equation} \begin{split} \frac{\partial \mathcal{L}}{\partial \bm{W}} &= \frac{||\hat{y}-y||_2^2}{\partial \bm{W}} \\ &= \frac{(\sum_{i=0}^{c}W[i, \Psi(a_i)]-y)^2}{\partial \bm{W}} \\ &= 2(\sum_{i=0}^{c}W[i, \Psi(a_i)]-y)\frac{\sum_{i=0}^{c}W[i, \Psi(a_i)]}{\partial \bm{W}} \end{split} \end{equation} $$ $$ \begin{equation} \frac{\partial \mathcal{L}}{W_{ij}} = \left\{ \begin{array}{cc} 0,&d_i \neq j+1 \\ 2(\sum_{i=0}^{c}W[i, \Psi(a_i)]-y),&else \end{array} \right. \end{equation} $$ 获得参数更新函数 $$ \begin{equation} \bm{W}(t+1) = \bm{W}(t) - \eta\frac{\partial \mathcal{L}}{\bm{W}(t)} \end{equation} $$ ```python import os import random import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.axes3d import Axes3D import seaborn as sn import imageio %matplotlib inline ``` ```python class CMAC(object): def __init__(self, input_dim, input_range, q_level, expend_dim, hash_number): """ input_dim: 输入维度 input_range: 输入取值范围,默认需要一个list q_level: 量化级,默认需要输入一个list expend_dim: 扩充地址维度 hash_number: 用于散列的质数 """ self.input_dim = input_dim self.input_range = np.array(input_range) self.q_level = q_level self.expend_dim = expend_dim self.hash_number = hash_number # 输出权值矩阵 random.seed(1024) np.random.seed(1024) self.weight_matrix = np.zeros((self.expend_dim, self.hash_number)) # 数据存储空间向量 self.real_vector = None self.output_vector = None def forward(self, x): """ x: 输入向量 """ # ------------- 离散化 --------------- input_q = self._quantification(np.array(x)) # ------------- 输入空间到扩充地址空间 ------------------ # (self.expend_dim, self.input_dim) expend_matrix = self._input2expend(input_q) # ------------- 扩充地址空间到虚拟存储空间 ----------------- # (self.expend_dim, 1) virtual_vector = self._expend2virtual(expend_matrix) # ------------- 虚拟存储空间到实际存储空间 ------------------ # (self.expend_dim, 1) self.real_vector = self._virtual2real(virtual_vector) # ------------- 实际存储空间到输出空间 -------------------- # (self.output_dim, 1) self.output_value = self._real2output(self.real_vector) return self.output_value def optim(self, true_output, lr): """ true_output: 真实输出 """ # 更新mask partial_matrix = np.zeros((self.expend_dim, self.hash_number)) partial_matrix[range(0, self.expend_dim), self.real_vector.reshape(-1)] = 1 self.weight_matrix -= lr * (self.output_value - true_output) * partial_matrix def _quantification(self, input_vector): """ input_vector: 输入向量 """ input_q = np.zeros(self.input_dim, dtype=np.int32) # (self.input_dim) for i in range(self.input_dim): _input_range = self.input_range[i, :] input_q[i] = np.math.ceil((input_vector[i]-_input_range[0])*(self.q_level[i]-1)/(_input_range[1]-_input_range[0])) return input_q def _input2expend(self, input_q): """ input_q: 量化后的输入向量 """ expend_matrix = np.zeros((self.input_dim, self.expend_dim)) for i in range(self.input_dim): # 计算取余运算 phi_ = input_q[i] % self.expend_dim if phi_ != 0: # index < phi_ add_number_list_1 = np.array(range(0, phi_)) # index > phi_ add_number_list_2 = np.array(range(0, self.expend_dim-phi_)) expend_matrix[i, :phi_] = input_q[i] + self.expend_dim - phi_ + add_number_list_1 expend_matrix[i, phi_:] = input_q[i] + add_number_list_2 else: expend_matrix[i] = input_q[i] + np.array(range(0, self.expend_dim)) return expend_matrix.astype(np.int32).T def _expend2virtual(self, expend_matrix): """ expend_matrix: 扩充地址空间矩阵 """ virtual_vector = np.zeros((self.expend_dim, 1), dtype=np.int32) # 进行组合 mul_num = 1 for i in range(self.input_dim): virtual_vector += expend_matrix[:, i:i+1] * mul_num mul_num *= self.q_level[i] + self.expend_dim - 1 return virtual_vector def _virtual2real(self, virtual_vector): """ virtual_vector: 虚拟存储空间向量 """ real_vector = np.zeros((self.expend_dim, 1), dtype=np.int32) for i in range(self.expend_dim): real_vector[i] = virtual_vector[i]%self.hash_number return real_vector def _real2output(self, real_vector): """ real_vector: 实际存储空间向量 """ output_value = np.sum(self.weight_matrix[range(0, self.expend_dim), real_vector.reshape(-1)]) return output_value ``` ```python # 测试数据 # 输入维度 input_dim = 2 # 输入范围 input_range = [[0, 6.2], [0, 6.2]] # 量化级 q_levle = [62, 62] # 扩充地址空间维度 expend_dim = 7 # 散列质数 hash_number = 5001 # 学习率 lr = 0.1 # 输出维度 output_dim = 1 # 测试输入 input_vector = [0.2, 0.2] # 测试输出 output_ = 1 my_cmac = CMAC(input_dim=input_dim, input_range=input_range, q_level=q_levle, expend_dim=expend_dim, hash_number=hash_number) # 离散值输出 input_q = my_cmac._quantification(input_vector) print("离散\n", input_q) # 输入空间到扩充地址空间 expend_matrix = my_cmac._input2expend(input_q) print("扩充地址空间\n", expend_matrix) # 扩充地址空间到虚拟存储空间 virtual_vector = my_cmac._expend2virtual(expend_matrix) print("虚拟存储空间\n", virtual_vector) # 虚拟存储空间到实际存储空间 real_vector = my_cmac._virtual2real(virtual_vector) print("实际存储空间\n", real_vector) # 实际存储空间到输出空间 output_value = my_cmac._real2output(real_vector) print("输出\t", output_value) # 参数优化 print("参数学习") for step in range(10): output_value_2 = my_cmac.forward(input_vector) my_cmac.optim(output_, lr) print("step:{}\t output_value:{:.6f}".format(step, output_value_2)) ``` 离散 [2 2] 扩充地址空间 [[7 7] [8 8] [2 2] [3 3] [4 4] [5 5] [6 6]] 虚拟存储空间 [[483] [552] [138] [207] [276] [345] [414]] 实际存储空间 [[483] [552] [138] [207] [276] [345] [414]] 输出 0.0 参数学习 step:0 output_value:0.000000 step:1 output_value:0.700000 step:2 output_value:0.910000 step:3 output_value:0.973000 step:4 output_value:0.991900 step:5 output_value:0.997570 step:6 output_value:0.999271 step:7 output_value:0.999781 step:8 output_value:0.999934 step:9 output_value:0.999980 ```python # 对函数进行拟合 # 拟合函数f(x1, x2) = sin(x1)cos(x2) # x1范围[-3, 3],总点数100 # x2范围[-3, 3],总点数100 # ------------------- 超参数 ------------------- # 输入维度 input_dim = 2 # 输入范围 input_range = [[-3, 3], [-3, 3]] # 量化级 q_levle = [100, 100] # 扩充地址空间维度 expend_dim = 13 # 散列质数 hash_number = 101 # 学习率 lr = 0.005 # 最大epoch iteration = 40000 # ------------------- 模型 ----------------------- my_cmac = CMAC(input_dim=input_dim, input_range=input_range, q_level=q_levle, expend_dim=expend_dim, hash_number=hash_number) # ------------------- 数据 ----------------------- # 生成数据的分辨率 sample_resolution = 100 x1, x2 = np.meshgrid(np.linspace(-3, 3, sample_resolution), np.linspace(-3, 3, sample_resolution)) train_x_list = np.concatenate((x1.reshape(-1, 1), x2.reshape(-1, 1)), axis=1) train_y_list = np.sin(train_x_list[:, 0:1]) * np.cos(train_x_list[:, 1:]) # ------------------- 参数优化 ------------------------ print("参数学习") random.seed(1024) print_frequency = 1 train_loss = 0 train_loss_dict = dict() train_pred_recoder = list() params_recoder = list() # 对所有输入进行预测 pred_matrix = np.zeros((sample_resolution, sample_resolution)) for _x1 in range(sample_resolution): for _x2 in range(sample_resolution): pred_y = my_cmac.forward([x1[_x1, _x2], x2[_x1, _x2]]) pred_matrix[_x1, _x2] = pred_y train_loss += (pred_y - np.sin(x1[_x1, _x2]) * np.cos(x2[_x1, _x2]))**2 train_loss /= sample_resolution ** 2 train_loss_dict[0] = train_loss print("iterations:[{}/{}] avg loss:{:.6f}".format(0, iteration, train_loss)) train_loss = 0 train_pred_recoder.append(pred_matrix) params_recoder.append(my_cmac.weight_matrix.copy()) # 开始训练 for i in range(1, iteration+1): sample_index = random.randint(0, len(train_x_list)-1) sample_x = train_x_list[sample_index] sample_y = train_y_list[sample_index] pred_y = my_cmac.forward(sample_x) my_cmac.optim(sample_y, lr) if i % print_frequency == 0 or i % iteration == 0: # 对所有输入进行预测 pred_matrix = np.zeros((sample_resolution, sample_resolution)) for _x1 in range(sample_resolution): for _x2 in range(sample_resolution): pred_y = my_cmac.forward([x1[_x1, _x2], x2[_x1, _x2]]) pred_matrix[_x1, _x2] = pred_y train_loss += (pred_y - np.sin(x1[_x1, _x2]) * np.cos(x2[_x1, _x2]))**2 train_loss /= sample_resolution * sample_resolution train_loss_dict[i] = train_loss print("iterations:[{}/{}] avg loss:{:.6f}".format(i, iteration, train_loss)) train_loss = 0 train_pred_recoder.append(pred_matrix) params_recoder.append(my_cmac.weight_matrix.copy()) print_frequency = int(pow(1.1, len(train_loss_dict))) ``` 参数学习 iterations:[0/40000] avg loss:0.249668 iterations:[1/40000] avg loss:0.248866 iterations:[2/40000] avg loss:0.248780 iterations:[3/40000] avg loss:0.247917 iterations:[4/40000] avg loss:0.247636 iterations:[5/40000] avg loss:0.247176 iterations:[6/40000] avg loss:0.247146 iterations:[7/40000] avg loss:0.247127 iterations:[8/40000] avg loss:0.247081 iterations:[10/40000] avg loss:0.246616 iterations:[12/40000] avg loss:0.245713 iterations:[14/40000] avg loss:0.244969 iterations:[15/40000] avg loss:0.244593 iterations:[18/40000] avg loss:0.244322 iterations:[21/40000] avg loss:0.244281 iterations:[24/40000] avg loss:0.243114 iterations:[28/40000] avg loss:0.241051 iterations:[30/40000] avg loss:0.238231 iterations:[35/40000] avg loss:0.235232 iterations:[36/40000] avg loss:0.235204 iterations:[42/40000] avg loss:0.232649 iterations:[49/40000] avg loss:0.231421 iterations:[56/40000] avg loss:0.229389 iterations:[64/40000] avg loss:0.226473 iterations:[72/40000] avg loss:0.222563 iterations:[80/40000] avg loss:0.219286 iterations:[88/40000] avg loss:0.217603 iterations:[91/40000] avg loss:0.215672 iterations:[98/40000] avg loss:0.213108 iterations:[105/40000] avg loss:0.209429 iterations:[119/40000] avg loss:0.203817 iterations:[133/40000] avg loss:0.198528 iterations:[147/40000] avg loss:0.193617 iterations:[161/40000] avg loss:0.187870 iterations:[175/40000] avg loss:0.183861 iterations:[196/40000] avg loss:0.176829 iterations:[210/40000] avg loss:0.171412 iterations:[238/40000] avg loss:0.163909 iterations:[259/40000] avg loss:0.157559 iterations:[287/40000] avg loss:0.151061 iterations:[315/40000] avg loss:0.141405 iterations:[343/40000] avg loss:0.134490 iterations:[378/40000] avg loss:0.126971 iterations:[420/40000] avg loss:0.119266 iterations:[462/40000] avg loss:0.111286 iterations:[504/40000] avg loss:0.104249 iterations:[560/40000] avg loss:0.094525 iterations:[616/40000] avg loss:0.085898 iterations:[679/40000] avg loss:0.077194 iterations:[742/40000] avg loss:0.069259 iterations:[819/40000] avg loss:0.062141 iterations:[903/40000] avg loss:0.054239 iterations:[994/40000] avg loss:0.047911 iterations:[1092/40000] avg loss:0.041417 iterations:[1197/40000] avg loss:0.035435 iterations:[1323/40000] avg loss:0.029391 iterations:[1449/40000] avg loss:0.025351 iterations:[1596/40000] avg loss:0.019751 iterations:[1757/40000] avg loss:0.016564 iterations:[1932/40000] avg loss:0.013696 iterations:[2128/40000] avg loss:0.011093 iterations:[2338/40000] avg loss:0.008763 iterations:[2576/40000] avg loss:0.006438 iterations:[2835/40000] avg loss:0.005285 iterations:[3115/40000] avg loss:0.004406 iterations:[3430/40000] avg loss:0.003611 iterations:[3773/40000] avg loss:0.003010 iterations:[4151/40000] avg loss:0.002522 iterations:[4564/40000] avg loss:0.002071 iterations:[5019/40000] avg loss:0.001858 iterations:[5523/40000] avg loss:0.001614 iterations:[6076/40000] avg loss:0.001406 iterations:[6685/40000] avg loss:0.001228 iterations:[7357/40000] avg loss:0.001124 iterations:[8092/40000] avg loss:0.001018 iterations:[8897/40000] avg loss:0.000920 iterations:[9793/40000] avg loss:0.000854 iterations:[10766/40000] avg loss:0.000783 iterations:[11844/40000] avg loss:0.000728 iterations:[13034/40000] avg loss:0.000680 iterations:[14336/40000] avg loss:0.000637 iterations:[15771/40000] avg loss:0.000600 iterations:[17346/40000] avg loss:0.000563 iterations:[19082/40000] avg loss:0.000526 iterations:[20993/40000] avg loss:0.000504 iterations:[23086/40000] avg loss:0.000477 iterations:[25396/40000] avg loss:0.000455 iterations:[27937/40000] avg loss:0.000442 iterations:[30730/40000] avg loss:0.000421 iterations:[33810/40000] avg loss:0.000406 iterations:[37191/40000] avg loss:0.000392 iterations:[40000/40000] avg loss:0.000380 ```python # ---------------------------- 绘图 ------------------------ # 探测碰撞 real_address_heatmap = np.zeros((expend_dim, hash_number)) for train_sample in train_x_list: pred_y = my_cmac.forward(train_sample) real_address_heatmap[range(0, my_cmac.expend_dim), my_cmac.real_vector.reshape(-1)-1] += 1 plt.figure(figsize=(30, 10)) plt.title("Collisions") sn.heatmap(real_address_heatmap) plt.show() # 绘制训练过程图 fig = plt.figure(figsize=(20, 20)) for i in range(len(train_loss_dict)): plt.cla() plt.clf() ax1 = fig.add_subplot(2, 2, 1, projection='3d') ax1.set_title("Ground True", fontsize=20) plt.xticks(fontsize=20) plt.yticks(fontsize=20) ax1.tick_params(axis='z', labelsize=20) ax1.set_zlim(-1, 1) ax1.plot_surface(x1, x2, np.sin(x1) * np.cos(x2), cmap="rainbow") ax2 = fig.add_subplot(2, 2, 2, projection='3d') ax2.set_title("Pred", fontsize=20) plt.xticks(fontsize=20) plt.yticks(fontsize=20) ax2.tick_params(axis='z', labelsize=20) ax2.set_zlim(-1, 1) ax2.plot_surface(x1, x2, train_pred_recoder[i].reshape((sample_resolution, sample_resolution)), cmap="rainbow") ax3 = fig.add_subplot(2, 2, 3) ax3.set_title("loss & iteration:{}".format(list(train_loss_dict.keys())[i]), fontsize=20) ax3.set_xlabel("iterations", fontsize=20) ax3.set_ylabel("loss", fontsize=20) plt.xticks(fontsize=20) plt.yticks(fontsize=20) ax3.plot(list(train_loss_dict.keys())[:i], list(train_loss_dict.values())[:i]) ax3.set_aspect(1.0/ax3.get_data_ratio(), adjustable="box") ax4 = fig.add_subplot(2, 2, 4) ax4.set_title("weight params & iteration:{}".format(list(train_loss_dict.keys())[i]), fontsize=20) plt.xticks(fontsize=20) plt.yticks(fontsize=20) sn.heatmap(params_recoder[i], vmax=0.1, vmin=-0.1, cmap="YlGnBu") plt.savefig("./images/temp/{}.png".format(i), dpi=70) plt.show() with imageio.get_writer("./images/{}.gif".format("CMAC_sin_cos"), mode="I", fps=10) as Writer: for ind in range(len(train_loss_dict)): image = imageio.imread("./images/temp/{}.png".format(ind)) os.remove("./images/temp/{}.png".format(ind)) Writer.append_data(image) ```
Formal statement is: lemmas prime_exp = prime_elem_power_iff[where ?'a = nat] Informal statement is: A natural number is prime if and only if it is a prime power.
/- Even more induction! -/ variable (r : α → α → Prop) -- The reflexive transitive closure of `r` as an inductive predicate inductive RTC : α → α → Prop where -- Notice how declaring `r` as a `variable` instead of as a parameter instead of declaring it -- directly as a parameter of `RTC` means we don't have to write `RTC r a a` inside the -- declaration of `RTC`. This also works with recursive `def`s! | refl : RTC a a | trans : r a b → RTC b c → RTC a c -- We have arbitrarily chosen a "left-biased" definition of `RTC.trans`, but can easily show the -- mirror version by induction on the predicate theorem RTC.trans' : RTC r a b → r b c → RTC r a c := by intros hab hbc induction hab with | refl => exact RTC.trans hbc RTC.refl -- `a/b/c` in the constructor `RTC.trans` are marked as *implicit* because we didn't specify them -- explicitly. -- Just like in other contexts, we can use `@` to specify/match implicit parameters in `induction`. | @trans a a' b haa' ha'b ih => exact RTC.trans haa' (ih hbc) open Nat -- By the way, we can leave out `:= fun p1 ... => match p1, ... with` at `def` def double : Nat → Nat | zero => 0 | succ n => succ (succ (double n)) theorem double.inj : double n = double m → n = m := by intro h -- Try to finish this proof. You might find that the inductive case is impossible to solve! -- Do you see a different approach? If not, read on! induction n generalizing m with/-SOL-/ | zero => cases m <;> trivial | succ n ih => cases m with | zero => contradiction | succ m => simp only [double] at h injection h with h injection h with h rw [ih h] -- alternatively: --apply congrArg --apply ih -- -- with `simp_all` we sometimes have to exclude "problematic" assumptions such as `ih` from fixpoint simplification --simp_all [-ih, double] -- The issue with the above approach is that our inductive hypothesis is not sufficiently general! -- When we begin induction, we have already fixed (introduced) a particular `m`, but for the inductive -- step we need the inductive hypothesis for a *different* m. -- We could avoid this by carefully introducing `m` (and `h`, which depends on it) only after `induction`: -- ``` -- theorem double.inj : ∀ m, double n = double m → n = m := by -- induction n with -- | zero => intro m h; ... -- ... -- ``` -- `induction` even allows us to apply a tactic before *each* case: -- ``` -- theorem double.inj : ∀ m, double n = double m → n = m := by -- induction n with -- intro m h -- | zero => ... -- ... -- ``` -- However, it turns out that we do not have to change the theorem statement at all: if we simply say -- ``` -- induction n generalizing m with -- ``` -- then `induction` will automatically `revert` (yes, that's also a tactic) and re`intro`duce the variable(s) -- before/after induction for us! So add `generalizing m` above, see how the inductive hypothesis is -- affected, and then go finish that proof! /- Partial & dependent maps -/ -- *Partial maps* are a useful data type for the semantics project and many other topics. -- They map *some* keys of one type to values of another type. abbrev Map (α β : Type) := α → Option β -- We express partiality via the `Option` type, which either holds `some b` for `b : β`, or `none`. -- Ctrl+click it for the whole definition. namespace Map def empty : Map α β := fun k => none -- If we wanted a partial map for programming, we might choose a more efficient implementation such -- as a search tree or a hash map. If, on the other hand, we are only interested in using it in a -- formalization, a simple function like above is usually the simpler solution. For example, a -- simple typing context `Γ` can be formalized as a partial map from variable names to their types. -- The function-based definition makes defining operations such as a map update quite easy: /-- Set the entry `k` of the map `m` to the value `v`. All other entries are unchanged. -/ def update [DecidableEq α] (m : Map α β) (k : α) (v : Option β) : Map α β := fun k' => if k = k' then v else m k' -- A `scoped` notation is activated only when opening/inside the current namespace scoped notation:max m "[" k " ↦ " v "]" => update m k v theorem apply_update [DecidableEq α] (m : Map α β) : m[k ↦ v] k = v := by simp [update] -- hint: use function extensionality (`apply funext`) theorem update_self [DecidableEq α] (m : Map α β) : m[k ↦ m k] = m := by funext k' -- an abbreviation for `apply funext; intro k'` byCases h : k = k' <;> simp [update, h] end Map -- One interesting generalization of partial maps we can express in Lean are *dependent maps* where -- the *type* of the value may depend on the key: abbrev DepMap (α : Type) (β : α → Type) := (k : α) → Option (β k) namespace DepMap def empty : DepMap α β := fun k => none -- If we try to define `update` as above, it turns out that we run into a type error! -- You may want to use the "dependent if" `if h : p then t else e` that makes a *proof* of -- the condition `p` available in each branch: `h : p` in the `then` branch and `h : ¬p` in the -- `else` branch. You should then be able to use rewriting (e.g. `▸`) to fix the type error. def update [DecidableEq α] (m : DepMap α β) (k : α) (v : Option (β k)) : DepMap α β := fun k' => if h : k = k' then h ▸ v else m k' local notation:max m "[" k " ↦ " v "]" => update m k v -- This one should be as before... theorem apply_update [DecidableEq α] (m : DepMap α β) : m[k ↦ v] k = v := by simp [update] -- ...but this one is where the fun starts: try replicating the corresponding `Map` proof... theorem update_self [DecidableEq α] (m : DepMap α β) : m[k ↦ m k] = m := by funext k' byCases h : k = k' case inl => rw [h] simp [update] case inr => simp [update, h] -- and you should end up with an unsolved goal containing a subterm of the shape `(_ : a = b) ▸ c`. This -- is the rewrite from `update`; the proof is elided as `_` by default because, as we said in week 1, Lean -- considers all proofs of a proposition as equal, so we really don't care what proof is displayed there. -- So how do we get rid of the `▸`? We know it is something like a match on `Eq.refl`; more formally, -- both `▸` and such a match compile down to an application of `Eq`'s *recursor* (week 3). -- We know matches/recursors reduce ("go away") when applied to a matching constructor application, -- i.e. for `▸` we have `(rfl ▸ c) ≡ c`. -- So why didn't `simp` reduce away `(_ : a = b) ▸` if it works for `rfl` and all proofs are the same? -- Well, all proofs of a *single* proposition are the same, but `rfl` is not a proof of `a = b` unless -- `a` and `b` are in fact the same term! Thus the general way to get rid of `(_ : a = b) ▸` is to -- first rewrite the goal with a proof of the very equality `a = b`. After that, `simp`, or definitional -- equality in general, will get rid of the `▸`. -- Now, for technical reasons we should use `rw` instead of `simp` itself to do this rewrite. The short -- answer as to why that is is that `simp` tries to be *too clever* in this case: it will rewrite `a = b` -- on both sides of the `▸` individually, which usually makes it more flexible (week 4, slide pages 17 & 20), -- but in this case unfortunately leads to a type-incorrect proof. The "naive" strategy of `rw`, which will -- simply replace all `a` with `b` everywhere simultaneously by applying the `Eq` recursor once at the root, -- turns out to be the better approach in this case. -- Phew, that was a lot of typing (in the theoretic sense and on my keyboard). If you can't get the proof to -- work, don't worry about it, we will not bother you with this kind of "esoteric" proof again. If, on the -- other hand, you are interested in this kind of strong dependent typing, we may have an interesting variant -- of the semantics project to offer you next week! end DepMap open List Nat /- Insertion Sort -/ -- We want to implement insertion sort in Lean and show that the resulting `List` is indeed sorted. -- To that end, we first assume that the type `α` is of the type class `LE`, meaning that we can use -- the symbol `≤` (\le) as notation. -- We also assume (notice that cool dot notation) that this relation is decidable: variable [LE α] [DecidableRel ((· ≤ ·) : α → α → Prop)] -- First, we want to define a predicate that holds if a list is sorted. -- The predicate should have three constructors: -- The empty list `[]` and the single element list `[a]` are sorted, -- and we can add `a` to the front of a sorted list `b :: l`, if `a ≤ b`.s inductive Sorted : List α → Prop where | nil : Sorted [] | single : Sorted [a] | cons_cons : a ≤ b → Sorted (b::l) → Sorted (a::b::l) -- The main ingredient to insertion sort is a function `insertInOrder` which inserts -- a given element `a` before the first entry `x` of a list for which `a ≤ x` holds. -- Define that function by recursion on the list. Remember that `≤` is decidable. def insertInOrder (a : α) (xs : List α) : List α := match xs with | [] => [a] | x :: xs => if a ≤ x then a :: x :: xs else x :: insertInOrder a xs -- Now, see whether the function actually does what it should do. #eval insertInOrder 4 [1, 3, 4, 6, 7] #eval insertInOrder 4 [1, 2, 3] -- Defining `insertionSort` itself is now an easy recursion. def insertionSort (xs : List α) : List α := match xs with | [] => [] | x :: xs => insertInOrder x (insertionSort xs) -- Let's test the sorting algorithm next. #eval insertionSort [6, 2, 4, 4, 1, 3, 64] #eval insertionSort [1, 2, 3] #eval insertionSort (repeat (fun xs => xs.length :: xs) 500 []) -- Now we want to move on to actually verify that the algorithm does what it claims to do! -- To prove this, we don't need the relation to be transitive, but we need to assume the following property: variable (antisymm : ∀ {x y : α}, ¬ x ≤ y → (y ≤ x)) -- Okay, now prove the statement itself! -- Hints: -- * You might at one point have the choice to either apply induction on a list or on a witness of `Sorted`. -- Choose wisely. -- * Remember the tactic `byCases` from the fifth exercise! theorem sorted_insertInOrder {xs : List α} (h : Sorted xs) : Sorted (insertInOrder x xs) := by induction h with | nil => exact Sorted.single | @single a => simp only [insertInOrder] byCases hxa : x ≤ a <;> simp only [hxa] case inl => exact Sorted.cons_cons hxa Sorted.single case inr => exact Sorted.cons_cons (antisymm hxa) Sorted.single | @cons_cons a b l hab hbl ih => simp only [insertInOrder] byCases hxa : x ≤ a <;> simp only [hxa] case inl => exact Sorted.cons_cons hxa (Sorted.cons_cons hab hbl) case inr => byCases hxb : x ≤ b <;> simp only [hxb] case inl => exact Sorted.cons_cons (antisymm hxa) (Sorted.cons_cons hxb hbl) case inr => simp only [insertInOrder, hxb] at ih exact Sorted.cons_cons hab ih theorem sorted_insertionSort (as : List α) : Sorted (insertionSort as) := match as with | [] => Sorted.nil | x :: xs => sorted_insertInOrder antisymm (sorted_insertionSort xs) -- Here's a "soft" question: Have we now fully verified that `insertionSort` is a sorting algorithm? -- What other property would be an obvious one to verify? /- We need to show that the resulting list is a permutation of the input. Otherwise, `insertionSort (as : List α) := []` would be a valid sorting algorithm. -/
The other candidate for the rarest from that mint is the 1861 @-@ D , with an estimated mintage of 1 @,@ 000 and perhaps 45 to 60 known . Two pairs of dies were shipped from Philadelphia to Dahlonega on December 10 , 1860 ; they arrived on January 7 , 1861 , two weeks before Georgia voted to secede from the Union , as the American Civil War began . Under orders from Governor Joseph E. Brown , state militia secured the mint , and at some point , small quantities of dollars and half eagles were produced . Records of how many coins were struck and when have not survived . Since dies crack in time , and all the mints were supplied with them from Philadelphia , coining could not last , and in May 1861 , coins and supplies remaining at Dahlonega were turned over to the treasury of the Confederate States of America , which Georgia had by then joined . Gold coins with a face value of $ 6 were put aside for assay . Normally , they would have been sent to Philadelphia to await the following year 's meeting of the United States Assay Commission , when they would be available for testing . Instead , these were sent to the initial Confederate capital of Montgomery , Alabama , though what was done with them there , and their ultimate fate , are unknown . The rarity of the 1861 @-@ D dollar , and the association with the Confederacy , make it especially prized .
(* Title: HOL/Number_Theory/Residues.thy Author: Jeremy Avigad An algebraic treatment of residue rings, and resulting proofs of Euler's theorem and Wilson's theorem. *) section \<open>Residue rings\<close> theory Residues imports Cong MiscAlgebra begin definition QuadRes :: "int \<Rightarrow> int \<Rightarrow> bool" where "QuadRes p a = (\<exists>y. ([y^2 = a] (mod p)))" definition Legendre :: "int \<Rightarrow> int \<Rightarrow> int" where "Legendre a p = (if ([a = 0] (mod p)) then 0 else if QuadRes p a then 1 else -1)" subsection \<open>A locale for residue rings\<close> definition residue_ring :: "int \<Rightarrow> int ring" where "residue_ring m = \<lparr>carrier = {0..m - 1}, mult = \<lambda>x y. (x * y) mod m, one = 1, zero = 0, add = \<lambda>x y. (x + y) mod m\<rparr>" locale residues = fixes m :: int and R (structure) assumes m_gt_one: "m > 1" defines "R \<equiv> residue_ring m" begin lemma abelian_group: "abelian_group R" apply (insert m_gt_one) apply (rule abelian_groupI) apply (unfold R_def residue_ring_def) apply (auto simp add: mod_add_right_eq [symmetric] ac_simps) apply (case_tac "x = 0") apply force apply (subgoal_tac "(x + (m - x)) mod m = 0") apply (erule bexI) apply auto done lemma comm_monoid: "comm_monoid R" apply (insert m_gt_one) apply (unfold R_def residue_ring_def) apply (rule comm_monoidI) apply auto apply (subgoal_tac "x * y mod m * z mod m = z * (x * y mod m) mod m") apply (erule ssubst) apply (subst mod_mult_right_eq [symmetric])+ apply (simp_all only: ac_simps) done lemma cring: "cring R" apply (rule cringI) apply (rule abelian_group) apply (rule comm_monoid) apply (unfold R_def residue_ring_def, auto) apply (subst mod_add_eq [symmetric]) apply (subst mult.commute) apply (subst mod_mult_right_eq [symmetric]) apply (simp add: field_simps) done end sublocale residues < cring by (rule cring) context residues begin text \<open> These lemmas translate back and forth between internal and external concepts. \<close> lemma res_carrier_eq: "carrier R = {0..m - 1}" unfolding R_def residue_ring_def by auto lemma res_add_eq: "x \<oplus> y = (x + y) mod m" unfolding R_def residue_ring_def by auto lemma res_mult_eq: "x \<otimes> y = (x * y) mod m" unfolding R_def residue_ring_def by auto lemma res_zero_eq: "\<zero> = 0" unfolding R_def residue_ring_def by auto lemma res_one_eq: "\<one> = 1" unfolding R_def residue_ring_def units_of_def by auto lemma res_units_eq: "Units R = {x. 0 < x \<and> x < m \<and> coprime x m}" apply (insert m_gt_one) apply (unfold Units_def R_def residue_ring_def) apply auto apply (subgoal_tac "x \<noteq> 0") apply auto apply (metis invertible_coprime_int) apply (subst (asm) coprime_iff_invertible'_int) apply (auto simp add: cong_int_def mult.commute) done lemma res_neg_eq: "\<ominus> x = (- x) mod m" apply (insert m_gt_one) apply (unfold R_def a_inv_def m_inv_def residue_ring_def) apply auto apply (rule the_equality) apply auto apply (subst mod_add_right_eq [symmetric]) apply auto apply (subst mod_add_left_eq [symmetric]) apply auto apply (subgoal_tac "y mod m = - x mod m") apply simp apply (metis minus_add_cancel mod_mult_self1 mult.commute) done lemma finite [iff]: "finite (carrier R)" by (subst res_carrier_eq) auto lemma finite_Units [iff]: "finite (Units R)" by (subst res_units_eq) auto text \<open> The function \<open>a \<mapsto> a mod m\<close> maps the integers to the residue classes. The following lemmas show that this mapping respects addition and multiplication on the integers. \<close> lemma mod_in_carrier [iff]: "a mod m \<in> carrier R" unfolding res_carrier_eq using insert m_gt_one by auto lemma add_cong: "(x mod m) \<oplus> (y mod m) = (x + y) mod m" unfolding R_def residue_ring_def apply auto apply presburger done lemma mult_cong: "(x mod m) \<otimes> (y mod m) = (x * y) mod m" unfolding R_def residue_ring_def by auto (metis mod_mult_eq) lemma zero_cong: "\<zero> = 0" unfolding R_def residue_ring_def by auto lemma one_cong: "\<one> = 1 mod m" using m_gt_one unfolding R_def residue_ring_def by auto (* FIXME revise algebra library to use 1? *) lemma pow_cong: "(x mod m) (^) n = x^n mod m" apply (insert m_gt_one) apply (induct n) apply (auto simp add: nat_pow_def one_cong) apply (metis mult.commute mult_cong) done lemma neg_cong: "\<ominus> (x mod m) = (- x) mod m" by (metis mod_minus_eq res_neg_eq) lemma (in residues) prod_cong: "finite A \<Longrightarrow> (\<Otimes>i\<in>A. (f i) mod m) = (\<Prod>i\<in>A. f i) mod m" by (induct set: finite) (auto simp: one_cong mult_cong) lemma (in residues) sum_cong: "finite A \<Longrightarrow> (\<Oplus>i\<in>A. (f i) mod m) = (\<Sum>i\<in>A. f i) mod m" by (induct set: finite) (auto simp: zero_cong add_cong) lemma mod_in_res_units [simp]: assumes "1 < m" and "coprime a m" shows "a mod m \<in> Units R" proof (cases "a mod m = 0") case True with assms show ?thesis by (auto simp add: res_units_eq gcd_red_int [symmetric]) next case False from assms have "0 < m" by simp with pos_mod_sign [of m a] have "0 \<le> a mod m" . with False have "0 < a mod m" by simp with assms show ?thesis by (auto simp add: res_units_eq gcd_red_int [symmetric] ac_simps) qed lemma res_eq_to_cong: "(a mod m) = (b mod m) \<longleftrightarrow> [a = b] (mod m)" unfolding cong_int_def by auto text \<open>Simplifying with these will translate a ring equation in R to a congruence.\<close> lemmas res_to_cong_simps = add_cong mult_cong pow_cong one_cong prod_cong sum_cong neg_cong res_eq_to_cong text \<open>Other useful facts about the residue ring.\<close> lemma one_eq_neg_one: "\<one> = \<ominus> \<one> \<Longrightarrow> m = 2" apply (simp add: res_one_eq res_neg_eq) apply (metis add.commute add_diff_cancel mod_mod_trivial one_add_one uminus_add_conv_diff zero_neq_one zmod_zminus1_eq_if) done end subsection \<open>Prime residues\<close> locale residues_prime = fixes p :: nat and R (structure) assumes p_prime [intro]: "prime p" defines "R \<equiv> residue_ring (int p)" sublocale residues_prime < residues p apply (unfold R_def residues_def) using p_prime apply auto apply (metis (full_types) of_nat_1 of_nat_less_iff prime_gt_1_nat) done context residues_prime begin lemma is_field: "field R" apply (rule cring.field_intro2) apply (rule cring) apply (auto simp add: res_carrier_eq res_one_eq res_zero_eq res_units_eq) apply (rule classical) apply (erule notE) apply (subst gcd.commute) apply (rule prime_imp_coprime_int) apply (simp add: p_prime) apply (rule notI) apply (frule zdvd_imp_le) apply auto done lemma res_prime_units_eq: "Units R = {1..p - 1}" apply (subst res_units_eq) apply auto apply (subst gcd.commute) apply (auto simp add: p_prime prime_imp_coprime_int zdvd_not_zless) done end sublocale residues_prime < field by (rule is_field) section \<open>Test cases: Euler's theorem and Wilson's theorem\<close> subsection \<open>Euler's theorem\<close> text \<open>The definition of the phi function.\<close> definition phi :: "int \<Rightarrow> nat" where "phi m = card {x. 0 < x \<and> x < m \<and> gcd x m = 1}" lemma phi_def_nat: "phi m = card {x. 0 < x \<and> x < nat m \<and> gcd x (nat m) = 1}" apply (simp add: phi_def) apply (rule bij_betw_same_card [of nat]) apply (auto simp add: inj_on_def bij_betw_def image_def) apply (metis dual_order.irrefl dual_order.strict_trans leI nat_1 transfer_nat_int_gcd(1)) apply (metis One_nat_def of_nat_0 of_nat_1 of_nat_less_0_iff int_nat_eq nat_int transfer_int_nat_gcd(1) of_nat_less_iff) done lemma prime_phi: assumes "2 \<le> p" "phi p = p - 1" shows "prime p" proof - have *: "{x. 0 < x \<and> x < p \<and> coprime x p} = {1..p - 1}" using assms unfolding phi_def_nat by (intro card_seteq) fastforce+ have False if **: "1 < x" "x < p" and "x dvd p" for x :: nat proof - from * have cop: "x \<in> {1..p - 1} \<Longrightarrow> coprime x p" by blast have "coprime x p" apply (rule cop) using ** apply auto done with \<open>x dvd p\<close> \<open>1 < x\<close> show ?thesis by auto qed then show ?thesis using \<open>2 \<le> p\<close> by (simp add: prime_nat_iff) (metis One_nat_def dvd_pos_nat nat_dvd_not_less nat_neq_iff not_gr0 not_numeral_le_zero one_dvd) qed lemma phi_zero [simp]: "phi 0 = 0" unfolding phi_def (* Auto hangs here. Once again, where is the simplification rule 1 \<equiv> Suc 0 coming from? *) apply (auto simp add: card_eq_0_iff) (* Add card_eq_0_iff as a simp rule? delete card_empty_imp? *) done lemma phi_one [simp]: "phi 1 = 0" by (auto simp add: phi_def card_eq_0_iff) lemma (in residues) phi_eq: "phi m = card (Units R)" by (simp add: phi_def res_units_eq) lemma (in residues) euler_theorem1: assumes a: "gcd a m = 1" shows "[a^phi m = 1] (mod m)" proof - from a m_gt_one have [simp]: "a mod m \<in> Units R" by (intro mod_in_res_units) from phi_eq have "(a mod m) (^) (phi m) = (a mod m) (^) (card (Units R))" by simp also have "\<dots> = \<one>" by (intro units_power_order_eq_one) auto finally show ?thesis by (simp add: res_to_cong_simps) qed (* In fact, there is a two line proof! lemma (in residues) euler_theorem1: assumes a: "gcd a m = 1" shows "[a^phi m = 1] (mod m)" proof - have "(a mod m) (^) (phi m) = \<one>" by (simp add: phi_eq units_power_order_eq_one a m_gt_one) then show ?thesis by (simp add: res_to_cong_simps) qed *) text \<open>Outside the locale, we can relax the restriction \<open>m > 1\<close>.\<close> lemma euler_theorem: assumes "m \<ge> 0" and "gcd a m = 1" shows "[a^phi m = 1] (mod m)" proof (cases "m = 0 | m = 1") case True then show ?thesis by auto next case False with assms show ?thesis by (intro residues.euler_theorem1, unfold residues_def, auto) qed lemma (in residues_prime) phi_prime: "phi p = nat p - 1" apply (subst phi_eq) apply (subst res_prime_units_eq) apply auto done lemma phi_prime: "prime (int p) \<Longrightarrow> phi p = nat p - 1" apply (rule residues_prime.phi_prime) apply simp apply (erule residues_prime.intro) done lemma fermat_theorem: fixes a :: int assumes "prime (int p)" and "\<not> p dvd a" shows "[a^(p - 1) = 1] (mod p)" proof - from assms have "[a ^ phi p = 1] (mod p)" by (auto intro!: euler_theorem intro!: prime_imp_coprime_int[of p] simp: gcd.commute[of _ "int p"]) also have "phi p = nat p - 1" by (rule phi_prime) (rule assms) finally show ?thesis by (metis nat_int) qed lemma fermat_theorem_nat: assumes "prime (int p)" and "\<not> p dvd a" shows "[a ^ (p - 1) = 1] (mod p)" using fermat_theorem [of p a] assms by (metis of_nat_1 of_nat_power transfer_int_nat_cong zdvd_int) subsection \<open>Wilson's theorem\<close> lemma (in field) inv_pair_lemma: "x \<in> Units R \<Longrightarrow> y \<in> Units R \<Longrightarrow> {x, inv x} \<noteq> {y, inv y} \<Longrightarrow> {x, inv x} \<inter> {y, inv y} = {}" apply auto apply (metis Units_inv_inv)+ done lemma (in residues_prime) wilson_theorem1: assumes a: "p > 2" shows "[fact (p - 1) = (-1::int)] (mod p)" proof - let ?Inverse_Pairs = "{{x, inv x}| x. x \<in> Units R - {\<one>, \<ominus> \<one>}}" have UR: "Units R = {\<one>, \<ominus> \<one>} \<union> \<Union>?Inverse_Pairs" by auto have "(\<Otimes>i\<in>Units R. i) = (\<Otimes>i\<in>{\<one>, \<ominus> \<one>}. i) \<otimes> (\<Otimes>i\<in>\<Union>?Inverse_Pairs. i)" apply (subst UR) apply (subst finprod_Un_disjoint) apply (auto intro: funcsetI) using inv_one apply auto[1] using inv_eq_neg_one_eq apply auto done also have "(\<Otimes>i\<in>{\<one>, \<ominus> \<one>}. i) = \<ominus> \<one>" apply (subst finprod_insert) apply auto apply (frule one_eq_neg_one) using a apply force done also have "(\<Otimes>i\<in>(\<Union>?Inverse_Pairs). i) = (\<Otimes>A\<in>?Inverse_Pairs. (\<Otimes>y\<in>A. y))" apply (subst finprod_Union_disjoint) apply auto apply (metis Units_inv_inv)+ done also have "\<dots> = \<one>" apply (rule finprod_one) apply auto apply (subst finprod_insert) apply auto apply (metis inv_eq_self) done finally have "(\<Otimes>i\<in>Units R. i) = \<ominus> \<one>" by simp also have "(\<Otimes>i\<in>Units R. i) = (\<Otimes>i\<in>Units R. i mod p)" apply (rule finprod_cong') apply auto apply (subst (asm) res_prime_units_eq) apply auto done also have "\<dots> = (\<Prod>i\<in>Units R. i) mod p" apply (rule prod_cong) apply auto done also have "\<dots> = fact (p - 1) mod p" apply (simp add: fact_prod) apply (insert assms) apply (subst res_prime_units_eq) apply (simp add: int_prod zmod_int prod_int_eq) done finally have "fact (p - 1) mod p = \<ominus> \<one>" . then show ?thesis by (metis of_nat_fact Divides.transfer_int_nat_functions(2) cong_int_def res_neg_eq res_one_eq) qed lemma wilson_theorem: assumes "prime p" shows "[fact (p - 1) = - 1] (mod p)" proof (cases "p = 2") case True then show ?thesis by (simp add: cong_int_def fact_prod) next case False then show ?thesis using assms prime_ge_2_nat by (metis residues_prime.wilson_theorem1 residues_prime.intro le_eq_less_or_eq) qed end
function [MHz] = rpm2MHz(rpm) % Convert frequency from revolutions per minute to Megahertz. % Chad A. Greene 2012 MHz = rpm/60/1000000;
Townsend 's solo albums , a diverse mix of hard rock , progressive metal , ambient , and new @-@ age , have featured a varying lineup of supporting musicians . In 2002 he formed the Devin Townsend Band , a dedicated lineup which recorded and toured for two of his solo releases . In 2007 , he disbanded both Strapping Young Lad and the Devin Townsend Band , taking a break from touring to spend more time with his family . After a two @-@ year hiatus , he began recording again , and soon announced the formation of the Devin Townsend Project . The project began with a series of four albums , released from 2009 to 2011 , each written in a different style , and Townsend continues to record and tour under the new moniker .
module Base.Change.Sums where open import Data.Sum open import Data.Product open import Relation.Binary.PropositionalEquality open import Level open import Base.Ascription open import Base.Change.Algebra open import Base.Change.Equivalence open import Base.Change.Equivalence.Realizers open import Postulate.Extensionality module SumChanges ℓ {X Y : Set ℓ} {{CX : ChangeAlgebra X}} {{CY : ChangeAlgebra Y}} where open ≡-Reasoning -- This is an indexed datatype, so it has two constructors per argument. But -- erasure would probably not be smart enough to notice. -- Should we rewrite this as two separate datatypes? data SumChange : X ⊎ Y → Set ℓ where ch₁ : ∀ {x} → (dx : Δ x) → SumChange (inj₁ x) rp₁₂ : ∀ {x} → (y : Y) → SumChange (inj₁ x) ch₂ : ∀ {y} → (dy : Δ y) → SumChange (inj₂ y) rp₂₁ : ∀ {y} → (x : X) → SumChange (inj₂ y) _⊕_ : (v : X ⊎ Y) → SumChange v → X ⊎ Y inj₁ x ⊕ ch₁ dx = inj₁ (x ⊞ dx) inj₂ y ⊕ ch₂ dy = inj₂ (y ⊞ dy) inj₁ x ⊕ rp₁₂ y = inj₂ y inj₂ y ⊕ rp₂₁ x = inj₁ x _⊝_ : ∀ (v₂ v₁ : X ⊎ Y) → SumChange v₁ inj₁ x₂ ⊝ inj₁ x₁ = ch₁ (x₂ ⊟ x₁) inj₂ y₂ ⊝ inj₂ y₁ = ch₂ (y₂ ⊟ y₁) inj₂ y₂ ⊝ inj₁ x₁ = rp₁₂ y₂ inj₁ x₂ ⊝ inj₂ y₁ = rp₂₁ x₂ s-nil : (v : X ⊎ Y) → SumChange v s-nil (inj₁ x) = ch₁ (nil x) s-nil (inj₂ y) = ch₂ (nil y) s-update-diff : ∀ (u v : X ⊎ Y) → v ⊕ (u ⊝ v) ≡ u s-update-diff (inj₁ x₂) (inj₁ x₁) = cong inj₁ (update-diff x₂ x₁) s-update-diff (inj₂ y₂) (inj₂ y₁) = cong inj₂ (update-diff y₂ y₁) s-update-diff (inj₁ x₂) (inj₂ y₁) = refl s-update-diff (inj₂ y₂) (inj₁ x₁) = refl s-update-nil : ∀ v → v ⊕ (s-nil v) ≡ v s-update-nil (inj₁ x) = cong inj₁ (update-nil x) s-update-nil (inj₂ y) = cong inj₂ (update-nil y) instance changeAlgebraSums : ChangeAlgebra (X ⊎ Y) changeAlgebraSums = record { Change = SumChange ; update = _⊕_ ; diff = _⊝_ ; nil = s-nil ; isChangeAlgebra = record { update-diff = s-update-diff ; update-nil = s-update-nil } } inj₁′ : Δ (inj₁ as (X → (X ⊎ Y))) inj₁′ = nil inj₁ inj₁′-realizer : RawChange (inj₁ as (X → (X ⊎ Y))) inj₁′-realizer x dx = ch₁ dx inj₁′Derivative : IsDerivative (inj₁ as (X → (X ⊎ Y))) inj₁′-realizer inj₁′Derivative x dx = refl inj₁′-realizer-correct : ∀ a da → apply inj₁′ a da ≙₍ inj₁ a as (X ⊎ Y) ₎ inj₁′-realizer a da inj₁′-realizer-correct a da = diff-update inj₁′-faster-w-proof : equiv-raw-change-to-change-ResType inj₁ inj₁′-realizer inj₁′-faster-w-proof = equiv-raw-change-to-change inj₁ inj₁′ inj₁′-realizer inj₁′-realizer-correct inj₁′-faster : Δ inj₁ inj₁′-faster = proj₁ inj₁′-faster-w-proof inj₂′ : Δ (inj₂ as (Y → (X ⊎ Y))) inj₂′ = nil inj₂ inj₂′-realizer : RawChange (inj₂ as (Y → (X ⊎ Y))) inj₂′-realizer y dy = ch₂ dy inj₂′Derivative : IsDerivative (inj₂ as (Y → (X ⊎ Y))) inj₂′-realizer inj₂′Derivative y dy = refl inj₂′-realizer-correct : ∀ b db → apply inj₂′ b db ≙₍ inj₂ b as (X ⊎ Y) ₎ inj₂′-realizer b db inj₂′-realizer-correct b db = diff-update inj₂′-faster-w-proof : equiv-raw-change-to-change-ResType inj₂ inj₂′-realizer inj₂′-faster-w-proof = equiv-raw-change-to-change inj₂ inj₂′ inj₂′-realizer inj₂′-realizer-correct inj₂′-faster : Δ inj₂ inj₂′-faster = proj₁ inj₂′-faster-w-proof module _ {Z : Set ℓ} {{CZ : ChangeAlgebra Z}} where -- Elimination form for sums. This is a less dependently-typed version of -- [_,_]. match : (X → Z) → (Y → Z) → X ⊎ Y → Z match f g (inj₁ x) = f x match f g (inj₂ y) = g y match′ : Δ match match′ = nil match match′-realizer : (f : X → Z) → Δ f → (g : Y → Z) → Δ g → (s : X ⊎ Y) → Δ s → Δ (match f g s) match′-realizer f df g dg (inj₁ x) (ch₁ dx) = apply df x dx match′-realizer f df g dg (inj₁ x) (rp₁₂ y) = ((g ⊞ dg) y) ⊟ (f x) match′-realizer f df g dg (inj₂ y) (rp₂₁ x) = ((f ⊞ df) x) ⊟ (g y) match′-realizer f df g dg (inj₂ y) (ch₂ dy) = apply dg y dy match′-realizer-correct : (f : X → Z) → (df : Δ f) → (g : Y → Z) → (dg : Δ g) → (s : X ⊎ Y) → (ds : Δ s) → apply (apply (apply match′ f df) g dg) s ds ≙₍ match f g s ₎ match′-realizer f df g dg s ds match′-realizer-correct f df g dg (inj₁ x) (ch₁ dx) = ≙-incrementalization f df x dx match′-realizer-correct f df g dg (inj₁ x) (rp₁₂ y) = ≙-refl match′-realizer-correct f df g dg (inj₂ y) (ch₂ dy) = ≙-incrementalization g dg y dy match′-realizer-correct f df g dg (inj₂ y) (rp₂₁ x) = ≙-refl -- We need a ternary variant of the lemma here. match′-faster-w-proof : equiv-raw-change-to-change-ternary-ResType match match′-realizer match′-faster-w-proof = equiv-raw-change-to-change-ternary match match′ match′-realizer match′-realizer-correct match′-faster : Δ match match′-faster = proj₁ match′-faster-w-proof
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Jannis Limperg -/ /-! # Monadic instances for `ulift` and `plift` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define `monad` and `is_lawful_monad` instances on `plift` and `ulift`. -/ universes u v namespace plift variables {α : Sort u} {β : Sort v} /-- Functorial action. -/ protected def map (f : α → β) (a : plift α) : plift β := plift.up (f a.down) @[simp] /-- Embedding of pure values. -/ @[simp] protected def pure : α → plift α := up /-- Applicative sequencing. -/ protected def seq (f : plift (α → β)) (x : plift α) : plift β := plift.up (f.down x.down) @[simp] lemma seq_up (f : α → β) (x : α) : (plift.up f).seq (plift.up x) = plift.up (f x) := rfl /-- Monadic bind. -/ protected def bind (a : plift α) (f : α → plift β) : plift β := f a.down @[simp] lemma bind_up (a : α) (f : α → plift β) : (plift.up a).bind f = f a := rfl instance : monad plift := { map := @plift.map, pure := @plift.pure, seq := @plift.seq, bind := @plift.bind } instance : is_lawful_functor plift := { id_map := λ α ⟨x⟩, rfl, comp_map := λ α β γ g h ⟨x⟩, rfl } instance : is_lawful_applicative plift := { pure_seq_eq_map := λ α β g ⟨x⟩, rfl, map_pure := λ α β g x, rfl, seq_pure := λ α β ⟨g⟩ x, rfl, seq_assoc := λ α β γ ⟨x⟩ ⟨g⟩ ⟨h⟩, rfl } instance : is_lawful_monad plift := { bind_pure_comp_eq_map := λ α β f ⟨x⟩, rfl, bind_map_eq_seq := λ α β ⟨a⟩ ⟨b⟩, rfl, pure_bind := λ α β x f, rfl, bind_assoc := λ α β γ ⟨x⟩ f g, rfl } @[simp] lemma rec.constant {α : Sort u} {β : Type v} (b : β) : @plift.rec α (λ _, β) (λ _, b) = λ _, b := funext (λ x, plift.cases_on x (λ a, eq.refl (plift.rec (λ a', b) {down := a}))) end plift namespace ulift variables {α : Type u} {β : Type v} /-- Functorial action. -/ protected def map (f : α → β) (a : ulift α) : ulift β := ulift.up (f a.down) @[simp] lemma map_up (f : α → β) (a : α) : (ulift.up a).map f = ulift.up (f a) := rfl /-- Embedding of pure values. -/ @[simp] protected def pure : α → ulift α := up /-- Applicative sequencing. -/ protected def seq (f : ulift (α → β)) (x : ulift α) : ulift β := ulift.up (f.down x.down) @[simp] lemma seq_up (f : α → β) (x : α) : (ulift.up f).seq (ulift.up x) = ulift.up (f x) := rfl /-- Monadic bind. -/ protected def bind (a : ulift α) (f : α → ulift β) : ulift β := f a.down @[simp] lemma bind_up (a : α) (f : α → ulift β) : (ulift.up a).bind f = f a := rfl instance : monad ulift := { map := @ulift.map, pure := @ulift.pure, seq := @ulift.seq, bind := @ulift.bind } instance : is_lawful_functor ulift := { id_map := λ α ⟨x⟩, rfl, comp_map := λ α β γ g h ⟨x⟩, rfl } instance : is_lawful_applicative ulift := { to_is_lawful_functor := ulift.is_lawful_functor, pure_seq_eq_map := λ α β g ⟨x⟩, rfl, map_pure := λ α β g x, rfl, seq_pure := λ α β ⟨g⟩ x, rfl, seq_assoc := λ α β γ ⟨x⟩ ⟨g⟩ ⟨h⟩, rfl } instance : is_lawful_monad ulift := { bind_pure_comp_eq_map := λ α β f ⟨x⟩, rfl, bind_map_eq_seq := λ α β ⟨a⟩ ⟨b⟩, rfl, pure_bind := λ α β x f, by { dsimp only [bind, pure, ulift.pure, ulift.bind], cases (f x), refl }, bind_assoc := λ α β γ ⟨x⟩ f g, by { dsimp only [bind, pure, ulift.pure, ulift.bind], cases (f x), refl } } @[simp] lemma rec.constant {α : Type u} {β : Sort v} (b : β) : @ulift.rec α (λ _, β) (λ _, b) = λ _, b := funext (λ x, ulift.cases_on x (λ a, eq.refl (ulift.rec (λ a', b) {down := a}))) end ulift
lemma components_maximal: "\<lbrakk>c \<in> components s; connected t; t \<subseteq> s; c \<inter> t \<noteq> {}\<rbrakk> \<Longrightarrow> t \<subseteq> c"
\subsection{Life cycle of a ShowOff module} Upon launch, Launcher parses the command line. It decides that a ShowOff must be started. This will read the parameters stored in Psyclone. The available parameter names are: \begin{itemize} \item[Attractors] A comma-separated list of attractors which are specified as $\langle$name$\rangle$:$\langle$weight$\rangle$. \end{itemize} After this, the ShowOff goes into a waiting loop, expecting stories and analyses on their respective whiteboards. When a story is received, a particle is created, when an analysis is received, the accompanying story is searched for and the particle is updated accordingly (attraction parameters are updated). \begin{figure}[htp] \centering \includegraphics{design/image/sequence-diagram-showoff} \caption{Sequence diagram of a ShowOff module} \end{figure}
[STATEMENT] lemma clinear: "clinear f" [PROOF STATE] proof (prove) goal (1 subgoal): 1. clinear f [PROOF STEP] by (fact local.clinear_axioms)
{-# OPTIONS --cubical --safe #-} open import Prelude open import Relation.Binary module Relation.Binary.Construct.Decision {a ℓ₁ ℓ₂} {A : Type a} (ord : TotalOrder A ℓ₁ ℓ₂) where open TotalOrder ord renaming (refl to ≤-refl) _<′_ : A → A → Type x <′ y = T (does (x <? y)) _≤′_ : A → A → Type x ≤′ y = T (not (does (y <? x))) witness-< : ∀ {x y} → x <′ y → x < y witness-< {x} {y} p with x <? y witness-< {x} {y} p | yes q = q witness-≤ : ∀ {x y} → x ≤′ y → x ≤ y witness-≤ {x} {y} p with y <? x witness-≤ {x} {y} p | no q = ≮⇒≥ q compute-< : ∀ {x y} → x < y → x <′ y compute-< {x} {y} p with x <? y compute-< {x} {y} p | yes q = tt compute-< {x} {y} p | no ¬p = ⊥-elim (¬p p) compute-≤ : ∀ {x y} → x ≤ y → x ≤′ y compute-≤ {x} {y} ¬p with y <? x compute-≤ {x} {y} ¬p | yes p = ⊥-elim (<⇒≱ p ¬p) compute-≤ {x} {y} ¬p | no _ = tt ≰⇒>′ : ∀ {x y} → ¬ (x ≤′ y) → y <′ x ≰⇒>′ {x} {y} p with y <? x ≰⇒>′ {x} {y} p | no _ = p tt ≰⇒>′ {x} {y} p | yes _ = tt ≮⇒≥′ : ∀ {x y} → ¬ (x <′ y) → y ≤′ x ≮⇒≥′ {x} {y} p with x <? y ≮⇒≥′ {x} {y} p | no _ = tt ≮⇒≥′ {x} {y} p | yes _ = p tt dec-ord : TotalOrder A ℓzero ℓzero StrictPreorder._<_ (StrictPartialOrder.strictPreorder (TotalOrder.strictPartialOrder dec-ord)) = _<′_ StrictPreorder.trans (StrictPartialOrder.strictPreorder (TotalOrder.strictPartialOrder dec-ord)) p q = compute-< (<-trans (witness-< p) (witness-< q)) StrictPreorder.irrefl (StrictPartialOrder.strictPreorder (TotalOrder.strictPartialOrder dec-ord)) p = irrefl (witness-< p) StrictPartialOrder.conn (TotalOrder.strictPartialOrder dec-ord) p q = conn (p ∘ compute-<) (q ∘ compute-<) Preorder._≤_ (PartialOrder.preorder (TotalOrder.partialOrder dec-ord)) = _≤′_ Preorder.refl (PartialOrder.preorder (TotalOrder.partialOrder dec-ord)) = compute-≤ ≤-refl PartialOrder.antisym (TotalOrder.partialOrder dec-ord) p q = antisym (witness-≤ p) (witness-≤ q) Preorder.trans (PartialOrder.preorder (TotalOrder.partialOrder dec-ord)) p q = compute-≤ (≤-trans (witness-≤ p) (witness-≤ q)) TotalOrder._<?_ dec-ord x y = iff-dec (compute-< iff witness-<) (x <? y) TotalOrder.≰⇒> dec-ord = ≰⇒>′ TotalOrder.≮⇒≥ dec-ord = ≮⇒≥′
module Libraries.Utils.Binary import Data.Buffer import Data.List import System.File import Libraries.Utils.String -- Serialising data as binary. Provides an interface TTC which allows -- reading and writing to chunks of memory, "Binary", which can be written -- to and read from files. %default covering public export record Binary where constructor MkBin buf : Buffer loc : Int size : Int -- Capacity used : Int -- Amount used export newBinary : Buffer -> Int -> Binary newBinary b s = MkBin b 0 s 0 export blockSize : Int blockSize = 655360 export avail : Binary -> Int avail c = (size c - loc c) - 1 export toRead : Binary -> Int toRead c = used c - loc c export appended : Int -> Binary -> Binary appended i (MkBin b loc s used) = MkBin b (loc+i) s (used + i) export incLoc : Int -> Binary -> Binary incLoc i c = record { loc $= (+i) } c export dumpBin : Binary -> IO () dumpBin chunk = do -- printLn !(traverse bufferData (map buf done)) printLn !(bufferData (buf chunk)) -- printLn !(traverse bufferData (map buf rest)) export nonEmptyRev : {xs : _} -> NonEmpty (xs ++ y :: ys) nonEmptyRev {xs = []} = IsNonEmpty nonEmptyRev {xs = (x :: xs)} = IsNonEmpty export fromBuffer : Buffer -> IO Binary fromBuffer buf = do len <- rawSize buf pure (MkBin buf 0 len len) export writeToFile : (fname : String) -> Binary -> IO (Either FileError ()) writeToFile fname c = writeBufferToFile fname (buf c) (used c) export readFromFile : (fname : String) -> IO (Either FileError Binary) readFromFile fname = do Right b <- createBufferFromFile fname | Left err => pure (Left err) bsize <- rawSize b pure (Right (MkBin b 0 bsize bsize))
/* * Copyright (c) 2016-2021 lymastee, All rights reserved. * Contact: [email protected] * * This file is part of the gslib project. * * 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. */ #pragma once #ifndef base_type_2aa01495_7feb_4c5e_ae38_9c775c29c9f1_h #define base_type_2aa01495_7feb_4c5e_ae38_9c775c29c9f1_h #include <assert.h> #include <stdint.h> #include <gslib/config.h> __gslib_begin__ #ifdef _GS_X86 typedef int8_t int8; typedef int16_t int16; typedef int32_t int32; typedef int64_t int64; typedef wchar_t wchar; typedef float real32; typedef double real; typedef uint8_t byte; typedef uint16_t word; typedef uint32_t dword; typedef uint64_t qword; typedef uint32_t uint; typedef uint16_t uint16; typedef uint32_t uint32; typedef uint64_t uint64; typedef void* addrptr; #ifdef _UNICODE typedef wchar gchar; #else typedef char gchar; #endif template<class t> struct typeof { typedef void type; }; /* virtual class ptr convert tools */ template<class ccp, class bcp> inline int virtual_bias() { static typeof<ccp>::type c; static const int bias = (int)&c - (int)static_cast<bcp>(&c); return bias; } template<class ccp, class bcp> inline ccp virtual_cast(bcp p) { byte* ptr = (byte*)p; ptr += virtual_bias<ccp, bcp>(); return reinterpret_cast<ccp>(ptr); } #endif /* end of _GS_X86 */ template<class _ty> inline _ty gs_min(_ty a, _ty b) { return a < b ? a : b; } template<class _ty> inline _ty gs_max(_ty a, _ty b) { return a > b ? a : b; } template<class _ty> inline _ty gs_clamp(_ty v, _ty a, _ty b) { assert(a <= b); return gs_min(b, gs_max(a, v)); } template<class _ty> inline void gs_swap(_ty& a, _ty& b) { auto t = a; a = b; b = t; } __gslib_end__ #endif
Require Import A1_Plan A2_Orientation . Require Import C1_Distance . Require Import D1_IntersectionCirclesProp . Require Import F5_Tactics . Require Import G1_Angles. Section ANGLE_PROPERTIES. Lemma EqAngleUniquePointSide1 : forall A B C D : Point, CongruentAngle C A B D A B -> Distance A C = Distance A D -> ~Clockwise A C B -> ~Clockwise A D B -> C = D. Proof. intros. apply (EqThirdPoint A B). apply (CongruentAngleDistinctBC C A B D A B H) . immediate5. apply (CongruentSAS A B C A B D). immediate5. immediate5. apply CongruentAngleRev; immediate5. immediate5. immediate5. Qed. Lemma EqAngleUniquePointSide2 : forall A B C D : Point, CongruentAngle B A C B A D -> Distance A C = Distance A D -> ~Clockwise A B C -> ~Clockwise A B D -> C = D. Proof. intros. apply (EqThirdPoint B A). apply sym_not_eq; apply (CongruentAngleDistinctBA B A C B A D H). apply (CongruentSAS A B C A B D); immediate5. immediate5. immediate5. immediate5. Qed. Lemma EqAngleOpenRay1 : forall A B C D : Point, CongruentAngle C A B D A B -> ~Clockwise A C B -> ~Clockwise A D B -> OpenRay A C D. Proof. intros. setMarkSegmentPoint5 A D A C ipattern:(E). apply (CongruentAngleDistinctED C A B D A B H). since5 (C = E). apply (EqAngleUniquePointSide1 A B C E). apply (CongruentAngleTrans C A B D A B E A B). immediate5. apply CongruentAngleSide1. immediate5. apply (CongruentAngleDistinctBC C A B D A B H). step5 H4. step5 H3. apply (CongruentAngleDistinctBA C A B D A B H). immediate5. immediate5. intro; elim H1; step5 H4. rewrite H5; immediate5. Qed. Lemma EqAngleOpenRay2 : forall A B C D : Point, CongruentAngle B A C B A D -> ~Clockwise A B C -> ~Clockwise A B D -> OpenRay A C D. Proof. intros. setMarkSegmentPoint5 A D A C ipattern:(E). apply (CongruentAngleDistinctEF B A C B A D H). since5 (C = E). apply (EqAngleUniquePointSide2 A B C E). apply (CongruentAngleTrans B A C B A D B A E). immediate5. apply CongruentAngleSide2. apply (CongruentAngleDistinctBA B A C B A D H). immediate5. step5 H4. step5 H3. apply (CongruentAngleDistinctBC B A C B A D H). immediate5. immediate5. intro; elim H1; step5 H4. rewrite H5; immediate5. Qed. End ANGLE_PROPERTIES.
Require Export CatSem.CAT.retype_functor_po. Require Export CatSem.CAT.rmonad_gen_type_po. Require Export CatSem.CAT.TLC_types. Set Implicit Arguments. Unset Strict Implicit. Unset Transparent Obligations. Unset Automatic Introduction. Definition TY := TLC.types. Notation "'IP'" := (IPO TY). Notation "a '~>' b" := (TLC.arrow a b) (at level 69, right associativity). Notation "a 'x' b" := (product a b) (at level 30). Notation "M [ z ]" := (FIB_RMOD _ z M) (at level 35). Notation "'d' M // s" := (DER_RMOD _ _ s M) (at level 25). Notation "'*'" := (Term (C:=RMOD _ PO)). Notation "f 'X' g" := (product_mor _ f g)(at level 30). Notation "'FM'" := (#(FIB_RMOD _ _ )). Notation "'FPB'":= (FIB_RPB _ _ _ ). Notation "'PRPB'":= (PROD_RPB _ _ _ _ ). (*Notation "'PBF'":= (PB_FIB _ _ _ ).*) Notation "'PBM'":= (#(PbRMOD _ _ )). Notation "'DM'":= (#(DER_RMOD _ _ _ )). Notation "'DPB'":= (DER_RPB _ _ _ ). Notation "y [* := z ]":= (Rsubstar z _ y)(at level 55). Section TLC_rep. Variable U : Type. Variable P : RMonad (SM_ipo U). Variable f : TY -> U. (** a monad is a representation if it is accompagnied by - a lot of morphisms of modules - beta-reduction *) Class TLCPO_rep_struct := { App : forall r s, (P[f (r~>s)]) x (P[f r]) ---> P[f s]; Abs : forall r s, (d P //(f r))[f s] ---> P[f (r ~> s)]; beta_red : forall r s V y z, App r s V (Abs r s V y, z) << y[*:= z] ; propag_App1: forall r s V y y' z, y << y' -> App r s V (y,z) << App _ _ _ (y',z) ; propag_App2: forall r s V y z z', z << z' -> App r s V (y,z) << App _ _ _ (y,z') ; propag_Abs: forall r s V y y', y << y' -> Abs r s V y << Abs _ _ _ y' }. End TLC_rep. Record TLCPO_rep := { type_type : Type; tlc_rep_monad :> RMonad (SM_ipo type_type); type_mor : TY -> type_type; tlc_rep_struct :> TLCPO_rep_struct tlc_rep_monad type_mor }. Existing Instance tlc_rep_struct. (** morphisms of representations *) Section rep_hom. Variables P R : TLCPO_rep. Section Rep_Hom_Class. (** a morphism of representations - (U, f, P, Rep) - (U', f', Q, Rep') is given by - g : U -> U' - H : f ; g = f' - generalized monad morphism P -> Q (with F = RETYPE g) - properties *) Variable f : type_type P -> type_type R. Variable H : forall t, f (type_mor P t) = type_mor R t. Check gen_RMonad_Hom. Variable M : gen_RMonad_Hom P R (G1:=RETYPE f) (G2:=RETYPE_PO f) (NNNT1 f). Definition MM := gen_PbRMod_ind_Hom M. Check FFib_Mod_Hom. Check FIB_RMOD_HOM. Print FIB_RMOD_eq. Check (fun r s => FIB_RMOD_eq (gen_PbRMod M R) (H (r ~> s))). Check (fun r s => App (P:=P) r s ;; FIB_RMOD_HOM M _ ). Check (fun r s => App (P:=P) r s ;; FIB_RMOD_HOM M _ ;; FIB_RMOD_eq (gen_PbRMod M R) (H _) ;; gen_pb_fib _ _ _ ). Check (fun r s => product_mor _ (FIB_RMOD_HOM M (type_mor _ (r~>s)) ;; FIB_RMOD_eq _ (H _ );; gen_pb_fib _ _ _ ) (FIB_RMOD_HOM M (type_mor _ r) ;; FIB_RMOD_eq _ (H _ );; gen_pb_fib _ _ _ ) ;; gen_PROD_PM _ _ _ _ ;; gen_PbRMod_Hom _ (App r s)). Check FFib_DER_Mod_Hom_eqrect. Check der_fib_hom. Check (fun r s => der_fib_hom _ _ (H _ ) ;; FIB_RMOD_eq _ (H s);; gen_pb_fib _ _ _ ;; gen_PbRMod_Hom M (Abs r s)). Check (fun r s => Abs r s ;; FIB_RMOD_HOM M _ ;; FIB_RMOD_eq _ (H _ );; gen_pb_fib _ _ _ ). Class TLCPO_rep_Hom_struct := { App_Hom : forall r s, App (P:=P) r s ;; FIB_RMOD_HOM M _ ;; FIB_RMOD_eq (gen_PbRMod M R) (H _) ;; gen_pb_fib _ _ _ == product_mor _ (FIB_RMOD_HOM M (type_mor _ (r~>s)) ;; FIB_RMOD_eq _ (H _ );; gen_pb_fib _ _ _ ) (FIB_RMOD_HOM M (type_mor _ r) ;; FIB_RMOD_eq _ (H _ );; gen_pb_fib _ _ _ ) ;; gen_PROD_PM _ _ _ _ ;; gen_PbRMod_Hom _ (App r s) ; Abs_Hom : forall r s, der_fib_hom _ _ (H _ ) ;; FIB_RMOD_eq _ (H s);; gen_pb_fib _ _ _ ;; gen_PbRMod_Hom M (Abs r s) == Abs r s ;; FIB_RMOD_HOM M _ ;; FIB_RMOD_eq _ (H _ );; gen_pb_fib _ _ _ }. End Rep_Hom_Class. (** the type of morphismes of representations P -> R *) Record TLCPO_rep_Hom := { tcomp : type_type P -> type_type R ; ttriag : forall t, tcomp (type_mor P t) = type_mor R t; rep_Hom_monad :> gen_RMonad_Hom P R (NNNT1 tcomp); rep_gen_Hom_monad_struct :> TLCPO_rep_Hom_struct ttriag rep_Hom_monad }. End rep_hom. Existing Instance rep_gen_Hom_monad_struct.
lemma sequence_unique_limpt: fixes f :: "nat \<Rightarrow> 'a::t2_space" assumes "(f \<longlongrightarrow> l) sequentially" and "l' islimpt (range f)" shows "l' = l"
\documentclass[9pt,twocolumn,twoside,]{pnas-new} % Use the lineno option to display guide line numbers if required. % Note that the use of elements such as single-column equations % may affect the guide line number alignment. \usepackage[T1]{fontenc} \usepackage[utf8]{inputenc} % 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 \newenvironment{Shaded}{}{} \newcommand{\AlertTok}[1]{\textcolor[rgb]{1.00,0.00,0.00}{\textbf{#1}}} \newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{#1}}}} \newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.49,0.56,0.16}{#1}} \newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{#1}} \newcommand{\BuiltInTok}[1]{#1} \newcommand{\CharTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{#1}} \newcommand{\CommentTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textit{#1}}} \newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{#1}}}} \newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.53,0.00,0.00}{#1}} \newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{\textbf{#1}}} \newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.56,0.13,0.00}{#1}} \newcommand{\DecValTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{#1}} \newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.73,0.13,0.13}{\textit{#1}}} \newcommand{\ErrorTok}[1]{\textcolor[rgb]{1.00,0.00,0.00}{\textbf{#1}}} \newcommand{\ExtensionTok}[1]{#1} \newcommand{\FloatTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{#1}} \newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.02,0.16,0.49}{#1}} \newcommand{\ImportTok}[1]{#1} \newcommand{\InformationTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{#1}}}} \newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{\textbf{#1}}} \newcommand{\NormalTok}[1]{#1} \newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}} \newcommand{\OtherTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{#1}} \newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.74,0.48,0.00}{#1}} \newcommand{\RegionMarkerTok}[1]{#1} \newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{#1}} \newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.73,0.40,0.53}{#1}} \newcommand{\StringTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{#1}} \newcommand{\VariableTok}[1]{\textcolor[rgb]{0.10,0.09,0.49}{#1}} \newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{#1}} \newcommand{\WarningTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\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} \templatetype{pnasmathematics} % Choose template \title{Problem Set 1} \author[]{Carlos Enrique Lezama Jacinto} \affil[]{Instituto Tecnológico Autónomo de México} % Please give the surname of the lead author for the running footer \leadauthor{} % Please add here a significance statement to explain the relevance of your work \significancestatement{} \authorcontributions{} \correspondingauthor{\textsuperscript{} My solutions to the first problem set in Advanced Microeconometrics (ECO -- 20513).} % Keywords are not mandatory, but authors are strongly encouraged to provide them. If provided, please include two to five keywords, separated by the pipe symbol, e.g: \begin{abstract} \end{abstract} \dates{This manuscript was compiled on \today} \doi{\url{www.pnas.org/cgi/doi/10.1073/pnas.XXXXXXXXXX}} \begin{document} % Optional adjustment to line up main text (after abstract) of first page with line numbers, when using both lineno and twocolumn options. % You should only change this length when you've finalised the article contents. \verticaladjustment{-2pt} \maketitle \thispagestyle{firststyle} \ifthenelse{\boolean{shortarticle}}{\ifthenelse{\boolean{singlecolumn}}{\abscontentformatted}{\abscontent}}{} % If your first paragraph (i.e. with the \dropcap) contains a list environment (quote, quotation, theorem, definition, enumerate, itemize...), the line after the list may have some extra indentation. If this is the case, add \parshape=0 to the end of the list environment. \acknow{} \newcommand{\ind}{\perp\!\!\!\!\perp} \hypertarget{the-model}{% \section*{The Model}\label{the-model}} \addcontentsline{toc}{section}{The Model} Assume that the economic model generating the data for potential outcomes is of the form: \begin{align*} Y_1 &= \alpha + \varphi + U_1, \\ Y_0 &= \alpha + U_0, \end{align*} where \(U_1\) and \(U_0\) represent the unobservables in the potential outcome equations and \(\varphi\) represents the benefit associated with the treatment (\(D = 1\)). Individuals decide whether or not to receive the treatment (\(D = 1\) or \(D = 0\)) based on a latent variable \(I\): \[ I = Z \gamma + V, \] where \(Z\) and \(V\) represent observables and unobservables, respectively. Thus, we can define a binary variable \(D\) indicating treatment status, \[ D = \mathds{1}\left[ I \geq 0\right]. \] Finally, we assume that the error terms in the model are not independent even conditioning on the observables, i.e.~\(U_1 \not\perp\!\!\!\!\perp U_0 \not\perp\!\!\!\!\perp V \mid Z\), but \((U_1, U_0, V) \perp\!\!\!\!\perp Z\). \hypertarget{treatment-parameters}{% \section{Treatment Parameters}\label{treatment-parameters}} Let \(\beta = Y_1 - Y_0 = \varphi + U_1 - U_0\) such that, in regression notation, \(Y = \alpha + \beta D + \varepsilon\) where \(\varepsilon = U_0\). \hypertarget{average-treatment-effect}{% \subsection*{Average Treatment Effect}\label{average-treatment-effect}} \addcontentsline{toc}{subsection}{Average Treatment Effect} \begin{align*} ATE &= E \left[ \beta \right] \\ &= E \left[ \varphi + U_1 - U_0 \right] \\ &= \varphi \end{align*} \hypertarget{treatment-on-the-treated}{% \subsection*{Treatment on the Treated}\label{treatment-on-the-treated}} \addcontentsline{toc}{subsection}{Treatment on the Treated} \begin{align*} TT &= E \left[ \beta \mid D = 1 \right] \\ &= E \left[ \varphi + U_1 - U_0 \mid Z \gamma + V \geq 0 \right] \\ &= \varphi + E \left[ U_1 - U_0 \mid V \geq - Z \gamma \right] \end{align*} \hypertarget{treatment-on-the-untreated}{% \subsection*{Treatment on the Untreated}\label{treatment-on-the-untreated}} \addcontentsline{toc}{subsection}{Treatment on the Untreated} \begin{align*} TUT &= E \left[ \beta \mid D = 0 \right] \\ &= E \left[ \varphi + U_1 - U_0 \mid Z \gamma + V < 0 \right] \\ &= \varphi + E \left[ U_1 - U_0 \mid V < - Z \gamma \right] \end{align*} \hypertarget{marginal-treatment-effect}{% \subsection*{Marginal Treatment Effect}\label{marginal-treatment-effect}} \addcontentsline{toc}{subsection}{Marginal Treatment Effect} \begin{align*} MTE &= E \left[ \beta \mid I = 0,\ V = v \right] \\ &= E \left[ \varphi + U_1 - U_0 \mid I = 0,\ V = v \right] \\ &= \varphi + E \left[ U_1 - U_0 \mid Z \gamma = - V,\ V = v \right] \end{align*} \hypertarget{instrumental-variables}{% \subsection*{Instrumental Variables}\label{instrumental-variables}} \addcontentsline{toc}{subsection}{Instrumental Variables} \[ \hat{\beta}_{\text{IV}} (J(Z)) = \frac{\text{Cov}(J(Z), Y)}{\text{Cov}(J(Z), D)} \overset{p}{\longrightarrow} \beta \] \hypertarget{ordinary-least-squares}{% \subsection*{Ordinary Least Squares}\label{ordinary-least-squares}} \addcontentsline{toc}{subsection}{Ordinary Least Squares} \[ \hat{\beta}_{\text{OLS}} = \frac{\text{Cov}(Y, D)}{\text{Var}(D)} \implies \hat{\beta}_{\text{OLS}} = \left( D^T D \right)^{-1} D^T Y \] \hypertarget{local-average-treatment-effect}{% \subsection*{Local Average Treatment Effect}\label{local-average-treatment-effect}} \addcontentsline{toc}{subsection}{Local Average Treatment Effect} \begin{align*} LATE &= E \left[ \beta \mid D(z) = 0, D(z') = 1 \right] \\ &= E \left[ \beta \mid z \gamma < - V \leq z' \gamma \right] \\ &= \varphi + E \left[ U_1 - U_0 \mid - z' \gamma \leq V < - z \gamma \right] \end{align*} \hypertarget{some-closed-form-expressions}{% \section{Some closed form expressions}\label{some-closed-form-expressions}} Suppose that the error terms in the model have the following structure: \begin{align*} U_1 &= \sigma_1 \epsilon, \\ U_0 &= \sigma_0 \epsilon, \\ V &= \sigma^*_V \epsilon, \\ \epsilon &\sim \mathcal{N} (0, 1). \end{align*} So, we can say that \begin{align*} TT &= \varphi + E \left[ U_1 - U_0 \mid V \geq - Z \gamma \right] \\ &= \varphi + E \left[ \epsilon (\sigma_1 - \sigma_0) \mid \epsilon \geq \frac{- Z \gamma}{\sigma^*_V} \right] \\ &= \varphi + (\sigma_1 - \sigma_0) E \left[ \epsilon \mid \epsilon \geq \frac{- Z \gamma}{\sigma^*_V} \right] \\ &= \varphi + (\sigma_1 - \sigma_0) \frac{\phi \left( - Z \gamma / \sigma^*_V \right)}{1 - \Phi \left( - Z \gamma / \sigma^*_V \right) }, \end{align*} and \begin{align*} TUT &= \varphi + E \left[ U_1 - U_0 \mid V < - Z \gamma \right] \\ &= \varphi + E \left[ \epsilon (\sigma_1 - \sigma_0) \mid \epsilon < \frac{- Z \gamma}{\sigma^*_V} \right] \\ &= \varphi + (\sigma_1 - \sigma_0) E \left[ \epsilon \mid \epsilon < \frac{- Z \gamma}{\sigma^*_V} \right] \\ &= \varphi - (\sigma_1 - \sigma_0) \frac{\phi \left( - Z \gamma / \sigma^*_V \right)}{\Phi \left( - Z \gamma / \sigma^*_V \right) } \\ &= \varphi + (\sigma_0 - \sigma_1) \frac{\phi \left( - Z \gamma / \sigma^*_V \right)}{\Phi \left( - Z \gamma / \sigma^*_V \right) }. \end{align*} \hypertarget{parametrization-1}{% \section{Parametrization 1}\label{parametrization-1}} Now, to add more structure to the problem, suppose that \(Z = (1, Z_1, Z_2)\), and \(\gamma = (\gamma_0, \gamma_1, \gamma_2)\). Also, suppose that \begin{align*} \gamma_0 = 0.2, && \gamma_1 = 0.3, && \gamma_2 = 0.1, \\ \sigma_1 = 0.012, && \sigma_0 = 0.05, && \sigma^*_V = 1, \\ \alpha = 0.02, && \varphi = 0.2. \end{align*} Finally, \begin{align*} Z_1 &\sim \mathcal{N}(-1, 9), \\ Z_2 &\sim \mathcal{N} (1, 9), \end{align*} where \(Z_1 \perp\!\!\!\!\perp Z_2\). Since we only observe either \(Y_1\) or \(Y_0\), the econometrician observes the outcome described as follows: \[ Y = DY_1 + (1 - D)Y_0. \] \newpage \begin{Shaded} \begin{Highlighting}[] \FunctionTok{set.seed}\NormalTok{(}\DecValTok{1234}\NormalTok{)} \NormalTok{TOL }\OtherTok{\textless{}{-}} \FloatTok{0.01} \NormalTok{N }\OtherTok{\textless{}{-}} \DecValTok{5000} \CommentTok{\# random sample observations} \NormalTok{alpha }\OtherTok{\textless{}{-}} \FloatTok{0.02} \NormalTok{phi }\OtherTok{\textless{}{-}} \FloatTok{0.2} \NormalTok{g }\OtherTok{\textless{}{-}} \FunctionTok{matrix}\NormalTok{(}\FunctionTok{c}\NormalTok{(}\FloatTok{0.2}\NormalTok{, }\FloatTok{0.3}\NormalTok{, }\FloatTok{0.1}\NormalTok{))} \NormalTok{sigma1 }\OtherTok{\textless{}{-}} \FloatTok{0.012} \NormalTok{sigma0 }\OtherTok{\textless{}{-}} \FloatTok{0.05} \NormalTok{sigmaV }\OtherTok{\textless{}{-}} \DecValTok{1} \NormalTok{eps }\OtherTok{\textless{}{-}} \FunctionTok{rnorm}\NormalTok{(N)} \NormalTok{U1 }\OtherTok{\textless{}{-}}\NormalTok{ sigma1 }\SpecialCharTok{*}\NormalTok{ eps} \NormalTok{U0 }\OtherTok{\textless{}{-}}\NormalTok{ sigma0 }\SpecialCharTok{*}\NormalTok{ eps} \NormalTok{V }\OtherTok{\textless{}{-}}\NormalTok{ sigmaV }\SpecialCharTok{*}\NormalTok{ eps} \NormalTok{Z }\OtherTok{\textless{}{-}} \FunctionTok{cbind}\NormalTok{(}\FunctionTok{rep}\NormalTok{(}\DecValTok{1}\NormalTok{, N),} \FunctionTok{rnorm}\NormalTok{(N, }\SpecialCharTok{{-}}\DecValTok{1}\NormalTok{, }\DecValTok{3}\NormalTok{),} \FunctionTok{rnorm}\NormalTok{(N, }\DecValTok{1}\NormalTok{, }\DecValTok{3}\NormalTok{))} \NormalTok{I }\OtherTok{\textless{}{-}}\NormalTok{ (Z }\SpecialCharTok{\%*\%}\NormalTok{ g) }\SpecialCharTok{+}\NormalTok{ V} \NormalTok{D }\OtherTok{\textless{}{-}} \FunctionTok{ifelse}\NormalTok{(I }\SpecialCharTok{\textgreater{}=} \DecValTok{0}\NormalTok{, }\DecValTok{1}\NormalTok{, }\DecValTok{0}\NormalTok{)} \NormalTok{Y1 }\OtherTok{\textless{}{-}}\NormalTok{ alpha }\SpecialCharTok{+}\NormalTok{ phi }\SpecialCharTok{+}\NormalTok{ U1} \NormalTok{Y0 }\OtherTok{\textless{}{-}}\NormalTok{ alpha }\SpecialCharTok{+}\NormalTok{ U0} \NormalTok{Y }\OtherTok{\textless{}{-}}\NormalTok{ (D }\SpecialCharTok{*}\NormalTok{ Y1) }\SpecialCharTok{+}\NormalTok{ ((}\DecValTok{1} \SpecialCharTok{{-}}\NormalTok{ D) }\SpecialCharTok{*}\NormalTok{ Y0)} \NormalTok{df }\OtherTok{\textless{}{-}} \FunctionTok{data.frame}\NormalTok{(}\StringTok{\textquotesingle{}beta\textquotesingle{}} \OtherTok{=}\NormalTok{ Y1 }\SpecialCharTok{{-}}\NormalTok{ Y0,} \StringTok{\textquotesingle{}decision\textquotesingle{}} \OtherTok{=}\NormalTok{ D,} \StringTok{\textquotesingle{}y1\textquotesingle{}} \OtherTok{=}\NormalTok{ Y1,} \StringTok{\textquotesingle{}y0\textquotesingle{}} \OtherTok{=}\NormalTok{ Y0,} \StringTok{\textquotesingle{}net utility\textquotesingle{}} \OtherTok{=}\NormalTok{ I)} \NormalTok{ATE }\OtherTok{\textless{}{-}}\NormalTok{ df }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{pull}\NormalTok{(beta) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{mean}\NormalTok{()} \NormalTok{TT }\OtherTok{\textless{}{-}}\NormalTok{ df }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{filter}\NormalTok{(decision }\SpecialCharTok{==} \DecValTok{1}\NormalTok{) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{pull}\NormalTok{(beta) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{mean}\NormalTok{()} \NormalTok{TUT }\OtherTok{\textless{}{-}}\NormalTok{ df }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{filter}\NormalTok{(decision }\SpecialCharTok{==} \DecValTok{0}\NormalTok{) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{pull}\NormalTok{(beta) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{mean}\NormalTok{()} \NormalTok{MTE }\OtherTok{\textless{}{-}}\NormalTok{ df }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{filter}\NormalTok{(}\FunctionTok{abs}\NormalTok{(net.utility }\SpecialCharTok{{-}}\NormalTok{ V) }\SpecialCharTok{\textless{}=}\NormalTok{ TOL) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{pull}\NormalTok{(beta) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{mean}\NormalTok{()} \end{Highlighting} \end{Shaded} \begin{center}\includegraphics[width=0.85\linewidth,]{out_files/figure-latex/unnamed-chunk-2-1} \end{center} \hypertarget{parametrization-2}{% \section{Parametrization 2}\label{parametrization-2}} \begin{Shaded} \begin{Highlighting}[] \NormalTok{LATE }\OtherTok{\textless{}{-}} \ControlFlowTok{function}\NormalTok{(param, old, new) \{} \NormalTok{ Z.old }\OtherTok{\textless{}{-}}\NormalTok{ Z} \NormalTok{ Z.new }\OtherTok{\textless{}{-}}\NormalTok{ Z} \NormalTok{ Z.old[, param] }\OtherTok{\textless{}{-}}\NormalTok{ old} \NormalTok{ Z.new[, param] }\OtherTok{\textless{}{-}}\NormalTok{ new} \NormalTok{ I.old }\OtherTok{\textless{}{-}}\NormalTok{ (Z.old }\SpecialCharTok{\%*\%}\NormalTok{ g) }\SpecialCharTok{+}\NormalTok{ V} \NormalTok{ D.old }\OtherTok{\textless{}{-}} \FunctionTok{ifelse}\NormalTok{(I.old }\SpecialCharTok{\textgreater{}=} \DecValTok{0}\NormalTok{, }\DecValTok{1}\NormalTok{, }\DecValTok{0}\NormalTok{)} \NormalTok{ I.new }\OtherTok{\textless{}{-}}\NormalTok{ (Z.new }\SpecialCharTok{\%*\%}\NormalTok{ g) }\SpecialCharTok{+}\NormalTok{ V} \NormalTok{ D.new }\OtherTok{\textless{}{-}} \FunctionTok{ifelse}\NormalTok{(I.new }\SpecialCharTok{\textgreater{}=} \DecValTok{0}\NormalTok{, }\DecValTok{1}\NormalTok{, }\DecValTok{0}\NormalTok{)} \NormalTok{ test }\OtherTok{\textless{}{-}} \FunctionTok{ifelse}\NormalTok{((D.old }\SpecialCharTok{==} \DecValTok{0}\NormalTok{) }\SpecialCharTok{\&}\NormalTok{ (D.new }\SpecialCharTok{==} \DecValTok{1}\NormalTok{), }\DecValTok{1}\NormalTok{, }\DecValTok{0}\NormalTok{)} \NormalTok{ temp.df }\OtherTok{\textless{}{-}} \FunctionTok{data.frame}\NormalTok{(} \StringTok{\textquotesingle{}beta\textquotesingle{}} \OtherTok{=}\NormalTok{ Y1 }\SpecialCharTok{{-}}\NormalTok{ Y0,} \StringTok{\textquotesingle{}test\textquotesingle{}} \OtherTok{=}\NormalTok{ test} \NormalTok{ )} \NormalTok{ r }\OtherTok{\textless{}{-}}\NormalTok{ temp.df }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{filter}\NormalTok{((test }\SpecialCharTok{==} \DecValTok{1}\NormalTok{)) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{pull}\NormalTok{(beta) }\SpecialCharTok{\%\textgreater{}\%} \FunctionTok{mean}\NormalTok{()} \FunctionTok{return}\NormalTok{(r)} \NormalTok{\}} \NormalTok{regress }\OtherTok{\textless{}{-}} \ControlFlowTok{function}\NormalTok{(beta) \{} \NormalTok{ intercept }\OtherTok{\textless{}{-}} \FunctionTok{mean}\NormalTok{(Y) }\SpecialCharTok{{-}}\NormalTok{ (beta }\SpecialCharTok{*} \FunctionTok{mean}\NormalTok{(D))} \NormalTok{ intercept }\SpecialCharTok{+}\NormalTok{ (beta }\SpecialCharTok{*}\NormalTok{ D)} \NormalTok{\}} \end{Highlighting} \end{Shaded} \hypertarget{latez_1--2-z_1-1}{% \subsection{\texorpdfstring{\(LATE(z_1 = -2, z'_1 = 1)\)}{LATE(z\_1 = -2, z'\_1 = 1)}}\label{latez_1--2-z_1-1}} \begin{Shaded} \begin{Highlighting}[] \NormalTok{LATE}\FloatTok{.1} \OtherTok{\textless{}{-}} \FunctionTok{LATE}\NormalTok{(}\DecValTok{2}\NormalTok{, }\SpecialCharTok{{-}}\DecValTok{2}\NormalTok{, }\DecValTok{1}\NormalTok{)} \end{Highlighting} \end{Shaded} \(LATE(z_1 = -2, z'_1 = 1) = 0.2051\). \hypertarget{latez_2-0-z_2-2}{% \subsection{\texorpdfstring{\(LATE(z_2 = 0, z'_2 = 2)\)}{LATE(z\_2 = 0, z'\_2 = 2)}}\label{latez_2-0-z_2-2}} \begin{Shaded} \begin{Highlighting}[] \NormalTok{LATE}\FloatTok{.2} \OtherTok{\textless{}{-}} \FunctionTok{LATE}\NormalTok{(}\DecValTok{3}\NormalTok{, }\DecValTok{0}\NormalTok{, }\DecValTok{2}\NormalTok{)} \end{Highlighting} \end{Shaded} \(LATE(z_2 = 0, z'_2 = 2) = 0.1982\). \hypertarget{ivz_1}{% \subsection{\texorpdfstring{\(IV(Z_1)\)}{IV(Z\_1)}}\label{ivz_1}} \begin{Shaded} \begin{Highlighting}[] \NormalTok{beta.IV.Z1 }\OtherTok{\textless{}{-}}\NormalTok{ (}\FunctionTok{cov}\NormalTok{(Z[, }\DecValTok{2}\NormalTok{], Y) }\SpecialCharTok{/} \FunctionTok{cov}\NormalTok{(Z[, }\DecValTok{2}\NormalTok{], D))[}\DecValTok{1}\NormalTok{, }\DecValTok{1}\NormalTok{]} \NormalTok{Y.IV.Z1 }\OtherTok{\textless{}{-}} \FunctionTok{regress}\NormalTok{(beta.IV.Z1)} \end{Highlighting} \end{Shaded} \(\hat{\beta}_{\text{IV}} (Z_1) = 0.2045\). \hypertarget{ivz_2}{% \subsection{\texorpdfstring{\(IV(Z_2)\)}{IV(Z\_2)}}\label{ivz_2}} \begin{Shaded} \begin{Highlighting}[] \NormalTok{beta.IV.Z2 }\OtherTok{\textless{}{-}}\NormalTok{ (}\FunctionTok{cov}\NormalTok{(Z[, }\DecValTok{3}\NormalTok{], Y) }\SpecialCharTok{/} \FunctionTok{cov}\NormalTok{(Z[, }\DecValTok{3}\NormalTok{], D))[}\DecValTok{1}\NormalTok{, }\DecValTok{1}\NormalTok{]} \NormalTok{Y.IV.Z2 }\OtherTok{\textless{}{-}} \FunctionTok{regress}\NormalTok{(beta.IV.Z2)} \end{Highlighting} \end{Shaded} \(\hat{\beta}_{\text{IV}} (Z_2) = 0.206\). \hypertarget{ols}{% \subsection{\texorpdfstring{\(OLS\)}{OLS}}\label{ols}} \begin{Shaded} \begin{Highlighting}[] \NormalTok{beta.OLS }\OtherTok{\textless{}{-}}\NormalTok{ (}\FunctionTok{cov}\NormalTok{(D, Y) }\SpecialCharTok{/} \FunctionTok{var}\NormalTok{(D))[}\DecValTok{1}\NormalTok{, }\DecValTok{1}\NormalTok{]} \NormalTok{Y.OLS }\OtherTok{\textless{}{-}} \FunctionTok{regress}\NormalTok{(beta.OLS)} \end{Highlighting} \end{Shaded} \(\hat{\beta}_{\text{OLS}} = 0.237\). \vspace*{20px} Given our regression outcomes, the OLS regression shows less variance than the other estimators, but it is more biased. These results exhibit the conflict in trying to simultaneously minimize these two sources of error. Similar estimations, also imply that there is not single best optimization algorithm as it is stated in the so called \emph{no free lunch theorem}. \hypertarget{gmm}{% \section{GMM}\label{gmm}} Using \(Z = (Z_1, Z_2)\) as instruments and \(\displaystyle \hat{V}_0 = \frac{1}{n} \sum_{i = 1}^n z_i' z_i\) as the weighting matrix, we can estimate our model by the generalized method of moments. Hence, we can obtain \[ \hat{\beta}_{\text{GMM}} = \left( D' Z V_0^{-1} Z' D \right)^{-1} D' Z V_0^{-1} Z' Y. \] Note that we can rewrite \(\displaystyle \hat{V}_0 = \frac{1}{n} Z' Z\). Thus, \begin{Shaded} \begin{Highlighting}[] \NormalTok{subset.Z }\OtherTok{\textless{}{-}}\NormalTok{ Z[, }\SpecialCharTok{{-}}\DecValTok{1}\NormalTok{]} \NormalTok{V0 }\OtherTok{\textless{}{-}}\NormalTok{ (}\DecValTok{1} \SpecialCharTok{/}\NormalTok{ N) }\SpecialCharTok{*}\NormalTok{ (}\FunctionTok{t}\NormalTok{(subset.Z) }\SpecialCharTok{\%*\%}\NormalTok{ subset.Z)} \NormalTok{beta.GMM }\OtherTok{\textless{}{-}} \NormalTok{ (} \FunctionTok{solve}\NormalTok{(}\FunctionTok{t}\NormalTok{(D) }\SpecialCharTok{\%*\%}\NormalTok{ subset.Z }\SpecialCharTok{\%*\%} \FunctionTok{solve}\NormalTok{(V0) }\SpecialCharTok{\%*\%} \FunctionTok{t}\NormalTok{(subset.Z) }\SpecialCharTok{\%*\%}\NormalTok{ D) }\SpecialCharTok{\%*\%} \FunctionTok{t}\NormalTok{(D) }\SpecialCharTok{\%*\%}\NormalTok{ subset.Z }\SpecialCharTok{\%*\%} \FunctionTok{solve}\NormalTok{(V0) }\SpecialCharTok{\%*\%} \FunctionTok{t}\NormalTok{(subset.Z) }\SpecialCharTok{\%*\%}\NormalTok{ Y} \NormalTok{ )[}\DecValTok{1}\NormalTok{, }\DecValTok{1}\NormalTok{]} \NormalTok{Y.GMM }\OtherTok{\textless{}{-}} \FunctionTok{regress}\NormalTok{(beta.GMM)} \end{Highlighting} \end{Shaded} \begin{longtable}[]{@{}lll@{}} \toprule Estimator & Estimate & Standard Error \\ \midrule \endhead \(\hat{\beta}_{\text{GMM}}\) & 0.2087 & 0.0321 \\ \(\hat{\beta}_{\text{IV}} (Z_1)\) & 0.2045 & 0.0331 \\ \(\hat{\beta}_{\text{IV}} (Z_2)\) & 0.206 & 0.0327 \\ \(\hat{\beta}_{\text{OLS}}\) & 0.237 & 0.0288 \\ \bottomrule \end{longtable} \hypertarget{likelihood-function}{% \section{Likelihood Function}\label{likelihood-function}} We know that \begin{align*} Pr\left(D = 1 \mid Z\right) &= Pr\left(\gamma Z + V \geq 0 \right) \\ &= Pr\left( \frac{-Z\gamma}{\sigma^*_V} \leq \epsilon \right) \\ &= 1 - Pr\left( \epsilon \leq \frac{-Z\gamma}{\sigma^*_V} \right) \\ &= 1 - \Phi \left( \frac{-Z\gamma}{\sigma^*_V} \right), \end{align*} and \begin{align*} Pr\left(D = 0 \mid Z\right) &= Pr\left(\gamma Z + V < 0 \right) \\ &= Pr\left( \epsilon \leq \frac{-Z\gamma}{\sigma^*_V} \right) \\ &= \Phi \left( \frac{-Z\gamma}{\sigma^*_V} \right). \end{align*} Hence, \begin{align*} \mathcal{L} &= \prod_{d_i = 0} \left[ \Phi \left( \frac{-Z\gamma}{\sigma^*_v} \right) \right] \prod_{d_i = 1} \left[ 1- \Phi \left( \frac{-Z\gamma}{\sigma^*_v} \right) \right] \\ &= \prod_{i} \left[ \Phi \left( \frac{-Z\gamma}{\sigma^*_v} \right) \right]^{1 - d_i} \left[ 1- \Phi \left( \frac{-Z\gamma}{\sigma^*_v} \right) \right]^{d_i}, \end{align*} and \begin{align*} \ell &= \log\mathcal{L} \\ &= \sum_{i} (1 - d_i) \log \left( \Phi \left( \frac{-Z\gamma}{\sigma^*_V} \right) \right) \\ &+ \sum_{i} d_i \log \left( 1 - \Phi \left( \frac{-Z\gamma}{\sigma^*_V} \right) \right) \\ &= \sum_{i} (1 - d_i) \log \left( \Phi \left( \frac{-\gamma_0 - z_1\gamma_1 - z_2\gamma_2}{\sigma^*_V} \right) \right) \\ &+ \sum_{i} d_i \log \left( 1 - \Phi \left( \frac{-\gamma_0 - z_1\gamma_1 - z_2\gamma_2}{\sigma^*_V} \right) \right). \end{align*} \hypertarget{discussion}{% \section{Discussion}\label{discussion}} The variance on \(V\) (\(\sigma^*_V\)) is not identified and so we normalize it to 1. \showmatmethods \showacknow \pnasbreak % Bibliography % \bibliography{pnas-sample} \end{document}
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.num.basic import Mathlib.data.bitvec.core import Mathlib.PostPort universes l u_1 namespace Mathlib /-! # Bitwise operations using binary representation of integers ## Definitions * bitwise operations for `pos_num` and `num`, * `snum`, a type that represents integers as a bit string with a sign bit at the end, * arithmetic operations for `snum`. -/ namespace pos_num def lor : pos_num → pos_num → pos_num := sorry def land : pos_num → pos_num → num := sorry def ldiff : pos_num → pos_num → num := sorry def lxor : pos_num → pos_num → num := sorry def test_bit : pos_num → ℕ → Bool := sorry def one_bits : pos_num → ℕ → List ℕ := sorry def shiftl (p : pos_num) : ℕ → pos_num := sorry def shiftr : pos_num → ℕ → num := sorry end pos_num namespace num def lor : num → num → num := sorry def land : num → num → num := sorry def ldiff : num → num → num := sorry def lxor : num → num → num := sorry def shiftl : num → ℕ → num := sorry def shiftr : num → ℕ → num := sorry def test_bit : num → ℕ → Bool := sorry def one_bits : num → List ℕ := sorry end num /-- This is a nonzero (and "non minus one") version of `snum`. See the documentation of `snum` for more details. -/ inductive nzsnum where | msb : Bool → nzsnum | bit : Bool → nzsnum → nzsnum /-- Alternative representation of integers using a sign bit at the end. The convention on sign here is to have the argument to `msb` denote the sign of the MSB itself, with all higher bits set to the negation of this sign. The result is interpreted in two's complement. 13 = ..0001101(base 2) = nz (bit1 (bit0 (bit1 (msb tt)))) -13 = ..1110011(base 2) = nz (bit1 (bit1 (bit0 (msb ff)))) As with `num`, a special case must be added for zero, which has no msb, but by two's complement symmetry there is a second special case for -1. Here the `bool` field indicates the sign of the number. 0 = ..0000000(base 2) = zero ff -1 = ..1111111(base 2) = zero tt -/ inductive snum where | zero : Bool → snum | nz : nzsnum → snum protected instance snum.has_coe : has_coe nzsnum snum := has_coe.mk snum.nz protected instance snum.has_zero : HasZero snum := { zero := snum.zero false } protected instance nzsnum.has_one : HasOne nzsnum := { one := nzsnum.msb tt } protected instance snum.has_one : HasOne snum := { one := snum.nz 1 } protected instance nzsnum.inhabited : Inhabited nzsnum := { default := 1 } protected instance snum.inhabited : Inhabited snum := { default := 0 } infixr:67 " :: " => Mathlib.nzsnum.bit /-! The `snum` representation uses a bit string, essentially a list of 0 (`ff`) and 1 (`tt`) bits, and the negation of the MSB is sign-extended to all higher bits. -/ namespace nzsnum def sign : nzsnum → Bool := sorry def not : nzsnum → nzsnum := sorry prefix:40 "~" => Mathlib.nzsnum.not def bit0 : nzsnum → nzsnum := bit false def bit1 : nzsnum → nzsnum := bit tt def head : nzsnum → Bool := sorry def tail : nzsnum → snum := sorry end nzsnum namespace snum def sign : snum → Bool := sorry def not : snum → snum := sorry prefix:40 "~" => Mathlib.snum.not def bit : Bool → snum → snum := sorry infixr:67 " :: " => Mathlib.snum.bit def bit0 : snum → snum := bit false def bit1 : snum → snum := bit tt theorem bit_zero (b : Bool) : b :: zero b = zero b := bool.cases_on b (Eq.refl (false :: zero false)) (Eq.refl (tt :: zero tt)) theorem bit_one (b : Bool) : b :: zero (!b) = ↑(nzsnum.msb b) := bool.cases_on b (Eq.refl (false :: zero (!false))) (Eq.refl (tt :: zero (!tt))) end snum namespace nzsnum def drec' {C : snum → Sort u_1} (z : (b : Bool) → C (snum.zero b)) (s : (b : Bool) → (p : snum) → C p → C (b :: p)) (p : nzsnum) : C ↑p := sorry end nzsnum namespace snum def head : snum → Bool := sorry def tail : snum → snum := sorry def drec' {C : snum → Sort u_1} (z : (b : Bool) → C (zero b)) (s : (b : Bool) → (p : snum) → C p → C (b :: p)) (p : snum) : C p := sorry def rec' {α : Sort u_1} (z : Bool → α) (s : Bool → snum → α → α) : snum → α := drec' z s def test_bit : ℕ → snum → Bool := sorry def succ : snum → snum := rec' (fun (b : Bool) => cond b 0 1) fun (b : Bool) (p succp : snum) => cond b (false :: succp) (tt :: p) def pred : snum → snum := rec' (fun (b : Bool) => cond b (~1) (~0)) fun (b : Bool) (p predp : snum) => cond b (false :: p) (tt :: predp) protected def neg (n : snum) : snum := succ (~n) protected instance has_neg : Neg snum := { neg := snum.neg } def czadd : Bool → Bool → snum → snum := sorry end snum namespace snum /-- `a.bits n` is the vector of the `n` first bits of `a` (starting from the LSB). -/ def bits : snum → (n : ℕ) → vector Bool n := sorry def cadd : snum → snum → Bool → snum := rec' (fun (a : Bool) (p : snum) (c : Bool) => czadd c a p) fun (a : Bool) (p : snum) (IH : snum → Bool → snum) => rec' (fun (b c : Bool) => czadd c b (a :: p)) fun (b : Bool) (q : snum) (_x : Bool → snum) (c : Bool) => bitvec.xor3 a b c :: IH q (bitvec.carry a b c) /-- Add two `snum`s. -/ protected def add (a : snum) (b : snum) : snum := cadd a b false protected instance has_add : Add snum := { add := snum.add } /-- Substract two `snum`s. -/ protected def sub (a : snum) (b : snum) : snum := a + -b protected instance has_sub : Sub snum := { sub := snum.sub } /-- Multiply two `snum`s. -/ protected def mul (a : snum) : snum → snum := rec' (fun (b : Bool) => cond b (-a) 0) fun (b : Bool) (q IH : snum) => cond b (bit0 IH + a) (bit0 IH) protected instance has_mul : Mul snum := { mul := snum.mul }
theorem Baire: fixes S::"'a::{real_normed_vector,heine_borel} set" assumes "closed S" "countable \<G>" and ope: "\<And>T. T \<in> \<G> \<Longrightarrow> openin (top_of_set S) T \<and> S \<subseteq> closure T" shows "S \<subseteq> closure(\<Inter>\<G>)"
# Copyright (c) 2018-2020, Carnegie Mellon University # See LICENSE for details # # n-qubit T and Tdag transforms # #F qTT( n, i ) - T Gate non-terminal #F Definition: (2^n x 2^n)-matrix that applies an n-point T Transform to the target qubits #F Note: qTT(1, 1) denotes the matrix[[1, 0], [0, e^(-ipi/4)]], and qTT(1, -1) denotes the matrix[[1, 0], [0, e^(ipi/4)]] #F qTT(_) is symmetric. #F #F qTT(n , i) -> an n-qubit T transform, or Tdag transform if i = -1 Class(qTT, TaggedNonTerminal, rec( abbrevs := [ (n, i) -> Checked(IsPosInt(n), [n, When(i <= -1, -1, 1)]) ], dims := self >> let(size := 2^self.params[1], [size, size]), terminate := self >> When(self.params[2] = -1, Tensor(Replicate(self.params[1], qTdag())), Tensor(Replicate(self.params[1], qT()))), isReal := self >> false, rChildren := self >> self.params, from_rChildren := (self, rch) >> self.__bases__[1](rch[1], rch[2]), groups := self >> [Replicate(self.params[1], 1)], recursive_def := (self, arch) >> self.__bases__[1](self.params[1], self.params[2]), SmallRandom := () -> Random([2..5]), LargeRandom := () -> Random([6..15]), normalizedArithCost := self >> Error("ArithCost not implemented"), TType := T_Complex(64), )); NewRulesFor(qTT, rec( # qTT_BinSplit rule # qTT_BinSplit qTT_(k) -> (qTT_(k1) tensor I) (I tensor qTT_(k2)) # k1 + k2 = k qTT_BinSplit := rec ( forTransposition := false, minSize := 2, applicable := (self, nt) >> nt.params[1] > 1, children := nt -> List( [1..nt.params[1] - 1], i -> [ Tensor(qTT(i, nt.params[2]), qTT(nt.params[1]-i, nt.params[2])).withTags(nt.getTags()) ] ), apply := (nt, c, cnt) -> c[1], switch := true, ), #F qTT_Base: qTT(1, _) = qT() or qT().inverse() (i.e. qTdag) SPL object #F Directly represent as an implementable gate qTT_Base := rec( info := "qTT_(1, _) -> qT()", forTransposition := false, applicable := (self, nt) >> nt.params[1]=1, apply := (nt, c, cnt) -> When(nt.params[2] = -1, qTdag(), qT()), ) ));
Formal statement is: lemma lim_explicit: "f \<longlonglongrightarrow> f0 \<longleftrightarrow> (\<forall>S. open S \<longrightarrow> f0 \<in> S \<longrightarrow> (\<exists>N. \<forall>n\<ge>N. f n \<in> S))" Informal statement is: A sequence $f$ converges to $f_0$ if and only if for every open set $S$ containing $f_0$, there exists an $N$ such that for all $n \geq N$, $f_n \in S$.
/* Copyright 2015 Rogier van Dalen. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef MATH_GENERALISE_TYPE_HPP_INCLUDED #define MATH_GENERALISE_TYPE_HPP_INCLUDED #include <type_traits> #include <boost/mpl/eval_if.hpp> #include <boost/mpl/identity.hpp> #include "meta/vector.hpp" #include "magma.hpp" namespace math { namespace detail { template <class Operations, class Magma> struct generalise_type_once; template <class Magma> struct generalise_type_once <meta::vector<>, Magma> { typedef Magma type; }; template <class FirstOperation, class ... Operations, class Magma> struct generalise_type_once < meta::vector <FirstOperation, Operations ...>, Magma> { typedef typename std::result_of <FirstOperation (Magma, Magma)>::type operation_result_type; typedef typename merge_magma::apply <Magma, operation_result_type>::type next_type; typedef typename generalise_type_once < meta::vector <Operations ...>, next_type>::type type; }; } // namespace detail /** Convert a magma type to a type in the same magma that can contain the result of any combination of a number of binary operations applied to it. For example, a \ref single_sequence under \ref plus will generalise to \ref optional_sequence; under \ref times (or under both) it will generalise to a \ref sequence. \tparam Operations A meta::vector of binary operations, usually from namespace callable. \tparam Magma The magma type to be generalised. */ template <class Operations, class Magma> struct generalise_type { typedef typename std::decay <Magma>::type magma_type; typedef typename detail::generalise_type_once <Operations, magma_type>::type next_type; typedef typename boost::mpl::eval_if < std::is_same <Magma, next_type>, boost::mpl::identity <Magma>, generalise_type <Operations, next_type> >::type type; }; } // namespace math #endif // MATH_GENERALISE_TYPE_HPP_INCLUDED
Readers are shown the regime 's downward spiral , Trujillo 's assassination , and its aftermath through the eyes of insiders , conspirators , and a middle @-@ aged woman looking back . The novel is therefore a kaleidoscopic portrait of dictatorial power , including its psychological effects , and its long @-@ term impact . The novel 's themes include the nature of power and corruption , and their relationship to machismo and sexual perversion in a rigidly hierarchical society with strongly gendered roles . Memory , and the process of remembering , is also an important theme , especially in Urania 's narrative as she recalls her youth in the Dominican Republic . Her story ( and the book as a whole ) ends when she recounts the terrible events that led to her leaving the country at the age of 14 . The book itself serves as a reminder of the atrocities of dictatorship , to ensure that the dangers of absolute power will be remembered by a new generation .
section \<open>Lens Algebraic Operators\<close> theory Lens_Algebra imports Lens_Laws begin subsection \<open>Lens Composition, Plus, Unit, and Identity\<close> text \<open> \begin{figure} \begin{center} \includegraphics[width=7cm]{figures/Composition} \end{center} \vspace{-5ex} \caption{Lens Composition} \label{fig:Comp} \end{figure} We introduce the algebraic lens operators; for more information please see our paper~\cite{Foster16a}. Lens composition, illustrated in Figure~\ref{fig:Comp}, constructs a lens by composing the source of one lens with the view of another.\<close> definition lens_comp :: "('a \<Longrightarrow> 'b) \<Rightarrow> ('b \<Longrightarrow> 'c) \<Rightarrow> ('a \<Longrightarrow> 'c)" (infixl ";\<^sub>L" 80) where [lens_defs]: "lens_comp Y X = \<lparr> lens_get = get\<^bsub>Y\<^esub> \<circ> lens_get X , lens_put = (\<lambda> \<sigma> v. lens_put X \<sigma> (lens_put Y (lens_get X \<sigma>) v)) \<rparr>" text \<open> \begin{figure} \begin{center} \includegraphics[width=7cm]{figures/Sum} \end{center} \vspace{-5ex} \caption{Lens Sum} \label{fig:Sum} \end{figure} Lens plus, as illustrated in Figure~\ref{fig:Sum} parallel composes two independent lenses, resulting in a lens whose view is the product of the two underlying lens views.\<close> definition lens_plus :: "('a \<Longrightarrow> 'c) \<Rightarrow> ('b \<Longrightarrow> 'c) \<Rightarrow> 'a \<times> 'b \<Longrightarrow> 'c" (infixr "+\<^sub>L" 75) where [lens_defs]: "X +\<^sub>L Y = \<lparr> lens_get = (\<lambda> \<sigma>. (lens_get X \<sigma>, lens_get Y \<sigma>)) , lens_put = (\<lambda> \<sigma> (u, v). lens_put X (lens_put Y \<sigma> v) u) \<rparr>" text \<open>The product functor lens similarly parallel composes two lenses, but in this case the lenses have different sources and so the resulting source is also a product.\<close> definition lens_prod :: "('a \<Longrightarrow> 'c) \<Rightarrow> ('b \<Longrightarrow> 'd) \<Rightarrow> ('a \<times> 'b \<Longrightarrow> 'c \<times> 'd)" (infixr "\<times>\<^sub>L" 85) where [lens_defs]: "lens_prod X Y = \<lparr> lens_get = map_prod get\<^bsub>X\<^esub> get\<^bsub>Y\<^esub> , lens_put = \<lambda> (u, v) (x, y). (put\<^bsub>X\<^esub> u x, put\<^bsub>Y\<^esub> v y) \<rparr>" text \<open>The $\lfst$ and $\lsnd$ lenses project the first and second elements, respectively, of a product source type.\<close> definition fst_lens :: "'a \<Longrightarrow> 'a \<times> 'b" ("fst\<^sub>L") where [lens_defs]: "fst\<^sub>L = \<lparr> lens_get = fst, lens_put = (\<lambda> (\<sigma>, \<rho>) u. (u, \<rho>)) \<rparr>" definition snd_lens :: "'b \<Longrightarrow> 'a \<times> 'b" ("snd\<^sub>L") where [lens_defs]: "snd\<^sub>L = \<lparr> lens_get = snd, lens_put = (\<lambda> (\<sigma>, \<rho>) u. (\<sigma>, u)) \<rparr>" lemma get_fst_lens [simp]: "get\<^bsub>fst\<^sub>L\<^esub> (x, y) = x" by (simp add: fst_lens_def) lemma get_snd_lens [simp]: "get\<^bsub>snd\<^sub>L\<^esub> (x, y) = y" by (simp add: snd_lens_def) text \<open>The swap lens is a bijective lens which swaps over the elements of the product source type.\<close> abbreviation swap_lens :: "'a \<times> 'b \<Longrightarrow> 'b \<times> 'a" ("swap\<^sub>L") where "swap\<^sub>L \<equiv> snd\<^sub>L +\<^sub>L fst\<^sub>L" text \<open>The zero lens is an ineffectual lens whose view is a unit type. This means the zero lens cannot distinguish or change the source type.\<close> definition zero_lens :: "unit \<Longrightarrow> 'a" ("0\<^sub>L") where [lens_defs]: "0\<^sub>L = \<lparr> lens_get = (\<lambda> _. ()), lens_put = (\<lambda> \<sigma> x. \<sigma>) \<rparr>" text \<open>The identity lens is a bijective lens where the source and view type are the same.\<close> definition id_lens :: "'a \<Longrightarrow> 'a" ("1\<^sub>L") where [lens_defs]: "1\<^sub>L = \<lparr> lens_get = id, lens_put = (\<lambda> _. id) \<rparr>" text \<open>The quotient operator $X \lquot Y$ shortens lens $X$ by cutting off $Y$ from the end. It is thus the dual of the composition operator.\<close> definition lens_quotient :: "('a \<Longrightarrow> 'c) \<Rightarrow> ('b \<Longrightarrow> 'c) \<Rightarrow> 'a \<Longrightarrow> 'b" (infixr "'/\<^sub>L" 90) where [lens_defs]: "X /\<^sub>L Y = \<lparr> lens_get = \<lambda> \<sigma>. get\<^bsub>X\<^esub> (create\<^bsub>Y\<^esub> \<sigma>) , lens_put = \<lambda> \<sigma> v. get\<^bsub>Y\<^esub> (put\<^bsub>X\<^esub> (create\<^bsub>Y\<^esub> \<sigma>) v) \<rparr>" text \<open>Lens inverse take a bijective lens and swaps the source and view types.\<close> definition lens_inv :: "('a \<Longrightarrow> 'b) \<Rightarrow> ('b \<Longrightarrow> 'a)" ("inv\<^sub>L") where [lens_defs]: "lens_inv x = \<lparr> lens_get = create\<^bsub>x\<^esub>, lens_put = \<lambda> \<sigma>. get\<^bsub>x\<^esub> \<rparr>" subsection \<open>Closure Poperties\<close> text \<open>We show that the core lenses combinators defined above are closed under the key lens classes.\<close> lemma id_wb_lens: "wb_lens 1\<^sub>L" by (unfold_locales, simp_all add: id_lens_def) lemma source_id_lens: "\<S>\<^bsub>1\<^sub>L\<^esub> = UNIV" by (simp add: id_lens_def lens_source_def) lemma unit_wb_lens: "wb_lens 0\<^sub>L" by (unfold_locales, simp_all add: zero_lens_def) lemma source_zero_lens: "\<S>\<^bsub>0\<^sub>L\<^esub> = UNIV" by (simp_all add: zero_lens_def lens_source_def) lemma comp_weak_lens: "\<lbrakk> weak_lens x; weak_lens y \<rbrakk> \<Longrightarrow> weak_lens (x ;\<^sub>L y)" by (unfold_locales, simp_all add: lens_comp_def) lemma comp_wb_lens: "\<lbrakk> wb_lens x; wb_lens y \<rbrakk> \<Longrightarrow> wb_lens (x ;\<^sub>L y)" by (unfold_locales, auto simp add: lens_comp_def wb_lens_def weak_lens.put_closure) lemma comp_mwb_lens: "\<lbrakk> mwb_lens x; mwb_lens y \<rbrakk> \<Longrightarrow> mwb_lens (x ;\<^sub>L y)" by (unfold_locales, auto simp add: lens_comp_def mwb_lens_def weak_lens.put_closure) lemma source_lens_comp: "\<lbrakk> mwb_lens x; mwb_lens y \<rbrakk> \<Longrightarrow> \<S>\<^bsub>x ;\<^sub>L y\<^esub> = {s \<in> \<S>\<^bsub>y\<^esub>. get\<^bsub>y\<^esub> s \<in> \<S>\<^bsub>x\<^esub>}" by (auto simp add: lens_comp_def lens_source_def, blast, metis mwb_lens.put_put mwb_lens_def weak_lens.put_get) lemma id_vwb_lens [simp]: "vwb_lens 1\<^sub>L" by (unfold_locales, simp_all add: id_lens_def) lemma unit_vwb_lens [simp]: "vwb_lens 0\<^sub>L" by (unfold_locales, simp_all add: zero_lens_def) lemma comp_vwb_lens: "\<lbrakk> vwb_lens x; vwb_lens y \<rbrakk> \<Longrightarrow> vwb_lens (x ;\<^sub>L y)" by (unfold_locales, simp_all add: lens_comp_def weak_lens.put_closure) lemma unit_ief_lens: "ief_lens 0\<^sub>L" by (unfold_locales, simp_all add: zero_lens_def) text \<open>Lens plus requires that the lenses be independent to show closure.\<close> lemma plus_mwb_lens: assumes "mwb_lens x" "mwb_lens y" "x \<bowtie> y" shows "mwb_lens (x +\<^sub>L y)" using assms apply (unfold_locales) apply (simp_all add: lens_plus_def prod.case_eq_if lens_indep_sym) apply (simp add: lens_indep_comm) done lemma plus_wb_lens: assumes "wb_lens x" "wb_lens y" "x \<bowtie> y" shows "wb_lens (x +\<^sub>L y)" using assms apply (unfold_locales, simp_all add: lens_plus_def) apply (simp add: lens_indep_sym prod.case_eq_if) done lemma plus_vwb_lens [simp]: assumes "vwb_lens x" "vwb_lens y" "x \<bowtie> y" shows "vwb_lens (x +\<^sub>L y)" using assms apply (unfold_locales, simp_all add: lens_plus_def) apply (simp add: lens_indep_sym prod.case_eq_if) apply (simp add: lens_indep_comm prod.case_eq_if) done lemma source_plus_lens: assumes "mwb_lens x" "mwb_lens y" "x \<bowtie> y" shows "\<S>\<^bsub>x +\<^sub>L y\<^esub> = \<S>\<^bsub>x\<^esub> \<inter> \<S>\<^bsub>y\<^esub>" apply (auto simp add: lens_source_def lens_plus_def) apply (meson assms(3) lens_indep_comm) apply (metis assms(1) mwb_lens.weak_get_put mwb_lens_weak weak_lens.put_closure) done lemma prod_mwb_lens: "\<lbrakk> mwb_lens X; mwb_lens Y \<rbrakk> \<Longrightarrow> mwb_lens (X \<times>\<^sub>L Y)" by (unfold_locales, simp_all add: lens_prod_def prod.case_eq_if) lemma prod_wb_lens: "\<lbrakk> wb_lens X; wb_lens Y \<rbrakk> \<Longrightarrow> wb_lens (X \<times>\<^sub>L Y)" by (unfold_locales, simp_all add: lens_prod_def prod.case_eq_if) lemma prod_vwb_lens: "\<lbrakk> vwb_lens X; vwb_lens Y \<rbrakk> \<Longrightarrow> vwb_lens (X \<times>\<^sub>L Y)" by (unfold_locales, simp_all add: lens_prod_def prod.case_eq_if) lemma prod_bij_lens: "\<lbrakk> bij_lens X; bij_lens Y \<rbrakk> \<Longrightarrow> bij_lens (X \<times>\<^sub>L Y)" by (unfold_locales, simp_all add: lens_prod_def prod.case_eq_if) lemma fst_vwb_lens: "vwb_lens fst\<^sub>L" by (unfold_locales, simp_all add: fst_lens_def prod.case_eq_if) lemma snd_vwb_lens: "vwb_lens snd\<^sub>L" by (unfold_locales, simp_all add: snd_lens_def prod.case_eq_if) lemma id_bij_lens: "bij_lens 1\<^sub>L" by (unfold_locales, simp_all add: id_lens_def) lemma inv_id_lens: "inv\<^sub>L 1\<^sub>L = 1\<^sub>L" by (auto simp add: lens_inv_def id_lens_def lens_create_def) lemma inv_inv_lens: "bij_lens X \<Longrightarrow> inv\<^sub>L (inv\<^sub>L X) = X" apply (cases X) apply (auto simp add: lens_defs fun_eq_iff) apply (metis (no_types) bij_lens.strong_get_put bij_lens_def select_convs(2) weak_lens.put_get) done lemma lens_inv_bij: "bij_lens X \<Longrightarrow> bij_lens (inv\<^sub>L X)" by (unfold_locales, simp_all add: lens_inv_def lens_create_def) lemma swap_bij_lens: "bij_lens swap\<^sub>L" by (unfold_locales, simp_all add: lens_plus_def prod.case_eq_if fst_lens_def snd_lens_def) subsection \<open>Composition Laws\<close> text \<open>Lens composition is monoidal, with unit @{term "1\<^sub>L"}, as the following theorems demonstrate. It also has @{term "0\<^sub>L"} as a right annihilator. \<close> lemma lens_comp_assoc: "X ;\<^sub>L (Y ;\<^sub>L Z) = (X ;\<^sub>L Y) ;\<^sub>L Z" by (auto simp add: lens_comp_def) lemma lens_comp_left_id [simp]: "1\<^sub>L ;\<^sub>L X = X" by (simp add: id_lens_def lens_comp_def) lemma lens_comp_right_id [simp]: "X ;\<^sub>L 1\<^sub>L = X" by (simp add: id_lens_def lens_comp_def) lemma lens_comp_anhil [simp]: "wb_lens X \<Longrightarrow> 0\<^sub>L ;\<^sub>L X = 0\<^sub>L" by (simp add: zero_lens_def lens_comp_def comp_def) lemma lens_comp_anhil_right [simp]: "wb_lens X \<Longrightarrow> X ;\<^sub>L 0\<^sub>L = 0\<^sub>L" by (simp add: zero_lens_def lens_comp_def comp_def) subsection \<open>Independence Laws\<close> text \<open>The zero lens @{term "0\<^sub>L"} is independent of any lens. This is because nothing can be observed or changed using @{term "0\<^sub>L"}. \<close> lemma zero_lens_indep [simp]: "0\<^sub>L \<bowtie> X" by (auto simp add: zero_lens_def lens_indep_def) lemma zero_lens_indep' [simp]: "X \<bowtie> 0\<^sub>L" by (auto simp add: zero_lens_def lens_indep_def) text \<open>Lens independence is irreflexive, but only for effectual lenses as otherwise nothing can be observed.\<close> lemma lens_indep_quasi_irrefl: "\<lbrakk> wb_lens x; eff_lens x \<rbrakk> \<Longrightarrow> \<not> (x \<bowtie> x)" by (auto simp add: lens_indep_def ief_lens_def ief_lens_axioms_def, metis (full_types) wb_lens.get_put) text \<open>Lens independence is a congruence with respect to composition, as the following properties demonstrate.\<close> lemma lens_indep_left_comp [simp]: "\<lbrakk> mwb_lens z; x \<bowtie> y \<rbrakk> \<Longrightarrow> (x ;\<^sub>L z) \<bowtie> (y ;\<^sub>L z)" apply (rule lens_indepI) apply (auto simp add: lens_comp_def) apply (simp add: lens_indep_comm) apply (simp add: lens_indep_sym) done lemma lens_indep_right_comp: "y \<bowtie> z \<Longrightarrow> (x ;\<^sub>L y) \<bowtie> (x ;\<^sub>L z)" apply (auto intro!: lens_indepI simp add: lens_comp_def) using lens_indep_comm lens_indep_sym apply fastforce apply (simp add: lens_indep_sym) done lemma lens_indep_left_ext [intro]: "y \<bowtie> z \<Longrightarrow> (x ;\<^sub>L y) \<bowtie> z" apply (auto intro!: lens_indepI simp add: lens_comp_def) apply (simp add: lens_indep_comm) apply (simp add: lens_indep_sym) done lemma lens_indep_right_ext [intro]: "x \<bowtie> z \<Longrightarrow> x \<bowtie> (y ;\<^sub>L z)" by (simp add: lens_indep_left_ext lens_indep_sym) lemma lens_comp_indep_cong_left: "\<lbrakk> mwb_lens Z; X ;\<^sub>L Z \<bowtie> Y ;\<^sub>L Z \<rbrakk> \<Longrightarrow> X \<bowtie> Y" apply (rule lens_indepI) apply (rename_tac u v \<sigma>) apply (drule_tac u=u and v=v and \<sigma>="create\<^bsub>Z\<^esub> \<sigma>" in lens_indep_comm) apply (simp add: lens_comp_def) apply (meson mwb_lens_weak weak_lens.view_determination) apply (rename_tac v \<sigma>) apply (drule_tac v=v and \<sigma>="create\<^bsub>Z\<^esub> \<sigma>" in lens_indep_get) apply (simp add: lens_comp_def) apply (drule lens_indep_sym) apply (rename_tac u \<sigma>) apply (drule_tac v=u and \<sigma>="create\<^bsub>Z\<^esub> \<sigma>" in lens_indep_get) apply (simp add: lens_comp_def) done lemma lens_comp_indep_cong: "mwb_lens Z \<Longrightarrow> (X ;\<^sub>L Z) \<bowtie> (Y ;\<^sub>L Z) \<longleftrightarrow> X \<bowtie> Y" using lens_comp_indep_cong_left lens_indep_left_comp by blast text \<open>The first and second lenses are independent since the view different parts of a product source.\<close> lemma fst_snd_lens_indep [simp]: "fst\<^sub>L \<bowtie> snd\<^sub>L" by (simp add: lens_indep_def fst_lens_def snd_lens_def) lemma snd_fst_lens_indep [simp]: "snd\<^sub>L \<bowtie> fst\<^sub>L" by (simp add: lens_indep_def fst_lens_def snd_lens_def) lemma split_prod_lens_indep: assumes "mwb_lens X" shows "(fst\<^sub>L ;\<^sub>L X) \<bowtie> (snd\<^sub>L ;\<^sub>L X)" using assms fst_snd_lens_indep lens_indep_left_comp vwb_lens_mwb by blast text \<open>Lens independence is preserved by summation.\<close> lemma plus_pres_lens_indep [simp]: "\<lbrakk> X \<bowtie> Z; Y \<bowtie> Z \<rbrakk> \<Longrightarrow> (X +\<^sub>L Y) \<bowtie> Z" apply (rule lens_indepI) apply (simp_all add: lens_plus_def prod.case_eq_if) apply (simp add: lens_indep_comm) apply (simp add: lens_indep_sym) done lemma plus_pres_lens_indep' [simp]: "\<lbrakk> X \<bowtie> Y; X \<bowtie> Z \<rbrakk> \<Longrightarrow> X \<bowtie> Y +\<^sub>L Z" by (auto intro: lens_indep_sym plus_pres_lens_indep) text \<open>Lens independence is preserved by product.\<close> lemma lens_indep_prod: "\<lbrakk> X\<^sub>1 \<bowtie> X\<^sub>2; Y\<^sub>1 \<bowtie> Y\<^sub>2 \<rbrakk> \<Longrightarrow> X\<^sub>1 \<times>\<^sub>L Y\<^sub>1 \<bowtie> X\<^sub>2 \<times>\<^sub>L Y\<^sub>2" apply (rule lens_indepI) apply (auto simp add: lens_prod_def prod.case_eq_if lens_indep_comm map_prod_def) apply (simp_all add: lens_indep_sym) done subsection \<open> Compatibility Laws \<close> lemma zero_lens_compat [simp]: "0\<^sub>L ##\<^sub>L X" by (auto simp add: zero_lens_def lens_override_def lens_compat_def) lemma id_lens_compat [simp]: "vwb_lens X \<Longrightarrow> 1\<^sub>L ##\<^sub>L X" by (auto simp add: id_lens_def lens_override_def lens_compat_def) subsection \<open>Algebraic Laws\<close> text \<open>Lens plus distributes to the right through composition.\<close> lemma plus_lens_distr: "mwb_lens Z \<Longrightarrow> (X +\<^sub>L Y) ;\<^sub>L Z = (X ;\<^sub>L Z) +\<^sub>L (Y ;\<^sub>L Z)" by (auto simp add: lens_comp_def lens_plus_def comp_def) text \<open>The first lens projects the first part of a summation.\<close> lemma fst_lens_plus: "wb_lens y \<Longrightarrow> fst\<^sub>L ;\<^sub>L (x +\<^sub>L y) = x" by (simp add: fst_lens_def lens_plus_def lens_comp_def comp_def) text \<open>The second law requires independence as we have to apply x first, before y\<close> lemma snd_lens_plus: "\<lbrakk> wb_lens x; x \<bowtie> y \<rbrakk> \<Longrightarrow> snd\<^sub>L ;\<^sub>L (x +\<^sub>L y) = y" apply (simp add: snd_lens_def lens_plus_def lens_comp_def comp_def) apply (subst lens_indep_comm) apply (simp_all) done text \<open>The swap lens switches over a summation.\<close> lemma lens_plus_swap: "X \<bowtie> Y \<Longrightarrow> swap\<^sub>L ;\<^sub>L (X +\<^sub>L Y) = (Y +\<^sub>L X)" by (auto simp add: lens_plus_def fst_lens_def snd_lens_def id_lens_def lens_comp_def lens_indep_comm) text \<open>The first, second, and swap lenses are all closely related.\<close> lemma fst_snd_id_lens: "fst\<^sub>L +\<^sub>L snd\<^sub>L = 1\<^sub>L" by (auto simp add: lens_plus_def fst_lens_def snd_lens_def id_lens_def) lemma swap_lens_idem: "swap\<^sub>L ;\<^sub>L swap\<^sub>L = 1\<^sub>L" by (simp add: fst_snd_id_lens lens_indep_sym lens_plus_swap) lemma swap_lens_fst: "fst\<^sub>L ;\<^sub>L swap\<^sub>L = snd\<^sub>L" by (simp add: fst_lens_plus fst_vwb_lens) lemma swap_lens_snd: "snd\<^sub>L ;\<^sub>L swap\<^sub>L = fst\<^sub>L" by (simp add: lens_indep_sym snd_lens_plus snd_vwb_lens) text \<open>The product lens can be rewritten as a sum lens.\<close> lemma prod_as_plus: "X \<times>\<^sub>L Y = X ;\<^sub>L fst\<^sub>L +\<^sub>L Y ;\<^sub>L snd\<^sub>L" by (auto simp add: lens_prod_def fst_lens_def snd_lens_def lens_comp_def lens_plus_def) lemma prod_lens_id_equiv: "1\<^sub>L \<times>\<^sub>L 1\<^sub>L = 1\<^sub>L" by (auto simp add: lens_prod_def id_lens_def) lemma prod_lens_comp_plus: "X\<^sub>2 \<bowtie> Y\<^sub>2 \<Longrightarrow> ((X\<^sub>1 \<times>\<^sub>L Y\<^sub>1) ;\<^sub>L (X\<^sub>2 +\<^sub>L Y\<^sub>2)) = (X\<^sub>1 ;\<^sub>L X\<^sub>2) +\<^sub>L (Y\<^sub>1 ;\<^sub>L Y\<^sub>2)" by (auto simp add: lens_comp_def lens_plus_def lens_prod_def prod.case_eq_if fun_eq_iff) text \<open>The following laws about quotient are similar to their arithmetic analogues. Lens quotient reverse the effect of a composition.\<close> lemma lens_comp_quotient: "weak_lens Y \<Longrightarrow> (X ;\<^sub>L Y) /\<^sub>L Y = X" by (simp add: lens_quotient_def lens_comp_def) lemma lens_quotient_id: "weak_lens X \<Longrightarrow> (X /\<^sub>L X) = 1\<^sub>L" by (force simp add: lens_quotient_def id_lens_def) lemma lens_quotient_id_denom: "X /\<^sub>L 1\<^sub>L = X" by (simp add: lens_quotient_def id_lens_def lens_create_def) lemma lens_quotient_unit: "weak_lens X \<Longrightarrow> (0\<^sub>L /\<^sub>L X) = 0\<^sub>L" by (simp add: lens_quotient_def zero_lens_def) lemma lens_obs_eq_zero: "s\<^sub>1 \<simeq>\<^bsub>0\<^sub>L\<^esub> s\<^sub>2 = (s\<^sub>1 = s\<^sub>2)" by (simp add: lens_defs) lemma lens_obs_eq_one: "s\<^sub>1 \<simeq>\<^bsub>1\<^sub>L\<^esub> s\<^sub>2" by (simp add: lens_defs) lemma lens_obs_eq_as_override: "vwb_lens X \<Longrightarrow> s\<^sub>1 \<simeq>\<^bsub>X\<^esub> s\<^sub>2 \<longleftrightarrow> (s\<^sub>2 = s\<^sub>1 \<oplus>\<^sub>L s\<^sub>2 on X)" by (auto simp add: lens_defs; metis vwb_lens.put_eq) end
Load LFindLoad. From lfind Require Import LFind. From QuickChick Require Import QuickChick. From adtind Require Import goal33. Derive Show for natural. Derive Arbitrary for natural. Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed. Lemma conj6synthconj4 : forall (lv0 : natural) (lv1 : natural), (@eq natural (Succ lv0) (plus Zero lv1)). Admitted. QuickChick conj6synthconj4.
module Minecraft.Core.Item.Put.Export import public Minecraft.Core.Item.Put %default total
[STATEMENT] lemma infinite_cball: fixes a :: "'a::euclidean_space" assumes "r > 0" shows "infinite (cball a r)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. infinite (cball a r) [PROOF STEP] using uncountable_cball[OF assms, THEN uncountable_infinite,of a] [PROOF STATE] proof (prove) using this: infinite (cball a r) goal (1 subgoal): 1. infinite (cball a r) [PROOF STEP] .
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.uniform_space.completion import Mathlib.topology.metric_space.isometry import Mathlib.PostPort universes u namespace Mathlib /-! # The completion of a metric space Completion of uniform spaces are already defined in `topology.uniform_space.completion`. We show here that the uniform space completion of a metric space inherits a metric space structure, by extending the distance to the completion and checking that it is indeed a distance, and that it defines the same uniformity as the already defined uniform structure on the completion -/ namespace metric /-- The distance on the completion is obtained by extending the distance on the original space, by uniform continuity. -/ protected instance uniform_space.completion.has_dist {α : Type u} [metric_space α] : has_dist (uniform_space.completion α) := has_dist.mk (uniform_space.completion.extension₂ dist) /-- The new distance is uniformly continuous. -/ protected theorem completion.uniform_continuous_dist {α : Type u} [metric_space α] : uniform_continuous fun (p : uniform_space.completion α × uniform_space.completion α) => dist (prod.fst p) (prod.snd p) := uniform_space.completion.uniform_continuous_extension₂ dist /-- The new distance is an extension of the original distance. -/ protected theorem completion.dist_eq {α : Type u} [metric_space α] (x : α) (y : α) : dist ↑x ↑y = dist x y := uniform_space.completion.extension₂_coe_coe uniform_continuous_dist x y /- Let us check that the new distance satisfies the axioms of a distance, by starting from the properties on α and extending them to `completion α` by continuity. -/ protected theorem completion.dist_self {α : Type u} [metric_space α] (x : uniform_space.completion α) : dist x x = 0 := sorry protected theorem completion.dist_comm {α : Type u} [metric_space α] (x : uniform_space.completion α) (y : uniform_space.completion α) : dist x y = dist y x := sorry protected theorem completion.dist_triangle {α : Type u} [metric_space α] (x : uniform_space.completion α) (y : uniform_space.completion α) (z : uniform_space.completion α) : dist x z ≤ dist x y + dist y z := sorry /-- Elements of the uniformity (defined generally for completions) can be characterized in terms of the distance. -/ protected theorem completion.mem_uniformity_dist {α : Type u} [metric_space α] (s : set (uniform_space.completion α × uniform_space.completion α)) : s ∈ uniformity (uniform_space.completion α) ↔ ∃ (ε : ℝ), ∃ (H : ε > 0), ∀ {a b : uniform_space.completion α}, dist a b < ε → (a, b) ∈ s := sorry /-- If two points are at distance 0, then they coincide. -/ protected theorem completion.eq_of_dist_eq_zero {α : Type u} [metric_space α] (x : uniform_space.completion α) (y : uniform_space.completion α) (h : dist x y = 0) : x = y := sorry /-- Reformulate `completion.mem_uniformity_dist` in terms that are suitable for the definition of the metric space structure. -/ protected theorem completion.uniformity_dist' {α : Type u} [metric_space α] : uniformity (uniform_space.completion α) = infi fun (ε : Subtype fun (ε : ℝ) => 0 < ε) => filter.principal (set_of fun (p : uniform_space.completion α × uniform_space.completion α) => dist (prod.fst p) (prod.snd p) < subtype.val ε) := sorry protected theorem completion.uniformity_dist {α : Type u} [metric_space α] : uniformity (uniform_space.completion α) = infi fun (ε : ℝ) => infi fun (H : ε > 0) => filter.principal (set_of fun (p : uniform_space.completion α × uniform_space.completion α) => dist (prod.fst p) (prod.snd p) < ε) := sorry /-- Metric space structure on the completion of a metric space. -/ protected instance completion.metric_space {α : Type u} [metric_space α] : metric_space (uniform_space.completion α) := metric_space.mk completion.dist_self completion.eq_of_dist_eq_zero completion.dist_comm completion.dist_triangle (fun (x y : uniform_space.completion α) => ennreal.of_real (uniform_space.completion.extension₂ dist x y)) (uniform_space.completion.uniform_space α) /-- The embedding of a metric space in its completion is an isometry. -/ theorem completion.coe_isometry {α : Type u} [metric_space α] : isometry coe := iff.mpr isometry_emetric_iff_metric completion.dist_eq end Mathlib
[STATEMENT] lemma test1: "\<lbrakk>test p; test q; p \<cdot> x \<cdot> !q = 0\<rbrakk> \<Longrightarrow> p \<cdot> x = p \<cdot> x \<cdot> q" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>test p; test q; p \<cdot> x \<cdot> !q = (0::'a)\<rbrakk> \<Longrightarrow> p \<cdot> x = p \<cdot> x \<cdot> q [PROOF STEP] (* nitpick *) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>test p; test q; p \<cdot> x \<cdot> !q = (0::'a)\<rbrakk> \<Longrightarrow> p \<cdot> x = p \<cdot> x \<cdot> q [PROOF STEP] oops
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel The Hausdorff distance on subsets of a metric (or emetric) space. Given two subsets `s` and `t` of a metric space, their Hausdorff distance is the smallest `d` such that any point `s` is within `d` of a point in `t`, and conversely. This quantity is often infinite (think of `s` bounded and `t` unbounded), and therefore better expressed in the setting of emetric spaces. This files introduces: * `inf_edist x s`, the infimum edistance of a point `x` to a set `s` in an emetric space * `Hausdorff_edist s t`, the Hausdorff edistance of two sets in an emetric space * Versions of these notions on metric spaces, called respectively `inf_dist` and `Hausdorff_dist`. -/ import topology.metric_space.isometry topology.instances.ennreal topology.metric_space.cau_seq_filter topology.metric_space.lipschitz noncomputable theory local attribute [instance, priority 0] classical.prop_decidable universes u v w open classical lattice set function topological_space filter namespace emetric section inf_edist local notation `∞` := (⊤ : ennreal) variables {α : Type u} {β : Type v} [emetric_space α] [emetric_space β] {x y : α} {s t : set α} {Φ : α → β} /-- The minimal edistance of a point to a set -/ def inf_edist (x : α) (s : set α) : ennreal := Inf ((edist x) '' s) @[simp] lemma inf_edist_empty : inf_edist x ∅ = ∞ := by unfold inf_edist; simp /-- The edist to a union is the minimum of the edists -/ @[simp] lemma inf_edist_union : inf_edist x (s ∪ t) = inf_edist x s ⊓ inf_edist x t := by simp [inf_edist, image_union, Inf_union] /-- The edist to a singleton is the edistance to the single point of this singleton -/ @[simp] lemma inf_edist_singleton : inf_edist x {y} = edist x y := by simp [inf_edist] /-- The edist to a set is bounded above by the edist to any of its points -/ lemma inf_edist_le_edist_of_mem (h : y ∈ s) : inf_edist x s ≤ edist x y := Inf_le ((mem_image _ _ _).2 ⟨y, h, by refl⟩) /-- If a point `x` belongs to `s`, then its edist to `s` vanishes -/ lemma inf_edist_zero_of_mem (h : x ∈ s) : inf_edist x s = 0 := le_zero_iff_eq.1 $ @edist_self _ _ x ▸ inf_edist_le_edist_of_mem h /-- The edist is monotonous with respect to inclusion -/ lemma inf_edist_le_inf_edist_of_subset (h : s ⊆ t) : inf_edist x t ≤ inf_edist x s := Inf_le_Inf (image_subset _ h) /-- If the edist to a set is `< r`, there exists a point in the set at edistance `< r` -/ lemma exists_edist_lt_of_inf_edist_lt {r : ennreal} (h : inf_edist x s < r) : ∃y∈s, edist x y < r := let ⟨t, ⟨ht, tr⟩⟩ := Inf_lt_iff.1 h in let ⟨y, ⟨ys, hy⟩⟩ := (mem_image _ _ _).1 ht in ⟨y, ys, by rwa ← hy at tr⟩ /-- The edist of `x` to `s` is bounded by the sum of the edist of `y` to `s` and the edist from `x` to `y` -/ lemma inf_edist_le_inf_edist_add_edist : inf_edist x s ≤ inf_edist y s + edist x y := begin have : ∀z ∈ s, Inf (edist x '' s) ≤ edist y z + edist x y := λz hz, calc Inf (edist x '' s) ≤ edist x z : Inf_le ((mem_image _ _ _).2 ⟨z, hz, by refl⟩) ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... = edist y z + edist x y : add_comm _ _, have : (λz, z + edist x y) (Inf (edist y '' s)) = Inf ((λz, z + edist x y) '' (edist y '' s)), { refine Inf_of_continuous _ _ (by simp), { exact continuous_add continuous_id continuous_const }, { assume a b h, simp, apply add_le_add_right' h }}, simp only [inf_edist] at this, rw [inf_edist, inf_edist, this, ← image_comp], simpa only [and_imp, function.comp_app, lattice.le_Inf_iff, exists_imp_distrib, ball_image_iff] end /-- The edist to a set depends continuously on the point -/ lemma continuous_inf_edist : continuous (λx, inf_edist x s) := continuous_of_le_add_edist 1 (by simp) $ by simp only [one_mul, inf_edist_le_inf_edist_add_edist, forall_2_true_iff] /-- The edist to a set and to its closure coincide -/ lemma inf_edist_closure : inf_edist x (closure s) = inf_edist x s := begin refine le_antisymm (inf_edist_le_inf_edist_of_subset subset_closure) _, refine ennreal.le_of_forall_epsilon_le (λε εpos h, _), have εpos' : (0 : ennreal) < ε := by simpa, have : inf_edist x (closure s) < inf_edist x (closure s) + ε/2 := ennreal.lt_add_right h (ennreal.half_pos εpos'), rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ycs, hy⟩, -- y : α, ycs : y ∈ closure s, hy : edist x y < inf_edist x (closure s) + ↑ε / 2 rcases emetric.mem_closure_iff'.1 ycs (ε/2) (ennreal.half_pos εpos') with ⟨z, zs, dyz⟩, -- z : α, zs : z ∈ s, dyz : edist y z < ↑ε / 2 calc inf_edist x s ≤ edist x z : inf_edist_le_edist_of_mem zs ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... ≤ (inf_edist x (closure s) + ε / 2) + (ε/2) : add_le_add' (le_of_lt hy) (le_of_lt dyz) ... = inf_edist x (closure s) + ↑ε : by simp [ennreal.add_halves] end /-- A point belongs to the closure of `s` iff its infimum edistance to this set vanishes -/ lemma mem_closure_iff_inf_edist_zero : x ∈ closure s ↔ inf_edist x s = 0 := ⟨λh, by rw ← inf_edist_closure; exact inf_edist_zero_of_mem h, λh, emetric.mem_closure_iff'.2 $ λε εpos, exists_edist_lt_of_inf_edist_lt (by rwa h)⟩ /-- Given a closed set `s`, a point belongs to `s` iff its infimum edistance to this set vanishes -/ lemma mem_iff_ind_edist_zero_of_closed (h : is_closed s) : x ∈ s ↔ inf_edist x s = 0 := begin convert ← mem_closure_iff_inf_edist_zero, exact closure_eq_iff_is_closed.2 h end /-- The infimum edistance is invariant under isometries -/ lemma inf_edist_image (hΦ : isometry Φ) : inf_edist (Φ x) (Φ '' t) = inf_edist x t := begin simp only [inf_edist], apply congr_arg, ext b, split, { assume hb, rcases (mem_image _ _ _).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rcases (mem_image _ _ _).1 hy with ⟨z, ⟨hz, hz'⟩⟩, rw [← hy', ← hz', hΦ x z], exact mem_image_of_mem _ hz }, { assume hb, rcases (mem_image _ _ _).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rw [← hy', ← hΦ x y], exact mem_image_of_mem _ (mem_image_of_mem _ hy) } end end inf_edist --section /-- The Hausdorff edistance between two sets is the smallest `r` such that each set is contained in the `r`-neighborhood of the other one -/ def Hausdorff_edist {α : Type u} [emetric_space α] (s t : set α) : ennreal := Sup ((λx, inf_edist x t) '' s) ⊔ Sup ((λx, inf_edist x s) '' t) section Hausdorff_edist local notation `∞` := (⊤ : ennreal) variables {α : Type u} {β : Type v} [emetric_space α] [emetric_space β] {x y : α} {s t u : set α} {Φ : α → β} /-- The Hausdorff edistance of a set to itself vanishes -/ @[simp] lemma Hausdorff_edist_self : Hausdorff_edist s s = 0 := begin unfold Hausdorff_edist, erw [lattice.sup_idem, ← le_bot_iff], apply Sup_le _, simp [le_bot_iff, inf_edist_zero_of_mem] {contextual := tt}, end /-- The Haudorff edistances of `s` to `t` and of `t` to `s` coincide -/ lemma Hausdorff_edist_comm : Hausdorff_edist s t = Hausdorff_edist t s := by unfold Hausdorff_edist; apply sup_comm /-- Bounding the Hausdorff edistance by bounding the edistance of any point in each set to the other set -/ lemma Hausdorff_edist_le_of_inf_edist {r : ennreal} (H1 : ∀x ∈ s, inf_edist x t ≤ r) (H2 : ∀x ∈ t, inf_edist x s ≤ r) : Hausdorff_edist s t ≤ r := begin simp only [Hausdorff_edist, -mem_image, set.ball_image_iff, lattice.Sup_le_iff, lattice.sup_le_iff], exact ⟨H1, H2⟩ end /-- Bounding the Hausdorff edistance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_edist_le_of_mem_edist {r : ennreal} (H1 : ∀x ∈ s, ∃y ∈ t, edist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, edist x y ≤ r) : Hausdorff_edist s t ≤ r := begin refine Hausdorff_edist_le_of_inf_edist _ _, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_edist_le_edist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_edist_le_edist_of_mem ys) hy } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_edist_le_Hausdorff_edist_of_mem (h : x ∈ s) : inf_edist x t ≤ Hausdorff_edist s t := begin refine le_trans (le_Sup _) le_sup_left, exact mem_image_of_mem _ h end /-- If the Hausdorff distance is `<r`, then any point in one of the sets has a corresponding point at distance `<r` in the other set -/ lemma exists_edist_lt_of_Hausdorff_edist_lt {r : ennreal} (h : x ∈ s) (H : Hausdorff_edist s t < r) : ∃y∈t, edist x y < r := exists_edist_lt_of_inf_edist_lt $ calc inf_edist x t ≤ Sup ((λx, inf_edist x t) '' s) : le_Sup (mem_image_of_mem _ h) ... ≤ Sup ((λx, inf_edist x t) '' s) ⊔ Sup ((λx, inf_edist x s) '' t) : le_sup_left ... < r : H /-- The distance from `x` to `s`or `t` is controlled in terms of the Hausdorff distance between `s` and `t` -/ lemma inf_edist_le_inf_edist_add_Hausdorff_edist : inf_edist x t ≤ inf_edist x s + Hausdorff_edist s t := ennreal.le_of_forall_epsilon_le $ λε εpos h, begin have εpos' : (0 : ennreal) < ε := by simpa, have : inf_edist x s < inf_edist x s + ε/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).1 (ennreal.half_pos εpos'), rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, dxy⟩, -- y : α, ys : y ∈ s, dxy : edist x y < inf_edist x s + ↑ε / 2 have : Hausdorff_edist s t < Hausdorff_edist s t + ε/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).2 (ennreal.half_pos εpos'), rcases exists_edist_lt_of_Hausdorff_edist_lt ys this with ⟨z, zt, dyz⟩, -- z : α, zt : z ∈ t, dyz : edist y z < Hausdorff_edist s t + ↑ε / 2 calc inf_edist x t ≤ edist x z : inf_edist_le_edist_of_mem zt ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... ≤ (inf_edist x s + ε/2) + (Hausdorff_edist s t + ε/2) : add_le_add' (le_of_lt dxy) (le_of_lt dyz) ... = inf_edist x s + Hausdorff_edist s t + ε : by simp [ennreal.add_halves, add_comm] end /-- The Hausdorff edistance is invariant under eisometries -/ lemma Hausdorff_edist_image (h : isometry Φ) : Hausdorff_edist (Φ '' s) (Φ '' t) = Hausdorff_edist s t := begin unfold Hausdorff_edist, congr, { ext b, split, { assume hb, rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rcases (mem_image _ _ _ ).1 hy with ⟨z, ⟨hz, hz'⟩⟩, rw [← hy', ← hz', inf_edist_image h], exact mem_image_of_mem _ hz }, { assume hb, rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rw [← hy', ← inf_edist_image h], exact mem_image_of_mem _ (mem_image_of_mem _ hy) }}, { ext b, split, { assume hb, rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rcases (mem_image _ _ _ ).1 hy with ⟨z, ⟨hz, hz'⟩⟩, rw [← hy', ← hz', inf_edist_image h], exact mem_image_of_mem _ hz }, { assume hb, rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rw [← hy', ← inf_edist_image h], exact mem_image_of_mem _ (mem_image_of_mem _ hy) }} end /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_edist_le_ediam (hs : s ≠ ∅) (ht : t ≠ ∅) : Hausdorff_edist s t ≤ diam (s ∪ t) := begin rcases ne_empty_iff_exists_mem.1 hs with ⟨x, xs⟩, rcases ne_empty_iff_exists_mem.1 ht with ⟨y, yt⟩, refine Hausdorff_edist_le_of_mem_edist _ _, { exact λz hz, ⟨y, yt, edist_le_diam_of_mem (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { exact λz hz, ⟨x, xs, edist_le_diam_of_mem (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_edist_triangle : Hausdorff_edist s u ≤ Hausdorff_edist s t + Hausdorff_edist t u := begin change Sup ((λx, inf_edist x u) '' s) ⊔ Sup ((λx, inf_edist x s) '' u) ≤ Hausdorff_edist s t + Hausdorff_edist t u, simp only [and_imp, set.mem_image, lattice.Sup_le_iff, exists_imp_distrib, lattice.sup_le_iff, -mem_image, set.ball_image_iff], split, show ∀x ∈ s, inf_edist x u ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xs, calc inf_edist x u ≤ inf_edist x t + Hausdorff_edist t u : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ Hausdorff_edist s t + Hausdorff_edist t u : add_le_add_right' (inf_edist_le_Hausdorff_edist_of_mem xs), show ∀x ∈ u, inf_edist x s ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xu, calc inf_edist x s ≤ inf_edist x t + Hausdorff_edist t s : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ Hausdorff_edist u t + Hausdorff_edist t s : add_le_add_right' (inf_edist_le_Hausdorff_edist_of_mem xu) ... = Hausdorff_edist s t + Hausdorff_edist t u : by simp [Hausdorff_edist_comm, add_comm] end /-- The Hausdorff edistance between a set and its closure vanishes -/ @[simp] lemma Hausdorff_edist_self_closure : Hausdorff_edist s (closure s) = 0 := begin erw ← le_bot_iff, simp only [Hausdorff_edist, inf_edist_closure, -le_zero_iff_eq, and_imp, set.mem_image, lattice.Sup_le_iff, exists_imp_distrib, lattice.sup_le_iff, set.ball_image_iff, ennreal.bot_eq_zero, -mem_image], simp only [inf_edist_zero_of_mem, mem_closure_iff_inf_edist_zero, le_refl, and_self, forall_true_iff] {contextual := tt} end /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closure₁ : Hausdorff_edist (closure s) t = Hausdorff_edist s t := begin refine le_antisymm _ _, { calc _ ≤ Hausdorff_edist (closure s) s + Hausdorff_edist s t : Hausdorff_edist_triangle ... = Hausdorff_edist s t : by simp [Hausdorff_edist_comm] }, { calc _ ≤ Hausdorff_edist s (closure s) + Hausdorff_edist (closure s) t : Hausdorff_edist_triangle ... = Hausdorff_edist (closure s) t : by simp } end /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closure₂ : Hausdorff_edist s (closure t) = Hausdorff_edist s t := by simp [@Hausdorff_edist_comm _ _ s _] /-- The Hausdorff edistance between sets or their closures is the same -/ @[simp] lemma Hausdorff_edist_closure : Hausdorff_edist (closure s) (closure t) = Hausdorff_edist s t := by simp /-- Two sets are at zero Hausdorff edistance if and only if they have the same closure -/ lemma Hausdorff_edist_zero_iff_closure_eq_closure : Hausdorff_edist s t = 0 ↔ closure s = closure t := ⟨begin assume h, refine subset.antisymm _ _, { have : s ⊆ closure t := λx xs, mem_closure_iff_inf_edist_zero.2 $ begin erw ← le_bot_iff, have := @inf_edist_le_Hausdorff_edist_of_mem _ _ _ _ t xs, rwa h at this, end, by rw ← @closure_closure _ _ t; exact closure_mono this }, { have : t ⊆ closure s := λx xt, mem_closure_iff_inf_edist_zero.2 $ begin erw ← le_bot_iff, have := @inf_edist_le_Hausdorff_edist_of_mem _ _ _ _ s xt, rw Hausdorff_edist_comm at h, rwa h at this, end, by rw ← @closure_closure _ _ s; exact closure_mono this } end, λh, by rw [← Hausdorff_edist_closure, h, Hausdorff_edist_self]⟩ /-- Two closed sets are at zero Hausdorff edistance if and only if they coincide -/ lemma Hausdorff_edist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t) : Hausdorff_edist s t = 0 ↔ s = t := by rw [Hausdorff_edist_zero_iff_closure_eq_closure, closure_eq_iff_is_closed.2 hs, closure_eq_iff_is_closed.2 ht] /-- The Haudorff edistance to the empty set is infinite -/ lemma Hausdorff_edist_empty (ne : s ≠ ∅) : Hausdorff_edist s ∅ = ∞ := begin rcases exists_mem_of_ne_empty ne with ⟨x, xs⟩, have : inf_edist x ∅ ≤ Hausdorff_edist s ∅ := inf_edist_le_Hausdorff_edist_of_mem xs, simpa using this, end /-- If a set is at finite Hausdorff edistance of a nonempty set, it is nonempty -/ lemma ne_empty_of_Hausdorff_edist_ne_top (hs : s ≠ ∅) (fin : Hausdorff_edist s t ≠ ⊤) : t ≠ ∅ := begin by_contradiction h, simp only [not_not, ne.def] at h, rw [h, Hausdorff_edist_empty hs] at fin, simpa using fin end end Hausdorff_edist -- section end emetric --namespace /-Now, we turn to the same notions in metric spaces. To avoid the difficulties related to Inf and Sup on ℝ (which is only conditionnally complete), we use the notions in ennreal formulated in terms of the edistance, and coerce them to ℝ. Then their properties follow readily from the corresponding properties in ennreal, modulo some tedious rewriting of inequalities from one to the other -/ namespace metric section variables {α : Type u} {β : Type v} [metric_space α] [metric_space β] {s t u : set α} {x y : α} {Φ : α → β} open emetric /-- The minimal distance of a point to a set -/ def inf_dist (x : α) (s : set α) : ℝ := ennreal.to_real (inf_edist x s) /-- the minimal distance is always nonnegative -/ lemma inf_dist_nonneg : 0 ≤ inf_dist x s := by simp [inf_dist] /-- the minimal distance to the empty set is 0 (if you want to have the more reasonable value ∞ instead, use `inf_edist`, which takes values in ennreal) -/ @[simp] lemma inf_dist_empty : inf_dist x ∅ = 0 := by simp [inf_dist] /-- In a metric space, the minimal edistance to a nonempty set is finite -/ lemma inf_edist_ne_top (h : s ≠ ∅) : inf_edist x s ≠ ⊤ := begin rcases exists_mem_of_ne_empty h with ⟨y, hy⟩, apply lt_top_iff_ne_top.1, calc inf_edist x s ≤ edist x y : inf_edist_le_edist_of_mem hy ... < ⊤ : lt_top_iff_ne_top.2 (edist_ne_top _ _) end /-- The minimal distance of a point to a set containing it vanishes -/ lemma inf_dist_zero_of_mem (h : x ∈ s) : inf_dist x s = 0 := by simp [inf_edist_zero_of_mem h, inf_dist] /-- The minimal distance to a singleton is the distance to the unique point in this singleton -/ @[simp] lemma inf_dist_singleton : inf_dist x {y} = dist x y := by simp [inf_dist, inf_edist, dist_edist] /-- The minimal distance to a set is bounded by the distance to any point in this set -/ lemma inf_dist_le_dist_of_mem (h : y ∈ s) : inf_dist x s ≤ dist x y := begin rw [dist_edist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top (ne_empty_of_mem h)) (edist_ne_top _ _)], exact inf_edist_le_edist_of_mem h end /-- The minimal distance is monotonous with respect to inclusion -/ lemma inf_dist_le_inf_dist_of_subset (h : s ⊆ t) (hs : s ≠ ∅) : inf_dist x t ≤ inf_dist x s := begin rcases ne_empty_iff_exists_mem.1 hs with ⟨y, hy⟩, have ht : t ≠ ∅ := ne_empty_of_mem (h hy), rw [inf_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) (inf_edist_ne_top hs)], exact inf_edist_le_inf_edist_of_subset h end /-- If the minimal distance to a set is `<r`, there exists a point in this set at distance `<r` -/ lemma exists_dist_lt_of_inf_dist_lt {r : real} (h : inf_dist x s < r) (hs : s ≠ ∅) : ∃y∈s, dist x y < r := begin have rpos : 0 < r := lt_of_le_of_lt inf_dist_nonneg h, have : inf_edist x s < ennreal.of_real r, { rwa [inf_dist, ← ennreal.to_real_of_real (le_of_lt rpos), ennreal.to_real_lt_to_real (inf_edist_ne_top hs)] at h, simp }, rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, hy⟩, rw [edist_dist, ennreal.of_real_lt_of_real_iff rpos] at hy, exact ⟨y, ys, hy⟩, end /-- The minimal distance from `x` to `s` is bounded by the distance from `y` to `s`, modulo the distance between `x` and `y` -/ lemma inf_dist_le_inf_dist_add_dist : inf_dist x s ≤ inf_dist y s + dist x y := begin by_cases hs : s = ∅, { by simp [hs, dist_nonneg] }, { rw [inf_dist, inf_dist, dist_edist, ← ennreal.to_real_add (inf_edist_ne_top hs) (edist_ne_top _ _), ennreal.to_real_le_to_real (inf_edist_ne_top hs)], { apply inf_edist_le_inf_edist_add_edist }, { simp [ennreal.add_eq_top, inf_edist_ne_top hs, edist_ne_top] }} end /-- The minimal distance to a set is uniformly continuous -/ lemma uniform_continuous_inf_dist : uniform_continuous (λx, inf_dist x s) := uniform_continuous_of_le_add 1 (by simp [inf_dist_le_inf_dist_add_dist]) /-- The minimal distance to a set is continuous -/ lemma continuous_inf_dist : continuous (λx, inf_dist x s) := uniform_continuous_inf_dist.continuous /-- The minimal distance to a set and its closure coincide -/ lemma inf_dist_eq_closure : inf_dist x (closure s) = inf_dist x s := by simp [inf_dist, inf_edist_closure] /-- A point belongs to the closure of `s` iff its infimum distance to this set vanishes -/ lemma mem_closure_iff_inf_dist_zero (h : s ≠ ∅) : x ∈ closure s ↔ inf_dist x s = 0 := by simp [mem_closure_iff_inf_edist_zero, inf_dist, ennreal.to_real_eq_zero_iff, inf_edist_ne_top h] /-- Given a closed set `s`, a point belongs to `s` iff its infimum distance to this set vanishes -/ lemma mem_iff_ind_dist_zero_of_closed (h : is_closed s) (hs : s ≠ ∅) : x ∈ s ↔ inf_dist x s = 0 := begin have := @mem_closure_iff_inf_dist_zero _ _ s x hs, rwa closure_eq_iff_is_closed.2 h at this end /-- The infimum distance is invariant under isometries -/ lemma inf_dist_image (hΦ : isometry Φ) : inf_dist (Φ x) (Φ '' t) = inf_dist x t := by simp [inf_dist, inf_edist_image hΦ] /-- The Hausdorff distance between two sets is the smallest nonnegative `r` such that each set is included in the `r`-neighborhood of the other. If there is no such `r`, it is defined to be `0`, arbitrarily -/ def Hausdorff_dist (s t : set α) : ℝ := ennreal.to_real (Hausdorff_edist s t) /-- The Hausdorff distance is nonnegative -/ lemma Hausdorff_dist_nonneg : 0 ≤ Hausdorff_dist s t := by simp [Hausdorff_dist] /-- If two sets are nonempty and bounded in a metric space, they are at finite Hausdorff edistance -/ lemma Hausdorff_edist_ne_top_of_ne_empty_of_bounded (hs : s ≠ ∅) (ht : t ≠ ∅) (bs : bounded s) (bt : bounded t) : Hausdorff_edist s t ≠ ⊤ := begin rcases ne_empty_iff_exists_mem.1 hs with ⟨cs, hcs⟩, rcases ne_empty_iff_exists_mem.1 ht with ⟨ct, hct⟩, rcases (bounded_iff_subset_ball ct).1 bs with ⟨rs, hrs⟩, rcases (bounded_iff_subset_ball cs).1 bt with ⟨rt, hrt⟩, have : Hausdorff_edist s t ≤ ennreal.of_real (max rs rt), { apply Hausdorff_edist_le_of_mem_edist, { assume x xs, existsi [ct, hct], have : dist x ct ≤ max rs rt := le_trans (hrs xs) (le_max_left _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }, { assume x xt, existsi [cs, hcs], have : dist x cs ≤ max rs rt := le_trans (hrt xt) (le_max_right _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }}, exact ennreal.lt_top_iff_ne_top.1 (lt_of_le_of_lt this (by simp [lt_top_iff_ne_top])) end /-- The Hausdorff distance between a set and itself is zero -/ @[simp] lemma Hausdorff_dist_self_zero : Hausdorff_dist s s = 0 := by simp [Hausdorff_dist] /-- The Hausdorff distance from `s` to `t` and from `t` to `s` coincide -/ lemma Hausdorff_dist_comm : Hausdorff_dist s t = Hausdorff_dist t s := by simp [Hausdorff_dist, Hausdorff_edist_comm] /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ennreal) -/ @[simp] lemma Hausdorff_dist_empty : Hausdorff_dist s ∅ = 0 := begin by_cases h : s = ∅, { simp [h] }, { simp [Hausdorff_dist, Hausdorff_edist_empty h] } end /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ennreal) -/ @[simp] lemma Hausdorff_dist_empty' : Hausdorff_dist ∅ s = 0 := by simp [Hausdorff_dist_comm] /-- Bounding the Hausdorff distance by bounding the distance of any point in each set to the other set -/ lemma Hausdorff_dist_le_of_inf_dist {r : ℝ} (hr : r ≥ 0) (H1 : ∀x ∈ s, inf_dist x t ≤ r) (H2 : ∀x ∈ t, inf_dist x s ≤ r) : Hausdorff_dist s t ≤ r := begin by_cases h : (Hausdorff_edist s t = ⊤) ∨ (s = ∅) ∨ (t = ∅), { rcases h with h1 | h2 | h3, { simpa [Hausdorff_dist, h1] }, { simpa [h2] }, { simpa [h3] }}, { simp only [not_or_distrib] at h, have : Hausdorff_edist s t ≤ ennreal.of_real r, { apply Hausdorff_edist_le_of_inf_edist _ _, { assume x hx, have I := H1 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top h.2.2) ennreal.of_real_ne_top] at I }, { assume x hx, have I := H2 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top h.2.1) ennreal.of_real_ne_top] at I }}, rwa [Hausdorff_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real h.1 ennreal.of_real_ne_top] } end /-- Bounding the Hausdorff distance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_dist_le_of_mem_dist {r : ℝ} (hr : 0 ≤ r) (H1 : ∀x ∈ s, ∃y ∈ t, dist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, dist x y ≤ r) : Hausdorff_dist s t ≤ r := begin apply Hausdorff_dist_le_of_inf_dist hr, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_dist_le_dist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_dist_le_dist_of_mem ys) hy } end /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_dist_le_diam (hs : s ≠ ∅) (bs : bounded s) (ht : t ≠ ∅) (bt : bounded t) : Hausdorff_dist s t ≤ diam (s ∪ t) := begin rcases ne_empty_iff_exists_mem.1 hs with ⟨x, xs⟩, rcases ne_empty_iff_exists_mem.1 ht with ⟨y, yt⟩, refine Hausdorff_dist_le_of_mem_dist diam_nonneg _ _, { exact λz hz, ⟨y, yt, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { exact λz hz, ⟨x, xs, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_dist_le_Hausdorff_dist_of_mem (hx : x ∈ s) (fin : Hausdorff_edist s t ≠ ⊤) : inf_dist x t ≤ Hausdorff_dist s t := begin have ht : t ≠ ∅ := ne_empty_of_Hausdorff_edist_ne_top (ne_empty_of_mem hx) fin, rw [Hausdorff_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) fin], exact inf_edist_le_Hausdorff_edist_of_mem hx end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt {r : ℝ} (h : x ∈ s) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t ≠ ⊤) : ∃y∈t, dist x y < r := begin have r0 : 0 < r := lt_of_le_of_lt (Hausdorff_dist_nonneg) H, have : Hausdorff_edist s t < ennreal.of_real r, by rwa [Hausdorff_dist, ← ennreal.to_real_of_real (le_of_lt r0), ennreal.to_real_lt_to_real fin (ennreal.of_real_ne_top)] at H, rcases exists_edist_lt_of_Hausdorff_edist_lt h this with ⟨y, hy, yr⟩, rw [edist_dist, ennreal.of_real_lt_of_real_iff r0] at yr, exact ⟨y, hy, yr⟩ end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt' {r : ℝ} (h : y ∈ t) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t ≠ ⊤) : ∃x∈s, dist x y < r := begin rw Hausdorff_dist_comm at H, rw Hausdorff_edist_comm at fin, simpa [dist_comm] using exists_dist_lt_of_Hausdorff_dist_lt h H fin end /-- The infimum distance to `s` and `t` are the same, up to the Hausdorff distance between `s` and `t` -/ lemma inf_dist_le_inf_dist_add_Hausdorff_dist (fin : Hausdorff_edist s t ≠ ⊤) : inf_dist x t ≤ inf_dist x s + Hausdorff_dist s t := begin by_cases (s = ∅) ∨ (t = ∅), { rcases h with h1 |h2, { have : t = ∅, { by_contradiction ht, rw Hausdorff_edist_comm at fin, exact ne_empty_of_Hausdorff_edist_ne_top ht fin h1 }, simp [‹s = ∅›, ‹t = ∅›] }, { have : s = ∅, { by_contradiction hs, exact ne_empty_of_Hausdorff_edist_ne_top hs fin h2 }, simp [‹s = ∅›, ‹t = ∅›] }}, { rw not_or_distrib at h, rw [inf_dist, inf_dist, Hausdorff_dist, ← ennreal.to_real_add (inf_edist_ne_top h.1) fin, ennreal.to_real_le_to_real (inf_edist_ne_top h.2)], { exact inf_edist_le_inf_edist_add_Hausdorff_edist }, { simp [ennreal.add_eq_top, not_or_distrib, fin, inf_edist_ne_top h.1] }} end /-- The Hausdorff distance is invariant under isometries -/ lemma Hausdorff_dist_image (h : isometry Φ) : Hausdorff_dist (Φ '' s) (Φ '' t) = Hausdorff_dist s t := by simp [Hausdorff_dist, Hausdorff_edist_image h] /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u := begin by_cases Hausdorff_edist s u = ⊤, { calc Hausdorff_dist s u = 0 + 0 : by simp [Hausdorff_dist, h] ... ≤ Hausdorff_dist s t + Hausdorff_dist t u : add_le_add (Hausdorff_dist_nonneg) (Hausdorff_dist_nonneg) }, { have Dtu : Hausdorff_edist t u < ⊤ := calc Hausdorff_edist t u ≤ Hausdorff_edist t s + Hausdorff_edist s u : Hausdorff_edist_triangle ... = Hausdorff_edist s t + Hausdorff_edist s u : by simp [Hausdorff_edist_comm] ... < ⊤ : by simp [ennreal.add_lt_top]; simp [ennreal.lt_top_iff_ne_top, h, fin], rw [Hausdorff_dist, Hausdorff_dist, Hausdorff_dist, ← ennreal.to_real_add fin (lt_top_iff_ne_top.1 Dtu), ennreal.to_real_le_to_real h], { exact Hausdorff_edist_triangle }, { simp [ennreal.add_eq_top, lt_top_iff_ne_top.1 Dtu, fin] }} end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle' (fin : Hausdorff_edist t u ≠ ⊤) : Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u := begin rw Hausdorff_edist_comm at fin, have I : Hausdorff_dist u s ≤ Hausdorff_dist u t + Hausdorff_dist t s := Hausdorff_dist_triangle fin, simpa [add_comm, Hausdorff_dist_comm] using I end /-- The Hausdorff distance between a set and its closure vanish -/ @[simp] lemma Hausdorff_dist_self_closure : Hausdorff_dist s (closure s) = 0 := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closure₁ : Hausdorff_dist (closure s) t = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closure₂ : Hausdorff_dist s (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- The Hausdorff distance between two sets and their closures coincide -/ @[simp] lemma Hausdorff_dist_closure : Hausdorff_dist (closure s) (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Two sets are at zero Hausdorff distance if and only if they have the same closures -/ lemma Hausdorff_dist_zero_iff_closure_eq_closure (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ closure s = closure t := by simp [Hausdorff_edist_zero_iff_closure_eq_closure.symm, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] /-- Two closed sets are at zero Hausdorff distance if and only if they coincide -/ lemma Hausdorff_dist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t) (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ s = t := by simp [(Hausdorff_edist_zero_iff_eq_of_closed hs ht).symm, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] end --section end metric --namespace
(* Title: HOL/Number_Theory/Residues.thy Author: Jeremy Avigad An algebraic treatment of residue rings, and resulting proofs of Euler's theorem and Wilson's theorem. *) section \<open>Residue rings\<close> theory Residues imports Cong "HOL-Algebra.Multiplicative_Group" Totient begin definition QuadRes :: "int \<Rightarrow> int \<Rightarrow> bool" where "QuadRes p a = (\<exists>y. ([y^2 = a] (mod p)))" definition Legendre :: "int \<Rightarrow> int \<Rightarrow> int" where "Legendre a p = (if ([a = 0] (mod p)) then 0 else if QuadRes p a then 1 else -1)" subsection \<open>A locale for residue rings\<close> definition residue_ring :: "int \<Rightarrow> int ring" where "residue_ring m = \<lparr>carrier = {0..m - 1}, monoid.mult = \<lambda>x y. (x * y) mod m, one = 1, zero = 0, add = \<lambda>x y. (x + y) mod m\<rparr>" locale residues = fixes m :: int and R (structure) assumes m_gt_one: "m > 1" defines "R \<equiv> residue_ring m" begin lemma abelian_group: "abelian_group R" proof - have "\<exists>y\<in>{0..m - 1}. (x + y) mod m = 0" if "0 \<le> x" "x < m" for x proof (cases "x = 0") case True with m_gt_one show ?thesis by simp next case False then have "(x + (m - x)) mod m = 0" by simp with m_gt_one that show ?thesis by (metis False atLeastAtMost_iff diff_ge_0_iff_ge diff_left_mono int_one_le_iff_zero_less less_le) qed with m_gt_one show ?thesis by (fastforce simp add: R_def residue_ring_def mod_add_right_eq ac_simps intro!: abelian_groupI) qed lemma comm_monoid: "comm_monoid R" unfolding R_def residue_ring_def apply (rule comm_monoidI) using m_gt_one apply auto apply (metis mod_mult_right_eq mult.assoc mult.commute) apply (metis mult.commute) done lemma cring: "cring R" apply (intro cringI abelian_group comm_monoid) unfolding R_def residue_ring_def apply (auto simp add: comm_semiring_class.distrib mod_add_eq mod_mult_left_eq) done end sublocale residues < cring by (rule cring) context residues begin text \<open> These lemmas translate back and forth between internal and external concepts. \<close> lemma res_carrier_eq: "carrier R = {0..m - 1}" by (auto simp: R_def residue_ring_def) lemma res_add_eq: "x \<oplus> y = (x + y) mod m" by (auto simp: R_def residue_ring_def) lemma res_mult_eq: "x \<otimes> y = (x * y) mod m" by (auto simp: R_def residue_ring_def) lemma res_zero_eq: "\<zero> = 0" by (auto simp: R_def residue_ring_def) lemma res_one_eq: "\<one> = 1" by (auto simp: R_def residue_ring_def units_of_def) lemma res_units_eq: "Units R = {x. 0 < x \<and> x < m \<and> coprime x m}" using m_gt_one apply (auto simp add: Units_def R_def residue_ring_def ac_simps invertible_coprime intro: ccontr) apply (subst (asm) coprime_iff_invertible'_int) apply (auto simp add: cong_def) done lemma res_neg_eq: "\<ominus> x = (- x) mod m" using m_gt_one unfolding R_def a_inv_def m_inv_def residue_ring_def apply simp apply (rule the_equality) apply (simp add: mod_add_right_eq) apply (simp add: add.commute mod_add_right_eq) apply (metis add.right_neutral minus_add_cancel mod_add_right_eq mod_pos_pos_trivial) done lemma finite [iff]: "finite (carrier R)" by (simp add: res_carrier_eq) lemma finite_Units [iff]: "finite (Units R)" by (simp add: finite_ring_finite_units) text \<open> The function \<open>a \<mapsto> a mod m\<close> maps the integers to the residue classes. The following lemmas show that this mapping respects addition and multiplication on the integers. \<close> lemma mod_in_carrier [iff]: "a mod m \<in> carrier R" unfolding res_carrier_eq using insert m_gt_one by auto lemma add_cong: "(x mod m) \<oplus> (y mod m) = (x + y) mod m" by (auto simp: R_def residue_ring_def mod_simps) lemma mult_cong: "(x mod m) \<otimes> (y mod m) = (x * y) mod m" by (auto simp: R_def residue_ring_def mod_simps) lemma zero_cong: "\<zero> = 0" by (auto simp: R_def residue_ring_def) lemma one_cong: "\<one> = 1 mod m" using m_gt_one by (auto simp: R_def residue_ring_def) (* FIXME revise algebra library to use 1? *) lemma pow_cong: "(x mod m) [^] n = x^n mod m" using m_gt_one apply (induct n) apply (auto simp add: nat_pow_def one_cong) apply (metis mult.commute mult_cong) done lemma neg_cong: "\<ominus> (x mod m) = (- x) mod m" by (metis mod_minus_eq res_neg_eq) lemma (in residues) prod_cong: "finite A \<Longrightarrow> (\<Otimes>i\<in>A. (f i) mod m) = (\<Prod>i\<in>A. f i) mod m" by (induct set: finite) (auto simp: one_cong mult_cong) lemma (in residues) sum_cong: "finite A \<Longrightarrow> (\<Oplus>i\<in>A. (f i) mod m) = (\<Sum>i\<in>A. f i) mod m" by (induct set: finite) (auto simp: zero_cong add_cong) lemma mod_in_res_units [simp]: assumes "1 < m" and "coprime a m" shows "a mod m \<in> Units R" proof (cases "a mod m = 0") case True with assms show ?thesis by (auto simp add: res_units_eq gcd_red_int [symmetric]) next case False from assms have "0 < m" by simp then have "0 \<le> a mod m" by (rule pos_mod_sign [of m a]) with False have "0 < a mod m" by simp with assms show ?thesis by (auto simp add: res_units_eq gcd_red_int [symmetric] ac_simps) qed lemma res_eq_to_cong: "(a mod m) = (b mod m) \<longleftrightarrow> [a = b] (mod m)" by (auto simp: cong_def) text \<open>Simplifying with these will translate a ring equation in R to a congruence.\<close> lemmas res_to_cong_simps = add_cong mult_cong pow_cong one_cong prod_cong sum_cong neg_cong res_eq_to_cong text \<open>Other useful facts about the residue ring.\<close> lemma one_eq_neg_one: "\<one> = \<ominus> \<one> \<Longrightarrow> m = 2" apply (simp add: res_one_eq res_neg_eq) apply (metis add.commute add_diff_cancel mod_mod_trivial one_add_one uminus_add_conv_diff zero_neq_one zmod_zminus1_eq_if) done end subsection \<open>Prime residues\<close> locale residues_prime = fixes p :: nat and R (structure) assumes p_prime [intro]: "prime p" defines "R \<equiv> residue_ring (int p)" sublocale residues_prime < residues p unfolding R_def residues_def using p_prime apply auto apply (metis (full_types) of_nat_1 of_nat_less_iff prime_gt_1_nat) done context residues_prime begin lemma p_coprime_left: "coprime p a \<longleftrightarrow> \<not> p dvd a" using p_prime by (auto intro: prime_imp_coprime dest: coprime_common_divisor) lemma p_coprime_right: "coprime a p \<longleftrightarrow> \<not> p dvd a" using p_coprime_left [of a] by (simp add: ac_simps) lemma p_coprime_left_int: "coprime (int p) a \<longleftrightarrow> \<not> int p dvd a" using p_prime by (auto intro: prime_imp_coprime dest: coprime_common_divisor) lemma p_coprime_right_int: "coprime a (int p) \<longleftrightarrow> \<not> int p dvd a" using p_coprime_left_int [of a] by (simp add: ac_simps) lemma is_field: "field R" proof - have "0 < x \<Longrightarrow> x < int p \<Longrightarrow> coprime (int p) x" for x by (rule prime_imp_coprime) (auto simp add: zdvd_not_zless) then show ?thesis by (intro cring.field_intro2 cring) (auto simp add: res_carrier_eq res_one_eq res_zero_eq res_units_eq ac_simps) qed lemma res_prime_units_eq: "Units R = {1..p - 1}" apply (subst res_units_eq) apply (auto simp add: p_coprime_right_int zdvd_not_zless) done end sublocale residues_prime < field by (rule is_field) section \<open>Test cases: Euler's theorem and Wilson's theorem\<close> subsection \<open>Euler's theorem\<close> lemma (in residues) totatives_eq: "totatives (nat m) = nat ` Units R" proof - from m_gt_one have "\<bar>m\<bar> > 1" by simp then have "totatives (nat \<bar>m\<bar>) = nat ` abs ` Units R" by (auto simp add: totatives_def res_units_eq image_iff le_less) (use m_gt_one zless_nat_eq_int_zless in force) moreover have "\<bar>m\<bar> = m" "abs ` Units R = Units R" using m_gt_one by (auto simp add: res_units_eq image_iff) ultimately show ?thesis by simp qed lemma (in residues) totient_eq: "totient (nat m) = card (Units R)" proof - have *: "inj_on nat (Units R)" by (rule inj_onI) (auto simp add: res_units_eq) then show ?thesis by (simp add: totient_def totatives_eq card_image) qed lemma (in residues_prime) totient_eq: "totient p = p - 1" using totient_eq by (simp add: res_prime_units_eq) lemma (in residues) euler_theorem: assumes "coprime a m" shows "[a ^ totient (nat m) = 1] (mod m)" proof - have "a ^ totient (nat m) mod m = 1 mod m" by (metis assms finite_Units m_gt_one mod_in_res_units one_cong totient_eq pow_cong units_power_order_eq_one) then show ?thesis using res_eq_to_cong by blast qed lemma euler_theorem: fixes a m :: nat assumes "coprime a m" shows "[a ^ totient m = 1] (mod m)" proof (cases "m = 0 \<or> m = 1") case True then show ?thesis by auto next case False with assms show ?thesis using residues.euler_theorem [of "int m" "int a"] cong_int_iff by (auto simp add: residues_def gcd_int_def) fastforce qed lemma fermat_theorem: fixes p a :: nat assumes "prime p" and "\<not> p dvd a" shows "[a ^ (p - 1) = 1] (mod p)" proof - from assms prime_imp_coprime [of p a] have "coprime a p" by (auto simp add: ac_simps) then have "[a ^ totient p = 1] (mod p)" by (rule euler_theorem) also have "totient p = p - 1" by (rule totient_prime) (rule assms) finally show ?thesis . qed subsection \<open>Wilson's theorem\<close> lemma (in field) inv_pair_lemma: "x \<in> Units R \<Longrightarrow> y \<in> Units R \<Longrightarrow> {x, inv x} \<noteq> {y, inv y} \<Longrightarrow> {x, inv x} \<inter> {y, inv y} = {}" apply auto apply (metis Units_inv_inv)+ done lemma (in residues_prime) wilson_theorem1: assumes a: "p > 2" shows "[fact (p - 1) = (-1::int)] (mod p)" proof - let ?Inverse_Pairs = "{{x, inv x}| x. x \<in> Units R - {\<one>, \<ominus> \<one>}}" have UR: "Units R = {\<one>, \<ominus> \<one>} \<union> \<Union>?Inverse_Pairs" by auto have "(\<Otimes>i\<in>Units R. i) = (\<Otimes>i\<in>{\<one>, \<ominus> \<one>}. i) \<otimes> (\<Otimes>i\<in>\<Union>?Inverse_Pairs. i)" apply (subst UR) apply (subst finprod_Un_disjoint) apply (auto intro: funcsetI) using inv_one apply auto[1] using inv_eq_neg_one_eq apply auto done also have "(\<Otimes>i\<in>{\<one>, \<ominus> \<one>}. i) = \<ominus> \<one>" apply (subst finprod_insert) apply auto apply (frule one_eq_neg_one) using a apply force done also have "(\<Otimes>i\<in>(\<Union>?Inverse_Pairs). i) = (\<Otimes>A\<in>?Inverse_Pairs. (\<Otimes>y\<in>A. y))" apply (subst finprod_Union_disjoint) apply (auto simp: pairwise_def disjnt_def) apply (metis Units_inv_inv)+ done also have "\<dots> = \<one>" apply (rule finprod_one_eqI) apply auto apply (subst finprod_insert) apply auto apply (metis inv_eq_self) done finally have "(\<Otimes>i\<in>Units R. i) = \<ominus> \<one>" by simp also have "(\<Otimes>i\<in>Units R. i) = (\<Otimes>i\<in>Units R. i mod p)" by (rule finprod_cong') (auto simp: res_units_eq) also have "\<dots> = (\<Prod>i\<in>Units R. i) mod p" by (rule prod_cong) auto also have "\<dots> = fact (p - 1) mod p" apply (simp add: fact_prod) using assms apply (subst res_prime_units_eq) apply (simp add: int_prod zmod_int prod_int_eq) done finally have "fact (p - 1) mod p = \<ominus> \<one>" . then show ?thesis by (simp add: cong_def res_neg_eq res_one_eq zmod_int) qed lemma wilson_theorem: assumes "prime p" shows "[fact (p - 1) = - 1] (mod p)" proof (cases "p = 2") case True then show ?thesis by (simp add: cong_def fact_prod) next case False then show ?thesis using assms prime_ge_2_nat by (metis residues_prime.wilson_theorem1 residues_prime.intro le_eq_less_or_eq) qed text \<open> This result can be transferred to the multiplicative group of \<open>\<int>/p\<int>\<close> for \<open>p\<close> prime.\<close> lemma mod_nat_int_pow_eq: fixes n :: nat and p a :: int shows "a \<ge> 0 \<Longrightarrow> p \<ge> 0 \<Longrightarrow> (nat a ^ n) mod (nat p) = nat ((a ^ n) mod p)" by (simp add: int_one_le_iff_zero_less nat_mod_distrib order_less_imp_le nat_power_eq[symmetric]) theorem residue_prime_mult_group_has_gen: fixes p :: nat assumes prime_p : "prime p" shows "\<exists>a \<in> {1 .. p - 1}. {1 .. p - 1} = {a^i mod p|i . i \<in> UNIV}" proof - have "p \<ge> 2" using prime_gt_1_nat[OF prime_p] by simp interpret R: residues_prime p "residue_ring p" by (simp add: residues_prime_def prime_p) have car: "carrier (residue_ring (int p)) - {\<zero>\<^bsub>residue_ring (int p)\<^esub>} = {1 .. int p - 1}" by (auto simp add: R.zero_cong R.res_carrier_eq) have "x [^]\<^bsub>residue_ring (int p)\<^esub> i = x ^ i mod (int p)" if "x \<in> {1 .. int p - 1}" for x and i :: nat using that R.pow_cong[of x i] by auto moreover obtain a where a: "a \<in> {1 .. int p - 1}" and a_gen: "{1 .. int p - 1} = {a[^]\<^bsub>residue_ring (int p)\<^esub>i|i::nat . i \<in> UNIV}" using field.finite_field_mult_group_has_gen[OF R.is_field] by (auto simp add: car[symmetric] carrier_mult_of) moreover have "nat ` {1 .. int p - 1} = {1 .. p - 1}" (is "?L = ?R") proof have "n \<in> ?R" if "n \<in> ?L" for n using that \<open>p\<ge>2\<close> by force then show "?L \<subseteq> ?R" by blast have "n \<in> ?L" if "n \<in> ?R" for n using that \<open>p\<ge>2\<close> by (auto intro: rev_image_eqI [of "int n"]) then show "?R \<subseteq> ?L" by blast qed moreover have "nat ` {a^i mod (int p) | i::nat. i \<in> UNIV} = {nat a^i mod p | i . i \<in> UNIV}" (is "?L = ?R") proof have "x \<in> ?R" if "x \<in> ?L" for x proof - from that obtain i where i: "x = nat (a^i mod (int p))" by blast then have "x = nat a ^ i mod p" using mod_nat_int_pow_eq[of a "int p" i] a \<open>p\<ge>2\<close> by auto with i show ?thesis by blast qed then show "?L \<subseteq> ?R" by blast have "x \<in> ?L" if "x \<in> ?R" for x proof - from that obtain i where i: "x = nat a^i mod p" by blast with mod_nat_int_pow_eq[of a "int p" i] a \<open>p\<ge>2\<close> show ?thesis by auto qed then show "?R \<subseteq> ?L" by blast qed ultimately have "{1 .. p - 1} = {nat a^i mod p | i. i \<in> UNIV}" by presburger moreover from a have "nat a \<in> {1 .. p - 1}" by force ultimately show ?thesis .. qed subsection \<open>Upper bound for the number of $n$-th roots\<close> lemma roots_mod_prime_bound: fixes n c p :: nat assumes "prime p" "n > 0" defines "A \<equiv> {x\<in>{..<p}. [x ^ n = c] (mod p)}" shows "card A \<le> n" proof - define R where "R = residue_ring (int p)" from assms(1) interpret residues_prime p R by unfold_locales (simp_all add: R_def) interpret R: UP_domain R "UP R" by (unfold_locales) let ?f = "UnivPoly.monom (UP R) \<one>\<^bsub>R\<^esub> n \<ominus>\<^bsub>(UP R)\<^esub> UnivPoly.monom (UP R) (int (c mod p)) 0" have in_carrier: "int (c mod p) \<in> carrier R" using prime_gt_1_nat[OF assms(1)] by (simp add: R_def residue_ring_def) have "deg R ?f = n" using assms in_carrier by (simp add: R.deg_minus_eq) hence f_not_zero: "?f \<noteq> \<zero>\<^bsub>UP R\<^esub>" using assms by (auto simp add : R.deg_nzero_nzero) have roots_bound: "finite {a \<in> carrier R. UnivPoly.eval R R id a ?f = \<zero>\<^bsub>R\<^esub>} \<and> card {a \<in> carrier R. UnivPoly.eval R R id a ?f = \<zero>\<^bsub>R\<^esub>} \<le> deg R ?f" using finite in_carrier by (intro R.roots_bound[OF _ f_not_zero]) simp have subs: "{x \<in> carrier R. x [^]\<^bsub>R\<^esub> n = int (c mod p)} \<subseteq> {a \<in> carrier R. UnivPoly.eval R R id a ?f = \<zero>\<^bsub>R\<^esub>}" using in_carrier by (auto simp: R.evalRR_simps) then have "card {x \<in> carrier R. x [^]\<^bsub>R\<^esub> n = int (c mod p)} \<le> card {a \<in> carrier R. UnivPoly.eval R R id a ?f = \<zero>\<^bsub>R\<^esub>}" using finite by (intro card_mono) auto also have "\<dots> \<le> n" using \<open>deg R ?f = n\<close> roots_bound by linarith also { fix x assume "x \<in> carrier R" hence "x [^]\<^bsub>R\<^esub> n = (x ^ n) mod (int p)" by (subst pow_cong [symmetric]) (auto simp: R_def residue_ring_def) } hence "{x \<in> carrier R. x [^]\<^bsub>R\<^esub> n = int (c mod p)} = {x \<in> carrier R. [x ^ n = int c] (mod p)}" by (fastforce simp: cong_def zmod_int) also have "bij_betw int A {x \<in> carrier R. [x ^ n = int c] (mod p)}" by (rule bij_betwI[of int _ _ nat]) (use cong_int_iff in \<open>force simp: R_def residue_ring_def A_def\<close>)+ from bij_betw_same_card[OF this] have "card {x \<in> carrier R. [x ^ n = int c] (mod p)} = card A" .. finally show ?thesis . qed end
function [M,linearInd]=subImage(M,nSub) % function M=subImage(M,nSub) % ------------------------------------------------------------------------ % %This function refines the input image M by splitting its voxels in half during nSub times %which contains all folders and sub-folders within the folder specified by %the input pathName. % % Kevin Mattheus Moerman % [email protected] % 18/04/2013 %------------------------------------------------------------------------ %% %TO DO: ADD WARNINGS AND INPUT PARSING HERE % nSub=round(nSub); %% if numel(nSub)==1 nSub=nSub.*ones(1,3); end stepSize_I=1/nSub(1); stepSize_J=1/nSub(2); stepSize_K=1/nSub(3); %Define image coordinates of new voxel centres within image coordinate %system of original coordinate mesh I_range=linspace((0.5+(stepSize_I/2)),(size(M,1)-(stepSize_I/2))+0.5,size(M,1)*nSub(1)); J_range=linspace((0.5+(stepSize_J/2)),(size(M,2)-(stepSize_J/2))+0.5,size(M,2)*nSub(2)); K_range=linspace((0.5+(stepSize_K/2)),(size(M,3)-(stepSize_K/2))+0.5,size(M,3)*nSub(3)); [In,Jn,Kn]=ndgrid(I_range,J_range,K_range); %Coordinate matrices %Rounding the coordinates so they "snap" to the mother voxel indices they %are found in. In=round(In); Jn=round(Jn); Kn=round(Kn); %Convert these subscript indiced to linear indices in the image linearInd =sub2ind(size(M),In,Jn,Kn); %Get intensity values Mc=M(:); %Image as column M=Mc(linearInd); %The refined image %% % _*GIBBON footer text*_ % % License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE> % % GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for % image segmentation, image-based modeling, meshing, and finite element % analysis. % % Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <http://www.gnu.org/licenses/>.
!<@brief The system state vector containing all carbon and !!hydrological, vegetation and soil pools. !> !>@details Defines the system state vector type and creates an instance !>an array of this type called ssv which is then used throughout the !>code. Also created is an instance of the type called ssv_temp. !> !>@author Mark Lomas !>@date July 2016 !>@param sldkfj sldkfj !>@param sldkfj sldkfj !>@todo module compartments use real_precision, only: dp use dims, only: max_cohorts, max_lai_comps, max_root_comps, & max_stem_comps, max_suma_comps type ValAge real(dp) :: val integer :: age end type ValAge type StemComps integer :: no type(ValAge), dimension(max_stem_comps) :: c real(dp) :: tot ! contains ! function total() ! ! end function total end type type RootComps integer :: no type(ValAge), dimension(max_root_comps) :: c real(dp) :: tot ! contains ! function total() ! ! end function total end type type LaiComps integer :: no type(ValAge), dimension(max_lai_comps) :: c real(dp) :: tot ! contains ! function total() ! ! end function total end type type SumaComps integer :: no type(ValAge), dimension(max_suma_comps) :: c real(dp) :: tot ! contains ! function total() ! ! end function total end type end module compartments module system_state use real_precision, only: dp use dims, only: max_cohorts, max_lai_comps, max_root_comps, & max_stem_comps, max_suma_comps use compartments private :: dp, max_cohorts, max_lai_comps, max_root_comps, & max_stem_comps, max_suma_comps public :: ssv, ssv_temp type SystemState !----------------------------------------------------------------------* real(dp), dimension(12,2) :: assj real(dp), dimension(12) :: assv !----------------------------------------------------------------------* real(dp) :: age real(dp), dimension(2) :: bio real(dp) :: cov real(dp) :: ppm real(dp) :: hgt !----------------------------------------------------------------------* real(dp), dimension(4) :: soil_h2o real(dp) :: snow real(dp) :: l_snow !----------------------------------------------------------------------* real(dp), dimension(8) :: c real(dp), dimension(8) :: n real(dp), dimension(3) :: minn real(dp), dimension(3) :: nppstore real(dp) :: slc real(dp) :: rlc real(dp) :: sln real(dp) :: rln !----------------------------------------------------------------------* real(dp), dimension(30) :: sm_trig integer :: bb integer :: ss integer :: bbgs integer :: dsbb integer :: chill integer :: dschill !----------------------------------------------------------------------* type(LaiComps) :: lai type(StemComps) :: stem type(RootComps) :: root type(SumaComps) :: suma !----------------------------------------------------------------------* real(dp) :: stemfr !----------------------------------------------------------------------* real(dp) :: npp real(dp) :: nps real(dp) :: npl real(dp) :: npr real(dp) :: evp !----------------------------------------------------------------------* real(dp) :: dslc real(dp) :: drlc real(dp) :: dsln real(dp) :: drln !----------------------------------------------------------------------* end type type(SystemState) :: ssv(max_cohorts), ssv_temp end module system_state
SUBROUTINE PZEMBED1( N, A, IA, JA, DESCA, B, IB, JB, DESCB, M, IM, $ JM, DESCM, WORK ) * IMPLICIT NONE * * .. Scalar Arguments .. INTEGER N, IA, JA, IB, JB, IM, JM * .. * .. Array Arguments .. INTEGER DESCA( * ), DESCB( * ), DESCM( * ) DOUBLE PRECISION M( * ), WORK( * ) COMPLEX*16 A( * ), B( * ) * .. * * Purpose * ======= * * PZEMBED1() is an auxiliary routine called by PZBSEIG(). * It generates a 2n-by-2n real symmetric matrix * * M = [ real(A)+real(B), imag(A)-imag(B); * -imag(A)-imag(B), real(A)-real(B) ], * * where A is n-by-n Hermitian, and B is n-by-n symmetric. * Only the lower triangular parts of these matrices are referenced. * * No argument check is performed, i.e., * all arguments are assumed to be valid. * * Notes * ===== * * Each global data object is described by an associated description * vector. This vector stores the information required to establish * the mapping between an object element and its corresponding process * and memory location. * * Let A be a generic term for any 2D block cyclicly distributed array. * Such a global array has an associated description vector DESCA. * In the following comments, the character _ should be read as * "of the global array". * * NOTATION STORED IN EXPLANATION * --------------- -------------- -------------------------------------- * DTYPE_A(global) DESCA( DTYPE_ )The descriptor type. In this case, * DTYPE_A = 1. * CTXT_A (global) DESCA( CTXT_ ) The BLACS context handle, indicating * the BLACS process grid A is distribu- * ted over. The context itself is glo- * bal, but the handle (the integer * value) may vary. * M_A (global) DESCA( M_ ) The number of rows in the global * array A. * N_A (global) DESCA( N_ ) The number of columns in the global * array A. * MB_A (global) DESCA( MB_ ) The blocking factor used to distribute * the rows of the array. * NB_A (global) DESCA( NB_ ) The blocking factor used to distribute * the columns of the array. * RSRC_A (global) DESCA( RSRC_ ) The process row over which the first * row of the array A is distributed. * CSRC_A (global) DESCA( CSRC_ ) The process column over which the * first column of the array A is * distributed. * LLD_A (local) DESCA( LLD_ ) The leading dimension of the local * array. LLD_A >= MAX(1,LOCr(M_A)). * * Let K be the number of rows or columns of a distributed matrix, * and assume that its process grid has dimension p x q. * LOCr( K ) denotes the number of elements of K that a process * would receive if K were distributed over the p processes of its * process column. * Similarly, LOCc( K ) denotes the number of elements of K that a * process would receive if K were distributed over the q processes of * its process row. * The values of LOCr() and LOCc() may be determined via a call to the * ScaLAPACK tool function, NUMROC: * LOCr( M ) = NUMROC( M, MB_A, MYROW, RSRC_A, NPROW ), * LOCc( N ) = NUMROC( N, NB_A, MYCOL, CSRC_A, NPCOL ). * An upper bound for these quantities may be computed by: * LOCr( M ) <= ceil( ceil(M/MB_A)/NPROW )*MB_A * LOCc( N ) <= ceil( ceil(N/NB_A)/NPCOL )*NB_A * * Arguments * ========= * * N (global input) INTEGER * The number of rows and columns to be operated on, i.e. the * order of the distributed submatrices sub( A ) and sub( B ). * N >= 0. * * A (local input) COMPLEX*16 pointer into the local memory * to an array of dimension (LLD_A, LOCc(JA+N-1)). * This array contains the local pieces of the N-by-N Hermitian * distributed matrix sub( A ). The leading N-by-N lower * triangular part of sub( A ) contains the lower triangular * part of the distributed matrix, and its strictly upper * triangular part is not referenced. * * IA (global input) INTEGER * The row index in the global array A indicating the first * row of sub( A ). * * JA (global input) INTEGER * The column index in the global array A indicating the * first column of sub( A ). * * DESCA (global and local input) INTEGER array of dimension DLEN_. * The array descriptor for the distributed matrix A. * * B (local input) COMPLEX*16 pointer into the local memory * to an array of dimension (LLD_B, LOCc(JB+N-1)). * This array contains the local pieces of the N-by-N symmetric * distributed matrix sub( B ). The leading N-by-N lower * triangular part of sub( B ) contains the lower triangular * part of the distributed matrix, and its strictly upper * triangular part is not referenced. * * IB (global input) INTEGER * The row index in the global array B indicating the first * row of sub( B ). * * JB (global input) INTEGER * The column index in the global array B indicating the * first column of sub( B ). * * DESCB (global and local input) INTEGER array of dimension DLEN_. * The array descriptor for the distributed matrix B. * * M (local output) DOUBLE PRECISION pointer into the local memory * to an array of dimension (LLD_M, LOCc(JM+2*N-1)). * On exit, this array contains the local pieces of the 2N-by-2N * symmetric distributed matrix sub( M ). The leading 2N-by-2N * lower triangular part of sub( M ) contains the lower * triangular part of the distributed matrix, and its strictly * upper triangular part is not referenced. * * IM (global input) INTEGER * The row index in the global array M indicating the first * row of sub( M ). * * JM (global input) INTEGER * The column index in the global array M indicating the * first column of sub( M ). * * DESCM (global and local input) INTEGER array of dimension DLEN_. * The array descriptor for the distributed matrix M. * * WORK (local output) DOUBLE PRECISION array. * The workspace needs to be at least as big as A and B. * * ===================================================================== * * .. Parameters .. INTEGER BLOCK_CYCLIC_2D, CSRC_, CTXT_, DLEN_, DTYPE_, $ LLD_, MB_, M_, NB_, N_, RSRC_ PARAMETER ( BLOCK_CYCLIC_2D = 1, DLEN_ = 9, DTYPE_ = 1, $ CTXT_ = 2, M_ = 3, N_ = 4, MB_ = 5, NB_ = 6, $ RSRC_ = 7, CSRC_ = 8, LLD_ = 9 ) DOUBLE PRECISION ZERO, ONE PARAMETER ( ZERO = 0.0D+0, ONE = 1.0D+0 ) * .. * .. Local Scalars .. INTEGER ICTXT, NPROW, NPCOL, MYROW, MYCOL, MBA, MBB, $ NBA, NBB, AROWS, ACOLS, LLDA, BROWS, BCOLS, $ LLDB, RSRC, CSRC, I, J, I0, J0 COMPLEX*16 ALPHA, BETA * .. * .. Intrinsic Functions .. INTRINSIC DBLE, DIMAG * .. * .. External Functions .. EXTERNAL NUMROC INTEGER NUMROC * .. * .. External Subroutines .. EXTERNAL BLACS_GRIDINFO, INFOG2L, PDTRADD, $ PDELSET, PZELGET * .. * .. Executable Statements .. * ICTXT = DESCA( CTXT_ ) MBA = DESCA( MB_ ) NBA = DESCA( NB_ ) MBB = DESCB( MB_ ) NBB = DESCB( NB_ ) CALL BLACS_GRIDINFO( ICTXT, NPROW, NPCOL, MYROW, MYCOL ) * IF ( ICTXT .EQ. DESCB( CTXT_ ) .AND. MBA .EQ. NBA .AND. $ MBB .EQ. NBB .AND. IA .EQ. 1 .AND. JA .EQ. 1 .AND. $ IB .EQ. 1 .AND. JB .EQ. 1 ) THEN * * A quick version for almost perfect alignment. * LLDB = DESCB( LLD_ ) BROWS = NUMROC( DESCB( M_ ), MBB, MYROW, 0, NPROW ) BCOLS = NUMROC( DESCB( N_ ), NBB, MYCOL, 0, NPCOL ) CALL INFOG2L( IB, JB, DESCB, NPROW, NPCOL, MYROW, MYCOL, I0, $ J0, RSRC, CSRC ) DO J = J0, BCOLS DO I = I0, BROWS WORK( I + (J-1)*LLDB ) = DBLE( B( I + (J-1)*LLDB ) ) END DO END DO CALL PDTRADD( 'L', 'N', N, N, ONE, WORK, IB, JB, DESCB, ZERO, $ M, IM, JM, DESCM ) CALL PDTRADD( 'L', 'N', N, N, -ONE, WORK, IB, JB, DESCB, ZERO, $ M, IM + N, JM + N, DESCM ) * DO J = J0, BCOLS DO I = I0, BROWS WORK( I + (J-1)*LLDB ) = DIMAG( B( I + (J-1)*LLDB ) ) END DO END DO * * The diagonal of imag(B) is accumulated only once. * CALL PDTRADD( 'L', 'N', N, N, -ONE, WORK, IB, JB, DESCB, ZERO, $ M, IM + N, JM, DESCM ) CALL PDTRADD( 'U', 'T', N, N, -ONE, WORK, IB, JB, DESCB, ZERO, $ M, IM + N, JM, DESCM ) * LLDA = DESCA( LLD_ ) AROWS = NUMROC( DESCA( M_ ), MBA, MYROW, 0, NPROW ) ACOLS = NUMROC( DESCA( N_ ), NBA, MYCOL, 0, NPCOL ) CALL INFOG2L( IA, JA, DESCA, NPROW, NPCOL, MYROW, MYCOL, I0, $ J0, RSRC, CSRC ) * DO J = J0, ACOLS DO I = I0, AROWS WORK( I + (J-1)*LLDA ) = DBLE( A( I + (J-1)*LLDA ) ) END DO END DO CALL PDTRADD( 'L', 'N', N, N, ONE, WORK, IA, JA, DESCA, ONE, $ M, IM, JM, DESCM ) CALL PDTRADD( 'L', 'N', N, N, ONE, WORK, IA, JA, DESCA, ONE, $ M, IM + N, JM + N, DESCM ) * DO J = J0, ACOLS DO I = I0, AROWS WORK( I + (J-1)*LLDA ) = DIMAG( A( I + (J-1)*LLDA ) ) END DO END DO * * The diagonal of imag(A) is accumulated twice. * This is safe because these entries are assumed to be zero. * CALL PDTRADD( 'L', 'N', N, N, -ONE, WORK, IA, JA, DESCA, ONE, $ M, IM + N, JM, DESCM ) CALL PDTRADD( 'U', 'T', N, N, ONE, WORK, IA, JA, DESCA, ONE, $ M, IM + N, JM, DESCM ) * ELSE * * A slow version that handles the general case. * DO J = 0, N-1 DO I = J, N-1 CALL PZELGET( 'A', ' ', ALPHA, A, IA + I, JA + J, DESCA ) CALL PZELGET( 'A', ' ', BETA, B, IB + I, JB + J, DESCB ) CALL PDELSET( M, IM + I, JM + J, DESCM, $ DBLE( ALPHA ) + DBLE( BETA ) ) CALL PDELSET( M, IM + N+I, JM + N+J, DESCM, $ DBLE( ALPHA ) - DBLE( BETA ) ) CALL PDELSET( M, IM + N+J, JM + I, DESCM, $ DIMAG( ALPHA ) - DIMAG( BETA ) ) CALL PDELSET( M, IM + N+I, JM + J, DESCM, $ -DIMAG( ALPHA ) - DIMAG( BETA ) ) END DO END DO END IF * RETURN * * End of PZEMBED1(). * END
The group from Colorado, comprised of frontman Nathaniel Rateliff and seven backing musicians, brought a fusion of funk, blues, and soulful R&B. the bands 60’s blues-rock sound, featuring groovy so. The 120 bpm bangers didn’t have as many peaks and valleys as I might like, but the consisten future ancient tribal kickers with warbling white boy soul glazed on top was delicious. They did that song. Featuring an incredible selection of music, art and activities, AUM NYE FESTIVAL 2017 represents the cutting-edge in. through to early hip hop and electro, soul, funk and RnB. The groovy, infectiou. Peppered with the wondrous echo of groovy sitar strings, the track is equal parts funk jam and breezy pop ballad. Listen in below (via Stereogum). The band have a few fall tour dates lined up, includi. Soulful deep house, for example, will tend towards 120 BPM, while funky house or tech house will be closer. Deep house is on the mellow end of the modern dance music spectrum, and has a warm, groov. Looks like Noisey got Korn frontman Jonathan Davis in on the fun with his own music. I love it too and I appreciate it, but it was time for us to do different types of songs. And it paid off, man. The most visible musical fashions are those we dance to, and dance steps come and go as fashion dictates. Queen Elizabeth I created a scandal when she danced the volta. The waltz, though it now seems. Groovy, right. conflicted (not so F and E who leave after three songs – G and R meanwhile sneak onto the stageside for the first song before being shooed away). His band look like Ford Mondeo funk. Don worries that Megan doesn’t fully appreciate death, while Megan genuinely doesn’t understand how Don could be okay enough with Betty’s condition to go out one night, and then be in a funk the next. The band released its first official song just a. Ariel Pink and Dam-Funk on a recent free mixtape. So even with its new album not yet released, there’s a good idea of what expect from the band’s s. Whether they’re disco screamers, candy-paint EDM nightmares, queasy mutant love ballads, or mind-melting trance weapons, the songs below trace the full spectrum of emotions—from burn-it-all-down anger. Every song on this masterful debut album is excellent. No one bends and blends genres like these guys. Metal, rock, funk, blues and then some, Shade is a delicious and wonderful stew that you must. But here are the top ten hipster bars in Miami. 10. Wood Tavern. There’s Taco Tuesday, offering delicious $2 Mexican street food out of a converted station wagon. Then there’s Sunday’s Backyard Boo. A lot of these kinds of songs gained popularity through the surge in open-airs. Most people in the club played around 120 BPM. So it wasn’t as hectic as all that when slowed down. But still, it’s a. Here he’ll perform a few songs he assembled with Jack White. a blind husband-and-wife duo who marry the spidery guitar rhythms emblematic of Mali with Western funk. Karen O wannabes, get thee to Ti. With the recent stream of discouraging debates, increasing police violence and growing cultural tension, Saxophonist, DJ and producer Grant Kwiecinski (GRiZ) aims to fight the forces of evil with the. Beyond the societal reasons for this song to be in Song of the Summer contention, there is also the simple fact that it is an incredibly catchy song which incorporates solid vocals, a catchy bridge, j. It must be Easter if Whammy and Wine Cellar are opening their doors for this three-night musical extravaganza. With the likes of Tono and the Finance Company, Princess Chelsea, and Street Chant lined.
printf("Hello world!\n");
[GOAL] p : ℕ inst✝⁴ : Fact (Nat.Prime p) k : Type u_1 inst✝³ : CommRing k inst✝² : IsDomain k inst✝¹ : CharP k p inst✝ : PerfectRing k p m : ℤ x : StandardOneDimIsocrystal p k m ⊢ ↑Φ(p, k) x = ↑p ^ m • ↑φ(p, k) x [PROOFSTEP] erw [smul_eq_mul] [GOAL] p : ℕ inst✝⁴ : Fact (Nat.Prime p) k : Type u_1 inst✝³ : CommRing k inst✝² : IsDomain k inst✝¹ : CharP k p inst✝ : PerfectRing k p m : ℤ x : StandardOneDimIsocrystal p k m ⊢ ↑Φ(p, k) x = ↑(IsFractionRing.lift (_ : Function.Injective ↑(algebraMap (WittVector p k) ((fun x => K(p, k)) x)))) (↑p ^ m) * ↑φ(p, k) x [PROOFSTEP] simp only [map_zpow₀, map_natCast] [GOAL] p : ℕ inst✝⁴ : Fact (Nat.Prime p) k : Type u_1 inst✝³ : CommRing k inst✝² : IsDomain k inst✝¹ : CharP k p inst✝ : PerfectRing k p m : ℤ x : StandardOneDimIsocrystal p k m ⊢ ↑Φ(p, k) x = ↑p ^ m * ↑φ(p, k) x [PROOFSTEP] rfl [GOAL] p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 ⊢ ∃ m, Nonempty (StandardOneDimIsocrystal p k m ≃ᶠⁱ[p, k] V) [PROOFSTEP] haveI : Nontrivial V := FiniteDimensional.nontrivial_of_finrank_eq_succ h_dim [GOAL] p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this : Nontrivial V ⊢ ∃ m, Nonempty (StandardOneDimIsocrystal p k m ≃ᶠⁱ[p, k] V) [PROOFSTEP] obtain ⟨x, hx⟩ : ∃ x : V, x ≠ 0 := exists_ne 0 [GOAL] case intro p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this : Nontrivial V x : V hx : x ≠ 0 ⊢ ∃ m, Nonempty (StandardOneDimIsocrystal p k m ≃ᶠⁱ[p, k] V) [PROOFSTEP] have : Φ(p, k) x ≠ 0 := by simpa only [map_zero] using Φ(p, k).injective.ne hx [GOAL] p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this : Nontrivial V x : V hx : x ≠ 0 ⊢ ↑Φ(p, k) x ≠ 0 [PROOFSTEP] simpa only [map_zero] using Φ(p, k).injective.ne hx [GOAL] case intro p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 ⊢ ∃ m, Nonempty (StandardOneDimIsocrystal p k m ≃ᶠⁱ[p, k] V) [PROOFSTEP] obtain ⟨a, ha, hax⟩ : ∃ a : K(p, k), a ≠ 0 ∧ Φ(p, k) x = a • x := by rw [finrank_eq_one_iff_of_nonzero' x hx] at h_dim obtain ⟨a, ha⟩ := h_dim (Φ(p, k) x) refine' ⟨a, _, ha.symm⟩ intro ha' apply this simp only [← ha, ha', zero_smul] [GOAL] p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 ⊢ ∃ a, a ≠ 0 ∧ ↑Φ(p, k) x = a • x [PROOFSTEP] rw [finrank_eq_one_iff_of_nonzero' x hx] at h_dim [GOAL] p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V this✝ : Nontrivial V x : V h_dim : ∀ (w : V), ∃ c, c • x = w hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 ⊢ ∃ a, a ≠ 0 ∧ ↑Φ(p, k) x = a • x [PROOFSTEP] obtain ⟨a, ha⟩ := h_dim (Φ(p, k) x) [GOAL] case intro p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V this✝ : Nontrivial V x : V h_dim : ∀ (w : V), ∃ c, c • x = w hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a • x = ↑Φ(p, k) x ⊢ ∃ a, a ≠ 0 ∧ ↑Φ(p, k) x = a • x [PROOFSTEP] refine' ⟨a, _, ha.symm⟩ [GOAL] case intro p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V this✝ : Nontrivial V x : V h_dim : ∀ (w : V), ∃ c, c • x = w hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a • x = ↑Φ(p, k) x ⊢ a ≠ 0 [PROOFSTEP] intro ha' [GOAL] case intro p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V this✝ : Nontrivial V x : V h_dim : ∀ (w : V), ∃ c, c • x = w hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a • x = ↑Φ(p, k) x ha' : a = 0 ⊢ False [PROOFSTEP] apply this [GOAL] case intro p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V this✝ : Nontrivial V x : V h_dim : ∀ (w : V), ∃ c, c • x = w hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a • x = ↑Φ(p, k) x ha' : a = 0 ⊢ ↑Φ(p, k) x = 0 [PROOFSTEP] simp only [← ha, ha', zero_smul] [GOAL] case intro.intro.intro p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x ⊢ ∃ m, Nonempty (StandardOneDimIsocrystal p k m ≃ᶠⁱ[p, k] V) [PROOFSTEP] obtain ⟨b, hb, m, hmb⟩ := WittVector.exists_frobenius_solution_fractionRing p ha [GOAL] case intro.intro.intro.intro.intro.intro p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑(IsFractionRing.fieldEquivOfRingEquiv (frobeniusEquiv p k)) b * a = ↑p ^ m * b ⊢ ∃ m, Nonempty (StandardOneDimIsocrystal p k m ≃ᶠⁱ[p, k] V) [PROOFSTEP] replace hmb : φ(p, k) b * a = (p : K(p, k)) ^ m * b := by convert hmb [GOAL] p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑(IsFractionRing.fieldEquivOfRingEquiv (frobeniusEquiv p k)) b * a = ↑p ^ m * b ⊢ ↑φ(p, k) b * a = ↑p ^ m * b [PROOFSTEP] convert hmb [GOAL] case intro.intro.intro.intro.intro.intro p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b ⊢ ∃ m, Nonempty (StandardOneDimIsocrystal p k m ≃ᶠⁱ[p, k] V) [PROOFSTEP] use m [GOAL] case h p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b ⊢ Nonempty (StandardOneDimIsocrystal p k m ≃ᶠⁱ[p, k] V) [PROOFSTEP] let F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x [GOAL] case h p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x ⊢ Nonempty (StandardOneDimIsocrystal p k m ≃ᶠⁱ[p, k] V) [PROOFSTEP] let F : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := by refine' LinearEquiv.ofBijective F₀ ⟨_, _⟩ · rw [← LinearMap.ker_eq_bot] exact LinearMap.ker_toSpanSingleton K(p, k) V hx · rw [← LinearMap.range_eq_top] rw [← (finrank_eq_one_iff_of_nonzero x hx).mp h_dim] rw [LinearMap.span_singleton_eq_range] -- Porting note: `refine'` below gets confused when this is inlined. [GOAL] p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x ⊢ StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V [PROOFSTEP] refine' LinearEquiv.ofBijective F₀ ⟨_, _⟩ [GOAL] case refine'_1 p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x ⊢ Function.Injective ↑F₀ [PROOFSTEP] rw [← LinearMap.ker_eq_bot] [GOAL] case refine'_1 p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x ⊢ LinearMap.ker F₀ = ⊥ [PROOFSTEP] exact LinearMap.ker_toSpanSingleton K(p, k) V hx [GOAL] case refine'_2 p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x ⊢ Function.Surjective ↑F₀ [PROOFSTEP] rw [← LinearMap.range_eq_top] [GOAL] case refine'_2 p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x ⊢ LinearMap.range F₀ = ⊤ [PROOFSTEP] rw [← (finrank_eq_one_iff_of_nonzero x hx).mp h_dim] [GOAL] case refine'_2 p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x ⊢ LinearMap.range F₀ = Submodule.span K(p, k) {x} [PROOFSTEP] rw [LinearMap.span_singleton_eq_range] -- Porting note: `refine'` below gets confused when this is inlined. [GOAL] case h p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x F : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.ofBijective F₀ (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀) ⊢ Nonempty (StandardOneDimIsocrystal p k m ≃ᶠⁱ[p, k] V) [PROOFSTEP] let E := (LinearEquiv.smulOfNeZero K(p, k) _ _ hb).trans F [GOAL] case h p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x F : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.ofBijective F₀ (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀) E : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.trans (LinearEquiv.smulOfNeZero K(p, k) (StandardOneDimIsocrystal p k m) b hb) F ⊢ Nonempty (StandardOneDimIsocrystal p k m ≃ᶠⁱ[p, k] V) [PROOFSTEP] refine' ⟨⟨E, _⟩⟩ [GOAL] case h p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x F : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.ofBijective F₀ (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀) E : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.trans (LinearEquiv.smulOfNeZero K(p, k) (StandardOneDimIsocrystal p k m) b hb) F ⊢ ∀ (x : StandardOneDimIsocrystal p k m), ↑Φ(p, k) (↑E x) = ↑E (↑Φ(p, k) x) [PROOFSTEP] simp only [GOAL] case h p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x F : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.ofBijective F₀ (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀) E : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.trans (LinearEquiv.smulOfNeZero K(p, k) (StandardOneDimIsocrystal p k m) b hb) F ⊢ ∀ (x_1 : StandardOneDimIsocrystal p k m), ↑Φ(p, k) (↑(LinearEquiv.trans (LinearEquiv.smulOfNeZero K(p, k) (StandardOneDimIsocrystal p k m) b hb) (LinearEquiv.ofBijective (LinearMap.toSpanSingleton K(p, k) V x) (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀))) x_1) = ↑(LinearEquiv.trans (LinearEquiv.smulOfNeZero K(p, k) (StandardOneDimIsocrystal p k m) b hb) (LinearEquiv.ofBijective (LinearMap.toSpanSingleton K(p, k) V x) (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀))) (↑Φ(p, k) x_1) [PROOFSTEP] intro c [GOAL] case h p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x F : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.ofBijective F₀ (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀) E : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.trans (LinearEquiv.smulOfNeZero K(p, k) (StandardOneDimIsocrystal p k m) b hb) F c : StandardOneDimIsocrystal p k m ⊢ ↑Φ(p, k) (↑(LinearEquiv.trans (LinearEquiv.smulOfNeZero K(p, k) (StandardOneDimIsocrystal p k m) b hb) (LinearEquiv.ofBijective (LinearMap.toSpanSingleton K(p, k) V x) (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀))) c) = ↑(LinearEquiv.trans (LinearEquiv.smulOfNeZero K(p, k) (StandardOneDimIsocrystal p k m) b hb) (LinearEquiv.ofBijective (LinearMap.toSpanSingleton K(p, k) V x) (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀))) (↑Φ(p, k) c) [PROOFSTEP] rw [LinearEquiv.trans_apply, LinearEquiv.trans_apply, LinearEquiv.smulOfNeZero_apply, LinearEquiv.smulOfNeZero_apply, LinearEquiv.map_smul, LinearEquiv.map_smul] -- Porting note: was -- simp only [hax, LinearEquiv.ofBijective_apply, LinearMap.toSpanSingleton_apply, -- LinearEquiv.map_smulₛₗ, StandardOneDimIsocrystal.frobenius_apply, Algebra.id.smul_eq_mul] [GOAL] case h p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x F : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.ofBijective F₀ (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀) E : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.trans (LinearEquiv.smulOfNeZero K(p, k) (StandardOneDimIsocrystal p k m) b hb) F c : StandardOneDimIsocrystal p k m ⊢ ↑Φ(p, k) (b • ↑(LinearEquiv.ofBijective (LinearMap.toSpanSingleton K(p, k) V x) (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀)) c) = b • ↑(LinearEquiv.ofBijective (LinearMap.toSpanSingleton K(p, k) V x) (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀)) (↑Φ(p, k) c) [PROOFSTEP] rw [LinearEquiv.ofBijective_apply, LinearEquiv.ofBijective_apply] [GOAL] case h p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x F : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.ofBijective F₀ (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀) E : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.trans (LinearEquiv.smulOfNeZero K(p, k) (StandardOneDimIsocrystal p k m) b hb) F c : StandardOneDimIsocrystal p k m ⊢ ↑Φ(p, k) (b • ↑(LinearMap.toSpanSingleton K(p, k) V x) c) = b • ↑(LinearMap.toSpanSingleton K(p, k) V x) (↑Φ(p, k) c) [PROOFSTEP] erw [LinearMap.toSpanSingleton_apply K(p, k) V x c, LinearMap.toSpanSingleton_apply K(p, k) V x] [GOAL] case h p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x F : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.ofBijective F₀ (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀) E : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.trans (LinearEquiv.smulOfNeZero K(p, k) (StandardOneDimIsocrystal p k m) b hb) F c : StandardOneDimIsocrystal p k m ⊢ ↑Φ(p, k) (b • c • x) = b • ↑Φ(p, k) c • x [PROOFSTEP] simp only [hax, LinearEquiv.ofBijective_apply, LinearMap.toSpanSingleton_apply, LinearEquiv.map_smulₛₗ, StandardOneDimIsocrystal.frobenius_apply, Algebra.id.smul_eq_mul] [GOAL] case h p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x F : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.ofBijective F₀ (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀) E : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.trans (LinearEquiv.smulOfNeZero K(p, k) (StandardOneDimIsocrystal p k m) b hb) F c : StandardOneDimIsocrystal p k m ⊢ ↑φ(p, k) b • ↑φ(p, k) c • a • x = b • (↑p ^ m • ↑φ(p, k) c) • x [PROOFSTEP] simp only [← mul_smul] [GOAL] case h p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x F : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.ofBijective F₀ (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀) E : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.trans (LinearEquiv.smulOfNeZero K(p, k) (StandardOneDimIsocrystal p k m) b hb) F c : StandardOneDimIsocrystal p k m ⊢ (↑φ(p, k) b * (↑φ(p, k) c * a)) • x = (b * ↑p ^ m • ↑φ(p, k) c) • x [PROOFSTEP] congr 1 -- Porting note: added the next two lines [GOAL] case h.e_a p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x F : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.ofBijective F₀ (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀) E : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.trans (LinearEquiv.smulOfNeZero K(p, k) (StandardOneDimIsocrystal p k m) b hb) F c : StandardOneDimIsocrystal p k m ⊢ ↑φ(p, k) b * (↑φ(p, k) c * a) = b * ↑p ^ m • ↑φ(p, k) c [PROOFSTEP] erw [smul_eq_mul] [GOAL] case h.e_a p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x F : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.ofBijective F₀ (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀) E : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.trans (LinearEquiv.smulOfNeZero K(p, k) (StandardOneDimIsocrystal p k m) b hb) F c : StandardOneDimIsocrystal p k m ⊢ ↑φ(p, k) b * (↑φ(p, k) c * a) = b * (↑(IsFractionRing.lift (_ : Function.Injective ↑(algebraMap (WittVector p k) ((fun x => K(p, k)) c)))) (↑p ^ m) * ↑φ(p, k) c) [PROOFSTEP] simp only [map_zpow₀, map_natCast] [GOAL] case h.e_a p : ℕ inst✝⁶ : Fact (Nat.Prime p) k✝ : Type u_1 inst✝⁵ : CommRing k✝ k : Type u_2 inst✝⁴ : Field k inst✝³ : IsAlgClosed k inst✝² : CharP k p V : Type u_3 inst✝¹ : AddCommGroup V inst✝ : Isocrystal p k V h_dim : finrank K(p, k) V = 1 this✝ : Nontrivial V x : V hx : x ≠ 0 this : ↑Φ(p, k) x ≠ 0 a : K(p, k) ha : a ≠ 0 hax : ↑Φ(p, k) x = a • x b : K(p, k) hb : b ≠ 0 m : ℤ hmb : ↑φ(p, k) b * a = ↑p ^ m * b F₀ : StandardOneDimIsocrystal p k m →ₗ[K(p, k)] V := LinearMap.toSpanSingleton K(p, k) V x F : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.ofBijective F₀ (_ : Function.Injective ↑F₀ ∧ Function.Surjective ↑F₀) E : StandardOneDimIsocrystal p k m ≃ₗ[K(p, k)] V := LinearEquiv.trans (LinearEquiv.smulOfNeZero K(p, k) (StandardOneDimIsocrystal p k m) b hb) F c : StandardOneDimIsocrystal p k m ⊢ ↑φ(p, k) b * (↑φ(p, k) c * a) = b * (↑p ^ m * ↑φ(p, k) c) [PROOFSTEP] linear_combination φ(p, k) c * hmb
{-# OPTIONS --without-K --rewriting #-} module lib.Basics where open import lib.Base public open import lib.Equivalence public open import lib.Function public open import lib.Funext public open import lib.NType public open import lib.PathFunctor public open import lib.PathGroupoid public open import lib.PathOver public open import lib.Relation public open import lib.Univalence public
= = Taxonomy and nomenclature = =
Formal statement is: lemma lmeasurable_compact: "compact S \<Longrightarrow> S \<in> lmeasurable" Informal statement is: Any compact set is Lebesgue measurable.
lemma continuous_on_open_avoid: fixes f :: "'a::metric_space \<Rightarrow> 'b::t1_space" assumes "continuous_on s f" and "open s" and "x \<in> s" and "f x \<noteq> a" shows "\<exists>e>0. \<forall>y. dist x y < e \<longrightarrow> f y \<noteq> a"
import combinatorics.simple_graph.clique import combinatorics.simple_graph.degree_sum import data.finset.basic import data.nat.basic import tactic.core import algebra.big_operators --local import turanpartition import multipartite import nbhd_res import fedges open finset nat turanpartition open_locale big_operators namespace simple_graph section ind variables {t n : ℕ} variables {α : Type*} (G H : simple_graph α)[fintype α][nonempty α]{s : finset α} [decidable_eq α][decidable_rel G.adj][decidable_rel H.adj] -- I found dealing with the mathlib "induced" subgraph too painful (probably just too early in my experience of lean) -- Graph induced by A:finset α, defined to be a simple_graph α (so all vertices outside A have empty neighborhoods) -- this is equvialent to "spanning_coe (induce (A:set α) G)" as we prove below. @[ext,reducible] def ind (A : finset α) : simple_graph α :={ adj:= λ x y, G.adj x y ∧ x ∈ A ∧ y ∈ A, symm:= begin intros x y hxy, rw adj_comm, tauto, end, loopless:= by obviously} lemma ind_univ : G.ind univ = G := begin ext, simp only [mem_univ, and_true], end -- why is this so messy to prove? (presumably it isn't..) lemma ind_eq_coe_induced {A : finset α} : spanning_coe (induce (A:set α) G) = (G.ind A):= begin ext, simp only [map_adj, comap_adj, function.embedding.coe_subtype, set_coe.exists, mem_coe, subtype.coe_mk, exists_prop], split, {rintros ⟨a,h1,b,h2,h3,h4,h5⟩,rw [←h4,←h5], exact ⟨h3,h1,h2⟩}, {rintros ⟨h,h1,h2⟩, exact ⟨x,h1,x_1,h2,h,rfl,rfl⟩,}, end -- induced subgraphs on disjoint sets meet in the empty graph lemma empty_of_disjoint_ind {A B: finset α} (h : disjoint A B): G.ind A ⊓ G.ind B = ⊥ := begin ext , simp only [inf_adj, bot_adj], split, {rintro ⟨⟨_,h1,_⟩,⟨_,h2,_⟩⟩, exact h (mem_inter.mpr ⟨h1,h2⟩)}, {tauto}, end lemma empty_of_ind_comp (A : finset α) : G.ind A ⊓ G.ind Aᶜ =⊥:= begin have :disjoint A Aᶜ:=disjoint_compl_right, exact G.empty_of_disjoint_ind (this), end -- different parts of a multi_part induce graphs that meet in the empty graph lemma empty_of_diff_parts {M : multi_part α} {i j : ℕ}(hi: i∈range(M.t+1)) (hj: j∈range(M.t+1)) (hne:i≠j): G.ind (M.P i) ⊓ G.ind (M.P j) = ⊥ := G.empty_of_disjoint_ind (M.disj i hi j hj hne) -- would like to just define the bUnion of the induced graphs directly but can't figure out how to do this. @[ext] def edges_inside (M : multi_part α) : finset(sym2 α):=(range(M.t+1)).bUnion (λi, (G.ind (M.P i)).edge_finset) --so counting edges inside M is same as summing of edges in induced parts (since parts are disjoint..) lemma edge_mp_count {M : multi_part α} : (G.edges_inside M).card = ∑ i in range(M.t+1),(G.ind (M.P i)).edge_finset.card:= begin apply card_bUnion, intros i hi j hj hne, rw disjoint_edges_iff_meet_empty,exact G.empty_of_diff_parts hi hj hne, end -- if v w are adjacent in induced graph then they are adjacent in G lemma ind_adj_imp {A :finset α} {v w :α} : (G.ind A).adj v w → G.adj v w:=λ h, h.1 -- if v w are adjacent in induced graph on A then they are both in A lemma ind_adj_imp' {A :finset α} {v w :α} : (G.ind A).adj v w → v ∈ A ∧ w ∈ A:=λ h , h.2 --nbhd of v ∈ A in the graph induced by A is exactly the nbhd of v restricted to A lemma ind_nbhd_mem {A : finset α} {v : α} : v∈ A → (G.ind A).neighbor_finset v = G.nbhd_res v A:= begin intros hv,unfold neighbor_finset nbhd_res, ext, simp only [*, set.mem_to_finset, mem_neighbor_set, and_self] at *, split,{intro ha, rw [mem_inter,set.mem_to_finset,mem_neighbor_set],exact ⟨ha.2.2,ha.1⟩}, {rw [mem_inter, set.mem_to_finset, mem_neighbor_set], tauto}, end -- induced degree of v ∈ A is deg res to A lemma ind_deg_mem {A : finset α} {v : α} : v∈ A → (G.ind A).degree v= G.deg_res v A:= begin unfold degree deg_res,intros hv, congr,exact G.ind_nbhd_mem hv, end -- if v∉A then v has no neighbors in the induced graph G.ind A lemma ind_nbhd_nmem {A : finset α} {v : α} : v∉A → ((G.ind A).neighbor_finset v) = ∅:= begin contrapose, push_neg,intros h, obtain ⟨w,hw⟩:=nonempty.bex (nonempty_of_ne_empty h), rw mem_neighbor_finset at hw, exact hw.2.1, end -- if v∉ A then (G.ind A).degree v is zero lemma ind_deg_nmem {A : finset α} {v : α} : v∉A → (G.ind A).degree v=0:= λ h, card_eq_zero.mpr (G.ind_nbhd_nmem h) -- so degrees of v in the induced graph are deg_res v A or 0 depending on whether or not v ∈ A lemma ind_deg {A :finset α}{v:α} : (G.ind A).degree v = ite (v∈A) (G.deg_res v A) (0):= begin unfold degree, split_ifs,{unfold deg_res,congr, exact G.ind_nbhd_mem h}, {rw G.ind_nbhd_nmem h, apply card_eq_zero.mpr rfl}, end -- finite support of G def fsupport : finset α := univ.filter (λ v, 0 < G.degree v ) -- member of support iff degree >0 lemma mem_fsupport (v : α) : v ∈ G.fsupport ↔ 0 < G.degree v:= begin unfold fsupport,rw mem_filter, simp only [mem_univ, true_and], end lemma deg_fsupport (v : α) : G.degree v = ite (v∈ G.fsupport) (G.degree v) (0):= begin split_ifs, refl,rw mem_fsupport at h, linarith, end -- a vertex is in the fsupport of (G.ind A) only if it is in A lemma mem_ind_fsupport {v : α} {A: finset α} : v ∈ (G.ind A).fsupport → v ∈ A:= begin rw (G.ind A).mem_fsupport v ,contrapose , push_neg, intros hv, rw G.ind_deg_nmem hv, end -- so when calculating any sum of degrees over a set can restrict to fsupport lemma deg_sum_fsupport {A : finset α} : ∑ v in A, G.degree v = ∑ v in A.filter (λ v , v ∈ G.fsupport), G.degree v:= begin rw sum_filter, apply sum_congr rfl, intros x hx,exact G.deg_fsupport x, end -- so degree sum over α in the induced subgraph is same as sum of deg_res over A -- both count 2*e(G[A]) lemma ind_deg_sum {A :finset α}: ∑v, (G.ind A).degree v = ∑v in A,(G.deg_res v A):= begin simp only [ind_deg], rw sum_ite,rw sum_const, rw smul_zero,rw add_zero, congr, ext,rw mem_filter,simp only [mem_univ],tauto, end --induced subgraph is a subgraph lemma ind_sub (A : finset α) : (G.ind A)≤ G:= λ x y, G.ind_adj_imp -- internal edges induced by parts of a partition M -- I should have defined this as G \(⋃ (G.ind M.P i)) if I -- could have made it work.. defining the bUnion operator for simple_graphs -- was a step too far.. ---bipartite graph induced by a finset A @[ext,reducible] def bipart (A :finset α) :simple_graph α := { adj:= λ v w, (G.adj v w) ∧ (v∈ A ∧ w ∉ A ∨ v∉ A ∧ w ∈ A), symm :=begin intros x y hxy, rw adj_comm, tauto, end, loopless :=by obviously,} -- the bipartite graph induced by A (and Aᶜ) is the same as that induced by Aᶜ (and A = Aᶜᶜ) lemma bipart_comp_eq_self {A : finset α} : (G.bipart A)=(G.bipart Aᶜ):= begin tidy; tauto end --induced subgraph on A meets bipartite induced subgraph e(A,Aᶜ) in empty graph lemma empty_of_ind_bipart (A: finset α) : (G.ind A ⊔ G.ind Aᶜ) ⊓ G.bipart A = ⊥ := begin ext, simp only [inf_adj, sup_adj,bot_adj, mem_compl], tauto, end -- Given A:finset α and G :simple_graph α we can partition G into G[A] G[Aᶜ] and G[A,Aᶜ] lemma split_induced (A : finset α): G = (G.ind A ⊔ G.ind Aᶜ) ⊔ G.bipart A:= begin ext, simp only [sup_adj, mem_compl], tauto, end --- Edge counting: e(G[A])+e(G[Aᶜ])+e(G[A,Aᶜ])=e(G) lemma edges_split_induced (A : finset α): (G.ind A).edge_finset.card + (G.ind Aᶜ).edge_finset.card + (G.bipart A).edge_finset.card = G.edge_finset.card := begin have:=G.split_induced A, rw eq_iff_edges_eq at this, rw this, rw card_edges_add_of_meet_empty (G.empty_of_ind_bipart A), rw add_left_inj, rwa card_edges_add_of_meet_empty (G.empty_of_ind_comp A), end -- v w adjacent in the bipartite graph given by A iff adj in bipartite graph given by Aᶜ (since they are the same graph..) lemma bipart_comp_adj_iff {A : finset α} {v w :α} : (G.bipart A).adj v w ↔ (G.bipart Aᶜ).adj v w:= begin tidy; tauto, end -- nbhd of v ∈ A in the bipartite graph is the nbhd of v in G restricted to Aᶜ lemma nbhd_bipart_mem {A : finset α} {v : α} (h: v∈ A) : (G.bipart A).neighbor_finset v = G.nbhd_res v Aᶜ:= begin ext, rw [mem_res_nbhd, mem_neighbor_finset,mem_neighbor_finset], tidy; tauto, end -- hence degree is deg_res v to Aᶜ lemma deg_bipart_mem {A : finset α} {v : α} (h: v∈ A) : (G.bipart A).degree v = (G.deg_res v Aᶜ):= begin unfold degree deg_res, rwa nbhd_bipart_mem, end -- nbhd of v ∉ A in the bipartite graph is the nbhd of v in G restricted to A lemma nbhd_bipart_not_mem {A : finset α} {v : α} (h: v ∉ A) : (G.bipart A).neighbor_finset v = G.nbhd_res v A:= begin ext, simp only [mem_res_nbhd, mem_neighbor_finset], tidy; tauto, end -- if v∉ A then in the bipartite graph deg v is the deg_res to A lemma deg_bipart_not_mem {A : finset α} {v : α} (h: v ∉ A) : (G.bipart A).degree v = G.deg_res v A:= begin unfold degree deg_res,rwa nbhd_bipart_not_mem, end -- degree of v ∈ A is degree in induced + degree in bipartite (ie count neighbour in A and Aᶜ) lemma deg_eq_ind_add_bipart {A : finset α} {v : α} : ∀v∈A, G.degree v= (G.ind A).degree v + (G.bipart A).degree v:= begin intros v hv, rw G.deg_bipart_mem hv, rw G.ind_deg_mem hv, rw ← G.deg_res_univ, exact G.deg_res_add (subset_univ A), end --ite to count edges from A to Aᶜ lemma bipart_sum_ite {A : finset α}: ∑ v in A, (G.bipart A).degree v = ∑ v in A, ∑ w in Aᶜ, ite (G.adj v w) (1) (0):= begin apply sum_congr rfl, intros x hx, rw G.deg_bipart_mem hx, rw deg_res,rw nbhd_res, rw card_eq_sum_ones, simp only [*, sum_const, algebra.id.smul_eq_mul, mul_one, sum_boole, cast_id], congr,ext,rw mem_inter,rw mem_neighbor_finset,rw mem_filter, end -- sum of degrees over each part are equal in any induced bipartite graph lemma bipart_sum_eq {A : finset α}: ∑ v in A, (G.bipart A).degree v = ∑ v in Aᶜ, (G.bipart A).degree v := begin rw [G.bipart_sum_ite, sum_comm], apply sum_congr rfl, intros x hx, rw [compl_eq_univ_sdiff, mem_sdiff] at hx, rw [G.deg_bipart_not_mem hx.2, deg_res, nbhd_res, card_eq_sum_ones, sum_ite, sum_const,sum_const], dsimp, rw [mul_one, mul_zero, add_zero, card_eq_sum_ones], apply sum_congr, ext, rw [mem_inter, mem_filter, mem_neighbor_finset, adj_comm], intros y hy,refl, end -- hence sum of degrees over one part counts edges once lemma sum_deg_bipart_eq_edge_card {A : finset α} :∑ v in A, (G.bipart A).degree v = (G.bipart A).edge_finset.card := begin apply (nat.mul_right_inj (by norm_num:0<2)).mp, rw ← sum_degrees_eq_twice_card_edges, rw [(by norm_num:2=1+1), add_mul, one_mul], nth_rewrite 0 G.bipart_sum_eq, rw compl_eq_univ_sdiff, symmetry, have:disjoint (univ\A) A := sdiff_disjoint, rw ← sum_union this, rw sdiff_union_of_subset (subset_univ A), end --- in the induced graph only need to sum over A to count all edges twice lemma sum_degrees_ind_eq_twice_card_edges {A : finset α} : ∑v in A, (G.ind A).degree v = 2*(G.ind A).edge_finset.card:= begin rw ← sum_degrees_eq_twice_card_edges, rw ind_deg_sum, apply sum_congr rfl, intros x hx, exact G.ind_deg_mem hx, end -- sum of degrees in A = twice number of edges in A + number of edges from A to Aᶜ lemma sum_deg_ind_bipart {A : finset α} : ∑ v in A, G.degree v = 2*(G.ind A).edge_finset.card + (G.bipart A).edge_finset.card := begin rw ← sum_degrees_ind_eq_twice_card_edges, rw ← sum_deg_bipart_eq_edge_card, rw ← sum_add_distrib, apply sum_congr rfl,intros x hx, rwa G.deg_eq_ind_add_bipart x hx, end -- any nbhd is contained in the fsupport lemma nbhd_sub_fsupport (v : α) :G.neighbor_finset v ⊆ G.fsupport := begin intro x,rw [mem_neighbor_finset, mem_fsupport, degree, card_pos], intro h, rw [adj_comm, ← mem_neighbor_finset] at h, exact ⟨v,h⟩, end -- should have been one line (on finsets not graphs) but couldn't find it: A ⊆ B → Aᶜ ∩ B = B\A lemma comp_nbhd_int_supp_eq_sdiff (v : α) :(G.neighbor_finset v)ᶜ ∩ G.fsupport = G.fsupport \(G.neighbor_finset v):= begin have h:=G.nbhd_sub_fsupport v, rw [sdiff_eq, inter_comm], refl, end -- Bound on max degree gives bound on edges of G in the following form: --(Note this almost gives Mantel's theorem since in a K_3-free graph nbhds are independent) lemma sum_deg_ind_max_nbhd {v : α} {A : finset α} (hm: G.degree v= G.max_degree) (hA: A=(G.neighbor_finset v)ᶜ) : 2*(G.ind A).edge_finset.card + (G.bipart A).edge_finset.card ≤ (G.fsupport.card - G.max_degree)*G.max_degree:= begin rw [← G.sum_deg_ind_bipart, G.deg_sum_fsupport, ← hm, degree], rw [sum_filter, sum_ite, sum_const, smul_zero, add_zero, ← card_sdiff (G.nbhd_sub_fsupport v)], nth_rewrite 0 card_eq_sum_ones,rw [sum_mul, one_mul], rw hA, rw [filter_mem_eq_inter, G.comp_nbhd_int_supp_eq_sdiff v], apply sum_le_sum, rw [← degree, hm], intros x hx, exact G.degree_le_max_degree x, end -- The essential bound for Furedi's result: -- e(G) + e(G[Γ(v)ᶜ]) ≤ (G.fsupport.card - Δ(G))*Δ(G) + e(G[Γ(v)]) lemma edge_bound_max_deg {v : α} {A : finset α} (hm: G.degree v= G.max_degree) (hA: A=(G.neighbor_finset v)ᶜ) : G.edge_finset.card + (G.ind A).edge_finset.card ≤ (G.fsupport.card - G.max_degree)*G.max_degree + (G.ind Aᶜ).edge_finset.card:= begin rw ← G.edges_split_induced A, have:=G.sum_deg_ind_max_nbhd hm hA, linarith, end -- any "actual" clique consists of vertices in the support lemma clique_sub_fsupport {t : ℕ} {S :finset α} (ht: 2 ≤ t) (h: G.is_n_clique t S) : S ⊆ G.fsupport:= begin intros a ha, rw is_n_clique_iff at h, have :(1 < S.card):= by linarith, obtain ⟨b,hb,hne⟩:= exists_ne_of_one_lt_card this a, rw ← mem_coe at *, have hadj:=h.1 hb ha hne, rw mem_coe, rw ← mem_neighbor_finset at hadj, exact (G.nbhd_sub_fsupport b) hadj, end -- any t+2 clique of an induced graph is a subset of the induced set lemma clique_ind_sub_ind {A S : finset α} (h: 2 ≤ t): (G.ind A).is_n_clique t S → S ⊆ A:= begin intros h1 a ha, exact G.mem_ind_fsupport (((G.ind A).clique_sub_fsupport h h1) ha), end -- if S a t-clique in a nbhd Γ(v) then inserting v gives a (t+1)-clique lemma clique_insert_nbhr {t : ℕ} {S :finset α} {v : α} (hc: G.is_n_clique t S) (hd: S ⊆ G.neighbor_finset v) : G.is_n_clique (t+1) (insert v S):= begin rw is_n_clique_iff at *, rw ← hc.2, have vnin:v∉S:=by apply set.not_mem_subset hd (G.not_mem_nbhd v), rw is_clique_iff at *, refine ⟨_,card_insert_of_not_mem vnin⟩, rw coe_insert, refine set.pairwise.insert hc.1 _, intros b hb hj, rw [G.adj_comm b v, and_self,← mem_neighbor_finset], exact hd hb, end -- Now the other key lemma for Furedi's result: -- If G is K_{t+3}-free then any nbhd induces a K_{t+2}-free graph -- (Could replace t by t-1 below, since G K_2 free → nbhds all empty → graphs induced by nbhds empty → they are K_1 -free ) lemma clique_free_nbhd_ind {t : ℕ} {v : α} : G.clique_free (t+3) → (G.ind (G.neighbor_finset v)).clique_free (t+2):= begin contrapose, unfold clique_free, push_neg, rintro ⟨S,hs⟩, use (insert v S), have:=G.clique_insert_nbhr (⟨(is_clique.mono (G.ind_sub (G.neighbor_finset v)) hs.1),hs.2⟩) (G.clique_ind_sub_ind (by linarith) hs), rwa [(by norm_num: 3=2+1),← add_assoc], end @[ext,reducible] def bUnion (M: multi_part α) : simple_graph α := { adj:= λ v w, ∃i ∈ range(M.t+1), (G.ind (M.P i)).adj v w, symm:= by obviously, loopless:= by obviously,} @[ext,reducible] def disJoin (M: multi_part α) : simple_graph α:={ adj:= λ v w , (G.adj v w) ∧ (∃ i ∈ range(M.t+1), v∈(M.P i) ∧w∈ (M.P i)), symm:= by obviously, loopless:= by obviously,} -- the two versions of "union of induced disjoint parts" are the same lemma bUnion_eq_disJoin_sum (M : multi_part α) : G.bUnion M = G.disJoin M:= begin ext,simp only [mem_range, exists_prop],split, {rintros ⟨i,hi,ad,hx,hy⟩,exact ⟨ad,i,hi,hx,hy⟩},{rintros ⟨ad,i,hi,hx,hy⟩,exact ⟨i,hi,ad,hx,hy⟩}, end -- edges inside M are the same as the edge_finset of bUnion M lemma edges_inside_eq (M : multi_part α) : (G.bUnion M).edge_finset = (G.edges_inside M):= begin unfold edges_inside, ext, simp only [mem_edge_finset, mem_bUnion, mem_range, exists_prop], unfold bUnion, induction a, work_on_goal 1 { cases a, dsimp at *, simp only [mem_range, exists_prop] at *, refl }, refl, end -- this is a subgraph of G lemma disJoin_sub (M : multi_part α) : (G.disJoin M)≤ G:=λ _ _ h, h.1 -- G with the internal edges removed is G ⊓ (mp M) lemma sdiff_with_int {M: multi_part α} (h: M.A =univ) : G\(G.disJoin M) = G⊓(mp M):= begin ext x y,dsimp, have hx: x∈ M.A:=by {rw h, exact mem_univ x}, have hy: y∈ M.A:=by {rw h, exact mem_univ y}, obtain ⟨i,hi,hx1⟩:=inv_part hx, obtain ⟨j,hj,hy1⟩:=inv_part hy, split,{ rintros ⟨hadj,h2⟩,refine ⟨hadj,_⟩, push_neg at h2, have h3:=h2 hadj, specialize h3 i hi hx1, refine mp_imp_adj hi hj hx1 hy1 _, intro ne,rw ne at h3, exact h3 hy1,},{ rintros ⟨hadj,h2⟩, refine ⟨hadj,_⟩, push_neg, intros hadj' i hi hx hy, exact not_nbhr_same_part hi hx h2 hy }, end -- G is the join of the edges induced by the parts and those in the complete -- multipartite graph M on α lemma self_eq_disJoin_ext_mp {M :multi_part α} (h: M.A=univ) : G = (G.disJoin M) ⊔ (G⊓(mp M)):= begin rw ← G.sdiff_with_int h,simp only [sup_sdiff_self_right, right_eq_sup], exact G.disJoin_sub M, end -- Given M and v,w vertices with v ∈ M.P i and w ∈ M.A then v,w are adjacent in -- the "internal induced subgraph" iff they are adjacent in the graph induced on M.P i lemma disJoin_edge_help {M :multi_part α} {v w : α} {i : ℕ}: i ∈ range(M.t+1) → v ∈ (M.P i) → w ∈ M.A → ((G.disJoin M).adj v w ↔ (G.ind (M.P i)).adj v w):= begin intros hi hv hw, obtain ⟨j,hj,hw⟩:=inv_part hw,dsimp, by_cases i=j,{ split, {intros h1,rw ←h at hw,exact ⟨h1.1,hv,hw⟩}, {intros h1, cases h1, exact ⟨h1_left,i,hi,h1_right⟩},}, { split,{intros h1, cases h1 with h2 h3, exfalso, rcases h3 with ⟨k, hkr, hk⟩, have ieqk:=uniq_part hi hkr hv hk.1,have jeqk:=uniq_part hj hkr hw hk.2, rw ← jeqk at ieqk, exact h ieqk}, {intros h1, exfalso, exact uniq_part' hi hj h h1.2.2 hw}, }, end --same as above but for degrees and assuming M covers all of α lemma disJoin_edge_help' {M :multi_part α} (h: M.A=univ) {v w:α}{i:ℕ}: i∈ range(M.t+1) → v ∈ (M.P i) → (G.disJoin M).degree v = (G.ind (M.P i)).degree v:= begin intros hi hv, unfold degree, apply congr_arg _, ext, have :=mem_univ a,rw ← h at this, have:=G.disJoin_edge_help hi hv this, rwa [mem_neighbor_finset,mem_neighbor_finset], end -- so sum of degrees in internal subgraph is sum over induced subgraphs on parts of sum of degrees lemma disJoin_deg_sum {M :multi_part α} (h: M.A=univ) : ∑v,(G.disJoin M).degree v = ∑ i in range(M.t+1), ∑ v, (G.ind (M.P i)).degree v:= begin have :=bUnion_parts M, rw ← h,nth_rewrite 0 this, rw sum_bUnion (pair_disjoint M), refine sum_congr rfl _, intros i hi, rw (sdiff_part hi), rw sum_union (sdiff_disjoint), have :∑x in M.A\(M.P i),(G.ind (M.P i)).degree x =0,{ apply sum_eq_zero,intros x hx, rw mem_sdiff at hx, exact G.ind_deg_nmem hx.2,}, rw this,rw zero_add, apply sum_congr rfl _, intros x hx, apply (G.disJoin_edge_help' h) hi hx, exact x, end -- number of edges in the subgraph induced inside all parts is the sum of those induced in each part lemma disJoin_edge_sum {M :multi_part α} (h: M.A=univ) : (G.disJoin M).edge_finset.card = ∑ i in range(M.t+1), (G.ind (M.P i)).edge_finset.card:= begin apply (nat.mul_right_inj (by norm_num:0<2)).mp, rw mul_sum, simp only [← sum_degrees_eq_twice_card_edges], exact G.disJoin_deg_sum h, end --counting edges in induced parts is (almost) the same as summing restricted degrees... lemma ind_edge_count {A : finset α}: ∑ v in A, G.deg_res v A = 2* ((G.ind A).edge_finset.card ) := begin rw [← sum_degrees_eq_twice_card_edges,G.ind_deg_sum], end end ind end simple_graph
classdef CantileverBeamMeshCreator < handle properties (Access = public) connec coords end properties (Access = private) dim length height end methods (Access = public) function obj = CantileverBeamMeshCreator(cParams) obj.init(cParams) end function mesh = create(obj, xdiv, ydiv) switch obj.dim case '2D' mesh = obj.create2Dcantilever(xdiv, ydiv); case '3D' mesh = obj.create3Dcantilever(xdiv, ydiv); end end end methods (Access = private) function init(obj,cParams) obj.dim = cParams.dim; obj.length = cParams.length; obj.height = cParams.height; end function mesh = create2Dcantilever(obj, xdiv, ydiv) obj.computeCoords2D(xdiv, ydiv); obj.computeConnec2D(xdiv, ydiv); mesh = obj.createMesh(); end function mesh = create3Dcantilever(obj, xdiv, ydiv) obj.computeCoords3D(xdiv, ydiv); obj.computeConnec3D(xdiv, ydiv); mesh = obj.createMesh(); end function coords = computeCoords2D(obj, xdiv, ydiv) x = linspace(0, obj.length, xdiv+1); y = linspace(0, obj.height, ydiv+1); [X,Y,Z] = meshgrid(x,y,0); fvc = surf2patch(X,Y,Z,'triangles'); fvc.vertices(:,3) = []; % 2D coords = fvc.vertices; obj.coords = coords; end function computeConnec2D(obj, xdiv, ydiv) conn = []; for j = 0:1:xdiv-1 for i = 1:1:ydiv node1 = j*(ydiv+1) + i; node2 = node1 + 1; node3 = node1 + (ydiv+1); node4 = node2 + (ydiv+1); elem = [node1, node2, node4, node3]; conn = [conn; elem]; end end obj.connec = conn; end function computeCoords3D(obj, xdiv, ydiv) x = linspace(0, obj.length, xdiv+1); y = linspace(0, obj.height, ydiv+1); z = linspace(0, obj.height, ydiv+1); [X,Y,Z] = meshgrid(x,y,z); npnod = size(X,1)*size(X,2)*size(X,3); Xr = reshape(X, npnod,1); Yr = reshape(Y, npnod,1); Zr = reshape(Z, npnod,1); coor = [Xr, Yr, Zr]; obj.coords = coor; end function computeConnec3D(obj, xdiv, ydiv) conn = []; % for z = 0:1:ydiv-1 % for j = 0:1:ydiv-1 % for i = 1:1:xdiv % addZ = (xdiv+1)*(ydiv+1)*z; % addZ1 = (xdiv+1)*(ydiv+1)*(z+1); % node1 = j*(xdiv+1)+i + addZ; % node2 = j*(xdiv+1)+i+1 + addZ; % node3 = (j+1)*(xdiv+1)+i + addZ; % node4 = (j+1)*(xdiv+1)+i+1 + addZ; % node5 = j*(xdiv+1)+i + addZ1; % node6 = j*(xdiv+1)+i+1 + addZ1; % node7 = (j+1)*(xdiv+1)+i + addZ1; % node8 = (j+1)*(xdiv+1)+i+1 + addZ1; % elem = [node1, node2, node3, node4, ... % node5, node6, node7, node8]; % conn = [conn; elem]; % end % end % end for z = 0:1:ydiv for j = 0:1:xdiv-1 for i = 1:1:ydiv addZ = (xdiv+1)*(ydiv+1)*z; node1 = j*(ydiv+1) + i; node2 = node1 + 1; node3 = node1 + (ydiv+1); node4 = node2 + (ydiv+1); node5 = j*(ydiv+1) + i + addZ; node6 = node5 + 1; node7 = node5 + (ydiv+1); node8 = node6 + (ydiv+1); elem = [node1, node2, node4, node3, ... node5, node6, node7, node8]; conn = [conn; elem]; end end end obj.connec = conn; end function mesh = createMesh(obj) m.coord = obj.coords; m.connec = obj.connec; mesh = Mesh(m); end end end
[STATEMENT] lemma card_remove_fset_less2: shows "x |\<in>| xs \<Longrightarrow> y |\<in>| xs \<Longrightarrow> card_fset (remove_fset y (remove_fset x xs)) < card_fset xs" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>x |\<in>| xs; y |\<in>| xs\<rbrakk> \<Longrightarrow> card_fset (remove_fset y (remove_fset x xs)) < card_fset xs [PROOF STEP] unfolding card_fset remove_fset in_fset [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>x \<in> fset xs; y \<in> fset xs\<rbrakk> \<Longrightarrow> card (fset xs - {x} - {y}) < card (fset xs) [PROOF STEP] by (rule card_Diff2_less[OF finite_fset])
/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <ctime> #include <boost/algorithm/string/trim.hpp> #include <osquery/tables.h> namespace osquery { namespace tables { QueryData genTime(QueryContext& context) { Row r; time_t _time = time(nullptr); struct tm* now = localtime(&_time); struct tm* gmt = gmtime(&_time); char weekday[10] = {0}; strftime(weekday, sizeof(weekday), "%A", now); char timezone[5] = {0}; strftime(timezone, sizeof(timezone), "%Z", now); std::string timestamp; timestamp = asctime(gmt); boost::algorithm::trim(timestamp); timestamp += " UTC"; char iso_8601[21] = {0}; strftime(iso_8601, sizeof(iso_8601), "%FT%TZ", gmt); r["weekday"] = TEXT(weekday); r["year"] = INTEGER(now->tm_year + 1900); r["month"] = INTEGER(now->tm_mon + 1); r["day"] = INTEGER(now->tm_mday); r["hour"] = INTEGER(now->tm_hour); r["minutes"] = INTEGER(now->tm_min); r["seconds"] = INTEGER(now->tm_sec); r["timezone"] = TEXT(timezone); r["unix_time"] = INTEGER(_time); r["timestamp"] = TEXT(timestamp); r["iso_8601"] = TEXT(iso_8601); QueryData results; results.push_back(r); return results; } } }
Let $f$ be a sequence of vectors in $\mathbb{R}^n$. For every finite subset $D$ of $\{1, \ldots, n\}$, there exists a subsequence $f_{r(n)}$ of $f$ and a vector $l$ such that for every $\epsilon > 0$, there exists $N$ such that for all $n \geq N$ and all $i \in D$, we have $|f_{r(n)}(i) - l(i)| < \epsilon$.
>> FYI: on these TP's there's a pilot signal and rolloff set to 0.20. > I'm wondering - how did you observe it ? I asked my colleagues who set up this modulator at uplink site, because we are working on these satellite DTH system.
[STATEMENT] lemma unreachable_Null: assumes reach: "s\<turnstile> l reachable_from x" shows "x\<noteq>nullV" [PROOF STATE] proof (prove) goal (1 subgoal): 1. x \<noteq> nullV [PROOF STEP] using reach [PROOF STATE] proof (prove) using this: s\<turnstile> l reachable_from x goal (1 subgoal): 1. x \<noteq> nullV [PROOF STEP] by (induct) auto
This comment was posted to reddit on Jul 10, 2018 at 10:59 am and was deleted within 15 minutes. I dont have any midi to cv modules but i figured out that i could use my Minibrute as a sort of bridge between my DAW and my Eurorack. All i had to do was connect my minibrute to my daw (via usb) and it reads as a midi device. I then sent the midi sequence i wrote in my DAW to the minibrute which automatically converts it to cv/oct and gate outputs for my eurorack. I used the MI Braids as my sound source for all 3 sequence patches and recorded them one by one(the viola bass patch is what is being played live). I used a lil bit of a sine wave lfo for the flute/clarinet patches to give the tremolo sound that those instruments naturally have. I also used some low pass filtering and fx processing with all 3 tracks. Anyways, hope you dig it!
#' Utah DWQ watershed management unit polygons #' #' Utah DWQ watershed management unit polygons. #' #' @format An sf type polygon shapefile "wmu_poly"
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.normed_space.lp_space import topology.sets.compacts /-! # The Kuratowski embedding Any separable metric space can be embedded isometrically in `ℓ^∞(ℝ)`. -/ noncomputable theory open set metric topological_space open_locale ennreal local notation `ℓ_infty_ℝ`:= lp (λ n : ℕ, ℝ) ∞ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace Kuratowski_embedding /-! ### Any separable metric space can be embedded isometrically in ℓ^∞(ℝ) -/ variables {f g : ℓ_infty_ℝ} {n : ℕ} {C : ℝ} [metric_space α] (x : ℕ → α) (a b : α) /-- A metric space can be embedded in `l^∞(ℝ)` via the distances to points in a fixed countable set, if this set is dense. This map is given in `Kuratowski_embedding`, without density assumptions. -/ def embedding_of_subset : ℓ_infty_ℝ := ⟨ λ n, dist a (x n) - dist (x 0) (x n), begin apply mem_ℓp_infty, use dist a (x 0), rintros - ⟨n, rfl⟩, exact abs_dist_sub_le _ _ _ end ⟩ lemma embedding_of_subset_coe : embedding_of_subset x a n = dist a (x n) - dist (x 0) (x n) := rfl /-- The embedding map is always a semi-contraction. -/ lemma embedding_of_subset_dist_le (a b : α) : dist (embedding_of_subset x a) (embedding_of_subset x b) ≤ dist a b := begin refine lp.norm_le_of_forall_le dist_nonneg (λn, _), simp only [lp.coe_fn_sub, pi.sub_apply, embedding_of_subset_coe, real.dist_eq], convert abs_dist_sub_le a b (x n) using 2, ring end /-- When the reference set is dense, the embedding map is an isometry on its image. -/ lemma embedding_of_subset_isometry (H : dense_range x) : isometry (embedding_of_subset x) := begin refine isometry.of_dist_eq (λa b, _), refine (embedding_of_subset_dist_le x a b).antisymm (le_of_forall_pos_le_add (λe epos, _)), /- First step: find n with dist a (x n) < e -/ rcases metric.mem_closure_range_iff.1 (H a) (e/2) (half_pos epos) with ⟨n, hn⟩, /- Second step: use the norm control at index n to conclude -/ have C : dist b (x n) - dist a (x n) = embedding_of_subset x b n - embedding_of_subset x a n := by { simp only [embedding_of_subset_coe, sub_sub_sub_cancel_right] }, have := calc dist a b ≤ dist a (x n) + dist (x n) b : dist_triangle _ _ _ ... = 2 * dist a (x n) + (dist b (x n) - dist a (x n)) : by { simp [dist_comm], ring } ... ≤ 2 * dist a (x n) + |dist b (x n) - dist a (x n)| : by apply_rules [add_le_add_left, le_abs_self] ... ≤ 2 * (e/2) + |embedding_of_subset x b n - embedding_of_subset x a n| : begin rw C, apply_rules [add_le_add, mul_le_mul_of_nonneg_left, hn.le, le_refl], norm_num end ... ≤ 2 * (e/2) + dist (embedding_of_subset x b) (embedding_of_subset x a) : begin have : |embedding_of_subset x b n - embedding_of_subset x a n| ≤ dist (embedding_of_subset x b) (embedding_of_subset x a), { simpa [dist_eq_norm] using lp.norm_apply_le_norm ennreal.top_ne_zero (embedding_of_subset x b - embedding_of_subset x a) n }, nlinarith, end ... = dist (embedding_of_subset x b) (embedding_of_subset x a) + e : by ring, simpa [dist_comm] using this end /-- Every separable metric space embeds isometrically in `ℓ_infty_ℝ`. -/ theorem exists_isometric_embedding (α : Type u) [metric_space α] [separable_space α] : ∃(f : α → ℓ_infty_ℝ), isometry f := begin cases (univ : set α).eq_empty_or_nonempty with h h, { use (λ_, 0), assume x, exact absurd h (nonempty.ne_empty ⟨x, mem_univ x⟩) }, { /- We construct a map x : ℕ → α with dense image -/ rcases h with ⟨basepoint⟩, haveI : inhabited α := ⟨basepoint⟩, have : ∃s:set α, s.countable ∧ dense s := exists_countable_dense α, rcases this with ⟨S, ⟨S_countable, S_dense⟩⟩, rcases set.countable_iff_exists_subset_range.1 S_countable with ⟨x, x_range⟩, /- Use embedding_of_subset to construct the desired isometry -/ exact ⟨embedding_of_subset x, embedding_of_subset_isometry x (S_dense.mono x_range)⟩ } end end Kuratowski_embedding open topological_space Kuratowski_embedding /-- The Kuratowski embedding is an isometric embedding of a separable metric space in `ℓ^∞(ℝ)`. -/ def Kuratowski_embedding (α : Type u) [metric_space α] [separable_space α] : α → ℓ_infty_ℝ := classical.some (Kuratowski_embedding.exists_isometric_embedding α) /-- The Kuratowski embedding is an isometry. -/ protected lemma Kuratowski_embedding.isometry (α : Type u) [metric_space α] [separable_space α] : isometry (Kuratowski_embedding α) := classical.some_spec (exists_isometric_embedding α) /-- Version of the Kuratowski embedding for nonempty compacts -/ def nonempty_compacts.Kuratowski_embedding (α : Type u) [metric_space α] [compact_space α] [nonempty α] : nonempty_compacts ℓ_infty_ℝ := { carrier := range (Kuratowski_embedding α), is_compact' := is_compact_range (Kuratowski_embedding.isometry α).continuous, nonempty' := range_nonempty _ }
function x = stft_iw(Sx, opt) % ISTFT Inverse short-time Fourier transform % % Very closely based on Steven Schimmel's stft.m and istft.m from % his SPHSC 503: Speech Signal Processing course at Univ. Washington. if nargin<2, opt = struct(); end if ~isfield(opt, 'window'), opt.window = round(size(Sx,2)/16); end if length(opt.window) == 1, opt.window = hamming(opt.window); end opt.overlap = length(opt.window)-1; window = opt.window / norm(opt.window, 2); % Unit norm Nwin = length(window); n = size(Sx, 2); % regenerate the full spectrum 0...2pi (minus zero Hz value) Sx = [Sx; conj(Sx(floor((Nwin+1)/2):-1:2,:))]; % take the inverse fft over the columns xbuf = real(ifft(Sx,[],1)); % apply the window to the columns xbuf = xbuf .* repmat(window(:),1,size(xbuf,2)); % overlap-add the columns x = unbuffer(xbuf,Nwin,opt.overlap); %%% subfunction function y = unbuffer(x,w,o) % UNBUFFER undo the effect of 'buffering' by overlap-add (see BUFFER) % A = UNBUFFER(B,WINDOWLEN,OVERLAP) returns the signal A that is % the unbuffered version of B. y = []; skip = w - o; N = ceil(w/skip); L = (size(x,2) - 1) * skip + size(x,1); % zero pad columns to make length nearest integer multiple of skip if size(x,1)<skip*N, x(skip*N,end) = 0; end; % selectively reshape columns of input into 1-d signals for i = 1:N t = reshape(x(:,i:N:end),1,[]); l = length(t); y(i,l+(i-1)*skip) = 0; y(i,[1:l]+(i-1)*skip) = t; end; % overlap-add y = sum(y,1); y = y(1:L);
[STATEMENT] lemma M_point_or_bot: "point M \<or> M = bot" [PROOF STATE] proof (prove) goal (1 subgoal): 1. point M \<or> M = bot [PROOF STEP] using M_bot_iff_S_not_surjective M_point_iff_S_surjective [PROOF STATE] proof (prove) using this: (M \<noteq> bot) = surjective S point M = surjective S goal (1 subgoal): 1. point M \<or> M = bot [PROOF STEP] by blast
-- | -- Module : Statistics.Matrix.Algorithms -- Copyright : 2014 Bryan O'Sullivan -- License : BSD3 -- -- Useful matrix functions. module Statistics.Matrix.Algorithms ( qr ) where import Control.Applicative import Control.Monad.ST (ST, runST) import Statistics.Matrix (Matrix, column, dimension, for, norm) import qualified Statistics.Matrix.Mutable as M import Statistics.Sample.Internal (sum) import qualified Data.Vector.Unboxed as U import Prelude hiding (sum, replicate) -- | /O(r*c)/ Compute the QR decomposition of a matrix. -- The result returned is the matrices (/q/,/r/). qr :: Matrix -> (Matrix, Matrix) qr mat = runST $ do let (m,n) = dimension mat r <- M.replicate n n 0 a <- M.thaw mat for 0 n $ \j -> do cn <- M.immutably a $ \aa -> norm (column aa j) M.unsafeWrite r j j cn for 0 m $ \i -> M.unsafeModify a i j (/ cn) for (j+1) n $ \jj -> do p <- innerProduct a j jj M.unsafeWrite r j jj p for 0 m $ \i -> do aij <- M.unsafeRead a i j M.unsafeModify a i jj $ subtract (p * aij) (,) <$> M.unsafeFreeze a <*> M.unsafeFreeze r innerProduct :: M.MMatrix s -> Int -> Int -> ST s Double innerProduct mmat j k = M.immutably mmat $ \mat -> sum $ U.zipWith (*) (column mat j) (column mat k)
\chapter{Application States} Now that all parts are ready, we start working on the actual application. In it, there are three application states needed: the initState where the program starts, the gameState in which the actual gameplay takes place and the scoreState which shows you the score when the game is over. Prepare an application `Tetris' containing a folder `states'. In that folder, you create three files: initState, gameState and scoreState. \section{Init State} In the init state, we provide the regular application functions: \eeFunc{InitPre}, \eeFunc{Init}, \eeFunc{Shut}, \eeFunc{Update} and \eeFunc{Draw}. You can take these from any program that you made earlier. Next, you provide the functions with the necessary code. So far, we mostly left the \eeFunc{InitPre} function alone. This is the first function that is executed when the application starts. You can use this function to adjust some basic settings. In this case, that will be the name of the program and the size of the window. This can be done by using the constants we declared before. \begin{code} void InitPre() { EE_INIT(); App.name(APP_NAME); D.mode(WINDOW_WIDTH, WINDOW_HEIGHT); } \end{code} The \eeFunc{init} function contains two lines of code. You should call the \eeFunc{create} method of the object \eeClass{Background} and the \eeFunc{startMusic} method of the object \eeClass{SoundManager}. You can certainly write this without an example, right? We'll skip the Update function for now. But in the \eeFunc{Draw} function you can go wild for a moment. This is where you create a beautiful startup screen. You can certainly use the image and show some text in the accompanying Tetris fonts. And with some extra effort, it is not too hard to make those move or even change colors. Make sure you also show a text ``Push space to start'', because that is how we will start the game. \section{The Game State} In the file `gamestate', you add three functions: \eeFunc{GameInit}, \eeFunc{GameUpdate} and \eeFunc{GameDraw}. These functions will be left empty for now, although you can already draw the background if you like. You also need to declare this new application state. Here you can see how this file should look right now: \begin{code} bool GameInit() { return true; } bool GameUpdate() { if(Kb.bp(KB_ESC)) return false; return true; } void GameDraw() { Background.draw(); } State GameState(GameUpdate, GameDraw, GameInit); \end{code} Now add some code to the Update function of the initial state: when you press the space bar, your application should switch over to the GameState, with a fade of 0.4 seconds. (If you do not know how to do that, look in Chapter \ref{chapter:application_states}. Test your application to see if the switch works. \section{Score State} This application state is closely related to the class \eeClass{score}. It is therefore necessary to develop them together. Start with the code for the application state: \begin{code} bool scoreUpdate() { return true; } void scoreDraw() {} State ScoreState(scoreUpdate, scoreDraw); \end{code} Create a separate code file for the class \eeClass{score}. The framework for this class looks like this: \begin{code} class score { private: int points; int level ; bool won ; float speed ; void checkWin() {} public: void init ( ) {} void addPoints (int value) {} float getSpeed ( ) C {} int getPoints ( ) C {} int getLevel ( ) C {} bool hasWon ( ) C {} void gameIsLost( ) {} } score Score; \end{code} As you can see, this class contains four values: points, level, won and speed. The latter does not really have anything to do with the score. But because the speed depends on the level, it is convenient to put it together with the rest. For example, the score object may also increase the speed when needed. \subsection{Simple Things} We'll do the basic functions first. The \eeFunc{init} method assigns all variables a suitable starting value. You start at level 1, with 0 points. And you have not won yet. The speed is equal to the constant \verb|INITIAL_SPEED|. The methods \eeFunc{getSpeed​}, \eeFunc{getPoints}, \eeFunc{getLevel} and \eeFunc{hasWon} just return the value of the corresponding variable. Write the contents of these five methods yourself. \subsection{checkWin \& gameIsLost} In \eeFunc{checkWin} you should check if the current level is greater than the constant \verb|NUM_LEVELS|. If so, then 'won' should be assigned \verb|true|. At this point, you also switch over to the `score' application state by writing \verb|ScoreState.set(1)| and play a festive sound with the \eeClass{Sound Manager}. The method \eeFunc{gameIsLost} is similar, but the check is not necessary. You have lost when a block does not fit in the playing field. The code to check that out does not belong in this class. We will write that someplace else, and at that point this method will be called. In this method, you ensure that `won' equals to \verb|false| and you also switch to \eeFunc{ScoreState}. And this time you start a less festive sound. \subsection{addPoints} This last feature will add points to the score. At that time we will also check whether the next level is reached and if so, adjust the speed. We will also check if the player has won the game, because this is the only moment when such can happen. Again, add the code below to your application. Make sure you understand all of it. Just typing is not enough! \begin{code} void addPoints(int value) { if(value > 0) { points += POINTS_PER_LINE * value; SoundManager.score(); if(points >= level * POINTS_PER_LEVEL) { level++; checkWin(); speed -= SPEED_CHANGE; } } } \end{code} \subsection{Score State} Now you are ready to add the code for the score state. The framework for that state was already done (otherwise you could not use the state in the \eeClass{score} class). As you can see, this state only contains an \eeFunc{update} and a \eeFunc{draw} method. Nothing needs to be initialised, so an \eeFunc{init} function is superfluous. For the draw function you can create something similar to the draw function in the Init state. It's probably best if it resembles that one. But you can create a slightly different version depending on whether you have won or not. (You can use the method \eeFunc{Score.hasWon()} to verify that.) You also want to show the score on the screen, and ask the player if (s)he wants to play another game. For the latter you provide a text on screen, requesting to press y or n. In the update function you check on the y and n keys. When the player presses y, then you switch back over to the GameState. If n is pressed, you exit the application.
The G.T.® Hammer Head® 90% tungsten dart has been the most desired dart among professional dart throwers for over 30 years. The hand machined barrel is front loaded and features a continuous taper allowing for unprecedented flight trajectory. The G.T.® III Thrust Cut TM allows the shooter a precise grip every throw!
""" Set x axis extent """ from typing import Dict import matplotlib.pyplot as pyplot import copy import numpy def set_x_extent(obj_mat, p): # type: (object, Dict) -> object """Set x axis extent Args: obj_mat (object): a matplotlib.image.AxesImage object p (dict): a properties of the matrix plot Returns: same as inputs """ old_extent = list(pyplot.getp(obj_mat, "extent")) old_x_extent = old_extent[0:2] old_y_extent = old_extent[2:4] new_min = p['matrix']['extent']['min']['x'] new_max = p['matrix']['extent']['max']['x'] if new_min is None and new_max is None: return else: new_x_extent = copy.deepcopy(old_x_extent) if new_min is not None: new_x_extent[0] = new_min else: pass if new_max is not None: new_x_extent[1] = new_max else: pass new_extent = new_x_extent + old_y_extent pyplot.setp(obj_mat, extent=new_extent) return
-- functional.lean -- variability-aware functional programming import .variability --import data.fintype --import data.finset --import tactic.basic --import order.boolean_algebra --import order.bounded_lattice namespace functional variables {α β : Type} section func --instance fin_fin_power {α : Type} [t : fintype α]: fintype (finset (finset α)) := --{ elems := finset.powerset (finset.univ.powerset) , -- complete := -- begin -- intros, apply finset.subset_univ, apply finset.mem_univ -- end} --def allProducts := allConfigs Feature L open variability open variability.PC --@[simp] def disjoint {Feature : Type} [fintype Feature] [decidable_eq Feature] (pc₁ pc₂: @PC Feature) : Prop := ⟦And pc₁ pc₂⟧ = ∅ lemma conj_preserves_disjoint {Feature : Type} [fintype Feature] [decidable_eq Feature] : ∀ (pc₁ : @PC Feature) (pc₂ : PC) (c : PC), disjoint pc₁ pc₂ → disjoint (And c pc₁) (And c pc₂) := begin --simp, -- ∀ (pc₁ pc₂ c : PC), semantics (And pc₁ pc₂) = ∅ → -- semantics (And (And c pc₁) (And c pc₂)) = ∅ intros pc₁ pc₂ c h, -- semantics (And (And c pc₁) (And c pc₂)) = ∅ unfold disjoint, unfold disjoint at h, unfold semantics, -- semantics c ∩ semantics pc₁ ∩ (semantics c ∩ semantics pc₂) = ∅ unfold semantics at h, -- a : semantics pc₁ ∩ semantics pc₂ = ∅ simp, rw finset.inter_comm _ (semantics pc₂), rw← finset.inter_assoc (semantics pc₁), rw h, rw finset.empty_inter, simp end --@[simp] def disjointList {Feature : Type} [t : fintype Feature] [decidable_eq Feature] (vs : list (@PC Feature)) : Prop := ∀ (x y : PC) , x ∈ vs → y ∈ vs → x ≠ y → disjoint x y def cover {Feature : Type} [t : fintype Feature] [d : decidable_eq Feature] (v : list (@PC Feature)) := semantics(list.foldr Or None v) /- lemma disj_cover {Feature : Type} [t : fintype Feature] [d : decidable_eq Feature] : ∀ (l₁ l₂ : list (@PC Feature)) (x y : PC), x ∈ l₁ → y ∈ l₂ → cover l₁ ∩ cover l₂ = ∅ → disjoint x y := begin intros l₁ l₂ x y h₁ h₂ h₃, unfold disjoint, unfold semantics, induction l₁, simp at h₁, by_contradiction, exact h₁, apply l₁_ih, simp at h₁, end -/ structure PCPartition {Feature: Type} [t : fintype Feature] [decidable_eq Feature] := (pcs : list (@PC Feature)) (disj : disjointList pcs) (comp : cover pcs = allConfigs) def getPC {Feature: Type} [t : fintype Feature] [d: decidable_eq Feature] (c : @Config Feature t) : (list (@PC Feature)) → @PC Feature | [] := None | (x :: xs) := ite (c ∈ ⟦x⟧) x (getPC xs) def pRel {Feature: Type} [t : fintype Feature] [d: decidable_eq Feature] (p : @PCPartition Feature t d) (c₁ : @Config Feature t) (c₂ : @Config Feature t) : Prop := getPC c₁ p.pcs = getPC c₂ p.pcs lemma pRelReflexive {Feature: Type} [t : fintype Feature] [d: decidable_eq Feature] (p : @PCPartition Feature t d) : ∀ (c : Config), pRel p c c := begin intros c, unfold pRel end lemma pRelSymmetric {Feature: Type} [t : fintype Feature] [d: decidable_eq Feature] (p : @PCPartition Feature t d) : symmetric (pRel p) := begin unfold symmetric, intros c₁ c₂ h, unfold pRel, unfold pRel at h, rw h end lemma pRelTransitive {Feature: Type} [t : fintype Feature] [d: decidable_eq Feature] (p : @PCPartition Feature t d) : ∀ (c₁ c₂ c₃: Config), pRel p c₁ c₂ → pRel p c₂ c₃ → pRel p c₁ c₃ := begin intros c₁ c₂ c₃ h₁ h₂, unfold pRel, unfold pRel at h₁, unfold pRel at h₂, rw h₁, rw← h₂ end lemma pRelEquiv {Feature: Type} [t : fintype Feature] [d: decidable_eq Feature] (p : @PCPartition Feature t d) : equivalence (pRel p) := ⟨pRelReflexive p, ⟨pRelSymmetric p, pRelTransitive p⟩⟩ structure Lifted {Feature: Type} [t : fintype Feature] [decidable_eq Feature] (α : Type) := (s : list (@Var Feature t α)) (nonEmpty : ¬s.empty) (disj : disjointList s) (comp : cover s = allConfigs) postfix `↑`:(max+1) := Lifted --lemma exists_config {Feature: Type} [t : fintype Feature] [d : decidable_eq Feature] (α : Type) : -- ∀ (x : @Lifted Feature t d α) (c : @Config Feature t), ∃ (v : @Var Feature t α), v ∈ x.s → c ∈ ⟦v.pc⟧ := --begin -- intros, --end def index' {Feature: Type} [t : fintype Feature] [decidable_eq Feature] {α : Type} (x : α↑) (c : Config) : list (@Var Feature t α) := let xs := list.filter (λ (y : @Var Feature t α), c ∈ ⟦y.pc⟧) x.s in xs #print equivalence lemma unique_index' {Feature: Type} [t : fintype Feature] [decidable_eq Feature] {α : Type} : ∀ (x : α↑) (c : @Config Feature t), list.length (index' x c) = 1 := begin --intros x c, unfold index', simp, intros x c, -- base case simp, apply x.nonEmpty, end --@[simp] def apply_single {Feature : Type} [t: fintype Feature] [d: decidable_eq Feature] {α β : Type} (f : @Var Feature t (α → β)) (u : α↑) : list (@Var Feature t β) := let sat := list.filter (λ(v : Var), ⟦And f.pc v.pc⟧ ≠ ∅) u.s in list.map (λ(v':Var), Var.mk (f.v v'.v) (And f.pc v'.pc)) sat lemma apply_single_disj {Feature : Type} [t: fintype Feature] [d: decidable_eq Feature] {α β : Type} : ∀ (f : @Var Feature t (α → β)) (u : @Lifted Feature t d α), disjointList (apply_single f u) := begin unfold apply_single, simp, intros f u, unfold disjointList, simp, intros x y x₁ h₁ h₂ h₃ x₂ h₄ h₅ h₆ h₇, rw[←h₃,←h₆], simp, apply conj_preserves_disjoint, apply u.disj, exact h₁, exact h₄, rw [←h₃, ←h₆] at h₇, simp at h₇, apply h₇ end section open classical lemma apply_single_cover {Feature : Type} [t : fintype Feature] [d: decidable_eq Feature] {α β : Type} : ∀ (f : @Var Feature t (α → β)) (u : @Lifted Feature t d α), cover (apply_single f u) = ⟦f.pc⟧ ∩ cover u.s := begin intros, unfold apply_single, induction u.s, -- base case simp, unfold cover, simp, unfold semantics, simp, -- induction simp, unfold list.filter, --unfold cover, simp, -- we need excluded middle.. this will be a classical proof cases decidable.em (semantics (PC.And (f.pc) (hd.pc)) = ∅) with hEmpty hNEmpty, { rw← hEmpty, simp, rw hEmpty, simp at ih, rw ih, unfold cover, simp, unfold semantics, rw finset.inter_distrib_left, unfold semantics at hEmpty, rw hEmpty, rw finset.empty_union }, { rw (if_pos hNEmpty), simp at ih, simp, unfold cover, simp, unfold cover at ih, unfold semantics, unfold semantics at ih, simp at ih, rw ih, rw finset.inter_distrib_left } end -- section #print lemma apply_single_append {Feature : Type} [t : fintype Feature] [d: decidable_eq Feature] {α β : Type} : ∀ (f₁ f₂ : @Var Feature t (α → β)) (u : @Lifted Feature t d α), disjoint f₁.pc f₂.pc → disjointList (apply_single f₁ u) → disjointList (apply_single f₂ u) → disjointList (list.append (apply_single f₁ u) (apply_single f₂ u)) := begin intros f₁ f₂ u, generalize : (apply_single f₁ u) = l₁, intros h₁ h₂ h₃, induction l₁, -- base case simp, apply h₃, -- induction simp, unfold disjointList at h₂, end @[simp] def apply_inner {Feature : Type} [t: fintype Feature] [d: decidable_eq Feature] (f : @Lifted Feature t d (α → β)) (v : @Lifted Feature t d α) : list (@Var Feature t β) := list.foldr list.append [] (list.map (λ x, apply_single x v) f.s lemma disjoint_append {Feature : Type} [t: fintype Feature] [d: decidable_eq Feature] {α β : Type} : ∀ (l₁ l₂ : list (@Var Feature t Feature)), cover l₁ ∩ cover l₂ = ∅ → disjointList l₁ → disjointList l₂ → disjointList (l₁ ++ l₂) := begin intros l₁ l₂ h₁ h₂ h₃, unfold disjointList, intros x y h₄ h₅ h₆, simp at h₄, simp at h₅, apply or.elim h₄, -- assume x ∈ l₁ intro h₇, apply or.elim h₅, -- and assume y ∈ l₁ intro h₈, unfold disjointList at h₂, apply h₂, exact h₇, exact h₈, exact h₆, -- now assume y ∈ l₂ intro h₈, -- base case simp, exact h₃, -- induction simp, unfold disjointList, intros x y h₄ h₅ h₆, simp at h₄, apply or.elim h₄, -- case 1 intro h₇, end lemma apply_inner_disjoint {Feature : Type} [t: fintype Feature] [d: decidable_eq Feature] {α β : Type} : ∀ (f : @Lifted Feature t d (α → β)) (v : @Lifted Feature t d α), disjointList(apply_inner f v) := begin unfold apply_inner, intros, induction f.s, -- base case unfold disjointList, simp, -- induction step unfold list.map, unfold list.foldr, unfold disjointList, intros, end lemma cover_append {Feature : Type} [t: fintype Feature] [d: decidable_eq Feature] {α : Type} : ∀ (l₁ l₂ : list (@Var Feature t α)), cover (list.append l₁ l₂) = cover l₁ ∪ cover l₂ := begin intros, induction l₁, -- base case simp, unfold cover, simp, unfold semantics, simp, -- induction unfold cover, simp, unfold semantics, unfold cover at l₁_ih, simp at l₁_ih, rw l₁_ih, rw← finset.union_assoc, cc end --#print finset.has_lift.lift #check finset.inter_univ lemma interAll {α : Type} {c: finset α} [d: decidable_eq α] [t: fintype α]: (c ∩ finset.univ) = c := begin intros, --lift finset.univ to (set α) using finset.lift, --finish[set.inter_eq_self_of_subset_left], apply finset.inter_univ end lemma apply_inner_complete {Feature : Type} [t: fintype Feature] [d: decidable_eq Feature] {α β : Type} : ∀ (f : @Lifted Feature t d (α → β)) (v : @Lifted Feature t d α), cover (apply_inner f v) = cover f.s := begin intros, unfold apply_inner, induction f.s, -- base case simp, refl, -- induction, simp, rw cover_append, simp at ih, rw ih, rw apply_single_cover, rw v.comp, simp, unfold cover, simp, unfold semantics end def apply {Feature : Type} [t: fintype Feature] [d: decidable_eq Feature] (f : @Lifted Feature t d (α → β)) (v : @Lifted Feature t d α) : @Lifted Feature t d β := ⟨apply_inner f v, _, apply_inner_complete⟩ end func end functional
(* Title: HOL/Auth/n_german_lemma_on_inv__42.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_german Protocol Case Study*} theory n_german_lemma_on_inv__42 imports n_german_base begin section{*All lemmas on causal relation between inv__42 and some rule r*} lemma n_RecvReqSVsinv__42: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__42 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvReqS N i" apply fastforce done from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__42 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Ident ''CurCmd'')) (Const Empty)) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv2) ''Cmd'')) (Const Inv))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv2)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Ident ''CurCmd'')) (Const Empty)) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv2) ''Cmd'')) (Const Inv))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvReqEVsinv__42: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__42 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvReqE N i" apply fastforce done from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__42 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInv__part__0Vsinv__42: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__42 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInv__part__0 i" apply fastforce done from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__42 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv2)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInv__part__1Vsinv__42: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__42 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInv__part__1 i" apply fastforce done from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__42 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv2)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInvAckVsinv__42: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__42 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInvAck i" apply fastforce done from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__42 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv2)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvInvAckVsinv__42: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__42 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvInvAck i" apply fastforce done from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__42 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "((formEval (eqn (IVar (Ident ''ExGntd'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Ident ''ExGntd'')) (Const true))) s))" by auto moreover { assume c1: "((formEval (eqn (IVar (Ident ''ExGntd'')) (Const true)) s))" have "?P3 s" apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv2) ''Cmd'')) (Const Inv)) (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv2) ''Cmd'')) (Const InvAck))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (neg (eqn (IVar (Ident ''ExGntd'')) (Const true))) s))" have "?P2 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately have "invHoldForRule s f r (invariants N)" by satx } moreover { assume b1: "(i~=p__Inv2)" have "((formEval (eqn (IVar (Ident ''ExGntd'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Ident ''ExGntd'')) (Const true))) s))" by auto moreover { assume c1: "((formEval (eqn (IVar (Ident ''ExGntd'')) (Const true)) s))" have "?P3 s" apply (cut_tac a1 a2 b1 c1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv2) ''Cmd'')) (Const Inv)) (eqn (IVar (Ident ''CurCmd'')) (Const ReqS))) (eqn (IVar (Field (Para (Ident ''Chan3'') i) ''Cmd'')) (Const InvAck))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (neg (eqn (IVar (Ident ''ExGntd'')) (Const true))) s))" have "?P2 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately have "invHoldForRule s f r (invariants N)" by satx } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendGntSVsinv__42: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__42 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntS i" apply fastforce done from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__42 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendGntEVsinv__42: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__42 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntE N i" apply fastforce done from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__42 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvGntSVsinv__42: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__42 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvGntS i" apply fastforce done from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__42 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv2)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvGntEVsinv__42: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__42 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvGntE i" apply fastforce done from a2 obtain p__Inv2 where a2:"p__Inv2\<le>N\<and>f=inv__42 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv2)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendReqE__part__1Vsinv__42: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__42 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_StoreVsinv__42: assumes a1: "\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__42 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendReqE__part__0Vsinv__42: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__42 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendReqSVsinv__42: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqS i" and a2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__42 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
function xdot = dto_rhs (t, x, u) % first-order equations of motion % required by dto_trap.m % input % t = current time % x = current state vector % x(1) = r, x(2) = u, x(3) = v % u = current control vector % output % xdot = rhs equations of motion % xdot(1) = r dot, xdot(2) = u dot, xdot(3) = v dot % Orbital Mechanics with MATLAB %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% global acc beta % current control variable theta = u(1); % current thrust acceleration accm = acc / (1.0 - beta * t); % evaluate equations of motion at current conditions xdot(1) = x(2); xdot(2) = (x(3) * x(3) - 1.0 / x(1)) / x(1) + accm * sin(theta); xdot(3) = -x(2) * x(3) / x(1) + accm * cos(theta);
{- Finitely presented algebras. An R-algebra A is finitely presented, if there merely is an exact sequence of R-modules: (f₁,⋯,fₘ) → R[X₁,⋯,Xₙ] → A → 0 (where f₁,⋯,fₘ ∈ R[X₁,⋯,Xₙ]) -} {-# OPTIONS --safe #-} module Cubical.Algebra.CommAlgebra.FPAlgebra where open import Cubical.Foundations.Prelude open import Cubical.Foundations.Equiv open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.Powerset open import Cubical.Foundations.Function open import Cubical.Foundations.HLevels open import Cubical.Foundations.Structure open import Cubical.Data.FinData open import Cubical.Data.Nat open import Cubical.Data.Vec open import Cubical.Data.Sigma open import Cubical.Data.Empty open import Cubical.HITs.PropositionalTruncation open import Cubical.Algebra.CommRing open import Cubical.Algebra.CommRing.FGIdeal using (inclOfFGIdeal) open import Cubical.Algebra.CommAlgebra open import Cubical.Algebra.CommAlgebra.FreeCommAlgebra renaming (inducedHom to freeInducedHom) open import Cubical.Algebra.CommAlgebra.QuotientAlgebra renaming (inducedHom to quotientInducedHom) open import Cubical.Algebra.CommAlgebra.Ideal open import Cubical.Algebra.CommAlgebra.FGIdeal open import Cubical.Algebra.CommAlgebra.Instances.Initial open import Cubical.Algebra.CommAlgebra.Instances.Unit renaming (UnitCommAlgebra to TerminalCAlg) open import Cubical.Algebra.CommAlgebra.Kernel open import Cubical.Algebra.Algebra.Properties open import Cubical.Algebra.Algebra private variable ℓ : Level module _ {R : CommRing ℓ} where open Construction using (var) Polynomials : (n : ℕ) → CommAlgebra R ℓ Polynomials n = R [ Fin n ] evPoly : {n : ℕ} (A : CommAlgebra R ℓ) → ⟨ Polynomials n ⟩ → FinVec ⟨ A ⟩ n → ⟨ A ⟩ evPoly A P values = fst (freeInducedHom A values) P evPolyPoly : {n : ℕ} (P : ⟨ Polynomials n ⟩) → evPoly (Polynomials n) P var ≡ P evPolyPoly {n = n} P = cong (λ u → fst u P) (inducedHomVar R (Fin n)) evPolyHomomorphic : {n : ℕ} (A B : CommAlgebra R ℓ) (f : CommAlgebraHom A B) → (P : ⟨ Polynomials n ⟩) → (values : FinVec ⟨ A ⟩ n) → (fst f) (evPoly A P values) ≡ evPoly B P (fst f ∘ values) evPolyHomomorphic A B f P values = (fst f) (evPoly A P values) ≡⟨ refl ⟩ (fst f) (fst (freeInducedHom A values) P) ≡⟨ refl ⟩ fst (f ∘a freeInducedHom A values) P ≡⟨ cong (λ u → fst u P) (natIndHomR f values) ⟩ fst (freeInducedHom B (fst f ∘ values)) P ≡⟨ refl ⟩ evPoly B P (fst f ∘ values) ∎ where open AlgebraHoms module _ {m : ℕ} (n : ℕ) (relation : FinVec ⟨ Polynomials n ⟩ m) where open CommAlgebraStr using (0a) open Cubical.Algebra.Algebra.Properties.AlgebraHoms relationsIdeal = generatedIdeal (Polynomials n) relation abstract {- The following definitions are abstract because of type checking speed problems - complete unfolding of FPAlgebra is triggered otherwise. This also means, the where blocks contain more type declarations than usual. -} FPAlgebra : CommAlgebra R ℓ FPAlgebra = Polynomials n / relationsIdeal modRelations : CommAlgebraHom (Polynomials n) (Polynomials n / relationsIdeal) modRelations = quotientHom (Polynomials n) relationsIdeal generator : (i : Fin n) → ⟨ FPAlgebra ⟩ generator = fst modRelations ∘ var relationsHold : (i : Fin m) → evPoly FPAlgebra (relation i) generator ≡ 0a (snd FPAlgebra) relationsHold i = evPoly FPAlgebra (relation i) generator ≡⟨ sym (evPolyHomomorphic (Polynomials n) FPAlgebra modRelations (relation i) var) ⟩ fst modRelations (evPoly (Polynomials n) (relation i) var) ≡⟨ cong (λ u → fst modRelations u) (evPolyPoly (relation i)) ⟩ fst modRelations (relation i) ≡⟨ isZeroFromIdeal {R = R} {A = (Polynomials n)} {I = relationsIdeal} (relation i) (incInIdeal (Polynomials n) relation i ) ⟩ 0a (snd FPAlgebra) ∎ inducedHom : (A : CommAlgebra R ℓ) (values : FinVec ⟨ A ⟩ n) (relationsHold : (i : Fin m) → evPoly A (relation i) values ≡ 0a (snd A)) → CommAlgebraHom FPAlgebra A inducedHom A values relationsHold = quotientInducedHom (Polynomials n) relationsIdeal A freeHom isInKernel where freeHom : CommAlgebraHom (Polynomials n) A freeHom = freeInducedHom A values isInKernel : fst (generatedIdeal (Polynomials n) relation) ⊆ fst (kernel (Polynomials n) A freeHom) isInKernel = inclOfFGIdeal (CommAlgebra→CommRing (Polynomials n)) relation (kernel (Polynomials n) A freeHom) relationsHold inducedHomOnGenerators : (A : CommAlgebra R ℓ) (values : FinVec ⟨ A ⟩ n) (relationsHold : (i : Fin m) → evPoly A (relation i) values ≡ 0a (snd A)) (i : Fin n) → fst (inducedHom A values relationsHold) (generator i) ≡ values i inducedHomOnGenerators _ _ _ _ = refl unique : {A : CommAlgebra R ℓ} (values : FinVec ⟨ A ⟩ n) (relationsHold : (i : Fin m) → evPoly A (relation i) values ≡ 0a (snd A)) (f : CommAlgebraHom FPAlgebra A) → ((i : Fin n) → fst f (generator i) ≡ values i) → inducedHom A values relationsHold ≡ f unique {A = A} values relationsHold f hasCorrectValues = injectivePrecomp (Polynomials n) relationsIdeal A (inducedHom A values relationsHold) f (sym ( f' ≡⟨ sym (inv f') ⟩ freeInducedHom A (evaluateAt A f') ≡⟨ cong (freeInducedHom A) (funExt hasCorrectValues) ⟩ freeInducedHom A values ≡⟨ cong (freeInducedHom A) refl ⟩ freeInducedHom A (evaluateAt A iHom') ≡⟨ inv iHom' ⟩ iHom' ∎)) where {- Poly n | \ modRelations f' ↓ ↘ FPAlgebra ─f→ A -} f' iHom' : CommAlgebraHom (Polynomials n) A f' = compAlgebraHom modRelations f iHom' = compAlgebraHom modRelations (inducedHom A values relationsHold) inv : retract (Iso.fun (homMapIso {I = Fin n} A)) (Iso.inv (homMapIso A)) inv = Iso.leftInv (homMapIso {R = R} {I = Fin n} A) universal : (A : CommAlgebra R ℓ) (values : FinVec ⟨ A ⟩ n) (relationsHold : (i : Fin m) → evPoly A (relation i) values ≡ 0a (snd A)) → isContr (Σ[ f ∈ CommAlgebraHom FPAlgebra A ] ((i : Fin n) → fst f (generator i) ≡ values i)) universal A values relationsHold = ( (inducedHom A values relationsHold) , (inducedHomOnGenerators A values relationsHold) ) , λ {(f , mapsValues) → Σ≡Prop (λ _ → isPropΠ (λ _ → isSetCommAlgebra A _ _)) (unique values relationsHold f mapsValues)} {- ∀ A : Comm-R-Algebra, ∀ J : Finitely-generated-Ideal, Hom(R[I]/J,A) is isomorphic to the Set of roots of the generators of J -} zeroLocus : (A : CommAlgebra R ℓ) → Type ℓ zeroLocus A = Σ[ v ∈ FinVec ⟨ A ⟩ n ] ((i : Fin m) → evPoly A (relation i) v ≡ 0a (snd A)) inducedHomFP : (A : CommAlgebra R ℓ) → zeroLocus A → CommAlgebraHom FPAlgebra A inducedHomFP A d = inducedHom A (fst d) (snd d) evaluateAtFP : {A : CommAlgebra R ℓ} → CommAlgebraHom FPAlgebra A → zeroLocus A evaluateAtFP {A} f = value , λ i → evPoly A (relation i) value ≡⟨ step1 (relation i) ⟩ fst compHom (evPoly (Polynomials n) (relation i) var) ≡⟨ refl ⟩ (fst f) ((fst modRelations) (evPoly (Polynomials n) (relation i) var)) ≡⟨ cong (fst f) (evPolyHomomorphic (Polynomials n) FPAlgebra modRelations (relation i) var) ⟩ (fst f) (evPoly FPAlgebra (relation i) generator) ≡⟨ cong (fst f) (relationsHold i) ⟩ (fst f) (0a (snd FPAlgebra)) ≡⟨ IsAlgebraHom.pres0 (snd f) ⟩ 0a (snd A) ∎ where compHom : CommAlgebraHom (Polynomials n) A compHom = CommAlgebraHoms.compCommAlgebraHom (Polynomials n) FPAlgebra A modRelations f value : FinVec ⟨ A ⟩ n value = (Iso.fun (homMapIso A)) compHom step1 : (x : ⟨ Polynomials n ⟩) → evPoly A x value ≡ fst compHom (evPoly (Polynomials n) x var) step1 x = sym (evPolyHomomorphic (Polynomials n) A compHom x var) FPHomIso : {A : CommAlgebra R ℓ} → Iso (CommAlgebraHom FPAlgebra A) (zeroLocus A) Iso.fun FPHomIso = evaluateAtFP Iso.inv FPHomIso = inducedHomFP _ Iso.rightInv (FPHomIso {A}) = λ b → Σ≡Prop (λ x → isPropΠ (λ i → isSetCommAlgebra A (evPoly A (relation i) x) (0a (snd A)))) refl Iso.leftInv (FPHomIso {A}) = λ a → Σ≡Prop (λ f → isPropIsCommAlgebraHom {ℓ} {R} {ℓ} {ℓ} {FPAlgebra} {A} f) λ i → fst (unique {A} (fst (evaluateAtFP {A} a)) (snd (evaluateAtFP a)) a (λ j → refl) i) homMapPathFP : (A : CommAlgebra R ℓ)→ CommAlgebraHom FPAlgebra A ≡ zeroLocus A homMapPathFP A = isoToPath (FPHomIso {A}) isSetZeroLocus : (A : CommAlgebra R ℓ) → isSet (zeroLocus A) isSetZeroLocus A = J (λ y _ → isSet y) (isSetAlgebraHom (CommAlgebra→Algebra FPAlgebra) (CommAlgebra→Algebra A)) (homMapPathFP A) record FinitePresentation (A : CommAlgebra R ℓ) : Type ℓ where field n : ℕ m : ℕ relations : FinVec ⟨ Polynomials n ⟩ m equiv : CommAlgebraEquiv (FPAlgebra n relations) A isFPAlgebra : (A : CommAlgebra R ℓ) → Type _ isFPAlgebra A = ∥ FinitePresentation A ∥₁ isFPAlgebraIsProp : {A : CommAlgebra R ℓ} → isProp (isFPAlgebra A) isFPAlgebraIsProp = isPropPropTrunc module Instances (R : CommRing ℓ) where open FinitePresentation {- Every (multivariate) polynomial algebra is finitely presented -} module _ (n : ℕ) where private A : CommAlgebra R ℓ A = Polynomials n emptyGen : FinVec (fst A) 0 emptyGen = λ () B : CommAlgebra R ℓ B = FPAlgebra n emptyGen polynomialAlgFP : FinitePresentation A FinitePresentation.n polynomialAlgFP = n m polynomialAlgFP = 0 relations polynomialAlgFP = emptyGen equiv polynomialAlgFP = -- Idea: A and B enjoy the same universal property. toAAsEquiv , snd toA where toA : CommAlgebraHom B A toA = inducedHom n emptyGen A Construction.var (λ ()) fromA : CommAlgebraHom A B fromA = freeInducedHom B (generator _ _) open AlgebraHoms inverse1 : fromA ∘a toA ≡ idAlgebraHom _ inverse1 = fromA ∘a toA ≡⟨ sym (unique _ _ _ _ _ (λ i → cong (fst fromA) ( fst toA (generator n emptyGen i) ≡⟨ inducedHomOnGenerators _ _ _ _ _ _ ⟩ Construction.var i ∎))) ⟩ inducedHom n emptyGen B (generator _ _) (relationsHold _ _) ≡⟨ unique _ _ _ _ _ (λ i → refl) ⟩ idAlgebraHom _ ∎ inverse2 : toA ∘a fromA ≡ idAlgebraHom _ inverse2 = isoFunInjective (homMapIso A) _ _ ( evaluateAt A (toA ∘a fromA) ≡⟨ sym (naturalEvR {A = B} {B = A} toA fromA) ⟩ fst toA ∘ evaluateAt B fromA ≡⟨ refl ⟩ fst toA ∘ generator _ _ ≡⟨ funExt (inducedHomOnGenerators _ _ _ _ _)⟩ Construction.var ∎) toAAsEquiv : ⟨ B ⟩ ≃ ⟨ A ⟩ toAAsEquiv = isoToEquiv (iso (fst toA) (fst fromA) (λ a i → fst (inverse2 i) a) (λ b i → fst (inverse1 i) b)) {- The initial R-algebra is finitely presented -} private R[⊥] : CommAlgebra R ℓ R[⊥] = Polynomials 0 emptyGen : FinVec (fst R[⊥]) 0 emptyGen = λ () R[⊥]/⟨0⟩ : CommAlgebra R ℓ R[⊥]/⟨0⟩ = FPAlgebra 0 emptyGen R[⊥]/⟨0⟩IsInitial : (B : CommAlgebra R ℓ) → isContr (CommAlgebraHom R[⊥]/⟨0⟩ B) R[⊥]/⟨0⟩IsInitial B = iHom , uniqueness where iHom : CommAlgebraHom R[⊥]/⟨0⟩ B iHom = inducedHom 0 emptyGen B (λ ()) (λ ()) uniqueness : (f : CommAlgebraHom R[⊥]/⟨0⟩ B) → iHom ≡ f uniqueness f = unique 0 emptyGen {A = B} (λ ()) (λ ()) f (λ ()) initialCAlgFP : FinitePresentation (initialCAlg R) n initialCAlgFP = 0 m initialCAlgFP = 0 relations initialCAlgFP = emptyGen equiv initialCAlgFP = equivByInitiality R R[⊥]/⟨0⟩ R[⊥]/⟨0⟩IsInitial {- The terminal R-algebra is finitely presented -} private unitGen : FinVec (fst R[⊥]) 1 unitGen zero = 1a where open CommAlgebraStr (snd R[⊥]) R[⊥]/⟨1⟩ : CommAlgebra R ℓ R[⊥]/⟨1⟩ = FPAlgebra 0 unitGen terminalCAlgFP : FinitePresentation (TerminalCAlg R) n terminalCAlgFP = 0 m terminalCAlgFP = 1 relations terminalCAlgFP = unitGen equiv terminalCAlgFP = equivFrom1≡0 R R[⊥]/⟨1⟩ (sym (⋆-lid 1a) ∙ relationsHold 0 unitGen zero) where open CommAlgebraStr (snd R[⊥]/⟨1⟩) {- Quotients of the base ring by principal ideals are finitely presented. -} module _ (x : ⟨ R ⟩) where ⟨x⟩ : IdealsIn (initialCAlg R) ⟨x⟩ = generatedIdeal (initialCAlg R) (replicateFinVec 1 x) R/⟨x⟩ = (initialCAlg R) / ⟨x⟩ open CommAlgebraStr ⦃...⦄ private relation : FinVec ⟨ Polynomials {R = R} 0 ⟩ 1 relation = replicateFinVec 1 (Construction.const x) B = FPAlgebra 0 relation π = quotientHom (initialCAlg R) ⟨x⟩ instance _ = snd R/⟨x⟩ _ = snd (initialCAlg R) _ = snd B πx≡0 : π $a x ≡ 0a πx≡0 = isZeroFromIdeal {A = initialCAlg R} {I = ⟨x⟩} x (incInIdeal (initialCAlg R) (replicateFinVec 1 x) zero) R/⟨x⟩FP : FinitePresentation R/⟨x⟩ n R/⟨x⟩FP = 0 m R/⟨x⟩FP = 1 relations R/⟨x⟩FP = relation equiv R/⟨x⟩FP = (isoToEquiv (iso (fst toA) (fst fromA) (λ a i → toFrom i $a a) λ a i → fromTo i $a a)) , (snd toA) where toA : CommAlgebraHom B R/⟨x⟩ toA = inducedHom 0 relation R/⟨x⟩ (λ ()) relation-holds where vals : FinVec ⟨ R/⟨x⟩ ⟩ 0 vals () vals' : FinVec ⟨ initialCAlg R ⟩ 0 vals' () relation-holds = λ zero → evPoly R/⟨x⟩ (relation zero) (λ ()) ≡⟨ sym (evPolyHomomorphic (initialCAlg R) R/⟨x⟩ π (Construction.const x) vals') ⟩ π $a (evPoly (initialCAlg R) (Construction.const x) vals') ≡⟨ cong (π $a_) (·Rid x) ⟩ π $a x ≡⟨ πx≡0 ⟩ 0a ∎ {- R ─→ R/⟨x⟩ id↓ ↓ ∃! R ─→ R[⊥]/⟨const x⟩ -} fromA : CommAlgebraHom R/⟨x⟩ B fromA = quotientInducedHom (initialCAlg R) ⟨x⟩ B (initialMap R B) (inclOfFGIdeal (CommAlgebra→CommRing (initialCAlg R)) (replicateFinVec 1 x) (kernel (initialCAlg R) B (initialMap R B)) λ {Fin.zero → relationsHold 0 relation Fin.zero}) open AlgebraHoms fromTo : fromA ∘a toA ≡ idCAlgHom B fromTo = cong fst (isContr→isProp (universal 0 relation B (λ ()) (relationsHold 0 relation)) (fromA ∘a toA , (λ ())) (idCAlgHom B , (λ ()))) toFrom : toA ∘a fromA ≡ idCAlgHom R/⟨x⟩ toFrom = injectivePrecomp (initialCAlg R) ⟨x⟩ R/⟨x⟩ (toA ∘a fromA) (idCAlgHom R/⟨x⟩) (isContr→isProp (initialityContr R R/⟨x⟩) _ _)
lemma LIM_const_not_eq[tendsto_intros]: "k \<noteq> L \<Longrightarrow> \<not> (\<lambda>x. k) \<midarrow>a\<rightarrow> L" for a :: "'a::perfect_space" and k L :: "'b::t2_space"
(* Title: HOL/Auth/n_flash_lemma_on_inv__32.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_flash Protocol Case Study*} theory n_flash_lemma_on_inv__32 imports n_flash_base begin section{*All lemmas on causal relation between inv__32 and some rule r*} lemma n_PI_Remote_GetVsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Get src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_PI_Remote_GetXVsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_GetX src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_NakVsinv__32: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Nak dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Nak__part__0Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Nak__part__1Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Nak__part__2Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Get__part__0Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Get__part__1Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Put_HeadVsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_PutVsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Put_DirtyVsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_Get_NakVsinv__32: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_Get_Nak_HomeVsinv__32: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_Get_PutVsinv__32: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_Get_Put_HomeVsinv__32: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') dst) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_Nak__part__0Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_Nak__part__1Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_Nak__part__2Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_GetX__part__0Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_GetX__part__1Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_1Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_2Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_3Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_4Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_5Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_6Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_8_HomeVsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_8Vsinv__32: assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__32: assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_10_HomeVsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_10Vsinv__32: assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_11Vsinv__32: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Local'')) (Const true))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_GetX_NakVsinv__32: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_GetX_Nak_HomeVsinv__32: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_GetX_PutXVsinv__32: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') dst) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_GetX_PutX_HomeVsinv__32: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_PutVsinv__32: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_PutXVsinv__32: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_PI_Local_Get_GetVsinv__32: assumes a1: "(r=n_PI_Local_Get_Get )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_GetX__part__0Vsinv__32: assumes a1: "(r=n_PI_Local_GetX_GetX__part__0 )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_GetX__part__1Vsinv__32: assumes a1: "(r=n_PI_Local_GetX_GetX__part__1 )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Nak_HomeVsinv__32: assumes a1: "(r=n_NI_Nak_Home )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_PutVsinv__32: assumes a1: "(r=n_NI_Local_Put )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_PutXAcksDoneVsinv__32: assumes a1: "(r=n_NI_Local_PutXAcksDone )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__32 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_PutX__part__0Vsinv__32: assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_WbVsinv__32: assumes a1: "r=n_NI_Wb " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_StoreVsinv__32: assumes a1: "\<exists> src data. src\<le>N\<and>data\<le>N\<and>r=n_Store src data" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_3Vsinv__32: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_1Vsinv__32: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Remote_ReplaceVsinv__32: assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_Store_HomeVsinv__32: assumes a1: "\<exists> data. data\<le>N\<and>r=n_Store_Home data" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_ReplaceVsinv__32: assumes a1: "r=n_PI_Local_Replace " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_existsVsinv__32: assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Remote_PutXVsinv__32: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvVsinv__32: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_PutXVsinv__32: assumes a1: "r=n_PI_Local_PutX " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_Get_PutVsinv__32: assumes a1: "r=n_PI_Local_Get_Put " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_ShWbVsinv__32: assumes a1: "r=n_NI_ShWb N " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__32: assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__0 N " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_ReplaceVsinv__32: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Replace src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_PutX__part__1Vsinv__32: assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_exists_HomeVsinv__32: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Replace_HomeVsinv__32: assumes a1: "r=n_NI_Replace_Home " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Nak_ClearVsinv__32: assumes a1: "r=n_NI_Nak_Clear " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_2Vsinv__32: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__32: assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__1 N " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_FAckVsinv__32: assumes a1: "r=n_NI_FAck " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__32 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
lemma limI: "X \<longlonglongrightarrow> L \<Longrightarrow> lim X = L"
Formal statement is: lemma degree_add_eq_left: "degree q < degree p \<Longrightarrow> degree (p + q) = degree p" Informal statement is: If the degree of $q$ is less than the degree of $p$, then the degree of $p + q$ is equal to the degree of $p$.
// // Created by shida on 06/12/16. // #include <Eigen/Geometry> #include "Modeler/ModelDrawer.h" namespace ORB_SLAM2 { ModelDrawer::ModelDrawer(Map* pMap):mpMap(pMap),mbModelUpdateRequested(false), mbModelUpdateDone(true) { target.setZero(); } void ModelDrawer::DrawModel(bool bRGB) { //TODO: find a way to optimize rendering keyframes // select 10 KFs int numKFs = 1; vector<KeyFrame*> vpKFs = mpMap->GetAllKeyFrames(); std::sort(vpKFs.begin(), vpKFs.end(), KeyFrame::lId); vector<KeyFrame*> vpKFtex; for(auto it = vpKFs.rbegin(); it != vpKFs.rend(); ++it) { if ((int)vpKFtex.size() >= numKFs) break; KeyFrame *kf = *it; kf->SetNotEraseDrawer(); if (kf->isBad()) { kf->SetEraseDrawer(); continue; } vpKFtex.push_back(kf); } UpdateModel(); if ((int)vpKFtex.size() >= numKFs) { static unsigned int frameTex = 0; if (!frameTex) glGenTextures(numKFs, &frameTex); cv::Size imSize = vpKFtex[0]->mImage.size(); cv::Mat mat_array[numKFs]; for (int i = 0; i < numKFs; i++) { if (vpKFtex[i]->mImage.channels() == 3) { mat_array[i] = vpKFtex[i]->mImage; } else { //num of channels is not 3, something is wrong for (auto it = vpKFtex.begin(); it != vpKFtex.end(); it++) (*it)->SetEraseDrawer(); //release the keyframes return; } } // cv::Mat texture; // cv::vconcat(mat_array, numKFs, texture); // // glEnable(GL_TEXTURE_2D); // // glBindTexture(GL_TEXTURE_2D, frameTex); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); // // image are saved in RGB format, grayscale images are converted // if (bRGB) { // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, // imSize.width, imSize.height*numKFs, 0, // GL_BGR, // GL_UNSIGNED_BYTE, // texture.data); // } else { // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, // imSize.width, imSize.height*numKFs, 0, // GL_RGB, // GL_UNSIGNED_BYTE, // texture.data); // } // // select one texture for each triangle // std::vector<int> tex4tri; // for (list<dlovi::Matrix>::const_iterator it = GetTris().begin(); it != GetTris().end(); it++) { // int tex_ind_curr = -1; // // for (int i = 0; i < numKFs; i++) { // dlovi::Matrix point0 = GetPoints()[(*it)(0)]; // dlovi::Matrix point1 = GetPoints()[(*it)(1)]; // dlovi::Matrix point2 = GetPoints()[(*it)(2)]; // // TextureFrame tex = imAndTexFrame[i].second; // vector<float> uv0 = tex.GetTexCoordinate(point0(0), point0(1), point0(2), imSize); // vector<float> uv1 = tex.GetTexCoordinate(point1(0), point1(1), point1(2), imSize); // vector<float> uv2 = tex.GetTexCoordinate(point2(0), point2(1), point2(2), imSize); // // if (uv0.size() == 2 && uv1.size() == 2 && uv2.size() == 2) { // tex_ind_curr = i; // break; // } // } // // if (tex_ind_curr < 0) // tex_ind_curr = 0; // // tex4tri.push_back(tex_ind_curr); // } glBegin(GL_TRIANGLES); glColor3f(1.0, 1.0, 1.0); int index = 0; for (list<dlovi::Matrix>::const_iterator it = GetTris().begin(); it != GetTris().end(); it++, index++) { dlovi::Matrix point0 = GetPoints()[(*it)(0)]; dlovi::Matrix point1 = GetPoints()[(*it)(1)]; dlovi::Matrix point2 = GetPoints()[(*it)(2)]; // glVertex3d(point0(0), point0(1), point0(2)); // glVertex3d(point1(0), point1(1), point1(2)); // glVertex3d(point2(0), point2(1), point2(2)); for (int i = 0; i < numKFs; i++) { vector<float> uv0 = vpKFtex[i]->GetTexCoordinate(point0(0), point0(1), point0(2), imSize); vector<float> uv1 = vpKFtex[i]->GetTexCoordinate(point1(0), point1(1), point1(2), imSize); vector<float> uv2 = vpKFtex[i]->GetTexCoordinate(point2(0), point2(1), point2(2), imSize); if (uv0.size() == 2 && uv1.size() == 2 && uv2.size() == 2) { glTexCoord2f(uv0[0], (uv0[1]+i)/numKFs); glVertex3d(point0(0), point0(1), point0(2)); glTexCoord2f(uv1[0], (uv1[1]+i)/numKFs); glVertex3d(point1(0), point1(1), point1(2)); glTexCoord2f(uv2[0], (uv2[1]+i)/numKFs); glVertex3d(point2(0), point2(1), point2(2)); break; } } } glEnd(); glDisable(GL_TEXTURE_2D); } for (auto it = vpKFtex.begin(); it != vpKFtex.end(); it++) (*it)->SetEraseDrawer(); //release the keyframes } void ModelDrawer::DrawModelPoints() { UpdateModel(); glPointSize(3); glBegin(GL_POINTS); glColor3f(0.5, 0.5, 0.5); //cout<<"model point size: "<<GetPoints().size()<<endl; for (size_t i = 0; i < GetPoints().size(); i++) { glVertex3d(GetPoints()[i](0), GetPoints()[i](1), GetPoints()[i](2)); } glEnd(); } void ModelDrawer::SetTarget(pangolin::OpenGlMatrix &Twc, Eigen::Vector3d t) { Eigen::Vector3d diff = t - target; if (diff.squaredNorm() > 0.0) { target = t; //Eigen::Matrix<double,4,4> m = Twc; //target_w = Eigen::Transform<double,3,Eigen::Affine>(m) * t; target_w = t; //search all map points, find nearest target_w, only in camera's x, y plane. double minDist = 99999; int nearestIndex = -1; for (size_t i = 0; i < GetPoints().size(); i++) { double distance = sqrt((GetPoints()[i](0)-target_w[0])*(GetPoints()[i](0)-target_w[0])+ (GetPoints()[i](1)-target_w[1])*(GetPoints()[i](1)-target_w[1]) + (GetPoints()[i](2)-target_w[2])*(GetPoints()[i](2)-target_w[2])); if(distance<minDist) { nearestIndex = i; minDist = distance; } } target_w[0] = GetPoints()[nearestIndex](0); target_w[1] = GetPoints()[nearestIndex](1); target_w[2] = GetPoints()[nearestIndex](2); // const vector<MapPoint*> &vpMPs = mpMap->GetAllMapPoints(); // if(vpMPs.empty()) // return; // // for(size_t i=0, iend=vpMPs.size(); i<iend;i++) // { // // if(vpMPs[i]->isBad()) // // continue; // cv::Mat pos = vpMPs[i]->GetWorldPos(); // double distance = sqrt((pos.at<double>(0)-target_w[0])*(pos.at<double>(0)-target_w[0])+ // (pos.at<double>(1)-target_w[1])*(pos.at<double>(1)-target_w[1])+ // (pos.at<double>(2)-target_w[2])*(pos.at<double>(2)-target_w[2])); // if(distance<minDist) // { // nearestIndex = i; // minDist = distance; // } // } // target_w[0] = (vpMPs[nearestIndex]->GetWorldPos()).at<double>(0); // target_w[1] = (vpMPs[nearestIndex]->GetWorldPos()).at<double>(1); // target_w[2] = (vpMPs[nearestIndex]->GetWorldPos()).at<double>(2); } //cout<<"selected target target_w: "<<target_w<<endl; } cv::Mat ModelDrawer::GetTarget() { cv::Mat T = (cv::Mat_<float>(3,1) << target_w[0], target[1], target[2]); return T; } string ModelDrawer::GetTargetStr() { std::stringstream ss; ss<<target_w[0]<<","<<target_w[1]<<","<<target_w[2]; return ss.str(); } void ModelDrawer::DrawTarget() { glPointSize(10); glBegin(GL_POINTS); glColor3f(0.0, 1.0, 0.0); glVertex3d(target_w[0], target_w[1], target_w[2]); glEnd(); } void ModelDrawer::DrawTarget(pangolin::OpenGlMatrix &Twc, Eigen::Vector3d t) { SetTarget(Twc, t); DrawTarget(); } void ModelDrawer::DrawTriangles(pangolin::OpenGlMatrix &Twc) { UpdateModel(); glPushMatrix(); #ifdef HAVE_GLES glMultMatrixf(Twc.m); #else glMultMatrixd(Twc.m); #endif GLfloat light_position[] = { 0.0, 0.0, 1.0, 0.0 }; glLightfv(GL_LIGHT0, GL_POSITION, light_position); glPopMatrix(); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glShadeModel(GL_FLAT); GLfloat material_diffuse[] = {0.2, 0.5, 0.8, 1}; glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, material_diffuse); glBegin(GL_TRIANGLES); glColor3f(1.0,1.0,1.0); for (list<dlovi::Matrix>::const_iterator it = GetTris().begin(); it != GetTris().end(); it++) { dlovi::Matrix point0 = GetPoints()[(*it)(0)]; dlovi::Matrix point1 = GetPoints()[(*it)(1)]; dlovi::Matrix point2 = GetPoints()[(*it)(2)]; dlovi::Matrix edge10 = point1 - point0; dlovi::Matrix edge20 = point2 - point0; dlovi::Matrix normal = edge20.cross(edge10); normal = normal / normal.norm(); glNormal3d(normal(0), normal(1), normal(2)); glVertex3d(point0(0), point0(1), point0(2)); glVertex3d(point1(0), point1(1), point1(2)); glVertex3d(point2(0), point2(1), point2(2)); } glEnd(); glDisable(GL_LIGHTING); } void ModelDrawer::DrawFrame(bool bRGB) { // select the last frame int numKFs = 1; vector<KeyFrame*> vpKFs = mpMap->GetAllKeyFrames(); std::sort(vpKFs.begin(), vpKFs.end(), KeyFrame::lId); vector<KeyFrame*> vpKFtex; for(auto it = vpKFs.rbegin(); it != vpKFs.rend(); ++it) { if ((int)vpKFtex.size() >= numKFs) break; KeyFrame *kf = *it; kf->SetNotEraseDrawer(); if (kf->isBad()) { kf->SetEraseDrawer(); continue; } vpKFtex.push_back(kf); } if ((int)vpKFtex.size() >= numKFs) { glColor3f(1.0,1.0,1.0); if (vpKFtex[0]->mImage.empty()){ std::cerr << "ERROR: empty frame image" << endl; return; } cv::Size imSize = vpKFtex[0]->mImage.size(); if(bRGB) { pangolin::GlTexture imageTexture(imSize.width, imSize.height, GL_RGB, false, 0, GL_BGR, GL_UNSIGNED_BYTE); imageTexture.Upload(vpKFtex[0]->mImage.data, GL_BGR, GL_UNSIGNED_BYTE); imageTexture.RenderToViewportFlipY(); } else { pangolin::GlTexture imageTexture(imSize.width, imSize.height, GL_RGB, false, 0, GL_RGB, GL_UNSIGNED_BYTE); imageTexture.Upload(vpKFtex[0]->mImage.data, GL_RGB, GL_UNSIGNED_BYTE); imageTexture.RenderToViewportFlipY(); } } } void ModelDrawer::UpdateModel() { if(mbModelUpdateRequested && ! mbModelUpdateDone) return; if(mbModelUpdateRequested && mbModelUpdateDone){ mModel = mUpdatedModel; mbModelUpdateRequested = false; return; } mbModelUpdateDone = false; mbModelUpdateRequested = true; // implicitly signals SurfaceInferer thread which is polling } void ModelDrawer::SetUpdatedModel(const vector<dlovi::Matrix> & modelPoints, const list<dlovi::Matrix> & modelTris) { mUpdatedModel.first = modelPoints; mUpdatedModel.second = modelTris; mbModelUpdateRequested = true; } vector<dlovi::Matrix> & ModelDrawer::GetPoints() { return mModel.first; } list<dlovi::Matrix> & ModelDrawer::GetTris() { return mModel.second; } void ModelDrawer::MarkUpdateDone() { mbModelUpdateDone = true; } bool ModelDrawer::UpdateRequested() { return mbModelUpdateRequested; } bool ModelDrawer::UpdateDone() { return mbModelUpdateDone; } void ModelDrawer::SetModeler(Modeler* pModeler) { mpModeler = pModeler; } } //namespace ORB_SLAM
[STATEMENT] lemma Trg_Dom_Cod: shows "Arr t \<Longrightarrow> Trg (Dom t) = Trg t \<and> Trg (Cod t) = Trg t" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Arr t \<Longrightarrow> Trg (Dom t) = Trg t \<and> Trg (Cod t) = Trg t [PROOF STEP] using trg_dom trg_cod [PROOF STATE] proof (prove) using this: trg (local.dom ?\<mu>) = trg ?\<mu> trg (cod ?\<mu>) = trg ?\<mu> goal (1 subgoal): 1. Arr t \<Longrightarrow> Trg (Dom t) = Trg t \<and> Trg (Cod t) = Trg t [PROOF STEP] by (induct t) auto
module ResourceProtocols %default total data DoorState = Open | Closed data Door : DoorState -> Type where MkDoor : (doorId : Int) -> Door st openDoor : (1 d : Door Closed) -> Door Open closeDoor : (1 d : Door Open) -> Door Closed newDoor : (1 p : (1 d : Door Closed) -> IO ()) -> IO () deleteDoor : (1 d : Door Closed) -> IO () doorProg : IO () doorProg = newDoor $ \d => let d' = openDoor d d'' = closeDoor d' in deleteDoor d''
module System.IO.Handle.Windows %default total -- --------------------------------------------------------------------------- %foreign "scheme,chez:(foreign-procedure #f \"GetStdHandle\" (unsigned-32) void*)" "javascript:lambda:(x) => 0" prim__win_GetStdHandle : Bits32 -> PrimIO AnyPtr -- --------------------------------------------------------------------------- public export data Handle = MkHandle AnyPtr -- --------------------------------------------------------------------------- export getStdin : HasIO io => io Handle getStdin = pure $ MkHandle !(primIO $ prim__win_GetStdHandle $ cast (-10)) export getStdout : HasIO io => io Handle getStdout = pure $ MkHandle !(primIO $ prim__win_GetStdHandle $ cast (-11)) export getStderr : HasIO io => io Handle getStderr = pure $ MkHandle !(primIO $ prim__win_GetStdHandle $ cast (-13)) -- --------------------------------------------------------------------------- -- vim: tw=80 sw=2 expandtab :
using BlockMaps using Test @testset "BlockMaps.jl" begin # Write your own tests here. end
theory Boolean_Algebra_Extras imports Lattice begin record 'a huntington_algebra = "'a partial_object" + hor :: "'a \<Rightarrow> 'a \<Rightarrow> 'a" (infixl "+\<index>" 70) hnot :: "'a \<Rightarrow> 'a" ("!\<index>") no_notation Groups.plus_class.plus (infixl "+" 65) and Groups.one_class.one ("1") and Groups.zero_class.zero ("0") locale huntington_algebra = fixes A (structure) assumes hor_closed: "\<lbrakk>x \<in> carrier A; y \<in> carrier A\<rbrakk> \<Longrightarrow> x + y \<in> carrier A" and hnot_closed: "x \<in> carrier A \<Longrightarrow> !x \<in> carrier A" and huntington: "\<lbrakk>x \<in> carrier A; y \<in> carrier A\<rbrakk> \<Longrightarrow> x = !(!x + y) + !(!x + !y)" and comm: "\<lbrakk>x \<in> carrier A; y \<in> carrier A\<rbrakk> \<Longrightarrow> x + y = y + x" and assoc: "\<lbrakk>x \<in> carrier A; y \<in> carrier A; z \<in> carrier A\<rbrakk> \<Longrightarrow> (x + y) + z = x + (y + z)" and carrier_non_empty: "carrier A \<noteq> {}" begin (* Following Allan L. Mann's 'A complete proof of the Robbins conjecture' *) lemma or_left_cong: "x = z \<Longrightarrow> x + y = z + y" by auto lemma or_right_cong: "y = z \<Longrightarrow> x + y = x + z" by auto lemma not_cong: "x = y \<Longrightarrow> !x = !y" by auto lemma H1: assumes xc: "x \<in> carrier A" shows "x + !x = !x + !(!x)" proof - have nxc: "!x \<in> carrier A" and nnxc: "!(!x) \<in> carrier A" by (metis assms hnot_closed)+ have "x + !x = !(!x + !(!x)) + !(!x + !(!(!x))) + (!(!(!x) + !(!x)) + !(!(!x) + !(!(!x))))" by (subst huntington[OF nxc nnxc], subst huntington[OF xc nnxc], simp) also have "... = !(!(!x) + !x) + !(!(!x) + !(!x)) + (!(!(!(!x)) + !x) + !(!(!(!x)) + !(!x)))" by (smt assoc comm hnot_closed hor_closed nxc) also have "... = !x + !(!x)" by (rule sym, subst huntington[OF nnxc nxc], subst huntington[OF nxc nxc], simp) finally show ?thesis . qed lemma double_neg: assumes xc: "x \<in> carrier A" shows "!(!x) = x" proof - have nxc: "!x \<in> carrier A" and nnxc: "!(!x) \<in> carrier A" by (metis assms hnot_closed)+ have "!(!x) = !(!(!(!x)) + !x) + !(!(!(!x)) + !(!x))" by (subst huntington[OF nnxc nxc], simp) also have "... = !(!(!(!x)) + !x) + !(!x + x)" by (rule or_right_cong, rule not_cong, metis H1 assms comm hnot_closed) also have "... = !(!x + !x) + !(!x + x)" by (smt H1 comm hnot_closed hor_closed huntington nxc) also have "... = x" by (metis assms comm hnot_closed hor_closed huntington) finally show ?thesis . qed lemma H2: "\<lbrakk>x \<in> carrier A; y \<in> carrier A\<rbrakk> \<Longrightarrow> !x = !y \<Longrightarrow> x = y" by (metis double_neg) definition hand :: "'a \<Rightarrow> 'a \<Rightarrow> 'a" (infixl "\<cdot>" 80) where "x \<cdot> y = !(!x + !y)" lemma hand_closed: "\<lbrakk>x \<in> carrier A; y \<in> carrier A\<rbrakk> \<Longrightarrow> x \<cdot> y \<in> carrier A" by (metis hand_def hnot_closed hor_closed) lemma de_morgan1: "\<lbrakk>x \<in> carrier A; y \<in> carrier A\<rbrakk> \<Longrightarrow> !(x + y) = !x \<cdot> !y" by (metis double_neg hand_def) lemma de_morgan2: "\<lbrakk>x \<in> carrier A; y \<in> carrier A\<rbrakk> \<Longrightarrow> !(x \<cdot> y) = !x + !y" by (metis double_neg hand_def hnot_closed hor_closed) lemma hor_as_hand: "\<lbrakk>x \<in> carrier A; y \<in> carrier A\<rbrakk> \<Longrightarrow> x + y = !(!x \<cdot> !y)" by (metis (lifting) de_morgan2 double_neg hnot_closed) lemma hunt_var: "\<lbrakk>x \<in> carrier A; y \<in> carrier A\<rbrakk> \<Longrightarrow> x = x\<cdot>y + x\<cdot>!y" by (metis (lifting) hand_def hnot_closed huntington) lemma hand_comm: "\<lbrakk>x \<in> carrier A; y \<in> carrier A\<rbrakk> \<Longrightarrow> x\<cdot>y = y\<cdot>x" by (metis (lifting) comm hand_def hnot_closed) lemma hand_assoc: "\<lbrakk>x \<in> carrier A; y \<in> carrier A; z \<in> carrier A\<rbrakk> \<Longrightarrow> (x\<cdot>y)\<cdot>z = x\<cdot>(y\<cdot>z)" by (smt assoc de_morgan2 hand_def hnot_closed) lemma and_right_cong: "y = z \<Longrightarrow> x\<cdot>y = x\<cdot>z" by auto lemma and_left_cong: "x = y \<Longrightarrow> x\<cdot>z = y\<cdot>z" by auto definition one_f :: "'a \<Rightarrow> 'a" where "one_f x \<equiv> x + !x" lemma one_f_const: assumes xc: "x \<in> carrier A" and yc: "y \<in> carrier A" shows "one_f x = one_f y" proof - have nxc: "!x \<in> carrier A" and nyc: "!y \<in> carrier A" by (metis hnot_closed xc yc)+ have "one_f x = x + !x" by (simp add: one_f_def) also have "... = ! (! x + ! y) + ! (! x + ! (! y)) + (! (! (! x) + ! y) + ! (! (! x) + ! (! y)))" by (subst huntington[OF nxc nyc], subst huntington[OF xc nyc], simp) also have "... = ! (! y + ! x) + ! (! y + ! (! x)) + (! (! (! y) + ! x) + ! (! (! y) + ! (! x)))" by (smt assoc comm hnot_closed hor_closed nxc nyc) also have "... = y + !y" by (rule sym, subst huntington[OF nyc nxc], subst huntington[OF yc nxc], simp) also have "... = one_f y" by (simp add: one_f_def) finally show ?thesis . qed definition hone :: "'a" ("1") where "1 \<equiv> THE x. x \<in> (one_f ` carrier A)" lemma one_prop: "x \<in> carrier A \<Longrightarrow> x + !x = 1" by (simp add: hone_def, rule the1I2, auto, (metis one_f_def one_f_const)+) lemma one_closed: "1 \<in> carrier A" apply (simp add: hone_def) apply (rule the1I2) apply auto apply (metis carrier_non_empty empty_is_image ex_in_conv) apply (metis one_f_const) by (metis hnot_closed hor_closed one_f_def) definition hzero :: "'a" ("0") where "0 = !1" lemma zero_closed: "0 \<in> carrier A" by (metis hnot_closed hzero_def one_closed) lemma or_zero: assumes xc: "x \<in> carrier A" shows "x + 0 = x" proof - have "!1 = 0" by (metis hzero_def) also have "... = ! (! 0 + 0) + ! (! 0 + ! 0)" by (subst huntington[OF zero_closed zero_closed], simp) also have "... = 0 + !(!0 + !0)" by (metis (lifting) double_neg hzero_def one_closed one_prop) also have "... = !1 + !(1 + 1)" by (metis hzero_def double_neg one_closed) finally have eq1: "!1 = !1 + !(1 + 1)" . hence eq2: "1 = 1 + !(1 + 1)" by (smt assoc double_neg hnot_closed hor_closed hzero_def one_prop zero_closed) hence eq3: "1 = 1 + 1" by (metis assoc hnot_closed hor_closed one_closed one_prop) from eq1 and eq3 have eq4: "0 = 0 + 0" by (metis hzero_def) have "x + 0 = ! (! x + x) + ! (! x + ! x) + 0" by (subst huntington[OF xc xc], simp) also have "... = !(!x + !x) + 0 + 0" by (smt assms comm hnot_closed hor_closed hzero_def one_prop) also have "... = !(!x + !x) + 0" by (metis assms assoc eq4 hand_closed hand_def zero_closed) also have "... = !(!x + !x) + !(!x + x)" by (metis assms comm hnot_closed hzero_def one_prop) also have "... = x" by (metis assms double_neg hand_def hunt_var) finally show ?thesis . qed lemma and_one: "x \<in> carrier A \<Longrightarrow> x\<cdot>1 = x" by (metis double_neg hand_def hnot_closed hzero_def or_zero) lemma and_zero: "x \<in> carrier A \<Longrightarrow> x\<cdot>0 = 0" by (smt H1 assoc de_morgan2 hand_def hnot_closed hor_closed hunt_var hzero_def one_prop) lemma or_one: "x \<in> carrier A \<Longrightarrow> x + 1 = 1" by (smt and_zero hand_def hnot_closed hor_as_hand hzero_def one_closed one_prop) lemma or_idem: "x \<in> carrier A \<Longrightarrow> x + x = x" by (smt double_neg hand_closed hnot_closed hor_as_hand huntington hzero_def one_prop or_zero) lemma and_idem: "x \<in> carrier A \<Longrightarrow> x\<cdot>x = x" by (metis double_neg hand_def hnot_closed or_idem) definition HBA :: "'a ord" where "HBA = \<lparr>carrier = carrier A, le = (\<lambda>x y. x + y = y)\<rparr>" lemma HBA_ord: "order HBA" by (default, simp_all add: HBA_def, (metis or_idem assoc comm)+) lemma HBA_carrier [simp]: "carrier HBA = carrier A" by (simp add: HBA_def) lemma HBA_lub: "\<lbrakk>x \<in> carrier A; y \<in> carrier A\<rbrakk> \<Longrightarrow> order.is_lub HBA (x + y) {x, y}" apply (simp add: order.is_lub_simp[OF HBA_ord], safe) apply (simp_all add: HBA_def) apply (metis hor_closed) apply (metis assoc or_idem) apply (metis assoc comm or_idem) by (metis assoc) lemma glb1: "\<lbrakk>x \<in> carrier A; y \<in> carrier A\<rbrakk> \<Longrightarrow> x \<cdot> y + x = x" by (smt and_idem assoc de_morgan2 hand_closed hand_def hnot_closed huntington) lemma glb2: "\<lbrakk>x \<in> carrier A; y \<in> carrier A\<rbrakk> \<Longrightarrow> x \<cdot> y + y = y" by (smt and_idem assoc de_morgan2 hand_closed hand_comm hand_def hnot_closed huntington) lemma absorb1: "\<lbrakk>x \<in> carrier A; y \<in> carrier A\<rbrakk> \<Longrightarrow> x\<cdot>(x + y) = x" by (smt comm double_neg glb1 hand_closed hand_def hnot_closed) lemma HBA_glb: "\<lbrakk>x \<in> carrier A; y \<in> carrier A\<rbrakk> \<Longrightarrow> order.is_glb HBA (x \<cdot> y) {x, y}" apply (simp add: order.is_glb_simp[OF HBA_ord], safe) apply (simp_all add: HBA_def) apply (metis hand_closed) apply (metis glb1) apply (metis glb2) by (smt H2 de_morgan1 de_morgan2 glb1 hand_assoc hand_closed hand_comm hnot_closed) lemma HBA_js: "join_semilattice HBA" apply default prefer 4 apply (rule_tac x = "x + y" in bexI) apply simp apply (metis HBA_lub) apply (simp_all add: HBA_def) apply (metis hor_closed) apply (metis or_idem) apply (metis assoc) by (metis comm) lemma HBA_ms: "meet_semilattice HBA" apply default prefer 4 apply (rule_tac x = "x \<cdot> y" in bexI) apply simp apply (metis HBA_glb) apply (simp_all add: HBA_def) apply (metis hand_closed) apply (metis or_idem) apply (metis assoc) by (metis comm) lemma HBA_lattice: "lattice HBA" by (simp add: lattice_def, metis HBA_ms HBA_js) lemma HBA_join [simp]: "\<lbrakk>x \<in> carrier A; y \<in> carrier A\<rbrakk> \<Longrightarrow> x \<squnion>\<^bsub>HBA\<^esub> y = x + y" apply (simp add: order.join_def[OF HBA_ord] order.lub_def[OF HBA_ord]) apply (rule the1I2) apply auto apply (metis HBA_lub) apply (metis HBA_ord order.is_lub_unique) by (metis HBA_lub HBA_ord order.is_lub_unique) lemma HBA_meet [simp]: "\<lbrakk>x \<in> carrier A; y \<in> carrier A\<rbrakk> \<Longrightarrow> x \<sqinter>\<^bsub>HBA\<^esub> y = x\<cdot>y" apply (simp add: order.meet_def[OF HBA_ord] order.glb_def[OF HBA_ord]) apply (rule the1I2) apply auto apply (metis HBA_glb) apply (metis HBA_ord order.is_glb_unique) by (metis (lifting) HBA_glb HBA_ord order.is_glb_unique) lemma HBA_bounded: "bounded_lattice HBA" apply (simp add: bounded_lattice_def bounded_lattice_axioms_def) apply safe apply (rule HBA_lattice) apply (rule_tac x = 0 in bexI) apply (metis comm or_zero zero_closed) apply (metis zero_closed) apply (rule_tac x = 1 in bexI) apply (metis and_one hand_comm one_closed) by (metis one_closed) lemma HBA_top [simp]: "bounded_lattice.top HBA = 1" apply (simp add: bounded_lattice.top_def[OF HBA_bounded]) apply (rule the1I2) apply (simp_all add: HBA_def) apply (metis and_one comm glb2 one_closed) by (metis double_neg hnot_closed one_prop) lemma HBA_bot [simp]: "bounded_lattice.bot HBA = 0" apply (simp add: bounded_lattice.bot_def[OF HBA_bounded]) apply (rule the1I2) apply (simp_all add: HBA_def) apply (metis (lifting) comm or_zero zero_closed) by (metis or_zero zero_closed) lemma HBA_complemented: "complemented_lattice HBA" apply (simp add: complemented_lattice_def complemented_lattice_axioms_def) apply safe apply (metis HBA_bounded) apply (rule_tac x = "!x" in exI) apply (subgoal_tac "!x \<in> carrier A") apply simp apply (metis hand_def hzero_def one_prop) by (metis hnot_closed) lemma distl: assumes xc: "x \<in> carrier A" and yc: "y \<in> carrier A" and zc: "z \<in> carrier A" shows "x\<cdot>(y + z) = x\<cdot>y + x\<cdot>z" proof - have c1: "x\<cdot>y \<in> carrier A" by (metis hand_closed xc yc) have c2: "x\<cdot>(y + z)\<cdot>!y \<in> carrier A" by (metis hand_closed hnot_closed hor_closed xc yc zc) have "x\<cdot>(y + z) = x\<cdot>(y + z)\<cdot>y + x\<cdot>(y + z)\<cdot>!y" by (smt comm hand_closed hnot_closed hor_closed hunt_var xc yc zc) also have "... = x\<cdot>y + x\<cdot>(y + z)\<cdot>!y" apply (rule or_left_cong) by (smt double_neg glb1 hand_assoc hand_closed hnot_closed hor_as_hand xc yc zc) also have "... = (x\<cdot>y\<cdot>z + x\<cdot>y\<cdot>!z) + (x\<cdot>(y + z)\<cdot>!y\<cdot>z + x\<cdot>(y + z)\<cdot>!y\<cdot>!z)" by (subst hunt_var[OF c1 zc], subst hunt_var[OF c2 zc], simp) also have "... = (x\<cdot>y\<cdot>z + x\<cdot>y\<cdot>!z) + (x\<cdot>!y\<cdot>z + x\<cdot>(y + z)\<cdot>!y\<cdot>!z)" apply (rule or_right_cong, rule or_left_cong) by (smt absorb1 comm hand_assoc hand_closed hand_comm hnot_closed hor_closed xc yc zc) also have "... = (x\<cdot>y\<cdot>z + x\<cdot>y\<cdot>!z) + (x\<cdot>!y\<cdot>z + x\<cdot>(y + z)\<cdot>!(y+z))" by (smt de_morgan1 hand_assoc hand_closed hnot_closed hor_closed xc yc zc) also have "... = (x\<cdot>y\<cdot>z + x\<cdot>y\<cdot>!z) + (x\<cdot>!y\<cdot>z + x\<cdot>0)" by (smt hand_assoc hand_def hnot_closed hor_closed hzero_def one_prop xc yc zc) also have "... = (x\<cdot>y\<cdot>z + x\<cdot>y\<cdot>!z) + (x\<cdot>!y\<cdot>z + 0)" by (metis and_zero xc) also have "... = x\<cdot>y\<cdot>z + x\<cdot>y\<cdot>!z + x\<cdot>!y\<cdot>z" by (metis hand_closed hnot_closed or_zero xc yc zc) also have "... = x\<cdot>y\<cdot>z + x\<cdot>y\<cdot>!z + x\<cdot>y\<cdot>z + x\<cdot>!y\<cdot>z" by (metis (no_types) c1 comm glb1 hand_closed hunt_var zc) also have "... = x\<cdot>y + x\<cdot>z" by (smt assoc hand_assoc hand_closed hand_comm hnot_closed hunt_var xc yc zc) finally show ?thesis . qed lemma distr: assumes xc: "x \<in> carrier A" and yc: "y \<in> carrier A" and zc: "z \<in> carrier A" shows "(x + y)\<cdot>z = x\<cdot>z + y\<cdot>z" by (metis distl hand_comm hor_closed xc yc zc) lemma HBA_distributive: "distributive_lattice HBA" apply (simp add: distributive_lattice_def distributive_lattice_axioms_def) apply safe apply (metis HBA_lattice) apply (subgoal_tac "y + z \<in> carrier A" "x\<cdot>y \<in> carrier A" "x\<cdot>z \<in> carrier A") apply simp apply (metis distl) apply (metis hand_closed)+ apply (metis hor_closed) apply (subgoal_tac "y\<cdot>z \<in> carrier A" "x + y \<in> carrier A" "x + z \<in> carrier A") apply simp apply (smt and_idem assoc comm distl distr glb1 glb2 hand_closed hand_def hor_as_hand) apply (metis hor_closed)+ by (metis hand_closed) lemma HBA_ba: "boolean_algebra HBA" by (simp add: boolean_algebra_def, metis HBA_complemented HBA_distributive) end lemma huntington_induces_ba: assumes hunt: "huntington_algebra \<lparr>carrier = A, hor = p, hnot = n\<rparr>" shows "boolean_algebra \<lparr>carrier = A, le = (\<lambda>x y. p x y = y)\<rparr>" proof - let ?H = "\<lparr>carrier = A, hor = p, hnot = n\<rparr>" have "boolean_algebra (huntington_algebra.HBA ?H)" by (metis assms huntington_algebra.HBA_ba) moreover have "\<lparr>carrier = A, le = (\<lambda>x y. p x y = y)\<rparr> = huntington_algebra.HBA ?H" by (simp add: huntington_algebra.HBA_def[OF hunt]) ultimately show ?thesis by auto qed notation Groups.plus_class.plus (infixl "+" 65) and Groups.one_class.one ("1") and Groups.zero_class.zero ("0") no_notation huntington_algebra.hor (infixl "+\<index>" 70) and huntington_algebra.hnot ("!\<index>") datatype 'a bexpr = BLeaf 'a | BOr "'a bexpr" "'a bexpr" (infixl ":+:" 70) | BNot "'a bexpr" | BAnd "'a bexpr" "'a bexpr" (infixl ":\<cdot>:" 70) | BOne | BZero primrec bexpr_map :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a bexpr \<Rightarrow> 'b bexpr" where "bexpr_map f (BLeaf x) = BLeaf (f x)" | "bexpr_map f (BOr x y) = BOr (bexpr_map f x) (bexpr_map f y)" | "bexpr_map f (BNot x) = BNot (bexpr_map f x)" | "bexpr_map f (BAnd x y) = BAnd (bexpr_map f x) (bexpr_map f y)" | "bexpr_map f BOne = BOne" | "bexpr_map f BZero = BZero" primrec bexpr_leaves :: "'a bexpr \<Rightarrow> 'a set" where "bexpr_leaves (BLeaf x) = {x}" | "bexpr_leaves (BOr x y) = bexpr_leaves x \<union> bexpr_leaves y" | "bexpr_leaves (BNot x) = bexpr_leaves x" | "bexpr_leaves (BAnd x y) = bexpr_leaves x \<union> bexpr_leaves y" | "bexpr_leaves BOne = {}" | "bexpr_leaves BZero = {}" inductive hunt_cong :: "'a bexpr \<Rightarrow> 'a bexpr \<Rightarrow> bool" where refl [intro]: "hunt_cong x x" | sym [sym]: "hunt_cong x y \<Longrightarrow> hunt_cong y x" | trans [trans]: "\<lbrakk>hunt_cong x y; hunt_cong y z\<rbrakk> \<Longrightarrow> hunt_cong x z" | or_compat: "hunt_cong x1 x2 \<Longrightarrow> hunt_cong y1 y2 \<Longrightarrow> hunt_cong (BOr x1 y1) (BOr x2 y2)" | not_compat: "hunt_cong x y \<Longrightarrow> hunt_cong (BNot x) (BNot y)" | and_compat: "hunt_cong x1 x2 \<Longrightarrow> hunt_cong y1 y2 \<Longrightarrow> hunt_cong (BAnd x1 y1) (BAnd x2 y2)" | huntington: "hunt_cong (BNot (BNot x :+: y) :+: BNot (BNot x :+: BNot y)) x" | comm: "hunt_cong (x :+: y) (y :+: x)" | assoc: "hunt_cong ((x :+: y) :+: z) (x :+: (y :+: z))" | one: "hunt_cong (x :+: BNot x) BOne" | zero: "hunt_cong (BNot BOne) BZero" | meet: "hunt_cong (x :\<cdot>: y) (BNot (BNot x :+: BNot y))" quotient_type 'a bterm = "'a bexpr" / "hunt_cong" apply (simp add: equivp_def, auto) apply (subgoal_tac "\<forall>z. hunt_cong x z = hunt_cong y z") apply auto by (metis hunt_cong.sym hunt_cong.trans)+ lift_definition bt_or :: "'a bterm \<Rightarrow> 'a bterm \<Rightarrow> 'a bterm" is BOr by (rule hunt_cong.or_compat, assumption+) lift_definition bt_not :: "'a bterm \<Rightarrow> 'a bterm" is BNot by (rule hunt_cong.not_compat, assumption) lift_definition bt_and :: "'a bterm \<Rightarrow> 'a bterm \<Rightarrow> 'a bterm" is BAnd by (rule hunt_cong.and_compat, assumption+) lift_definition bt_one :: "'a bterm" is BOne by (rule hunt_cong.refl) lift_definition bt_zero :: "'a bterm" is BZero by (rule hunt_cong.refl) definition free_ba where "free_ba \<equiv> \<lparr>carrier = UNIV, le = (\<lambda>x y. bt_or x y = y)\<rparr>" lemma free_ba_hunt: "huntington_algebra \<lparr>carrier = UNIV, hor = bt_or, hnot = bt_not\<rparr>" proof (default, simp_all) fix x y z :: "'b bterm" show "x = bt_or (bt_not (bt_or (bt_not x) y)) (bt_not (bt_or (bt_not x) (bt_not y)))" by (rule HOL.sym, transfer, rule hunt_cong.huntington) show "bt_or x y = bt_or y x" by (transfer, rule hunt_cong.comm) show "bt_or (bt_or x y) z = bt_or x (bt_or y z)" by (transfer, rule hunt_cong.assoc) qed abbreviation BTH where "BTH \<equiv> \<lparr>carrier = UNIV, hor = bt_or, hnot = bt_not\<rparr>" lemma bt_hone [simp]: "huntington_algebra.hone BTH = bt_one" proof - have "bt_or bt_one (bt_not bt_one) = bt_one" by (transfer, metis one) thus ?thesis by (simp add: huntington_algebra.one_prop[symmetric, OF free_ba_hunt]) qed lemma bt_hzero [simp]: "huntington_algebra.hzero BTH = bt_zero" proof - have "bt_not bt_one = bt_zero" by (transfer, metis zero) thus ?thesis by (simp add: huntington_algebra.hzero_def[OF free_ba_hunt]) qed interpretation hba: huntington_algebra "BTH" where "hor BTH x y = bt_or x y" and "hnot BTH x = bt_not x" and "huntington_algebra.hand BTH x y = bt_and x y" and "huntington_algebra.hone BTH = bt_one" and "huntington_algebra.hzero BTH = bt_zero" and "x \<in> carrier BTH = True" apply (simp_all add: free_ba_hunt) apply (simp add: huntington_algebra.hand_def[OF free_ba_hunt]) apply transfer apply (metis hunt_cong.sym meet) done theorem free_ba: "boolean_algebra free_ba" proof (simp add: free_ba_def) from free_ba_hunt show "boolean_algebra \<lparr>carrier = UNIV, le = \<lambda>x y. bt_or x y = y\<rparr>" by (rule huntington_induces_ba) qed lemma free_ba_ord: "order free_ba" apply (insert free_ba) apply (simp add: boolean_algebra_def distributive_lattice_def) apply (simp add: lattice_def join_semilattice_def) by auto lemma [simp]: "x \<squnion>\<^bsub>free_ba\<^esub> y = bt_or x y" apply (simp add: order.join_def[OF free_ba_ord] order.lub_simp[OF free_ba_ord]) apply (simp add: free_ba_def) apply (rule the1I2) apply auto apply (smt hba.assoc hba.comm hba.or_idem) apply (metis hba.comm) by (metis (full_types) hba.assoc hba.comm hba.or_idem) lemma [simp]: "x \<sqinter>\<^bsub>free_ba\<^esub> y = bt_and x y" apply (simp add: order.meet_def[OF free_ba_ord] order.glb_simp[OF free_ba_ord]) apply (simp add: free_ba_def) apply (rule the1I2) apply auto apply (rule_tac x = "bt_and x y" in exI) apply (metis hba.absorb1 hba.distl hba.glb2 hba.hand_comm) apply (metis hba.comm) by (smt hba.absorb1 hba.distr hba.glb2 hba.hand_comm) lemma free_ba_bl: "bounded_lattice free_ba" apply (insert free_ba) apply (simp add: boolean_algebra_def complemented_lattice_def) apply auto done lemma [simp]: "bounded_lattice.top free_ba = bt_one" apply (simp add: bounded_lattice.top_def[OF free_ba_bl]) apply (simp add: free_ba_def) apply (rule the1I2) apply auto apply (metis hba.or_one) apply (metis hba.comm) by (metis hba.comm hba.or_one) lemma [simp]: "bounded_lattice.bot free_ba = bt_zero" apply (simp add: bounded_lattice.bot_def[OF free_ba_bl]) apply (simp add: free_ba_def) apply (rule the1I2) apply auto apply (metis hba.comm hba.or_zero) apply (metis hba.or_zero) by (metis hba.or_zero) interpretation ba: join_semilattice free_ba where "x \<squnion>\<^bsub>free_ba\<^esub> y = bt_or x y" and "x \<sqinter>\<^bsub>free_ba\<^esub> y = bt_and x y" and "carrier free_ba = UNIV" and "bounded_lattice.top free_ba = bt_one" and "bounded_lattice.bot free_ba = bt_zero" by (insert free_ba, simp_all add: boolean_algebra_def distributive_lattice_def lattice_def, auto) interpretation ba: meet_semilattice free_ba where "x \<squnion>\<^bsub>free_ba\<^esub> y = bt_or x y" and "x \<sqinter>\<^bsub>free_ba\<^esub> y = bt_and x y" and "carrier free_ba = UNIV" and "bounded_lattice.top free_ba = bt_one" and "bounded_lattice.bot free_ba = bt_zero" by (insert free_ba, simp_all add: boolean_algebra_def distributive_lattice_def lattice_def, auto) interpretation ba: boolean_algebra free_ba where "x \<squnion>\<^bsub>free_ba\<^esub> y = bt_or x y" and "x \<sqinter>\<^bsub>free_ba\<^esub> y = bt_and x y" and "carrier free_ba = UNIV" and "bounded_lattice.top free_ba = bt_one" and "bounded_lattice.bot free_ba = bt_zero" by (insert free_ba, simp_all) end