Datasets:
AI4M
/

text
stringlengths
0
3.34M
# Programming Exercise 4: Neural Networks Learning ## Introduction In this exercise, you will implement the backpropagation algorithm for neural networks and apply it to the task of hand-written digit recognition. Before starting on the programming exercise, we strongly recommend watching the video lectures and completing the review questions for the associated topics. All the information you need for solving this assignment is in this notebook, and all the code you will be implementing will take place within this notebook. The assignment can be promptly submitted to the coursera grader directly from this notebook (code and instructions are included below). Before we begin with the exercises, we need to import all libraries required for this programming exercise. Throughout the course, we will be using [`numpy`](http://www.numpy.org/) for all arrays and matrix operations, [`matplotlib`](https://matplotlib.org/) for plotting, and [`scipy`](https://docs.scipy.org/doc/scipy/reference/) for scientific and numerical computation functions and tools. You can find instructions on how to install required libraries in the README file in the [github repository](https://github.com/dibgerge/ml-coursera-python-assignments). ```python # used for manipulating directory paths import os # Scientific and vector computation for python import numpy as np # Plotting library from matplotlib import pyplot # Optimization module in scipy from scipy import optimize # will be used to load MATLAB mat datafile format from scipy.io import loadmat # library written for this exercise providing additional functions for assignment submission, and others import utils # define the submission/grader object for this exercise grader = utils.Grader() # tells matplotlib to embed plots within the notebook %matplotlib inline ``` ## Submission and Grading After completing each part of the assignment, be sure to submit your solutions to the grader. The following is a breakdown of how each part of this exercise is scored. | Section | Part | Submission function | Points | :- |:- | :- | :-: | 1 | [Feedforward and Cost Function](#section1) | [`nnCostFunction`](#nnCostFunction) | 30 | 2 | [Regularized Cost Function](#section2) | [`nnCostFunction`](#nnCostFunction) | 15 | 3 | [Sigmoid Gradient](#section3) | [`sigmoidGradient`](#sigmoidGradient) | 5 | 4 | [Neural Net Gradient Function (Backpropagation)](#section4) | [`nnCostFunction`](#nnCostFunction) | 40 | 5 | [Regularized Gradient](#section5) | [`nnCostFunction`](#nnCostFunction) |10 | | Total Points | | 100 You are allowed to submit your solutions multiple times, and we will take only the highest score into consideration. <div class="alert alert-block alert-warning"> At the end of each section in this notebook, we have a cell which contains code for submitting the solutions thus far to the grader. Execute the cell to see your score up to the current section. For all your work to be submitted properly, you must execute those cells at least once. </div> ## Neural Networks In the previous exercise, you implemented feedforward propagation for neural networks and used it to predict handwritten digits with the weights we provided. In this exercise, you will implement the backpropagation algorithm to learn the parameters for the neural network. We start the exercise by first loading the dataset. ```python # training data stored in arrays X, y data = loadmat(os.path.join('Data', 'ex4data1.mat')) X, y = data['X'], data['y'].ravel() # set the zero digit to 0, rather than its mapped 10 in this dataset # This is an artifact due to the fact that this dataset was used in # MATLAB where there is no index 0 y[y == 10] = 0 # Number of training examples m = y.size ``` ### 1.1 Visualizing the data You will begin by visualizing a subset of the training set, using the function `displayData`, which is the same function we used in Exercise 3. It is provided in the `utils.py` file for this assignment as well. The dataset is also the same one you used in the previous exercise. There are 5000 training examples in `ex4data1.mat`, where each training example is a 20 pixel by 20 pixel grayscale image of the digit. Each pixel is represented by a floating point number indicating the grayscale intensity at that location. The 20 by 20 grid of pixels is “unrolled” into a 400-dimensional vector. Each of these training examples becomes a single row in our data matrix $X$. This gives us a 5000 by 400 matrix $X$ where every row is a training example for a handwritten digit image. $$ X = \begin{bmatrix} - \left(x^{(1)} \right)^T - \\ - \left(x^{(2)} \right)^T - \\ \vdots \\ - \left(x^{(m)} \right)^T - \\ \end{bmatrix} $$ The second part of the training set is a 5000-dimensional vector `y` that contains labels for the training set. The following cell randomly selects 100 images from the dataset and plots them. ```python # Randomly select 100 data points to display rand_indices = np.random.choice(m, 100, replace=False) sel = X[rand_indices, :] utils.displayData(sel) ``` ### 1.2 Model representation Our neural network is shown in the following figure. It has 3 layers - an input layer, a hidden layer and an output layer. Recall that our inputs are pixel values of digit images. Since the images are of size $20 \times 20$, this gives us 400 input layer units (not counting the extra bias unit which always outputs +1). The training data was loaded into the variables `X` and `y` above. You have been provided with a set of network parameters ($\Theta^{(1)}, \Theta^{(2)}$) already trained by us. These are stored in `ex4weights.mat` and will be loaded in the next cell of this notebook into `Theta1` and `Theta2`. The parameters have dimensions that are sized for a neural network with 25 units in the second layer and 10 output units (corresponding to the 10 digit classes). ```python # Setup the parameters you will use for this exercise input_layer_size = 400 # 20x20 Input Images of Digits hidden_layer_size = 25 # 25 hidden units num_labels = 10 # 10 labels, from 0 to 9 # Load the weights into variables Theta1 and Theta2 weights = loadmat(os.path.join('Data', 'ex4weights.mat')) # Theta1 has size 25 x 401 # Theta2 has size 10 x 26 Theta1, Theta2 = weights['Theta1'], weights['Theta2'] # swap first and last columns of Theta2, due to legacy from MATLAB indexing, # since the weight file ex3weights.mat was saved based on MATLAB indexing Theta2 = np.roll(Theta2, 1, axis=0) # Unroll parameters nn_params = np.concatenate([Theta1.ravel(), Theta2.ravel()]) ``` <a id="section1"></a> ### 1.3 Feedforward and cost function Now you will implement the cost function and gradient for the neural network. First, complete the code for the function `nnCostFunction` in the next cell to return the cost. Recall that the cost function for the neural network (without regularization) is: $$ J(\theta) = \frac{1}{m} \sum_{i=1}^{m}\sum_{k=1}^{K} \left[ - y_k^{(i)} \log \left( \left( h_\theta \left( x^{(i)} \right) \right)_k \right) - \left( 1 - y_k^{(i)} \right) \log \left( 1 - \left( h_\theta \left( x^{(i)} \right) \right)_k \right) \right]$$ where $h_\theta \left( x^{(i)} \right)$ is computed as shown in the neural network figure above, and K = 10 is the total number of possible labels. Note that $h_\theta(x^{(i)})_k = a_k^{(3)}$ is the activation (output value) of the $k^{th}$ output unit. Also, recall that whereas the original labels (in the variable y) were 0, 1, ..., 9, for the purpose of training a neural network, we need to encode the labels as vectors containing only values 0 or 1, so that $$ y = \begin{bmatrix} 1 \\ 0 \\ 0 \\\vdots \\ 0 \end{bmatrix}, \quad \begin{bmatrix} 0 \\ 1 \\ 0 \\ \vdots \\ 0 \end{bmatrix}, \quad \cdots \quad \text{or} \qquad \begin{bmatrix} 0 \\ 0 \\ 0 \\ \vdots \\ 1 \end{bmatrix}. $$ For example, if $x^{(i)}$ is an image of the digit 5, then the corresponding $y^{(i)}$ (that you should use with the cost function) should be a 10-dimensional vector with $y_5 = 1$, and the other elements equal to 0. You should implement the feedforward computation that computes $h_\theta(x^{(i)})$ for every example $i$ and sum the cost over all examples. **Your code should also work for a dataset of any size, with any number of labels** (you can assume that there are always at least $K \ge 3$ labels). <div class="alert alert-box alert-warning"> **Implementation Note:** The matrix $X$ contains the examples in rows (i.e., X[i,:] is the i-th training example $x^{(i)}$, expressed as a $n \times 1$ vector.) When you complete the code in `nnCostFunction`, you will need to add the column of 1’s to the X matrix. The parameters for each unit in the neural network is represented in Theta1 and Theta2 as one row. Specifically, the first row of Theta1 corresponds to the first hidden unit in the second layer. You can use a for-loop over the examples to compute the cost. </div> <a id="nnCostFunction"></a> ```python def nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_=0.0): """ Implements the neural network cost function and gradient for a two layer neural network which performs classification. Parameters ---------- nn_params : array_like The parameters for the neural network which are "unrolled" into a vector. This needs to be converted back into the weight matrices Theta1 and Theta2. input_layer_size : int Number of features for the input layer. hidden_layer_size : int Number of hidden units in the second layer. num_labels : int Total number of labels, or equivalently number of units in output layer. X : array_like Input dataset. A matrix of shape (m x input_layer_size). y : array_like Dataset labels. A vector of shape (m,). lambda_ : float, optional Regularization parameter. Returns ------- J : float The computed value for the cost function at the current weight values. grad : array_like An "unrolled" vector of the partial derivatives of the concatenatation of neural network weights Theta1 and Theta2. Instructions ------------ You should complete the code by working through the following parts. - Part 1: Feedforward the neural network and return the cost in the variable J. After implementing Part 1, you can verify that your cost function computation is correct by verifying the cost computed in the following cell. - Part 2: Implement the backpropagation algorithm to compute the gradients Theta1_grad and Theta2_grad. You should return the partial derivatives of the cost function with respect to Theta1 and Theta2 in Theta1_grad and Theta2_grad, respectively. After implementing Part 2, you can check that your implementation is correct by running checkNNGradients provided in the utils.py module. Note: The vector y passed into the function is a vector of labels containing values from 0..K-1. You need to map this vector into a binary vector of 1's and 0's to be used with the neural network cost function. Hint: We recommend implementing backpropagation using a for-loop over the training examples if you are implementing it for the first time. - Part 3: Implement regularization with the cost function and gradients. Hint: You can implement this around the code for backpropagation. That is, you can compute the gradients for the regularization separately and then add them to Theta1_grad and Theta2_grad from Part 2. Note ---- We have provided an implementation for the sigmoid function in the file `utils.py` accompanying this assignment. """ # Reshape nn_params back into the parameters Theta1 and Theta2, the weight matrices # for our 2 layer neural network Theta1 = np.reshape(nn_params[:hidden_layer_size * (input_layer_size + 1)], (hidden_layer_size, (input_layer_size + 1))) Theta2 = np.reshape(nn_params[(hidden_layer_size * (input_layer_size + 1)):], (num_labels, (hidden_layer_size + 1))) # Setup some useful variables m = y.size # You need to return the following variables correctly J = 0 Theta1_grad = np.zeros(Theta1.shape) Theta2_grad = np.zeros(Theta2.shape) # ====================== YOUR CODE HERE ====================== # print('input_layer_size', input_layer_size) # print('hidden_layer_size', hidden_layer_size) # print('num_labels', num_labels) # Add ones to the X data matrix X = np.concatenate([np.ones((m, 1)), X], axis=1) # Encoding y # > recall that whereas the original labels (in the variable y) were 0, 1, ..., 9, # > for the purpose of training a neural network, we need to encode the labels as # > vectors containing only values 0 or 1 y_encoded = np.zeros((y.size, num_labels)) # y_encoded will be of size m x k y_encoded[np.arange(y.size), y] = 1 Z2 = Theta1 @ X.T A2 = utils.sigmoid(Z2).T A2 = np.concatenate([np.ones((A2.shape[0], 1)), A2], axis=1) # add bias term to A2 (hidden layer units) Z3 = Theta2 @ A2.T A3 = utils.sigmoid(Z3).T # hypothesis hyp = A3 for i in range(m): J += (y_encoded[i] @ np.log(hyp[i]) + (1 - y_encoded[i]) @ np.log(1 - hyp[i])) regularization = (lambda_ / (2 * m)) * (np.sum(Theta1[:,1:] ** 2) + np.sum(Theta2[:,1:] ** 2)) J = - (1 / m) * J + regularization for t in range(m): a1 = X[t] z2 = Theta1 @ a1 a2 = utils.sigmoid(z2) a2 = np.concatenate([[1], a2]) z3 = Theta2 @ a2 a3 = utils.sigmoid(z3) # hypothesis delta_3 = a3 - y_encoded[t] delta_2 = (Theta2.T @ delta_3) * (a2 * (1 - a2)) delta_2 = delta_2[1:] Theta2_grad = Theta2_grad + delta_3.reshape(-1, 1) @ a2.reshape(-1, 1).T Theta1_grad = Theta1_grad + delta_2.reshape(-1, 1) @ a1.reshape(-1, 1).T Theta2_regularization = (lambda_ / m) * Theta2[:, 1:] Theta2_regularization = np.hstack((np.zeros((Theta2.shape[0], 1)), Theta2_regularization)) Theta1_regularization = (lambda_ / m) * Theta1[:, 1:] Theta1_regularization = np.hstack((np.zeros((Theta1.shape[0], 1)), Theta1_regularization)) Theta2_grad = (1 / m) * Theta2_grad + Theta2_regularization Theta1_grad = (1 / m) * Theta1_grad + Theta1_regularization # ================================================================ # Unroll gradients # grad = np.concatenate([Theta1_grad.ravel(order=order), Theta2_grad.ravel(order=order)]) grad = np.concatenate([Theta1_grad.ravel(), Theta2_grad.ravel()]) return J, grad ``` <div class="alert alert-box alert-warning"> Use the following links to go back to the different parts of this exercise that require to modify the function `nnCostFunction`.<br> Back to: - [Feedforward and cost function](#section1) - [Regularized cost](#section2) - [Neural Network Gradient (Backpropagation)](#section4) - [Regularized Gradient](#section5) </div> Once you are done, call your `nnCostFunction` using the loaded set of parameters for `Theta1` and `Theta2`. You should see that the cost is about 0.287629. ```python lambda_ = 0 J, _ = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_) print('Cost at parameters (loaded from ex4weights): %.6f ' % J) print('The cost should be about : 0.287629.') ``` Cost at parameters (loaded from ex4weights): 0.287629 The cost should be about : 0.287629. *You should now submit your solutions.* ```python grader = utils.Grader() grader[1] = nnCostFunction grader.grade() ``` Submitting Solutions | Programming Exercise neural-network-learning Use token from last successful submission ()? (Y/n): n Login (email address): [email protected] Token: ZtX4LNmGkZKhVO2u Part Name | Score | Feedback --------- | ----- | -------- Feedforward and Cost Function | 30 / 30 | Nice work! Regularized Cost Function | 0 / 15 | Sigmoid Gradient | 0 / 5 | Neural Network Gradient (Backpropagation) | 0 / 40 | Regularized Gradient | 0 / 10 | -------------------------------- | 30 / 100 | <a id="section2"></a> ### 1.4 Regularized cost function The cost function for neural networks with regularization is given by: $$ J(\theta) = \frac{1}{m} \sum_{i=1}^{m}\sum_{k=1}^{K} \left[ - y_k^{(i)} \log \left( \left( h_\theta \left( x^{(i)} \right) \right)_k \right) - \left( 1 - y_k^{(i)} \right) \log \left( 1 - \left( h_\theta \left( x^{(i)} \right) \right)_k \right) \right] + \frac{\lambda}{2 m} \left[ \sum_{j=1}^{25} \sum_{k=1}^{400} \left( \Theta_{j,k}^{(1)} \right)^2 + \sum_{j=1}^{10} \sum_{k=1}^{25} \left( \Theta_{j,k}^{(2)} \right)^2 \right] $$ You can assume that the neural network will only have 3 layers - an input layer, a hidden layer and an output layer. However, your code should work for any number of input units, hidden units and outputs units. While we have explicitly listed the indices above for $\Theta^{(1)}$ and $\Theta^{(2)}$ for clarity, do note that your code should in general work with $\Theta^{(1)}$ and $\Theta^{(2)}$ of any size. Note that you should not be regularizing the terms that correspond to the bias. For the matrices `Theta1` and `Theta2`, this corresponds to the first column of each matrix. You should now add regularization to your cost function. Notice that you can first compute the unregularized cost function $J$ using your existing `nnCostFunction` and then later add the cost for the regularization terms. [Click here to go back to `nnCostFunction` for editing.](#nnCostFunction) Once you are done, the next cell will call your `nnCostFunction` using the loaded set of parameters for `Theta1` and `Theta2`, and $\lambda = 1$. You should see that the cost is about 0.383770. ```python # Weight regularization parameter (we set this to 1 here). lambda_ = 1 J, _ = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_) print('Cost at parameters (loaded from ex4weights): %.6f' % J) print('This value should be about : 0.383770.') ``` Cost at parameters (loaded from ex4weights): 0.383770 This value should be about : 0.383770. *You should now submit your solutions.* ```python grader[2] = nnCostFunction grader.grade() ``` Submitting Solutions | Programming Exercise neural-network-learning Use token from last successful submission ([email protected])? (Y/n): y Part Name | Score | Feedback --------- | ----- | -------- Feedforward and Cost Function | 30 / 30 | Nice work! Regularized Cost Function | 15 / 15 | Nice work! Sigmoid Gradient | 0 / 5 | Neural Network Gradient (Backpropagation) | 0 / 40 | Regularized Gradient | 0 / 10 | -------------------------------- | 45 / 100 | ## 2 Backpropagation In this part of the exercise, you will implement the backpropagation algorithm to compute the gradient for the neural network cost function. You will need to update the function `nnCostFunction` so that it returns an appropriate value for `grad`. Once you have computed the gradient, you will be able to train the neural network by minimizing the cost function $J(\theta)$ using an advanced optimizer such as `scipy`'s `optimize.minimize`. You will first implement the backpropagation algorithm to compute the gradients for the parameters for the (unregularized) neural network. After you have verified that your gradient computation for the unregularized case is correct, you will implement the gradient for the regularized neural network. <a id="section3"></a> ### 2.1 Sigmoid Gradient To help you get started with this part of the exercise, you will first implement the sigmoid gradient function. The gradient for the sigmoid function can be computed as $$ g'(z) = \frac{d}{dz} g(z) = g(z)\left(1-g(z)\right) $$ where $$ \text{sigmoid}(z) = g(z) = \frac{1}{1 + e^{-z}} $$ Now complete the implementation of `sigmoidGradient` in the next cell. <a id="sigmoidGradient"></a> ```python def sigmoidGradient(z): """ Computes the gradient of the sigmoid function evaluated at z. This should work regardless if z is a matrix or a vector. In particular, if z is a vector or matrix, you should return the gradient for each element. Parameters ---------- z : array_like A vector or matrix as input to the sigmoid function. Returns -------- g : array_like Gradient of the sigmoid function. Has the same shape as z. Instructions ------------ Compute the gradient of the sigmoid function evaluated at each value of z (z can be a matrix, vector or scalar). Note ---- We have provided an implementation of the sigmoid function in `utils.py` file accompanying this assignment. """ g = np.zeros(z.shape) # ====================== YOUR CODE HERE ====================== g = utils.sigmoid(z) * (1 - utils.sigmoid(z)) # ============================================================= return g ``` When you are done, the following cell call `sigmoidGradient` on a given vector `z`. Try testing a few values by calling `sigmoidGradient(z)`. For large values (both positive and negative) of z, the gradient should be close to 0. When $z = 0$, the gradient should be exactly 0.25. Your code should also work with vectors and matrices. For a matrix, your function should perform the sigmoid gradient function on every element. ```python z = np.array([-1, -0.5, 0, 0.5, 1]) g = sigmoidGradient(z) print('Sigmoid gradient evaluated at [-1 -0.5 0 0.5 1]:\n ') print(g) ``` Sigmoid gradient evaluated at [-1 -0.5 0 0.5 1]: [0.19661193 0.23500371 0.25 0.23500371 0.19661193] *You should now submit your solutions.* ```python grader[3] = sigmoidGradient grader.grade() ``` Submitting Solutions | Programming Exercise neural-network-learning Use token from last successful submission ([email protected])? (Y/n): y Part Name | Score | Feedback --------- | ----- | -------- Feedforward and Cost Function | 30 / 30 | Nice work! Regularized Cost Function | 15 / 15 | Nice work! Sigmoid Gradient | 5 / 5 | Nice work! Neural Network Gradient (Backpropagation) | 0 / 40 | Regularized Gradient | 0 / 10 | -------------------------------- | 50 / 100 | ## 2.2 Random Initialization When training neural networks, it is important to randomly initialize the parameters for symmetry breaking. One effective strategy for random initialization is to randomly select values for $\Theta^{(l)}$ uniformly in the range $[-\epsilon_{init}, \epsilon_{init}]$. You should use $\epsilon_{init} = 0.12$. This range of values ensures that the parameters are kept small and makes the learning more efficient. <div class="alert alert-box alert-warning"> One effective strategy for choosing $\epsilon_{init}$ is to base it on the number of units in the network. A good choice of $\epsilon_{init}$ is $\epsilon_{init} = \frac{\sqrt{6}}{\sqrt{L_{in} + L_{out}}}$ where $L_{in} = s_l$ and $L_{out} = s_{l+1}$ are the number of units in the layers adjacent to $\Theta^{l}$. </div> Your job is to complete the function `randInitializeWeights` to initialize the weights for $\Theta$. Modify the function by filling in the following code: ```python # Randomly initialize the weights to small values W = np.random.rand(L_out, 1 + L_in) * 2 * epsilon_init - epsilon_init ``` Note that we give the function an argument for $\epsilon$ with default value `epsilon_init = 0.12`. ```python def randInitializeWeights(L_in, L_out, epsilon_init=0.12): """ Randomly initialize the weights of a layer in a neural network. Parameters ---------- L_in : int Number of incomming connections. L_out : int Number of outgoing connections. epsilon_init : float, optional Range of values which the weight can take from a uniform distribution. Returns ------- W : array_like The weight initialiatized to random values. Note that W should be set to a matrix of size(L_out, 1 + L_in) as the first column of W handles the "bias" terms. Instructions ------------ Initialize W randomly so that we break the symmetry while training the neural network. Note that the first column of W corresponds to the parameters for the bias unit. """ # You need to return the following variables correctly W = np.zeros((L_out, 1 + L_in)) # ====================== YOUR CODE HERE ====================== # Randomly initialize the weights to small values W = np.random.rand(L_out, 1 + L_in) * 2 * epsilon_init - epsilon_init # ============================================================ return W ``` *You do not need to submit any code for this part of the exercise.* Execute the following cell to initialize the weights for the 2 layers in the neural network using the `randInitializeWeights` function. ```python print('Initializing Neural Network Parameters ...') initial_Theta1 = randInitializeWeights(input_layer_size, hidden_layer_size) initial_Theta2 = randInitializeWeights(hidden_layer_size, num_labels) # Unroll parameters initial_nn_params = np.concatenate([initial_Theta1.ravel(), initial_Theta2.ravel()], axis=0) ``` Initializing Neural Network Parameters ... <a id="section4"></a> ### 2.4 Backpropagation Now, you will implement the backpropagation algorithm. Recall that the intuition behind the backpropagation algorithm is as follows. Given a training example $(x^{(t)}, y^{(t)})$, we will first run a “forward pass” to compute all the activations throughout the network, including the output value of the hypothesis $h_\theta(x)$. Then, for each node $j$ in layer $l$, we would like to compute an “error term” $\delta_j^{(l)}$ that measures how much that node was “responsible” for any errors in our output. For an output node, we can directly measure the difference between the network’s activation and the true target value, and use that to define $\delta_j^{(3)}$ (since layer 3 is the output layer). For the hidden units, you will compute $\delta_j^{(l)}$ based on a weighted average of the error terms of the nodes in layer $(l+1)$. In detail, here is the backpropagation algorithm (also depicted in the figure above). You should implement steps 1 to 4 in a loop that processes one example at a time. Concretely, you should implement a for-loop `for t in range(m)` and place steps 1-4 below inside the for-loop, with the $t^{th}$ iteration performing the calculation on the $t^{th}$ training example $(x^{(t)}, y^{(t)})$. Step 5 will divide the accumulated gradients by $m$ to obtain the gradients for the neural network cost function. 1. Set the input layer’s values $(a^{(1)})$ to the $t^{th }$training example $x^{(t)}$. Perform a feedforward pass, computing the activations $(z^{(2)}, a^{(2)}, z^{(3)}, a^{(3)})$ for layers 2 and 3. Note that you need to add a `+1` term to ensure that the vectors of activations for layers $a^{(1)}$ and $a^{(2)}$ also include the bias unit. In `numpy`, if a 1 is a column matrix, adding one corresponds to `a_1 = np.concatenate([np.ones((m, 1)), a_1], axis=1)`. 1. For each output unit $k$ in layer 3 (the output layer), set $$\delta_k^{(3)} = \left(a_k^{(3)} - y_k \right)$$ where $y_k \in \{0, 1\}$ indicates whether the current training example belongs to class $k$ $(y_k = 1)$, or if it belongs to a different class $(y_k = 0)$. You may find logical arrays helpful for this task (explained in the previous programming exercise). 1. For the hidden layer $l = 2$, set $$ \delta^{(2)} = \left( \Theta^{(2)} \right)^T \delta^{(3)} * g'\left(z^{(2)} \right)$$ Note that the symbol $*$ performs element wise multiplication in `numpy`. 1. Accumulate the gradient from this example using the following formula. Note that you should skip or remove $\delta_0^{(2)}$. In `numpy`, removing $\delta_0^{(2)}$ corresponds to `delta_2 = delta_2[1:]`. $$ \Delta^{(l)} = \Delta^{(l)} + \delta^{(l+1)} (a^{(l)})^{(T)} $$ 1. Obtain the (unregularized) gradient for the neural network cost function by dividing the accumulated gradients by $\frac{1}{m}$: $$ \frac{\partial}{\partial \Theta_{ij}^{(l)}} J(\Theta) = D_{ij}^{(l)} = \frac{1}{m} \Delta_{ij}^{(l)}$$ <div class="alert alert-box alert-warning"> **Python/Numpy tip**: You should implement the backpropagation algorithm only after you have successfully completed the feedforward and cost functions. While implementing the backpropagation alogrithm, it is often useful to use the `shape` function to print out the shapes of the variables you are working with if you run into dimension mismatch errors. </div> [Click here to go back and update the function `nnCostFunction` with the backpropagation algorithm](#nnCostFunction). **Note:** If the iterative solution provided above is proving to be difficult to implement, try implementing the vectorized approach which is easier to implement in the opinion of the moderators of this course. You can find the tutorial for the vectorized approach [here](https://www.coursera.org/learn/machine-learning/discussions/all/threads/a8Kce_WxEeS16yIACyoj1Q). After you have implemented the backpropagation algorithm, we will proceed to run gradient checking on your implementation. The gradient check will allow you to increase your confidence that your code is computing the gradients correctly. ### 2.4 Gradient checking In your neural network, you are minimizing the cost function $J(\Theta)$. To perform gradient checking on your parameters, you can imagine “unrolling” the parameters $\Theta^{(1)}$, $\Theta^{(2)}$ into a long vector $\theta$. By doing so, you can think of the cost function being $J(\Theta)$ instead and use the following gradient checking procedure. Suppose you have a function $f_i(\theta)$ that purportedly computes $\frac{\partial}{\partial \theta_i} J(\theta)$; you’d like to check if $f_i$ is outputting correct derivative values. $$ \text{Let } \theta^{(i+)} = \theta + \begin{bmatrix} 0 \\ 0 \\ \vdots \\ \epsilon \\ \vdots \\ 0 \end{bmatrix} \quad \text{and} \quad \theta^{(i-)} = \theta - \begin{bmatrix} 0 \\ 0 \\ \vdots \\ \epsilon \\ \vdots \\ 0 \end{bmatrix} $$ So, $\theta^{(i+)}$ is the same as $\theta$, except its $i^{th}$ element has been incremented by $\epsilon$. Similarly, $\theta^{(i−)}$ is the corresponding vector with the $i^{th}$ element decreased by $\epsilon$. You can now numerically verify $f_i(\theta)$’s correctness by checking, for each $i$, that: $$ f_i\left( \theta \right) \approx \frac{J\left( \theta^{(i+)}\right) - J\left( \theta^{(i-)} \right)}{2\epsilon} $$ The degree to which these two values should approximate each other will depend on the details of $J$. But assuming $\epsilon = 10^{-4}$, you’ll usually find that the left- and right-hand sides of the above will agree to at least 4 significant digits (and often many more). We have implemented the function to compute the numerical gradient for you in `computeNumericalGradient` (within the file `utils.py`). While you are not required to modify the file, we highly encourage you to take a look at the code to understand how it works. In the next cell we will run the provided function `checkNNGradients` which will create a small neural network and dataset that will be used for checking your gradients. If your backpropagation implementation is correct, you should see a relative difference that is less than 1e-9. <div class="alert alert-box alert-success"> **Practical Tip**: When performing gradient checking, it is much more efficient to use a small neural network with a relatively small number of input units and hidden units, thus having a relatively small number of parameters. Each dimension of $\theta$ requires two evaluations of the cost function and this can be expensive. In the function `checkNNGradients`, our code creates a small random model and dataset which is used with `computeNumericalGradient` for gradient checking. Furthermore, after you are confident that your gradient computations are correct, you should turn off gradient checking before running your learning algorithm. </div> <div class="alert alert-box alert-success"> <b>Practical Tip:</b> Gradient checking works for any function where you are computing the cost and the gradient. Concretely, you can use the same `computeNumericalGradient` function to check if your gradient implementations for the other exercises are correct too (e.g., logistic regression’s cost function). </div> ```python utils.checkNNGradients(nnCostFunction) ``` [[-9.27825235e-03 -9.27825236e-03] [-3.04978931e-06 -3.04978914e-06] [-1.75060082e-04 -1.75060082e-04] [-9.62660618e-05 -9.62660620e-05] [ 8.89911959e-03 8.89911960e-03] [ 1.42869450e-05 1.42869443e-05] [ 2.33146358e-04 2.33146357e-04] [ 1.17982666e-04 1.17982666e-04] [-8.36010761e-03 -8.36010762e-03] [-2.59383093e-05 -2.59383100e-05] [-2.87468729e-04 -2.87468729e-04] [-1.37149709e-04 -1.37149706e-04] [ 7.62813551e-03 7.62813551e-03] [ 3.69883213e-05 3.69883234e-05] [ 3.35320347e-04 3.35320347e-04] [ 1.53247079e-04 1.53247082e-04] [-6.74798369e-03 -6.74798370e-03] [-4.68759764e-05 -4.68759769e-05] [-3.76215588e-04 -3.76215587e-04] [-1.66560294e-04 -1.66560294e-04] [ 3.14544970e-01 3.14544970e-01] [ 1.64090819e-01 1.64090819e-01] [ 1.64567932e-01 1.64567932e-01] [ 1.58339334e-01 1.58339334e-01] [ 1.51127527e-01 1.51127527e-01] [ 1.49568335e-01 1.49568335e-01] [ 1.11056588e-01 1.11056588e-01] [ 5.75736494e-02 5.75736493e-02] [ 5.77867379e-02 5.77867378e-02] [ 5.59235296e-02 5.59235296e-02] [ 5.36967009e-02 5.36967009e-02] [ 5.31542052e-02 5.31542052e-02] [ 9.74006970e-02 9.74006970e-02] [ 5.04575855e-02 5.04575855e-02] [ 5.07530173e-02 5.07530173e-02] [ 4.91620841e-02 4.91620841e-02] [ 4.71456249e-02 4.71456249e-02] [ 4.65597186e-02 4.65597186e-02]] The above two columns you get should be very similar. (Left-Your Numerical Gradient, Right-Analytical Gradient) If your backpropagation implementation is correct, then the relative difference will be small (less than 1e-9). Relative Difference: 2.25938e-11 *Once your cost function passes the gradient check for the (unregularized) neural network cost function, you should submit the neural network gradient function (backpropagation).* ```python grader[4] = nnCostFunction grader.grade() ``` Submitting Solutions | Programming Exercise neural-network-learning Use token from last successful submission ([email protected])? (Y/n): y Part Name | Score | Feedback --------- | ----- | -------- Feedforward and Cost Function | 30 / 30 | Nice work! Regularized Cost Function | 15 / 15 | Nice work! Sigmoid Gradient | 5 / 5 | Nice work! Neural Network Gradient (Backpropagation) | 40 / 40 | Nice work! Regularized Gradient | 0 / 10 | -------------------------------- | 90 / 100 | <a id="section5"></a> ### 2.5 Regularized Neural Network After you have successfully implemented the backpropagation algorithm, you will add regularization to the gradient. To account for regularization, it turns out that you can add this as an additional term *after* computing the gradients using backpropagation. Specifically, after you have computed $\Delta_{ij}^{(l)}$ using backpropagation, you should add regularization using $$ \begin{align} & \frac{\partial}{\partial \Theta_{ij}^{(l)}} J(\Theta) = D_{ij}^{(l)} = \frac{1}{m} \Delta_{ij}^{(l)} & \qquad \text{for } j = 0 \\ & \frac{\partial}{\partial \Theta_{ij}^{(l)}} J(\Theta) = D_{ij}^{(l)} = \frac{1}{m} \Delta_{ij}^{(l)} + \frac{\lambda}{m} \Theta_{ij}^{(l)} & \qquad \text{for } j \ge 1 \end{align} $$ Note that you should *not* be regularizing the first column of $\Theta^{(l)}$ which is used for the bias term. Furthermore, in the parameters $\Theta_{ij}^{(l)}$, $i$ is indexed starting from 1, and $j$ is indexed starting from 0. Thus, $$ \Theta^{(l)} = \begin{bmatrix} \Theta_{1,0}^{(i)} & \Theta_{1,1}^{(l)} & \cdots \\ \Theta_{2,0}^{(i)} & \Theta_{2,1}^{(l)} & \cdots \\ \vdots & ~ & \ddots \end{bmatrix} $$ [Now modify your code that computes grad in `nnCostFunction` to account for regularization.](#nnCostFunction) After you are done, the following cell runs gradient checking on your implementation. If your code is correct, you should expect to see a relative difference that is less than 1e-9. ```python # Check gradients by running checkNNGradients lambda_ = 3 utils.checkNNGradients(nnCostFunction, lambda_) # Also output the costFunction debugging values debug_J, _ = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_) print('\n\nCost at (fixed) debugging parameters (w/ lambda = %f): %f ' % (lambda_, debug_J)) print('(for lambda = 3, this value should be about 0.576051)') ``` [[-9.27825235e-03 -9.27825236e-03] [-1.67679797e-02 -1.67679797e-02] [-6.01744725e-02 -6.01744725e-02] [-1.73704651e-02 -1.73704651e-02] [ 8.89911959e-03 8.89911960e-03] [ 3.94334829e-02 3.94334829e-02] [-3.19612287e-02 -3.19612287e-02] [-5.75658668e-02 -5.75658668e-02] [-8.36010761e-03 -8.36010762e-03] [ 5.93355565e-02 5.93355565e-02] [ 2.49225535e-02 2.49225535e-02] [-4.51963845e-02 -4.51963845e-02] [ 7.62813551e-03 7.62813551e-03] [ 2.47640974e-02 2.47640974e-02] [ 5.97717617e-02 5.97717617e-02] [ 9.14587966e-03 9.14587966e-03] [-6.74798369e-03 -6.74798370e-03] [-3.26881426e-02 -3.26881426e-02] [ 3.86410548e-02 3.86410548e-02] [ 5.46101547e-02 5.46101547e-02] [ 3.14544970e-01 3.14544970e-01] [ 1.18682669e-01 1.18682669e-01] [ 2.03987128e-01 2.03987128e-01] [ 1.25698067e-01 1.25698067e-01] [ 1.76337550e-01 1.76337550e-01] [ 1.32294136e-01 1.32294136e-01] [ 1.11056588e-01 1.11056588e-01] [ 3.81928689e-05 3.81928696e-05] [ 1.17148233e-01 1.17148233e-01] [-4.07588279e-03 -4.07588279e-03] [ 1.13133142e-01 1.13133142e-01] [-4.52964427e-03 -4.52964427e-03] [ 9.74006970e-02 9.74006970e-02] [ 3.36926556e-02 3.36926556e-02] [ 7.54801264e-02 7.54801264e-02] [ 1.69677090e-02 1.69677090e-02] [ 8.61628953e-02 8.61628953e-02] [ 1.50048382e-03 1.50048382e-03]] The above two columns you get should be very similar. (Left-Your Numerical Gradient, Right-Analytical Gradient) If your backpropagation implementation is correct, then the relative difference will be small (less than 1e-9). Relative Difference: 2.22022e-11 Cost at (fixed) debugging parameters (w/ lambda = 3.000000): 0.576051 (for lambda = 3, this value should be about 0.576051) ```python grader[5] = nnCostFunction grader.grade() ``` Submitting Solutions | Programming Exercise neural-network-learning Use token from last successful submission ([email protected])? (Y/n): y Part Name | Score | Feedback --------- | ----- | -------- Feedforward and Cost Function | 30 / 30 | Nice work! Regularized Cost Function | 15 / 15 | Nice work! Sigmoid Gradient | 5 / 5 | Nice work! Neural Network Gradient (Backpropagation) | 40 / 40 | Nice work! Regularized Gradient | 10 / 10 | Nice work! -------------------------------- | 100 / 100 | ### 2.6 Learning parameters using `scipy.optimize.minimize` After you have successfully implemented the neural network cost function and gradient computation, the next step we will use `scipy`'s minimization to learn a good set parameters. ```python # After you have completed the assignment, change the maxiter to a larger # value to see how more training helps. options= {'maxiter': 500} # You should also try different values of lambda lambda_ = 1 # Create "short hand" for the cost function to be minimized costFunction = lambda p: nnCostFunction(p, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_) # Now, costFunction is a function that takes in only one argument # (the neural network parameters) res = optimize.minimize(costFunction, initial_nn_params, jac=True, method='TNC', options=options) # get the solution of the optimization nn_params = res.x # Obtain Theta1 and Theta2 back from nn_params Theta1 = np.reshape(nn_params[:hidden_layer_size * (input_layer_size + 1)], (hidden_layer_size, (input_layer_size + 1))) Theta2 = np.reshape(nn_params[(hidden_layer_size * (input_layer_size + 1)):], (num_labels, (hidden_layer_size + 1))) ``` After the training completes, we will proceed to report the training accuracy of your classifier by computing the percentage of examples it got correct. If your implementation is correct, you should see a reported training accuracy of about 95.3% (this may vary by about 1% due to the random initialization). It is possible to get higher training accuracies by training the neural network for more iterations. We encourage you to try training the neural network for more iterations (e.g., set `maxiter` to 400) and also vary the regularization parameter $\lambda$. With the right learning settings, it is possible to get the neural network to perfectly fit the training set. ```python pred = utils.predict(Theta1, Theta2, X) print('Training Set Accuracy: %f' % (np.mean(pred == y) * 100)) ``` Training Set Accuracy: 99.540000 ## 3 Visualizing the Hidden Layer One way to understand what your neural network is learning is to visualize what the representations captured by the hidden units. Informally, given a particular hidden unit, one way to visualize what it computes is to find an input $x$ that will cause it to activate (that is, to have an activation value ($a_i^{(l)}$) close to 1). For the neural network you trained, notice that the $i^{th}$ row of $\Theta^{(1)}$ is a 401-dimensional vector that represents the parameter for the $i^{th}$ hidden unit. If we discard the bias term, we get a 400 dimensional vector that represents the weights from each input pixel to the hidden unit. Thus, one way to visualize the “representation” captured by the hidden unit is to reshape this 400 dimensional vector into a 20 × 20 image and display it (It turns out that this is equivalent to finding the input that gives the highest activation for the hidden unit, given a “norm” constraint on the input (i.e., $||x||_2 \le 1$)). The next cell does this by using the `displayData` function and it will show you an image with 25 units, each corresponding to one hidden unit in the network. In your trained network, you should find that the hidden units corresponds roughly to detectors that look for strokes and other patterns in the input. ```python utils.displayData(Theta1[:, 1:]) ``` ### 3.1 Optional (ungraded) exercise In this part of the exercise, you will get to try out different learning settings for the neural network to see how the performance of the neural network varies with the regularization parameter $\lambda$ and number of training steps (the `maxiter` option when using `scipy.optimize.minimize`). Neural networks are very powerful models that can form highly complex decision boundaries. Without regularization, it is possible for a neural network to “overfit” a training set so that it obtains close to 100% accuracy on the training set but does not as well on new examples that it has not seen before. You can set the regularization $\lambda$ to a smaller value and the `maxiter` parameter to a higher number of iterations to see this for youself.
theory func_cor_OSMboxAccept imports func_cor_lemma begin lemma OSMboxAccept_pre_stable:" stable (OSMboxAccept_pre t) (OSMboxAccept_rely t) " by(simp add:OSMboxAccept_pre_def OSMboxAccept_rely_def stable_def gvars_conf_stable_def gvars_conf_def) lemma OSMboxAccept_pre_stable1:" stable (OSMboxAccept_pre t \<inter> \<lbrace>pevent \<in> \<acute>OSMailBoxs\<rbrace>) (OSMboxAccept_rely t) " by(simp add:OSMboxAccept_pre_def OSMboxAccept_rely_def stable_def gvars_conf_stable_def gvars_conf_def) lemma OSMboxAccept_post_stable:" stable (OSMboxAccept_post t) (OSMboxAccept_rely t) " by(simp add:OSMboxAccept_post_def OSMboxAccept_rely_def stable_def) lemma mylist_nhd_in_tl: "dist_list l \<Longrightarrow> hd l \<notin> set (tl l) " by (meson dist_hd_nin_tl distinct_conv_nth) lemma mylist_hd_in_list: "l \<noteq> [] \<Longrightarrow>hd l \<in> set l" by auto lemma OSMboxAccept_satRG_h1:" \<turnstile>\<^sub>I (W\<acute>get_msg := \<acute>get_msg(t := msgPtr (\<acute>OSMailbox_info pevent));; \<acute>OSMailbox_info := \<acute>OSMailbox_info (pevent := msgPtr_update Map.empty (\<acute>OSMailbox_info pevent))) sat\<^sub>p [OSMboxAccept_pre t \<inter> \<lbrace>pevent \<in> \<acute>OSMailBoxs\<rbrace> \<inter> \<lbrace>\<acute>cur = Some t\<rbrace> \<inter> {V}, {(x, y). x = y}, UNIV, \<lbrace>\<acute>(Pair V) \<in> OSMboxAccept_guar t\<rbrace> \<inter> OSMboxAccept_post t]" apply(case_tac "OSMboxAccept_pre t \<inter> \<lbrace>pevent \<in> \<acute>OSMailBoxs\<rbrace> \<inter> \<lbrace>\<acute>cur = Some t\<rbrace> \<inter> {V} = {}") apply auto apply(simp add:Emptyprecond) apply(simp add:Emptyprecond) apply(simp add:Emptyprecond) apply(rule Seq[where mid = "{V\<lparr>get_msg := (get_msg V)(t := msgPtr (OSMailbox_info V pevent))\<rparr>}"]) apply(rule Basic) apply auto apply(simp add:stable_id2) apply(simp add:stable_id2) apply(rule Basic) apply auto apply(simp add:OSMboxAccept_pre_def OSMboxAccept_guar_def gvars_conf_stable_def gvars_conf_def) apply auto apply(simp add:inv_def inv_cur_def inv_thd_waitq_def) apply auto[1] apply(simp add:lvars_nochange_def) apply(simp add:OSMboxAccept_post_def inv_def inv_cur_def inv_thd_waitq_def OSMboxAccept_pre_def) apply auto apply(simp add:stable_id2) apply(simp add:stable_id2) done lemma OSMboxAccept_satRG: "\<Gamma> (OSMboxAccept t pevent) \<turnstile> OSMboxAccept_RGCond t" apply (simp add:Evt_sat_RG_def) apply (simp add:OSMboxAccept_def OSMboxAccept_RGCond_def) apply(simp add:body_def Pre\<^sub>f_def Post\<^sub>f_def guard_def Rely\<^sub>f_def Guar\<^sub>f_def getrgformula_def) apply(unfold stm_def) apply (rule BasicEvt) apply(simp add:body_def guard_def) apply(rule Await) apply(simp add:OSMboxAccept_pre_stable1) apply(simp add: OSMboxAccept_post_stable) apply auto apply(rule Await) apply(simp add:stable_id2) apply(simp add:stable_id2) apply auto apply(case_tac "{V} \<inter> {Va}={}") apply auto apply(simp add:Emptyprecond) (* satRG_h1*) apply(simp add:OSMboxAccept_satRG_h1) apply(simp add:OSMboxAccept_pre_stable) apply(simp add:OSMboxAccept_guar_def) done end
(*************************************************************) (* Copyright Dominique Larchey-Wendling [*] *) (* *) (* [*] Affiliation LORIA -- CNRS *) (*************************************************************) (* This file is distributed under the terms of the *) (* CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT *) (*************************************************************) Require Import List Arith Lia. From Undecidability.Shared.Libs.DLW Require Import utils_tac utils_nat pos vec sss. From Undecidability.MinskyMachines Require Import mm_defs. From Undecidability.MuRec Require Import recalg ra_mm. Set Implicit Arguments. Local Notation "'⟦' f '⟧'" := (@ra_rel _ f) (at level 0). Local Notation "P // s -+> t" := (sss_progress (@mm_sss _) P s t). Local Notation "P // s ->> t" := (sss_compute (@mm_sss _) P s t). Local Notation "P // s ~~> t" := (sss_output (@mm_sss _) P s t). Local Notation "P // s ↓" := (sss_terminates (@mm_sss _) P s). Theorem ra_mm_simulator n (f : recalg n) : { m & { P : list (mm_instr (pos (n+S m))) | forall v, ex (⟦f⟧ v) <-> (1,P) // (1,vec_app v vec_zero) ↓ } }. Proof. destruct (ra_mm_compiler f) as (m & P & H1 & H2). exists m, P; split. + intros (x & Hx). exists (1+length P,vec_app v (x##vec_zero)); split; auto. simpl; lia. + intros H; apply H2; eq goal H; do 2 f_equal. Qed. Corollary ra_mm_simulator_0 (f : recalg 0) : { m & { P : list (mm_instr (pos (S m))) | ex (⟦f⟧ vec_nil) <-> (1,P) // (1,vec_zero) ↓ } }. Proof. destruct (ra_mm_simulator f) as (m & P & HP). exists m, P; rewrite (HP vec_nil), vec_app_nil; tauto. Qed.
------------------------------------------------------------------------ -- Examples ------------------------------------------------------------------------ module StructurallyRecursiveDescentParsing.Examples where open import Data.List open import Data.Vec using ([]; _∷_) open import Data.Nat open import Data.Bool open import Data.Char using (Char) import Data.Char.Properties as C import Data.String as S open S using (String) open import Codata.Musical.Notation open import Relation.Binary.PropositionalEquality as P using (_≡_) open import StructurallyRecursiveDescentParsing.Index open import StructurallyRecursiveDescentParsing.Grammar open import StructurallyRecursiveDescentParsing.DepthFirst open import StructurallyRecursiveDescentParsing.Lib open Token C.decSetoid -- Some functions used to simplify the examples a little. infix 5 _∈?_/_ _∈?_ _∈?_/_ : ∀ {NT i R} → String → Parser NT Char i R → Grammar NT Char → List R s ∈? p / g = parseComplete (⟦ p ⟧ g) (S.toList s) _∈?_ : ∀ {i R} → String → Parser EmptyNT Char i R → List R s ∈? p = s ∈? p / emptyGrammar module Ex₁ where mutual -- e ∷= 0 + e | 0 data Nonterminal : NonTerminalType where e : Nonterminal i Char private i = _ grammar : Grammar Nonterminal Char grammar e = tok '0' ⊛> tok '+' ⊛> ! e ∣ tok '0' ex₁ : "0+0" ∈? ! e / grammar ≡ [ '0' ] ex₁ = P.refl module Ex₂ where mutual -- e ∷= f + e | f -- f ∷= 0 | 0 * f | ( e ) data Nonterminal : NonTerminalType where expr : Nonterminal i₁ Char factor : Nonterminal i₂ Char private i₁ = _ i₂ = _ grammar : Grammar Nonterminal Char grammar expr = ! factor ⊛> tok '+' ⊛> ! expr ∣ ! factor grammar factor = tok '0' ∣ tok '0' ⊛> tok '*' ⊛> ! factor ∣ tok '(' ⊛> ! expr <⊛ tok ')' ex₁ : "(0*)" ∈? ! expr / grammar ≡ [] ex₁ = P.refl ex₂ : "0*(0+0)" ∈? ! expr / grammar ≡ [ '0' ] ex₂ = P.refl {- module Ex₃ where mutual -- This is not allowed: -- e ∷= f + e | f -- f ∷= 0 | f * 0 | ( e ) data Nonterminal : NonTerminalType where expr : Nonterminal i₁ Char factor : Nonterminal i₂ Char private i₁ = _ i₂ = _ grammar : Grammar Nonterminal Char grammar expr = ! factor ⊛> tok '+' ⊛> ! expr ∣ ! factor grammar factor = tok '0' ∣ ! factor ⊛> tok '*' ⊛> tok '0' ∣ tok '(' ⊛> ! expr <⊛ tok ')' -} module Ex₄ where mutual -- The language aⁿbⁿcⁿ, which is not context free. -- The non-terminal top returns the number of 'a' characters -- parsed. data NT : NonTerminalType where top : NT i₁ ℕ -- top ∷= aⁿbⁿcⁿ as : ℕ → NT i₂ ℕ -- as n ∷= aˡ⁺¹bⁿ⁺ˡ⁺¹cⁿ⁺ˡ⁺¹ bcs : Char → ℕ → NT i₃ ℕ -- bcs x n ∷= xⁿ⁺¹ private i₁ = _ i₂ = _ i₃ = _ grammar : Grammar NT Char grammar top = return 0 ∣ ! (as zero) grammar (as n) = suc <$ tok 'a' ⊛ ( ! (as (suc n)) ∣ _+_ <$> ! (bcs 'b' n) ⊛ ! (bcs 'c' n) ) grammar (bcs c zero) = tok c ⊛> return 0 grammar (bcs c (suc n)) = tok c ⊛> ! (bcs c n) ex₁ : "aaabbbccc" ∈? ! top / grammar ≡ [ 3 ] ex₁ = P.refl ex₂ : "aaabbccc" ∈? ! top / grammar ≡ [] ex₂ = P.refl module Ex₄′ where mutual -- A monadic variant of Ex₄. aⁿbⁿcⁿ = return 0 ∣ tok 'a' + !>>= λ as → ♯ (let n = length as in exactly n (tok 'b') ⊛> exactly n (tok 'c') ⊛> return n) ex₁ : "aaabbbccc" ∈? aⁿbⁿcⁿ ≡ [ 3 ] ex₁ = P.refl ex₂ : "aaabbccc" ∈? aⁿbⁿcⁿ ≡ [] ex₂ = P.refl module Ex₅ where mutual -- A grammar making use of a parameterised parser from the -- library. data NT : NonTerminalType where a : NT i₁ Char as : NT i₂ ℕ private i₁ = _ i₂ = _ grammar : Grammar NT Char grammar a = tok 'a' grammar as = length <$> ! a ⋆ ex₁ : "aaaaa" ∈? ! as / grammar ≡ [ 5 ] ex₁ = P.refl module Ex₆ where mutual -- A grammar which uses the chain≥ combinator. data NT : NonTerminalType where op : NT i₁ (ℕ → ℕ → ℕ) expr : (a : Assoc) → NT i₂ ℕ private i₁ = _ i₂ = _ grammar : Grammar NT Char grammar op = _+_ <$ tok '+' ∣ _*_ <$ tok '*' ∣ _∸_ <$ tok '∸' grammar (expr a) = chain≥ 0 a number (! op) ex₁ : "12345" ∈? number / grammar ≡ [ 12345 ] ex₁ = P.refl ex₂ : "1+5*2∸3" ∈? ! (expr left) / grammar ≡ [ 9 ] ex₂ = P.refl ex₃ : "1+5*2∸3" ∈? ! (expr right) / grammar ≡ [ 1 ] ex₃ = P.refl module Ex₇ where mutual -- A proper expression example. data NT : NonTerminalType where expr : NT i₁ ℕ term : NT i₂ ℕ factor : NT i₃ ℕ addOp : NT i₄ (ℕ → ℕ → ℕ) mulOp : NT i₅ (ℕ → ℕ → ℕ) private i₁ = _ i₂ = _ i₃ = _ i₄ = _ i₅ = _ grammar : Grammar NT Char grammar expr = chain≥ 0 left (! term) (! addOp) grammar term = chain≥ 0 left (! factor) (! mulOp) grammar factor = tok '(' ⊛> ! expr <⊛ tok ')' ∣ number grammar addOp = _+_ <$ tok '+' ∣ _∸_ <$ tok '∸' grammar mulOp = _*_ <$ tok '*' ex₁ : "1+5*2∸3" ∈? ! expr / grammar ≡ [ 8 ] ex₁ = P.refl ex₂ : "1+5*(2∸3)" ∈? ! expr / grammar ≡ [ 1 ] ex₂ = P.refl module Ex₈ where mutual -- An example illustrating the use of one grammar within another. data NT : NonTerminalType where lib : ∀ {i R} (nt : Ex₇.NT i R) → NT i R exprs : NT i (List ℕ) private i = _ expr = lib Ex₇.expr grammar : Grammar NT Char grammar (lib nt) = mapNT lib (Ex₇.grammar nt) grammar exprs = ! expr sepBy tok ',' ex₁ : "1,2∸1" ∈? ! exprs / grammar ≡ [ 1 ∷ 1 ∷ [] ] ex₁ = P.refl module Ex₉ where mutual -- An example illustrating the use of one grammar within another -- when the inner grammar contains non-terminals parameterised on -- parsers, and the outer grammar instantiates one of these -- parsers with an outer non-terminal. infix 55 _★ _∔ data LibraryNT (NT : NonTerminalType) (Tok : Set) : NonTerminalType where _★ : ∀ {c R} → Parser NT Tok (false ◇ c) R → LibraryNT NT Tok (i₁ c) (List R) _∔ : ∀ {c R} → Parser NT Tok (false ◇ c) R → LibraryNT NT Tok (i₂ c) (List R) private i₁ i₂ : _ → _ i₁ = _ i₂ = _ library : ∀ {NT Tok} → (∀ {i R} → LibraryNT NT Tok i R → NT i R) → ∀ {i R} → LibraryNT NT Tok i R → Parser NT Tok i R library lift (p ★) = return [] ∣ ! (lift (p ∔)) library lift (p ∔) = p >>= λ x → ! (lift (p ★)) >>= λ xs → return (x ∷ xs) mutual data NT : NonTerminalType where lib : ∀ {i R} → LibraryNT NT Char i R → NT i R a : NT i₃ Char as : NT i₄ (List Char) private i₃ = _ i₄ = _ grammar : Grammar NT Char grammar (lib nt) = library lib nt grammar a = tok 'a' grammar as = ! (lib (! a ★)) ex₁ : "aa" ∈? ! as / grammar ≡ [ 'a' ∷ 'a' ∷ [] ] ex₁ = P.refl
* * $Id$ * *====================================================================== * * DISCLAIMER * * This material was prepared as an account of work sponsored by an * agency of the United States Government. Neither the United States * Government nor the United States Department of Energy, nor Battelle, * nor any of their employees, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, * COMPLETENESS, OR USEFULNESS OF ANY INFORMATION, APPARATUS, PRODUCT, * SOFTWARE, OR PROCESS DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT * INFRINGE PRIVATELY OWNED RIGHTS. * * ACKNOWLEDGMENT * * This software and its documentation were produced with Government * support under Contract Number DE-AC06-76RLO-1830 awarded by the United * States Department of Energy. The Government retains a paid-up * non-exclusive, irrevocable worldwide license to reproduce, prepare * derivative works, perform publicly and display publicly by or for the * Government, including the right to distribute to other Government * contractors. * *====================================================================== * * -- PEIGS routine (version 2.1) -- * Pacific Northwest Laboratory * July 28, 1995 * *====================================================================== program machine c c double precision dlamch real slamch c write(*,*) write(*,*) ' Double Precision results' write(*,1000) ' depsilon ', dlamch('e') write(*,1000) ' dbase ', dlamch('b') write(*,1000) ' dsafeulp ', dlamch('s') write(*,1000) ' dlamch(u) ', dlamch('u') c write(*,*) write(*,*) ' Single Precision results' write(*,1000) ' depsilon ', slamch('e') write(*,1000) ' dbase ', slamch('b') write(*,1000) ' dsafeulp ', slamch('s') write(*,1000) ' slamch(u) ', slamch('u') write(*,*) 1000 FORMAT( A12, 1X, 1P, E26.16 ) stop end
module SIAMFANLEquations using LinearAlgebra using LinearAlgebra.BLAS using SparseArrays using SuiteSparse using BandedMatrices using Printf export nsolsc export ptcsolsc export ptcsol export ptcsoli export nsol export nsoli export aasol export nofact export secant export armijosc export kl_gmres export kl_bicgstab export Katv export kstore export Orthogonalize! export EvalF! export solhistinit include("Tools/armijo.jl") include("Tools/PrintError.jl") include("Tools/FunctionJacobianEvals.jl") include("Tools/ManageStats.jl") include("Tools/IterationInit.jl") include("Tools/ErrorTest.jl") include("Tools/NewtonKrylov_Tools.jl") include("Tools/PTCTools.jl") include("Tools/PTCToolsi.jl") include("Tools/AA_Tools.jl") include("Solvers/Chapter1/nsolsc.jl") include("Solvers/Chapter1/ptcsolsc.jl") include("Solvers/Chapter1/secant.jl") include("Solvers/ptcsol.jl") include("Solvers/ptcsoli.jl") include("Solvers/nsol.jl") include("Solvers/nsoli.jl") include("Solvers/aasol.jl") include("Solvers/aa_qr_update.jl") include("Solvers/LinearSolvers/kl_gmres.jl") include("Solvers/LinearSolvers/kl_bicgstab.jl") include("Solvers/LinearSolvers/Orthogonalize!.jl") include("PlotsTables/printhist.jl") module TestProblems using LinearAlgebra using SparseArrays using SuiteSparse using BandedMatrices using AbstractFFTs using FFTW using Printf export #Functions fcos, fpatan, spitchfork, linatan, sptestp, sptest, ftanx, ftanxp, heqinit, heqf!, heqJ!, HeqFix!, simple!, jsimple!, JVsimple, heqbos!, setc!, chandprint, bvpinit, Fbvp!, Jbvp!, FBeam!, FBeamtd!, BeamJ!, BeamtdJ!, beaminit, ptctest, pdeF!, pdeJ!, Jvec2d, pdeinit, pdegminit, fishinit, fish2d, sintv, isintv, Pfish2d, Pvec2d, Lap2d, Dx2d, Dy2d, solexact, l2dexact, dxexact, dyexact, hardleft!, hardleftFix! include("TestProblems/Scalars/fcos.jl") include("TestProblems/Scalars/fpatan.jl") include("TestProblems/Scalars/spitchfork.jl") include("TestProblems/Scalars/linatan.jl") include("TestProblems/Scalars/ftanx.jl") include("TestProblems/Systems/simple!.jl") include("TestProblems/Systems/Fbvp!.jl") include("TestProblems/Systems/FBeam!.jl") include("TestProblems/Systems/Hequation.jl") include("TestProblems/Systems/EllipticPDE.jl") include("TestProblems/Systems/PDE_Tools.jl") end module Examples using SIAMFANLEquations using SIAMFANLEquations.TestProblems using LinearAlgebra using BandedMatrices export ptciBeam export ptcBeam export ivpBeam export BVP_solve export nsolheq export NsolPDE export NsoliPDE export PDE_aa include("Examples/ptciBeam.jl") include("Examples/ptcBeam.jl") include("Examples/ivpBeam.jl") include("Examples/BVP_solve.jl") include("Examples/NsolPDE.jl") include("Examples/NsoliPDE.jl") include("Examples/PDE_aa.jl") include("Examples/Internal/nsolheq.jl") end end # module
The Moses Gate has rapidly gained a great reputation in the Music Venue world. All major Tribute/Cover bands have & will perform this compact lively venue. The atmosphere is second to none! performed well whatever the genre.
#!/usr/bin/python # # Project Saturn # _____________________________________________________________________________ # # _oo. # August 2019 _.u[[/;:,. .odMMMMMM' # .o888UU[[[/;:-. .o@P^ MMM^ # buildingblocks.py oN88888UU[[[/;::-. dP^ # connect neural networks dNMMNN888UU[[[/;:--. .o@P^ # in space and time ,MMMMMMN888UU[[/;::-. o@^ # NNMMMNN888UU[[[/~.o@P^ # Markus Ernst 888888888UU[[[/o@^-.. # oI8888UU[[[/o@P^:--.. # .@^ YUU[[[/o@^;::---.. # oMP ^/o@P^;:::---.. # .dMMM .o@^ ^;::---... # dMMMMMMM@^` `^^^^ # YMMMUP^ # ^^ # _____________________________________________________________________________ # # # Copyright 2019 Markus Ernst # # 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. # # _____________________________________________________________________________ # ---------------- # import libraries # ---------------- # import tensorflow as tf import tensorflow.compat.v1 as tf tf.disable_eager_execution() import numpy as np # constant for cmd-line visualization INDENT = 0 VERBOSE = False # activation functions # ----- def softmax_cross_entropy(a, b, name): """ custom loss function based on cross-entropy that can be used within the error module """ return tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2( logits=a, labels=b, name=name)) def sigmoid_cross_entropy(a, b, name): """ custom loss function based on sigmoid cross-entropy that can be used within the error module """ return tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits=a, labels=b, name=name)) def lrn_relu(x, name=None, depth_radius=5, bias=1, alpha=1e-4, beta=0.5): """ custom activation function that combines ReLU with a Local Response Normalization and custom parameters""" return tf.nn.lrn(input=tf.nn.relu(x, name), depth_radius=5, bias=1, alpha=1e-4, beta=0.5, name=name) # ---------- # foundation # ---------- class InputContainer(list): """ InputContainer inherits from list. It allows for appending variables to InputContainer with the increment_add operator (+=) """ def __iadd__(self, other): self.append(other) return self class Module: """ Module is an abstract class. It is the base class of all following modules and constitutes the basic properties, IO and naming. @param name str, every module must have a name """ def __init__(self, name, *args, **kwargs): """ Creates Module object. Args: name: string, name of the Module """ self.inputs = InputContainer() self.outputs = {} self.name = name def output_exists(self, t): """ output_exists takes a Module object and an integer t and returns true iff self.outputs has an entry for timeslice t Args: t: int, indicates the timeslice Returns: ?: bool """ return t in self.outputs def need_to_create_output(self, t): """ need_to_create_output takes a Module object and an integer t and returns true iff t>=0 and there is not already an output for timeslice t. Args: t: int, indicates the timeslice Returns: ?: bool """ return True if t >= 0 and not self.output_exists(t) else False def create_output(self, t): """ create_output takes a Module object and an integer t. It creates outputs for the modules using its inputs Args: t: int, indicates the timeslice Returns: ?: None """ global INDENT global VERBOSE if VERBOSE: print("| " * INDENT + "creating output of {} at time {}".format(self.name, t)) INDENT += 1 for inp, dt in self.inputs: if inp.need_to_create_output(dt + t): inp.create_output(dt + t) tensors = self.input_tensors(t) self.outputs[t] = self.operation(*tensors) INDENT -= 1 if VERBOSE: print("| " * INDENT + "|{}".format(self.outputs[t])) def input_tensors(self, t): """ input_tensors takes a Module object and an integer t. It aggregates and returns a list of all inputs to Module at all timeslices in the future of timeslice t Args: t: int, indicates the timeslice Returns: ?: list of Module outputs """ return [inp.outputs[t + dt] for inp, dt in self.inputs if t + dt >= 0] class OperationModule(Module): """ Operation Module is an abstract class. It inherits from Module and can perform an operation on the output of another Module in the same time-slice. To inherit from it, overwrite the 'operation' method in the following way: The operation method should take as many parameters as there are modules connected to it and return a tensorflow tensor. These parameters are the output tensors of the previous modules in the same time slice. See the implementation of child classes for more information. """ def add_input(self, other): """ The method add_input connects the module to the output of another module in the same time slice. Args: other: Module Returns: self: OperationModule Example usage: mw_module.add_input(other_module) """ self.inputs += other, 0 return self def operation(self, x): """ The method operation is supposed to perform an operation on OperationModule's inputs, it has to be overwritten when inherting from this abstract class """ raise Exception("Calling abstract class, \ please overwrite this function") class TimeOperationModule(OperationModule): """ TimeOperationModule is an abstract class. It inherits from OperationModule and can perform an operation on the output of another Module in the a different time slice. For Usage, see OperationModule. TimeOperationModule and Operationmodule are separated to help the user better keep track of the connectivity in time. """ def add_input(self, other, t): """ The method add_input connects the module to the output of another module in the same OR ANY OTHER time slice. Connecting the module to a future time slice (ie t=1, 2...) makes no sense. @param other Module, an other module @param t int, the delta t which specify to which time slice to connect to Example usage: same timeslice mw_module.add_input(other_module, 0) previous timeslice mw_module.add_input(other_module, -1) """ self.inputs += other, t return self class FakeModule(TimeOperationModule): """ FakeModule is an abstract class. It inherits from TimeOperationModule and serves testing and visualization purposes. Performs no operation. """ def operation(self, *args): return self.name, args class VariableModule(OperationModule): """ VariableModule is an abstract class. It inherits from OperationModule and allows storing a tensorflow variable in addition to performing an operation. To inherit from it, overwrite the 'create_variables' method. The method is then automatically called by the constructor. See the implementation of child classes for more information. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.create_variables(self.name + "_var") def create_variables(self, name): """ The method create_variables is supposed to create a tensorflow variable, it has to be overwritten when inherting from this abstract class @param name str, name can be accessed from self """ raise Exception("Calling abstract class, overwrite this function") class TimeAddModule(TimeOperationModule): """ TimeAddModule inherits from TimeOperationModule. It can have as many inputs as required and sums their outputs. It does support recursions. """ def operation(self, *args): """ operation takes a TimeAddModule and the input modules Args: *args: list of modules Returns: ret: tensor, sum of input tensors """ ret = args[0] for e in args[1:]: ret = tf.add(ret, e, name=self.name) return ret class AddModule(OperationModule): """ AddModule inherits from OperationModule. It can have as many inputs as required and sums their outputs. It does not support recursions. """ def operation(self, *args): """ operation takes an AddModule and the input modules Args: *args: list of modules Returns: ret: tensor, sum of input tensors """ ret = args[0] for e in args[1:]: ret = tf.add(ret, e, name=self.name) return ret class TimeMultModule(TimeOperationModule): """ TimeMultModule inherits from TimeOperationModule. It can have as many inputs as required and multiplies their outputs. It does support recursions. """ def operation(self, *args): """ operation takes a TimeMultModule and the input modules Args: *args: list of modules Returns: ret: tensor, sum of input tensors """ ret = args[0] for e in args[1:]: ret = tf.multiply(ret, e, name=self.name) return ret class MultModule(OperationModule): """ MultModule inherits from OperationModule. It can have as many inputs as required and multiplies up their outputs. It does not support recursions. """ def operation(self, *args): """ operation takes an MultModule and the input modules Args: *args: list of modules Returns: ret: tensor, sum of input tensors """ ret = args[0] for e in args[1:]: ret = tf.multiply(ret, e, name=self.name) return ret class AbstractComposedModule(Module): """ AbstractComposedModule is an abstract class. It inherits from Module and lays the groundwork for a module comprised of other modules """ def __init__(self, *args, **kwargs): """ Creates an AbstractComposedModule Object """ super().__init__(*args, **kwargs) self.define_inner_modules(*args, **kwargs) self.inputs = self.input_module.inputs self.outputs = self.output_module.outputs def create_output(self, t): """ create_output takes an AbstractComposesModule object and an integer t. It creates outputs for the modules using its inputs """ self.output_module.create_output(t) def define_inner_modules(self, *args, **kwargs): raise Exception("Calling abstract class, overwrite this function") class TimeComposedModule(AbstractComposedModule, TimeOperationModule): """ TimeComposedModule is an abstract class. It inherits from AbstractComposedModule and TimeOperationModule. It allows when overwritten to create a module that is composed of other modules and accept recursions. See the implementation of ConvolutionalLayerModule for more info. The method 'define_inner_modules' must be overwritten, the attribute input_module must be set to the module which is the input of the composed module. The attribute output_module must be set to the module which is the output of the composed module """ pass class ComposedModule(AbstractComposedModule, OperationModule): """ ComposedModule is an abstract class. It inherits from AbstractComposedModule and OperationModule. It allows when overwritten to create a module that is composed of other modules and does not accept recursions. See the implementation of ConvolutionalLayerModule for more info. The method 'define_inner_modules' must be overwritten, the attribute input_module must be set to the module which is the input of the composed module, the attribute output_module must be set to the module which is the output of the composed module """ pass # -------------------------- # simple layer network parts # -------------------------- class NontrainableVariableModule(VariableModule): """ NontrainableVariableModule inherits from VariableModule. It holds on to a variable that is not trainable. Eventual input modules to NontrainableVariableModule are disregarded. [DEPRECATION INFO]: Was called ConstantVariableModule in earlier versions. """ def __init__(self, name, shape, dtype): """ Creates NontrainableVariableModule object Args: name: string, name of the module shape: array, shape of the variable to be stored dtype: data type """ self.shape = shape self.dtype = dtype super().__init__(name, shape, dtype) def operation(self, *args): """ operation takes a NontrainableVariableModule and returns the tensorflow variable which holds the variable created by create_variables """ return self.variable def create_variables(self, name): """ create_variables takes a NontrainableVariableModule and a name and instatiates a tensorflow variable with the shape specified in the constructor. It returns nothing. @param name str, name can be accessed from self """ self.variable = tf.Variable(tf.zeros(shape=self.shape, dtype=self.dtype), name=name, trainable=False) class BiasModule(VariableModule): """ BiasModule inherits from VariableModule. It holds on to a bias variable, that can be added to another tensor. Eventual input modules to BiasModule are disregarded. """ def __init__(self, name, bias_shape): """ Creates a BiasModule Object Args: name: string, name of the module bias_shape: array, shape of the bias, i.e. [B,H,W,C] """ self.bias_shape = bias_shape super().__init__(name, bias_shape) def operation(self, *args): """ operation takes a BiasModule and returns the tensorflow variable which holds the variable created by create_variables """ return self.bias def create_variables(self, name): """ create_variables takes a BiasModule and a name and instantiates a tensorflow variable with the shape specified in the constructor. It returns nothing. @param name str, name can be accessed from self """ self.bias = tf.Variable(tf.zeros(shape=self.bias_shape), name=name) class Conv2DModule(VariableModule): """ Conv2DModule inherits from VariableModule. It takes a single input module and performs a convolution. """ def __init__(self, name, filter_shape, strides, init_mean=None, init_std=None, padding='SAME'): """ Creates a Conv2DModule object Args: name: string, name of the module filter_shape: array, defines the shape of the filter strides: list of ints length 4, stride of the sliding window for each dimension of input init_mean: float, mean value of the weight initialization init_std: float, stddev value of the weight initialization padding: string from: "SAME", "VALID", type of padding algorithm to use. For more information see tf.nn.conv2d """ self.filter_shape = filter_shape self.init_mean = init_mean if init_mean is not None else 0.0 # initialize sqrt(2/n_in), for truncated sqrt(4/n_in) self.init_std = init_std if init_std is not None else \ np.sqrt(2.0 / np.prod(self.filter_shape[:-1])) super().__init__(name, filter_shape, strides, padding) self.strides = strides self.padding = padding def operation(self, x): """ operation takes a Conv2DModule and x, a 4D tensor and performs a convolution of the input module in the current time slice Args: x: 4D tensor [B,H,W,C] Returns: ?: 4D tensor [B,H,W,C] """ return tf.nn.conv2d(x, self.weights, strides=self.strides, padding=self.padding, name=self.name) def create_variables(self, name): """ create_variables takes a Conv2DModule and a name and instantiates a tensorflow variable for the filters (or weights) for the convolution as specified by the parameters given in the constructor. """ self.weights = tf.Variable(tf.random.truncated_normal( shape=self.filter_shape, mean=self.init_mean, stddev=self.init_std), name=name) # TODO: weight initializer with xavier glorot init class DepthwiseConv2DModule(Conv2DModule): """ DepthwiseConv2DModule inherits from Conv2DModule. It takes a single input module and performs a depthwise convolution. """ def operation(self, x): """ operation takes a Conv2DModule and x, a 4D tensor and performs a convolution of the input module in the current time slice Args: x: 4D tensor [B,H,W,C] Returns: ?: 4D tensor [B,H,W,C] """ return tf.nn.depthwise_conv2d(x, self.weights, strides=self.strides, padding=self.padding, name=self.name) class Conv2DTransposeModule(VariableModule): """ Conv2DTransposeModule inherits from VariableModule. It takes a single input module and performs a deconvolution. """ def __init__(self, name, filter_shape, strides, output_shape, init_mean=None, init_std=None, padding='SAME'): """ Creates a Conv2DTransposeModule object Args: name: string, name of the module filter_shape: array, defines the shape of the filter [height, width, output_channels, in_channels] output_shape: array, output shape of the deconvolution op strides: list of ints length 4, stride of the sliding window for each dimension of input init_mean: float, mean value of the weight initialization init_std: float, stddev value of the weight initialization padding: string from: "SAME", "VALID", type of padding algorithm to use. For more information see tf.nn.conv2d_transpose """ self.filter_shape = filter_shape self.init_mean = init_mean if init_mean is not None else 0.0 # initialize sqrt(2/n_in), for truncated sqrt(4/n_in) self.init_std = init_std if init_std is not None else \ np.sqrt(2.0 / np.prod( np.concatenate( [self.filter_shape[:-2], self.filter_shape[-1:]]))) super().__init__(name, filter_shape, strides, output_shape, padding) self.strides = strides self.output_shape = output_shape self.padding = padding def operation(self, x): """ operation takes a Conv2DTransposeModule and x, a 4D tensor and performs a deconvolution of the input module in the current time slice Args: x: 4D tensor [B,H,W,C] Returns: ?: 4D tensor [B,H,W,C] """ return tf.nn.conv2d_transpose(x, self.weights, self.output_shape, strides=self.strides, padding=self.padding, name=self.name) def create_variables(self, name): """ create_variables takes a Conv2DTransposeModule and a name and instantiates a tensorflow variable for the filters (or weights) of the deconvolution as specified by the parameters given in the constructor. """ self.weights = tf.Variable(tf.random.truncated_normal( shape=self.filter_shape, mean=self.init_mean, stddev=self.init_std), name=name) class MaxPoolingModule(OperationModule): """ MaxPoolingModule inherits from OperationModule. It takes a single input module and performs a maxpooling operation """ def __init__(self, name, ksize, strides, padding='SAME'): """ Creates a MaxPoolingModule object Args: name: string, name of the Module ksize: kernelsize (usually [1,2,2,1]) strides: padding: """ super().__init__(name, ksize, strides, padding) self.ksize = ksize self.strides = strides self.padding = padding def operation(self, x): """ operation takes a MaxPoolingModule and x, a 4D tensor and performs a maxpooling of the input module in the current time slice Args: x: 4D tensor, [B,H,W,C] Returns: ?: 4D tensor, [B,H,W,C] """ return tf.nn.max_pool2d(x, self.ksize, self.strides, self.padding, name=self.name) class GlobalAveragePoolingModule(OperationModule): """ GlobalAveragePoolingModule inherits from OperationModule. It takes a single input module and performs global average pooling on it. Useful for transferring the output of a convolutional layer to a fully connected layer and class activation mapping """ def operation(self, x): """ operation takes a GlobalAveragePoolingModule and x, a tensor and performs a global average pooling operation of the input module in the current time slice Args: x: 4D tensor, [B,H,W,C] Returns: ret: 2D tensor, [B,C] """ ret = tf.reduce_mean(x, [1, 2], name=self.name) return ret class FlattenModule(OperationModule): """ FlattenModule inherits from OperationModule. It takes a single input module and reshapes it. Useful for transfering the output of a convolutional layer to a fully connected layer at the end of the network """ def operation(self, x): """ operation takes a FlattenModule and x, a tensor and performs a flattening operation of the input module in the current time slice Args: x: 4D tensor, [B,H,W,C] Returns: ret: 2D tensor, [B,H*W*C] """ ret = tf.reshape(x, (x.shape[0], -1), name=self.name) return ret class ReshapeModule(OperationModule): """ ReshapeModule inherits from OperationModule. It takes a single input module and reshapes it. Useful for transfering the output of a fully connected layer to a convolutional layer """ def __init__(self, name, output_shape): """ Creates a FlattenModule object Args: name: string, name of the Module shape: list [B,H,W,C] """ super().__init__(name, output_shape) self.shape = output_shape def operation(self, x): """ operation takes a ReshapeModule and x, a tensor and performs a reshape operation of the input module in the current time slice Args: x: tensor Returns: ret: tensor, reshaped tensor x """ ret = tf.reshape(x, self.shape, name=self.name) return ret class FullyConnectedModule(VariableModule): """ FullyConnectedModule inherits from VariableModule. It takes a single module as input and performs a basic matrix multiplication without bias """ def __init__(self, name, in_size, out_size, init_mean=None, init_std=None): """ Creates FullyConnectedModule object Args: name: string, name of the Module in_size: int, the number of neurons in the previous layer out_size: int, the number of neurons in the current new layer init_mean: float, mean value of the weight initialization init_std: float, stddev value of the weight initialization """ self.in_size = in_size self.out_size = out_size self.init_mean = init_mean if init_mean is not None else 0.0 self.init_std = init_std if init_std is not None else \ np.sqrt(2.0 / (self.in_size + self.out_size)) super().__init__(name, in_size, out_size) def operation(self, x): """ operation takes a FullyConnectedModule, a tensor x and returns the matrix multiplication of the output of the input module by a weight matrix defined by create_variables Args: x: tensor Returns: ?: tensor, matrix multiplication of x times a weight matrix """ return tf.matmul(x, self.weights, name=self.name) def create_variables(self, name): """ create_variables takes a FullyConnectedModule object and a name and instantiates a tensorflow variable for the learnable weights of the matrix as specified by the parameters for sizes given in the constructor. """ self.weights = tf.Variable( tf.random.truncated_normal(shape=(self.in_size, self.out_size), mean=self.init_mean, stddev=self.init_std), name=name) class DropoutModule(OperationModule): """ DropoutModule inherits from OperationModule. It takes a single module as input and applies dropout to the output of the input module """ def __init__(self, name, keep_prob, noise_shape=None, seed=None): """ Creates DropoutModule object Args: name: string, name of the Module keep_prob: float, the probability that each element is kept. noise_shape: 1D int tensor, representing the shape for randomly generated keep/drop flags seed: int, make errors reproducable by submitting the random seed """ super().__init__(name, keep_prob, noise_shape, seed) self.keep_prob = keep_prob self.noise_shape = noise_shape self.seed = seed def operation(self, x): """ operation takes a DropoutModule, a tensor x and returns a tensor of the same shape with some entries randomly set to zero Args: x: 4D tensor, [B,H,W,C] Returns: ?: 4D tensor, same shape as x """ return tf.nn.dropout(x, rate=1 - self.keep_prob, noise_shape=self.noise_shape, seed=self.seed, name=self.name) class BatchNormalizationModule(OperationModule): """ BatchNormalizationModule inherits from OperationModule. It takes a single input module, performs Batch normalization and outputs a tensor of the same shape as the input. """ def __init__(self, name, n_out, is_training, beta_init=0.0, gamma_init=1.0, ema_decay_rate=0.5, moment_axes=[0, 1, 2], variance_epsilon=1e-3): """ Creates a BatchNormalizationModule Args: name: tensor, 4D BHWD input n_out: integer, depth of input is_training: boolean tf.Variable, true indicates training phase moment_axes: Array of ints. Axes along which to compute mean and variance. """ super().__init__(name, n_out, is_training, moment_axes, ema_decay_rate) self.n_out = n_out self.is_training = is_training self.moment_axes = moment_axes self.ema_decay_rate = ema_decay_rate self.variance_epsilon = variance_epsilon self.beta = tf.Variable(tf.constant(beta_init, shape=[self.n_out]), name=self.name + '_beta', trainable=True) self.gamma = tf.Variable(tf.constant(gamma_init, shape=[self.n_out]), name=self.name + '_gamma', trainable=True) def operation(self, x): """ operation takes a BatchNormalizationModule and a 4D BHWD input tensor and returns a tensor the same size Args: x: tensor, 4D [B,H,W,C] Returns: ret: batch-normalized tensor, 4D [B,H,W,C] """ # should be only over axis 0, if used for non-conv layers batch_mean, batch_var = tf.nn.moments(x, self.moment_axes, name=self.name + '_moments') ema = tf.train.ExponentialMovingAverage(decay=self.ema_decay_rate) def mean_var_with_update(): ema_apply_op = ema.apply([batch_mean, batch_var]) with tf.control_dependencies([ema_apply_op]): return tf.identity(batch_mean), tf.identity(batch_var) mean, var = tf.cond(self.is_training, mean_var_with_update, lambda: (ema.average(batch_mean), ema.average(batch_var))) ret = tf.nn.batch_normalization(x, mean, var, self.beta, self.gamma, self.variance_epsilon) return ret class PlaceholderModule(OperationModule): """ PlaceholderModule inherits from OperationModule and takes no input. It holds a place where the user can feed in a value to be used in the network graph. [Deprecation Info]: PlaceholderModule subsumes the functionality of ConstantPlaceholderModule """ def __init__(self, name, shape, dtype=tf.float32): super().__init__(name, shape, dtype) self.shape = shape self.dtype = dtype self.placeholder = tf.placeholder(shape=shape, dtype=dtype, name=self.name) def operation(self): return self.placeholder class TimeVaryingPlaceholderModule(PlaceholderModule): """ TimeVaryingPlaceholderModule inherits from PlaceholderModule and takes no input. It remembers the input which is fed by the user and rolls it so that at each time slice the network sees a new value """ def __init__(self, name, shape, dtype=tf.float32): """ Creates a TimeVaryingPlaceholderModule object Args: name: string, name of the Module shape: array, shape of the placeholder dtype: type, dtype of the placeholder """ super().__init__(name, shape, dtype) self.outputs[0] = self.placeholder def get_max_time(self): return len(self.outputs) max_time = property(get_max_time) def need_to_create_output(self, t): return True if t >= self.max_time else False def shift_by_one(self): for i in reversed(range(self.max_time)): self.outputs[i + 1] = self.outputs[i] self.outputs[0] = self.delayed(self.outputs[1]) def delayed(self, v): v_curr = tf.Variable(tf.zeros(shape=v.shape), trainable=False) v_prev = tf.Variable(tf.zeros(shape=v.shape), trainable=False) with tf.control_dependencies([v_prev.assign(v_curr)]): with tf.control_dependencies([v_curr.assign(v)]): v_curr = tf.identity(v_curr) v_prev = tf.identity(v_prev) return v_prev def create_output(self, t): global INDENT global VERBOSE if VERBOSE: print("| " * INDENT + "creating output of {} at time {}".format( self.name, t)) for i in range(t - self.max_time + 1): self.shift_by_one() if VERBOSE: print("| " * INDENT + "|{}".format(self.outputs[t])) class ActivationModule(OperationModule): """ ActivationModule inherits from OperationModule. It takes a single input module and applies and activation function to it """ def __init__(self, name, activation): """ Creates an ActivationModule object Args: name: string, name of the Module activation: callable, tf activation function """ super().__init__(name, activation) self.activation = activation def operation(self, x): """ operation takes a ActivationModule, a tensor x and returns the resulting tensor after applying the activation function Args: x: tensor, preactivation Returns: ?: tensor, same shape as x """ return self.activation(x, name=self.name) class MaxPoolingWithArgmaxModule(OperationModule): """ MaxPoolingWithArgmaxModule inherits from OperationModule. It takes a single input module and performs a maxpooling with argmax operation. """ def __init__(self, name, ksize, strides, padding='SAME'): """ Creates a MaxPoolingWithArgmaxModule object Args: name: string, name of the Module ksize: strides: padding: """ super().__init__(name, ksize, strides, padding) self.ksize = ksize self.strides = strides self.padding = padding def operation(self, x): """ operation takes a MaxPoolingModule and x, a 4D tensor and performs a maxpooling of the input module in the current time slice. Args: x: 4D tensor, [B,H,W,C] Returns: ?: 4D tensor, [B,H,W,C] """ out, mask = tf.nn.max_pool_with_argmax(x, self.ksize, self.strides, self.padding, name=self.name) self.mask = tf.stop_gradient(mask) return out class UnpoolingModule(OperationModule): """ UnpoolingModule inherits from OperationModule. It takes a exactly two input modules and performs an unpooling operation """ def __init__(self, name, ksize, strides, padding='SAME'): """ Creates a UnpoolingModule object Args: name: string, name of the Module ksize: strides: padding: """ super().__init__(name, ksize, strides, padding) self.ksize = ksize self.strides = strides self.padding = padding def operation(self, *args): """ operation takes a UnpoolingModule, a 4D tensor and|or a MaxPoolingWithArgmaxModule and performs a reverse maxpooling of the input module in the current time slice Args: x: 4D tensor [B,H,W,C] Returns: unpooled: 4D tensor [B,H,W,C], unpooled version of the input tensor """ MaxArgMax, _ = self.inputs[-1] argmax = MaxArgMax.mask x = args[0] unpool_shape = None batch_size = None x_shape = x.get_shape().as_list() argmax_shape = argmax.get_shape().as_list() assert not(x_shape[0] is None and batch_size is None), \ "must input batch_size if number of batch is alterable" if x_shape[0] is None: x_shape[0] = batch_size if argmax_shape[0] is None: argmax_shape[0] = x_shape[0] if unpool_shape is None: unpool_shape = [x_shape[i] * self.strides[i] for i in range(4)] self.unpool_shape = unpool_shape elif unpool_shape[0] is None: unpool_shape[0] = batch_size unpool = tf.get_variable(name=self.name, shape=[np.prod(unpool_shape)], initializer=tf.zeros_initializer(), trainable=False) self.unpool = unpool argmax = tf.cast(argmax, tf.int32) argmax = tf.reshape(argmax, [np.prod(argmax_shape)]) x = tf.reshape(x, [np.prod(argmax.get_shape().as_list())]) unpool = tf.scatter_update(unpool, argmax, x) unpool = tf.reshape(unpool, unpool_shape) return unpool class UnConvolutionModule(OperationModule): """ UnConvolutionModule inherits from VariableModule. It takes an input module and a Conv2DModule and performs a deconvolution using the weights. """ def __init__(self, name, filter_shape, strides, output_shape, padding='SAME'): """ Creates a UnConvolutionModule object Args: name: string, name of the module filter_shape: array, defines the shape of the filter output_shape: array, output shape of the deconvolution op strides: list of ints length 4, stride of the sliding window for each dimension of input padding: string from: "SAME", "VALID", type of padding algorithm to use. For more information see tf.nn.conv2d_transpose """ self.filter_shape = filter_shape super().__init__(name, filter_shape, strides, output_shape, padding) self.strides = strides self.output_shape = output_shape self.padding = padding def operation(self, *args): """ operation takes a UnConvolutionModule and x, a 4D tensor and performs a deconvolution of the input module in the current time slice Args: x: 4D tensor [B,H,W,C] Returns: ? """ C2D, _ = self.inputs[-1] weights = C2D.conv.weights x = args[0] return tf.nn.conv2d_transpose(x, weights, self.output_shape, strides=self.strides, padding=self.padding, name=self.name) # ----------------- # output statistics # ----------------- class ErrorModule(OperationModule): """ ErrorModule inherits from OperationModule. It takes two modules as input and computes an error (or applies any tensorflow operation on two and only two tensors) """ def __init__(self, name, error_func): """ Creates ErrorModule object Args: name: string, name of the Module error_func: callable, function that takes exactly 2 args, returns a tf.tensor """ super().__init__(name, error_func) self.error_func = error_func def operation(self, x1, x2): """ operation takes an ErrorModule, a tensor x1, a tensor x2 and returns the output of error_func as defined in __init__ Args: x1: tensor, logits x2: tensor, labels Returns: ?: 1D tensor, error-value """ return self.error_func(x1, x2, name=self.name) class LossModule(OperationModule): """ LossModule inherits from OperationModule. It takes one module as input and computes a any tensorflow operation on one and only one tensor """ def __init__(self, name, loss_func): """ Creates LossModule object Args: name: string, name of the Module error_func: callable, function that takes exactly 1 args, returns a tf.tensor """ super().__init__(name, loss_func) self.loss_func = loss_func def operation(self, x1): """ operation takes an LossModule and tensor x1 and returns the output of loss_function as defined in __init__ Args: x1: tensor Returns: ?: 1D tensor, loss-value """ return self.loss_func(x1, name=self.name) class BooleanComparisonModule(OperationModule): """ BooleanComparisonModule inherits from OperationModule. It takes two modules as input and compares both element-wise [DEPRECATION INFO]: Was called BoolClassificationModule in earlier versions """ def __init__(self, name): """ Creates BooleanComparisonModule object Args: name: string, name of the Module """ super().__init__(name) def operation(self, x1, x2): """ operation takes an BooleanComparisonModule, a tensor x1, a tensor x2 and returns the output of a tensor of bool of the same size Args: x1: tensor, logits x2: tensor, labels Returns: ?: tensor, bool """ return tf.equal(x1, x2) class OptimizerModule(OperationModule): """ OptimizerModule inherits from OperationModule. It takes a single module as input and can be used to train a network """ def __init__(self, name, optimizer, var_list=None): """ Creates OptimizerModule object Args: name: string, name of the Module optimizer: tf.train.Optimizer, an instance of an optimizer """ super().__init__(name, optimizer) self.optimizer = optimizer self.var_list = var_list def operation(self, x): """ operation takes a OptimizerModule, a tensor x and returns the output of the input module after adding a dependency in the tensorflow graph. Once the output of this module is computed the network is trained Args: x: tensor, most likely the last layer of your network Returns: ?: tensor x """ with tf.control_dependencies([self.optimizer.minimize(x, var_list=self.var_list)]): ret = tf.identity(x, name=self.name) return ret class BatchAccuracyModule(OperationModule): """ BatchAccuracyModule inherits from OperationModule. It takes a exactly two modules as input and computes the classification accuracy """ def operation(self, x1, x2): """ operation takes a BatchAccuracyModule, a tensor x1, a tensor x2 and returns the computed classification accuracy Args: x1: tensor, prediction of the network x2: tensor, targets of the supervised task Returns: ?: 1D tensor, accuracy """ correct_prediction = tf.equal(tf.argmax(x1, 1), tf.argmax(x2, 1)) return tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) class NHotBatchAccuracyModule(OperationModule): """ BatchAccuracyModule inherits from OperationModule. It takes a exactly two modules as input and computes the classification accuracy for multi Label problems """ def __init__(self, name, all_labels_true=True): """ Creates an NHotBatchAccuracyModule object Args: name: string, name of the Module all_labels_true: bool, False: ALL correctly predicted labels are considered for the accuracy True: Considered only, if all labels of an IMAGE are predicted correctly """ super().__init__(name, all_labels_true) self.all_labels_true = all_labels_true def operation(self, x1, x2): """ operation takes a BatchAccuracyModule, a tensor x1, a tensor x2 and returns a computed classification accuracy Args: x1: tensor, prediction of the network x2: tensor, multi-hot targets of the supervised task Returns: accuracy1: perc. of all labels, that are predicted correctly accuracy2: perc. of images, where all labels are predicted correctly """ n = tf.count_nonzero(x2[-1], dtype=tf.int32) nlabels = tf.shape(x2)[-1] x1_topk_ind = tf.nn.top_k(x1, k=n).indices x1_nhot = tf.reduce_sum(tf.one_hot(x1_topk_ind, depth=nlabels), axis=-2) correct_prediction = tf.equal(x1_nhot, x2) if self.all_labels_true: all_labels = tf.reduce_min(tf.cast(correct_prediction, tf.float32), -1) accuracy2 = tf.reduce_mean(all_labels) return accuracy2 else: accuracy1 = tf.reduce_sum(tf.cast(correct_prediction, tf.float32), -1) accuracy1 = (accuracy1 - tf.cast((nlabels - 2*n), tf.float32)) / \ tf.cast((2*n), tf.float32) accuracy1 = tf.reduce_mean(accuracy1) return accuracy1 # --------------------------- # complex layer network parts # --------------------------- # TODO: Write a composed module for CAM which basically is the last part of a # network but has a method that computes activation maps if desired class ConvolutionalLayerModule(ComposedModule): """ ConvolutionalLayerModule inherits from ComposedModule. This composed module performs a convolution and applies a bias and an activation function. It does not allow recursions """ def define_inner_modules(self, name, activation, filter_shape, strides, bias_shape, padding='SAME'): self.input_module = Conv2DModule(name + "_conv", filter_shape, strides, padding=padding) self.bias = BiasModule(name + "_bias", bias_shape) self.preactivation = AddModule(name + "_preactivation") self.output_module = ActivationModule(name + "_output", activation) self.preactivation.add_input(self.input_module) self.preactivation.add_input(self.bias) self.output_module.add_input(self.preactivation) class ConvolutionalLayerWithBatchNormalizationModule(ComposedModule): """ ConvolutionalLayerWithBatchNormalizationModule inherits from ComposedModule. This composed module performs a convolution and applies a bias then BatchNormalization and an activation function. It does not allow recursions """ def define_inner_modules(self, name, n_out, is_training, beta_init, gamma_init, ema_decay_rate, activation, filter_shape, strides, bias_shape, padding='SAME'): self.input_module = Conv2DModule(name + "_conv", filter_shape, strides, padding=padding) # self.bias = BiasModule(name + "_bias", bias_shape) # self.preactivation = AddModule(name + "_preactivation") self.batchnorm = BatchNormalizationModule(name + "_batchnorm", n_out, is_training, beta_init, gamma_init, ema_decay_rate, moment_axes=[0, 1, 2], variance_epsilon=1e-3) self.output_module = ActivationModule(name + "_output", activation) # self.preactivation.add_input(self.input_module) # self.preactivation.add_input(self.bias) self.batchnorm.add_input(self.input_module) self.output_module.add_input(self.batchnorm) class TimeConvolutionalLayerModule(TimeComposedModule): """ TimeConvolutionalLayerModule inherits from TimeComposedModule. This composed module adds up inputs, performs a convolution and applies a bias and an activation function. It does allow recursions on two different hooks (input and preactivation). """ def define_inner_modules(self, name, activation, filter_shape, strides, bias_shape, w_init_m=None, w_init_std=None, padding='SAME'): # multiply_inputs=True self.input_module = TimeAddModule(name + "_input") self.conv = Conv2DModule(name + "_conv", filter_shape, strides, w_init_m, w_init_std, padding=padding) self.bias = BiasModule(name + "_bias", bias_shape) self.preactivation = TimeAddModule(name + "_preactivation") # self.preactivation_plus = TimeAddModule( # name + "_preactivation_plus") self.output_module = ActivationModule(name + "_output", activation) # wiring of modules self.conv.add_input(self.input_module) self.preactivation.add_input(self.conv, 0) self.preactivation.add_input(self.bias, 0) self.output_module.add_input(self.preactivation) class TimeConvolutionalLayerWithBatchNormalizationModule(TimeComposedModule): """ TimeConvolutionalLayerWithBatchNormalizationModule inherits from TimeComposedModule. This composed module performs a convolution, applies a bias, batchnormalizes the preactivation and then applies an activation function. It does allow recursions on two different hooks (input and preactivation) """ def define_inner_modules(self, name, n_out, is_training, beta_init, gamma_init, ema_decay_rate, activation, filter_shape, strides, bias_shape, w_init_m=None, w_init_std=None, padding='SAME'): self.input_module = TimeAddModule(name + "_input") self.conv = Conv2DModule(name + "_conv", filter_shape, strides, w_init_m, w_init_std, padding=padding) # self.bias = BiasModule(name + "_bias", bias_shape) self.preactivation = TimeAddModule(name + "_preactivation") self.batchnorm = BatchNormalizationModule(name + "_batchnorm", n_out, is_training, beta_init, gamma_init, ema_decay_rate, moment_axes=[0, 1, 2], variance_epsilon=1e-3) self.output_module = ActivationModule(name + "_output", activation) # wiring of modules self.conv.add_input(self.input_module) self.preactivation.add_input(self.conv, 0) # self.preactivation.add_input(self.bias) self.batchnorm.add_input(self.preactivation) self.output_module.add_input(self.batchnorm) class FullyConnectedLayerModule(ComposedModule): """ FullyConnectedLayerModule inherits from ComposedModule. This composed module performs a full connection and applies a bias and an activation function. It does not allow recursions. """ def define_inner_modules(self, name, activation, in_size, out_size, w_init_m=None, w_init_std=None): self.input_module = FullyConnectedModule(name + "_fc", in_size, out_size, w_init_m, w_init_std) self.bias = BiasModule(name + "_bias", (1, out_size)) self.preactivation = AddModule(name + "_preactivation") self.output_module = ActivationModule(name + "_output", activation) self.preactivation.add_input(self.input_module) self.preactivation.add_input(self.bias) self.output_module.add_input(self.preactivation) class FullyConnectedLayerWithBatchNormalizationModule(ComposedModule): """ FullyConnectedLayerWithBatchNormalizationModule inherits from ComposedModule. This composed module performs a full connection and applies a bias batchnormalizes the preactivation and an activation function. It does not allow recursions. """ def define_inner_modules(self, name, n_out, is_training, beta_init, gamma_init, ema_decay_rate, activation, in_size, out_size, w_init_m=None, w_init_std=None): self.input_module = FullyConnectedModule(name + "_fc", in_size, out_size, w_init_m, w_init_std) # self.bias = BiasModule(name + "_bias", (1, out_size)) self.preactivation = AddModule(name + "_preactivation") self.batchnorm = BatchNormalizationModule(name + "_batchnorm", n_out, is_training, beta_init, gamma_init, ema_decay_rate, moment_axes=[0], variance_epsilon=1e-3) self.output_module = ActivationModule(name + "_output", activation) self.preactivation.add_input(self.input_module) # self.preactivation.add_input(self.bias) self.batchnorm.add_input(self.preactivation) self.output_module.add_input(self.batchnorm) # --------------------- # input transformations # --------------------- class CropModule(OperationModule): """ CropModule inherits from OperationModule. It takes a single input module and resizes it using a central crop. """ def __init__(self, name, height, width): """ Creates a CropModule object Args: name: string, name of the Module height: int, desired output image height weight: int, desired output image width """ super().__init__(name, height, width) self.height = height self.width = width def operation(self, x): """ operation takes a CropModule and x, a tensor and performs a cropping operation of the input module in the current time slice Args: x: 4D tensor, [B,H,W,C] Returns: ret: 4D tensor, [B, self.height, self.width, C] """ ret = tf.image.resize_image_with_crop_or_pad(x, self.height, self.width) return ret class CropAndConcatModule(TimeOperationModule): """ CropAndConcatModule inherits from TimeOperationModule. It takes exactly 2 input modules, crops the output of input module 1 to the size of the output of input module 2 and concatenates them along a predefined axis """ def __init__(self, name, axis=3, *args): """ Creates a CropAndConcatModule Args: name: string, name of the Module axis: int, dimension along which the concatination takes place """ super().__init__(name) self.axis = axis def operation(self, x1, x2): """ operation takes a CropAndConcatModule, tensor x1, tensor x2 and crops and concatenates them together Args: x1: tensor x2: tensor, same shape as x1 Returns: ?: tensor (c,x,y,d), same c,x,y as tensor x1, d tensor x1 + tensor x2 """ x1_shape = tf.shape(x1) x2_shape = tf.shape(x2) # offsets for the top left corner of the crop offsets = [0, (x1_shape[1] - x2_shape[1]) // 2, (x1_shape[2] - x2_shape[2]) // 2, 0] size = [-1, x2_shape[1], x2_shape[2], -1] x1_crop = tf.slice(x1, offsets, size) return tf.concat([x1_crop, x2], self.axis) class AugmentModule(ComposedModule): """ AugmentModule inherits from ComposedModule. This composed module performs a rotation of an image, changes its image properties and crops it. It does not allow recursions """ def define_inner_modules(self, name, is_training, image_width, angle_max=10., brightness_max_delta=.5, contrast_lower=.5, contrast_upper=1., hue_max_delta=.05): self.input_module = RotateImageModule('_rotate', is_training, angle_max) self.centercrop = AugmentCropModule('_centercrop', is_training, image_width//10*5, image_width//10*5) self.imagestats = RandomImageStatsModule('_imageprops', is_training, brightness_max_delta, contrast_lower, contrast_upper, hue_max_delta) self.output_module = RandomCropModule('_randomcrop', is_training, image_width//10*4, image_width//10*4) self.centercrop.add_input(self.input_module) self.imagestats.add_input(self.centercrop) self.output_module.add_input(self.imagestats) class RotateImageModule(OperationModule): """ RotateImageModule inherits from OperationModule. It takes a single module as input and applies a rotation. """ def __init__(self, name, is_training, angle_max, random_seed=None): """ Creates RotateImageModule object Args: name: string, name of the Module is_training: bool, indicates training or testing angle_max: float, angle at 1 sigma random_seed: int, An operation-specific seed """ super().__init__(name, is_training, angle_max, random_seed) self.is_training = is_training self.angle_max = angle_max self.random_seed = random_seed def operation(self, x): """ operation takes a RotateImageModule, a tensor x and returns a tensor of the same shape. Args: x: tensor, [B,H,W,C] Returns: ?: tensor, same shape as x """ batch_size = x.shape[0:1] # angles have to be in terms of pi angles = (2*np.pi / 360.) * self.angle_max * tf.random_normal( batch_size, mean=0.0, stddev=1.0, dtype=tf.float32, seed=self.random_seed, name=None ) def apply_transformation(): return tf.contrib.image.rotate( x, angles, interpolation='NEAREST' ) def ret_identity(): return tf.identity(x) rotated_x = tf.cond(self.is_training, apply_transformation, ret_identity) return rotated_x class RandomImageStatsModule(OperationModule): """ RandomImageStatsModule inherits from OperationModule. It takes a single module as input and randomly assigns new image statistics """ def __init__(self, name, is_training, brightness_max_delta, contrast_lower, contrast_upper, hue_max_delta, random_seed=None): """ Creates RandomImageStatsModule object Args: name: string, name of the Module is_training: bool, indicates training or testing brightness_max_delta: float, must be non-negative. contrast_lower: float, Lower bound for the random contrast factor. contrast_upper: float, Upper bound for the random contrast factor. hue_max_delta: float, Maximum value for the random delta. random_seed: int, An operation-specific seed """ super().__init__(name, is_training, brightness_max_delta, contrast_lower, contrast_upper, hue_max_delta, random_seed) self.is_training = is_training self.brightness_max_delta = brightness_max_delta self.contrast_lower = contrast_lower self.contrast_upper = contrast_upper self.hue_max_delta = hue_max_delta self.random_seed = random_seed def operation(self, x): """ operation takes a RandomImageStatsModule, a tensor x and returns a tensor of the same shape. Args: x: tensor, RGBA image Returns: ?: tensor, same shape as x """ bright_x = tf.image.random_brightness( x, self.brightness_max_delta, seed=self.random_seed ) contrast_x = tf.image.random_contrast( bright_x, self.contrast_lower, self.contrast_upper, seed=self.random_seed ) hue_x = tf.image.random_hue( contrast_x, self.hue_max_delta, seed=self.random_seed ) flipped_x = tf.image.random_flip_left_right( hue_x, seed=self.random_seed ) def apply_transformation(): return tf.map_fn(tf.image.random_flip_left_right, contrast_x) def ret_identity(): return tf.identity(x) flipped_x = tf.cond(self.is_training, apply_transformation, ret_identity) return flipped_x class RandomCropModule(OperationModule): """ RandomCropModule inherits from OperationModule. It takes a single input module and resizes it by cropping a random portion of the image. """ def __init__(self, name, is_training, height, width): """ Creates a RandomCropModule object Args: name: string, name of the Module is_training: bool, indicates training or testing height: int, desired output image height weight: int, desired output image width """ super().__init__(name, height, width) self.is_training = is_training self.height = height self.width = width def operation(self, x): """ operation takes a RandomCropModule and x, a tensor and performs a cropping operation of the input module in the current time slice Args: x: tensor, [B,H,W,C] Returns: ret: tensor, [B,self.height,self.width,C] """ batchsize = x.shape[0] channels = x.shape[-1] def apply_transformation(): return tf.random_crop(x, [batchsize, self.height, self.width, channels]) def ret_identity(): return tf.identity(x) ret = tf.cond(self.is_training, apply_transformation, ret_identity) return ret class AugmentCropModule(OperationModule): """ AugmentCropModule inherits from OperationModule. It takes a single input module and resizes it. It is similar to CropModule, but aware of is_training. """ def __init__(self, name, is_training, height, width): """ Creates a CropModule object Args: name: string, name of the Module is_training: bool, indicates training or testing height: int, desired output image height weight: int, desired output image width """ super().__init__(name, height, width) self.is_training = is_training self.height = height self.width = width def operation(self, x): """ operation takes a AugmentCropModule and x, a tensor and performs a cropping operation of the input module in the current time slice. Args: x: tensor, [B,H,W,C] Returns: ret: tensor, [B,self.height,self.width,C] """ def apply_transformation(): return tf.image.resize_image_with_crop_or_pad(x, self.height, self.width) # very specific transformation for the os-ycb dataset def apply_alt_transformation(): return tf.image.resize_image_with_crop_or_pad(x, self.height//5*4, self.width//5*4) ret = tf.cond(self.is_training, apply_transformation, apply_alt_transformation) return ret class InputCanvasModule(OperationModule): """ InputCanvasModule inherits from OperationModule and takes no input. It holds a place where the user can feed in a value to be used in the graph. Additionally it creates a trainable variable of the same size to visualize network internals. """ def __init__(self, name, shape, trainable_input, dtype=tf.float32): super().__init__(name, shape, trainable_input, dtype) self.shape = shape self.dtype = dtype self.trainable_input = trainable_input self.placeholder = tf.placeholder(shape=shape, dtype=dtype, name=self.name) self.canvas = tf.Variable(tf.random.truncated_normal(shape=self.shape, mean=0.0, stddev=0.1), name=name) # self.canvas = tf.Variable(tf.zeros(shape=self.shape), name=name) # self.canvas = tf.get_variable(name=self.name, # shape=[],dtype=tf.float32) def operation(self): def return_placeholder(): return tf.cast(self.placeholder, tf.float32) def return_trainable_input(): return self.canvas ret = tf.cond(self.trainable_input, return_trainable_input, return_placeholder) return ret class InputSwitchModule(OperationModule): """ InputSwitchModule inherits from OperationModule and takes one input. It holds a place where the user can feed in a value to be used in the graph. """ def __init__(self, name, shape, alt_input, dtype=tf.float32): super().__init__(name, shape, alt_input, dtype) self.shape = shape self.dtype = dtype self.alt_input = alt_input self.placeholder = tf.placeholder(shape=shape, dtype=dtype, name=self.name) def operation(self, x): def return_placeholder(): return tf.cast(self.placeholder, tf.float32) def return_alt_input(): return x ret = tf.cond(self.alt_input, return_alt_input, return_placeholder) return ret class SwitchModule(OperationModule): """ SwitchModule inherits from OperationModule. It takes exactly two modules as an input and a boolean to decide which input to forward """ def __init__(self, name, alt_input, dtype=tf.float32): super().__init__(name, alt_input) self.alt_input = alt_input self.dtype = dtype def operation(self, x1, x2): def return_input1(): return tf.cast(x1, self.dtype) def return_input2(): return tf.cast(x2, self.dtype) ret = tf.cond(self.alt_input, return_input2, return_input1) return ret class NormalizationModule(OperationModule): """ NormalizationModule inherits from OperationModule. It takes a single module as input and applies normalization to it (i.e. values between inp_min and inp_max) """ def __init__(self, name, inp_max=1, inp_min=-1, dtype=tf.float32): """ Creates NormalizationModule object Args: name: string, name of the Module inp_max: float, maximum of the rescaled range, default: 1 inp_min: float, minimum of the rescaled range, default: -1 dtype: type, dtype of the tensor """ super().__init__(name, inp_max, inp_min) self.inp_max = inp_max self.inp_min = inp_min self.dtype = dtype def operation(self, x): """ operation takes a NormalizationModule, a tensor x and returns a tensor of the same shape with values rescaled between inp_max, inp_min Args: x: 4D tensor, [B,H,W,C] Returns: ?: 4D tensor, [B,H,W,C], same shape as x """ casted_x = tf.cast(x, dtype=self.dtype) def apply_transformation(): rescaled_x = (self.inp_max-self.inp_min) * \ (casted_x - tf.reduce_min(casted_x)) / \ (tf.reduce_max(casted_x) - tf.reduce_min(casted_x)) + \ self.inp_min return rescaled_x def ret_identity(): return casted_x ret = tf.cond(tf.equal(tf.reduce_max(casted_x), 0.), ret_identity, apply_transformation) # TODO: rethink this pis = tf.image.per_image_standardization(casted_x) return ret class PixelwiseNormalizationModule(OperationModule): """ PixelwiseNormalizationModule inherits from OperationModule. It takes a single module as input and applies pixel wise normalization across the dataset. """ def __init__(self, name, input_shape, dtype=tf.float32): """ Creates PixelwiseNormalizationModule object Args: name: string, name of the Module dtype: type, dtype of the tensor """ super().__init__(name) self.dtype = dtype self.sxx = tf.Variable(tf.ones(input_shape), trainable=False) self.sx = tf.Variable(tf.zeros(input_shape), trainable=False) self.n = tf.Variable(1., trainable=False) def operation(self, x): """ operation takes a PixelwiseNormalizationModule, a tensor x and returns a tensor of the same shape with values rescaled between based on the input statistics. If statistics are not assigned, operation just returns the original tensor Args: x: tensor, RGBA image Returns: ?: tensor, same shape as x """ # Var = (SumSq − (Sum × Sum) / n) / (n − 1) sd = tf.math.sqrt( ((self.sxx - (tf.math.square(self.sx)) / self.n)) / (self.n - 1) ) m = self.sx/self.n rescaled_x = (tf.cast(x, self.dtype) - m)/sd non_nan = tf.where(tf.math.is_nan(rescaled_x), tf.zeros_like(rescaled_x), rescaled_x) clipped = tf.clip_by_value(non_nan, clip_value_min=-5*sd, clip_value_max=+5*sd, ) return clipped if __name__ == '__main__': # visualize recurrent sample structure in cmd-line f1 = FakeModule("input") f2 = FakeModule("conv1") f3 = FakeModule("tanh1") f4 = FakeModule("conv2") f5 = FakeModule("relu2") f2.add_input(f1, 0) f2.add_input(f2, -1) f2.add_input(f4, -1) f3.add_input(f2, 0) f4.add_input(f3, 0) f4.add_input(f4, -1) f5.add_input(f4, 0) f5.create_output(1) fs = [f1, f2, f3, f4, f5] for f in fs: print(f.name, "---", f.outputs)
Formal statement is: lemma locally_constant: assumes "connected S" shows "locally (\<lambda>U. f constant_on U) S \<longleftrightarrow> f constant_on S" (is "?lhs = ?rhs") Informal statement is: If $S$ is connected, then $f$ is locally constant on $S$ if and only if $f$ is constant on $S$.
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, MagicHash, FlexibleInstances, FlexibleContexts, UnboxedTuples, DeriveDataTypeable, CPP, BangPatterns #-} #ifdef __GLASGOW_HASKELL__ #if __GLASGOW_HASKELL__ < 610 {-# OPTIONS_GHC -frewrite-rules #-} #else {-# OPTIONS_GHC -fenable-rewrite-rules #-} #endif #endif ----------------------------------------------------------------------------- -- | -- Module : Data.Array.CArray.Base -- Copyright : (c) 2001 The University of Glasgow -- (c) 2008 Jed Brown -- License : BSD-style -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable -- -- This module provides both the immutable 'CArray' and mutable 'IOCArray'. The -- underlying storage is exactly the same - pinned memory on the GC'd heap. -- Elements are stored according to the class 'Storable'. You can obtain a -- pointer to the array contents to manipulate elements from languages like C. -- -- 'CArray' is 16-byte aligned by default. If you create a 'CArray' with -- 'unsafeForeignPtrToCArray' then it may not be aligned. This will be an issue -- if you intend to use SIMD instructions. -- -- 'CArray' is similar to 'Data.Array.Unboxed.UArray' but slower if you stay -- within Haskell. 'CArray' can handle more types and can be used by external -- libraries. -- -- 'IOCArray' is equivalent to 'Data.Array.Storable.StorableArray' and similar -- to 'Data.Array.IO.IOUArray' but slower. 'IOCArray' has O(1) versions of -- 'unsafeFreeze' and 'unsafeThaw' when converting to/from 'CArray'. ----------------------------------------------------------------------------- module Data.Array.CArray.Base where import Control.Applicative import Control.Monad import Data.Ix.Shapable import Data.Array.Base import Data.Array.MArray import Data.Array.IArray () import qualified Data.ByteString.Internal as S import Data.Binary import Data.Complex import Data.List import System.IO.Unsafe (unsafePerformIO) import Foreign.Storable import Foreign.ForeignPtr import Foreign.Ptr import Foreign.Marshal.Alloc import Foreign.Marshal.Array (copyArray) import Data.Word () import Data.Generics (Data(..), Typeable(..)) import GHC.Ptr (Ptr(..)) import GHC.ForeignPtr (ForeignPtr(..), mallocPlainForeignPtrBytes) -- | The immutable array type. data CArray i e = CArray !i !i Int !(ForeignPtr e) deriving (Data, Typeable) -- | Absolutely equivalent representation, but used for the mutable interface. data IOCArray i e = IOCArray !i !i Int !(ForeignPtr e) deriving (Data, Typeable) instance Storable e => MArray IOCArray e IO where getBounds (IOCArray l u _ _) = return (l,u) getNumElements (IOCArray _ _ n _) = return n newArray (l,u) e0 = do fp <- mallocForeignPtrArrayAligned n withForeignPtr fp $ \a -> sequence_ [pokeElemOff a i e0 | i <- [0 .. n - 1]] return (IOCArray l u n fp) where n = rangeSize (l,u) unsafeNewArray_ (l,u) = do let n = rangeSize (l,u) fp <- mallocForeignPtrArrayAligned n return (IOCArray l u n fp) newArray_ = unsafeNewArray_ unsafeRead (IOCArray _ _ _ fp) i = withForeignPtr fp $ \a -> peekElemOff a i unsafeWrite (IOCArray _ _ _ fp) i e = withForeignPtr fp $ \a -> pokeElemOff a i e -- | The pointer to the array contents is obtained by 'withCArray'. -- The idea is similar to 'ForeignPtr' (used internally here). -- The pointer should be used only during execution of the 'IO' action -- retured by the function passed as argument to 'withCArray'. withCArray :: CArray i e -> (Ptr e -> IO a) -> IO a withCArray (CArray _ _ _ fp) f = withForeignPtr fp f withIOCArray :: IOCArray i e -> (Ptr e -> IO a) -> IO a withIOCArray (IOCArray _ _ _ fp) f = withForeignPtr fp f -- | If you want to use it afterwards, ensure that you -- 'touchCArray' after the last use of the pointer, -- so the array is not freed too early. touchIOCArray :: IOCArray i e -> IO () touchIOCArray (IOCArray _ _ _ fp) = touchForeignPtr fp -- | /O(1)/ Construct a 'CArray' from an arbitrary 'ForeignPtr'. It is -- the caller's responsibility to ensure that the 'ForeignPtr' points to -- an area of memory sufficient for the specified bounds. unsafeForeignPtrToCArray :: Ix i => ForeignPtr e -> (i,i) -> IO (CArray i e) unsafeForeignPtrToCArray p (l,u) = return (CArray l u (rangeSize (l,u)) p) -- | /O(1)/ Construct a 'CArray' from an arbitrary 'ForeignPtr'. It is -- the caller's responsibility to ensure that the 'ForeignPtr' points to -- an area of memory sufficient for the specified bounds. unsafeForeignPtrToIOCArray :: Ix i => ForeignPtr e -> (i,i) -> IO (IOCArray i e) unsafeForeignPtrToIOCArray p (l,u) = return (IOCArray l u (rangeSize (l,u)) p) -- | /O(1)/ Extract ForeignPtr from a CArray. toForeignPtr :: CArray i e -> (Int, ForeignPtr e) toForeignPtr (CArray _ _ n fp) = (n, fp) -- | /O(1)/ Turn a CArray into a ByteString. Unsafe because it uses -- 'castForeignPtr' and thus is not platform independent. unsafeCArrayToByteString :: (Storable e) => CArray i e -> S.ByteString unsafeCArrayToByteString (CArray _ _ l fp) = go undefined fp where go :: (Storable e) => e -> ForeignPtr e -> S.ByteString go dummy fp' = S.fromForeignPtr (castForeignPtr fp') 0 (l * sizeOf dummy) -- | /O(1)/ Turn a ByteString into a CArray. Unsafe because it uses -- 'castForeignPtr' and thus is not platform independent. Returns 'Nothing' if -- the range specified is larger than the size of the ByteString or the start of -- the ByteString does not fulfil the alignment requirement of the resulting -- CArray (as specified by the Storable instance). unsafeByteStringToCArray :: (Ix i, Storable e, IArray CArray e) => (i,i) -> S.ByteString -> Maybe (CArray i e) unsafeByteStringToCArray lu bs = go undefined lu where go :: (Ix i, Storable e, IArray CArray e) => e -> (i,i) -> Maybe (CArray i e) go dummy (l,u) | safe = Just (CArray l u n fp) | otherwise = Nothing where n = rangeSize (l,u) !((ForeignPtr addr contents), off, len) = S.toForeignPtr bs !p@(Ptr addr') = Ptr addr `plusPtr` off fp = ForeignPtr addr' contents safe = sizeOf dummy * n <= len && p == p `alignPtr` alignment dummy copy :: (Ix i, Storable e) => CArray i e -> IO (CArray i e) copy ain@(CArray l u n _) = createCArray (l,u) $ \op -> withCArray ain $ \ip -> copyArray op ip n freezeIOCArray :: (Ix i, Storable e) => IOCArray i e -> IO (CArray i e) freezeIOCArray = unsafeFreezeIOCArray >=> copy unsafeFreezeIOCArray :: (Ix i) => IOCArray i e -> IO (CArray i e) unsafeFreezeIOCArray (IOCArray l u n fp) = return (CArray l u n fp) thawIOCArray :: (Ix i, Storable e) => CArray i e -> IO (IOCArray i e) thawIOCArray = copy >=> unsafeThawIOCArray unsafeThawIOCArray :: (Ix i) => CArray i e -> IO (IOCArray i e) unsafeThawIOCArray (CArray l u n fp) = return (IOCArray l u n fp) -- Since we can remove the (Storable e) restriction for these, the rules are -- compact and general. {-# RULES "unsafeFreeze/IOCArray" unsafeFreeze = unsafeFreezeIOCArray "unsafeThaw/IOCArray" unsafeThaw = unsafeThawIOCArray #-} -- Since we can't parameterize the rules with the (Storable e) constraint, we -- have to specialize manually. This is unfortunate since it is less general. {-# RULES "freeze/IOCArray/Int" freeze = freezeIOCArray :: (Ix i) => IOCArray i Int -> IO (CArray i Int) "freeze/IOCArray/Float" freeze = freezeIOCArray :: (Ix i) => IOCArray i Float -> IO (CArray i Float) "freeze/IOCArray/Double" freeze = freezeIOCArray :: (Ix i) => IOCArray i Double -> IO (CArray i Double) "thaw/IOCArray/Int" thaw = thawIOCArray :: (Ix i) => CArray i Int -> IO (IOCArray i Int) "thaw/IOCArray/Float" thaw = thawIOCArray :: (Ix i) => CArray i Float -> IO (IOCArray i Float) "thaw/IOCArray/Double" thaw = thawIOCArray :: (Ix i) => CArray i Double -> IO (IOCArray i Double) #-} instance Storable e => IArray CArray e where {-# INLINE bounds #-} bounds (CArray l u _ _) = (l,u) {-# INLINE numElements #-} numElements (CArray _ _ n _) = n {-# NOINLINE unsafeArray #-} unsafeArray lu ies = unsafePerformIO $ unsafeArrayCArray lu ies (zeroElem (undefined :: e)) {-# INLINE unsafeAt #-} unsafeAt (CArray _ _ _ fp) i = S.inlinePerformIO $ withForeignPtr fp $ \a -> peekElemOff a i {-# NOINLINE unsafeReplace #-} unsafeReplace arr ies = unsafePerformIO $ unsafeReplaceCArray arr ies {-# NOINLINE unsafeAccum #-} unsafeAccum f arr ies = unsafePerformIO $ unsafeAccumCArray f arr ies {-# NOINLINE unsafeAccumArray #-} unsafeAccumArray f e0 lu ies = unsafePerformIO $ unsafeAccumArrayCArray f e0 lu ies -- | Hackish way to get the zero element for a Storable type. {-# NOINLINE zeroElem #-} zeroElem :: Storable a => a -> a zeroElem u = unsafePerformIO $ do allocaBytes n $ \p -> do sequence_ [pokeByteOff p off (0 :: Word8) | off <- [0 .. n - 1] ] peek (castPtr p) where n = sizeOf u {-# INLINE unsafeArrayCArray #-} unsafeArrayCArray :: (MArray IOCArray e IO, Storable e, Ix i) => (i,i) -> [(Int, e)] -> e -> IO (CArray i e) unsafeArrayCArray lu ies default_elem = do marr <- newArray lu default_elem sequence_ [unsafeWrite marr i e | (i, e) <- ies] unsafeFreezeIOCArray marr {-# INLINE unsafeReplaceCArray #-} unsafeReplaceCArray :: (MArray IOCArray e IO, Storable e, Ix i) => CArray i e -> [(Int, e)] -> IO (CArray i e) unsafeReplaceCArray arr ies = do marr <- thawIOCArray arr sequence_ [unsafeWrite marr i e | (i, e) <- ies] unsafeFreezeIOCArray marr {-# INLINE unsafeAccumCArray #-} unsafeAccumCArray :: (MArray IOCArray e IO, Storable e, Ix i) => (e -> e' -> e) -> CArray i e -> [(Int, e')] -> IO (CArray i e) unsafeAccumCArray f arr ies = do marr <- thawIOCArray arr sequence_ [do old <- unsafeRead marr i unsafeWrite marr i (f old new) | (i, new) <- ies] unsafeFreezeIOCArray marr {-# INLINE unsafeAccumArrayCArray #-} unsafeAccumArrayCArray :: (MArray IOCArray e IO, Storable e, Ix i) => (e -> e' -> e) -> e -> (i,i) -> [(Int, e')] -> IO (CArray i e) unsafeAccumArrayCArray f e0 lu ies = do marr <- newArray lu e0 sequence_ [do old <- unsafeRead marr i unsafeWrite marr i (f old new) | (i, new) <- ies] unsafeFreezeIOCArray marr {-# INLINE eqCArray #-} eqCArray :: (IArray CArray e, Ix i, Eq e) => CArray i e -> CArray i e -> Bool eqCArray arr1@(CArray l1 u1 n1 _) arr2@(CArray l2 u2 n2 _) = if n1 == 0 then n2 == 0 else l1 == l2 && u1 == u2 && and [unsafeAt arr1 i == unsafeAt arr2 i | i <- [0 .. n1 - 1]] {-# INLINE cmpCArray #-} cmpCArray :: (IArray CArray e, Ix i, Ord e) => CArray i e -> CArray i e -> Ordering cmpCArray arr1 arr2 = compare (assocs arr1) (assocs arr2) {-# INLINE cmpIntCArray #-} cmpIntCArray :: (IArray CArray e, Ord e, Storable e) => CArray Int e -> CArray Int e -> Ordering cmpIntCArray arr1@(CArray l1 u1 n1 _) arr2@(CArray l2 u2 n2 _) = if n1 == 0 then if n2 == 0 then EQ else LT else if n2 == 0 then GT else case compare l1 l2 of EQ -> foldr cmp (compare u1 u2) [0 .. (n1 `min` n2) - 1] other -> other where cmp i rest = case compare (unsafeAt arr1 i) (unsafeAt arr2 i) of EQ -> rest other -> other -- {-# RULES "cmpCArray/Int" cmpCArray = cmpIntCArray #-} instance (Ix ix, Eq e, IArray CArray e) => Eq (CArray ix e) where (==) = eqCArray instance (Ix ix, Ord e, IArray CArray e) => Ord (CArray ix e) where compare = cmpCArray instance (Ix ix, Show ix, Show e, IArray CArray e) => Show (CArray ix e) where showsPrec = showsIArray -- -- General purpose array operations which happen to be very fast for CArray. -- -- | O(1) reshape an array. The number of elements in the new shape must not -- exceed the number in the old shape. The elements are in C-style ordering. reshape :: (Ix i, Ix j) => (j,j) -> CArray i e -> CArray j e reshape (l',u') (CArray _ _ n fp) | n' > n = error "reshape: new size too large" | otherwise = CArray l' u' n' fp where n' = rangeSize (l', u') -- | O(1) make a rank 1 array from an arbitrary shape. -- It has the property that 'reshape (0, size a - 1) a == flatten a'. flatten :: Ix i => CArray i e -> CArray Int e flatten (CArray _ _ n fp) = CArray 0 (n - 1) n fp -- -- None of the following are specific to CArray. Some could have slightly -- faster versions specialized to CArray. In general, slicing is expensive -- because the slice is not contiguous in memory, so must be copied. There are -- many specialized versions. -- -- | Generic slice and map. This takes the new range, the inverse map on -- indices, and function to produce the next element. It is the most general -- operation in its class. ixmapWithIndP :: (Ix i, Ix i', IArray a e, IArray a' e') => (i',i') -> (i' -> i) -> (i -> e -> i' -> e') -> a i e -> a' i' e' ixmapWithIndP lu f g arr = listArray lu [ let i = f i' in g i (arr ! i) i' | i' <- range lu ] -- | Less polymorphic version. ixmapWithInd :: (Ix i, Ix i', IArray a e, IArray a e') => (i',i') -> (i' -> i) -> (i -> e -> i' -> e') -> a i e -> a i' e' ixmapWithInd = ixmapWithIndP -- | Perform an operation on the elements, independent of their location. ixmapWithP :: (Ix i, Ix i', IArray a e, IArray a' e') => (i',i') -> (i' -> i) -> (e -> e') -> a i e -> a' i' e' ixmapWithP lu f g arr = listArray lu [ g (arr ! f i') | i' <- range lu ] -- | Less polymorphic version. ixmapWith :: (Ix i, Ix i', IArray a e, IArray a e') => (i',i') -> (i' -> i) -> (e -> e') -> a i e -> a i' e' ixmapWith = ixmapWithP -- | More polymorphic version of 'ixmap'. ixmapP :: (Ix i, Ix i', IArray a e, IArray a' e) => (i',i') -> (i' -> i) -> a i e -> a' i' e ixmapP lu f arr = ixmapWithP lu f id arr -- | More friendly sub-arrays with element mapping. sliceStrideWithP :: (Ix i, Shapable i, Ix i', IArray a e, IArray a' e') => (i',i') -> (i,i,i) -> (e -> e') -> a i e -> a' i' e' sliceStrideWithP lu (start,next,end) f arr | all (inRange (bounds arr)) [start,next,end] = listArray lu es | otherwise = error "sliceStrideWith: out of bounds" where is = offsetShapeFromThenTo (shape arr) (index' start) (index' next) (index' end) es = map (f . (unsafeAt arr)) is index' = indexes arr -- | Less polymorphic version. sliceStrideWith :: (Ix i, Shapable i, Ix i', IArray a e, IArray a e') => (i',i') -> (i,i,i) -> (e -> e') -> a i e -> a i' e' sliceStrideWith = sliceStrideWithP -- | Strided sub-array without element mapping. sliceStrideP :: (Ix i, Shapable i, Ix i', IArray a e, IArray a' e) => (i',i') -> (i,i,i) -> a i e -> a' i' e sliceStrideP lu sne = sliceStrideWithP lu sne id -- | Less polymorphic version. sliceStride :: (Ix i, Shapable i, Ix i', IArray a e) => (i',i') -> (i,i,i) -> a i e -> a i' e sliceStride = sliceStrideP -- | Contiguous sub-array with element mapping. sliceWithP :: (Ix i, Shapable i, Ix i', IArray a e, IArray a' e') => (i',i') -> (i,i) -> (e -> e') -> a i e -> a' i' e' sliceWithP lu (start,end) f arr | all (inRange (bounds arr)) [start,end] = listArray lu es | otherwise = error "sliceWith: out of bounds" where is = offsetShapeFromTo (shape arr) (index' start) (index' end) es = map (f . (unsafeAt arr)) is index' = indexes arr -- | Less polymorphic version. sliceWith :: (Ix i, Shapable i, Ix i', IArray a e, IArray a e') => (i',i') -> (i,i) -> (e -> e') -> a i e -> a i' e' sliceWith = sliceWithP -- | Contiguous sub-array without element mapping. sliceP :: (Ix i, Shapable i, Ix i', IArray a e, IArray a' e) => (i',i') -> (i,i) -> a i e -> a' i' e sliceP lu se = sliceWithP lu se id -- | Less polymorphic version. slice :: (Ix i, Shapable i, Ix i', IArray a e) => (i',i') -> (i,i) -> a i e -> a i' e slice = sliceP -- | In-place map on CArray. Note that this is /IN PLACE/ so you should not -- retain any reference to the original. It flagrantly breaks referential -- transparency! {-# INLINE mapCArrayInPlace #-} mapCArrayInPlace :: (Ix i, IArray CArray e, Storable e) => (e -> e) -> CArray i e -> CArray i e mapCArrayInPlace f a = S.inlinePerformIO $ do withCArray a $ \p -> forM_ [0 .. size a - 1] $ \i -> peekElemOff p i >>= pokeElemOff p i . f return a ----------------------------------------- -- These are meant to be internal only indexes :: (Ix i, Shapable i, IArray a e) => a i e -> i -> [Int] indexes a i = map pred $ (sShape . fst . bounds) a i offsetShapeFromThenTo :: [Int] -> [Int] -> [Int] -> [Int] -> [Int] offsetShapeFromThenTo s a b c = foldr (liftA2 (+)) [0] (ilists stride a b c) where ilists = zipWith4 (\s' a' b' c' -> map (*s') $ enumFromThenTo a' b' c') stride = shapeToStride s offsetShapeFromTo :: [Int] -> [Int] -> [Int] -> [Int] offsetShapeFromTo = offsetShapeFromTo' id offsetShapeFromTo' :: ([[Int]] -> [[Int]]) -> [Int] -> [Int] -> [Int] -> [Int] offsetShapeFromTo' f s a b = foldr (liftA2 (+)) [0] (f $ ilists stride a b) where ilists = zipWith3 (\s' a' b' -> map (*s') $ enumFromTo a' b') stride = shapeToStride s offsets :: (Ix a, Shapable a) => (a, a) -> a -> [Int] offsets lu i = reverse . osets (index lu i) . reverse . scanl1 (*) . uncurry sShape $ lu where osets 0 [] = [] osets i' (b:bs) = r : osets d bs where (d,r) = i' `divMod` b osets _ _ = error "osets" ----------------------------------------- -- | p-norm on the array taken as a vector normp :: (Ix i, RealFloat e', Abs e e', IArray a e) => e' -> a i e -> e' normp p a | 1 <= p && not (isInfinite p) = (** (1/p)) $ foldl' (\z e -> z + (abs_ e) ** p) 0 (elems a) | otherwise = error "normp: p < 1" -- | 2-norm on the array taken as a vector (Frobenius norm for matrices) norm2 :: (Ix i, Floating e', Abs e e', IArray a e) => a i e -> e' norm2 a = sqrt $ foldl' (\z e -> z + abs_ e ^ (2 :: Int)) 0 (elems a) -- | Sup norm on the array taken as a vector normSup :: (Ix i, Num e', Ord e', Abs e e', IArray a e) => a i e -> e' normSup a = foldl' (\z e -> z `max` abs_ e) 0 (elems a) -- | Polymorphic version of amap. liftArrayP :: (Ix i, IArray a e, IArray a1 e1) => (e -> e1) -> a i e -> a1 i e1 liftArrayP f a = listArray (bounds a) (map f (elems a)) -- | Equivalent to amap. Here for consistency only. liftArray :: (Ix i, IArray a e, IArray a e1) => (e -> e1) -> a i e -> a i e1 liftArray = liftArrayP -- | Polymorphic 2-array lift. liftArray2P :: (Ix i, IArray a e, IArray a1 e1, IArray a2 e2) => (e -> e1 -> e2) -> a i e -> a1 i e1 -> a2 i e2 liftArray2P f a b | aBounds == bounds b = listArray aBounds (zipWith f (elems a) (elems b)) | otherwise = error "liftArray2: array bounds must match" where aBounds = bounds a -- | Less polymorphic version. liftArray2 :: (Ix i, IArray a e, IArray a e1, IArray a e2) => (e -> e1 -> e2) -> a i e -> a i e1 -> a i e2 liftArray2 = liftArray2P -- | Polymorphic 3-array lift. liftArray3P :: (Ix i, IArray a e, IArray a1 e1, IArray a2 e2, IArray a3 e3) => (e -> e1 -> e2 -> e3) -> a i e -> a1 i e1 -> a2 i e2 -> a3 i e3 liftArray3P f a b c | aBounds == bounds b && aBounds == bounds c = listArray aBounds (zipWith3 f (elems a) (elems b) (elems c)) | otherwise = error "liftArray2: array bounds must match" where aBounds = bounds a -- | Less polymorphic version. liftArray3 :: (Ix i, IArray a e, IArray a e1, IArray a e2, IArray a e3) => (e -> e1 -> e2 -> e3) -> a i e -> a i e1 -> a i e2 -> a i e3 liftArray3 = liftArray3P -- | Hack so that norms have a sensible type. class Abs a b | a -> b where abs_ :: a -> b instance Abs (Complex Double) Double where abs_ = magnitude instance Abs (Complex Float) Float where abs_ = magnitude instance Abs Double Double where abs_ = abs instance Abs Float Float where abs_ = abs -- | Allocate an array which is 16-byte aligned. Essential for SIMD instructions. mallocForeignPtrArrayAligned :: Storable a => Int -> IO (ForeignPtr a) mallocForeignPtrArrayAligned n = doMalloc undefined where doMalloc :: Storable b => b -> IO (ForeignPtr b) doMalloc dummy = mallocForeignPtrBytesAligned (n * sizeOf dummy) -- | Allocate memory which is 16-byte aligned. This is essential for SIMD -- instructions. We know that mallocPlainForeignPtrBytes will give word-aligned -- memory, so we pad enough to be able to return the desired amount of memory -- after aligning our pointer. mallocForeignPtrBytesAligned :: Int -> IO (ForeignPtr a) mallocForeignPtrBytesAligned n = do (ForeignPtr addr contents) <- mallocPlainForeignPtrBytes (n + pad) let !(Ptr addr') = alignPtr (Ptr addr) 16 return (ForeignPtr addr' contents) where pad = 16 - sizeOf (undefined :: Word) -- | Make a new CArray with an IO action. createCArray :: (Ix i, Storable e) => (i,i) -> (Ptr e -> IO ()) -> IO (CArray i e) createCArray lu f = do fp <- mallocForeignPtrArrayAligned (rangeSize lu) withForeignPtr fp f unsafeForeignPtrToCArray fp lu unsafeCreateCArray :: (Ix i, Storable e) => (i,i) -> (Ptr e -> IO ()) -> CArray i e unsafeCreateCArray lu = unsafePerformIO . createCArray lu instance (Ix i, Binary i, Binary e, Storable e) => Binary (CArray i e) where put a = do put (bounds a) mapM_ put (elems a) get = do lu <- get es <- replicateM (rangeSize lu) get return $ listArray lu es
# Decision Lens API # # No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # # OpenAPI spec version: 1.0 # # Generated by: https://github.com/swagger-api/swagger-codegen.git #' Mappings Class #' #' @field size #' @field items #' #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export Mappings <- R6::R6Class( 'Mappings', public = list( `size` = NULL, `items` = NULL, initialize = function(`size`, `items`){ if (!missing(`size`)) { stopifnot(is.numeric(`size`), length(`size`) == 1) self$`size` <- `size` } if (!missing(`items`)) { stopifnot(is.list(`items`), length(`items`) != 0) lapply(`items`, function(x) stopifnot(R6::is.R6(x))) self$`items` <- `items` } }, toJSON = function() { MappingsObject <- list() if (!is.null(self$`size`)) { MappingsObject[['size']] <- self$`size` } if (!is.null(self$`items`)) { MappingsObject[['items']] <- lapply(self$`items`, function(x) x$toJSON()) } MappingsObject }, fromJSON = function(MappingsJson) { MappingsObject <- dlensFromJSON(MappingsJson) if (!is.null(MappingsObject$`size`)) { self$`size` <- MappingsObject$`size` } if (!is.null(MappingsObject$`items`)) { self$`items` <- lapply(MappingsObject$`items`, function(x) { itemsObject <- Mapping$new() itemsObject$fromJSON(jsonlite::toJSON(x, auto_unbox = TRUE)) itemsObject }) } }, toJSONString = function() { sprintf( '{ "size": %d, "items": [%s] }', self$`size`, lapply(self$`items`, function(x) paste(x$toJSON(), sep=",")) ) }, fromJSONString = function(MappingsJson) { MappingsObject <- dlensFromJSON(MappingsJson) self$`size` <- MappingsObject$`size` self$`items` <- lapply(MappingsObject$`items`, function(x) Mapping$new()$fromJSON(jsonlite::toJSON(x, auto_unbox = TRUE))) } ) )
(* Title: SIFUM-Type-Systems Authors: Sylvia Grewe, Heiko Mantel, Daniel Schoepe *) section \<open>Type System for Ensuring SIFUM-Security of Commands\<close> theory TypeSystem imports Main Preliminaries Security Language Compositionality begin subsection \<open>Typing Rules\<close> type_synonym Type = Sec type_synonym 'Var TyEnv = "'Var \<rightharpoonup> Type" (* We introduce a locale that instantiates the SIFUM-security property for the language from SIFUM_Lang.thy *) locale sifum_types = sifum_lang ev\<^sub>A ev\<^sub>B + sifum_security dma Stop eval\<^sub>w for ev\<^sub>A :: "('Var, 'Val) Mem \<Rightarrow> 'AExp \<Rightarrow> 'Val" and ev\<^sub>B :: "('Var, 'Val) Mem \<Rightarrow> 'BExp \<Rightarrow> bool" context sifum_types begin (* Redefined since Isabelle does not seem to be able to reuse the abbreviation from the old locale *) abbreviation mm_equiv_abv2 :: "(_, _, _) LocalConf \<Rightarrow> (_, _, _) LocalConf \<Rightarrow> bool" (infix "\<approx>" 60) where "mm_equiv_abv2 c c' \<equiv> mm_equiv_abv c c'" abbreviation eval_abv2 :: "(_, 'Var, 'Val) LocalConf \<Rightarrow> (_, _, _) LocalConf \<Rightarrow> bool" (infixl "\<leadsto>" 70) where "x \<leadsto> y \<equiv> (x, y) \<in> eval\<^sub>w" abbreviation low_indistinguishable_abv :: "'Var Mds \<Rightarrow> ('Var, 'AExp, 'BExp) Stmt \<Rightarrow> (_, _, _) Stmt \<Rightarrow> bool" ("_ \<sim>\<index> _" [100, 100] 80) where "c \<sim>\<^bsub>mds\<^esub> c' \<equiv> low_indistinguishable mds c c'" definition to_total :: "'Var TyEnv \<Rightarrow> 'Var \<Rightarrow> Sec" where "to_total \<Gamma> v \<equiv> if v \<in> dom \<Gamma> then the (\<Gamma> v) else dma v" definition max_dom :: "Sec set \<Rightarrow> Sec" where "max_dom xs \<equiv> if High \<in> xs then High else Low" inductive type_aexpr :: "'Var TyEnv \<Rightarrow> 'AExp \<Rightarrow> Type \<Rightarrow> bool" ("_ \<turnstile>\<^sub>a _ \<in> _" [120, 120, 120] 1000) where type_aexpr [intro!]: "\<Gamma> \<turnstile>\<^sub>a e \<in> max_dom (image (\<lambda> x. to_total \<Gamma> x) (aexp_vars e))" inductive_cases type_aexpr_elim [elim]: "\<Gamma> \<turnstile>\<^sub>a e \<in> t" inductive type_bexpr :: "'Var TyEnv \<Rightarrow> 'BExp \<Rightarrow> Type \<Rightarrow> bool" ("_ \<turnstile>\<^sub>b _ \<in> _ " [120, 120, 120] 1000) where type_bexpr [intro!]: "\<Gamma> \<turnstile>\<^sub>b e \<in> max_dom (image (\<lambda> x. to_total \<Gamma> x) (bexp_vars e))" inductive_cases type_bexpr_elim [elim]: "\<Gamma> \<turnstile>\<^sub>b e \<in> t" definition mds_consistent :: "'Var Mds \<Rightarrow> 'Var TyEnv \<Rightarrow> bool" where "mds_consistent mds \<Gamma> \<equiv> dom \<Gamma> = {(x :: 'Var). (dma x = Low \<and> x \<in> mds AsmNoRead) \<or> (dma x = High \<and> x \<in> mds AsmNoWrite)}" fun add_anno_dom :: "'Var TyEnv \<Rightarrow> 'Var ModeUpd \<Rightarrow> 'Var set" where "add_anno_dom \<Gamma> (Acq v AsmNoRead) = (if dma v = Low then dom \<Gamma> \<union> {v} else dom \<Gamma>)" | "add_anno_dom \<Gamma> (Acq v AsmNoWrite) = (if dma v = High then dom \<Gamma> \<union> {v} else dom \<Gamma>)" | "add_anno_dom \<Gamma> (Acq v _) = dom \<Gamma>" | "add_anno_dom \<Gamma> (Rel v AsmNoRead) = (if dma v = Low then dom \<Gamma> - {v} else dom \<Gamma>)" | "add_anno_dom \<Gamma> (Rel v AsmNoWrite) = (if dma v = High then dom \<Gamma> - {v} else dom \<Gamma>)" | "add_anno_dom \<Gamma> (Rel v _) = dom \<Gamma>" definition add_anno :: "'Var TyEnv \<Rightarrow> 'Var ModeUpd \<Rightarrow> 'Var TyEnv" (infix "\<oplus>" 60) where "\<Gamma> \<oplus> upd = ((\<lambda>x. Some (to_total \<Gamma> x)) |` add_anno_dom \<Gamma> upd)" definition context_le :: "'Var TyEnv \<Rightarrow> 'Var TyEnv \<Rightarrow> bool" (infixr "\<sqsubseteq>\<^sub>c" 100) where "\<Gamma> \<sqsubseteq>\<^sub>c \<Gamma>' \<equiv> (dom \<Gamma> = dom \<Gamma>') \<and> (\<forall> x \<in> dom \<Gamma>. the (\<Gamma> x) \<sqsubseteq> the (\<Gamma>' x))" inductive has_type :: "'Var TyEnv \<Rightarrow> ('Var, 'AExp, 'BExp) Stmt \<Rightarrow> 'Var TyEnv \<Rightarrow> bool" ("\<turnstile> _ {_} _" [120, 120, 120] 1000) where stop_type [intro]: "\<turnstile> \<Gamma> {Stop} \<Gamma>" | skip_type [intro] : "\<turnstile> \<Gamma> {Skip} \<Gamma>" | assign\<^sub>1 : "\<lbrakk> x \<notin> dom \<Gamma> ; \<Gamma> \<turnstile>\<^sub>a e \<in> t; t \<sqsubseteq> dma x \<rbrakk> \<Longrightarrow> \<turnstile> \<Gamma> {x \<leftarrow> e} \<Gamma>" | assign\<^sub>2 : "\<lbrakk> x \<in> dom \<Gamma> ; \<Gamma> \<turnstile>\<^sub>a e \<in> t \<rbrakk> \<Longrightarrow> has_type \<Gamma> (x \<leftarrow> e) (\<Gamma> (x := Some t))" | if_type [intro]: "\<lbrakk> \<Gamma> \<turnstile>\<^sub>b e \<in> High \<longrightarrow> ((\<forall> mds. mds_consistent mds \<Gamma> \<longrightarrow> (low_indistinguishable mds c\<^sub>1 c\<^sub>2)) \<and> (\<forall> x \<in> dom \<Gamma>'. \<Gamma>' x = Some High)) ; \<turnstile> \<Gamma> { c\<^sub>1 } \<Gamma>' ; \<turnstile> \<Gamma> { c\<^sub>2 } \<Gamma>' \<rbrakk> \<Longrightarrow> \<turnstile> \<Gamma> { If e c\<^sub>1 c\<^sub>2 } \<Gamma>'" | while_type [intro]: "\<lbrakk> \<Gamma> \<turnstile>\<^sub>b e \<in> Low ; \<turnstile> \<Gamma> { c } \<Gamma> \<rbrakk> \<Longrightarrow> \<turnstile> \<Gamma> { While e c } \<Gamma>" | anno_type [intro]: "\<lbrakk> \<Gamma>' = \<Gamma> \<oplus> upd ; \<turnstile> \<Gamma>' { c } \<Gamma>'' ; c \<noteq> Stop ; \<forall> x. to_total \<Gamma> x \<sqsubseteq> to_total \<Gamma>' x \<rbrakk> \<Longrightarrow> \<turnstile> \<Gamma> { c@[upd] } \<Gamma>''" | seq_type [intro]: "\<lbrakk> \<turnstile> \<Gamma> { c\<^sub>1 } \<Gamma>' ; \<turnstile> \<Gamma>' { c\<^sub>2 } \<Gamma>'' \<rbrakk> \<Longrightarrow> \<turnstile> \<Gamma> { c\<^sub>1 ;; c\<^sub>2 } \<Gamma>''" | sub : "\<lbrakk> \<turnstile> \<Gamma>\<^sub>1 { c } \<Gamma>\<^sub>1' ; \<Gamma>\<^sub>2 \<sqsubseteq>\<^sub>c \<Gamma>\<^sub>1 ; \<Gamma>\<^sub>1' \<sqsubseteq>\<^sub>c \<Gamma>\<^sub>2' \<rbrakk> \<Longrightarrow> \<turnstile> \<Gamma>\<^sub>2 { c } \<Gamma>\<^sub>2'" subsection \<open>Typing Soundness\<close> text \<open>The following predicate is needed to exclude some pathological cases, that abuse the @{term Stop} command which is not allowed to occur in actual programs.\<close> fun has_annotated_stop :: "('Var, 'AExp, 'BExp) Stmt \<Rightarrow> bool" where "has_annotated_stop (c@[_]) = (if c = Stop then True else has_annotated_stop c)" | "has_annotated_stop (Seq p q) = (has_annotated_stop p \<or> has_annotated_stop q)" | "has_annotated_stop (If _ p q) = (has_annotated_stop p \<or> has_annotated_stop q)" | "has_annotated_stop (While _ p) = has_annotated_stop p" | "has_annotated_stop _ = False" inductive_cases has_type_elim: "\<turnstile> \<Gamma> { c } \<Gamma>'" inductive_cases has_type_stop_elim: "\<turnstile> \<Gamma> { Stop } \<Gamma>'" definition tyenv_eq :: "'Var TyEnv \<Rightarrow> ('Var, 'Val) Mem \<Rightarrow> ('Var, 'Val) Mem \<Rightarrow> bool" (infix "=\<index>" 60) where "mem\<^sub>1 =\<^bsub>\<Gamma>\<^esub> mem\<^sub>2 \<equiv> \<forall> x. (to_total \<Gamma> x = Low \<longrightarrow> mem\<^sub>1 x = mem\<^sub>2 x)" lemma tyenv_eq_sym: "mem\<^sub>1 =\<^bsub>\<Gamma>\<^esub> mem\<^sub>2 \<Longrightarrow> mem\<^sub>2 =\<^bsub>\<Gamma>\<^esub> mem\<^sub>1" by (auto simp: tyenv_eq_def) (* Parametrized relations for type soundness proof *) inductive_set \<R>\<^sub>1 :: "'Var TyEnv \<Rightarrow> (('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf rel" and \<R>\<^sub>1_abv :: "'Var TyEnv \<Rightarrow> (('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf \<Rightarrow> (('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf \<Rightarrow> bool" ("_ \<R>\<^sup>1\<index> _" [120, 120] 1000) for \<Gamma>' :: "'Var TyEnv" where "x \<R>\<^sup>1\<^bsub>\<Gamma>\<^esub> y \<equiv> (x, y) \<in> \<R>\<^sub>1 \<Gamma>" | intro [intro!] : "\<lbrakk> \<turnstile> \<Gamma> { c } \<Gamma>' ; mds_consistent mds \<Gamma> ; mem\<^sub>1 =\<^bsub>\<Gamma>\<^esub> mem\<^sub>2 \<rbrakk> \<Longrightarrow> \<langle>c, mds, mem\<^sub>1\<rangle> \<R>\<^sup>1\<^bsub>\<Gamma>'\<^esub> \<langle>c, mds, mem\<^sub>2\<rangle>" inductive_set \<R>\<^sub>2 :: "'Var TyEnv \<Rightarrow> (('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf rel" and \<R>\<^sub>2_abv :: "'Var TyEnv \<Rightarrow> (('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf \<Rightarrow> (('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf \<Rightarrow> bool" ("_ \<R>\<^sup>2\<index> _" [120, 120] 1000) for \<Gamma>' :: "'Var TyEnv" where "x \<R>\<^sup>2\<^bsub>\<Gamma>\<^esub> y \<equiv> (x, y) \<in> \<R>\<^sub>2 \<Gamma>" | intro [intro!] : "\<lbrakk> \<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<approx> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle> ; \<forall> x \<in> dom \<Gamma>'. \<Gamma>' x = Some High ; \<turnstile> \<Gamma>\<^sub>1 { c\<^sub>1 } \<Gamma>' ; \<turnstile> \<Gamma>\<^sub>2 { c\<^sub>2 } \<Gamma>' ; mds_consistent mds \<Gamma>\<^sub>1 ; mds_consistent mds \<Gamma>\<^sub>2 \<rbrakk> \<Longrightarrow> \<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>2\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" inductive \<R>\<^sub>3_aux :: "'Var TyEnv \<Rightarrow> (('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf \<Rightarrow> (('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf \<Rightarrow> bool" ("_ \<R>\<^sup>3\<index> _" [120, 120] 1000) and \<R>\<^sub>3 :: "'Var TyEnv \<Rightarrow> (('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf rel" where "\<R>\<^sub>3 \<Gamma>' \<equiv> {(lc\<^sub>1, lc\<^sub>2). \<R>\<^sub>3_aux \<Gamma>' lc\<^sub>1 lc\<^sub>2}" | intro\<^sub>1 [intro] : "\<lbrakk> \<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>1\<^bsub>\<Gamma>\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>; \<turnstile> \<Gamma> { c } \<Gamma>' \<rbrakk> \<Longrightarrow> \<langle>Seq c\<^sub>1 c, mds, mem\<^sub>1\<rangle> \<R>\<^sup>3\<^bsub>\<Gamma>'\<^esub> \<langle>Seq c\<^sub>2 c, mds, mem\<^sub>2\<rangle>" | intro\<^sub>2 [intro] : "\<lbrakk> \<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>2\<^bsub>\<Gamma>\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>; \<turnstile> \<Gamma> { c } \<Gamma>' \<rbrakk> \<Longrightarrow> \<langle>Seq c\<^sub>1 c, mds, mem\<^sub>1\<rangle> \<R>\<^sup>3\<^bsub>\<Gamma>'\<^esub> \<langle>Seq c\<^sub>2 c, mds, mem\<^sub>2\<rangle>" | intro\<^sub>3 [intro] : "\<lbrakk> \<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>3\<^bsub>\<Gamma>\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>; \<turnstile> \<Gamma> { c } \<Gamma>' \<rbrakk> \<Longrightarrow> \<langle>Seq c\<^sub>1 c, mds, mem\<^sub>1\<rangle> \<R>\<^sup>3\<^bsub>\<Gamma>'\<^esub> \<langle>Seq c\<^sub>2 c, mds, mem\<^sub>2\<rangle>" (* A weaker property than bisimulation to reason about the sub-relations of \<R>: *) definition weak_bisim :: "(('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf rel \<Rightarrow> (('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf rel \<Rightarrow> bool" where "weak_bisim \<T>\<^sub>1 \<T> \<equiv> \<forall> c\<^sub>1 c\<^sub>2 mds mem\<^sub>1 mem\<^sub>2 c\<^sub>1' mds' mem\<^sub>1'. ((\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle>, \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>) \<in> \<T>\<^sub>1 \<and> (\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<leadsto> \<langle>c\<^sub>1', mds', mem\<^sub>1'\<rangle>)) \<longrightarrow> (\<exists> c\<^sub>2' mem\<^sub>2'. \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle> \<leadsto> \<langle>c\<^sub>2', mds', mem\<^sub>2'\<rangle> \<and> (\<langle>c\<^sub>1', mds', mem\<^sub>1'\<rangle>, \<langle>c\<^sub>2', mds', mem\<^sub>2'\<rangle>) \<in> \<T>)" inductive_set \<R> :: "'Var TyEnv \<Rightarrow> (('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf rel" and \<R>_abv :: "'Var TyEnv \<Rightarrow> (('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf \<Rightarrow> (('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf \<Rightarrow> bool" ("_ \<R>\<^sup>u\<index> _" [120, 120] 1000) for \<Gamma> :: "'Var TyEnv" where "x \<R>\<^sup>u\<^bsub>\<Gamma>\<^esub> y \<equiv> (x, y) \<in> \<R> \<Gamma>" | intro\<^sub>1: "lc \<R>\<^sup>1\<^bsub>\<Gamma>\<^esub> lc' \<Longrightarrow> (lc, lc') \<in> \<R> \<Gamma>" | intro\<^sub>2: "lc \<R>\<^sup>2\<^bsub>\<Gamma>\<^esub> lc' \<Longrightarrow> (lc, lc') \<in> \<R> \<Gamma>" | intro\<^sub>3: "lc \<R>\<^sup>3\<^bsub>\<Gamma>\<^esub> lc' \<Longrightarrow> (lc, lc') \<in> \<R> \<Gamma>" (* Some eliminators for the above relations *) inductive_cases \<R>\<^sub>1_elim [elim]: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>1\<^bsub>\<Gamma>\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" inductive_cases \<R>\<^sub>2_elim [elim]: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>2\<^bsub>\<Gamma>\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" inductive_cases \<R>\<^sub>3_elim [elim]: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>3\<^bsub>\<Gamma>\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" inductive_cases \<R>_elim [elim]: "(\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle>, \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>) \<in> \<R> \<Gamma>" inductive_cases \<R>_elim': "(\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle>, \<langle>c\<^sub>2, mds\<^sub>2, mem\<^sub>2\<rangle>) \<in> \<R> \<Gamma>" inductive_cases \<R>\<^sub>1_elim' : "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>1\<^bsub>\<Gamma>\<^esub> \<langle>c\<^sub>2, mds\<^sub>2, mem\<^sub>2\<rangle>" inductive_cases \<R>\<^sub>2_elim' : "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>2\<^bsub>\<Gamma>\<^esub> \<langle>c\<^sub>2, mds\<^sub>2, mem\<^sub>2\<rangle>" inductive_cases \<R>\<^sub>3_elim' : "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>3\<^bsub>\<Gamma>\<^esub> \<langle>c\<^sub>2, mds\<^sub>2, mem\<^sub>2\<rangle>" (* To prove that \<R> is a bisimulation, we first show symmetry *) lemma \<R>\<^sub>1_sym: "sym (\<R>\<^sub>1 \<Gamma>)" unfolding sym_def apply auto by (metis (no_types) \<R>\<^sub>1.intro \<R>\<^sub>1_elim' tyenv_eq_sym) lemma \<R>\<^sub>2_sym: "sym (\<R>\<^sub>2 \<Gamma>)" unfolding sym_def apply clarify by (metis (no_types) \<R>\<^sub>2.intro \<R>\<^sub>2_elim' mm_equiv_sym) lemma \<R>\<^sub>3_sym: "sym (\<R>\<^sub>3 \<Gamma>)" unfolding sym_def proof (clarify) fix c\<^sub>1 mds mem\<^sub>1 c\<^sub>2 mds' mem\<^sub>2 assume asm: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>3\<^bsub>\<Gamma>\<^esub> \<langle>c\<^sub>2, mds', mem\<^sub>2\<rangle>" hence [simp]: "mds' = mds" using \<R>\<^sub>3_elim' by blast from asm show "\<langle>c\<^sub>2, mds', mem\<^sub>2\<rangle> \<R>\<^sup>3\<^bsub>\<Gamma>\<^esub> \<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle>" apply auto apply (induct rule: \<R>\<^sub>3_aux.induct) apply (metis (lifting) \<R>\<^sub>1_sym \<R>\<^sub>3_aux.intro\<^sub>1 symD) apply (metis (lifting) \<R>\<^sub>2_sym \<R>\<^sub>3_aux.intro\<^sub>2 symD) by (metis (lifting) \<R>\<^sub>3_aux.intro\<^sub>3) qed lemma \<R>_mds [simp]: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>u\<^bsub>\<Gamma>\<^esub> \<langle>c\<^sub>2, mds', mem\<^sub>2\<rangle> \<Longrightarrow> mds = mds'" apply (rule \<R>_elim') apply (auto) apply (metis \<R>\<^sub>1_elim') apply (metis \<R>\<^sub>2_elim') apply (insert \<R>\<^sub>3_elim') by blast lemma \<R>_sym: "sym (\<R> \<Gamma>)" unfolding sym_def proof (clarify) fix c\<^sub>1 mds mem\<^sub>1 c\<^sub>2 mds\<^sub>2 mem\<^sub>2 assume asm: "(\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle>, \<langle>c\<^sub>2, mds\<^sub>2, mem\<^sub>2\<rangle>) \<in> \<R> \<Gamma>" with \<R>_mds have [simp]: "mds\<^sub>2 = mds" by blast from asm show "(\<langle>c\<^sub>2, mds\<^sub>2, mem\<^sub>2\<rangle>, \<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle>) \<in> \<R> \<Gamma>" using \<R>.intro\<^sub>1 [of \<Gamma>] and \<R>.intro\<^sub>2 [of \<Gamma>] and \<R>.intro\<^sub>3 [of \<Gamma>] using \<R>\<^sub>1_sym [of \<Gamma>] and \<R>\<^sub>2_sym [of \<Gamma>] and \<R>\<^sub>3_sym [of \<Gamma>] apply simp apply (erule \<R>_elim) by (auto simp: sym_def) qed (* Next, we show that the relations are closed under globally consistent changes *) lemma \<R>\<^sub>1_closed_glob_consistent: "closed_glob_consistent (\<R>\<^sub>1 \<Gamma>')" unfolding closed_glob_consistent_def proof (clarify) fix c\<^sub>1 mds mem\<^sub>1 c\<^sub>2 mem\<^sub>2 x \<Gamma>' assume R1: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>1\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" hence [simp]: "c\<^sub>2 = c\<^sub>1" by blast from R1 obtain \<Gamma> where \<Gamma>_props: "\<turnstile> \<Gamma> { c\<^sub>1 } \<Gamma>'" "mem\<^sub>1 =\<^bsub>\<Gamma>\<^esub> mem\<^sub>2" "mds_consistent mds \<Gamma>" by blast hence "\<And> v. \<langle>c\<^sub>1, mds, mem\<^sub>1 (x := v)\<rangle> \<R>\<^sup>1\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2 (x := v)\<rangle>" by (auto simp: tyenv_eq_def mds_consistent_def) moreover from \<Gamma>_props have "\<And> v\<^sub>1 v\<^sub>2. \<lbrakk> dma x = High ; x \<notin> mds AsmNoWrite \<rbrakk> \<Longrightarrow> \<langle>c\<^sub>1, mds, mem\<^sub>1(x := v\<^sub>1)\<rangle> \<R>\<^sup>1\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2(x := v\<^sub>2)\<rangle>" apply (auto simp: mds_consistent_def tyenv_eq_def) by (metis (lifting, full_types) Sec.simps(2) mem_Collect_eq to_total_def) ultimately show "(dma x = High \<and> x \<notin> mds AsmNoWrite \<longrightarrow> (\<forall>v\<^sub>1 v\<^sub>2. \<langle>c\<^sub>1, mds, mem\<^sub>1(x := v\<^sub>1)\<rangle> \<R>\<^sup>1\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2(x := v\<^sub>2)\<rangle>)) \<and> (dma x = Low \<and> x \<notin> mds AsmNoWrite \<longrightarrow> (\<forall>v. \<langle>c\<^sub>1, mds, mem\<^sub>1(x := v)\<rangle> \<R>\<^sup>1\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2(x := v)\<rangle>))" using intro\<^sub>1 by auto qed (* A predicate like this seems to be necessary to make induct generate the correct goal in the following lemma. Without it, it somehow does not "unify" the local configuration components in the goal and the assumptions. *) fun closed_glob_helper :: "'Var TyEnv \<Rightarrow> (('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf \<Rightarrow> (('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf \<Rightarrow> bool" where "closed_glob_helper \<Gamma>' \<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<langle>c\<^sub>2, mds\<^sub>2, mem\<^sub>2\<rangle> = (\<forall> x. ((dma x = High \<and> x \<notin> mds AsmNoWrite) \<longrightarrow> (\<forall> v\<^sub>1 v\<^sub>2. (\<langle> c\<^sub>1, mds, mem\<^sub>1 (x := v\<^sub>1) \<rangle>, \<langle> c\<^sub>2, mds, mem\<^sub>2 (x := v\<^sub>2) \<rangle>) \<in> \<R>\<^sub>3 \<Gamma>')) \<and> ((dma x = Low \<and> x \<notin> mds AsmNoWrite) \<longrightarrow> (\<forall> v. (\<langle> c\<^sub>1, mds, mem\<^sub>1 (x := v) \<rangle>, \<langle> c\<^sub>2, mds, mem\<^sub>2 (x := v) \<rangle>) \<in> \<R>\<^sub>3 \<Gamma>')))" lemma \<R>\<^sub>3_closed_glob_consistent: assumes R3: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>3\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" shows "\<forall> x. (dma x = High \<and> x \<notin> mds AsmNoWrite \<longrightarrow> (\<forall>v\<^sub>1 v\<^sub>2. (\<langle>c\<^sub>1, mds, mem\<^sub>1(x := v\<^sub>1)\<rangle>, \<langle>c\<^sub>2, mds, mem\<^sub>2(x := v\<^sub>2)\<rangle>) \<in> \<R>\<^sub>3 \<Gamma>')) \<and> (dma x = Low \<and> x \<notin> mds AsmNoWrite \<longrightarrow> (\<forall>v. (\<langle>c\<^sub>1, mds, mem\<^sub>1(x := v)\<rangle>, \<langle>c\<^sub>2, mds, mem\<^sub>2(x := v)\<rangle>) \<in> \<R>\<^sub>3 \<Gamma>'))" proof - from R3 have "closed_glob_helper \<Gamma>' \<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" proof (induct rule: \<R>\<^sub>3_aux.induct) case (intro\<^sub>1 \<Gamma> c\<^sub>1 mds mem\<^sub>1 c\<^sub>2 mem\<^sub>2 c \<Gamma>') thus ?case using \<R>\<^sub>1_closed_glob_consistent [of \<Gamma>] and \<R>\<^sub>3_aux.intro\<^sub>1 unfolding closed_glob_consistent_def by (simp, blast) next case (intro\<^sub>2 \<Gamma> c\<^sub>1 mds mem\<^sub>1 c\<^sub>2 mem\<^sub>2 c \<Gamma>') thus ?case using \<R>\<^sub>2_closed_glob_consistent [of \<Gamma>] and \<R>\<^sub>3_aux.intro\<^sub>2 unfolding closed_glob_consistent_def by (simp, blast) next case intro\<^sub>3 thus ?case using \<R>\<^sub>3_aux.intro\<^sub>3 by (simp, blast) qed thus ?thesis by simp qed lemma \<R>_closed_glob_consistent: "closed_glob_consistent (\<R> \<Gamma>')" unfolding closed_glob_consistent_def proof (clarify, erule \<R>_elim, simp_all) fix c\<^sub>1 mds mem\<^sub>1 c\<^sub>2 mem\<^sub>2 x assume R1: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>1\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" with \<R>\<^sub>1_closed_glob_consistent show "(dma x = High \<and> x \<notin> mds AsmNoWrite \<longrightarrow> (\<forall>v\<^sub>1 v\<^sub>2. (\<langle>c\<^sub>1, mds, mem\<^sub>1(x := v\<^sub>1)\<rangle>, \<langle>c\<^sub>2, mds, mem\<^sub>2(x := v\<^sub>2)\<rangle>) \<in> \<R> \<Gamma>')) \<and> (dma x = Low \<and> x \<notin> mds AsmNoWrite \<longrightarrow> (\<forall>v. (\<langle>c\<^sub>1, mds, mem\<^sub>1(x := v)\<rangle>, \<langle>c\<^sub>2, mds, mem\<^sub>2(x := v)\<rangle>) \<in> \<R> \<Gamma>'))" unfolding closed_glob_consistent_def using intro\<^sub>1 apply clarify by metis next fix c\<^sub>1 mds mem\<^sub>1 c\<^sub>2 mem\<^sub>2 x assume R2: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>2\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" with \<R>\<^sub>2_closed_glob_consistent show "(dma x = High \<and> x \<notin> mds AsmNoWrite \<longrightarrow> (\<forall>v\<^sub>1 v\<^sub>2. (\<langle>c\<^sub>1, mds, mem\<^sub>1(x := v\<^sub>1)\<rangle>, \<langle>c\<^sub>2, mds, mem\<^sub>2(x := v\<^sub>2)\<rangle>) \<in> \<R> \<Gamma>')) \<and> (dma x = Low \<and> x \<notin> mds AsmNoWrite \<longrightarrow> (\<forall>v. (\<langle>c\<^sub>1, mds, mem\<^sub>1(x := v)\<rangle>, \<langle>c\<^sub>2, mds, mem\<^sub>2(x := v)\<rangle>) \<in> \<R> \<Gamma>'))" unfolding closed_glob_consistent_def using intro\<^sub>2 apply clarify by metis next fix c\<^sub>1 mds mem\<^sub>1 c\<^sub>2 mem\<^sub>2 x \<Gamma>' assume R3: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>3\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" thus "(dma x = High \<and> x \<notin> mds AsmNoWrite \<longrightarrow> (\<forall>v\<^sub>1 v\<^sub>2. (\<langle>c\<^sub>1, mds, mem\<^sub>1(x := v\<^sub>1)\<rangle>, \<langle>c\<^sub>2, mds, mem\<^sub>2(x := v\<^sub>2)\<rangle>) \<in> \<R> \<Gamma>')) \<and> (dma x = Low \<and> x \<notin> mds AsmNoWrite \<longrightarrow> (\<forall>v. (\<langle>c\<^sub>1, mds, mem\<^sub>1(x := v)\<rangle>, \<langle>c\<^sub>2, mds, mem\<^sub>2(x := v)\<rangle>) \<in> \<R> \<Gamma>'))" using \<R>\<^sub>3_closed_glob_consistent apply auto apply (metis \<R>.intro\<^sub>3) by (metis (lifting) \<R>.intro\<^sub>3) qed (* It now remains to show that steps of the first of two related configurations can be matched by the second: *) (* Some technical lemmas: *) lemma type_low_vars_low: assumes typed: "\<Gamma> \<turnstile>\<^sub>a e \<in> Low" assumes mds_cons: "mds_consistent mds \<Gamma>" assumes x_in_vars: "x \<in> aexp_vars e" shows "to_total \<Gamma> x = Low" using assms by (metis (full_types) Sec.exhaust imageI max_dom_def type_aexpr_elim) lemma type_low_vars_low_b: assumes typed : "\<Gamma> \<turnstile>\<^sub>b e \<in> Low" assumes mds_cons: "mds_consistent mds \<Gamma>" assumes x_in_vars: "x \<in> bexp_vars e" shows "to_total \<Gamma> x = Low" using assms by (metis (full_types) Sec.exhaust imageI max_dom_def type_bexpr.simps) lemma mode_update_add_anno: "mds_consistent mds \<Gamma> \<Longrightarrow> mds_consistent (update_modes upd mds) (\<Gamma> \<oplus> upd)" apply (induct arbitrary: \<Gamma> rule: add_anno_dom.induct) by (auto simp: add_anno_def mds_consistent_def) lemma context_le_trans: "\<lbrakk> \<Gamma> \<sqsubseteq>\<^sub>c \<Gamma>' ; \<Gamma>' \<sqsubseteq>\<^sub>c \<Gamma>'' \<rbrakk> \<Longrightarrow> \<Gamma> \<sqsubseteq>\<^sub>c \<Gamma>''" apply (auto simp: context_le_def) by (metis domI order_trans option.sel) lemma context_le_refl [simp]: "\<Gamma> \<sqsubseteq>\<^sub>c \<Gamma>" by (metis context_le_def order_refl) (* Strangely, using only \<turnstile> \<Gamma> { Stop } \<Gamma>' as assumption does not work *) lemma stop_cxt : "\<lbrakk> \<turnstile> \<Gamma> { c } \<Gamma>' ; c = Stop \<rbrakk> \<Longrightarrow> \<Gamma> \<sqsubseteq>\<^sub>c \<Gamma>'" apply (induct rule: has_type.induct) apply auto by (metis context_le_trans) (* First we show that (roughly) typeability is preserved by evaluation steps *) lemma preservation: assumes typed: "\<turnstile> \<Gamma> { c } \<Gamma>'" assumes eval: "\<langle>c, mds, mem\<rangle> \<leadsto> \<langle>c', mds', mem'\<rangle>" shows "\<exists> \<Gamma>''. (\<turnstile> \<Gamma>'' { c' } \<Gamma>') \<and> (mds_consistent mds \<Gamma> \<longrightarrow> mds_consistent mds' \<Gamma>'')" using typed eval proof (induct arbitrary: c' mds rule: has_type.induct) case (anno_type \<Gamma>'' \<Gamma> upd c\<^sub>1 \<Gamma>') hence "\<langle>c\<^sub>1, update_modes upd mds, mem\<rangle> \<leadsto> \<langle>c', mds', mem'\<rangle>" by (metis upd_elim) with anno_type(3) obtain \<Gamma>''' where "\<turnstile> \<Gamma>''' { c' } \<Gamma>' \<and> (mds_consistent (update_modes upd mds) \<Gamma>'' \<longrightarrow> mds_consistent mds' \<Gamma>''')" by auto moreover have "mds_consistent mds \<Gamma> \<longrightarrow> mds_consistent (update_modes upd mds) \<Gamma>''" using anno_type apply auto by (metis mode_update_add_anno) ultimately show ?case by blast next case stop_type with stop_no_eval show ?case .. next case skip_type hence "c' = Stop \<and> mds' = mds" by (metis skip_elim) thus ?case by (metis stop_type) next case (assign\<^sub>1 x \<Gamma> e t c' mds) hence "c' = Stop \<and> mds' = mds" by (metis assign_elim) thus ?case by (metis stop_type) next case (assign\<^sub>2 x \<Gamma> e t c' mds) hence "c' = Stop \<and> mds' = mds" by (metis assign_elim) thus ?case apply (rule_tac x = "\<Gamma> (x \<mapsto> t)" in exI) apply (auto simp: mds_consistent_def) apply (metis Sec.exhaust) apply (metis (lifting, full_types) CollectD domI assign\<^sub>2(1)) apply (metis (lifting, full_types) CollectD domI assign\<^sub>2(1)) apply (metis (lifting) CollectE domI assign\<^sub>2(1)) apply (metis (lifting, full_types) domD mem_Collect_eq) by (metis (lifting, full_types) domD mem_Collect_eq) next case (if_type \<Gamma> e th el \<Gamma>' c' mds) thus ?case apply (rule_tac x = \<Gamma> in exI) by force next case (while_type \<Gamma> e c c' mds) hence [simp]: "mds' = mds \<and> c' = If e (c ;; While e c) Stop" by (metis while_elim) thus ?case apply (rule_tac x = \<Gamma> in exI) apply auto by (metis Sec.simps(2) has_type.while_type if_type while_type(1) while_type(2) seq_type stop_type type_bexpr_elim) next case (seq_type \<Gamma> c\<^sub>1 \<Gamma>\<^sub>1 c\<^sub>2 \<Gamma>\<^sub>2 c' mds) thus ?case proof (cases "c\<^sub>1 = Stop") assume [simp]: "c\<^sub>1 = Stop" with seq_type have [simp]: "mds' = mds \<and> c' = c\<^sub>2" by (metis seq_stop_elim) thus ?case apply auto by (metis (lifting) \<open>c\<^sub>1 = Stop\<close> context_le_refl seq_type(1) seq_type(3) stop_cxt sub) next assume "c\<^sub>1 \<noteq> Stop" then obtain c\<^sub>1' where "\<langle>c\<^sub>1, mds, mem\<rangle> \<leadsto> \<langle>c\<^sub>1', mds', mem'\<rangle> \<and> c' = (c\<^sub>1' ;; c\<^sub>2)" by (metis seq_elim seq_type.prems) then obtain \<Gamma>''' where "\<turnstile> \<Gamma>''' {c\<^sub>1'} \<Gamma>\<^sub>1 \<and> (mds_consistent mds \<Gamma> \<longrightarrow> mds_consistent mds' \<Gamma>''')" using seq_type(2) by auto moreover from seq_type have "\<turnstile> \<Gamma>\<^sub>1 { c\<^sub>2 } \<Gamma>\<^sub>2" by auto moreover ultimately show ?case apply (rule_tac x = \<Gamma>''' in exI) by (metis (lifting) \<open>\<langle>c\<^sub>1, mds, mem\<rangle> \<leadsto> \<langle>c\<^sub>1', mds', mem'\<rangle> \<and> c' = c\<^sub>1' ;; c\<^sub>2\<close> has_type.seq_type) qed next case (sub \<Gamma>\<^sub>1 c \<Gamma>\<^sub>1' \<Gamma>\<^sub>2 \<Gamma>\<^sub>2' c' mds) then obtain \<Gamma>'' where "\<turnstile> \<Gamma>'' { c' } \<Gamma>\<^sub>1' \<and> (mds_consistent mds \<Gamma>\<^sub>1 \<longrightarrow> mds_consistent mds' \<Gamma>'')" by auto thus ?case apply (rule_tac x = \<Gamma>'' in exI) apply (rule conjI) apply (metis (lifting) has_type.sub sub(4) stop_cxt stop_type) apply (simp add: mds_consistent_def) by (metis context_le_def sub.hyps(3)) qed lemma \<R>\<^sub>1_mem_eq: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>1\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle> \<Longrightarrow> mem\<^sub>1 =\<^bsub>mds\<^esub>\<^sup>l mem\<^sub>2" apply (rule \<R>\<^sub>1_elim) apply (auto simp: tyenv_eq_def mds_consistent_def to_total_def) by (metis (lifting) Sec.simps(1) low_mds_eq_def) lemma \<R>\<^sub>2_mem_eq: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>2\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle> \<Longrightarrow> mem\<^sub>1 =\<^bsub>mds\<^esub>\<^sup>l mem\<^sub>2" apply (rule \<R>\<^sub>2_elim) by (auto simp: mm_equiv_elim strong_low_bisim_mm_def) fun bisim_helper :: "(('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf \<Rightarrow> (('Var, 'AExp, 'BExp) Stmt, 'Var, 'Val) LocalConf \<Rightarrow> bool" where "bisim_helper \<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<langle>c\<^sub>2, mds\<^sub>2, mem\<^sub>2\<rangle> = mem\<^sub>1 =\<^bsub>mds\<^esub>\<^sup>l mem\<^sub>2" lemma \<R>\<^sub>3_mem_eq: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>3\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle> \<Longrightarrow> mem\<^sub>1 =\<^bsub>mds\<^esub>\<^sup>l mem\<^sub>2" apply (subgoal_tac "bisim_helper \<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>") apply simp apply (induct rule: \<R>\<^sub>3_aux.induct) by (auto simp: \<R>\<^sub>1_mem_eq \<R>\<^sub>2_mem_eq) (* \<R>\<^sub>2 is a full bisimulation so we can show the stronger step statement here: *) lemma \<R>\<^sub>2_bisim_step: assumes case2: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>2\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" assumes eval: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<leadsto> \<langle>c\<^sub>1', mds', mem\<^sub>1'\<rangle>" shows "\<exists> c\<^sub>2' mem\<^sub>2'. \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle> \<leadsto> \<langle>c\<^sub>2', mds', mem\<^sub>2'\<rangle> \<and> \<langle>c\<^sub>1', mds', mem\<^sub>1'\<rangle> \<R>\<^sup>2\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2', mds', mem\<^sub>2'\<rangle>" proof - from case2 have aux: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<approx> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" "\<forall> x \<in> dom \<Gamma>'. \<Gamma>' x = Some High" by (rule \<R>\<^sub>2_elim, auto) with eval obtain c\<^sub>2' mem\<^sub>2' where c\<^sub>2'_props: "\<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle> \<leadsto> \<langle>c\<^sub>2', mds', mem\<^sub>2'\<rangle> \<and> \<langle>c\<^sub>1', mds', mem\<^sub>1'\<rangle> \<approx> \<langle>c\<^sub>2', mds', mem\<^sub>2'\<rangle>" using mm_equiv_strong_low_bisim strong_low_bisim_mm_def by metis (* with aux(1) obtain \<R>' where \<R>'_props: "(\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle>, \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>) \<in> \<R>'" "strong_low_bisim_mm \<R>'" *) (* using mm_equiv_elim *) (* by auto *) from case2 obtain \<Gamma>\<^sub>1 \<Gamma>\<^sub>2 where "\<turnstile> \<Gamma>\<^sub>1 { c\<^sub>1 } \<Gamma>'" "\<turnstile> \<Gamma>\<^sub>2 { c\<^sub>2 } \<Gamma>'" "mds_consistent mds \<Gamma>\<^sub>1" "mds_consistent mds \<Gamma>\<^sub>2" by (metis \<R>\<^sub>2_elim') with preservation and c\<^sub>2'_props obtain \<Gamma>\<^sub>1' \<Gamma>\<^sub>2' where "\<turnstile> \<Gamma>\<^sub>1' {c\<^sub>1'} \<Gamma>'" "mds_consistent mds' \<Gamma>\<^sub>1'" "\<turnstile> \<Gamma>\<^sub>2' {c\<^sub>2'} \<Gamma>'" "mds_consistent mds' \<Gamma>\<^sub>2'" using eval by metis with c\<^sub>2'_props show ?thesis using \<R>\<^sub>2.intro aux(2) c\<^sub>2'_props by blast qed (* To achieve more "symmetry" later, we prove a property analogous to the ones for \<R>\<^sub>1 and \<R>\<^sub>3 which are not, by themselves, bisimulations. *) lemma \<R>\<^sub>2_weak_bisim: "weak_bisim (\<R>\<^sub>2 \<Gamma>') (\<R> \<Gamma>')" unfolding weak_bisim_def using \<R>.intro\<^sub>2 apply auto by (metis \<R>\<^sub>2_bisim_step) (* Not actually needed, but an interesting "asymmetry" since \<R>\<^sub>1 and \<R>\<^sub>3 aren't bisimulations. *) lemma \<R>\<^sub>2_bisim: "strong_low_bisim_mm (\<R>\<^sub>2 \<Gamma>')" unfolding strong_low_bisim_mm_def by (auto simp: \<R>\<^sub>2_sym \<R>\<^sub>2_closed_glob_consistent \<R>\<^sub>2_mem_eq \<R>\<^sub>2_bisim_step) lemma annotated_no_stop: "\<lbrakk> \<not> has_annotated_stop (c@[upd]) \<rbrakk> \<Longrightarrow> \<not> has_annotated_stop c" apply (cases c) by auto lemma typed_no_annotated_stop: "\<lbrakk> \<turnstile> \<Gamma> { c } \<Gamma>' \<rbrakk> \<Longrightarrow> \<not> has_annotated_stop c" by (induct rule: has_type.induct, auto) lemma not_stop_eval: "\<lbrakk> c \<noteq> Stop ; \<not> has_annotated_stop c \<rbrakk> \<Longrightarrow> \<forall> mds mem. \<exists> c' mds' mem'. \<langle>c, mds, mem\<rangle> \<leadsto> \<langle>c', mds', mem'\<rangle>" proof (induct) case (Assign x exp) thus ?case by (metis cxt_to_stmt.simps(1) eval\<^sub>w_simplep.assign eval\<^sub>wp.unannotated eval\<^sub>wp_eval\<^sub>w_eq) next case Skip thus ?case by (metis cxt_to_stmt.simps(1) eval\<^sub>w.unannotated eval\<^sub>w_simple.skip) next case (ModeDecl c mu) hence "\<not> has_annotated_stop c \<and> c \<noteq> Stop" by (metis has_annotated_stop.simps(1)) with ModeDecl show ?case apply (clarify, rename_tac mds mem) apply simp apply (erule_tac x = "update_modes mu mds" in allE) apply (erule_tac x = mem in allE) apply (erule exE)+ by (metis cxt_to_stmt.simps(1) eval\<^sub>w.decl) next case (Seq c\<^sub>1 c\<^sub>2) thus ?case proof (cases "c\<^sub>1 = Stop") assume "c\<^sub>1 = Stop" thus ?case by (metis cxt_to_stmt.simps(1) eval\<^sub>w_simplep.seq_stop eval\<^sub>wp.unannotated eval\<^sub>wp_eval\<^sub>w_eq) next assume "c\<^sub>1 \<noteq> Stop" with Seq show ?case by (metis eval\<^sub>w.seq has_annotated_stop.simps(2)) qed next case (If bexp c\<^sub>1 c\<^sub>2) thus ?case apply (clarify, rename_tac mds mem) apply (case_tac "ev\<^sub>B mem bexp") apply (metis cxt_to_stmt.simps(1) eval\<^sub>w.unannotated eval\<^sub>w_simple.if_true) by (metis cxt_to_stmt.simps(1) eval\<^sub>w.unannotated eval\<^sub>w_simple.if_false) next case (While bexp c) thus ?case by (metis cxt_to_stmt.simps(1) eval\<^sub>w_simplep.while eval\<^sub>wp.unannotated eval\<^sub>wp_eval\<^sub>w_eq) next case Stop thus ?case by blast qed lemma stop_bisim: assumes bisim: "\<langle>Stop, mds, mem\<^sub>1\<rangle> \<approx> \<langle>c, mds, mem\<^sub>2\<rangle>" assumes typeable: "\<turnstile> \<Gamma> { c } \<Gamma>'" shows "c = Stop" proof (rule ccontr) let ?lc\<^sub>1 = "\<langle>Stop, mds, mem\<^sub>1\<rangle>" and ?lc\<^sub>2 = "\<langle>c, mds, mem\<^sub>2\<rangle>" assume "c \<noteq> Stop" from typeable have "\<not> has_annotated_stop c" by (metis typed_no_annotated_stop) with \<open>c \<noteq> Stop\<close> obtain c' mds' mem\<^sub>2' where "?lc\<^sub>2 \<leadsto> \<langle>c', mds', mem\<^sub>2'\<rangle>" using not_stop_eval by blast moreover from bisim have "?lc\<^sub>2 \<approx> ?lc\<^sub>1" by (metis mm_equiv_sym) ultimately obtain c\<^sub>1' mds\<^sub>1' mem\<^sub>1' where "\<langle>Stop, mds, mem\<^sub>1\<rangle> \<leadsto> \<langle>c\<^sub>1', mds\<^sub>1', mem\<^sub>1'\<rangle>" using mm_equiv_strong_low_bisim unfolding strong_low_bisim_mm_def by blast thus False by (metis (lifting) stop_no_eval) qed (* This is the main part of the proof and used in \<R>\<^sub>1_weak_bisim: *) lemma \<R>_typed_step: "\<lbrakk> \<turnstile> \<Gamma> { c\<^sub>1 } \<Gamma>' ; mds_consistent mds \<Gamma> ; mem\<^sub>1 =\<^bsub>\<Gamma>\<^esub> mem\<^sub>2 ; \<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<leadsto> \<langle>c\<^sub>1', mds', mem\<^sub>1'\<rangle> \<rbrakk> \<Longrightarrow> (\<exists> c\<^sub>2' mem\<^sub>2'. \<langle>c\<^sub>1, mds, mem\<^sub>2\<rangle> \<leadsto> \<langle>c\<^sub>2', mds', mem\<^sub>2'\<rangle> \<and> \<langle>c\<^sub>1', mds', mem\<^sub>1'\<rangle> \<R>\<^sup>u\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2', mds', mem\<^sub>2'\<rangle>)" proof (induct arbitrary: mds c\<^sub>1' rule: has_type.induct) case (seq_type \<Gamma> c\<^sub>1 \<Gamma>'' c\<^sub>2 \<Gamma>' mds) show ?case proof (cases "c\<^sub>1 = Stop") assume "c\<^sub>1 = Stop" hence [simp]: "c\<^sub>1' = c\<^sub>2" "mds' = mds" "mem\<^sub>1' = mem\<^sub>1" using seq_type by (auto simp: seq_stop_elim) from seq_type \<open>c\<^sub>1 = Stop\<close> have "\<Gamma> \<sqsubseteq>\<^sub>c \<Gamma>''" by (metis stop_cxt) hence "\<turnstile> \<Gamma> { c\<^sub>2 } \<Gamma>'" by (metis context_le_refl seq_type(3) sub) have "\<langle>c\<^sub>2, mds, mem\<^sub>1\<rangle> \<R>\<^sup>1\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" apply (rule \<R>\<^sub>1.intro [of \<Gamma>]) by (auto simp: seq_type \<open>\<turnstile> \<Gamma> { c\<^sub>2 } \<Gamma>'\<close>) thus ?case using \<R>.intro\<^sub>1 apply clarify apply (rule_tac x = c\<^sub>2 in exI) apply (rule_tac x = mem\<^sub>2 in exI) apply (auto simp: \<open>c\<^sub>1 = Stop\<close>) by (metis cxt_to_stmt.simps(1) eval\<^sub>w_simplep.seq_stop eval\<^sub>wp.unannotated eval\<^sub>wp_eval\<^sub>w_eq) next assume "c\<^sub>1 \<noteq> Stop" with \<open>\<langle>c\<^sub>1 ;; c\<^sub>2, mds, mem\<^sub>1\<rangle> \<leadsto> \<langle>c\<^sub>1', mds', mem\<^sub>1'\<rangle>\<close> obtain c\<^sub>1'' where c\<^sub>1''_props: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<leadsto> \<langle>c\<^sub>1'', mds', mem\<^sub>1'\<rangle> \<and> c\<^sub>1' = c\<^sub>1'' ;; c\<^sub>2" by (metis seq_elim) with seq_type(2) obtain c\<^sub>2'' mem\<^sub>2' where c\<^sub>2''_props: "\<langle>c\<^sub>1, mds, mem\<^sub>2\<rangle> \<leadsto> \<langle>c\<^sub>2'', mds', mem\<^sub>2'\<rangle> \<and> \<langle>c\<^sub>1'', mds', mem\<^sub>1'\<rangle> \<R>\<^sup>u\<^bsub>\<Gamma>''\<^esub> \<langle>c\<^sub>2'', mds', mem\<^sub>2'\<rangle>" by (metis seq_type(5) seq_type(6)) hence "\<langle>c\<^sub>1'' ;; c\<^sub>2, mds', mem\<^sub>1'\<rangle> \<R>\<^sup>u\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2'' ;; c\<^sub>2, mds', mem\<^sub>2'\<rangle>" apply (rule conjE) apply (erule \<R>_elim, auto) apply (metis \<R>.intro\<^sub>3 \<R>\<^sub>3_aux.intro\<^sub>1 seq_type(3)) apply (metis \<R>.intro\<^sub>3 \<R>\<^sub>3_aux.intro\<^sub>2 seq_type(3)) by (metis \<R>.intro\<^sub>3 \<R>\<^sub>3_aux.intro\<^sub>3 seq_type(3)) moreover from c\<^sub>2''_props have "\<langle>c\<^sub>1 ;; c\<^sub>2, mds, mem\<^sub>2\<rangle> \<leadsto> \<langle>c\<^sub>2'' ;; c\<^sub>2, mds', mem\<^sub>2'\<rangle>" by (metis eval\<^sub>w.seq) ultimately show ?case by (metis c\<^sub>1''_props) qed next case (anno_type \<Gamma>' \<Gamma> upd c \<Gamma>'' mds) have "mem\<^sub>1 =\<^bsub>\<Gamma>'\<^esub> mem\<^sub>2" by (metis less_eq_Sec_def anno_type(5) anno_type(7) tyenv_eq_def) have "mds_consistent (update_modes upd mds) \<Gamma>'" by (metis (lifting) anno_type(1) anno_type(6) mode_update_add_anno) then obtain c\<^sub>2' mem\<^sub>2' where "(\<langle>c, update_modes upd mds, mem\<^sub>2\<rangle> \<leadsto> \<langle>c\<^sub>2', mds', mem\<^sub>2'\<rangle> \<and> \<langle>c\<^sub>1', mds', mem\<^sub>1'\<rangle> \<R>\<^sup>u\<^bsub>\<Gamma>''\<^esub> \<langle>c\<^sub>2', mds', mem\<^sub>2'\<rangle>)" using anno_type apply auto by (metis \<open>mem\<^sub>1 =\<^bsub>\<Gamma>'\<^esub> mem\<^sub>2\<close> anno_type(1) upd_elim) thus ?case apply (rule_tac x = c\<^sub>2' in exI) apply (rule_tac x = mem\<^sub>2' in exI) apply auto by (metis cxt_to_stmt.simps(1) eval\<^sub>w.decl) next case stop_type with stop_no_eval show ?case by auto next case (skip_type \<Gamma> mds) moreover with skip_type have [simp]: "mds' = mds" "c\<^sub>1' = Stop" "mem\<^sub>1' = mem\<^sub>1" using skip_elim by (metis, metis, metis) with skip_type have "\<langle>Stop, mds, mem\<^sub>1\<rangle> \<R>\<^sup>1\<^bsub>\<Gamma>\<^esub> \<langle>Stop, mds, mem\<^sub>2\<rangle>" by auto thus ?case using \<R>.intro\<^sub>1 and unannotated [where c = Skip and E = "[]"] apply auto by (metis eval\<^sub>w_simple.skip) next (* assign\<^sub>1 *) case (assign\<^sub>1 x \<Gamma> e t mds) hence [simp]: "c\<^sub>1' = Stop" "mds' = mds" "mem\<^sub>1' = mem\<^sub>1 (x := ev\<^sub>A mem\<^sub>1 e)" using assign_elim by (auto, metis) have "mem\<^sub>1 (x := ev\<^sub>A mem\<^sub>1 e) =\<^bsub>\<Gamma>\<^esub> mem\<^sub>2 (x := ev\<^sub>A mem\<^sub>2 e)" proof (cases "to_total \<Gamma> x") assume "to_total \<Gamma> x = High" thus ?thesis using assign\<^sub>1 tyenv_eq_def by auto next assume "to_total \<Gamma> x = Low" with assign\<^sub>1 have [simp]: "t = Low" by (metis less_eq_Sec_def to_total_def) hence "dma x = Low" using assign\<^sub>1 \<open>to_total \<Gamma> x = Low\<close> by (metis to_total_def) with assign\<^sub>1 have "\<forall> v \<in> aexp_vars e. to_total \<Gamma> v = Low" using type_low_vars_low by auto thus ?thesis using eval_vars_det\<^sub>A apply (auto simp: tyenv_eq_def) apply (metis (no_types) assign\<^sub>1(5) tyenv_eq_def) by (metis assign\<^sub>1(5) tyenv_eq_def) qed hence "\<langle>x \<leftarrow> e, mds, mem\<^sub>2\<rangle> \<leadsto> \<langle>Stop, mds', mem\<^sub>2 (x := ev\<^sub>A mem\<^sub>2 e)\<rangle>" "\<langle>Stop, mds', mem\<^sub>1 (x := ev\<^sub>A mem\<^sub>1 e)\<rangle> \<R>\<^sup>u\<^bsub>\<Gamma>\<^esub> \<langle>Stop, mds', mem\<^sub>2 (x := ev\<^sub>A mem\<^sub>2 e)\<rangle>" apply auto apply (metis cxt_to_stmt.simps(1) eval\<^sub>w.unannotated eval\<^sub>w_simple.assign) by (rule \<R>.intro\<^sub>1, auto simp: assign\<^sub>1) thus ?case using \<open>c\<^sub>1' = Stop\<close> and \<open>mem\<^sub>1' = mem\<^sub>1 (x := ev\<^sub>A mem\<^sub>1 e)\<close> by blast next (* assign\<^sub>2 *) case (assign\<^sub>2 x \<Gamma> e t mds) hence [simp]: "c\<^sub>1' = Stop" "mds' = mds" "mem\<^sub>1' = mem\<^sub>1 (x := ev\<^sub>A mem\<^sub>1 e)" using assign_elim assign\<^sub>2 by (auto, metis) let ?\<Gamma>' = "\<Gamma> (x \<mapsto> t)" have "\<langle>x \<leftarrow> e, mds, mem\<^sub>2\<rangle> \<leadsto> \<langle>Stop, mds, mem\<^sub>2 (x := ev\<^sub>A mem\<^sub>2 e)\<rangle>" using assign\<^sub>2 by (metis cxt_to_stmt.simps(1) eval\<^sub>w_simplep.assign eval\<^sub>wp.unannotated eval\<^sub>wp_eval\<^sub>w_eq) moreover have "\<langle>Stop, mds, mem\<^sub>1 (x := ev\<^sub>A mem\<^sub>1 e)\<rangle> \<R>\<^sup>1\<^bsub>?\<Gamma>'\<^esub> \<langle>Stop, mds, mem\<^sub>2 (x := ev\<^sub>A mem\<^sub>2 e)\<rangle>" proof (auto) from assign\<^sub>2 show "mds_consistent mds ?\<Gamma>'" apply (simp add: mds_consistent_def) by (metis (lifting) insert_absorb assign\<^sub>2(1)) next show "mem\<^sub>1 (x := ev\<^sub>A mem\<^sub>1 e) =\<^bsub>?\<Gamma>'\<^esub> mem\<^sub>2 (x := ev\<^sub>A mem\<^sub>2 e)" unfolding tyenv_eq_def proof (auto) assume "to_total (\<Gamma>(x \<mapsto> t)) x = Low" with \<open>\<Gamma> \<turnstile>\<^sub>a e \<in> t\<close> have "\<And> x. x \<in> aexp_vars e \<Longrightarrow> to_total \<Gamma> x = Low" by (metis assign\<^sub>2.prems(1) domI fun_upd_same option.sel to_total_def type_low_vars_low) thus "ev\<^sub>A mem\<^sub>1 e = ev\<^sub>A mem\<^sub>2 e" by (metis assign\<^sub>2.prems(2) eval_vars_det\<^sub>A tyenv_eq_def) next fix y assume "y \<noteq> x" and "to_total (\<Gamma> (x \<mapsto> t)) y = Low" thus "mem\<^sub>1 y = mem\<^sub>2 y" by (metis (full_types) assign\<^sub>2.prems(2) domD domI fun_upd_other to_total_def tyenv_eq_def) qed qed ultimately have "\<langle>x \<leftarrow> e, mds, mem\<^sub>2\<rangle> \<leadsto> \<langle>Stop, mds', mem\<^sub>2 (x := ev\<^sub>A mem\<^sub>2 e)\<rangle>" "\<langle>Stop, mds', mem\<^sub>1 (x := ev\<^sub>A mem\<^sub>1 e)\<rangle> \<R>\<^sup>u\<^bsub>\<Gamma>(x \<mapsto> t)\<^esub> \<langle>Stop, mds', mem\<^sub>2 (x := ev\<^sub>A mem\<^sub>2 e)\<rangle>" using \<R>.intro\<^sub>1 by auto thus ?case using \<open>mds' = mds\<close> \<open>c\<^sub>1' = Stop\<close> \<open>mem\<^sub>1' = mem\<^sub>1(x := ev\<^sub>A mem\<^sub>1 e)\<close> by blast next (* if *) case (if_type \<Gamma> e th el \<Gamma>') have "(\<langle>c\<^sub>1', mds, mem\<^sub>1\<rangle>, \<langle>c\<^sub>1', mds, mem\<^sub>2\<rangle>) \<in> \<R> \<Gamma>'" apply (rule intro\<^sub>1) apply clarify apply (rule \<R>\<^sub>1.intro [where \<Gamma> = \<Gamma> and \<Gamma>' = \<Gamma>']) apply (auto simp: if_type) by (metis (lifting) if_elim if_type(2) if_type(4) if_type(8)) have eq_condition: "ev\<^sub>B mem\<^sub>1 e = ev\<^sub>B mem\<^sub>2 e \<Longrightarrow> ?case" proof - assume "ev\<^sub>B mem\<^sub>1 e = ev\<^sub>B mem\<^sub>2 e" with if_type(8) have "(\<langle>If e th el, mds, mem\<^sub>2\<rangle> \<leadsto> \<langle>c\<^sub>1', mds, mem\<^sub>2\<rangle>)" apply (cases "ev\<^sub>B mem\<^sub>1 e") apply (subgoal_tac "c\<^sub>1' = th") apply clarify apply (metis cxt_to_stmt.simps(1) eval\<^sub>w_simplep.if_true eval\<^sub>wp.unannotated eval\<^sub>wp_eval\<^sub>w_eq if_type(8)) apply (metis if_elim if_type(8)) apply (subgoal_tac "c\<^sub>1' = el") apply (metis (hide_lams, mono_tags) cxt_to_stmt.simps(1) eval\<^sub>w.unannotated eval\<^sub>w_simple.if_false if_type(8)) by (metis if_elim if_type(8)) thus ?thesis by (metis \<open>\<langle>c\<^sub>1', mds, mem\<^sub>1\<rangle> \<R>\<^sup>u\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>1', mds, mem\<^sub>2\<rangle>\<close> if_elim if_type(8)) qed have "mem\<^sub>1 =\<^bsub>mds\<^esub>\<^sup>l mem\<^sub>2" apply (auto simp: low_mds_eq_def mds_consistent_def) apply (subgoal_tac "x \<notin> dom \<Gamma>") apply (metis if_type(7) to_total_def tyenv_eq_def) by (metis (lifting, mono_tags) CollectD Sec.simps(2) if_type(6) mds_consistent_def) obtain t where "\<Gamma> \<turnstile>\<^sub>b e \<in> t" by (metis type_bexpr.intros) from if_type show ?case proof (cases t) assume "t = High" with if_type show ?thesis proof (cases "ev\<^sub>B mem\<^sub>1 e = ev\<^sub>B mem\<^sub>2 e") assume "ev\<^sub>B mem\<^sub>1 e = ev\<^sub>B mem\<^sub>2 e" with eq_condition show ?thesis by auto next assume neq: "ev\<^sub>B mem\<^sub>1 e \<noteq> ev\<^sub>B mem\<^sub>2 e" from if_type \<open>t = High\<close> have "th \<sim>\<^bsub>mds\<^esub> el" by (metis \<open>\<Gamma> \<turnstile>\<^sub>b e \<in> t\<close>) from neq show ?thesis proof (cases "ev\<^sub>B mem\<^sub>1 e") assume "ev\<^sub>B mem\<^sub>1 e" hence "c\<^sub>1' = th" by (metis (lifting) if_elim if_type(8)) hence "\<langle>If e th el, mds, mem\<^sub>2\<rangle> \<leadsto> \<langle>el, mds, mem\<^sub>2\<rangle>" by (metis \<open>ev\<^sub>B mem\<^sub>1 e\<close> cxt_to_stmt.simps(1) eval\<^sub>w.unannotated eval\<^sub>w_simple.if_false if_type(8) neq) moreover with \<open>mem\<^sub>1 =\<^bsub>mds\<^esub>\<^sup>l mem\<^sub>2\<close> have "\<langle>th, mds, mem\<^sub>1\<rangle> \<approx> \<langle>el, mds, mem\<^sub>2\<rangle>" by (metis low_indistinguishable_def \<open>th \<sim>\<^bsub>mds\<^esub> el\<close>) have "\<forall> x \<in> dom \<Gamma>'. \<Gamma>' x = Some High" using if_type \<open>t = High\<close> by (metis \<open>\<Gamma> \<turnstile>\<^sub>b e \<in> t\<close>) have "\<langle>th, mds, mem\<^sub>1\<rangle> \<R>\<^sup>2\<^bsub>\<Gamma>'\<^esub> \<langle>el, mds, mem\<^sub>2\<rangle>" by (metis (lifting) \<R>\<^sub>2.intro \<open>\<forall>x\<in>dom \<Gamma>'. \<Gamma>' x = Some High\<close> \<open>\<langle>th, mds, mem\<^sub>1\<rangle> \<approx> \<langle>el, mds, mem\<^sub>2\<rangle>\<close> if_type(2) if_type(4) if_type(6)) ultimately show ?thesis using \<R>.intro\<^sub>2 apply clarify by (metis \<open>c\<^sub>1' = th\<close> if_elim if_type(8)) next assume "\<not> ev\<^sub>B mem\<^sub>1 e" hence [simp]: "c\<^sub>1' = el" by (metis (lifting) if_type(8) if_elim) hence "\<langle>If e th el, mds, mem\<^sub>2\<rangle> \<leadsto> \<langle>th, mds, mem\<^sub>2\<rangle>" by (metis (hide_lams, mono_tags) \<open>\<not> ev\<^sub>B mem\<^sub>1 e\<close> cxt_to_stmt.simps(1) eval\<^sub>w.unannotated eval\<^sub>w_simple.if_true if_type(8) neq) moreover from \<open>th \<sim>\<^bsub>mds\<^esub> el\<close> have "el \<sim>\<^bsub>mds\<^esub> th" by (metis low_indistinguishable_sym) with \<open>mem\<^sub>1 =\<^bsub>mds\<^esub>\<^sup>l mem\<^sub>2\<close> have "\<langle>el, mds, mem\<^sub>1\<rangle> \<approx> \<langle>th, mds, mem\<^sub>2\<rangle>" by (metis low_indistinguishable_def) have "\<forall> x \<in> dom \<Gamma>'. \<Gamma>' x = Some High" using if_type \<open>t = High\<close> by (metis \<open>\<Gamma> \<turnstile>\<^sub>b e \<in> t\<close>) have "\<langle>el, mds, mem\<^sub>1\<rangle> \<R>\<^sup>2\<^bsub>\<Gamma>'\<^esub> \<langle>th, mds, mem\<^sub>2\<rangle>" apply (rule \<R>\<^sub>2.intro [where \<Gamma>\<^sub>1 = \<Gamma> and \<Gamma>\<^sub>2 = \<Gamma>]) by (auto simp: if_type \<open>\<langle>el, mds, mem\<^sub>1\<rangle> \<approx> \<langle>th, mds, mem\<^sub>2\<rangle>\<close> \<open>\<forall> x \<in> dom \<Gamma>'. \<Gamma>' x = Some High\<close>) ultimately show ?thesis using \<R>.intro\<^sub>2 apply clarify by (metis \<open>c\<^sub>1' = el\<close> if_elim if_type(8)) qed qed next assume "t = Low" with if_type have "ev\<^sub>B mem\<^sub>1 e = ev\<^sub>B mem\<^sub>2 e" using eval_vars_det\<^sub>B apply (simp add: tyenv_eq_def \<open>\<Gamma> \<turnstile>\<^sub>b e \<in> t\<close> type_low_vars_low_b) by (metis (lifting) \<open>\<Gamma> \<turnstile>\<^sub>b e \<in> t\<close> type_low_vars_low_b) with eq_condition show ?thesis by auto qed next (* while *) case (while_type \<Gamma> e c) hence [simp]: "c\<^sub>1' = (If e (c ;; While e c) Stop)" and [simp]: "mds' = mds" and [simp]: "mem\<^sub>1' = mem\<^sub>1" by (auto simp: while_elim) with while_type have "\<langle>While e c, mds, mem\<^sub>2\<rangle> \<leadsto> \<langle>c\<^sub>1', mds, mem\<^sub>2\<rangle>" by (metis cxt_to_stmt.simps(1) eval\<^sub>w_simplep.while eval\<^sub>wp.unannotated eval\<^sub>wp_eval\<^sub>w_eq) moreover have "\<langle>c\<^sub>1', mds, mem\<^sub>1\<rangle> \<R>\<^sup>1\<^bsub>\<Gamma>\<^esub> \<langle>c\<^sub>1', mds, mem\<^sub>2\<rangle>" apply (rule \<R>\<^sub>1.intro [where \<Gamma> = \<Gamma>]) apply (auto simp: while_type) apply (rule if_type) apply (metis (lifting) Sec.simps(1) while_type(1) type_bexpr_elim) apply (rule seq_type [where \<Gamma>' = \<Gamma>]) by (auto simp: while_type) ultimately show ?case using \<R>.intro\<^sub>1 [of \<Gamma>] by (auto, blast) next case (sub \<Gamma>\<^sub>1 c \<Gamma>\<^sub>1' \<Gamma> \<Gamma>' mds c\<^sub>1') hence "dom \<Gamma>\<^sub>1 \<subseteq> dom \<Gamma>" "dom \<Gamma>' \<subseteq> dom \<Gamma>\<^sub>1'" apply (metis (lifting) context_le_def equalityE) by (metis context_le_def sub(4) order_refl) hence "mds_consistent mds \<Gamma>\<^sub>1" using sub apply (auto simp: mds_consistent_def) apply (metis (lifting, full_types) context_le_def domD mem_Collect_eq) by (metis (lifting, full_types) context_le_def domD mem_Collect_eq) moreover have "mem\<^sub>1 =\<^bsub>\<Gamma>\<^sub>1\<^esub> mem\<^sub>2" unfolding tyenv_eq_def by (metis (lifting, no_types) context_le_def less_eq_Sec_def sub.hyps(3) sub.prems(2) to_total_def tyenv_eq_def) ultimately obtain c\<^sub>2' mem\<^sub>2' where c\<^sub>2'_props: "\<langle>c, mds, mem\<^sub>2\<rangle> \<leadsto> \<langle>c\<^sub>2', mds', mem\<^sub>2'\<rangle>" "\<langle>c\<^sub>1', mds', mem\<^sub>1'\<rangle> \<R>\<^sup>u\<^bsub>\<Gamma>\<^sub>1'\<^esub> \<langle>c\<^sub>2', mds', mem\<^sub>2'\<rangle>" using sub by blast moreover have "\<And> c\<^sub>1 mds mem\<^sub>1 c\<^sub>2 mem\<^sub>2. \<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>u\<^bsub>\<Gamma>\<^sub>1'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle> \<Longrightarrow> \<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>u\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" proof - fix c\<^sub>1 mds mem\<^sub>1 c\<^sub>2 mem\<^sub>2 let ?lc\<^sub>1 = "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle>" and ?lc\<^sub>2 = "\<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" assume asm: "?lc\<^sub>1 \<R>\<^sup>u\<^bsub>\<Gamma>\<^sub>1'\<^esub> ?lc\<^sub>2" moreover have "?lc\<^sub>1 \<R>\<^sup>1\<^bsub>\<Gamma>\<^sub>1'\<^esub> ?lc\<^sub>2 \<Longrightarrow> ?lc\<^sub>1 \<R>\<^sup>1\<^bsub>\<Gamma>'\<^esub> ?lc\<^sub>2" apply (erule \<R>\<^sub>1_elim) apply auto by (metis (lifting) has_type.sub sub(4) stop_cxt stop_type) moreover have "?lc\<^sub>1 \<R>\<^sup>2\<^bsub>\<Gamma>\<^sub>1'\<^esub> ?lc\<^sub>2 \<Longrightarrow> ?lc\<^sub>1 \<R>\<^sup>2\<^bsub>\<Gamma>'\<^esub> ?lc\<^sub>2" proof - assume r2: "?lc\<^sub>1 \<R>\<^sup>2\<^bsub>\<Gamma>\<^sub>1'\<^esub> ?lc\<^sub>2" then obtain \<Lambda>\<^sub>1 \<Lambda>\<^sub>2 where "\<turnstile> \<Lambda>\<^sub>1 { c\<^sub>1 } \<Gamma>\<^sub>1'" "\<turnstile> \<Lambda>\<^sub>2 { c\<^sub>2 } \<Gamma>\<^sub>1'" "mds_consistent mds \<Lambda>\<^sub>1" "mds_consistent mds \<Lambda>\<^sub>2" by (metis \<R>\<^sub>2_elim) hence "\<turnstile> \<Lambda>\<^sub>1 { c\<^sub>1 } \<Gamma>'" using sub(4) by (metis context_le_refl has_type.sub sub(4)) moreover have "\<turnstile> \<Lambda>\<^sub>2 { c\<^sub>2 } \<Gamma>'" by (metis \<open>\<turnstile> \<Lambda>\<^sub>2 {c\<^sub>2} \<Gamma>\<^sub>1'\<close> context_le_refl has_type.sub sub(4)) moreover from r2 have "\<forall> x \<in> dom \<Gamma>\<^sub>1'. \<Gamma>\<^sub>1' x = Some High" apply (rule \<R>\<^sub>2_elim) by auto hence "\<forall> x \<in> dom \<Gamma>'. \<Gamma>' x = Some High" by (metis Sec.simps(2) \<open>dom \<Gamma>' \<subseteq> dom \<Gamma>\<^sub>1'\<close> context_le_def domD less_eq_Sec_def sub(4) rev_subsetD option.sel) ultimately show ?thesis by (metis (no_types) \<R>\<^sub>2.intro \<R>\<^sub>2_elim' \<open>mds_consistent mds \<Lambda>\<^sub>1\<close> \<open>mds_consistent mds \<Lambda>\<^sub>2\<close> r2) qed moreover have "?lc\<^sub>1 \<R>\<^sup>3\<^bsub>\<Gamma>\<^sub>1'\<^esub> ?lc\<^sub>2 \<Longrightarrow> ?lc\<^sub>1 \<R>\<^sup>3\<^bsub>\<Gamma>'\<^esub> ?lc\<^sub>2" apply (erule \<R>\<^sub>3_elim) proof - fix \<Gamma> c\<^sub>1'' c\<^sub>2''' c assume [simp]: "c\<^sub>1 = c\<^sub>1'' ;; c" "c\<^sub>2 = c\<^sub>2''' ;; c" assume case1: "\<turnstile> \<Gamma> {c} \<Gamma>\<^sub>1'" "\<langle>c\<^sub>1'', mds, mem\<^sub>1\<rangle> \<R>\<^sup>1\<^bsub>\<Gamma>\<^esub> \<langle>c\<^sub>2''', mds, mem\<^sub>2\<rangle>" hence "\<turnstile> \<Gamma> {c} \<Gamma>'" using context_le_refl has_type.sub sub.hyps(4) by blast with case1 show "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>3\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" using \<R>\<^sub>3_aux.intro\<^sub>1 by simp next fix \<Gamma> c\<^sub>1'' c\<^sub>2''' c'' assume [simp]: "c\<^sub>1 = c\<^sub>1'' ;; c''" "c\<^sub>2 = c\<^sub>2''' ;; c''" assume "\<langle>c\<^sub>1'', mds, mem\<^sub>1\<rangle> \<R>\<^sup>2\<^bsub>\<Gamma>\<^esub> \<langle>c\<^sub>2''', mds, mem\<^sub>2\<rangle>" "\<turnstile> \<Gamma> {c''} \<Gamma>\<^sub>1'" thus "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>3\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" using \<R>\<^sub>3_aux.intro\<^sub>2 apply simp apply (rule \<R>\<^sub>3_aux.intro\<^sub>2 [where \<Gamma> = \<Gamma>]) apply simp by (metis context_le_refl has_type.sub sub.hyps(4)) next fix \<Gamma> c\<^sub>1'' c\<^sub>2''' c'' assume [simp]: "c\<^sub>1 = c\<^sub>1'' ;; c''" "c\<^sub>2 = c\<^sub>2''' ;; c''" assume "\<langle>c\<^sub>1'', mds, mem\<^sub>1\<rangle> \<R>\<^sup>3\<^bsub>\<Gamma>\<^esub> \<langle>c\<^sub>2''', mds, mem\<^sub>2\<rangle>" "\<turnstile> \<Gamma> {c''} \<Gamma>\<^sub>1'" thus "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>3\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" using \<R>\<^sub>3_aux.intro\<^sub>3 apply auto by (metis (hide_lams, no_types) context_le_refl has_type.sub sub.hyps(4)) qed ultimately show "?thesis c\<^sub>1 mds mem\<^sub>1 c\<^sub>2 mem\<^sub>2" by (auto simp: \<R>.intros) qed with c\<^sub>2'_props show ?case by blast qed (* We can now show that \<R>\<^sub>1 and \<R>\<^sub>3 are weak bisimulations of \<R>,: *) lemma \<R>\<^sub>1_weak_bisim: "weak_bisim (\<R>\<^sub>1 \<Gamma>') (\<R> \<Gamma>')" unfolding weak_bisim_def using \<R>\<^sub>1_elim \<R>_typed_step by auto lemma \<R>_to_\<R>\<^sub>3: "\<lbrakk> \<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>u\<^bsub>\<Gamma>\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle> ; \<turnstile> \<Gamma> { c } \<Gamma>' \<rbrakk> \<Longrightarrow> \<langle>c\<^sub>1 ;; c, mds, mem\<^sub>1\<rangle> \<R>\<^sup>3\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2 ;; c, mds, mem\<^sub>2\<rangle>" apply (erule \<R>_elim) by auto lemma \<R>\<^sub>2_implies_typeable: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>2\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle> \<Longrightarrow> \<exists> \<Gamma>\<^sub>1. \<turnstile> \<Gamma>\<^sub>1 { c\<^sub>2 } \<Gamma>'" apply (erule \<R>\<^sub>2_elim) by auto (* Hence \<R> is a bisimulation: *) lemma \<R>_bisim: "strong_low_bisim_mm (\<R> \<Gamma>')" unfolding strong_low_bisim_mm_def proof (auto) from \<R>_sym show "sym (\<R> \<Gamma>')" . next from \<R>_closed_glob_consistent show "closed_glob_consistent (\<R> \<Gamma>')" . next fix c\<^sub>1 mds mem\<^sub>1 c\<^sub>2 mem\<^sub>2 assume "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>u\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" thus "mem\<^sub>1 =\<^bsub>mds\<^esub>\<^sup>l mem\<^sub>2" apply (rule \<R>_elim) by (auto simp: \<R>\<^sub>1_mem_eq \<R>\<^sub>2_mem_eq \<R>\<^sub>3_mem_eq) next fix c\<^sub>1 mds mem\<^sub>1 c\<^sub>2 mem\<^sub>2 c\<^sub>1' mds' mem\<^sub>1' assume eval: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<leadsto> \<langle>c\<^sub>1', mds', mem\<^sub>1'\<rangle>" assume R: "\<langle>c\<^sub>1, mds, mem\<^sub>1\<rangle> \<R>\<^sup>u\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle>" from R show "\<exists> c\<^sub>2' mem\<^sub>2'. \<langle>c\<^sub>2, mds, mem\<^sub>2\<rangle> \<leadsto> \<langle>c\<^sub>2', mds', mem\<^sub>2'\<rangle> \<and> \<langle>c\<^sub>1', mds', mem\<^sub>1'\<rangle> \<R>\<^sup>u\<^bsub>\<Gamma>'\<^esub> \<langle>c\<^sub>2', mds', mem\<^sub>2'\<rangle>" apply (rule \<R>_elim) apply (insert \<R>\<^sub>1_weak_bisim \<R>\<^sub>2_weak_bisim \<R>\<^sub>3_weak_bisim eval weak_bisim_def) apply (clarify, blast)+ by (metis mem_Collect_eq case_prodI) qed lemma Typed_in_\<R>: assumes typeable: "\<turnstile> \<Gamma> { c } \<Gamma>'" assumes mds_cons: "mds_consistent mds \<Gamma>" assumes mem_eq: "\<forall> x. to_total \<Gamma> x = Low \<longrightarrow> mem\<^sub>1 x = mem\<^sub>2 x" shows "\<langle>c, mds, mem\<^sub>1\<rangle> \<R>\<^sup>u\<^bsub>\<Gamma>'\<^esub> \<langle>c, mds, mem\<^sub>2\<rangle>" apply (rule \<R>.intro\<^sub>1 [of \<Gamma>']) apply clarify apply (rule \<R>\<^sub>1.intro [of \<Gamma>]) by (auto simp: assms tyenv_eq_def) (* We then prove the main soundness theorem using the fact that typeable configurations can be related using \<R>\<^sub>1 *) theorem type_soundness: assumes well_typed: "\<turnstile> \<Gamma> { c } \<Gamma>'" assumes mds_cons: "mds_consistent mds \<Gamma>" assumes mem_eq: "\<forall> x. to_total \<Gamma> x = Low \<longrightarrow> mem\<^sub>1 x = mem\<^sub>2 x" shows "\<langle>c, mds, mem\<^sub>1\<rangle> \<approx> \<langle>c, mds, mem\<^sub>2\<rangle>" using \<R>_bisim Typed_in_\<R> by (metis mds_cons mem_eq mm_equiv.simps well_typed) definition "\<Gamma>\<^sub>0" :: "'Var TyEnv" where "\<Gamma>\<^sub>0 x = None" (* The typing relation for lists of commands ("thread pools"). *) inductive type_global :: "('Var, 'AExp, 'BExp) Stmt list \<Rightarrow> bool" ("\<turnstile> _" [120] 1000) where "\<lbrakk> list_all (\<lambda> c. \<turnstile> \<Gamma>\<^sub>0 { c } \<Gamma>\<^sub>0) cs ; \<forall> mem. sound_mode_use (add_initial_modes cs, mem) \<rbrakk> \<Longrightarrow> type_global cs" inductive_cases type_global_elim: "\<turnstile> cs" lemma mds\<^sub>s_consistent: "mds_consistent mds\<^sub>s \<Gamma>\<^sub>0" by (auto simp: mds\<^sub>s_def mds_consistent_def \<Gamma>\<^sub>0_def) lemma typed_secure: "\<lbrakk> \<turnstile> \<Gamma>\<^sub>0 { c } \<Gamma>\<^sub>0 \<rbrakk> \<Longrightarrow> com_sifum_secure c" apply (auto simp: com_sifum_secure_def low_indistinguishable_def mds_consistent_def type_soundness) apply (auto simp: low_mds_eq_def) apply (rule type_soundness [of \<Gamma>\<^sub>0 c \<Gamma>\<^sub>0]) apply (auto simp: mds\<^sub>s_consistent to_total_def \<Gamma>\<^sub>0_def) by (metis empty_iff mds\<^sub>s_def) lemma "\<lbrakk> mds_consistent mds \<Gamma>\<^sub>0 ; dma x = Low \<rbrakk> \<Longrightarrow> x \<notin> mds AsmNoRead" by (auto simp: mds_consistent_def \<Gamma>\<^sub>0_def) lemma list_all_set: "\<forall> x \<in> set xs. P x \<Longrightarrow> list_all P xs" by (metis (lifting) list_all_iff) theorem type_soundness_global: assumes typeable: "\<turnstile> cs" assumes no_assms_term: "no_assumptions_on_termination cs" shows "prog_sifum_secure cs" using typeable apply (rule type_global_elim) apply (subgoal_tac "\<forall> c \<in> set cs. com_sifum_secure c") apply (metis list_all_set no_assms_term sifum_compositionality sound_mode_use.simps) by (metis (lifting) list_all_iff typed_secure) end end
import data.set.basic variable α: Type* variables A B: set α open set -- requires classical logic theorem Q4a: compl (A ∩ B) = (compl A) ∪ (compl B) := ext $ λ x, ⟨λ hi, classical.by_cases (λ ha, or.inr (λ hb, hi ⟨ha, hb⟩)) (λ hn, or.inl hn), λ hu, or.elim hu (λ hac ⟨ha, hb⟩, hac ha) (λ hbc ⟨ha, hb⟩, hbc hb)⟩ theorem Q4b: compl (A ∪ B) = (compl A) ∩ (compl B) := ext $ λ x, ⟨λ hu, ⟨λ ha, hu (or.inl ha), λ hb, hu (or.inr hb)⟩, λ ⟨hac, hbc⟩ hu, or.elim hu (λ ha, hac ha) (λ hb, hbc hb)⟩
[STATEMENT] lemma iMODb_iprev_nth_if: " [r, mod m, c] \<leftarrow> a = (if a \<le> c then r + m * (c - a) else r)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. [ r, mod m, c ] \<leftarrow> a = (if a \<le> c then r + m * (c - a) else r) [PROOF STEP] by (simp add: iMODb_iprev_nth iprev_nth_card_iMin iT_finite iT_not_empty iT_Min iT_card)
import neurokit2 as nk import pandas as pd import numpy as np sampling_rate = 1000 for heartrate in [80]: # Simulate signal ecg = nk.ecg_simulate(duration=60, sampling_rate=sampling_rate, heartrate=heartrate, noise=0) # Segment _, rpeaks = nk.ecg_peaks(ecg, sampling_rate=sampling_rate) # _, waves = nk.ecg_delineator(ecg, rpeaks=rpeaks["ECG_R_Peaks"])
\documentclass{article} \usepackage[margin=0.7in]{geometry} \usepackage[parfill]{parskip} \usepackage[utf8]{inputenc} \usepackage{amsmath,amssymb,amsfonts,amsthm} \begin{document} \section*{a} \plot{plotex_a.png} \section*{b} \plot{plotex_b.png} \plot{plotex_c.png} \plot{plotex_d.png} \plot{plotex_e.png} \plot{plotex_f.png} \plot{plotex_g.png} \end{document}
> module Predicates > import Prelude.Maybe > import Data.Fin > import Control.Isomorphism > import Sigma.Sigma > %default total > %access public export > ||| Notion of finiteness for types > Finite : Type -> Type > Finite A = Sigma Nat (\ n => Iso A (Fin n)) > Finite0 : Type -> Type > Finite0 = Finite > Finite1 : {A : Type} -> (P : A -> Type) -> Type > Finite1 {A} P = (a : A) -> Finite0 (P a) > {- This definition requires an exact cardinality |n| which may be difficult to compute. But it is enough to know a finite bound, so an alternative definition which may be more convenient is the following: > FiniteSub : Type -> Type > FiniteSub A = Exists (\ n => EmbProj A (Fin n)) ---------------- > FiniteN : Nat -> Type -> Type > FiniteN n A = Iso A (Fin n) > ---}
module unit where open import level open import eq data ⊤ {ℓ : Level} : Set ℓ where triv : ⊤ {-# COMPILE GHC ⊤ = data () (()) #-} single-range : ∀{ℓ}{U : Set ℓ}{g : U → ⊤ {ℓ}} → ∀{u : U} → g u ≡ triv single-range {_}{U}{g}{u} with g u ... | triv = refl
theory mccarthy91_M2 imports Main "$HIPSTER_HOME/IsaHipster" begin fun m :: "int => int" where "m x = (if x > 100 then x - 10 else m (m (x + 11)))" (*hipster m *) theorem x0 : "!! (n :: int) . (n >= 101) ==> ((m n) = (n - 10))" by (tactic \<open>Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1\<close>) end
------------------------------------------------------------------------------ -- Fairness of the ABP channels ------------------------------------------------------------------------------ {-# OPTIONS --exact-split #-} {-# OPTIONS --no-sized-types #-} {-# OPTIONS --no-universe-polymorphism #-} {-# OPTIONS --without-K #-} module FOTC.Program.ABP.Fair.Type where open import FOTC.Base open import FOTC.Base.List open import FOTC.Data.List open import FOTC.Program.ABP.Terms ------------------------------------------------------------------------------ -- The Fair co-inductive predicate -- From (Dybjer and Sander 1989): al : F*T if al is a list of zero or -- more 0's followed by a final 1. data F*T : D → Set where f*tnil : F*T (T ∷ []) f*tcons : ∀ {ft} → F*T ft → F*T (F ∷ ft) -- Functor for the Fair type. -- FairF : (D → Set) → D → Set -- FairF A os = ∃[ ft ] ∃[ os' ] F*T ft ∧ os ≡ ft ++ os' ∧ A os' -- Fair is the greatest fixed of FairF (by Fair-out and Fair-coind). postulate Fair : D → Set -- Fair a is post-fixed point of FairF, i.e. -- -- Fair ≤ FairF Fair. postulate Fair-out : ∀ {os} → Fair os → ∃[ ft ] ∃[ os' ] F*T ft ∧ os ≡ ft ++ os' ∧ Fair os' {-# ATP axiom Fair-out #-} -- Fair is the greatest post-fixed point of FairF, i.e. -- -- ∀ A. A ≤ FairF A ⇒ A ≤ Fair. -- -- N.B. This is an axiom schema. Because in the automatic proofs we -- *must* use an instance, we do not add this postulate as an ATP -- axiom. postulate Fair-coind : (A : D → Set) → -- A is post-fixed point of FairF. (∀ {os} → A os → ∃[ ft ] ∃[ os' ] F*T ft ∧ os ≡ ft ++ os' ∧ A os') → -- Fair is greater than A. ∀ {os} → A os → Fair os ------------------------------------------------------------------------------ -- References -- -- Dybjer, Peter and Sander, Herbert P. (1989). A Functional -- Programming Approach to the Specification and Verification of -- Concurrent Systems. Formal Aspects of Computing 1, pp. 303–319.
[STATEMENT] lemma evaluate_match_total0: fixes s :: "'a state" assumes "\<And>p e env s'::'a state. (p, e) \<in> set pes \<Longrightarrow> clock s' \<le> clock s \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)" shows "\<exists>s' r. evaluate_match True env s v pes v' (s', r)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>s' r. evaluate_match True env s v pes v' (s', r) [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: \<lbrakk>(?p, ?e) \<in> set pes; clock ?s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True ?env ?s' ?e (s'', r) goal (1 subgoal): 1. \<exists>s' r. evaluate_match True env s v pes v' (s', r) [PROOF STEP] proof (induction pes arbitrary: env s) [PROOF STATE] proof (state) goal (2 subgoals): 1. \<And>env s. (\<And>p e s' env. \<lbrakk>(p, e) \<in> set []; clock s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)) \<Longrightarrow> \<exists>s' r. evaluate_match True env s v [] v' (s', r) 2. \<And>a pes env s. \<lbrakk>\<And>env s. (\<And>p e s' env. \<lbrakk>(p, e) \<in> set pes; clock s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)) \<Longrightarrow> \<exists>s' r. evaluate_match True env s v pes v' (s', r); \<And>p e s' env. \<lbrakk>(p, e) \<in> set (a # pes); clock s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)\<rbrakk> \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (a # pes) v' (s', r) [PROOF STEP] case Nil [PROOF STATE] proof (state) this: \<lbrakk>(?p, ?e) \<in> set []; clock ?s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True ?env ?s' ?e (s'', r) goal (2 subgoals): 1. \<And>env s. (\<And>p e s' env. \<lbrakk>(p, e) \<in> set []; clock s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)) \<Longrightarrow> \<exists>s' r. evaluate_match True env s v [] v' (s', r) 2. \<And>a pes env s. \<lbrakk>\<And>env s. (\<And>p e s' env. \<lbrakk>(p, e) \<in> set pes; clock s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)) \<Longrightarrow> \<exists>s' r. evaluate_match True env s v pes v' (s', r); \<And>p e s' env. \<lbrakk>(p, e) \<in> set (a # pes); clock s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)\<rbrakk> \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (a # pes) v' (s', r) [PROOF STEP] show ?case [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>s' r. evaluate_match True env s v [] v' (s', r) [PROOF STEP] by (metis mat_empty) [PROOF STATE] proof (state) this: \<exists>s' r. evaluate_match True env s v [] v' (s', r) goal (1 subgoal): 1. \<And>a pes env s. \<lbrakk>\<And>env s. (\<And>p e s' env. \<lbrakk>(p, e) \<in> set pes; clock s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)) \<Longrightarrow> \<exists>s' r. evaluate_match True env s v pes v' (s', r); \<And>p e s' env. \<lbrakk>(p, e) \<in> set (a # pes); clock s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)\<rbrakk> \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (a # pes) v' (s', r) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>a pes env s. \<lbrakk>\<And>env s. (\<And>p e s' env. \<lbrakk>(p, e) \<in> set pes; clock s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)) \<Longrightarrow> \<exists>s' r. evaluate_match True env s v pes v' (s', r); \<And>p e s' env. \<lbrakk>(p, e) \<in> set (a # pes); clock s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)\<rbrakk> \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (a # pes) v' (s', r) [PROOF STEP] case (Cons pe pes) [PROOF STATE] proof (state) this: (\<And>p e s' env. \<lbrakk>(p, e) \<in> set pes; clock s' \<le> clock ?s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)) \<Longrightarrow> \<exists>s' r. evaluate_match True ?env ?s v pes v' (s', r) \<lbrakk>(?p, ?e) \<in> set (pe # pes); clock ?s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True ?env ?s' ?e (s'', r) goal (1 subgoal): 1. \<And>a pes env s. \<lbrakk>\<And>env s. (\<And>p e s' env. \<lbrakk>(p, e) \<in> set pes; clock s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)) \<Longrightarrow> \<exists>s' r. evaluate_match True env s v pes v' (s', r); \<And>p e s' env. \<lbrakk>(p, e) \<in> set (a # pes); clock s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)\<rbrakk> \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (a # pes) v' (s', r) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: (\<And>p e s' env. \<lbrakk>(p, e) \<in> set pes; clock s' \<le> clock ?s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)) \<Longrightarrow> \<exists>s' r. evaluate_match True ?env ?s v pes v' (s', r) \<lbrakk>(?p, ?e) \<in> set (pe # pes); clock ?s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True ?env ?s' ?e (s'', r) [PROOF STEP] obtain p e where "pe = (p, e)" [PROOF STATE] proof (prove) using this: (\<And>p e s' env. \<lbrakk>(p, e) \<in> set pes; clock s' \<le> clock ?s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)) \<Longrightarrow> \<exists>s' r. evaluate_match True ?env ?s v pes v' (s', r) \<lbrakk>(?p, ?e) \<in> set (pe # pes); clock ?s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True ?env ?s' ?e (s'', r) goal (1 subgoal): 1. (\<And>p e. pe = (p, e) \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by force [PROOF STATE] proof (state) this: pe = (p, e) goal (1 subgoal): 1. \<And>a pes env s. \<lbrakk>\<And>env s. (\<And>p e s' env. \<lbrakk>(p, e) \<in> set pes; clock s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)) \<Longrightarrow> \<exists>s' r. evaluate_match True env s v pes v' (s', r); \<And>p e s' env. \<lbrakk>(p, e) \<in> set (a # pes); clock s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r)\<rbrakk> \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (a # pes) v' (s', r) [PROOF STEP] show ?case [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] proof (cases "allDistinct (pat_bindings p [])") [PROOF STATE] proof (state) goal (2 subgoals): 1. allDistinct (pat_bindings p []) \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) 2. \<not> allDistinct (pat_bindings p []) \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] case distinct: True [PROOF STATE] proof (state) this: allDistinct (pat_bindings p []) goal (2 subgoals): 1. allDistinct (pat_bindings p []) \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) 2. \<not> allDistinct (pat_bindings p []) \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] proof (cases "pmatch (c env) (refs s) p v []") [PROOF STATE] proof (state) goal (3 subgoals): 1. pmatch (c env) (refs s) p v [] = No_match \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) 2. pmatch (c env) (refs s) p v [] = Match_type_error \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) 3. \<And>x3. pmatch (c env) (refs s) p v [] = Match x3 \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] case No_match [PROOF STATE] proof (state) this: pmatch (c env) (refs s) p v [] = No_match goal (3 subgoals): 1. pmatch (c env) (refs s) p v [] = No_match \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) 2. pmatch (c env) (refs s) p v [] = Match_type_error \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) 3. \<And>x3. pmatch (c env) (refs s) p v [] = Match x3 \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] have "\<exists>s' r. evaluate_match True env s v pes v' (s', r)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>s' r. evaluate_match True env s v pes v' (s', r) [PROOF STEP] apply (rule Cons) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>p e s' env. \<lbrakk>(p, e) \<in> set pes; clock s' \<le> clock s\<rbrakk> \<Longrightarrow> \<exists>s'' r. evaluate True env s' e (s'', r) [PROOF STEP] apply (rule Cons) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>p e s' env. \<lbrakk>(p, e) \<in> set pes; clock s' \<le> clock s\<rbrakk> \<Longrightarrow> (?p2 p e s' env, e) \<in> set (pe # pes) 2. \<And>p e s' env. \<lbrakk>(p, e) \<in> set pes; clock s' \<le> clock s\<rbrakk> \<Longrightarrow> clock s' \<le> clock s [PROOF STEP] by auto [PROOF STATE] proof (state) this: \<exists>s' r. evaluate_match True env s v pes v' (s', r) goal (3 subgoals): 1. pmatch (c env) (refs s) p v [] = No_match \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) 2. pmatch (c env) (refs s) p v [] = Match_type_error \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) 3. \<And>x3. pmatch (c env) (refs s) p v [] = Match x3 \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<exists>s' r. evaluate_match True env s v pes v' (s', r) [PROOF STEP] obtain s' r where "evaluate_match True env s v pes v' (s', r)" [PROOF STATE] proof (prove) using this: \<exists>s' r. evaluate_match True env s v pes v' (s', r) goal (1 subgoal): 1. (\<And>s' r. evaluate_match True env s v pes v' (s', r) \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: evaluate_match True env s v pes v' (s', r) goal (3 subgoals): 1. pmatch (c env) (refs s) p v [] = No_match \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) 2. pmatch (c env) (refs s) p v [] = Match_type_error \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) 3. \<And>x3. pmatch (c env) (refs s) p v [] = Match x3 \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] unfolding \<open>pe = _\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>s' r. evaluate_match True env s v ((p, e) # pes) v' (s', r) [PROOF STEP] apply (intro exI) [PROOF STATE] proof (prove) goal (1 subgoal): 1. evaluate_match True env s v ((p, e) # pes) v' (?s', ?r1) [PROOF STEP] apply (rule mat_cons2) [PROOF STATE] proof (prove) goal (1 subgoal): 1. allDistinct (pat_bindings p []) \<and> pmatch (c env) (refs s) p v [] = No_match \<and> evaluate_match True env s v pes v' (?s', ?r1) [PROOF STEP] apply safe [PROOF STATE] proof (prove) goal (3 subgoals): 1. allDistinct (pat_bindings p []) 2. pmatch (c env) (refs s) p v [] = No_match 3. evaluate_match True env s v pes v' (?s', ?r1) [PROOF STEP] by fact+ [PROOF STATE] proof (state) this: \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) goal (2 subgoals): 1. pmatch (c env) (refs s) p v [] = Match_type_error \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) 2. \<And>x3. pmatch (c env) (refs s) p v [] = Match x3 \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] next [PROOF STATE] proof (state) goal (2 subgoals): 1. pmatch (c env) (refs s) p v [] = Match_type_error \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) 2. \<And>x3. pmatch (c env) (refs s) p v [] = Match x3 \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] case Match_type_error [PROOF STATE] proof (state) this: pmatch (c env) (refs s) p v [] = Match_type_error goal (2 subgoals): 1. pmatch (c env) (refs s) p v [] = Match_type_error \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) 2. \<And>x3. pmatch (c env) (refs s) p v [] = Match x3 \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: pmatch (c env) (refs s) p v [] = Match_type_error [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: pmatch (c env) (refs s) p v [] = Match_type_error goal (1 subgoal): 1. \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] unfolding \<open>pe = _\<close> [PROOF STATE] proof (prove) using this: pmatch (c env) (refs s) p v [] = Match_type_error goal (1 subgoal): 1. \<exists>s' r. evaluate_match True env s v ((p, e) # pes) v' (s', r) [PROOF STEP] by (metis mat_cons3) [PROOF STATE] proof (state) this: \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) goal (1 subgoal): 1. \<And>x3. pmatch (c env) (refs s) p v [] = Match x3 \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>x3. pmatch (c env) (refs s) p v [] = Match x3 \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] case (Match env') [PROOF STATE] proof (state) this: pmatch (c env) (refs s) p v [] = Match env' goal (1 subgoal): 1. \<And>x3. pmatch (c env) (refs s) p v [] = Match x3 \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] have "\<exists>s' r. evaluate True (env \<lparr> sem_env.v := (nsAppend (alist_to_ns env') (sem_env.v env)) \<rparr>) s e (s', r)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>s' r. evaluate True (update_v (\<lambda>_. nsAppend (alist_to_ns env') (sem_env.v env)) env) s e (s', r) [PROOF STEP] apply (rule Cons) [PROOF STATE] proof (prove) goal (2 subgoals): 1. (?p, e) \<in> set (pe # pes) 2. clock s \<le> clock s [PROOF STEP] unfolding \<open>pe = _\<close> [PROOF STATE] proof (prove) goal (2 subgoals): 1. (?p, e) \<in> set ((p, e) # pes) 2. clock s \<le> clock s [PROOF STEP] by auto [PROOF STATE] proof (state) this: \<exists>s' r. evaluate True (update_v (\<lambda>_. nsAppend (alist_to_ns env') (sem_env.v env)) env) s e (s', r) goal (1 subgoal): 1. \<And>x3. pmatch (c env) (refs s) p v [] = Match x3 \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<exists>s' r. evaluate True (update_v (\<lambda>_. nsAppend (alist_to_ns env') (sem_env.v env)) env) s e (s', r) [PROOF STEP] obtain s' r where "evaluate True (env \<lparr> sem_env.v := (nsAppend (alist_to_ns env') (sem_env.v env)) \<rparr>) s e (s', r)" [PROOF STATE] proof (prove) using this: \<exists>s' r. evaluate True (update_v (\<lambda>_. nsAppend (alist_to_ns env') (sem_env.v env)) env) s e (s', r) goal (1 subgoal): 1. (\<And>s' r. evaluate True (update_v (\<lambda>_. nsAppend (alist_to_ns env') (sem_env.v env)) env) s e (s', r) \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: evaluate True (update_v (\<lambda>_. nsAppend (alist_to_ns env') (sem_env.v env)) env) s e (s', r) goal (1 subgoal): 1. \<And>x3. pmatch (c env) (refs s) p v [] = Match x3 \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] unfolding \<open>pe = _\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>s' r. evaluate_match True env s v ((p, e) # pes) v' (s', r) [PROOF STEP] apply (intro exI) [PROOF STATE] proof (prove) goal (1 subgoal): 1. evaluate_match True env s v ((p, e) # pes) v' (?s', ?r1) [PROOF STEP] apply (rule mat_cons1) [PROOF STATE] proof (prove) goal (1 subgoal): 1. allDistinct (pat_bindings p []) \<and> pmatch (c env) (refs s) p v [] = Match ?env'2 \<and> evaluate True (update_v (\<lambda>_. nsAppend (alist_to_ns ?env'2) (sem_env.v env)) env) s e (?s', ?r1) [PROOF STEP] apply safe [PROOF STATE] proof (prove) goal (3 subgoals): 1. allDistinct (pat_bindings p []) 2. pmatch (c env) (refs s) p v [] = Match ?env'2 3. evaluate True (update_v (\<lambda>_. nsAppend (alist_to_ns ?env'2) (sem_env.v env)) env) s e (?s', ?r1) [PROOF STEP] apply fact+ [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done [PROOF STATE] proof (state) this: \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) goal (1 subgoal): 1. \<not> allDistinct (pat_bindings p []) \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<not> allDistinct (pat_bindings p []) \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] case False [PROOF STATE] proof (state) this: \<not> allDistinct (pat_bindings p []) goal (1 subgoal): 1. \<not> allDistinct (pat_bindings p []) \<Longrightarrow> \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<not> allDistinct (pat_bindings p []) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: \<not> allDistinct (pat_bindings p []) goal (1 subgoal): 1. \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) [PROOF STEP] unfolding \<open>pe = _\<close> [PROOF STATE] proof (prove) using this: \<not> allDistinct (pat_bindings p []) goal (1 subgoal): 1. \<exists>s' r. evaluate_match True env s v ((p, e) # pes) v' (s', r) [PROOF STEP] by (metis mat_cons4) [PROOF STATE] proof (state) this: \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: \<exists>s' r. evaluate_match True env s v (pe # pes) v' (s', r) goal: No subgoals! [PROOF STEP] qed
-- Andreas, 2017-09-03, issue #2730: -- Skip termination check when giving. -- C-c C-SPC fails because of termination problems, but -- C-u C-c C-SPC should succeed here. f : Set f = {! f !}
[STATEMENT] lemma polys_inf_sign_thresholds: assumes "finite (ps :: real poly set)" obtains l u where "l \<le> u" and "\<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0}" and "\<And>p x. \<lbrakk>p \<in> ps; x \<ge> u\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_inf p" and "\<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_neg_inf p" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>l u. \<lbrakk>l \<le> u; \<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0}; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_inf p; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_neg_inf p\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] proof goal_cases [PROOF STATE] proof (state) goal (1 subgoal): 1. (\<And>l u. \<lbrakk>l \<le> u; \<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0}; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_inf p; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_neg_inf p\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] case prems: 1 [PROOF STATE] proof (state) this: \<lbrakk>?l \<le> ?u; \<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. ?l < x \<and> x \<le> ?u \<and> poly p x = 0} = {x. poly p x = 0}; \<And>p x. \<lbrakk>p \<in> ps; ?u \<le> x\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_inf p; \<And>p x. \<lbrakk>p \<in> ps; x \<le> ?l\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_neg_inf p\<rbrakk> \<Longrightarrow> thesis goal (1 subgoal): 1. (\<And>l u. \<lbrakk>l \<le> u; \<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0}; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_inf p; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_neg_inf p\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] have "\<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> ps \<and> x \<ge> u \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> ps \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p)" (is "\<exists>l u. ?P ps l u") [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> ps \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> ps \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) [PROOF STEP] proof (induction rule: finite_subset_induct[OF assms(1), where A = UNIV]) [PROOF STATE] proof (state) goal (3 subgoals): 1. ps \<subseteq> UNIV 2. \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> {} \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> {} \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) 3. \<And>a F. \<lbrakk>finite F; a \<in> UNIV; a \<notin> F; \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p)\<rbrakk> \<Longrightarrow> \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> insert a F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> insert a F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) [PROOF STEP] case 1 [PROOF STATE] proof (state) this: goal (3 subgoals): 1. ps \<subseteq> UNIV 2. \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> {} \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> {} \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) 3. \<And>a F. \<lbrakk>finite F; a \<in> UNIV; a \<notin> F; \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p)\<rbrakk> \<Longrightarrow> \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> insert a F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> insert a F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) [PROOF STEP] show ?case [PROOF STATE] proof (prove) goal (1 subgoal): 1. ps \<subseteq> UNIV [PROOF STEP] by simp [PROOF STATE] proof (state) this: ps \<subseteq> UNIV goal (2 subgoals): 1. \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> {} \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> {} \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) 2. \<And>a F. \<lbrakk>finite F; a \<in> UNIV; a \<notin> F; \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p)\<rbrakk> \<Longrightarrow> \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> insert a F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> insert a F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) [PROOF STEP] next [PROOF STATE] proof (state) goal (2 subgoals): 1. \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> {} \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> {} \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) 2. \<And>a F. \<lbrakk>finite F; a \<in> UNIV; a \<notin> F; \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p)\<rbrakk> \<Longrightarrow> \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> insert a F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> insert a F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) [PROOF STEP] case 2 [PROOF STATE] proof (state) this: goal (2 subgoals): 1. \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> {} \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> {} \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) 2. \<And>a F. \<lbrakk>finite F; a \<in> UNIV; a \<notin> F; \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p)\<rbrakk> \<Longrightarrow> \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> insert a F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> insert a F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) [PROOF STEP] show ?case [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> {} \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> {} \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) [PROOF STEP] by (intro exI[of _ 42], simp) [PROOF STATE] proof (state) this: \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> {} \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> {} \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) goal (1 subgoal): 1. \<And>a F. \<lbrakk>finite F; a \<in> UNIV; a \<notin> F; \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p)\<rbrakk> \<Longrightarrow> \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> insert a F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> insert a F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>a F. \<lbrakk>finite F; a \<in> UNIV; a \<notin> F; \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p)\<rbrakk> \<Longrightarrow> \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> insert a F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> insert a F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) [PROOF STEP] case prems: (3 p ps) [PROOF STATE] proof (state) this: finite ps p \<in> UNIV p \<notin> ps \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> ps \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> ps \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) goal (1 subgoal): 1. \<And>a F. \<lbrakk>finite F; a \<in> UNIV; a \<notin> F; \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p)\<rbrakk> \<Longrightarrow> \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> insert a F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> insert a F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) [PROOF STEP] from prems(4) [PROOF STATE] proof (chain) picking this: \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> ps \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> ps \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) [PROOF STEP] obtain l u where lu_props: "?P ps l u" [PROOF STATE] proof (prove) using this: \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> ps \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> ps \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) goal (1 subgoal): 1. (\<And>l u. l \<le> u \<and> (\<forall>p x. p \<in> ps \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> ps \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by blast [PROOF STATE] proof (state) this: l \<le> u \<and> (\<forall>p x. p \<in> ps \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> ps \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) goal (1 subgoal): 1. \<And>a F. \<lbrakk>finite F; a \<in> UNIV; a \<notin> F; \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p)\<rbrakk> \<Longrightarrow> \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> insert a F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> insert a F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) [PROOF STEP] from poly_lim_inf [PROOF STATE] proof (chain) picking this: \<forall>\<^sub>F x in at_top. sgn (poly ?p x) = poly_inf ?p [PROOF STEP] obtain u' where u'_props: "\<forall>x\<ge>u'. sgn (poly p x) = poly_inf p" [PROOF STATE] proof (prove) using this: \<forall>\<^sub>F x in at_top. sgn (poly ?p x) = poly_inf ?p goal (1 subgoal): 1. (\<And>u'. \<forall>x\<ge>u'. sgn (poly p x) = poly_inf p \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by (force simp add: eventually_at_top_linorder) [PROOF STATE] proof (state) this: \<forall>x\<ge>u'. sgn (poly p x) = poly_inf p goal (1 subgoal): 1. \<And>a F. \<lbrakk>finite F; a \<in> UNIV; a \<notin> F; \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p)\<rbrakk> \<Longrightarrow> \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> insert a F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> insert a F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) [PROOF STEP] from poly_lim_neg_inf [PROOF STATE] proof (chain) picking this: \<forall>\<^sub>F x in at_bot. sgn (poly ?p x) = poly_neg_inf ?p [PROOF STEP] obtain l' where l'_props: "\<forall>x\<le>l'. sgn (poly p x) = poly_neg_inf p" [PROOF STATE] proof (prove) using this: \<forall>\<^sub>F x in at_bot. sgn (poly ?p x) = poly_neg_inf ?p goal (1 subgoal): 1. (\<And>l'. \<forall>x\<le>l'. sgn (poly p x) = poly_neg_inf p \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by (force simp add: eventually_at_bot_linorder) [PROOF STATE] proof (state) this: \<forall>x\<le>l'. sgn (poly p x) = poly_neg_inf p goal (1 subgoal): 1. \<And>a F. \<lbrakk>finite F; a \<in> UNIV; a \<notin> F; \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p)\<rbrakk> \<Longrightarrow> \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> insert a F \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> insert a F \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) [PROOF STEP] show ?case [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>l u. l \<le> u \<and> (\<forall>pa x. pa \<in> insert p ps \<and> u \<le> x \<longrightarrow> sgn (poly pa x) = poly_inf pa) \<and> (\<forall>pa x. pa \<in> insert p ps \<and> x \<le> l \<longrightarrow> sgn (poly pa x) = poly_neg_inf pa) [PROOF STEP] by (rule exI[of _ "min l l'"], rule exI[of _ "max u u'"], insert lu_props l'_props u'_props, auto) [PROOF STATE] proof (state) this: \<exists>l u. l \<le> u \<and> (\<forall>pa x. pa \<in> insert p ps \<and> u \<le> x \<longrightarrow> sgn (poly pa x) = poly_inf pa) \<and> (\<forall>pa x. pa \<in> insert p ps \<and> x \<le> l \<longrightarrow> sgn (poly pa x) = poly_neg_inf pa) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> ps \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> ps \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) goal (1 subgoal): 1. (\<And>l u. \<lbrakk>l \<le> u; \<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0}; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_inf p; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_neg_inf p\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> ps \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> ps \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) [PROOF STEP] obtain l u where lu_props: "l \<le> u" "\<And>p x. p \<in> ps \<Longrightarrow> u \<le> x \<Longrightarrow> sgn (poly p x) = poly_inf p" "\<And>p x. p \<in> ps \<Longrightarrow> x \<le> l \<Longrightarrow> sgn (poly p x) = poly_neg_inf p" [PROOF STATE] proof (prove) using this: \<exists>l u. l \<le> u \<and> (\<forall>p x. p \<in> ps \<and> u \<le> x \<longrightarrow> sgn (poly p x) = poly_inf p) \<and> (\<forall>p x. p \<in> ps \<and> x \<le> l \<longrightarrow> sgn (poly p x) = poly_neg_inf p) goal (1 subgoal): 1. (\<And>l u. \<lbrakk>l \<le> u; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_inf p; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_neg_inf p\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by blast [PROOF STATE] proof (state) this: l \<le> u \<lbrakk>?p \<in> ps; u \<le> ?x\<rbrakk> \<Longrightarrow> sgn (poly ?p ?x) = poly_inf ?p \<lbrakk>?p \<in> ps; ?x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly ?p ?x) = poly_neg_inf ?p goal (1 subgoal): 1. (\<And>l u. \<lbrakk>l \<le> u; \<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0}; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_inf p; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_neg_inf p\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] moreover [PROOF STATE] proof (state) this: l \<le> u \<lbrakk>?p \<in> ps; u \<le> ?x\<rbrakk> \<Longrightarrow> sgn (poly ?p ?x) = poly_inf ?p \<lbrakk>?p \<in> ps; ?x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly ?p ?x) = poly_neg_inf ?p goal (1 subgoal): 1. (\<And>l u. \<lbrakk>l \<le> u; \<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0}; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_inf p; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_neg_inf p\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] { [PROOF STATE] proof (state) this: l \<le> u \<lbrakk>?p \<in> ps; u \<le> ?x\<rbrakk> \<Longrightarrow> sgn (poly ?p ?x) = poly_inf ?p \<lbrakk>?p \<in> ps; ?x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly ?p ?x) = poly_neg_inf ?p goal (1 subgoal): 1. (\<And>l u. \<lbrakk>l \<le> u; \<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0}; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_inf p; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_neg_inf p\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] fix p x [PROOF STATE] proof (state) goal (1 subgoal): 1. (\<And>l u. \<lbrakk>l \<le> u; \<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0}; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_inf p; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_neg_inf p\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] assume A: "p \<in> ps" "p \<noteq> 0" "poly p x = 0" [PROOF STATE] proof (state) this: p \<in> ps p \<noteq> 0 poly p x = 0 goal (1 subgoal): 1. (\<And>l u. \<lbrakk>l \<le> u; \<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0}; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_inf p; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_neg_inf p\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] from A [PROOF STATE] proof (chain) picking this: p \<in> ps p \<noteq> 0 poly p x = 0 [PROOF STEP] have "l < x" "x < u" [PROOF STATE] proof (prove) using this: p \<in> ps p \<noteq> 0 poly p x = 0 goal (1 subgoal): 1. l < x &&& x < u [PROOF STEP] by (auto simp: not_le[symmetric] dest: lu_props(2,3)) [PROOF STATE] proof (state) this: l < x x < u goal (1 subgoal): 1. (\<And>l u. \<lbrakk>l \<le> u; \<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0}; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_inf p; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_neg_inf p\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] } [PROOF STATE] proof (state) this: \<lbrakk>?p2 \<in> ps; ?p2 \<noteq> 0; poly ?p2 ?x2 = 0\<rbrakk> \<Longrightarrow> l < ?x2 \<lbrakk>?p2 \<in> ps; ?p2 \<noteq> 0; poly ?p2 ?x2 = 0\<rbrakk> \<Longrightarrow> ?x2 < u goal (1 subgoal): 1. (\<And>l u. \<lbrakk>l \<le> u; \<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0}; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_inf p; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_neg_inf p\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] note A = this [PROOF STATE] proof (state) this: \<lbrakk>?p2 \<in> ps; ?p2 \<noteq> 0; poly ?p2 ?x2 = 0\<rbrakk> \<Longrightarrow> l < ?x2 \<lbrakk>?p2 \<in> ps; ?p2 \<noteq> 0; poly ?p2 ?x2 = 0\<rbrakk> \<Longrightarrow> ?x2 < u goal (1 subgoal): 1. (\<And>l u. \<lbrakk>l \<le> u; \<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0}; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_inf p; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_neg_inf p\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] have "\<And>p. p \<in> ps \<Longrightarrow> p \<noteq> 0 \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0} [PROOF STEP] by (auto dest: A) [PROOF STATE] proof (state) this: \<lbrakk>?p \<in> ps; ?p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly ?p x = 0} = {x. poly ?p x = 0} goal (1 subgoal): 1. (\<And>l u. \<lbrakk>l \<le> u; \<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> {x. l < x \<and> x \<le> u \<and> poly p x = 0} = {x. poly p x = 0}; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_inf p; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> sgn (poly p x) = poly_neg_inf p\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] from prems[OF lu_props(1) this lu_props(2,3)] [PROOF STATE] proof (chain) picking this: \<lbrakk>\<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> p \<in> ps; \<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> p \<noteq> 0; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> p \<in> ps; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> u \<le> x; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> p \<in> ps; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> x \<le> l\<rbrakk> \<Longrightarrow> thesis [PROOF STEP] show thesis [PROOF STATE] proof (prove) using this: \<lbrakk>\<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> p \<in> ps; \<And>p. \<lbrakk>p \<in> ps; p \<noteq> 0\<rbrakk> \<Longrightarrow> p \<noteq> 0; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> p \<in> ps; \<And>p x. \<lbrakk>p \<in> ps; u \<le> x\<rbrakk> \<Longrightarrow> u \<le> x; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> p \<in> ps; \<And>p x. \<lbrakk>p \<in> ps; x \<le> l\<rbrakk> \<Longrightarrow> x \<le> l\<rbrakk> \<Longrightarrow> thesis goal (1 subgoal): 1. thesis [PROOF STEP] . [PROOF STATE] proof (state) this: thesis goal: No subgoals! [PROOF STEP] qed
lemma continuous_on_ext_cont[continuous_intros]: "continuous_on (cbox a b) f \<Longrightarrow> continuous_on S (ext_cont f a b)"
{-# LANGUAGE CApiFFI #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module LatticeSymmetries.CSR where -- import Data.Binary (Binary (..)) -- import Data.Vector.Binary -- import Control.Exception.Safe (bracket, impureThrow, throwIO) import Control.Monad.Primitive (PrimMonad, PrimState) import Control.Monad.ST -- import qualified Control.Monad.ST.Unsafe (unsafeIOToST) -- import Data.Aeson -- import Data.Aeson.Types (typeMismatch) -- import Data.Scientific (toRealFloat) import Data.Bits (Bits, toIntegralSized) import Data.Complex import qualified Data.List import Data.Type.Equality -- import qualified Data.List.NonEmpty as NonEmpty -- import qualified Data.Vector.Fusion.Stream.Monadic as Stream -- import qualified Data.Vector.Storable as S import qualified Data.Vector import qualified Data.Vector as B import qualified Data.Vector.Algorithms.Intro as Intro import Data.Vector.Fusion.Bundle (Bundle) import qualified Data.Vector.Fusion.Bundle as Bundle (inplace) import qualified Data.Vector.Fusion.Bundle.Monadic as Bundle import Data.Vector.Fusion.Bundle.Size (Size (..), toMax) import Data.Vector.Fusion.Stream.Monadic (Step (..), Stream (..)) import qualified Data.Vector.Fusion.Util (unId) import Data.Vector.Generic ((!)) import qualified Data.Vector.Generic as G import qualified Data.Vector.Generic.Mutable as GM import qualified Data.Vector.Storable as S import qualified Data.Vector.Unboxed -- import qualified Data.Vector.Storable.Mutable as SM -- import Data.Vector.Unboxed (Unbox) -- import qualified Data.Vector.Unboxed as U -- import Data.Yaml (decodeFileWithWarnings) -- import Foreign.C.String (CString, peekCString) import Foreign.C.Types (CInt (..), CUInt (..)) -- import Foreign.ForeignPtr -- import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr) -- import Foreign.Marshal.Alloc (alloca, free, malloc, mallocBytes) -- import Foreign.Marshal.Array (newArray, withArrayLen) import Foreign.Marshal.Utils (with) import Foreign.Ptr (FunPtr, Ptr, castPtr) -- import Foreign.StablePtr import Foreign.Storable (Storable (..)) import qualified GHC.Exts as GHC (IsList (..)) import GHC.TypeLits import qualified GHC.TypeLits as GHC -- import qualified GHC.ForeignPtr as GHC (Finalizers (..), ForeignPtr (..), ForeignPtrContents (..)) -- import GHC.Generics -- import qualified GHC.IORef as GHC (atomicSwapIORef) -- import GHC.Prim -- import qualified GHC.Ptr as GHC (Ptr (..)) -- import qualified Language.C.Inline as C -- import qualified Language.C.Inline.Unsafe as CU import LatticeSymmetries.Dense -- import LatticeSymmetries.IO -- import LatticeSymmetries.Types import qualified System.IO.Unsafe import qualified Unsafe.Coerce -- import qualified System.Mem.Weak import Prelude hiding (group, product, sort) -- typedef struct ls_csr_matrix { -- unsigned *offsets; -- unsigned *columns; -- _Complex double *off_diag_elements; -- _Complex double *diag_elements; -- unsigned dimension; -- unsigned number_nonzero; -- } ls_csr_matrix; data Ccsr_matrix = Ccsr_matrix { c_csr_matrix_offsets :: !(Ptr CUInt), c_csr_matrix_columns :: !(Ptr CUInt), c_csr_matrix_off_diag_elements :: !(Ptr (Complex Double)), c_csr_matrix_diag_elements :: !(Ptr (Complex Double)), c_csr_matrix_dimension :: !CUInt, c_csr_matrix_number_nonzero :: !CUInt } instance Storable Ccsr_matrix where alignment _ = 8 sizeOf _ = 40 peek p = Ccsr_matrix <$> peekByteOff p 0 <*> peekByteOff p 8 <*> peekByteOff p 16 <*> peekByteOff p 24 <*> peekByteOff p 32 <*> peekByteOff p 36 poke p x = do pokeByteOff p 0 (c_csr_matrix_offsets x) pokeByteOff p 8 (c_csr_matrix_columns x) pokeByteOff p 16 (c_csr_matrix_off_diag_elements x) pokeByteOff p 24 (c_csr_matrix_diag_elements x) pokeByteOff p 32 (c_csr_matrix_dimension x) pokeByteOff p 36 (c_csr_matrix_number_nonzero x) data CsrMatrix = CsrMatrix !(S.Vector CUInt) !(S.Vector CUInt) !(S.Vector (Complex Double)) !(S.Vector (Complex Double)) deriving stock (Show, Eq) withCsrMatrix :: CsrMatrix -> (Ptr Ccsr_matrix -> IO a) -> IO a withCsrMatrix m@(CsrMatrix offsets columns offDiagElems diagElems) action = S.unsafeWith offsets $ \offsetsPtr -> S.unsafeWith columns $ \columnsPtr -> S.unsafeWith offDiagElems $ \offDiagElemsPtr -> S.unsafeWith diagElems $ \diagElemsPtr -> with (Ccsr_matrix offsetsPtr columnsPtr offDiagElemsPtr diagElemsPtr c_dimension c_number_non_zero) action where c_dimension = fromIntegral (csrDim m) c_number_non_zero = fromIntegral (csrNumberNonZero m) unsafeNewCsrMatrix :: Int -> Int -> IO CsrMatrix unsafeNewCsrMatrix dimension nnz = pure $ CsrMatrix (G.replicate (dimension + 1) 0) (G.replicate nnz 0) (G.replicate nnz 0) (G.replicate dimension 0) csrMatrixShrink :: HasCallStack => Int -> CsrMatrix -> CsrMatrix csrMatrixShrink nnz m@(CsrMatrix offsets columns offDiagElems diagElems) | nnz == csrNumberNonZero m = m | nnz < csrNumberNonZero m = CsrMatrix offsets (G.take nnz columns) (G.take nnz offDiagElems) diagElems | otherwise = error "general resizing not implemented" csrDim :: CsrMatrix -> Int csrDim (CsrMatrix _ _ _ diagElems) = G.length diagElems csrNumberNonZero :: CsrMatrix -> Int csrNumberNonZero (CsrMatrix _ _ offDiagElems _) = G.length offDiagElems csrMatrixFromDense :: (HasCallStack, G.Vector v (Complex Double), G.Vector v Int) => DenseMatrix v (Complex Double) -> CsrMatrix csrMatrixFromDense m@(DenseMatrix nRows nCols v) | nRows == nCols = runST $ do let nnz = countOffDiagNonZero m diagElems = G.convert $ extractDiagonal m offsetsBuffer <- GM.new (nRows + 1) columnsBuffer <- GM.new nnz offDiagElemsBuffer <- GM.new nnz let go2 !i !j !offset | i == j = go2 i (j + 1) offset | j < nCols = let x = indexDenseMatrix m (i, j) in if x /= 0 then do GM.write columnsBuffer offset (fromIntegral j) GM.write offDiagElemsBuffer offset x go2 i (j + 1) (offset + 1) else go2 i (j + 1) offset | otherwise = pure offset go1 !i !offset | i < nRows = do offset' <- go2 i 0 offset GM.write offsetsBuffer (i + 1) (fromIntegral offset') go1 (i + 1) offset' | otherwise = pure offset GM.write offsetsBuffer 0 0 offset <- go1 0 0 unless (nnz == offset) $ error "this is probably a bug" CsrMatrix <$> G.unsafeFreeze offsetsBuffer <*> G.unsafeFreeze columnsBuffer <*> G.unsafeFreeze offDiagElemsBuffer <*> pure diagElems | otherwise = error "expected a square matrix" foreign import capi unsafe "csr.h ls_csr_plus" ls_csr_plus :: Ptr Ccsr_matrix -> Ptr Ccsr_matrix -> Ptr Ccsr_matrix -> IO () foreign import capi unsafe "csr.h ls_csr_minus" ls_csr_minus :: Ptr Ccsr_matrix -> Ptr Ccsr_matrix -> Ptr Ccsr_matrix -> IO () foreign import capi unsafe "csr.h ls_csr_times" ls_csr_times :: Ptr Ccsr_matrix -> Ptr Ccsr_matrix -> Ptr Ccsr_matrix -> IO () foreign import capi unsafe "csr.h ls_csr_kron" ls_csr_kron :: Ptr Ccsr_matrix -> Ptr Ccsr_matrix -> Ptr Ccsr_matrix -> IO () binaryOp :: (Ptr Ccsr_matrix -> Ptr Ccsr_matrix -> Ptr Ccsr_matrix -> IO ()) -> CsrMatrix -> CsrMatrix -> CsrMatrix binaryOp opKernel a b = System.IO.Unsafe.unsafePerformIO $ do let pessimisticNNZ = csrNumberNonZero a + csrNumberNonZero b c <- unsafeNewCsrMatrix (csrDim a) pessimisticNNZ nnz <- withCsrMatrix a $ \aPtr -> withCsrMatrix b $ \bPtr -> withCsrMatrix c $ \cPtr -> do opKernel aPtr bPtr cPtr fromIntegral . c_csr_matrix_number_nonzero <$> peek cPtr pure $ csrMatrixShrink nnz c instance Num CsrMatrix where (+) = binaryOp ls_csr_plus (-) = binaryOp ls_csr_minus (*) = binaryOp ls_csr_times abs (CsrMatrix offsets columns offDiagElems diagElems) = CsrMatrix offsets columns (G.map abs offDiagElems) (G.map abs diagElems) signum (CsrMatrix offsets columns offDiagElems diagElems) = CsrMatrix offsets columns (G.map signum offDiagElems) (G.map signum diagElems) fromInteger _ = error "Num instance of CsrMatrix does not implement fromInteger" csrScale :: Complex Double -> CsrMatrix -> CsrMatrix csrScale c (CsrMatrix offsets columns offDiagElems diagElems) = CsrMatrix offsets columns (G.map (c *) offDiagElems) (G.map (c *) diagElems) csrKron :: CsrMatrix -> CsrMatrix -> CsrMatrix csrKron a b = System.IO.Unsafe.unsafePerformIO $ do let dimension = csrDim a * csrDim b nnz = csrNumberNonZero a * csrNumberNonZero b c <- unsafeNewCsrMatrix dimension nnz nnz' <- withCsrMatrix a $ \aPtr -> withCsrMatrix b $ \bPtr -> withCsrMatrix c $ \cPtr -> do ls_csr_kron aPtr bPtr cPtr fromIntegral . c_csr_matrix_number_nonzero <$> peek cPtr unless (nnz == nnz') $ error $ "this is probably a bug: " <> show nnz <> " /= " <> show nnz' pure c csrKronMany :: HasCallStack => [CsrMatrix] -> CsrMatrix csrKronMany [] = error "expected a non-empty list of matrices" csrKronMany xs = Data.List.foldl1' csrKron xs
module Issue274 where -- data ⊥ : Set where record U : Set where constructor roll field ap : U → U -- lemma : U → ⊥ -- lemma (roll u) = lemma (u (roll u)) -- bottom : ⊥ -- bottom = lemma (roll λ x → x)
REBOL [] ;Improved cookie support parse-cookies: func [ {Parse a HTTP header for cookies and return them as a nested list} header [any-string!] /local name-val optionals cookie-rule cookie-list cookie cookies ] [ cookie-list: copy [] cookies: copy [] cookie-rule: [ thru "Set-Cookie:" copy c thru newline (append cookies c)] name-val: [ copy name to "=" skip copy val to ";" skip (append cookie reduce [ "name" name "value" val])] optionals: [copy name to "=" skip [ copy val to ";" skip | copy val to newline ] (append cookie reduce [name val])] parse header [ some cookie-rule ] foreach entry cookies [ cookie: copy [] parse entry [ name-val [some optionals]] append/only cookie-list cookie ] return cookie-list ] ctx-httpr: make object! [ port-flags: 0 open-check: none close-check: none write-check: none init: func [ "Parse URL and/or check the port spec object" port "Unopened port spec" spec {Argument passed to open or make (a URL or port-spec)} /local scheme ][ if url? spec [net-utils/url-parser/parse-url port spec] scheme: port/scheme port/url: spec if none? port/host [ net-error reform ["No network server for" scheme "is specified"] ] if none? port/port-id [ net-error reform ["No port address for" scheme "is specified"] ] ] open-proto: func [ {Open the socket connection and confirm server response.} port "Initalized port spec" /sub-protocol subproto /secure /generic /locals sub-port data in-bypass find-bypass bp ][ if not sub-protocol [subproto: 'tcp] net-utils/net-log reduce ["Opening" to-string subproto "for" to-string port/scheme] if not system/options/quiet [print ["connecting to:" port/host]] find-bypass: func [host bypass /local x] [ if found? host [ foreach item bypass [ if any [ all [x: find/match/any host item tail? x] ] [return true] ] ] false ] in-bypass: func [host bypass /local item x] [ if any [none? bypass empty? bypass] [return false] if not tuple? load host [host: form system/words/read join dns:// host] either find-bypass host bypass [ true ] [ host: system/words/read join dns:// host find-bypass host bypass ] ] either all [ port/proxy/host bp: not in-bypass port/host port/proxy/bypass find [socks4 socks5 socks] port/proxy/type ] [ port/sub-port: net-utils/connect-proxy/sub-protocol port 'connect subproto ] [ sub-port: system/words/open/lines compose [ scheme: (to-lit-word subproto) host: either all [port/proxy/type = 'generic generic bp] [port/proxy/host] [port/proxy/host: none port/host] user: port/user pass: port/pass port-id: either all [port/proxy/type = 'generic generic bp] [port/proxy/port-id] [port/port-id] ] port/sub-port: sub-port ] if all [secure find [ssl tls] subproto] [system/words/set-modes port/sub-port [secure: true]] port/sub-port/timeout: port/timeout port/sub-port/user: port/user port/sub-port/pass: port/pass port/sub-port/path: port/path port/sub-port/target: port/target net-utils/confirm/multiline port/sub-port open-check port/state/flags: port/state/flags or port-flags ] open: func [ port "the port to open" /local http-packet http-command response-actions success error response-line target headers http-version post-data result generic-proxy? sub-protocol build-port send-and-check create-request cookie-list][ port/locals: make object! [list: copy [] headers: none] generic-proxy?: all [port/proxy/type = 'generic not none? port/proxy/host] build-port: func [] [ sub-protocol: either port/scheme = 'https ['ssl] ['tcp] open-proto/sub-protocol/generic port sub-protocol ;port/url: rejoin [lowercase to-string port/scheme "://" port/host either port/port-id <> 80 [join #":" port/port-id] [copy ""] slash] ;We need to change port/scheme to http to fool the world (httpr is no protocol in real life) port/url: rejoin [lowercase to-string 'http "://" port/host either port/port-id <> 80 [join #":" port/port-id] [copy ""] slash] if found? port/path [append port/url port/path] if found? port/target [append port/url port/target] if sub-protocol = 'ssl [ if generic-proxy? [ HTTP-Get-Header: make object! [ Host: join port/host any [all [port/port-id (port/port-id <> 80) join #":" port/port-id] #] ] user: get in port/proxy 'user pass: get in port/proxy 'pass if string? :user [ HTTP-Get-Header: make HTTP-Get-Header [ Proxy-Authorization: join "Basic " enbase join user [#":" pass] ] ] http-packet: reform ["CONNECT" HTTP-Get-Header/Host "HTTP/1.1^/"] append http-packet net-utils/export HTTP-Get-Header append http-packet "^/" net-utils/net-log http-packet insert port/sub-port http-packet continue-post/tunnel ] system/words/set-modes port/sub-port [secure: true] ] ] http-command: "GET" HTTP-Get-Header: make object! [ Accept: "*/*" Connection: "close" ;User-Agent: get in get in system/schemes port/scheme 'user-agent User-Agent: "Rugby" Host: join port/host any [all [port/port-id (port/port-id <> 80) join #":" port/port-id] #] ] if all [block? port/state/custom post-data: select port/state/custom 'header block? post-data] [ HTTP-Get-Header: make HTTP-Get-Header post-data ] HTTP-Header: make object! [ Date: Server: Last-Modified: Accept-Ranges: Content-Encoding: Content-Type: Content-Length: Location: Expires: Referer: Connection: Authorization: none ] create-request: func [/local target user pass u] [ http-version: "HTTP/1.0^/" all [port/user port/pass HTTP-Get-Header: make HTTP-Get-Header [Authorization: join "Basic " enbase join port/user [#":" port/pass]]] user: get in port/proxy 'user pass: get in port/proxy 'pass if all [generic-proxy? string? :user] [ HTTP-Get-Header: make HTTP-Get-Header [ Proxy-Authorization: join "Basic " enbase join user [#":" pass] ] ] if port/state/index > 0 [ http-version: "HTTP/1.1^/" HTTP-Get-Header: make HTTP-Get-Header [ Range: rejoin ["bytes=" port/state/index "-"] ] ] target: next mold to-file join (join "/" either found? port/path [port/path] [""]) either found? port/target [port/target] [""] post-data: none if all [block? port/state/custom post-data: find port/state/custom 'post post-data/2] [ http-command: "POST" HTTP-Get-Header: make HTTP-Get-Header append [ Referer: either find port/url #"?" [head clear find copy port/url #"?"] [port/url] Content-Type: "application/x-www-form-urlencoded" Content-Length: length? post-data/2 ] either block? post-data/3 [post-data/3] [[]] post-data: post-data/2 ] http-packet: reform [http-command either generic-proxy? [port/url] [target] http-version] append http-packet net-utils/export HTTP-Get-Header append http-packet "^/" if post-data [append http-packet post-data] ] send-and-check: func [] [ net-utils/net-log http-packet insert port/sub-port http-packet return ;write-io port/sub-port http-packet length? http-packet ;We don't care about forwards and such as it is ;used for Rugby only ;continue-post ] continue-post: func [/tunnel] [ response-line: system/words/pick port/sub-port 1 net-utils/net-log response-line either none? response-line [do error] [ either none? result: select either tunnel [tunnel-actions] [response-actions] response-code: to-integer second parse response-line none [ do error] [ net-utils/net-log mold result do get result] ] ] tunnel-actions: [ 200 tunnel-success ] response-actions: [ 100 continue-post 200 success 201 success 204 success 206 success 300 forward 301 forward 302 forward 304 success 407 proxyauth ] tunnel-success: [ while [(line: pick port/sub-port 1) <> ""] [net-log line] ] ;success: [ ; headers: make string! 500 ; while [(line: pick port/sub-port 1) <> ""] [append headers join line "^/"] ; cookie-list: parse-cookies headers ; port/locals/headers: headers: Parse-Header HTTP-Header headers ; port/locals/headers: make port/locals/headers [ cookies: cookie-list] ; port/size: 0 ; if querying [if headers/Content-Length [port/size: load headers/Content-Length]] ; if error? try [port/date: parse-header-date headers/Last-Modified] [port/date: none] ; port/status: 'file ;] success: copy [print "***SUCCES***"] error: [ system/words/close port/sub-port net-error reform ["Error. Target url:" port/url "could not be retrieved. Server response:" response-line] ] forward: [ page: copy "" while [(str: pick port/sub-port 1) <> ""] [append page reduce [str newline]] headers: Parse-Header HTTP-Header page insert port/locals/list port/url either found? headers/Location [ either any [find/match headers/Location "http://" find/match headers/Location "https://"] [ port/path: port/target: port/port-id: none net-utils/URL-Parser/parse-url/set-scheme port to-url port/url: headers/Location ;port/scheme: 'HTTPR port/port-id: any [port/port-id get in get in system/schemes port/scheme 'port-id] ] [ either (first headers/Location) = slash [port/path: none remove headers/Location] [either port/path [insert port/path "/"] [port/path: copy "/"]] port/target: headers/Location port/url: rejoin [lowercase to-string port/scheme "://" port/host either port/path [port/path] [""] either port/target [port/target] [""]] ] if find/case port/locals/list port/url [net-error reform ["Error. Target url:" port/url {could not be retrieved. Circular forwarding detected}]] system/words/close port/sub-port build-port http-get-header/Host: port/host create-request send-and-check ] [ do error] ] proxyauth: [ system/words/close port/sub-port either all [generic-proxy? (not string? get in port/proxy 'user)] [ port/proxy/user: system/schemes/http/proxy/user: port/proxy/user port/proxy/pass: system/schemes/http/proxy/pass: port/proxy/pass if not error? [result: get in system/schemes 'https] [ result/proxy/user: port/proxy/user result/proxy/pass: port/proxy/pass ] ] [ net-error reform ["Error. Target url:" port/url {could not be retrieved: Proxy authentication denied}] ] build-port create-request send-and-check ] build-port create-request send-and-check ] close: func [port][system/words/close port/sub-port] write: func [ "Default write operation called from buffer layer." port "An open port spec" data "Data to write" ][ net-utils/net-log ["low level write of " port/state/num "bytes"] write-io port/sub-port data port/state/num ] read: func [ port "An open port spec" data "A buffer to use for the read" ][ net-utils/net-log ["low level read of " port/state/num "bytes"] read-io port/sub-port data port/state/num ] get-sub-port: func [ port "An open port spec" ][ port/sub-port ] awake: func [ port "An open port spec" ][ none ] get-modes: func [ port "An open port spec" modes "A mode block" ][ system/words/get-modes port/sub-port modes ] set-modes: func [ port "An open port spec" modes "A mode block" ][ system/words/set-modes port/sub-port modes ] querying: false query: func [port][ if not port/locals [ querying: true open port ] none ] ] net-utils/net-install HTTPR ctx-httpr 80 system/schemes/http: make system/schemes/http [user-agent: reform ["REBOL" system/version]]
lemma convex_finite: assumes "finite S" shows "convex S \<longleftrightarrow> (\<forall>u. (\<forall>x\<in>S. 0 \<le> u x) \<and> sum u S = 1 \<longrightarrow> sum (\<lambda>x. u x *\<^sub>R x) S \<in> S)" (is "?lhs = ?rhs")
{-# OPTIONS --allow-unsolved-metas #-} module _ where open import Agda.Primitive postulate Applicative : ∀ {a b} (F : Set a → Set b) → Set (lsuc a ⊔ b) record Traversable {a} (T : Set a) : Set (lsuc a) where constructor mkTrav field traverse : ∀ {F} {{AppF : Applicative F}} → T → F T -- unsolved metas in type of F postulate V : ∀ {a} → Set a travV : ∀ {a} {F : Set a → Set a} {{AppF : Applicative F}} → V → F V module M (a : Level) where TravV : Traversable {a} V TravV = mkTrav travV postulate a : Level F : Set → Set instance AppF : Applicative F mapM : V → F V mapM = Traversable.traverse (M.TravV _) -- Here we try to cast (TypeChecking.Constraints.castConstraintToCurrentContext) -- a level constraint from M talking about the local (a : Level) to the top-level -- (empty) context. This ought not result in an __IMPOSSIBLE__.
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.metric_space.lipschitz import topology.uniform_space.complete_separated /-! # Antilipschitz functions We say that a map `f : α → β` between two (extended) metric spaces is `antilipschitz_with K`, `K ≥ 0`, if for all `x, y` we have `edist x y ≤ K * edist (f x) (f y)`. For a metric space, the latter inequality is equivalent to `dist x y ≤ K * dist (f x) (f y)`. ## Implementation notes The parameter `K` has type `ℝ≥0`. This way we avoid conjuction in the definition and have coercions both to `ℝ` and `ℝ≥0∞`. We do not require `0 < K` in the definition, mostly because we do not have a `posreal` type. -/ variables {α : Type*} {β : Type*} {γ : Type*} open_locale nnreal uniformity open set /-- We say that `f : α → β` is `antilipschitz_with K` if for any two points `x`, `y` we have `K * edist x y ≤ edist (f x) (f y)`. -/ def antilipschitz_with [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) (f : α → β) := ∀ x y, edist x y ≤ K * edist (f x) (f y) lemma antilipschitz_with_iff_le_mul_dist [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0} {f : α → β} : antilipschitz_with K f ↔ ∀ x y, dist x y ≤ K * dist (f x) (f y) := by { simp only [antilipschitz_with, edist_nndist, dist_nndist], norm_cast } alias antilipschitz_with_iff_le_mul_dist ↔ antilipschitz_with.le_mul_dist antilipschitz_with.of_le_mul_dist lemma antilipschitz_with.mul_le_dist [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0} {f : α → β} (hf : antilipschitz_with K f) (x y : α) : ↑K⁻¹ * dist x y ≤ dist (f x) (f y) := begin by_cases hK : K = 0, by simp [hK, dist_nonneg], rw [nnreal.coe_inv, ← div_eq_inv_mul], rw div_le_iff' (nnreal.coe_pos.2 $ pos_iff_ne_zero.2 hK), exact hf.le_mul_dist x y end namespace antilipschitz_with variables [pseudo_emetric_space α] [pseudo_emetric_space β] [pseudo_emetric_space γ] variables {K : ℝ≥0} {f : α → β} /-- Extract the constant from `hf : antilipschitz_with K f`. This is useful, e.g., if `K` is given by a long formula, and we want to reuse this value. -/ @[nolint unused_arguments] -- uses neither `f` nor `hf` protected def K (hf : antilipschitz_with K f) : ℝ≥0 := K protected lemma injective {α : Type*} {β : Type*} [emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0} {f : α → β} (hf : antilipschitz_with K f) : function.injective f := λ x y h, by simpa only [h, edist_self, mul_zero, edist_le_zero] using hf x y lemma mul_le_edist (hf : antilipschitz_with K f) (x y : α) : ↑K⁻¹ * edist x y ≤ edist (f x) (f y) := begin by_cases hK : K = 0, by simp [hK], rw [ennreal.coe_inv hK, mul_comm, ← div_eq_mul_inv], apply ennreal.div_le_of_le_mul, rw mul_comm, exact hf x y end protected lemma id : antilipschitz_with 1 (id : α → α) := λ x y, by simp only [ennreal.coe_one, one_mul, id, le_refl] lemma comp {Kg : ℝ≥0} {g : β → γ} (hg : antilipschitz_with Kg g) {Kf : ℝ≥0} {f : α → β} (hf : antilipschitz_with Kf f) : antilipschitz_with (Kf * Kg) (g ∘ f) := λ x y, calc edist x y ≤ Kf * edist (f x) (f y) : hf x y ... ≤ Kf * (Kg * edist (g (f x)) (g (f y))) : ennreal.mul_left_mono (hg _ _) ... = _ : by rw [ennreal.coe_mul, mul_assoc] lemma restrict (hf : antilipschitz_with K f) (s : set α) : antilipschitz_with K (s.restrict f) := λ x y, hf x y lemma cod_restrict (hf : antilipschitz_with K f) {s : set β} (hs : ∀ x, f x ∈ s) : antilipschitz_with K (s.cod_restrict f hs) := λ x y, hf x y lemma to_right_inv_on' {s : set α} (hf : antilipschitz_with K (s.restrict f)) {g : β → α} {t : set β} (g_maps : maps_to g t s) (g_inv : right_inv_on g f t) : lipschitz_with K (t.restrict g) := λ x y, by simpa only [restrict_apply, g_inv x.mem, g_inv y.mem, subtype.edist_eq, subtype.coe_mk] using hf ⟨g x, g_maps x.mem⟩ ⟨g y, g_maps y.mem⟩ lemma to_right_inv_on (hf : antilipschitz_with K f) {g : β → α} {t : set β} (h : right_inv_on g f t) : lipschitz_with K (t.restrict g) := (hf.restrict univ).to_right_inv_on' (maps_to_univ g t) h lemma to_right_inverse (hf : antilipschitz_with K f) {g : β → α} (hg : function.right_inverse g f) : lipschitz_with K g := begin intros x y, have := hf (g x) (g y), rwa [hg x, hg y] at this end lemma comap_uniformity_le (hf : antilipschitz_with K f) : (𝓤 β).comap (prod.map f f) ≤ 𝓤 α := begin refine ((uniformity_basis_edist.comap _).le_basis_iff uniformity_basis_edist).2 (λ ε h₀, _), refine ⟨K⁻¹ * ε, ennreal.mul_pos.2 ⟨ennreal.inv_pos.2 ennreal.coe_ne_top, h₀⟩, _⟩, refine λ x hx, (hf x.1 x.2).trans_lt _, rw [mul_comm, ← div_eq_mul_inv] at hx, rw mul_comm, exact ennreal.mul_lt_of_lt_div hx end protected lemma uniform_inducing (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : uniform_inducing f := ⟨le_antisymm hf.comap_uniformity_le hfc.le_comap⟩ protected lemma uniform_embedding {α : Type*} {β : Type*} [emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0} {f : α → β} (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : uniform_embedding f := ⟨hf.uniform_inducing hfc, hf.injective⟩ lemma is_complete_range [complete_space α] (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : is_complete (range f) := (hf.uniform_inducing hfc).is_complete_range lemma is_closed_range {α β : Type*} [pseudo_emetric_space α] [emetric_space β] [complete_space α] {f : α → β} {K : ℝ≥0} (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : is_closed (range f) := (hf.is_complete_range hfc).is_closed lemma closed_embedding {α : Type*} {β : Type*} [emetric_space α] [emetric_space β] {K : ℝ≥0} {f : α → β} [complete_space α] (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : closed_embedding f := { closed_range := hf.is_closed_range hfc, .. (hf.uniform_embedding hfc).embedding } lemma subtype_coe (s : set α) : antilipschitz_with 1 (coe : s → α) := antilipschitz_with.id.restrict s lemma of_subsingleton [subsingleton α] {K : ℝ≥0} : antilipschitz_with K f := λ x y, by simp only [subsingleton.elim x y, edist_self, zero_le] end antilipschitz_with namespace antilipschitz_with open metric variables [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0} {f : α → β} lemma bounded_preimage (hf : antilipschitz_with K f) {s : set β} (hs : bounded s) : bounded (f ⁻¹' s) := exists.intro (K * diam s) $ λ x y hx hy, calc dist x y ≤ K * dist (f x) (f y) : hf.le_mul_dist x y ... ≤ K * diam s : mul_le_mul_of_nonneg_left (dist_le_diam_of_mem hs hx hy) K.2 /-- The image of a proper space under an expanding onto map is proper. -/ protected lemma proper_space {α : Type*} [metric_space α] {K : ℝ≥0} {f : α → β} [proper_space α] (hK : antilipschitz_with K f) (f_cont : continuous f) (hf : function.surjective f) : proper_space β := begin apply proper_space_of_compact_closed_ball_of_le 0 (λx₀ r hr, _), let K := f ⁻¹' (closed_ball x₀ r), have A : is_closed K := is_closed_ball.preimage f_cont, have B : bounded K := hK.bounded_preimage bounded_closed_ball, have : is_compact K := compact_iff_closed_bounded.2 ⟨A, B⟩, convert this.image f_cont, exact (hf.image_preimage _).symm end end antilipschitz_with lemma lipschitz_with.to_right_inverse [pseudo_emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0} {f : α → β} (hf : lipschitz_with K f) {g : β → α} (hg : function.right_inverse g f) : antilipschitz_with K g := λ x y, by simpa only [hg _] using hf (g x) (g y)
Formal statement is: lemma proper_map_polyfun_eq: assumes "f holomorphic_on UNIV" shows "(\<forall>k. compact k \<longrightarrow> compact {z. f z \<in> k}) \<longleftrightarrow> (\<exists>c n. 0 < n \<and> (c n \<noteq> 0) \<and> f = (\<lambda>z. \<Sum>i\<le>n. c i * z^i))" (is "?lhs = ?rhs") Informal statement is: A holomorphic function $f$ is proper if and only if there exist $c_0, c_1, \ldots, c_n$ and $n \in \mathbb{N}$ such that $c_n \neq 0$ and $f(z) = c_0 + c_1 z + \cdots + c_n z^n$.
From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrint seq. From CoqUtils Require Import word. From extructures Require Import fmap. Require Import Coq.Strings.String. Require Import Common.Either. Require Import Intermediate.Machine. Require Import MicroPolicies.Types. Require Import MicroPolicies.Instance. Require Import I2MP.Encode. Require Import I2MP.Linearize. Require Import Tests.RSC_DC_MD_Test. Require Import Tests.IntermediateProgramGeneration. From QuickChick Require Import QuickChick. Import QcDefaultNotation. Import QcNotation. Open Scope qc_scope. (* TL Questions: *) (* Do I really need compiler errors? *) (* ASW: what about unrespected interfaces? *) (* I do need traces, right? *) (* YEP!! *) (* What about execution errors? What's the needed level of details? *) (* Doesn't NEED to be meaningful *) (* REMINDER: if a compiled program has +16384 instructions, the alloc syscall won't work on the micro-policiy machine, due to address space layout and imm word size. *) Definition mp_program := { fmap mword mt -> matom }. Definition ExecutionResult := unit. Definition ExecutionError := unit. Fixpoint mp_exec (s : state) (fuel : nat) : (@Either ExecutionResult ExecutionError) * Log := let list_of_option {A : Type} (o : option A) : list A := match o with | None => nil | Some x => cons x nil end in match fuel with | O => (Common.Either.Right tt, nil) | S n => match stepf s with | Some (s', e) => let (r, l) := mp_exec s' n in (r, (list_of_option e ++ l))%list | None => (Common.Either.Left "The machine either halted or failed" tt, nil) end end. Definition mp_eval (p : mp_program) (fuel : nat) : (@Either ExecutionResult ExecutionError) * Log := mp_exec (load p) fuel. Definition compile_program (ip : Intermediate.program) : @Either mp_program False := Common.Either.Right (encode (linearize ip)). Instance show_false : Show False := {| show := (fun f => match (f: False) with end) |}. Definition mp_rsc_correct (fuel : nat) := let max_components := 15%nat in let min_components := 8%nat in rsc_correct empty_cag empty_dag min_components max_components compile_program mp_eval fuel. Definition run_rsc_test := show (quickCheck (mp_rsc_correct 500%nat)).
(* *********************************************************************) (* *) (* The CertiKOS Certified Kit Operating System *) (* *) (* The FLINT Group, Yale University *) (* *) (* Copyright The FLINT Group, Yale University. All rights reserved. *) (* This file is distributed under the terms of the Yale University *) (* Non-Commercial License Agreement. *) (* *) (* *********************************************************************) Require Import compcert.lib.Coqlib. Require Import compcert.common.Memtype. Require Import compcert.common.Globalenvs. Require Import liblayers.logic.LayerData. Require Import liblayers.compcertx.Stencil. Require Import liblayers.compcertx.AbstractData. Require Import liblayers.compcertx.Observation. Section WITH_MEMORY_MODEL. Context `{Hobs: Observation}. Context `{Hmem: Mem.MemoryModel}. Context `{Hstencil: Stencil}. (** * Abstract data and simulation relation blueprints *) Class CompatDataOps data := { empty_data : data; high_level_invariant: data -> Prop; low_level_invariant: block -> data -> Prop; kernel_mode: data -> Prop; observe: principal -> data -> obs }. Class CompatData data `{data_ops: CompatDataOps data} := { low_level_invariant_incr n n' d: (n <= n')%positive -> low_level_invariant n d -> low_level_invariant n' d; empty_data_low_level_invariant: forall n, low_level_invariant n empty_data; empty_data_high_level_invariant: high_level_invariant empty_data }. (** Although we do not need a memory model to define our [CompatData], it is needed for [LayerData], and so we include it here as well so that the coercion [compatdata_layerdata] can work properly. *) Record compatdata {mem} `{mem_ops: !Mem.MemoryModelOps mem} := { cdata_type : Type; cdata_ops : CompatDataOps cdata_type; cdata_prf : CompatData cdata_type }. Global Existing Instance cdata_ops. Global Existing Instance cdata_prf. Definition cdata := Build_compatdata. Global Arguments cdata {_ _} _ {_ _}. Class CompatRelOps `{stencil_ops: StencilOps} (D1 D2: compatdata) := { relate_AbData: stencil -> meminj -> cdata_type D1 -> cdata_type D2 -> Prop; match_AbData: stencil -> cdata_type D1 -> mem -> meminj -> Prop; new_glbl: list AST.ident }. Class CompatRel D1 D2 `{ops: !CompatRelOps D1 D2} := { match_compose: forall s d1 m2 f m2' j, match_AbData s d1 m2 f -> Mem.inject j m2 m2' -> inject_incr (Mem.flat_inj (genv_next s)) j -> match_AbData s d1 m2' (compose_meminj f j); store_match_correct: forall s abd m0 m0' f b2 v v' chunk, match_AbData s abd m0 f -> (forall i b, In i new_glbl -> find_symbol s i = Some b -> b <> b2) -> Mem.store chunk m0 b2 v v' = Some m0' -> match_AbData s abd m0' f; alloc_match_correct: forall s abd m'0 m'1 f f' ofs sz b0 b'1, match_AbData s abd m'0 f-> Mem.alloc m'0 ofs sz = (m'1, b'1) -> f' b0 = Some (b'1, 0%Z) -> (forall b : block, b <> b0 -> f' b = f b) -> inject_incr f f' -> (forall i b, In i new_glbl -> find_symbol s i = Some b -> b <> b0) -> match_AbData s abd m'1 f'; free_match_correct: forall s abd m0 m0' f ofs sz b2, match_AbData s abd m0 f-> (forall i b, In i new_glbl -> find_symbol s i = Some b -> b <> b2) -> Mem.free m0 b2 ofs sz = Some m0' -> match_AbData s abd m0' f; storebytes_match_correct: forall s abd m0 m0' f b2 v v', match_AbData s abd m0 f -> (forall i b, In i new_glbl -> find_symbol s i = Some b -> b <> b2) -> Mem.storebytes m0 b2 v v' = Some m0' -> match_AbData s abd m0' f; relate_incr: forall s abd abd' f f', relate_AbData s f abd abd' -> inject_incr f f' -> relate_AbData s f' abd abd'; relate_kernel_mode: forall s f abd abd', relate_AbData s f abd abd' -> (kernel_mode abd <-> kernel_mode abd'); relate_observe: forall s f abd abd' p, relate_AbData s f abd abd' -> observe p abd = observe p abd' }. Class compatrel D1 D2 := { crel_ops :> CompatRelOps D1 D2; crel_prf :> CompatRel D1 D2 }. Instance one_crel data1 data2 `{CompatData data1} `{CompatData data2} `{!CompatRelOps (cdata data1) (cdata data2)} `{!CompatRel (cdata data1) (cdata data2)}: compatrel (cdata data1) (cdata data2) := {}. Definition crel data1 data2 `{CompatData data1} `{CompatData data2} `{!CompatRelOps (cdata data1) (cdata data2)} `{!CompatRel (cdata data1) (cdata data2)}: freerg compatrel (cdata data1) (cdata data2) := freerg_inj _ _ _ (one_crel data1 data2). (* Global Existing Instance crel_ops. Global Existing Instance crel_prf. *) Global Instance compat_rg: ReflexiveGraph compatdata (freerg compatrel). (** * Compatibility with the new framework *) Instance compatdata_layerdata_ops data `{CompatDataOps data}: AbstractDataOps data := { init_data := empty_data; data_inject ι d1 d2 := True; inv m d := high_level_invariant d /\ low_level_invariant (Mem.nextblock m) d }. Instance compatdata_layerdata_prf: forall data `{CompatDataOps data}, CompatData data -> AbstractData data. Proof. intros data data_ops Hdata; split. * split. apply empty_data_high_level_invariant. apply empty_data_low_level_invariant. * intros d. apply I. * intros ι ι' d1 d2 d3 H12 H23. apply I. * intros ι1 ι2 Hι d1 d2 Hd d1' d2' Hd' H. apply I. Qed. Definition compatdata_layerdata (D: compatdata): layerdata := {| ldata_type := cdata_type D |}. End WITH_MEMORY_MODEL. Coercion compatdata_layerdata : compatdata >-> layerdata.
# Add alternative data importation commands for files in # the data folder that should not be imported using standard data importation rules
module Replica.App.Set import Control.App import Control.App.Console import Data.List import Language.JSON import Replica.App.FileSystem import Replica.App.Format import Replica.App.Log import Replica.App.Replica import Replica.Command.Set import Replica.Core import Replica.Option.Global import Replica.Other.Decorated import Replica.Other.String import Replica.Other.Validation import System.Path %default total export data HomeDir : Type where export data SetContext : Type where export updateConfig : List (String, JSON) -> Setter -> JSON updateConfig = updateConfig' [] where updateConfig' : List (String, JSON) -> List (String, JSON) -> Setter -> JSON updateConfig' xs [] (MkSetter key value) = JObject $ reverse $ (key, value) :: xs updateConfig' xs (x :: ys) s@(MkSetter key value) = if fst x == key then JObject $ reverse xs ++ ((key, value) :: ys) else updateConfig' (x :: xs) ys s export setReplica : FileSystem (FSError :: e) => Has [ Console , State HomeDir (Maybe String) , State SetContext SetCommand , State GlobalConfig Global , Exception ReplicaError ] e => App e () setReplica = do setCtx <- get SetContext debug "Set: \{show setCtx}" tgt <- case setCtx.target of Local => pure $ "."</> ".replica.json" Global => do Just hd <- get HomeDir | Nothing => throw $ InvalidJSON ["Can't access global config: No HOME"] pure $ hd </> ".replica.json" f <- catchNew (readFile tgt) (\err : FSError => case err of (MissingFile x) => pure $ show $ JObject [] pat => throw $ InvalidJSON ["Error when accessing config"]) let Just (JObject xs) = JSON.parse f | Nothing => throw $ InvalidJSON ["Can't parse current config \{show tgt} (either delete the file or fix its content)"] | Just _ => throw $ InvalidJSON ["Current config \{show tgt} is invalid (object expected) (either delete the file or fix its content)"] let newConfig = updateConfig xs !(setter <$> get SetContext) catchNew (writeFile tgt $ show newConfig) (\err : FSError => throw $ InvalidJSON ["Can't write config"])
module ArbFloats import Base: hash, convert, promote_rule, isa, string, show, showcompact, showall, parse, finalizer, decompose, precision, setprecision, copy, deepcopy, zero, one, isinteger, ldexp, frexp, eps, isequal, isless, (==),(!=),(<),(<=),(>=),(>), contains, min, max, minmax, isnan, isinf, isfinite, issubnormal, signbit, sign, flipsign, copysign, abs, inv, (+),(-),(*),(/),(\),(%),(^), sqrt, hypot, trunc, round, ceil, floor, fld, cld, div, mod, rem, divrem, fldmod, muladd, fma, exp, expm1, log, log1p, log2, log10, sin, cos, tan, csc, sec, cot, asin, acos, atan, atan2, sinh, cosh, tanh, csch, sech, coth, asinh, acosh, atanh, sinc, gamma, lgamma, digamma, zeta, factorial, BigInt, BigFloat, Cint export ArbFloat, # co-matched decimal rounding, n | round(hi,n,10) == round(lo,n,10) ArbFloat512, ArbFloat256, ArbFloat128, ArbFloat64, ArbFloat32, ArbFloat16, @ArbFloat, # converts string form of argument, precision is optional first arg in two arg form midpoint, radius, upperbound, lowerbound, bounds, stringCompact, stringAll, stringAllCompact, smartvalue, smartstring, showsmart, showallcompact, two, three, four, copymidpoint, copyradius, deepcopyradius, epsilon, trim, decompose, isexact, notexact, iszero, notzero, nonzero, isone, notone, notinteger, ispositive, notpositive, isnegative, notnegative, includesAnInteger, excludesIntegers, includesZero, excludesZero, includesPositive, excludesPositive, includesNegative, excludesNegative, includesNonpositive, includesNonnegative, notequal, approxeq, ≊, overlap, donotoverlap, iscontainedby, doesnotcontain, isnotcontainedby, invsqrt, pow, root, tanpi, cotpi, logbase, sincos, sincospi, sinhcosh, doublefactorial, risingfactorial, rgamma, agm, polylog, relativeError, relativeAccuracy, midpointPrecision, trimmedAccuracy, PI,SQRTPI,LOG2,LOG10,EXP1,EULER,CATALAN,KHINCHIN,GLAISHER,APERY, # constants MullerKahanChallenge # ensure the requisite libraries are available isdir(Pkg.dir("Nemo")) || throw(ErrorException("Nemo not found")) libDir = Pkg.dir("Nemo/local/lib"); libFiles = readdir(libDir); libarb = joinpath(libDir,libFiles[findfirst([startswith(x,"libarb") for x in libFiles])]) libflint = joinpath(libDir,libFiles[findfirst([startswith(x,"libflint") for x in libFiles])]) isfile(libarb) || throw(ErrorException("libarb not found")) isfile(libflint) || throw(ErrorException("libflint not found")) @static if is_linux() || is_bsd() || is_unix() libarb = String(split(libarb,".so")[1]) libflint = String(split(libflint,".so")[1]) end @static if is_apple() libarb = String(split(libarb,".dynlib")[1]) libflint = String(split(libflint,".dynlib")[1]) end @static if is_windows() libarb = String(split(libarb,".dll")[1]) libflint = String(split(libflint,".dll")[1]) end macro libarb(sym) (:($sym), libarb) end macro libflint(sym) (:($sym), libflint) end NotImplemented(info::AbstractString="") = error(string("this is not implemented\n\t",info,"\n")) include("type/ArfFloat.jl") include("type/ArbFloat.jl") include("type/primitive.jl") include("type/predicates.jl") include("type/string.jl") include("type/convert.jl") include("type/compare.jl") include("type/io.jl") include("math/arith.jl") include("math/round.jl") include("math/elementary.jl") include("math/constants.jl") include("math/special.jl") end # ArbFloats
import algebra.archimedean import data.list import all import .trythis namespace nng lemma add_assoc (a b c : ℕ) : (a + b) + c = a + (b + c) := begin -- rw [nat.add_assoc, nat.add_comm a], simp [nat.add_assoc] end open nat lemma succ_add (a b : ℕ) : succ a + b = succ (a + b) := begin -- rw [← add_succ, add_succ, succ_add] apply succ_add; rw [nat.add_comm, nat.zero_add]; refl end lemma add_right_comm (a b c : ℕ) : a + b + c = a + c + b := begin -- rw [add_comm a, add_comm a, add_assoc], -- rw [add_comm b, add_comm a, add_assoc] rw add_right_comm; refl end lemma succ_mul (a b : ℕ) : succ a * b = a * b + b := begin -- rw [← nat.succ_mul], rw [← add_one, succ_mul] end theorem add_le_add_right {a b : ℕ} : a ≤ b → ∀ t, (a + t) ≤ (b + t) := begin -- intros h t, -- rw [nat.add_comm a t, nat.add_comm b t], -- apply nat.add_le_add_left h _ apply nat.add_le_add_right end theorem mul_left_cancel (a b c : ℕ) (ha : a ≠ 0) : a * b = (a + 0) * c → b = 1 * c := begin -- simp, -- rintro (⟨⟨h₁, h₂⟩, rfl⟩ | ⟨⟨h₁, h₂⟩, rfl⟩), -- assumption, -- contradiction simpa [one_mul] using (mul_left_inj' ha).mp end lemma lt_aux_two (a b : ℕ) : succ a ≤ b → a ≤ b ∧ ¬ (b ≤ a) := begin intro h, exact ⟨nat.le_of_succ_le h, not_le_of_gt h⟩ end universe u variables {R : Type u} [linear_ordered_ring R] [floor_ring R] {x : R} lemma floor_ciel (z : ℤ) : z = ⌈(z:R)⌉ := begin -- rw [ceil, ← int.cast_neg, floor_coe, neg_neg] simp end example (x y : ℤ) : (- - x) - y = -(y - x) := begin -- simp simp end variables {G : Type u} [group G] example (x y z : G) : (x * z) * (z⁻¹ * y) = x * y := begin -- group rw [←mul_assoc, mul_inv_cancel_right] end open list example {α: Type u} (a : α) (l : list α) : list.reverse (l ++ [a]) = a :: l.reverse := begin simp -- induction l, {refl}, {simp only [*, cons_append, reverse_cons, append_assoc, reverse_nil, perm.nil, append_nil, perm.cons], simp} end end nng
{-# OPTIONS --cubical --no-import-sorts --safe #-} module Cubical.Experiments.CohomologyGroups where open import Cubical.ZCohomology.Base open import Cubical.ZCohomology.Properties open import Cubical.ZCohomology.MayerVietorisUnreduced open import Cubical.ZCohomology.Groups.Unit open import Cubical.ZCohomology.KcompPrelims open import Cubical.ZCohomology.Groups.Sn open import Cubical.Foundations.HLevels open import Cubical.Foundations.Prelude open import Cubical.Foundations.Structure open import Cubical.Foundations.Isomorphism open import Cubical.HITs.Pushout open import Cubical.HITs.Sn open import Cubical.HITs.SetTruncation renaming (rec to sRec ; elim to sElim ; elim2 to sElim2) hiding (map) open import Cubical.HITs.PropositionalTruncation renaming (rec to pRec ; ∥_∥ to ∥_∥₁ ; ∣_∣ to ∣_∣₁) hiding (map) open import Cubical.Data.Bool open import Cubical.Data.Sigma open import Cubical.Data.Int open import Cubical.Algebra.Group open GroupIso open GroupHom open BijectionIso -- --------------------------H¹(S¹) ----------------------------------- {- In order to apply Mayer-Vietoris, we need the following lemma. Given the following diagram a ↦ (a , 0) ψ ϕ A --> A × A -------> B ---> C If ψ is an isomorphism and ϕ is surjective with ker ϕ ≡ {ψ (a , a) ∣ a ∈ A}, then C ≅ B -} diagonalIso : ∀ {ℓ ℓ' ℓ''} {A : Group {ℓ}} (B : Group {ℓ'}) {C : Group {ℓ''}} (ψ : GroupIso (dirProd A A) B) (ϕ : GroupHom B C) → isSurjective _ _ ϕ → ((x : ⟨ B ⟩) → isInKer B C ϕ x → ∃[ y ∈ ⟨ A ⟩ ] x ≡ (fun (map ψ)) (y , y)) → ((x : ⟨ B ⟩) → (∃[ y ∈ ⟨ A ⟩ ] x ≡ (fun (map ψ)) (y , y)) → isInKer B C ϕ x) → GroupIso A C diagonalIso {A = A} B {C = C} ψ ϕ issurj ker→diag diag→ker = BijectionIsoToGroupIso bijIso where open GroupStr module A = GroupStr (snd A) module B = GroupStr (snd B) module C = GroupStr (snd C) module A×A = GroupStr (snd (dirProd A A)) module ψ = GroupIso ψ module ϕ = GroupHom ϕ ψ⁻ = inv ψ fstProj : GroupHom A (dirProd A A) fun fstProj a = a , GroupStr.0g (snd A) isHom fstProj g0 g1 i = (g0 A.+ g1) , GroupStr.lid (snd A) (GroupStr.0g (snd A)) (~ i) bijIso : BijectionIso A C map' bijIso = compGroupHom fstProj (compGroupHom (map ψ) ϕ) inj bijIso a inker = pRec (isSetCarrier A _ _) (λ {(a' , id) → (cong fst (sym (leftInv ψ (a , GroupStr.0g (snd A))) ∙∙ cong ψ⁻ id ∙∙ leftInv ψ (a' , a'))) ∙ cong snd (sym (leftInv ψ (a' , a')) ∙∙ cong ψ⁻ (sym id) ∙∙ leftInv ψ (a , GroupStr.0g (snd A)))}) (ker→diag _ inker) surj bijIso c = pRec propTruncIsProp (λ { (b , id) → ∣ (fst (ψ⁻ b) A.+ (A.- snd (ψ⁻ b))) , ((sym (GroupStr.rid (snd C) _) ∙∙ cong ((fun ϕ) ((fun (map ψ)) (fst (ψ⁻ b) A.+ (A.- snd (ψ⁻ b)) , GroupStr.0g (snd A))) C.+_) (sym (diag→ker (fun (map ψ) ((snd (ψ⁻ b)) , (snd (ψ⁻ b)))) ∣ (snd (ψ⁻ b)) , refl ∣₁)) ∙∙ sym ((isHom ϕ) _ _)) ∙∙ cong (fun ϕ) (sym ((isHom (map ψ)) _ _) ∙∙ cong (fun (map ψ)) (ΣPathP (sym (GroupStr.assoc (snd A) _ _ _) ∙∙ cong (fst (ψ⁻ b) A.+_) (GroupStr.invl (snd A) _) ∙∙ GroupStr.rid (snd A) _ , (GroupStr.lid (snd A) _))) ∙∙ rightInv ψ b) ∙∙ id) ∣₁ }) (issurj c) H¹-S¹≅ℤ : GroupIso intGroup (coHomGr 1 (S₊ 1)) H¹-S¹≅ℤ = diagonalIso (coHomGr 0 (S₊ 0)) (invGroupIso H⁰-S⁰≅ℤ×ℤ) (K.d 0) (λ x → K.Ker-i⊂Im-d 0 x (ΣPathP (isOfHLevelSuc 0 (isContrHⁿ-Unit 0) _ _ , isOfHLevelSuc 0 (isContrHⁿ-Unit 0) _ _))) ((sElim (λ _ → isOfHLevelΠ 2 λ _ → isOfHLevelSuc 1 propTruncIsProp) (λ x inker → pRec propTruncIsProp (λ {((f , g) , id') → helper x f g id' inker}) ((K.Ker-d⊂Im-Δ 0 ∣ x ∣₂ inker))))) ((sElim (λ _ → isOfHLevelΠ 2 λ _ → isOfHLevelPath 2 setTruncIsSet _ _) λ F surj → pRec (setTruncIsSet _ _) (λ { (x , id) → K.Im-Δ⊂Ker-d 0 ∣ F ∣₂ ∣ (∣ (λ _ → x) ∣₂ , ∣ (λ _ → 0) ∣₂) , (cong ∣_∣₂ (funExt (surjHelper x))) ∙ sym id ∣₁ }) surj) ) □ invGroupIso (coHomPushout≅coHomSn 0 1) where module K = MV Unit Unit (S₊ 0) (λ _ → tt) (λ _ → tt) surjHelper : (x : Int) (x₁ : S₊ 0) → x -[ 0 ]ₖ 0 ≡ S0→Int (x , x) x₁ surjHelper x true = Iso.leftInv (Iso-Kn-ΩKn+1 0) x surjHelper x false = Iso.leftInv (Iso-Kn-ΩKn+1 0) x helper : (F : S₊ 0 → Int) (f g : ∥ (Unit → Int) ∥₂) (id : GroupHom.fun (K.Δ 0) (f , g) ≡ ∣ F ∣₂) → isInKer (coHomGr 0 (S₊ 0)) (coHomGr 1 (Pushout (λ _ → tt) (λ _ → tt))) (K.d 0) ∣ F ∣₂ → ∃[ x ∈ Int ] ∣ F ∣₂ ≡ inv H⁰-S⁰≅ℤ×ℤ (x , x) helper F = sElim2 (λ _ _ → isOfHLevelΠ 2 λ _ → isOfHLevelΠ 2 λ _ → isOfHLevelSuc 1 propTruncIsProp) λ f g id inker → pRec propTruncIsProp (λ ((a , b) , id2) → sElim2 {C = λ f g → GroupHom.fun (K.Δ 0) (f , g) ≡ ∣ F ∣₂ → _ } (λ _ _ → isOfHLevelΠ 2 λ _ → isOfHLevelSuc 1 propTruncIsProp) (λ f g id → ∣ (helper2 f g .fst) , (sym id ∙ sym (helper2 f g .snd)) ∣₁) a b id2) (MV.Ker-d⊂Im-Δ _ _ (S₊ 0) (λ _ → tt) (λ _ → tt) 0 ∣ F ∣₂ inker) where helper2 : (f g : Unit → Int) → Σ[ x ∈ Int ] (inv H⁰-S⁰≅ℤ×ℤ (x , x)) ≡ GroupHom.fun (K.Δ 0) (∣ f ∣₂ , ∣ g ∣₂) helper2 f g = (f _ -[ 0 ]ₖ g _) , cong ∣_∣₂ (funExt λ {true → refl ; false → refl})
import numpy as np import tensorflow as tf from sklearn.model_selection import train_test_split from sklearn.utils.validation import check_array, check_X_y from tensorflow.contrib.distributions import Normal import baselines.common.tf_util as U from remps.model_approx.model_approximator import ModelApproximator from remps.utils.utils import get_default_tf_dtype def reduce_std(x, axis, dtype=tf.float32): mean = tf.reduce_mean(x, axis=axis, keepdims=True) var = tf.reduce_sum(tf.square(x - mean), axis=axis, keepdims=True) / ( tf.cast(tf.shape(x)[0], dtype) - 1 ) return tf.sqrt(var) class NNModel(ModelApproximator): def get_probability(self): return self.prob def __init__(self, state_dim, param_dim, name="NN", training_set_size=4000): """ Fit a NN for predicting the next state distribution Output of NN are the parameters of a parametric distribution (Gaussian) """ self.sess = None self.log_prob = None self.prob = None self.dtype = get_default_tf_dtype() # must be initialized self.name = name self.x_range = 4.8 self.theta_range = 180 self.XData = None self.YData = None self.state_dim = state_dim self.x_dim = state_dim + param_dim self.gp_list = [] self.training_set_size = training_set_size self.global_step = 0 self.folder = self.name + "NNData" + "/" self.min_omega = 0.1 self.max_omega = 30 def __call__( self, states, actions, next_states, initial_omega=8, training_set_size=4000, actions_one_hot=None, sess=None, summary_writer=None, ): """ :param states: Nxm matrix :param actions: Vector of all possible actions: Nx n_actions :param next_states: Nxm matrix containing the next states :param initial_omega: value of the initial omega :return: """ self.sess = sess self.training_set_size = training_set_size self.summary_writer = summary_writer train_or_test = U.get_placeholder("train_or_test", tf.bool, ()) # statistics self.Xmean_ph = U.get_placeholder( name="Xmean", dtype=self.dtype, shape=(1, self.x_dim) ) self.Ymean_ph = U.get_placeholder( name="Ymean", dtype=self.dtype, shape=(1, self.state_dim) ) self.Xstd_ph = U.get_placeholder( name="Xstd", dtype=self.dtype, shape=(1, self.x_dim) ) self.Ystd_ph = U.get_placeholder( name="Ystd", dtype=self.dtype, shape=(1, self.state_dim) ) self.X = U.get_placeholder(name="X", dtype=self.dtype, shape=(None, self.x_dim)) self.Y = U.get_placeholder( name="Y", dtype=self.dtype, shape=(None, self.state_dim) ) with tf.variable_scope(self.name): # build the action vector self.omega = tf.get_variable( dtype=self.dtype, name="omega", shape=(), initializer=tf.initializers.constant(initial_omega), ) X = self.X # - Xmean_) / Xstd_ Y = self.Y # - YMean_) / Ystd_ # build the action vector forces = self.omega * actions forces_full = tf.concat( [tf.reshape(forces[:, 0], (-1, 1)), tf.reshape(forces[:, 1], (-1, 1))], axis=0, ) batch_size = tf.shape(states)[0] x_full = tf.concat([states, states], axis=0) x_full = tf.concat([x_full, forces_full], axis=1) x_full = (x_full - self.Xmean_ph) / self.Xstd_ph next_states_full = tf.concat([next_states, next_states], axis=0) next_states_full = (next_states_full - self.Ymean_ph) / self.Ystd_ph # build the network hidden_layer_size = 10 biases = tf.get_variable( "b", [hidden_layer_size], initializer=tf.random_normal_initializer(0, 0.001, dtype=self.dtype), dtype=self.dtype, ) W = tf.get_variable( "W", [self.x_dim, hidden_layer_size], initializer=tf.random_normal_initializer(0, 0.001, dtype=self.dtype), dtype=self.dtype, ) x_input = U.switch(train_or_test, X, x_full) h = tf.matmul(x_input, W) h = tf.tanh(h + biases) # now we need state_dim output neurons, one for each state dimension to predict biases_out = tf.get_variable( "b_out", [self.state_dim], initializer=tf.random_normal_initializer(0, 0.001, dtype=self.dtype), dtype=self.dtype, ) W_out = tf.get_variable( "W_out", [hidden_layer_size, self.state_dim], initializer=tf.random_normal_initializer(0, 0.001, dtype=self.dtype), dtype=self.dtype, ) means = tf.matmul(h, W_out) + biases_out # x_input_first = x_input[:, 0:self.x_dim - 1] # forces = tf.reshape(x_input[:, self.x_dim - 1], (-1, 1)) # x_input = tf.concat([x_input_first, tf.abs(forces)], axis=1) hidden_var = 10 biases_var = tf.get_variable( "b_var", [hidden_var], initializer=tf.random_normal_initializer(0, 0.001, dtype=self.dtype), dtype=self.dtype, ) W_var = tf.get_variable( "W_var", [self.x_dim, hidden_var], initializer=tf.random_normal_initializer(0, 0.001, dtype=self.dtype), dtype=self.dtype, ) h = tf.nn.sigmoid(tf.matmul(x_input, W_var) + biases_var) W_out_var = tf.get_variable( "W_out_var", [hidden_var, self.state_dim], initializer=tf.random_normal_initializer(0, 0.001, dtype=self.dtype), dtype=self.dtype, ) biases_out_var = tf.get_variable( "b_out_var", [self.state_dim], initializer=tf.random_normal_initializer(0, 0.001, dtype=self.dtype), dtype=self.dtype, ) var = tf.exp(tf.matmul(h, W_out_var) + biases_out_var) std = tf.sqrt(var) pdf = Normal(means, std) y_output = U.switch(train_or_test, Y, next_states_full) log_prob = tf.reduce_sum(pdf.log_prob(y_output), axis=1, keepdims=True) prob = tf.reduce_prod(pdf.prob(y_output), axis=1, keepdims=True) # loss is the negative loss likelihood self.loss = -tf.reduce_mean(log_prob) self.valid_loss = -tf.reduce_mean(log_prob) self.fitting_vars = [ biases, W, biases_out, W_out, biases_var, W_var, W_out_var, biases_out_var, ] # create fitting collection for v in self.fitting_vars: tf.add_to_collection("fitting", v) opt = tf.train.AdamOptimizer() self.minimize_op = opt.minimize(self.loss, var_list=self.fitting_vars) log_prob_a0 = log_prob[0:batch_size, :] log_prob_a1 = log_prob[batch_size:, :] prob_a0 = prob[0:batch_size, :] prob_a1 = prob[batch_size:, :] self.log_prob = tf.concat([log_prob_a0, log_prob_a1], axis=1) self.prob = tf.concat([prob_a0, prob_a1], axis=1) means_list = [] var_list = [] for i in range(self.state_dim): means_a0 = tf.reshape(means[0:batch_size, i], (-1, 1)) means_a1 = tf.reshape(means[batch_size : 2 * batch_size, i], (-1, 1)) means_actions = tf.concat([means_a0, means_a1], axis=1) means_ = tf.reduce_sum( tf.multiply(means_actions, actions_one_hot), axis=1, keepdims=True ) means_list.append(means_) # same for variance var_a0 = tf.reshape(var[0:batch_size, i], (-1, 1)) var_a1 = tf.reshape(var[batch_size : 2 * batch_size, i], (-1, 1)) var_actions = tf.concat([var_a0, var_a1], axis=1) var_ = tf.reduce_sum( tf.multiply(var_actions, actions_one_hot), axis=1, keepdims=True ) var_list.append(var_) self.means = tf.concat(means_list, axis=1) self.variances = tf.concat(var_list, axis=1) self.train_or_test = train_or_test self.loss_summary = tf.summary.scalar("Loss", self.loss) self.valid_loss_summary = tf.summary.scalar("ValidLoss", self.valid_loss) return self.log_prob, self.prob def store_data(self, X, Y, normalize_data=False, update_statistics=True): """ Store training data inside training set """ X, Y = check_X_y(X, Y, multi_output=True, y_numeric=True) np.save(self.folder + "X.npy", X) np.save(self.folder + "Y.npy", Y) # if self.XData is None: # X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=42) # self.XData = X_train # self.YData = y_train # self.XTest = X_test # self.YTest = y_test # else: # self.XData = np.vstack((self.XData, X)) # self.YData = np.vstack((self.YData, Y)) # # if update_statistics: # if normalize_data: # self.Xmean = np.reshape(np.mean(self.XData, axis=0), (1,-1)) # self.Xstd = np.reshape(np.std(self.XData, axis=0), (1,-1)) # self.Ymean = np.reshape(np.mean(self.YData, axis=0), (1,-1)) # self.Ystd = np.reshape(np.std(self.YData, axis=0), (1,-1)) # else: # self.Xmean = np.zeros((1, np.shape(self.XData)[1]), dtype=self.XData.dtype) # self.Ymean = np.zeros((1, np.shape(self.YData)[1]), dtype=self.YData.dtype) # self.Xstd = np.ones((1, np.shape(self.XData)[1]), dtype=self.XData.dtype) # self.Ystd = np.ones((1, np.shape(self.YData)[1]), dtype=self.XData.dtype) # self.normalizedXData = (self.XData - self.Xmean) / self.Xstd # self.normalizedYData = (self.YData - self.Ymean) / self.Ystd # self.normalizedXTest = (self.XTest - self.Xmean) / self.Xstd # self.normalizedYTest = (self.YTest - self.Ymean) / self.Ystd # fit the gaussian process using XData and YData provided in store data def fit( self, load_from_file=False, save_to_file=True, action_ph=None, states_ph=None, next_states_ph=None, load_weights=True, add_onpolicy=False, training_step=40000, ): training_set_size = 100000 X = np.load(self.folder + "X.npy") Y = np.load(self.folder + "Y.npy") if add_onpolicy: X_onpolicy = np.load(self.folder + "on_policyX.npy") Y_onpolicy = np.load(self.folder + "on_policyY.npy") X = np.vstack((X, X_onpolicy)) Y = np.vstack((Y, Y_onpolicy)) X_train, X_test, y_train, y_test = train_test_split( X, Y, test_size=0.2, random_state=42 ) if not add_onpolicy: self.Xmean = np.reshape(np.mean(X_train, axis=0), (1, -1)) self.Xstd = np.reshape(np.std(X_train, axis=0), (1, -1)) self.Ymean = np.reshape(np.mean(y_train, axis=0), (1, -1)) self.Ystd = np.reshape(np.std(y_test, axis=0), (1, -1)) if not load_weights: X_train = (X_train - self.Xmean) / self.Xstd X_test = (X_test - self.Xmean) / self.Xstd y_train = (y_train - self.Ymean) / self.Ystd y_test = (y_test - self.Ymean) / self.Ystd batch_size = 10000 for _ in range(training_step): # sample a batch ind = np.arange(0, np.shape(X_train)[0]) selected_ind = np.random.choice(ind, size=batch_size, replace=False) inputs = X_train[selected_ind, :] targets = y_train[selected_ind, :] feed_dict = { self.train_or_test: True, self.X: inputs, self.Y: targets, self.Xmean_ph: self.Xmean, self.Ymean_ph: self.Ymean, self.Xstd_ph: self.Xstd, self.Ystd_ph: self.Ystd, # dummy things action_ph: [[0, 1]], states_ph: np.ones((1, X.shape[1] - 1)), next_states_ph: np.ones((1, Y.shape[1])), } # train loss, _, summary_str = self.sess.run( [self.loss, self.minimize_op, self.loss_summary], feed_dict=feed_dict, ) self.summary_writer.add_summary(summary_str, self.global_step) # validation feed_dict = { self.train_or_test: True, self.X: X_test, self.Y: y_test, self.Xmean_ph: self.Xmean, self.Ymean_ph: self.Ymean, self.Xstd_ph: self.Xstd, self.Ystd_ph: self.Ystd, # dummy things action_ph: [[0, 1]], states_ph: np.ones((1, X.shape[1] - 1)), next_states_ph: np.ones((1, Y.shape[1])), } valid_loss, loss_summary = self.sess.run( [self.valid_loss, self.valid_loss_summary], feed_dict=feed_dict ) self.summary_writer.add_summary(loss_summary, self.global_step) # print("Loss: ", loss) # print("Validation Loss: ", valid_loss) self.global_step += 1 print("FITTED!!") if not add_onpolicy: weights = U.GetFlat(self.fitting_vars)() np.save(self.folder + "weights.npy", weights) else: weights = np.load(self.folder + "weights.npy") U.SetFromFlat(self.fitting_vars, dtype=self.dtype)(weights) def get_omega(self): return self.omega def set_omega(self): pass def get_feed_dict(self): return { self.X: np.ones((1, self.Xmean.shape[1])), self.Y: np.ones((1, self.Ymean.shape[1])), self.Xmean_ph: self.Xmean, self.Xstd_ph: self.Xstd, self.Ymean_ph: self.Ymean, self.Ystd_ph: self.Ystd, self.train_or_test: False, } def get_variables_to_bound(self): return {self.omega: (self.min_omega, self.max_omega)} def get_variable_summaries(self): return [tf.summary.scalar("Omega", self.omega)] @property def trainable_vars(self): return [self.omega]
Require Export Omega. Set Implicit Arguments. Local Close Scope nat. Local Open Scope Z. Lemma Z_mul_neg1_r a: a * -1 = - a. Proof. omega. Qed. Lemma Z_add_neg_r a b: a + -b = a - b. Proof. omega. Qed. Ltac Z_simp_all := simpl in *; repeat rewrite Z.add_0_r in *; repeat rewrite Z.mul_1_r in *; repeat rewrite Z_mul_neg1_r in *; repeat rewrite Z_add_neg_r in *.
""" Backtracking line search using the Armijo-Goldstein condition.""" from math import isnan import numpy as np from openmdao.core.system import AnalysisError from openmdao.solvers.solver_base import LineSearch from openmdao.util.record_util import update_local_meta, create_local_meta class BackTracking(LineSearch): """A line search subsolver that implements backracking using the Armijo-Goldstein condition.. Options ------- options['err_on_maxiter'] : bool(False) If True, raise an AnalysisError if not converged at maxiter. options['iprint'] : int(0) Set to 0 to print only failures, set to 1 to print iteration totals to stdout, set to 2 to print the residual each iteration to stdout, or -1 to suppress all printing. options['maxiter'] : int(10) Maximum number of line searches. options['solve_subsystems'] : bool(True) Set to True to solve subsystems. You may need this for solvers nested under Newton. options['rho'] : int(0.5) Backtracking step. options['c'] : int(0.5) Slope check trigger. """ def __init__(self): super(BackTracking, self).__init__() opt = self.options opt.add_option('maxiter', 5, lower=0, desc='Maximum number of line searches.') opt.add_option('solve_subsystems', True, desc='Set to True to solve subsystems. You may need this for solvers nested under Newton.') opt.add_option('rho', 0.5, desc="Backtracking step.") opt.add_option('c', 0.5, desc="Slope check trigger.") self.print_name = 'BK_TKG' def solve(self, params, unknowns, resids, system, solver, alpha_scalar, alpha, base_u, base_norm, fnorm, fnorm0, metadata=None): """ Take the gradient calculated by the parent solver and figure out how far to go. Args ---- params : `VecWrapper` `VecWrapper` containing parameters. (p) unknowns : `VecWrapper` `VecWrapper` containing outputs and states. (u) resids : `VecWrapper` `VecWrapper` containing residuals. (r) system : `System` Parent `System` object. solver : `Solver` Parent solver instance. alpha_scalar : float Initial over-relaxation factor as used in parent solver. alpha : ndarray Initial over-relaxation factor as used in parent solver, vector (so we don't re-allocate). base_u : ndarray Initial value of unknowns before the Newton step. base_norm : float Norm of the residual prior to taking the Newton step. fnorm : float Norm of the residual after taking the Newton step. fnorm0 : float Initial norm of the residual for iteration printing. metadata : dict, optional Dictionary containing execution metadata (e.g. iteration coordinate). Returns -------- float Norm of the final residual """ maxiter = self.options['maxiter'] rho = self.options['rho'] c = self.options['c'] iprint = self.options['iprint'] result = system.dumat[None] local_meta = create_local_meta(metadata, system.pathname) itercount = 0 ls_alpha = alpha_scalar # Further backtacking if needed. # The Armijo-Goldstein is basically a slope comparison --actual vs predicted. # We don't have an actual gradient, but we have the Newton vector that should # take us to zero, and our "runs" are the same, and we can just compare the # "rise". while itercount < maxiter and (base_norm - fnorm) < c*ls_alpha*base_norm: ls_alpha *= rho # If our step will violate any upper or lower bounds, then reduce # alpha in just that direction so that we only step to that # boundary. unknowns.vec[:] = base_u alpha[:] = ls_alpha alpha = unknowns.distance_along_vector_to_limit(alpha, result) unknowns.vec += alpha*result.vec itercount += 1 # Metadata update update_local_meta(local_meta, (solver.iter_count, itercount)) # Just evaluate the model with the new points if self.options['solve_subsystems']: system.children_solve_nonlinear(local_meta) system.apply_nonlinear(params, unknowns, resids, local_meta) solver.recorders.record_iteration(system, local_meta) fnorm = resids.norm() if iprint == 2: self.print_norm(self.print_name, system, itercount, fnorm, fnorm0, indent=1, solver='LS') # Final residual print if you only want the last one if iprint == 1: self.print_norm(self.print_name, system, itercount, fnorm, fnorm0, indent=1, solver='LS') if itercount >= maxiter or isnan(fnorm): if self.options['err_on_maxiter']: msg = "Solve in '{}': BackTracking failed to converge after {} " \ "iterations." raise AnalysisError(msg.format(system.pathname, maxiter)) msg = 'FAILED to converge after %d iterations' % itercount fail = True else: msg = 'Converged in %d iterations' % itercount fail = False if iprint > 0 or (fail and iprint > -1 ): self.print_norm(self.print_name, system, itercount, fnorm, fnorm0, msg=msg, indent=1, solver='LS') return fnorm
\pgfkeys{ /pgfplots/Interval/.style={ axis x line=middle, axis y line=none, every axis x label/.style={ at={(ticklabel* cs:1.05)}, anchor=west, }, axis line style={stealth-stealth, thick}, label style={font=\large}, tick label style={font=\small}, samples=200, xmin=-5, xmax=5, ymin=0, ymax=5, domain=-5:5, y=0.5cm, restrict y to domain=0:4, axis lines=left, enlarge x limits=upper, scatter/classes={o={mark=*,fill=white}}, scatter, scatter src=explicit symbolic, every axis plot post/.style={mark=*,thick}, }} \chapter{Introduction}\label{chapter:intro} In this chapter we introduce key concepts that will be used in later chapters. For this reason, unlike other chapters it contains many statements, sometimes given without thorough explanations or reasoning. While all of these statements are grounded in deep ideas and can be formulated in a rigorous manner, it is advised to first get an intuitive understanding of the ideas before diving into their more formal construction. \vspace{2em} \begin{note}{In case you are already familiar with the topics}{} It is recommended for readers who are familiar with the topics to at least gloss over this chapter and make sure they know and understand all the concepts presented here. \end{note}
/** @file header.h * */ #ifndef HEADER_H #define HEADER_H #define _GNU_SOURCE #include <time.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <string.h> #include <omp.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_interp2d.h> #include <gsl/gsl_spline2d.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_sf_legendre.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_monte.h> #include <gsl/gsl_monte_vegas.h> #include <gsl/gsl_odeiv2.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_sf_expint.h> #include <ctype.h> #include "cuba.h" #define PSC 101L #define ST 102L #define TK 103L #define GROWTH 104L #define DERGROWTH 105L #define NONLINEAR 106L #define LINEAR 107L #define GAUSSIAN 114L #define NONGAUSSIAN 115L #define INIT 116L #define LOCAL 117L #define EQUILATERAL 118L #define ORTHOGONAL 119L #define QSF 120L #define HS 121L #define NGLOOP 122L #define derNGLOOP 123L #define QUADRATIC 124L #define TIDE 125L #define GAMMA 126L #define LPOWER 127L #define NLPOWER 128L #define CDM 90L #define BA 91L #define TOT 92L #define CO10 131L #define CO21 132L #define CO32 133L #define CO43 134L #define CO54 135L #define CO65 136L #define CII 137L #define MATTER 138L #define LINEMATTER 139L #define LINE 140L #define DST 141L #define GFILTER 142L #define BSPLINE 143L #define TREE 144L #define LOOP 145L #define WIR 146L #define NOIR 147L #define HALO 148L #define MEAN 149L #define HMshot 150L #define HMclust 151L #define PS_KMIN 1.e-5 #define PS_KMAX 300.1 #define PS_ZMAX 14. #define CLEANUP 1 #define DO_NOT_EVALUATE -1.0 #define NPARS 6 #define MAXL 2000 extern struct globals gb; /** * List of limHaloPT header files */ /// \cond DO_NOT_DOCUMENT #include "../Class/include/class.h" /// \endcond #include "global_structs.h" #include "hcubature.h" #include "utilities.h" #include "setup_teardown.h" #include "cosmology.h" #include "ir_res.h" #include "line_ingredients.h" #include "ps_halo_1loop.h" #include "ps_line_hm.h" #include "ps_line_pt.h" #include "survey_specs.h" #include "wnw_split.h" /** * A structure passed to the integrators to hold the parameters fixed in the integration */ struct integrand_parameters { double p1; double p2; double p3; double p4; double p5; double p6; double p7; double p8; double p9; double p10; double p11; long p12; long p13; }; /** * Another structure passed to the integrators to hold the parameters fixed in the integration */ struct integrand_parameters2 { struct Cosmology *p1; struct Cosmology *p2; struct Cosmology *p3; double p4; double p5; double p6; double p7; double p8; double p9; double p10; double p11; double p12; long p13; long p14; long p15; long p16; long p17; long p18; int p19; double *p20; size_t p22; }; #endif
[STATEMENT] lemma sdrop_numeral_scons[simp]: "x \<noteq> \<bottom> \<Longrightarrow> sdrop\<cdot>1\<cdot>(x :# xs) = xs" "x \<noteq> \<bottom> \<Longrightarrow> sdrop\<cdot>(numeral (Num.Bit0 k))\<cdot>(x :# xs) = sdrop\<cdot>(numeral (Num.BitM k))\<cdot>xs" "x \<noteq> \<bottom> \<Longrightarrow> sdrop\<cdot>(numeral (Num.Bit1 k))\<cdot>(x :# xs) = sdrop\<cdot>(numeral (Num.Bit0 k))\<cdot>xs" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x \<noteq> \<bottom> \<Longrightarrow> sdrop\<cdot>1\<cdot>(x :# xs) = xs) &&& (x \<noteq> \<bottom> \<Longrightarrow> sdrop\<cdot>(numeral (num.Bit0 k))\<cdot>(x :# xs) = sdrop\<cdot>(numeral (Num.BitM k))\<cdot>xs) &&& (x \<noteq> \<bottom> \<Longrightarrow> sdrop\<cdot>(numeral (num.Bit1 k))\<cdot>(x :# xs) = sdrop\<cdot>(numeral (num.Bit0 k))\<cdot>xs) [PROOF STEP] by (subst sdrop.simps, simp add: zero_Integer_def one_Integer_def numeral_Integer_eq; cases xs; simp)+
Formal statement is: lemma poly_power [simp]: "poly (p ^ n) x = poly p x ^ n" for p :: "'a::comm_semiring_1 poly" Informal statement is: The $n$th power of a polynomial is the polynomial whose value at $x$ is the $n$th power of the value of the original polynomial at $x$.
# 3. faza: Vizualizacija podatkov Odstotek <- (podatki$okuzbe) / podatki$rutinsko.dnevno Aktivne_okuzbe <- cumsum(podatki$okuzbe) Aktivne_okuzbe[15:154] = Aktivne_okuzbe[15:154]- Aktivne_okuzbe[1:140] CCA_aktivne_okuzbe <- cumsum((podatki$okuzbe) / podatki$rutinsko.dnevno * 1000) CCA_aktivne_okuzbe[15:154] = CCA_aktivne_okuzbe[15:154]- CCA_aktivne_okuzbe[1:140] US <- podatki_svet %>% filter(location=="United States") cases_cela_Evropa <- podatki_svet %>% group_by(date )%>% filter(continent== "Europe") %>% summarise(vsota_cela_EV = sum(total_cases_per_million/51,na.rm = TRUE)) #DNEVNO STEVILO TESTIRANJ dnevno_stevilo_testiranj_linija <- ggplot(podatki, aes(x=datum,y=rutinsko.dnevno)) + geom_line(col="red")+ geom_smooth(col="red") + ylab("Število testov na dan")+ ggtitle("Dnevno število testiranj v Sloveniji") #skupno stevilo okuzenih stevilo_okuzenih_nekonstantnovskonstantno <- ggplot(podatki %>% arrange(datum) %>% mutate(skupno.stevilo=cumsum(okuzbe), stevilo.konstantno=cumsum(okuzbe / rutinsko.dnevno) * mean(rutinsko.dnevno)) %>% gather("tip", "stevilo", skupno.stevilo, stevilo.konstantno), aes(x=datum, y=stevilo, color=tip)) + geom_line() + ylab("Skupno število okuženih") + ggtitle("Okuženi: konstantno in realno testiranje") #skupno stevilo testiranj stevilo_testiranj <- ggplot(podatki %>% group_by(datum) %>% summarise(stevilo=sum(rutinsko.dnevno),na.rm = TRUE) %>% arrange(datum) %>% mutate(skupno.stevilo=cumsum(stevilo)), aes(x=datum, y=skupno.stevilo/1000)) + geom_col(col="yellow")+ ylab("Skupno število testiranj v tisočih")+ ggtitle("Skupno število testiranj v Sloveniji") #MOŠKI VS ŽENSKE DNEVNO okuženi dnevno_stevilo_okuzenih_moskivszenske <- ggplot(podatki_spol, aes(x=datum, y=stevilo, color=spol)) + geom_smooth(size=1) + geom_line() + ylab("Število okuženih")+ ggtitle("Dnevno okuženih moški proti ženskam") #Dnevno testiranih vikend vs delovni dan dnevno_stevilo_testiranj_delovni_dan <- ggplot(podatki, aes(x=datum, y=rutinsko.dnevno, col = delovni.dan)) + geom_line() + geom_smooth(size=1)+ ylab("Število testiranj")+ ggtitle("Primerjava testiranja med delovnimi dnevi in vikendom v Sloveniji") #procent okuzenih procent_okuzenih_dnevno <- ggplot(podatki, aes(x=datum, y = Odstotek ))+ geom_line(col="blue")+ geom_smooth(fill="lightblue")+ ggtitle("Odstotek dnevno okuženih v Sloveniji") #Število dni okuženih 0-5, 5-10, 10-15.... frekvenca_stevila_okuzb <-ggplot(podatki, aes(x=okuzbe)) + geom_histogram(binwidth=5) #Celoten svet cases/million cases_cel_svet <- podatki_svet %>% group_by(date)%>% summarise(vsota_cel_svet = sum(total_cases_per_million/212,na.rm = TRUE)) stevilo_primerov_na_svetu_na_million <- ggplot(cases_cel_svet, aes(x=date,y=vsota_cel_svet)) + geom_line(size=3,col="red")+ ylab("Število okuženih na milijon")+ ggtitle("Število primerov na svetu na million prebivalcev") #prebivalstvo Evrope po drzavah prebivalstvo_EU <- podatki_svet %>% filter(continent == "Europe") %>% transmute(location, millions=total_cases/total_cases_per_million) %>% filter(!is.nan(millions), !is.na(millions)) %>% group_by(location) %>% summarise(millions=mean(millions)) #USA vs Europe podatki_EU_USA <- rbind(podatki_svet %>% filter(continent == "Europe") %>% group_by(date) %>% summarise(total_cases=sum(total_cases, na.rm=TRUE)) %>% transmute(date, location="Europe", total_cases_per_million=total_cases/sum(prebivalstvo_EU$millions)), podatki_svet %>% filter(location == "United States") %>% select(date, location, total_cases_per_million)) USAvsEU <- ggplot(podatki_EU_USA,aes(x = date,y = total_cases_per_million,col=location))+ geom_line(size=2)+ ylab("Število okuženih na milijon")+ ggtitle("Primerjava okuženosti ZDA proti Evropi") #Zemljevid data("World") Zemljevid_cases_per_million <- tm_shape(merge(World, podatki_svet %>% filter(date == "2020-05-05"), by.x="iso_a3", by.y="iso_code")) + tm_polygons("total_cases_per_million")
(*-------------------------------------------* | Example 1 [Roscoe_Dathi_1987 P.10] | | WITH computation | | Self-timed version of a systolic array | | June 2005 | | December 2005 (modified) | | | | on DFP on CSP-Prover ver.3.0 | | September 2006 (modified) | | | | on DFP on CSP-Prover ver.4.0 | | April 2007 (modified) | | | | on DFP on CSP-Prover ver.5.0 | | July 2009 (modified) | | | | CSP-Prover on Isabelle2012 | | November 2012 (modified) | | | | Yoshinao Isobe (AIST JAPAN) | *-------------------------------------------*) theory SA_main imports SA_condition SA_expanding SA_local begin (*=================================================================* | main theorem (deadlock freedom) | *=================================================================*) theorem Example1_ring: "ALL N. N ~= 0 --> DeadlockFreeNetwork (Systolic_Array N)" apply (intro allI impI) apply (rule Rule1_Roscoe_Dathi_1987_I) apply (simp_all) apply (rule EX1_isFailureOf[simplified Systolic_ArrayF_def]) (* nonempty *) apply (simp add: Array_Index_def) apply (fast) (* finite *) apply (simp add: Example1_finite) (* 3triple_disjoint*) apply (simp add: Example1_triple_disjoint[simplified Systolic_ArrayF_def]) (* BusyNetwork *) apply (simp add: Example1_BusyNetwork[simplified Systolic_ArrayF_def]) (* variant function *) apply (rule_tac x="(%(i,j). (%(s,X). (lengtht s) + 2 * (i + j)))" in exI) apply (simp) apply (intro ballI impI allI) apply (simp add: Example1_index_mem) apply (elim conjE exE) apply (rename_tac N ij1 ij2 t Yf i1 i2 j1 j2) apply (simp) apply (subgoal_tac "(i1 = i2 & j1 = Suc j2) | (i1 = i2 & j2 = Suc j1) | (i1 = Suc i2 & j1 = j2) | (i2 = Suc i1 & j1 = j2)") apply (elim conjE disjE) apply (simp add: local_hori_rev) apply (simp add: local_hori) apply (simp add: local_vert_rev) apply (simp add: local_vert) apply (simp add: possible_pairs) done (****************** to add it again ******************) end
Require Export PredMonad.Unordered.Monad. (*** *** Monads with State Effects ***) Section MonadState. Context (S : Type) {R_S} `{LR_S:@LR S R_S} (M : Type -> Type) `{MonadOps M}. (* State effects = get and put *) Class MonadStateOps : Type := { getM : M S ; putM : S -> M unit }. Class MonadState `{MonadStateOps} : Prop := { monad_state_monad :> Monad M; monad_proper_get :> Proper lr_leq getM; monad_proper_put :> Proper lr_leq putM; monad_state_get : forall {A} `{LR A} (m : M A), Proper lr_leq m -> bindM getM (fun _ => m) ~~ m ; monad_state_get_put : forall {A} `{LR A} (f : S -> unit -> M A), Proper lr_leq f -> bindM getM (fun s => bindM (putM s) (f s)) ~~ bindM getM (fun s => f s tt) ; monad_state_put_get : forall {A} `{LR A} s (f : unit -> S -> M A), Proper lr_leq s -> Proper lr_leq f -> bindM (putM s) (fun u => bindM getM (f u)) ~~ bindM (putM s) (fun u => f u s) ; monad_state_put_put : forall {A} `{LR A} s1 s2 (f : unit -> unit -> M A), Proper lr_leq s1 -> Proper lr_leq s2 -> Proper lr_leq f -> bindM (putM s1) (fun u => bindM (putM s2) (f u)) ~~ bindM (putM s2) (f tt) }. End MonadState. (*** *** The State Monad Transformer ***) Section StateT. Context (S:Type) {R_S:LR_Op S} `{@LR S R_S} (M:Type -> Type) `{Monad M}. Definition StateT (X:Type) := S -> M (S * X). Global Instance StateT_MonadOps : MonadOps StateT := {returnM := fun A x => fun s => returnM (s, x); bindM := fun A B m f => fun s => do s_x <- m s; f (snd s_x) (fst s_x); lrM := fun {A} _ => LR_Op_fun }. (* The Monad instance for StateT *) Global Instance StateT_Monad : Monad (StateT). Proof. constructor; intros; unfold StateT, returnM, bindM, lrM, StateT_MonadOps. - auto with typeclass_instances. - prove_lr_proper. - prove_lr_proper. - intros R1 R2 subR; apply LRFun_Proper_subrelation; apply monad_proper_lrM; apply LRPair_Proper_subrelation; try assumption; reflexivity. - prove_lr. - transitivity (fun s => do s_x <- m s; returnM s_x). + split; build_lr_fun; apply monad_proper_bind; prove_lr. + prove_lr; autorewrite with LR; prove_lr. - prove_lr. Qed. Global Instance StateT_MonadStateOps : MonadStateOps S StateT := { getM := fun s => returnM (s, s) ; putM := fun s _ => returnM (s, tt) }. Global Instance StateT_MonadState : MonadState S StateT. Proof. constructor; intros; unfold StateT, returnM, bindM, lrM, getM, putM, StateT_MonadOps, StateT_MonadStateOps. - auto with typeclass_instances. - prove_lr_proper. - prove_lr_proper. - prove_lr. - prove_lr. - prove_lr. - prove_lr. Qed. End StateT.
= = Release and reception = =
= = Release and reception = =
import NBG.SetTheory.Axioms.Extensionality -- Classoid private theorem ClassEqIsEquivalence : @Equivalence Class Class.Eq := { refl := ClassEq.refl, symm := ClassEq.symm, trans := ClassEq.trans } instance Classoid : Setoid Class where r := Class.Eq iseqv := ClassEqIsEquivalence def Class' : Type u := Quotient Classoid theorem Classoid.sound {X Y : Class}: X = Y → (Quot.mk Class.Eq X) = (Quot.mk Class.Eq Y) := fun h => Quot.sound h theorem Classoid.refl : ∀(X : Class'), X=X := by { intro _; apply Quot.inductionOn (motive := fun X => X=X); intro X; apply Classoid.sound; exact ClassEq.refl X; }
lemma order_2: assumes "p \<noteq> 0" shows "\<not> [:-a, 1:] ^ Suc (order a p) dvd p"
import os, sys import scipy.io tags = ['image', 'label'] print(sys.argv[1]) print(sys.argv[2]) for tag in tags: directory = os.path.join(sys.argv[1], tag) #'../../Segmentation_dataset/GTA/image' splitFile = sys.argv[2] #'../../Segmentation_dataset/GTA/mapping/split.mat' split = scipy.io.loadmat(splitFile) trainIds = list(split['trainIds'].reshape(-1)) valIds = list(split['valIds'].reshape(-1)) testIds = list(split['testIds'].reshape(-1)) trainDir='{}/train'.format(directory) valDir='{}/val'.format(directory) testDir='{}/test'.format(directory) if not os.path.exists(trainDir): os.mkdir(trainDir) if not os.path.exists(valDir): os.mkdir(valDir) if not os.path.exists(testDir): os.mkdir(testDir) i = 0 for filename in os.listdir(directory): if filename == 'train' or filename == 'val' or filename == 'test': pass elif int(filename.split('.')[0]) in trainIds: originalPath = os.path.join(directory, filename) newPath = os.path.join(trainDir, filename) i += 1 os.rename(originalPath, newPath) print('\r{}'.format(i), end = '') elif int(filename.split('.')[0]) in valIds: originalPath = os.path.join(directory, filename) newPath = os.path.join(valDir, filename) i += 1 os.rename(originalPath, newPath) print('\r{}'.format(i), end = '') elif int(filename.split('.')[0]) in testIds: originalPath = os.path.join(directory, filename) newPath = os.path.join(testDir, filename) i += 1 os.rename(originalPath, newPath) print('\r{}'.format(i), end = '') else: raise NotImplementedError
############################################################################# # # Mark Cembrowski, Janelia Research Campus, Nov 6 2016 # # This script plots does PCA for all hippocampal cells. # # If gsnList is supplied, then the PCA is performed on this list; otherwise, # high CV genes are chosen across a range of expression values. # ############################################################################# singleCellPca <- function(gsnList=c(),x='PC1',y='PC2',quiet=T, xLim=c(),yLim=c(),alpha=0.2){ subMat <- scHip if(length(gsnList)<0.1){ # Identify genes to use for analysis via overdispersion. theAvg <- apply(subMat,1,mean) binMin <- 1 # molecules/cell to consider use for analysis. subMat <- subMat[theAvg>binMin,] theAvg <- apply(subMat,1,mean) theSd <- apply(subMat,1,sd) theCv <- theSd/theAvg binSize <- 118 totGenesPerBin <- 3 subMat <- subMat[order(theAvg),] theAvg <- theAvg[order(theAvg)] theSd <- theSd[order(theAvg)] theCv <- theSd[order(theAvg)] genesToKeep <- c() for (ii in 1:(floor(length(theAvg))/binSize)){ firstInd <- 1+(ii-1)*binSize lastInd <- ii*binSize tempMat <- subMat[firstInd:lastInd,] tempCv <- apply(tempMat,1,sd)/apply(tempMat,1,mean) tempCv <- tempCv[order(-1*tempCv)] genesToKeep <- c(genesToKeep,names(tempCv)[1:totGenesPerBin]) } }else{ genesToKeep <- gsnList # Ensure all genes provided are in single cell data. genesToKeep <- genesToKeep[genesToKeep%in%rownames(scHip)] } print(paste('Using',length(genesToKeep),'for PCA')) # Do PCA. tempDat <- scHip[genesToKeep,] # Need to exclude genes if not expressed anywhere. isZero <- apply(tempDat,1,sum) < 0.1 tempDat <- tempDat[!isZero,] # tempDat <- log10(tempDat+1) colourRule <- c('astrocytes_ependymal'='blue', 'interneurons'='purple','microglia'='green', 'oligodendrocytes'='brown','endothelial-mural'='red','pyramidal CA1'='grey') PC <- prcomp(t(tempDat),scale=T) if(!quiet){print(summary(PC))} dat <- data.frame(obsnames=row.names(PC$x),PC$x) theClasses <- scMeta$level1class[colnames(scHip)] dat[,'grp'] <- theClasses[rownames(dat)] # Sort data frame for nice plotting. dat <- rbind( subset(dat,grp=='pyramidal CA1'), subset(dat,grp=='oligodendrocytes'), subset(dat,grp=='interneurons'), subset(dat,grp=='astrocytes_ependymal'), subset(dat,grp=='microglia'), subset(dat,grp=='endothelial-mural')) # dat <- dat[order(-dat$grp),] # # dat$grp <- factor(dat$grp,levels=c('astrocytes_ependymal', # 'interneurons','oligodendrocytes','endothelial-mural','microglia','pyramidal CA1')) plot <- ggplot(dat,aes_string(x=x,y=y)) plot <- plot + geom_point(alpha=alpha, size = 2, aes(label = obsnames,colour=grp)) plot <- plot + theme_bw() plot <- plot + scale_colour_manual(values=colourRule) # plot <- plot + scale_x_log10() + scale_y_log10() if(abs(length(xLim)-2)<0.1){plot <- plot + scale_x_continuous(lim=xLim)} if(abs(length(yLim)-2)<0.1){plot <- plot + scale_y_continuous(lim=yLim)} # plot <- plot + scale_x_continuous(lim=c(xLo,xHi)) # plot <- plot + scale_y_continuous(lim=c(yLo,yHi)) # if(xLabLo<0){ # plot <- plot + geom_text(data=subset(datLab,xVal<xLabLo),aes(x=xVal,y=yVal,label=obsnames),hjust=0,vjust=0,size=2) # } # if(xLabHi>0){ # plot <- plot + geom_text(data=subset(datLab,xVal>xLabHi),aes(x=xVal,y=yVal,label=obsnames),hjust=0,vjust=0,size=2) # } # if(yLabLo<0){ # plot <- plot + geom_text(data=subset(datLab,yVal<yLabLo),aes(x=xVal,y=yVal,label=obsnames),hjust=0,vjust=0,size=2) # } # if(yLabHi>0){ # plot <- plot + geom_text(data=subset(datLab,yVal>yLabHi),aes(x=xVal,y=yVal,label=obsnames),hjust=0,vjust=0,size=2) # } print(plot) }
The Xbox skill for Amazon Alex is now available in the UK. The skill (which is currently in beta) enables you to turn on and off your Xbox One, launch a game and control media playback. As well as controlling the Xbox via commands like “Alexa, tell Xbox to record that” the skill also enable the Xbox to work as a smart home device meaning you can ask “Alexa, turn on Xbox” or “Alexa, launch Forza Motorsport 6”. The skill means you can add Xbox to your smart home routines like a routine to turn on your TV, audio receiver, Xbox and load up Netflix. You can find the skill in the Alexa app.
[GOAL] K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V A B : Subspace K V ⊢ A.carrier = B.carrier → A = B [PROOFSTEP] cases A [GOAL] case mk K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V B : Subspace K V carrier✝ : Set (ℙ K V) mem_add'✝ : ∀ (v w : V) (hv : v ≠ 0) (hw : w ≠ 0) (hvw : v + w ≠ 0), Projectivization.mk K v hv ∈ carrier✝ → Projectivization.mk K w hw ∈ carrier✝ → Projectivization.mk K (v + w) hvw ∈ carrier✝ ⊢ { carrier := carrier✝, mem_add' := mem_add'✝ }.carrier = B.carrier → { carrier := carrier✝, mem_add' := mem_add'✝ } = B [PROOFSTEP] cases B [GOAL] case mk.mk K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V carrier✝¹ : Set (ℙ K V) mem_add'✝¹ : ∀ (v w : V) (hv : v ≠ 0) (hw : w ≠ 0) (hvw : v + w ≠ 0), Projectivization.mk K v hv ∈ carrier✝¹ → Projectivization.mk K w hw ∈ carrier✝¹ → Projectivization.mk K (v + w) hvw ∈ carrier✝¹ carrier✝ : Set (ℙ K V) mem_add'✝ : ∀ (v w : V) (hv : v ≠ 0) (hw : w ≠ 0) (hvw : v + w ≠ 0), Projectivization.mk K v hv ∈ carrier✝ → Projectivization.mk K w hw ∈ carrier✝ → Projectivization.mk K (v + w) hvw ∈ carrier✝ ⊢ { carrier := carrier✝¹, mem_add' := mem_add'✝¹ }.carrier = { carrier := carrier✝, mem_add' := mem_add'✝ }.carrier → { carrier := carrier✝¹, mem_add' := mem_add'✝¹ } = { carrier := carrier✝, mem_add' := mem_add'✝ } [PROOFSTEP] simp [GOAL] K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V A : Set (ℙ K V) B : Subspace K V ⊢ A ≤ ↑B → span A ≤ B [PROOFSTEP] intro h x hx [GOAL] K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V A : Set (ℙ K V) B : Subspace K V h : A ≤ ↑B x : ℙ K V hx : x ∈ span A ⊢ x ∈ B [PROOFSTEP] induction' hx with y hy [GOAL] case of K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V A : Set (ℙ K V) B : Subspace K V h : A ≤ ↑B x y : ℙ K V hy : y ∈ A ⊢ y ∈ B [PROOFSTEP] apply h [GOAL] case of.a K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V A : Set (ℙ K V) B : Subspace K V h : A ≤ ↑B x y : ℙ K V hy : y ∈ A ⊢ y ∈ A [PROOFSTEP] assumption [GOAL] case mem_add K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V A : Set (ℙ K V) B : Subspace K V h : A ≤ ↑B x : ℙ K V v✝ w✝ : V hv✝ : v✝ ≠ 0 hw✝ : w✝ ≠ 0 hvw✝ : v✝ + w✝ ≠ 0 a✝¹ : spanCarrier A (Projectivization.mk K v✝ hv✝) a✝ : spanCarrier A (Projectivization.mk K w✝ hw✝) a_ih✝¹ : Projectivization.mk K v✝ hv✝ ∈ B a_ih✝ : Projectivization.mk K w✝ hw✝ ∈ B ⊢ Projectivization.mk K (v✝ + w✝) hvw✝ ∈ B [PROOFSTEP] apply B.mem_add [GOAL] case mem_add.a K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V A : Set (ℙ K V) B : Subspace K V h : A ≤ ↑B x : ℙ K V v✝ w✝ : V hv✝ : v✝ ≠ 0 hw✝ : w✝ ≠ 0 hvw✝ : v✝ + w✝ ≠ 0 a✝¹ : spanCarrier A (Projectivization.mk K v✝ hv✝) a✝ : spanCarrier A (Projectivization.mk K w✝ hw✝) a_ih✝¹ : Projectivization.mk K v✝ hv✝ ∈ B a_ih✝ : Projectivization.mk K w✝ hw✝ ∈ B ⊢ Projectivization.mk K v✝ ?mem_add.hv ∈ B case mem_add.a K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V A : Set (ℙ K V) B : Subspace K V h : A ≤ ↑B x : ℙ K V v✝ w✝ : V hv✝ : v✝ ≠ 0 hw✝ : w✝ ≠ 0 hvw✝ : v✝ + w✝ ≠ 0 a✝¹ : spanCarrier A (Projectivization.mk K v✝ hv✝) a✝ : spanCarrier A (Projectivization.mk K w✝ hw✝) a_ih✝¹ : Projectivization.mk K v✝ hv✝ ∈ B a_ih✝ : Projectivization.mk K w✝ hw✝ ∈ B ⊢ Projectivization.mk K w✝ ?mem_add.hw ∈ B case mem_add.hv K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V A : Set (ℙ K V) B : Subspace K V h : A ≤ ↑B x : ℙ K V v✝ w✝ : V hv✝ : v✝ ≠ 0 hw✝ : w✝ ≠ 0 hvw✝ : v✝ + w✝ ≠ 0 a✝¹ : spanCarrier A (Projectivization.mk K v✝ hv✝) a✝ : spanCarrier A (Projectivization.mk K w✝ hw✝) a_ih✝¹ : Projectivization.mk K v✝ hv✝ ∈ B a_ih✝ : Projectivization.mk K w✝ hw✝ ∈ B ⊢ v✝ ≠ 0 case mem_add.hw K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V A : Set (ℙ K V) B : Subspace K V h : A ≤ ↑B x : ℙ K V v✝ w✝ : V hv✝ : v✝ ≠ 0 hw✝ : w✝ ≠ 0 hvw✝ : v✝ + w✝ ≠ 0 a✝¹ : spanCarrier A (Projectivization.mk K v✝ hv✝) a✝ : spanCarrier A (Projectivization.mk K w✝ hw✝) a_ih✝¹ : Projectivization.mk K v✝ hv✝ ∈ B a_ih✝ : Projectivization.mk K w✝ hw✝ ∈ B ⊢ w✝ ≠ 0 [PROOFSTEP] assumption' [GOAL] K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V A : Set (Subspace K V) v w : V hv : v ≠ 0 hw : w ≠ 0 hvw : v + w ≠ 0 h1 : Projectivization.mk K v hv ∈ sInf (SetLike.coe '' A) h2 : Projectivization.mk K w hw ∈ sInf (SetLike.coe '' A) t : Set (ℙ K V) ⊢ t ∈ SetLike.coe '' A → Projectivization.mk K (v + w) hvw ∈ t [PROOFSTEP] rintro ⟨s, hs, rfl⟩ [GOAL] case intro.intro K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V A : Set (Subspace K V) v w : V hv : v ≠ 0 hw : w ≠ 0 hvw : v + w ≠ 0 h1 : Projectivization.mk K v hv ∈ sInf (SetLike.coe '' A) h2 : Projectivization.mk K w hw ∈ sInf (SetLike.coe '' A) s : Subspace K V hs : s ∈ A ⊢ Projectivization.mk K (v + w) hvw ∈ ↑s [PROOFSTEP] exact s.mem_add v w hv hw _ (h1 s ⟨s, hs, rfl⟩) (h2 s ⟨s, hs, rfl⟩) [GOAL] K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V src✝ : Inf (Subspace K V) := inferInstance ⊢ ∀ (s : Set (Subspace K V)), IsGLB s (sInf s) [PROOFSTEP] refine fun s => ⟨fun a ha x hx => hx _ ⟨a, ha, rfl⟩, fun a ha x hx E => ?_⟩ [GOAL] K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V src✝ : Inf (Subspace K V) := inferInstance s : Set (Subspace K V) a : Subspace K V ha : a ∈ lowerBounds s x : ℙ K V hx : x ∈ a E : Set (ℙ K V) ⊢ E ∈ SetLike.coe '' s → x ∈ E [PROOFSTEP] rintro ⟨E, hE, rfl⟩ [GOAL] case intro.intro K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V src✝ : Inf (Subspace K V) := inferInstance s : Set (Subspace K V) a : Subspace K V ha : a ∈ lowerBounds s x : ℙ K V hx : x ∈ a E : Subspace K V hE : E ∈ s ⊢ x ∈ ↑E [PROOFSTEP] exact ha hE hx [GOAL] K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V ⊢ span Set.univ = ⊤ [PROOFSTEP] rw [eq_top_iff, SetLike.le_def] [GOAL] K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V ⊢ ∀ ⦃x : ℙ K V⦄, x ∈ ⊤ → x ∈ span Set.univ [PROOFSTEP] intro x _hx [GOAL] K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V x : ℙ K V _hx : x ∈ ⊤ ⊢ x ∈ span Set.univ [PROOFSTEP] exact subset_span _ (Set.mem_univ x) [GOAL] K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V S : Set (ℙ K V) W : Subspace K V ⊢ W ⊔ span S = span (↑W ∪ S) [PROOFSTEP] rw [span_union, span_coe] [GOAL] K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V S : Set (ℙ K V) W : Subspace K V ⊢ span S ⊔ W = span (S ∪ ↑W) [PROOFSTEP] rw [span_union, span_coe] [GOAL] K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V S : Set (ℙ K V) u : ℙ K V ⊢ u ∈ span S ↔ ∀ (W : Subspace K V), S ⊆ ↑W → u ∈ W [PROOFSTEP] simp_rw [← span_le_subspace_iff] [GOAL] K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V S : Set (ℙ K V) u : ℙ K V ⊢ u ∈ span S ↔ ∀ (W : Subspace K V), span S ≤ W → u ∈ W [PROOFSTEP] exact ⟨fun hu W hW => hW hu, fun W => W (span S) (le_refl _)⟩ [GOAL] K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V S : Set (ℙ K V) ⊢ span S = sInf {W | S ⊆ ↑W} [PROOFSTEP] ext x [GOAL] case carrier.h K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V S : Set (ℙ K V) x : ℙ K V ⊢ x ∈ (span S).carrier ↔ x ∈ (sInf {W | S ⊆ ↑W}).carrier [PROOFSTEP] simp_rw [mem_carrier_iff, mem_span x] [GOAL] case carrier.h K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V S : Set (ℙ K V) x : ℙ K V ⊢ (∀ (W : Subspace K V), S ⊆ ↑W → x ∈ W) ↔ x ∈ sInf {W | S ⊆ ↑W} [PROOFSTEP] refine ⟨fun hx => ?_, fun hx W hW => ?_⟩ [GOAL] case carrier.h.refine_1 K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V S : Set (ℙ K V) x : ℙ K V hx : ∀ (W : Subspace K V), S ⊆ ↑W → x ∈ W ⊢ x ∈ sInf {W | S ⊆ ↑W} [PROOFSTEP] rintro W ⟨T, hT, rfl⟩ [GOAL] case carrier.h.refine_1.intro.intro K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V S : Set (ℙ K V) x : ℙ K V hx : ∀ (W : Subspace K V), S ⊆ ↑W → x ∈ W T : Subspace K V hT : T ∈ {W | S ⊆ ↑W} ⊢ x ∈ ↑T [PROOFSTEP] exact hx T hT [GOAL] case carrier.h.refine_2 K : Type u_1 V : Type u_2 inst✝² : Field K inst✝¹ : AddCommGroup V inst✝ : Module K V S : Set (ℙ K V) x : ℙ K V hx : x ∈ sInf {W | S ⊆ ↑W} W : Subspace K V hW : S ⊆ ↑W ⊢ x ∈ W [PROOFSTEP] exact (@sInf_le _ _ {W : Subspace K V | S ⊆ ↑W} W hW) hx
[GOAL] R : Type u L : Type v inst✝² : CommRing R inst✝¹ : LieRing L inst✝ : LieAlgebra R L I : LieIdeal R L h : LieModule.IsTrivial L { x // x ∈ ↑I } x y : { x // x ∈ ↑I } ⊢ ⁅x, y⁆ = 0 [PROOFSTEP] apply h.trivial [GOAL] R : Type u L₁ : Type v L₂ : Type w inst✝⁴ : CommRing R inst✝³ : LieRing L₁ inst✝² : LieRing L₂ inst✝¹ : LieAlgebra R L₁ inst✝ : LieAlgebra R L₂ f : L₁ →ₗ⁅R⁆ L₂ h₁ : Surjective ↑f h₂ : IsLieAbelian L₁ x y : L₂ ⊢ ⁅x, y⁆ = 0 [PROOFSTEP] obtain ⟨u, rfl⟩ := h₁ x [GOAL] case intro R : Type u L₁ : Type v L₂ : Type w inst✝⁴ : CommRing R inst✝³ : LieRing L₁ inst✝² : LieRing L₂ inst✝¹ : LieAlgebra R L₁ inst✝ : LieAlgebra R L₂ f : L₁ →ₗ⁅R⁆ L₂ h₁ : Surjective ↑f h₂ : IsLieAbelian L₁ y : L₂ u : L₁ ⊢ ⁅↑f u, y⁆ = 0 [PROOFSTEP] obtain ⟨v, rfl⟩ := h₁ y [GOAL] case intro.intro R : Type u L₁ : Type v L₂ : Type w inst✝⁴ : CommRing R inst✝³ : LieRing L₁ inst✝² : LieRing L₂ inst✝¹ : LieAlgebra R L₁ inst✝ : LieAlgebra R L₂ f : L₁ →ₗ⁅R⁆ L₂ h₁ : Surjective ↑f h₂ : IsLieAbelian L₁ u v : L₁ ⊢ ⁅↑f u, ↑f v⁆ = 0 [PROOFSTEP] rw [← LieHom.map_lie, trivial_lie_zero, LieHom.map_zero] [GOAL] A : Type v inst✝ : Ring A ⊢ (IsCommutative A fun x x_1 => x * x_1) ↔ IsLieAbelian A [PROOFSTEP] have h₁ : IsCommutative A (· * ·) ↔ ∀ a b : A, a * b = b * a := ⟨fun h => h.1, fun h => ⟨h⟩⟩ [GOAL] A : Type v inst✝ : Ring A h₁ : (IsCommutative A fun x x_1 => x * x_1) ↔ ∀ (a b : A), a * b = b * a ⊢ (IsCommutative A fun x x_1 => x * x_1) ↔ IsLieAbelian A [PROOFSTEP] have h₂ : IsLieAbelian A ↔ ∀ a b : A, ⁅a, b⁆ = 0 := ⟨fun h => h.1, fun h => ⟨h⟩⟩ [GOAL] A : Type v inst✝ : Ring A h₁ : (IsCommutative A fun x x_1 => x * x_1) ↔ ∀ (a b : A), a * b = b * a h₂ : IsLieAbelian A ↔ ∀ (a b : A), ⁅a, b⁆ = 0 ⊢ (IsCommutative A fun x x_1 => x * x_1) ↔ IsLieAbelian A [PROOFSTEP] simp only [h₁, h₂, LieRing.of_associative_ring_bracket, sub_eq_zero] [GOAL] R : Type u L : Type v inst✝² : CommRing R inst✝¹ : LieRing L inst✝ : LieAlgebra R L x✝¹ x✝ : { x // x ∈ ↑⊥ } x : L hx : x ∈ ↑⊥ ⊢ ⁅{ val := x, property := hx }, x✝⁆ = 0 [PROOFSTEP] simp [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N x : L ⊢ x ∈ LieModule.ker R L M ↔ ∀ (m : M), ⁅x, m⁆ = 0 [PROOFSTEP] simp only [LieModule.ker, LieHom.mem_ker, LinearMap.ext_iff, LinearMap.zero_apply, toEndomorphism_apply_apply] [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N x y : M hx : x ∈ {m | ∀ (x : L), ⁅x, m⁆ = 0} hy : y ∈ {m | ∀ (x : L), ⁅x, m⁆ = 0} z : L ⊢ ⁅z, x + y⁆ = 0 [PROOFSTEP] rw [lie_add, hx, hy, add_zero] [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N c : R x : M hx : x ∈ { toAddSubsemigroup := { carrier := {m | ∀ (x : L), ⁅x, m⁆ = 0}, add_mem' := (_ : ∀ {x y : M}, x ∈ {m | ∀ (x : L), ⁅x, m⁆ = 0} → y ∈ {m | ∀ (x : L), ⁅x, m⁆ = 0} → ∀ (z : L), ⁅z, x + y⁆ = 0) }, zero_mem' := (_ : ∀ (x : L), ⁅x, 0⁆ = 0) }.toAddSubsemigroup.carrier y : L ⊢ ⁅y, c • x⁆ = 0 [PROOFSTEP] rw [lie_smul, hx, smul_zero] [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N x : L m : M hm : m ∈ { toAddSubmonoid := { toAddSubsemigroup := { carrier := {m | ∀ (x : L), ⁅x, m⁆ = 0}, add_mem' := (_ : ∀ {x y : M}, x ∈ {m | ∀ (x : L), ⁅x, m⁆ = 0} → y ∈ {m | ∀ (x : L), ⁅x, m⁆ = 0} → ∀ (z : L), ⁅z, x + y⁆ = 0) }, zero_mem' := (_ : ∀ (x : L), ⁅x, 0⁆ = 0) }, smul_mem' := (_ : ∀ (c : R) (x : M), x ∈ { toAddSubsemigroup := { carrier := {m | ∀ (x : L), ⁅x, m⁆ = 0}, add_mem' := (_ : ∀ {x y : M}, x ∈ {m | ∀ (x : L), ⁅x, m⁆ = 0} → y ∈ {m | ∀ (x : L), ⁅x, m⁆ = 0} → ∀ (z : L), ⁅z, x + y⁆ = 0) }, zero_mem' := (_ : ∀ (x : L), ⁅x, 0⁆ = 0) }.toAddSubsemigroup.carrier → ∀ (y : L), ⁅y, c • x⁆ = 0) }.toAddSubmonoid.toAddSubsemigroup.carrier y : L ⊢ ⁅y, ⁅x, m⁆⁆ = 0 [PROOFSTEP] rw [hm, lie_zero] [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N I : LieIdeal R L ⊢ ⁅I, maxTrivSubmodule R L M⁆ = ⊥ [PROOFSTEP] rw [← LieSubmodule.coe_toSubmodule_eq_iff, LieSubmodule.lieIdeal_oper_eq_linear_span, LieSubmodule.bot_coeSubmodule, Submodule.span_eq_bot] [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N I : LieIdeal R L ⊢ ∀ (x : M), x ∈ {m | ∃ x n, ⁅↑x, ↑n⁆ = m} → x = 0 [PROOFSTEP] rintro m ⟨⟨x, hx⟩, ⟨⟨m, hm⟩, rfl⟩⟩ [GOAL] case intro.mk.intro.mk R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N I : LieIdeal R L x : L hx : x ∈ I m : M hm : m ∈ maxTrivSubmodule R L M ⊢ ⁅↑{ val := x, property := hx }, ↑{ val := m, property := hm }⁆ = 0 [PROOFSTEP] exact hm x [GOAL] R : Type u L : Type v M : Type w N✝ : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N✝ inst✝² : Module R N✝ inst✝¹ : LieRingModule L N✝ inst✝ : LieModule R L N✝ N : LieSubmodule R L M ⊢ N ≤ maxTrivSubmodule R L M ↔ ⁅⊤, N⁆ = ⊥ [PROOFSTEP] refine' ⟨fun h => _, fun h m hm => _⟩ [GOAL] case refine'_1 R : Type u L : Type v M : Type w N✝ : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N✝ inst✝² : Module R N✝ inst✝¹ : LieRingModule L N✝ inst✝ : LieModule R L N✝ N : LieSubmodule R L M h : N ≤ maxTrivSubmodule R L M ⊢ ⁅⊤, N⁆ = ⊥ [PROOFSTEP] rw [← le_bot_iff, ← ideal_oper_maxTrivSubmodule_eq_bot R L M ⊤] [GOAL] case refine'_1 R : Type u L : Type v M : Type w N✝ : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N✝ inst✝² : Module R N✝ inst✝¹ : LieRingModule L N✝ inst✝ : LieModule R L N✝ N : LieSubmodule R L M h : N ≤ maxTrivSubmodule R L M ⊢ ⁅⊤, N⁆ ≤ ⁅⊤, maxTrivSubmodule R L M⁆ [PROOFSTEP] exact LieSubmodule.mono_lie_right _ _ ⊤ h [GOAL] case refine'_2 R : Type u L : Type v M : Type w N✝ : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N✝ inst✝² : Module R N✝ inst✝¹ : LieRingModule L N✝ inst✝ : LieModule R L N✝ N : LieSubmodule R L M h : ⁅⊤, N⁆ = ⊥ m : M hm : m ∈ N ⊢ m ∈ maxTrivSubmodule R L M [PROOFSTEP] rw [mem_maxTrivSubmodule] [GOAL] case refine'_2 R : Type u L : Type v M : Type w N✝ : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N✝ inst✝² : Module R N✝ inst✝¹ : LieRingModule L N✝ inst✝ : LieModule R L N✝ N : LieSubmodule R L M h : ⁅⊤, N⁆ = ⊥ m : M hm : m ∈ N ⊢ ∀ (x : L), ⁅x, m⁆ = 0 [PROOFSTEP] rw [LieSubmodule.lie_eq_bot_iff] at h [GOAL] case refine'_2 R : Type u L : Type v M : Type w N✝ : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N✝ inst✝² : Module R N✝ inst✝¹ : LieRingModule L N✝ inst✝ : LieModule R L N✝ N : LieSubmodule R L M h : ∀ (x : L), x ∈ ⊤ → ∀ (m : M), m ∈ N → ⁅x, m⁆ = 0 m : M hm : m ∈ N ⊢ ∀ (x : L), ⁅x, m⁆ = 0 [PROOFSTEP] exact fun x => h x (LieSubmodule.mem_top x) m hm [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N ⊢ IsTrivial L M ↔ maxTrivSubmodule R L M = ⊤ [PROOFSTEP] constructor [GOAL] case mp R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N ⊢ IsTrivial L M → maxTrivSubmodule R L M = ⊤ [PROOFSTEP] rintro ⟨h⟩ [GOAL] case mp.mk R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N h : ∀ (x : L) (m : M), ⁅x, m⁆ = 0 ⊢ maxTrivSubmodule R L M = ⊤ [PROOFSTEP] ext [GOAL] case mp.mk.h R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N h : ∀ (x : L) (m : M), ⁅x, m⁆ = 0 m✝ : M ⊢ m✝ ∈ maxTrivSubmodule R L M ↔ m✝ ∈ ⊤ [PROOFSTEP] simp only [mem_maxTrivSubmodule, h, forall_const, LieSubmodule.mem_top] [GOAL] case mpr R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N ⊢ maxTrivSubmodule R L M = ⊤ → IsTrivial L M [PROOFSTEP] intro h [GOAL] case mpr R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N h : maxTrivSubmodule R L M = ⊤ ⊢ IsTrivial L M [PROOFSTEP] constructor [GOAL] case mpr.trivial R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N h : maxTrivSubmodule R L M = ⊤ ⊢ ∀ (x : L) (m : M), ⁅x, m⁆ = 0 [PROOFSTEP] intro x m [GOAL] case mpr.trivial R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N h : maxTrivSubmodule R L M = ⊤ x : L m : M ⊢ ⁅x, m⁆ = 0 [PROOFSTEP] revert x [GOAL] case mpr.trivial R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N h : maxTrivSubmodule R L M = ⊤ m : M ⊢ ∀ (x : L), ⁅x, m⁆ = 0 [PROOFSTEP] rw [← mem_maxTrivSubmodule R L M, h] [GOAL] case mpr.trivial R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N h : maxTrivSubmodule R L M = ⊤ m : M ⊢ m ∈ ⊤ [PROOFSTEP] exact LieSubmodule.mem_top m [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N f : M →ₗ⁅R,L⁆ N m n : { x // x ∈ ↑(maxTrivSubmodule R L M) } ⊢ (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) (m + n) = (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) m + (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) n [PROOFSTEP] simp [Function.comp_apply] [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N f : M →ₗ⁅R,L⁆ N m n : { x // x ∈ ↑(maxTrivSubmodule R L M) } ⊢ { val := ↑f ↑m + ↑f ↑n, property := (_ : (fun x => x ∈ ↑(maxTrivSubmodule R L N)) (↑f ↑m + ↑f ↑n)) } = { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) } + { val := ↑f ↑n, property := (_ : ∀ (x : L), ⁅x, ↑f ↑n⁆ = 0) } [PROOFSTEP] rfl -- Porting note: [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N f : M →ₗ⁅R,L⁆ N t : R m : { x // x ∈ ↑(maxTrivSubmodule R L M) } ⊢ AddHom.toFun { toFun := fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }, map_add' := (_ : ∀ (m n : { x // x ∈ ↑(maxTrivSubmodule R L M) }), (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) (m + n) = (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) m + (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) n) } (t • m) = ↑(RingHom.id R) t • AddHom.toFun { toFun := fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }, map_add' := (_ : ∀ (m n : { x // x ∈ ↑(maxTrivSubmodule R L M) }), (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) (m + n) = (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) m + (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) n) } m [PROOFSTEP] simp [Function.comp_apply] [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N f : M →ₗ⁅R,L⁆ N t : R m : { x // x ∈ ↑(maxTrivSubmodule R L M) } ⊢ { val := t • ↑f ↑m, property := (_ : (fun x => x ∈ ↑(maxTrivSubmodule R L N)) (t • ↑f ↑m)) } = t • { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) } [PROOFSTEP] rfl -- these two were `by simpa` [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N f : M →ₗ⁅R,L⁆ N x : L m : { x // x ∈ ↑(maxTrivSubmodule R L M) } ⊢ AddHom.toFun { toAddHom := { toFun := fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }, map_add' := (_ : ∀ (m n : { x // x ∈ ↑(maxTrivSubmodule R L M) }), (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) (m + n) = (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) m + (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) n) }, map_smul' := (_ : ∀ (t : R) (m : { x // x ∈ ↑(maxTrivSubmodule R L M) }), AddHom.toFun { toFun := fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }, map_add' := (_ : ∀ (m n : { x // x ∈ ↑(maxTrivSubmodule R L M) }), (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) (m + n) = (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) m + (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) n) } (t • m) = ↑(RingHom.id R) t • AddHom.toFun { toFun := fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }, map_add' := (_ : ∀ (m n : { x // x ∈ ↑(maxTrivSubmodule R L M) }), (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) (m + n) = (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) m + (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) n) } m) }.toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun { toAddHom := { toFun := fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }, map_add' := (_ : ∀ (m n : { x // x ∈ ↑(maxTrivSubmodule R L M) }), (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) (m + n) = (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) m + (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) n) }, map_smul' := (_ : ∀ (t : R) (m : { x // x ∈ ↑(maxTrivSubmodule R L M) }), AddHom.toFun { toFun := fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }, map_add' := (_ : ∀ (m n : { x // x ∈ ↑(maxTrivSubmodule R L M) }), (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) (m + n) = (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) m + (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) n) } (t • m) = ↑(RingHom.id R) t • AddHom.toFun { toFun := fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }, map_add' := (_ : ∀ (m n : { x // x ∈ ↑(maxTrivSubmodule R L M) }), (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) (m + n) = (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) m + (fun m => { val := ↑f ↑m, property := (_ : ∀ (x : L), ⁅x, ↑f ↑m⁆ = 0) }) n) } m) }.toAddHom m⁆ [PROOFSTEP] simp [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N e : M ≃ₗ⁅R,L⁆ N src✝ : { x // x ∈ ↑(maxTrivSubmodule R L M) } →ₗ⁅R,L⁆ { x // x ∈ ↑(maxTrivSubmodule R L N) } := maxTrivHom e.toLieModuleHom m : { x // x ∈ ↑(maxTrivSubmodule R L M) } ⊢ ↑(maxTrivHom (LieModuleEquiv.symm e).toLieModuleHom) (AddHom.toFun (↑{ toLinearMap := { toAddHom := { toFun := ↑(maxTrivHom e.toLieModuleHom), map_add' := (_ : ∀ (x y : { x // x ∈ ↑(maxTrivSubmodule R L M) }), AddHom.toFun src✝.toAddHom (x + y) = AddHom.toFun src✝.toAddHom x + AddHom.toFun src✝.toAddHom y) }, map_smul' := (_ : ∀ (r : R) (x : { x // x ∈ ↑(maxTrivSubmodule R L M) }), AddHom.toFun src✝.toAddHom (r • x) = ↑(RingHom.id R) r • AddHom.toFun src✝.toAddHom x) }, map_lie' := (_ : ∀ {x : L} {m : { x // x ∈ ↑(maxTrivSubmodule R L M) }}, AddHom.toFun src✝.toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun src✝.toAddHom m⁆) }).toAddHom m) = m [PROOFSTEP] ext [GOAL] case a R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N e : M ≃ₗ⁅R,L⁆ N src✝ : { x // x ∈ ↑(maxTrivSubmodule R L M) } →ₗ⁅R,L⁆ { x // x ∈ ↑(maxTrivSubmodule R L N) } := maxTrivHom e.toLieModuleHom m : { x // x ∈ ↑(maxTrivSubmodule R L M) } ⊢ ↑(↑(maxTrivHom (LieModuleEquiv.symm e).toLieModuleHom) (AddHom.toFun (↑{ toLinearMap := { toAddHom := { toFun := ↑(maxTrivHom e.toLieModuleHom), map_add' := (_ : ∀ (x y : { x // x ∈ ↑(maxTrivSubmodule R L M) }), AddHom.toFun src✝.toAddHom (x + y) = AddHom.toFun src✝.toAddHom x + AddHom.toFun src✝.toAddHom y) }, map_smul' := (_ : ∀ (r : R) (x : { x // x ∈ ↑(maxTrivSubmodule R L M) }), AddHom.toFun src✝.toAddHom (r • x) = ↑(RingHom.id R) r • AddHom.toFun src✝.toAddHom x) }, map_lie' := (_ : ∀ {x : L} {m : { x // x ∈ ↑(maxTrivSubmodule R L M) }}, AddHom.toFun src✝.toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun src✝.toAddHom m⁆) }).toAddHom m)) = ↑m [PROOFSTEP] simp [LieModuleEquiv.coe_to_lieModuleHom] [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N e : M ≃ₗ⁅R,L⁆ N src✝ : { x // x ∈ ↑(maxTrivSubmodule R L M) } →ₗ⁅R,L⁆ { x // x ∈ ↑(maxTrivSubmodule R L N) } := maxTrivHom e.toLieModuleHom n : { x // x ∈ ↑(maxTrivSubmodule R L N) } ⊢ AddHom.toFun (↑{ toLinearMap := { toAddHom := { toFun := ↑(maxTrivHom e.toLieModuleHom), map_add' := (_ : ∀ (x y : { x // x ∈ ↑(maxTrivSubmodule R L M) }), AddHom.toFun src✝.toAddHom (x + y) = AddHom.toFun src✝.toAddHom x + AddHom.toFun src✝.toAddHom y) }, map_smul' := (_ : ∀ (r : R) (x : { x // x ∈ ↑(maxTrivSubmodule R L M) }), AddHom.toFun src✝.toAddHom (r • x) = ↑(RingHom.id R) r • AddHom.toFun src✝.toAddHom x) }, map_lie' := (_ : ∀ {x : L} {m : { x // x ∈ ↑(maxTrivSubmodule R L M) }}, AddHom.toFun src✝.toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun src✝.toAddHom m⁆) }).toAddHom (↑(maxTrivHom (LieModuleEquiv.symm e).toLieModuleHom) n) = n [PROOFSTEP] ext [GOAL] case a R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N e : M ≃ₗ⁅R,L⁆ N src✝ : { x // x ∈ ↑(maxTrivSubmodule R L M) } →ₗ⁅R,L⁆ { x // x ∈ ↑(maxTrivSubmodule R L N) } := maxTrivHom e.toLieModuleHom n : { x // x ∈ ↑(maxTrivSubmodule R L N) } ⊢ ↑(AddHom.toFun (↑{ toLinearMap := { toAddHom := { toFun := ↑(maxTrivHom e.toLieModuleHom), map_add' := (_ : ∀ (x y : { x // x ∈ ↑(maxTrivSubmodule R L M) }), AddHom.toFun src✝.toAddHom (x + y) = AddHom.toFun src✝.toAddHom x + AddHom.toFun src✝.toAddHom y) }, map_smul' := (_ : ∀ (r : R) (x : { x // x ∈ ↑(maxTrivSubmodule R L M) }), AddHom.toFun src✝.toAddHom (r • x) = ↑(RingHom.id R) r • AddHom.toFun src✝.toAddHom x) }, map_lie' := (_ : ∀ {x : L} {m : { x // x ∈ ↑(maxTrivSubmodule R L M) }}, AddHom.toFun src✝.toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun src✝.toAddHom m⁆) }).toAddHom (↑(maxTrivHom (LieModuleEquiv.symm e).toLieModuleHom) n)) = ↑n [PROOFSTEP] simp [LieModuleEquiv.coe_to_lieModuleHom] [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N ⊢ maxTrivEquiv LieModuleEquiv.refl = LieModuleEquiv.refl [PROOFSTEP] ext [GOAL] case h.a R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N m✝ : { x // x ∈ ↑(maxTrivSubmodule R L M) } ⊢ ↑(↑(maxTrivEquiv LieModuleEquiv.refl) m✝) = ↑(↑LieModuleEquiv.refl m✝) [PROOFSTEP] simp only [coe_maxTrivEquiv_apply, LieModuleEquiv.refl_apply] [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N f : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) } x : L m : M ⊢ AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆ [PROOFSTEP] have hf : ⁅x, f.val⁆ m = 0 := by rw [f.property x, LinearMap.zero_apply] [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N f : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) } x : L m : M ⊢ ↑⁅x, ↑f⁆ m = 0 [PROOFSTEP] rw [f.property x, LinearMap.zero_apply] [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N f : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) } x : L m : M hf : ↑⁅x, ↑f⁆ m = 0 ⊢ AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆ [PROOFSTEP] rw [LieHom.lie_apply, sub_eq_zero, ← LinearMap.toFun_eq_coe] at hf [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N f : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) } x : L m : M hf : ⁅x, AddHom.toFun (↑f).toAddHom m⁆ = AddHom.toFun (↑f).toAddHom ⁅x, m⁆ ⊢ AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆ [PROOFSTEP] exact hf.symm [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N f g : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) } ⊢ (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) (f + g) = (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) f + (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) g [PROOFSTEP] ext [GOAL] case h R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N f g : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) } m✝ : M ⊢ ↑((fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) (f + g)) m✝ = ↑((fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) f + (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) g) m✝ [PROOFSTEP] simp [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N F : R G : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) } ⊢ AddHom.toFun { toFun := fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }, map_add' := (_ : ∀ (f g : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) }), (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) (f + g) = (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) f + (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) g) } (F • G) = ↑(RingHom.id R) F • AddHom.toFun { toFun := fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }, map_add' := (_ : ∀ (f g : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) }), (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) (f + g) = (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) f + (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) g) } G [PROOFSTEP] ext [GOAL] case h R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N F : R G : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) } m✝ : M ⊢ ↑(AddHom.toFun { toFun := fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }, map_add' := (_ : ∀ (f g : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) }), (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) (f + g) = (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) f + (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) g) } (F • G)) m✝ = ↑(↑(RingHom.id R) F • AddHom.toFun { toFun := fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }, map_add' := (_ : ∀ (f g : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) }), (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) (f + g) = (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) f + (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) g) } G) m✝ [PROOFSTEP] simp [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N F : M →ₗ⁅R,L⁆ N x : L ⊢ ⁅x, ↑F⁆ = 0 [PROOFSTEP] ext [GOAL] case h R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N F : M →ₗ⁅R,L⁆ N x : L x✝ : M ⊢ ↑⁅x, ↑F⁆ x✝ = ↑0 x✝ [PROOFSTEP] simp [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N f : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) } ⊢ (fun F => { val := ↑F, property := (_ : ∀ (x : L), ⁅x, ↑F⁆ = 0) }) (AddHom.toFun { toAddHom := { toFun := fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }, map_add' := (_ : ∀ (f g : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) }), (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) (f + g) = (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) f + (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) g) }, map_smul' := (_ : ∀ (F : R) (G : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) }), AddHom.toFun { toFun := fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }, map_add' := (_ : ∀ (f g : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) }), (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) (f + g) = (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) f + (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) g) } (F • G) = ↑(RingHom.id R) F • AddHom.toFun { toFun := fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }, map_add' := (_ : ∀ (f g : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) }), (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) (f + g) = (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) f + (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) g) } G) }.toAddHom f) = f [PROOFSTEP] simp [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N F : M →ₗ⁅R,L⁆ N ⊢ AddHom.toFun { toAddHom := { toFun := fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }, map_add' := (_ : ∀ (f g : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) }), (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) (f + g) = (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) f + (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) g) }, map_smul' := (_ : ∀ (F : R) (G : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) }), AddHom.toFun { toFun := fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }, map_add' := (_ : ∀ (f g : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) }), (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) (f + g) = (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) f + (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) g) } (F • G) = ↑(RingHom.id R) F • AddHom.toFun { toFun := fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }, map_add' := (_ : ∀ (f g : { x // x ∈ ↑(maxTrivSubmodule R L (M →ₗ[R] N)) }), (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) (f + g) = (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) f + (fun f => { toLinearMap := ↑f, map_lie' := (_ : ∀ {x : L} {m : M}, AddHom.toFun (↑f).toAddHom ⁅x, m⁆ = ⁅x, AddHom.toFun (↑f).toAddHom m⁆) }) g) } G) }.toAddHom ((fun F => { val := ↑F, property := (_ : ∀ (x : L), ⁅x, ↑F⁆ = 0) }) F) = F [PROOFSTEP] simp [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N f : { x // x ∈ maxTrivSubmodule R L (M →ₗ[R] N) } ⊢ ↑(↑maxTrivLinearMapEquivLieModuleHom f) = ↑↑f [PROOFSTEP] ext [GOAL] case h R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N f : { x // x ∈ maxTrivSubmodule R L (M →ₗ[R] N) } x✝ : M ⊢ ↑(↑maxTrivLinearMapEquivLieModuleHom f) x✝ = ↑↑f x✝ [PROOFSTEP] rfl [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N f : { x // x ∈ maxTrivSubmodule R L (M →ₗ[R] N) } ⊢ ↑(↑maxTrivLinearMapEquivLieModuleHom f) = ↑f [PROOFSTEP] ext [GOAL] case h R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N f : { x // x ∈ maxTrivSubmodule R L (M →ₗ[R] N) } x✝ : M ⊢ ↑↑(↑maxTrivLinearMapEquivLieModuleHom f) x✝ = ↑↑f x✝ [PROOFSTEP] rfl [GOAL] R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N ⊢ LieModule.ker R L L = center R L [PROOFSTEP] ext y [GOAL] case h R : Type u L : Type v M : Type w N : Type w₁ inst✝¹⁰ : CommRing R inst✝⁹ : LieRing L inst✝⁸ : LieAlgebra R L inst✝⁷ : AddCommGroup M inst✝⁶ : Module R M inst✝⁵ : LieRingModule L M inst✝⁴ : LieModule R L M inst✝³ : AddCommGroup N inst✝² : Module R N inst✝¹ : LieRingModule L N inst✝ : LieModule R L N y : L ⊢ y ∈ LieModule.ker R L L ↔ y ∈ center R L [PROOFSTEP] simp only [LieModule.mem_maxTrivSubmodule, LieModule.mem_ker, ← lie_skew _ y, neg_eq_zero] [GOAL] R : Type u L : Type v M : Type w inst✝⁷ : CommRing R inst✝⁶ : LieRing L inst✝⁵ : LieAlgebra R L inst✝⁴ : AddCommGroup M inst✝³ : Module R M inst✝² : LieRingModule L M inst✝¹ : LieModule R L M N N' : LieSubmodule R L M I J : LieIdeal R L inst✝ : LieModule.IsTrivial L M ⊢ ⁅I, N⁆ = ⊥ [PROOFSTEP] suffices : ⁅I, N⁆ ≤ ⊥ [GOAL] R : Type u L : Type v M : Type w inst✝⁷ : CommRing R inst✝⁶ : LieRing L inst✝⁵ : LieAlgebra R L inst✝⁴ : AddCommGroup M inst✝³ : Module R M inst✝² : LieRingModule L M inst✝¹ : LieModule R L M N N' : LieSubmodule R L M I J : LieIdeal R L inst✝ : LieModule.IsTrivial L M this : ⁅I, N⁆ ≤ ⊥ ⊢ ⁅I, N⁆ = ⊥ case this R : Type u L : Type v M : Type w inst✝⁷ : CommRing R inst✝⁶ : LieRing L inst✝⁵ : LieAlgebra R L inst✝⁴ : AddCommGroup M inst✝³ : Module R M inst✝² : LieRingModule L M inst✝¹ : LieModule R L M N N' : LieSubmodule R L M I J : LieIdeal R L inst✝ : LieModule.IsTrivial L M ⊢ ⁅I, N⁆ ≤ ⊥ [PROOFSTEP] exact le_bot_iff.mp this [GOAL] case this R : Type u L : Type v M : Type w inst✝⁷ : CommRing R inst✝⁶ : LieRing L inst✝⁵ : LieAlgebra R L inst✝⁴ : AddCommGroup M inst✝³ : Module R M inst✝² : LieRingModule L M inst✝¹ : LieModule R L M N N' : LieSubmodule R L M I J : LieIdeal R L inst✝ : LieModule.IsTrivial L M ⊢ ⁅I, N⁆ ≤ ⊥ [PROOFSTEP] rw [lieIdeal_oper_eq_span, LieSubmodule.lieSpan_le] [GOAL] case this R : Type u L : Type v M : Type w inst✝⁷ : CommRing R inst✝⁶ : LieRing L inst✝⁵ : LieAlgebra R L inst✝⁴ : AddCommGroup M inst✝³ : Module R M inst✝² : LieRingModule L M inst✝¹ : LieModule R L M N N' : LieSubmodule R L M I J : LieIdeal R L inst✝ : LieModule.IsTrivial L M ⊢ {m | ∃ x n, ⁅↑x, ↑n⁆ = m} ⊆ ↑⊥ [PROOFSTEP] rintro m ⟨x, n, h⟩ [GOAL] case this.intro.intro R : Type u L : Type v M : Type w inst✝⁷ : CommRing R inst✝⁶ : LieRing L inst✝⁵ : LieAlgebra R L inst✝⁴ : AddCommGroup M inst✝³ : Module R M inst✝² : LieRingModule L M inst✝¹ : LieModule R L M N N' : LieSubmodule R L M I J : LieIdeal R L inst✝ : LieModule.IsTrivial L M m : M x : { x // x ∈ I } n : { x // x ∈ N } h : ⁅↑x, ↑n⁆ = m ⊢ m ∈ ↑⊥ [PROOFSTEP] rw [trivial_lie_zero] at h [GOAL] case this.intro.intro R : Type u L : Type v M : Type w inst✝⁷ : CommRing R inst✝⁶ : LieRing L inst✝⁵ : LieAlgebra R L inst✝⁴ : AddCommGroup M inst✝³ : Module R M inst✝² : LieRingModule L M inst✝¹ : LieModule R L M N N' : LieSubmodule R L M I J : LieIdeal R L inst✝ : LieModule.IsTrivial L M m : M x : { x // x ∈ I } n : { x // x ∈ N } h : 0 = m ⊢ m ∈ ↑⊥ [PROOFSTEP] simp [← h] [GOAL] R : Type u L : Type v M : Type w inst✝⁶ : CommRing R inst✝⁵ : LieRing L inst✝⁴ : LieAlgebra R L inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : LieRingModule L M inst✝ : LieModule R L M N N' : LieSubmodule R L M I J : LieIdeal R L ⊢ IsLieAbelian { x // x ∈ ↑I } ↔ ⁅I, I⁆ = ⊥ [PROOFSTEP] simp only [_root_.eq_bot_iff, lieIdeal_oper_eq_span, LieSubmodule.lieSpan_le, LieSubmodule.bot_coe, Set.subset_singleton_iff, Set.mem_setOf_eq, exists_imp] [GOAL] R : Type u L : Type v M : Type w inst✝⁶ : CommRing R inst✝⁵ : LieRing L inst✝⁴ : LieAlgebra R L inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : LieRingModule L M inst✝ : LieModule R L M N N' : LieSubmodule R L M I J : LieIdeal R L ⊢ IsLieAbelian { x // x ∈ ↑I } ↔ ∀ (y : L) (x : { x // x ∈ I }) (x_1 : { x // x ∈ I }), ⁅↑x, ↑x_1⁆ = y → y = 0 [PROOFSTEP] refine' ⟨fun h z x y hz => hz.symm.trans (((I : LieSubalgebra R L).coe_bracket x y).symm.trans ((coe_zero_iff_zero _ _).mpr (by apply h.trivial))), fun h => ⟨fun x y => ((I : LieSubalgebra R L).coe_zero_iff_zero _).mp (h _ x y rfl)⟩⟩ [GOAL] R : Type u L : Type v M : Type w inst✝⁶ : CommRing R inst✝⁵ : LieRing L inst✝⁴ : LieAlgebra R L inst✝³ : AddCommGroup M inst✝² : Module R M inst✝¹ : LieRingModule L M inst✝ : LieModule R L M N N' : LieSubmodule R L M I J : LieIdeal R L h : IsLieAbelian { x // x ∈ ↑I } z : L x : { x // x ∈ I } y : { x // x ∈ I } hz : ⁅↑x, ↑y⁆ = z ⊢ ⁅x, y⁆ = 0 [PROOFSTEP] apply h.trivial
/- Copyright (c) 2021 Kalle Kytölä. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kalle Kytölä -/ import data.complex.is_R_or_C import analysis.normed_space.operator_norm import analysis.normed_space.pointwise /-! # Normed spaces over R or C This file is about results on normed spaces over the fields `ℝ` and `ℂ`. ## Main definitions None. ## Main theorems * `continuous_linear_map.op_norm_bound_of_ball_bound`: A bound on the norms of values of a linear map in a ball yields a bound on the operator norm. ## Notes This file exists mainly to avoid importing `is_R_or_C` in the main normed space theory files. -/ open metric @[simp, is_R_or_C_simps] lemma is_R_or_C.norm_coe_norm {𝕜 : Type*} [is_R_or_C 𝕜] {E : Type*} [normed_group E] {z : E} : ∥(∥z∥ : 𝕜)∥ = ∥z∥ := by { unfold_coes, simp only [norm_algebra_map_eq, ring_hom.to_fun_eq_coe, norm_norm], } variables {𝕜 : Type*} [is_R_or_C 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] /-- Lemma to normalize a vector in a normed space `E` over either `ℂ` or `ℝ` to unit length. -/ @[simp] lemma norm_smul_inv_norm {x : E} (hx : x ≠ 0) : ∥(∥x∥⁻¹ : 𝕜) • x∥ = 1 := begin have : ∥x∥ ≠ 0 := by simp [hx], field_simp [norm_smul] end /-- Lemma to normalize a vector in a normed space `E` over either `ℂ` or `ℝ` to length `r`. -/ lemma norm_smul_inv_norm' {r : ℝ} (r_nonneg : 0 ≤ r) {x : E} (hx : x ≠ 0) : ∥(r * ∥x∥⁻¹ : 𝕜) • x∥ = r := begin have : ∥x∥ ≠ 0 := by simp [hx], field_simp [norm_smul, is_R_or_C.norm_eq_abs, r_nonneg] with is_R_or_C_simps end lemma linear_map.bound_of_sphere_bound {r : ℝ} (r_pos : 0 < r) (c : ℝ) (f : E →ₗ[𝕜] 𝕜) (h : ∀ z ∈ sphere (0 : E) r, ∥f z∥ ≤ c) (z : E) : ∥f z∥ ≤ c / r * ∥z∥ := begin by_cases z_zero : z = 0, { rw z_zero, simp only [linear_map.map_zero, norm_zero, mul_zero], }, set z₁ := (r * ∥z∥⁻¹ : 𝕜) • z with hz₁, have norm_f_z₁ : ∥f z₁∥ ≤ c, { apply h, rw mem_sphere_zero_iff_norm, exact norm_smul_inv_norm' r_pos.le z_zero }, have r_ne_zero : (r : 𝕜) ≠ 0 := (algebra_map ℝ 𝕜).map_ne_zero.mpr r_pos.ne.symm, have eq : f z = ∥z∥ / r * (f z₁), { rw [hz₁, linear_map.map_smul, smul_eq_mul], rw [← mul_assoc, ← mul_assoc, div_mul_cancel _ r_ne_zero, mul_inv_cancel, one_mul], simp only [z_zero, is_R_or_C.of_real_eq_zero, norm_eq_zero, ne.def, not_false_iff], }, rw [eq, normed_field.norm_mul, normed_field.norm_div, is_R_or_C.norm_coe_norm, is_R_or_C.norm_of_nonneg r_pos.le, div_mul_eq_mul_div, div_mul_eq_mul_div, mul_comm], apply div_le_div _ _ r_pos rfl.ge, { exact mul_nonneg ((norm_nonneg _).trans norm_f_z₁) (norm_nonneg z), }, apply mul_le_mul norm_f_z₁ rfl.le (norm_nonneg z) ((norm_nonneg _).trans norm_f_z₁), end /-- `linear_map.bound_of_ball_bound` is a version of this over arbitrary nondiscrete normed fields. It produces a less precise bound so we keep both versions. -/ lemma linear_map.bound_of_ball_bound' {r : ℝ} (r_pos : 0 < r) (c : ℝ) (f : E →ₗ[𝕜] 𝕜) (h : ∀ z ∈ closed_ball (0 : E) r, ∥f z∥ ≤ c) (z : E) : ∥f z∥ ≤ c / r * ∥z∥ := f.bound_of_sphere_bound r_pos c (λ z hz, h z hz.le) z lemma continuous_linear_map.op_norm_bound_of_ball_bound {r : ℝ} (r_pos : 0 < r) (c : ℝ) (f : E →L[𝕜] 𝕜) (h : ∀ z ∈ closed_ball (0 : E) r, ∥f z∥ ≤ c) : ∥f∥ ≤ c / r := begin apply continuous_linear_map.op_norm_le_bound, { apply div_nonneg _ r_pos.le, exact (norm_nonneg _).trans (h 0 (by simp only [norm_zero, mem_closed_ball, dist_zero_left, r_pos.le])), }, apply linear_map.bound_of_ball_bound' r_pos, exact λ z hz, h z hz, end variables (𝕜) include 𝕜 lemma normed_space.sphere_nonempty_is_R_or_C [nontrivial E] {r : ℝ} (hr : 0 ≤ r) : nonempty (sphere (0:E) r) := begin letI : normed_space ℝ E := normed_space.restrict_scalars ℝ 𝕜 E, exact (sphere (0:E) r).nonempty_coe_sort.mpr (normed_space.sphere_nonempty.mpr hr), end
MIDDLETOWN, NJ - The Egg Hunt is back—with a twist! Bring your basket, running shoes and a flashlight and get ready to find those eggs at Croydon Hall Football Field! This is strictly an egg hunt. Registration closes Wednesday, March 25. No registrations will be taken at the event. Croydon Hall is located at 900 Leonardville Road, Leonardo. Middletown Residents only. Ages 1-10.
module System.File.Error import System.Errno import System.File.Support import public System.File.Types import System.FFI %default total fileClass : String fileClass = "io/github/mmhelloworld/idrisjvm/runtime/ChannelIo" %foreign support "idris2_fileError" "node:lambda:x=>(x===1?1:0)" jvm' fileClass "getErrorNumber" fileClass "int" prim__error : FilePtr -> PrimIO Int %foreign support "idris2_fileErrno" "node:support:fileErrno,support_system_file" jvm' runtimeClass "getErrorNumber" "java/lang/Object" "int" prim__fileErrno : PrimIO Int public export data FileError = GenericFileError Int -- errno | FileReadError | FileWriteError | FileNotFound | PermissionDenied | FileExists export returnError : HasIO io => io (Either FileError a) returnError = do err <- primIO prim__fileErrno pure $ Left $ case err of 0 => FileReadError 1 => FileWriteError 2 => FileNotFound 3 => PermissionDenied 4 => FileExists _ => GenericFileError (err-5) export Show FileError where show (GenericFileError errno) = strerror errno show FileReadError = "File Read Error" show FileWriteError = "File Write Error" show FileNotFound = "File Not Found" show PermissionDenied = "Permission Denied" show FileExists = "File Exists" export fileError : HasIO io => File -> io Bool fileError (FHandle f) = do x <- primIO $ prim__error f pure (x /= 0)
Require Import String. Require Import Ascii. Require Import Bool. Require Import Arith. Require Import Omega. Require Import Program.Tactics. (* * I should polish this up and get merged upstream. * coq's string library is a disgrace. *) Section MissingListBits. (* XXX why isn't this in the library? or is it and I can't find it? *) Function take {T} (n: nat) (xs: list T) := match n, xs with | S n, (x :: more)%list => (x :: take n more)%list | _, _ => nil end. Lemma take_length: forall T (xs : list T) n, List.length (take n xs) <= List.length xs. Proof. intros. revert n. induction xs; intros. - destruct n; rewrite take_equation; auto. - destruct n; rewrite take_equation; simpl; try omega. apply le_n_S. apply IHxs. Qed. Lemma take_length_strict: forall T (xs : list T) n, n <= List.length xs -> List.length (take n xs) = n. Proof. intros. revert H. revert n. induction xs; intros. - simpl in H. assert (n = 0) by omega. subst. simpl. reflexivity. - destruct n; rewrite take_equation; simpl in *; try apply eq_S; try apply IHxs; omega. Qed. Lemma take_correctness: forall T n (xs : list T) k x, k < n -> List.nth k (take n xs) x = List.nth k xs x. Proof. intros T n xs. revert n. induction xs; intros; rewrite take_equation; destruct n; destruct k; simpl; try discriminate; try apply IHxs; try omega; auto. Qed. Lemma take_correctness_2: forall T n (xs : list T) k x, k >= n -> List.nth k (take n xs) x = x. Proof. intros T n xs. revert n. induction xs; intros; rewrite take_equation; destruct n; destruct k; simpl; try apply IHxs; try omega; auto. Qed. (* and I'd expect to find this too... *) Function natlist_sum (ns : list nat): nat := match ns with | nil => 0 | (n :: more)%list => n + (natlist_sum more) end. Lemma natlist_sum_ge: forall n ns, List.In n ns -> natlist_sum ns >= n. Proof. intros. revert H. revert n. induction ns; intros. - unfold List.In in H. contradiction. - rewrite natlist_sum_equation. apply List.in_inv in H. destruct H; subst; try apply IHns in H; try omega. Qed. (* not sure what else to prove about natlist_sum *) End MissingListBits. Section CharacterFacts. (* * These bits are from pset3regex *) (* `ascii_eq` is an executable equality test for characters. *) Definition ascii_eq (a b:ascii) : bool := match (a, b) with | (Ascii a1 a2 a3 a4 a5 a6 a7 a8, Ascii b1 b2 b3 b4 b5 b6 b7 b8) => eqb a1 b1 && eqb a2 b2 && eqb a3 b3 && eqb a4 b4 && eqb a5 b5 && eqb a6 b6 && eqb a7 b7 && eqb a8 b8 end. Lemma ascii_eq_refl (a:ascii): ascii_eq a a = true. Proof. destruct a; unfold ascii_eq; repeat rewrite eqb_reflx; simpl; auto. Qed. (* `ascii_eq` is equivalent to character equality. *) Lemma ascii_eq_iff a b: ascii_eq a b = true <-> a = b. Proof. split; intros. - unfold ascii_eq in H; destruct a; destruct b; repeat rewrite andb_true_iff in *; destruct_pairs; rewrite eqb_true_iff in *; congruence. - rewrite H; apply ascii_eq_refl. Qed. (* * These bits are mine *) (* we also need inequality *) Lemma ascii_neq_iff a b: ascii_eq a b = false <-> a <> b. Proof. split; intros. - unfold ascii_eq in H; destruct a; destruct b; repeat rewrite andb_false_iff in *. repeat rewrite eqb_false_iff in *. injection. (* destruct pairs doesn't work... *) repeat (destruct H; auto). - unfold ascii_eq; destruct a; destruct b. unfold eqb. (* there must be a better way to do this... *) destruct b; destruct b0; auto; destruct b1; destruct b8; auto; simpl; destruct b2; destruct b9; auto; destruct b3; destruct b10; auto; simpl; destruct b4; destruct b11; auto; destruct b5; destruct b12; auto; simpl; destruct b6; destruct b13; auto; destruct b7; destruct b14; auto; simpl; contradiction. Qed. End CharacterFacts. Section StringFacts. (* * These bits are from pset3regex *) Lemma append_nil_l s: ("" ++ s)%string = s. Proof. simpl; auto. Qed. Lemma append_nil_r s: (s ++ "")%string = s. Proof. induction s; simpl; try rewrite IHs; auto. Qed. Lemma append_assoc s1 s2 s3: (s1 ++ s2 ++ s3)%string = ((s1 ++ s2) ++ s3)%string. Proof. induction s1; simpl; try rewrite IHs1; auto. Qed. Lemma append_comm_cons a s1 s2: (String a s1 ++ s2)%string = String a (s1 ++ s2)%string. Proof. induction s1; simpl; auto. Qed. Definition strlen := String.length. Lemma append_strlen_l s1 s2: strlen s1 <= strlen (s1 ++ s2). Proof. induction s1; simpl; try rewrite IHs1; omega. Qed. Lemma append_strlen_r s1 s2: strlen s1 <= strlen (s1 ++ s2). Proof. induction s1; simpl; try rewrite IHs1; omega. Qed. (* * These bits are mine. *) Lemma length_zero_empty: forall s, strlen s = 0 -> s = EmptyString. Proof. intros. induction s. - auto. - simpl in H. discriminate. Qed. Lemma length_cons: forall c s, strlen (String c s) = S (strlen s). Proof. intros; simpl; auto. Qed. Lemma length_append: forall s1 s2, String.length (s1 ++ s2)%string = String.length s1 + String.length s2. Proof. intros. induction s1. - simpl; auto. - rewrite append_comm_cons. repeat rewrite length_cons. rewrite plus_Sn_m. apply eq_S. auto. Qed. Lemma cons_substring: forall n c s, String.substring 0 (S n) (String c s) = String c (String.substring 0 n s). Proof. intros. simpl. auto. Qed. Lemma cons_eq_cons: forall c s1 s2, String c s1 = String c s2 <-> s1 = s2. Proof. intros. split. - congruence. - intro. rewrite H. auto. Qed. Lemma cons_neq_cons: forall c s1 s2, String c s1 <> String c s2 <-> s1 <> s2. Proof. split; intros; congruence. Qed. (* XXX this needs a better name *) Lemma cons_neq_cons_2: forall c1 c2 s, String c1 s <> String c2 s <-> c1 <> c2. Proof. split; intros; congruence. Qed. (* XXX this too *) Lemma cons_neq_cons_3: forall c1 c2 s1 s2, String c1 s1 <> String c2 s2 <-> c1 <> c2 \/ s1 <> s2. Proof. split; intros. - destruct (ascii_dec c1 c2); subst. * rewrite cons_neq_cons in H. auto. * auto. - destruct H; congruence. Qed. Lemma cons_not_itself: forall c s, String c s = s -> False. Proof. intros. induction s; try discriminate. inversion H; subst. auto. Qed. Lemma cons_is_prepend: forall c s, String c s = ((String c EmptyString) ++ s)%string. Proof. intros. induction s; simpl; auto. Qed. Lemma append_eq_append: forall s1 s2 s3, (s1 ++ s3)%string = (s2 ++ s3)%string -> s1 = s2. Proof. (* There must be a less messy way to do this. *) intros. revert H. revert s1 s2. induction s3; intros. - repeat rewrite append_nil_r in H. auto. - rewrite cons_is_prepend in H. repeat rewrite append_assoc in H. apply IHs3 with (s1 := (s1 ++ String a "")%string) (s2 := (s2 ++ String a "")%string) in H. revert H; revert s2; induction s1; intros. * destruct s2; auto. simpl in H. destruct (ascii_dec a a0); subst. + assert (EmptyString = (s2 ++ String a0 EmptyString)%string) by congruence. destruct s2. -- rewrite append_nil_l in H0. discriminate. -- simpl in H0. discriminate. + congruence. * destruct s2; simpl in H. + destruct (ascii_dec a a0); subst. -- assert ((s1 ++ String a0 EmptyString)%string = EmptyString) by congruence. destruct s1. ** rewrite append_nil_l in H0. discriminate. ** simpl in H0. discriminate. -- congruence. + destruct (ascii_dec a0 a1); subst. -- assert ((s1 ++ String a "")%string = (s2 ++ String a "")%string) by congruence. apply IHs1 in H0. rewrite H0; auto. -- congruence. Qed. Lemma prepend_eq_prepend: forall s1 s2 s3, (s1 ++ s2)%string = (s1 ++ s3)%string -> s2 = s3. Proof. intros. induction s1. - repeat rewrite append_nil_l in H; auto. - simpl in H. apply cons_eq_cons in H. auto. Qed. Lemma null_substring: forall s, String.substring 0 0 s = EmptyString. Proof. intros. (* just compute doesn't work *) induction s; compute; auto. Qed. Lemma entire_substring: forall s, String.substring 0 (String.length s) s = s. Proof. intros. remember (String.length s) as n. revert Heqn. revert n. induction s; intros. - simpl in Heqn. rewrite Heqn. compute. auto. - assert (exists m, n = S m) as M by (induction n; [simpl in Heqn; omega | exists n; auto]). destruct M as [m M]. rewrite M. rewrite cons_substring. rewrite cons_eq_cons. apply IHs. simpl in Heqn. omega. Qed. Lemma substring_cons_head: forall c s n, String.substring 0 (S n) (String c s) = String c (String.substring 0 n s). Proof. intros; simpl; auto. Qed. Lemma substring_cons_tail: forall c s m n, String.substring (S m) n (String c s) = String.substring m n s. Proof. intros; simpl; auto. Qed. (* substring of s1 ++ s2 that falls entirely within s1 *) Lemma substring_append_first: forall s1 s2 m n, m + n <= String.length s1 -> String.substring m n (s1 ++ s2)%string = String.substring m n s1. Proof. intro. (* s1 only *) induction s1; intros. - simpl in H. assert (m = 0) by omega. assert (n = 0) by omega. subst. simpl. rewrite null_substring. auto. - destruct (Nat.eq_dec m 0). * subst. rewrite Nat.add_0_l in H. destruct (Nat.eq_dec n 0). + subst. repeat rewrite null_substring. auto. + assert (exists k, n = S k) as kEq by (exists (Nat.pred n); rewrite Nat.succ_pred; auto). destruct kEq as [k kEq]. rewrite kEq. rewrite append_comm_cons. repeat rewrite substring_cons_head. rewrite cons_eq_cons. apply IHs1. simpl in H. omega. * assert (exists k, m = S k) as kEq by (exists (Nat.pred m); rewrite Nat.succ_pred; auto). destruct kEq as [k kEq]. rewrite kEq. rewrite append_comm_cons. repeat rewrite substring_cons_tail. apply IHs1. simpl in H. omega. Qed. (* substring of s1 ++ s2 that includes parts of both s1 and s2 *) Lemma substring_append_both: forall s1 s2 m n, m <= String.length s1 -> m + n >= String.length s1 -> String.substring m n (s1 ++ s2)%string = (String.substring m (String.length s1 - m) s1 ++ String.substring 0 ((m + n) - String.length s1) s2)%string. Proof. intro; (* s1 only *) induction s1; intros. - simpl in H. assert (m = 0) by omega; subst. simpl. rewrite Nat.sub_0_r. auto. - rewrite length_cons. destruct m; simpl in H; simpl in H0. * assert (exists k, n = S k) as kEq by (exists (Nat.pred n); rewrite Nat.succ_pred; omega). destruct kEq as [k kEq]. rewrite kEq. specialize IHs1 with (s2 := s2) (m := 0) (n := k). rewrite Nat.sub_0_r in *. rewrite Nat.add_0_l in *. rewrite append_comm_cons. repeat rewrite substring_cons_head. rewrite append_comm_cons. rewrite cons_eq_cons. rewrite Nat.sub_succ. apply IHs1; omega. * rewrite plus_Sn_m. repeat rewrite Nat.sub_succ. apply IHs1; omega. Qed. (* substring of s1 ++ s2 that falls entirely within s2 *) Lemma substring_append_second: forall s1 s2 m n, m >= String.length s1 -> String.substring m n (s1 ++ s2)%string = String.substring (m - String.length s1) n s2. Proof. intro. (* s1 only *) induction s1; intros. - simpl. rewrite Nat.sub_0_r. auto. - rewrite append_comm_cons. simpl in H. assert (exists k, m = S k) as kEq by (exists (Nat.pred m); rewrite Nat.succ_pred; omega). destruct kEq as [k kEq]. rewrite kEq. simpl. apply IHs1. omega. Qed. (* General statement of substring_append. *) Lemma substring_append: forall s1 s2 m n, exists m1 n1 m2 n2, String.substring m n (s1 ++ s2)%string = (String.substring m1 n1 s1 ++ String.substring m2 n2 s2)%string. Proof. intros. destruct (le_gt_dec m (String.length s1)). 1: destruct (le_gt_dec (m + n) (String.length s1)). - (* substring_append_first *) exists m; exists n. exists 0; exists 0. rewrite null_substring. rewrite append_nil_r. apply substring_append_first. auto. - (* substring_append_both *) exists m; exists (String.length s1 - m). exists 0; exists ((m + n) - String.length s1). apply substring_append_both; omega. - (* substring_append_second *) exists 0; exists 0. exists (m - String.length s1); exists n. rewrite null_substring. rewrite append_nil_l. apply substring_append_second. omega. Qed. (* Specialization of substring_append_first for m = 0 *) Lemma substring_append_head_shorter: forall s1 s2 n, n <= String.length s1 -> String.substring 0 n (s1 ++ s2)%string = String.substring 0 n s1. Proof. intros. apply substring_append_first. omega. Qed. (* Specialization of substring_append_both for m = 0 *) Lemma substring_append_head_longer: forall s1 s2 n, n >= String.length s1 -> String.substring 0 n (s1 ++ s2)%string = (s1 ++ String.substring 0 (n - String.length s1) s2)%string. Proof. intros. assert (String.substring 0 n (s1 ++ s2)%string = (String.substring 0 (String.length s1 - 0) s1 ++ String.substring 0 ((0 + n) - String.length s1) s2)%string) by (rewrite substring_append_both; try omega; auto). rewrite H0. rewrite Nat.sub_0_r. rewrite entire_substring. simpl. reflexivity. Qed. (* Specialization of substring_append_both for n = strlen s - m *) Lemma substring_append_tail_longer: forall s1 s2 m, m <= String.length s1 -> String.substring m (String.length (s1 ++ s2)%string - m) (s1 ++ s2)%string = (String.substring m (String.length s1 - m) s1 ++ s2)%string. Proof. intros. assert (m <= String.length (s1 ++ s2)%string) by (rewrite length_append; omega). assert (String.length (s1 ++ s2)%string >= String.length s1) by (rewrite length_append; omega). assert(String.substring m (String.length (s1 ++ s2)%string - m) (s1 ++ s2)%string = (String.substring m (String.length s1 - m) s1 ++ String.substring 0 ((m + (String.length (s1 ++ s2)%string - m)) - String.length s1) s2)%string) by (rewrite substring_append_both; try omega; try rewrite <- le_plus_minus; auto). rewrite H2. rewrite <- le_plus_minus; auto. rewrite length_append. rewrite minus_plus. rewrite entire_substring. reflexivity. Qed. (* Specialization of substring_append_second for n = strlen s - m *) Lemma substring_append_tail_shorter: forall s1 s2 m, m >= String.length s1 -> String.substring m (String.length (s1 ++ s2)%string - m) (s1 ++ s2)%string = String.substring (m - String.length s1) (String.length s2 - (m - String.length s1)) s2. Proof. intros. rewrite substring_append_second; auto. rewrite length_append. (* ! *) assert (forall a b c, b >= c -> a - (b - c) = c + a - b) as Ha by (intros; omega). rewrite Ha; auto. Qed. Lemma split_once: forall s n, n <= String.length s -> ((String.substring 0 n s) ++ (String.substring n (String.length s - n) s))%string = s. Proof. intros. revert H. revert n. induction s; intros. - simpl in H. assert (n = 0) by omega. subst. simpl. auto. - destruct (Nat.eq_dec n 0). * subst. simpl. rewrite entire_substring. auto. * assert (n > 0) by omega. assert (exists m, n = S m) as mEq by (exists (Nat.pred n); rewrite Nat.succ_pred; auto). destruct mEq as [m mEq]. rewrite mEq. rewrite substring_cons_head. rewrite substring_cons_tail. simpl. rewrite cons_eq_cons. apply IHs. simpl in H. omega. Qed. Function concat (xs : list string): string := match xs with | nil => ""%string | (s :: more)%list => (s ++ concat more)%string end. Lemma concat_substring: forall k xs, k < List.length xs -> String.substring (natlist_sum (take k (List.map String.length xs))) (String.length (List.nth k xs EmptyString)) (concat xs) = List.nth k xs EmptyString. Proof. intros k xs. revert k. induction xs; intros. - simpl in H. omega. - rewrite List.map_cons. rewrite concat_equation. destruct k. * rewrite take_equation. rewrite natlist_sum_equation. simpl. rewrite substring_append_head_shorter; try omega. rewrite entire_substring. auto. * rewrite take_equation. rewrite natlist_sum_equation. simpl. rewrite substring_append_second; try omega. rewrite minus_plus. apply IHxs. simpl in H. omega. Qed. Lemma concat_length: forall xs, length (concat xs) = natlist_sum (List.map length xs). Proof. intros. induction xs. - simpl. auto. - rewrite List.map_cons. rewrite concat_equation. rewrite natlist_sum_equation. rewrite length_append. rewrite IHxs. auto. Qed. Lemma concat_in: forall x xs, List.In x xs -> exists m, String.substring m (String.length x) (concat xs) = x. Proof. intros. revert H. revert x. induction xs; intros. - simpl in H. contradiction. - apply List.in_inv in H. destruct H. * rewrite H. rewrite concat_equation. exists 0. rewrite substring_append_head_shorter; try omega. rewrite entire_substring. auto. * apply IHxs in H. destruct H as [m H]. rewrite concat_equation. exists (length a + m). rewrite substring_append_second; try omega. rewrite minus_plus. auto. Qed. Function reverse s: string := match s with | EmptyString => EmptyString | String c s' => ((reverse s') ++ String c EmptyString)%string end. Lemma length_reverse: forall s, String.length (reverse s) = String.length s. Proof. intro. induction s; simpl. - auto. - rewrite length_append. simpl. rewrite Nat.add_1_r. apply eq_S. auto. Qed. Lemma reverse_cons: forall c s, reverse (String c s) = (reverse s ++ String c EmptyString)%string. Proof. intros. rewrite reverse_equation. auto. Qed. Lemma cons_reverse: forall c s, String c (reverse s) = reverse (s ++ String c EmptyString)%string. Proof. intros. induction s. - rewrite append_nil_l. simpl. auto. - simpl. rewrite <- IHs. rewrite append_comm_cons. auto. Qed. Lemma reverse_reverse: forall s, reverse (reverse s) = s. Proof. intro. induction s; simpl. - auto. - rewrite <- cons_reverse. rewrite cons_eq_cons. auto. Qed. Function StringMap f s: string := match s with | EmptyString => EmptyString | String c s' => String (f c) (StringMap f s') end. Lemma map_identity: forall s, StringMap (fun c => c) s = s. Proof. intro. induction s; simpl. - auto. - rewrite cons_eq_cons. auto. Qed. Lemma map_length: forall s f, String.length (StringMap f s) = String.length s. Proof. intros; induction s; simpl; try rewrite IHs; auto. Qed. Lemma map_cons: forall c s f, StringMap f (String c s) = String (f c) (StringMap f s). Proof. intros; destruct s; simpl; auto. Qed. Lemma map_append: forall s1 s2 f, StringMap f (s1 ++ s2)%string = (StringMap f s1 ++ StringMap f s2)%string. Proof. intros. induction s1; simpl. - auto. - rewrite cons_eq_cons. auto. Qed. Lemma map_reverse: forall s f, StringMap f (reverse s) = reverse (StringMap f s). Proof. intros. induction s; simpl. - auto. - rewrite map_append. rewrite map_cons. rewrite IHs. simpl. auto. Qed. Inductive StringIn: ascii -> string -> Prop := | string_in_cons_eq: forall c s, StringIn c (String c s) | string_in_cons_neq: forall c1 c2 s, StringIn c1 s -> StringIn c1 (String c2 s) . Inductive StringNotIn: ascii -> string -> Prop := | string_notin_nil: forall c, StringNotIn c EmptyString | string_notin_cons: forall c1 c2 s, c1 <> c2 -> StringNotIn c1 s -> StringNotIn c1 (String c2 s) . (* this is redundant XXX *) Lemma StringInCons: forall c1 c2 s, StringIn c1 s -> StringIn c1 (String c2 s). Proof. intros; inversion H; subst; apply string_in_cons_neq; auto. Qed. Lemma StringInInv: forall c1 c2 s, StringIn c1 (String c2 s) -> c1 = c2 \/ StringIn c1 s. Proof. intros. destruct (ascii_dec c1 c2). - left; auto. - right. inversion H; subst; try contradiction; auto. Qed. Function StringNth n s def: ascii := match n, s with | _, EmptyString => def | 0, String c _ => c | S n', String _ s' => StringNth n' s' def end. Lemma StringNthCons: forall n s def c, StringNth n s def = StringNth (S n) (String c s) def. Proof. intros. revert n; induction s; intros; destruct n; simpl; auto. Qed. Lemma StringNthOverflow: forall s n def, String.length s <= n -> StringNth n s def = def. Proof. intro. (* s only *) induction s; intros. - rewrite StringNth_equation. destruct n; auto. - destruct n; try rewrite StringNth_equation; try apply IHs; simpl in H; omega. Qed. Lemma StringNthIndep: forall s n def def', n < String.length s -> StringNth n s def = StringNth n s def'. Proof. intro. (* s only *) induction s; intros. - simpl in H. omega. - destruct n; rewrite StringNth_equation. * rewrite StringNth_equation; auto. * simpl. apply IHs. simpl in H. omega. Qed. Lemma StringNthSCons: forall n s def c, StringIn (StringNth n s def) s -> StringIn (StringNth (S n) (String c s) def) (String c s). Proof. intros. rewrite <- StringNthCons. apply StringInCons. auto. Qed. Lemma StringNthIn: forall n s def, n < String.length s -> StringIn (StringNth n s def) s. Proof. intros n s. revert n. induction s; intros. - simpl in H. omega. - destruct n; simpl. * apply string_in_cons_eq. * apply StringInCons. apply IHs. simpl in H. omega. Qed. Lemma StringInNth: forall s c def, StringIn c s -> exists n, n < String.length s /\ StringNth n s def = c. Proof. intro. (* s only *) induction s; intros. - inversion H. - apply StringInInv in H. destruct H. * rewrite H. exists 0; split; simpl; try omega; auto. * apply IHs with (def := def) in H. destruct H as [n H]. exists (S n). simpl. rewrite <- Nat.succ_lt_mono. auto. Qed. Lemma StringNthInOrDefault: forall n s def, {StringIn (StringNth n s def) s} + {StringNth n s def = def}. Proof. intros. destruct (le_gt_dec (String.length s) n). - right; apply StringNthOverflow; auto. - left. apply StringNthIn. omega. Qed. Lemma StringAppNth_l: forall s1 s2 def n, n < String.length s1 -> StringNth n (s1 ++ s2)%string def = StringNth n s1 def. Proof. intro. (* s1 only *) induction s1; intros; simpl in H. - omega. - rewrite append_comm_cons. destruct n; simpl. * auto. * apply IHs1. omega. Qed. Lemma StringAppNth_r: forall s1 s2 def n, n >= String.length s1 -> StringNth n (s1 ++ s2)%string def = StringNth (n - String.length s1) s2 def. Proof. intro. (* s1 only *) induction s1; intros; simpl in H. - simpl. rewrite Nat.sub_0_r. auto. - rewrite append_comm_cons. destruct n; simpl; try apply IHs1; omega. Qed. Lemma StringNthSplit: forall n s def, n < String.length s -> exists s1 s2, s = (s1 ++ String (StringNth n s def) s2)%string /\ String.length s1 = n. Proof. intros n s. revert n. induction s; intros. - simpl in H. omega. - destruct n. * exists EmptyString, s. rewrite append_nil_l. simpl. split; auto. * simpl. specialize IHs with (n := n) (def := def). simpl in H. apply lt_S_n in H. apply IHs in H. destruct H as [s1 [s2 [H1 H2]]]. exists (String a s1), s2. rewrite append_comm_cons. rewrite cons_eq_cons. simpl. rewrite H2. split; auto. Qed. Lemma StringRevNth: forall s def n, n < String.length s -> StringNth n (reverse s) def = StringNth (String.length s - S n) s def. Proof. intro. (* s only *) induction s; intros; simpl in H. - omega. - simpl. destruct (Nat.eq_dec n (String.length s)). * subst. rewrite StringAppNth_r; rewrite length_reverse; try omega. rewrite Nat.sub_diag. simpl. auto. * simpl in H. assert (n < length s) by omega. rewrite StringAppNth_l; try rewrite length_reverse; auto. apply IHs with (def := def) in H0. rewrite H0. assert (S (length s - S n) = length s - n) by omega. rewrite <- H1. rewrite <- StringNthCons. auto. Qed. Lemma StringMapNth: forall f s def n, StringNth n (StringMap f s) (f def) = f (StringNth n s def). Proof. intros f s. revert f. induction s; intros; destruct n; simpl; auto. Qed. Lemma string_dec: forall s1 s2 : string, {s1 = s2} + {s1 <> s2}. Proof. intro. induction s1; intros; destruct s2. - left. auto. - right. congruence. - right. congruence. - destruct (ascii_dec a a0); destruct IHs1 with (s2 := s2); subst. * left; auto. * right; congruence. * right; congruence. * right; congruence. Qed. (* * string_eq is an executable equality test for strings *) Function string_eq (s1 s2 : string): bool := match s1, s2 with | EmptyString, EmptyString => true | String c1 s1', String c2 s2' => ascii_eq c1 c2 && string_eq s1' s2' | _, _ => false end. (* string equality is reflexive *) Lemma string_eq_refl: forall s, string_eq s s = true. Proof. intros. induction s; simpl; auto. rewrite andb_true_iff. rewrite ascii_eq_iff. auto. Qed. (* show that string_eq is equivalent to structural equality *) Lemma string_eq_iff: forall s1 s2, string_eq s1 s2 = true <-> s1 = s2. Proof. split; revert s2; induction s1; intros; destruct s2; try discriminate; auto. - simpl in H. rewrite andb_true_iff in H. destruct H as [H1 H2]. apply IHs1 in H2. rewrite ascii_eq_iff in H1. subst; auto. - simpl. rewrite andb_true_iff. split. * rewrite ascii_eq_iff; congruence. * rewrite IHs1; auto; congruence. Qed. (* also nonequality *) Lemma string_neq_iff: forall s1 s2, string_eq s1 s2 = false <-> s1 <> s2. Proof. split; revert s2; induction s1; intros; destruct s2; try discriminate; try contradiction; auto. - simpl in H. rewrite andb_false_iff in H. destruct H. * rewrite ascii_neq_iff in H. congruence. * apply IHs1 in H. congruence. - simpl. rewrite andb_false_iff. apply cons_neq_cons_3 in H. destruct H. * left. rewrite ascii_neq_iff. auto. * right. apply IHs1. auto. Qed. End StringFacts.
[STATEMENT] lemma welltyped_Seq_iff[simp]: "e1 ? e2 ::: T \<longleftrightarrow> (T = \<B> \<and> e1 ::: \<B> \<and> e2 ::: \<B>)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. e1 ? e2 ::: T = (T = \<B> \<and> e1 ::: \<B> \<and> e2 ::: \<B>) [PROOF STEP] by auto
module Proginduction where import MHMonad import Distr import Data.Monoid import Statistics.Distribution import Statistics.Distribution.Normal (normalDistr) import Graphics.Rendering.Chart import Graphics.Rendering.Chart.Backend.Diagrams import Graphics.Rendering.Chart.State import Data.Colour import Data.Colour.Names import Data.Default.Class import Control.Lens -- A grammar for a simple expression language data BinOp = Add | Multiply data UnOp = Neg data Expr = BinOp BinOp Expr Expr | UnOp UnOp Expr | Number Double | Var | Cond BoolExpr Expr Expr data BoolExpr = Leq Expr Expr -- Simple evaluation function for expressions eval :: Expr -> Double -> Double eval (BinOp Add e1 e2) x = (eval e1 x) + (eval e2 x) eval (BinOp Multiply e1 e2) x = (eval e1 x) * (eval e2 x) eval (UnOp Neg e ) x = - (eval e x) eval (Number r) x = r eval (Cond (Leq e1 e2) e3 e4) x = if (eval e1 x) <= (eval e2 x) then (eval e3 x) else (eval e4 x) eval Var x = x -- a probabilistic context free grammar pcfgbinop :: Meas BinOp pcfgbinop = do n <- categorical [0.5,0.5] case n of 0 -> return Add 1 -> return Multiply pcfgexpr :: Meas Expr pcfgexpr = do n <- categorical [0.2,0.1,0.3,0.39,0.01] case n of 0 -> do {o <- pcfgbinop ; e1 <- pcfgexpr ; e2 <- pcfgexpr ; return $ BinOp o e1 e2 } 1 -> do {e <- pcfgexpr ; return $ UnOp Neg e } 2 -> do {r <- normal 0 3 ; return $ Number r } 3 -> return $ Var 4 -> do {e1 <- return Var ; r <- normal 0 4 ; e3 <- pcfgexpr ; e4 <- pcfgexpr ; return $ Cond (Leq e1 (Number r)) e3 e4 } -- length of an expression len :: Expr -> Integer len (BinOp _ e1 e2) = len e1 + len e2 + 1 len (UnOp _ e1) = len e1 + 1 len (Number r) = 1 len Var = 1 len (Cond (Leq e1 e2) e3 e4) = len e1 + len e2 + len e3 + len e4 + 1 -- a random expression is drawn from the context free grammar, -- but then we weight to get a more reasonable length randexpr :: Meas (Double -> Double) randexpr = do { e <- pcfgexpr ; score ((normalPdf 25 5) (fromIntegral $ len e)) ; return $ \x -> eval e x } -- functions for plotting a histogram totalweight :: [(Integer,Double)] -> Double totalweight rxs = sum $ map (\(_,r) -> r) rxs toHistogram :: [(Integer,Double)] -> Integer -> Integer -> [Double] toHistogram rxs from to = if from > to then [] else ((sum $ map (\(x,r) -> if x == from then r else 0) rxs) / (totalweight rxs)) : (toHistogram rxs (from + 1) to) chart :: [Double] -> Renderable () chart rs = toRenderable layout where layout = layout_title .~ "Sample Bars" ++ btitle $ layout_title_style . font_size .~ 10 $ layout_x_axis . laxis_generate .~ autoIndexAxis alabels $ layout_y_axis . laxis_override .~ axisGridHide $ layout_left_axis_visibility . axis_show_ticks .~ False $ layout_plots .~ [ plotBars bars2 ] $ def :: Layout PlotIndex Double bars2 = plot_bars_titles .~ [""] $ plot_bars_values .~ addIndexes (map (\x -> [x]) rs) -- [45,30],[30,20],[70,25]] -- $ plot_bars_style .~ BarsClustered $ plot_bars_spacing .~ BarsFixGap 30 5 $ plot_bars_item_styles .~ map mkstyle (cycle defaultColorSeq) $ def alabels = map show [0 .. ((length rs)-1)] btitle = "" bstyle = Just (solidLine 1.0 $ opaque black) mkstyle c = (solidFillStyle c, bstyle) -- plot a histogram of lengths when the weighted pcfg grammar is used test1 = let test = do e <- pcfgexpr -- score ((density $ normalDistr 25 5) (fromIntegral $ len e)) return $ len e in do rxs' <- weightedsamples test let rxs = map (\(x,r) -> (x,r)) rxs' _ <- renderableToFile def "histogram.svg" (chart (toHistogram (take 100000 rxs) 0 40)) return () sample_fun f = [ (x, f x) | x <- [(-0.25),(-0.25+0.1)..6.2]] plot_funs :: String -> [(Double,Double)] -> [Double -> Double] -> IO () plot_funs filename dataset funs = let graphs = map sample_fun funs in let my_lines = plot_lines_style . line_color .~ blue `withOpacity` 0.1 $ plot_lines_values .~ graphs $ def in let my_dots = plot_points_style .~ filledCircles 4 (opaque black) $ plot_points_values .~ dataset $ def in let my_layout = layout_plots .~ [toPlot my_lines , toPlot my_dots] $ layout_x_axis . laxis_generate .~ scaledAxis def (0,6) $ layout_y_axis . laxis_generate .~ scaledAxis def (-2,10) $ def in let graphic = toRenderable my_layout in do putStr ("Generating " ++ filename ++ "...") renderableToFile def filename graphic; putStrLn (" Done!") return () dataset :: [(Double, Double)] dataset = [(0,0.6), (1, 0.7), (2,1.2), (3,3.2), (4,6.8), (5, 8.2), (6,8.4)] fit prior dataset = do f <- prior mapM (\(x,y) -> score $ (density $ normalDistr (f x) 0.3) y) dataset return f every n xs = case drop (n-1) xs of (y:ys) -> y : every n ys [] -> [] -- Plot some fitted expressions test3 = do fs' <- mh $ fit randexpr dataset let fs = map (\(f,_)->f) $ take 10 $ every 1000 $ drop 1000000 $ fs' plot_funs "prog-ind.svg" dataset fs return () -- Histogram of the posterior length test4 = do let posteriorLength = do e <- pcfgexpr mapM (\(x,y) -> score $ (density $ normalDistr (eval e x) 0.3) y) dataset return (len e) ls <- mh $ posteriorLength let rxs = map (\(x,r) -> (x,getProduct r)) ls _ <- renderableToFile def "histogram.svg" (chart (toHistogram (take 100000 $ drop 100000 rxs) 0 40)) return ()
# Agave Platform Science API # # Power your digital lab and reduce the time from theory to discovery using the Agave Science-as-a-Service API Platform. Agave provides hosted services that allow researchers to manage data, conduct experiments, and publish and share results from anywhere at any time. # # Agave Platform version: 2.2.14 # # Generated by: https://github.com/swagger-api/swagger-codegen.git #' FileMkdirAction Class #' #' Request for a new directory to be created on the target system. This will recursively create missing directories. #' #' @field action #' @field path Name of new directory or target file or folder. #' #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export FileMkdirAction <- R6::R6Class( 'FileMkdirAction', public = list( `action` = NULL, `path` = NULL, initialize = function(`action`, `path`){ if (!missing(`action`)) { stopifnot(R6::is.R6(`action`)) self$`action` <- `action` } if (!missing(`path`)) { stopifnot(is.character(`path`), length(`path`) == 1) self$`path` <- `path` } }, asJSON = function() { self$toJSON() }, toJSON = function() { FileMkdirActionObject <- list() if (!is.null(self$`action`)) { FileMkdirActionObject[['action']] <- self$`action`$toJSON() } else { FileMkdirActionObject[['action']] <- NULL } if (!is.null(self$`path`)) { FileMkdirActionObject[['path']] <- self$`path` } else { FileMkdirActionObject[['path']] <- NULL } FileMkdirActionObject }, fromJSON = function(FileMkdirActionObject) { if (is.character(FileMkdirActionObject)) { FileMkdirActionObject <- jsonlite::fromJSON(FileMkdirActionJson) } if ("result" %in% names(FileMkdirActionObject)) { FileMkdirActionObject <- FileMkdirActionObject$result } if (!is.null(FileMkdirActionObject$`action`)) { actionObject <- FileManagementActionType$new() actionObject$fromJSON(jsonlite::toJSON(FileMkdirActionObject$action, auto_unbox = TRUE)) self$`action` <- actionObject } if (!is.null(FileMkdirActionObject$`path`)) { self$`path` <- FileMkdirActionObject$`path` } }, toJSONString = function() { sprintf( '{ "action": %s, "path": %s }', self$`action`$toJSON(), ifelse( is.null(self$`path`),"null",paste0(c('"', self$`path`, '"'))) ) }, fromJSONString = function(FileMkdirActionJson) { FileMkdirActionObject <- jsonlite::fromJSON(FileMkdirActionJson) self::fromJSON(FileMkdirActionObject) } ) )
(* * Copyright 2014, General Dynamics C4 Systems * * SPDX-License-Identifier: GPL-2.0-only *) theory CSpace_C imports CSpaceAcc_C Machine_C begin context kernel_m begin lemma maskCapRights_cap_cases: "return (maskCapRights R c) = (case c of ArchObjectCap ac \<Rightarrow> return (Arch.maskCapRights R ac) | EndpointCap _ _ _ _ _ _ \<Rightarrow> return (capEPCanGrantReply_update (\<lambda>_. capEPCanGrantReply c \<and> capAllowGrantReply R) (capEPCanGrant_update (\<lambda>_. capEPCanGrant c \<and> capAllowGrant R) (capEPCanReceive_update (\<lambda>_. capEPCanReceive c \<and> capAllowRead R) (capEPCanSend_update (\<lambda>_. capEPCanSend c \<and> capAllowWrite R) c)))) | NotificationCap _ _ _ _ \<Rightarrow> return (capNtfnCanReceive_update (\<lambda>_. capNtfnCanReceive c \<and> capAllowRead R) (capNtfnCanSend_update (\<lambda>_. capNtfnCanSend c \<and> capAllowWrite R) c)) | ReplyCap _ _ _ \<Rightarrow> return (capReplyCanGrant_update (\<lambda>_. capReplyCanGrant c \<and> capAllowGrant R) c) | _ \<Rightarrow> return c)" apply (simp add: maskCapRights_def Let_def split del: if_split) apply (cases c; simp add: isCap_simps split del: if_split) done lemma wordFromVMRights_spec: "\<forall>s. \<Gamma> \<turnstile> {s} Call wordFromVMRights_'proc \<lbrace>\<acute>ret__unsigned_long = \<^bsup>s\<^esup>vm_rights\<rbrace>" by vcg simp? lemma vmRightsFromWord_spec: "\<forall>s. \<Gamma> \<turnstile> {s} Call vmRightsFromWord_'proc \<lbrace>\<acute>ret__unsigned_long = \<^bsup>s\<^esup>w\<rbrace>" by vcg simp? lemmas vmrights_defs = Kernel_C.VMNoAccess_def Kernel_C.VMReadOnly_def Kernel_C.VMKernelOnly_def Kernel_C.VMReadWrite_def lemma maskVMRights_spec: "\<forall>s. \<Gamma> \<turnstile> ({s} \<inter> \<lbrace> \<acute>vm_rights && mask 2 = \<acute>vm_rights \<rbrace>) Call maskVMRights_'proc \<lbrace> vmrights_to_H \<acute>ret__unsigned_long = maskVMRights (vmrights_to_H \<^bsup>s\<^esup>vm_rights) (cap_rights_to_H (seL4_CapRights_lift \<^bsup>s\<^esup>cap_rights_mask)) \<and> \<acute>ret__unsigned_long && mask 2 = \<acute>ret__unsigned_long \<rbrace>" apply vcg apply clarsimp apply (rule conjI) apply ((auto simp: vmrights_to_H_def maskVMRights_def vmrights_defs cap_rights_to_H_def to_bool_def split: bool.split | simp add: mask_def | word_bitwise)+)[1] apply clarsimp apply (subgoal_tac "vm_rights = 0 \<or> vm_rights = 1 \<or> vm_rights = 2 \<or> vm_rights = 3") apply (auto simp: vmrights_to_H_def maskVMRights_def vmrights_defs cap_rights_to_H_def seL4_CapRights_lift_def to_bool_def mask_def split: bool.splits)[1] apply (subst(asm) mask_eq_iff_w2p) apply (simp add: word_size) apply (rule ccontr, clarsimp) apply (drule inc_le, simp, drule(1) order_le_neq_trans [OF _ not_sym])+ apply (drule inc_le, simp) done lemma small_frame_cap_rights [simp]: "cap_get_tag cap = scast cap_small_frame_cap \<Longrightarrow> cap_small_frame_cap_CL.capFVMRights_CL (cap_small_frame_cap_lift cap) && mask 2 = cap_small_frame_cap_CL.capFVMRights_CL (cap_small_frame_cap_lift cap)" apply (simp add: cap_small_frame_cap_lift_def) by (simp add: cap_lift_def cap_tag_defs mask_def word_bw_assocs) lemma frame_cap_rights [simp]: "cap_get_tag cap = scast cap_frame_cap \<Longrightarrow> cap_frame_cap_CL.capFVMRights_CL (cap_frame_cap_lift cap) && mask 2 = cap_frame_cap_CL.capFVMRights_CL (cap_frame_cap_lift cap)" apply (simp add: cap_frame_cap_lift_def) by (simp add: cap_lift_def cap_tag_defs mask_def word_bw_assocs) lemma Arch_maskCapRights_ccorres [corres]: "ccorres ccap_relation ret__struct_cap_C_' \<top> (UNIV \<inter> \<lbrace>ccap_relation (ArchObjectCap arch_cap) \<acute>cap\<rbrace> \<inter> \<lbrace>ccap_rights_relation R \<acute>cap_rights_mask\<rbrace>) [] (return (Arch.maskCapRights R arch_cap)) (Call Arch_maskCapRights_'proc)" apply (cinit' (trace) lift: cap_' cap_rights_mask_') apply csymbr apply (unfold ARM_HYP_H.maskCapRights_def) apply (simp only: Let_def) apply (case_tac "cap_get_tag cap = scast cap_small_frame_cap") apply (clarsimp simp add: ccorres_cond_iffs cap_get_tag_isCap isCap_simps) apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV]) apply (rule allI, rule conseqPre, vcg) apply (clarsimp simp: cap_get_tag_isCap isCap_simps) apply (clarsimp simp: return_def) apply (unfold ccap_relation_def)[1] apply (simp add: cap_small_frame_cap_lift [THEN iffD1]) apply (clarsimp simp: cap_to_H_def) apply (simp add: map_option_case split: option.splits) apply (clarsimp simp add: cap_to_H_def Let_def split: cap_CL.splits if_split_asm) apply (simp add: cap_small_frame_cap_lift_def) apply (simp add: ccap_rights_relation_def) apply (simp add: cap_small_frame_cap_lift_def) apply (simp add: ccap_rights_relation_def) apply (simp add: pageSize_def) apply (simp add: pageSize_def) apply (clarsimp simp add: cap_get_tag_isCap isCap_simps simp del: not_ex) apply (rule conjI, clarsimp) apply (simp add: ccorres_cond_iffs) apply (rule ccorres_guard_imp) apply (csymbr) apply (case_tac "cap_get_tag cap = scast cap_frame_cap") apply (clarsimp simp add: ccorres_cond_iffs cap_get_tag_isCap isCap_simps simp del: not_ex) apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV]) apply (rule allI, rule conseqPre, vcg) apply (clarsimp simp: cap_get_tag_isCap isCap_simps simp del: not_ex) apply (clarsimp simp: return_def) apply (unfold ccap_relation_def)[1] apply (simp add: cap_frame_cap_lift [THEN iffD1]) apply (clarsimp simp: cap_to_H_def) apply (simp add: map_option_case split: option.splits) apply (clarsimp simp add: isCap_simps pageSize_def cap_to_H_def Let_def simp del: not_ex split: cap_CL.splits if_split_asm) apply (simp add: cap_frame_cap_lift_def) apply (simp add: ccap_rights_relation_def) apply (simp add: c_valid_cap_def cl_valid_cap_def cap_lift_frame_cap) apply (simp add: cap_frame_cap_lift_def) apply (simp add: ccap_rights_relation_def) apply (simp add: c_valid_cap_def cl_valid_cap_def cap_lift_frame_cap) apply (clarsimp simp add: cap_get_tag_isCap isCap_simps simp del: not_ex)+ apply (simp add: ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws) apply (rule allI, rule conseqPre, vcg) apply (clarsimp simp add: return_def simp del: not_ex) apply (cases arch_cap) by (fastforce simp add: cap_get_tag_isCap isCap_simps simp del: not_ex simp_thms(44))+ (* FIXME: move to Wellformed_C (or move to_bool_bf out of Wellformed_C) *) lemma to_bool_mask_to_bool_bf: "to_bool (x && 1) = to_bool_bf (x::word32)" by (simp add: to_bool_bf_def to_bool_def) lemma to_bool_cap_rights_bf: "to_bool (capAllowRead_CL (seL4_CapRights_lift R)) = to_bool_bf (capAllowRead_CL (seL4_CapRights_lift R))" "to_bool (capAllowWrite_CL (seL4_CapRights_lift R)) = to_bool_bf (capAllowWrite_CL (seL4_CapRights_lift R))" "to_bool (capAllowGrant_CL (seL4_CapRights_lift R)) = to_bool_bf (capAllowGrant_CL (seL4_CapRights_lift R))" "to_bool (capAllowGrantReply_CL (seL4_CapRights_lift R)) = to_bool_bf (capAllowGrantReply_CL (seL4_CapRights_lift R))" by (subst to_bool_bf_to_bool_mask, simp add: seL4_CapRights_lift_def mask_def word_bw_assocs, simp)+ lemma to_bool_ntfn_cap_bf: "cap_lift c = Some (Cap_notification_cap cap) \<Longrightarrow> to_bool (capNtfnCanSend_CL cap) = to_bool_bf (capNtfnCanSend_CL cap) \<and> to_bool (capNtfnCanReceive_CL cap) = to_bool_bf (capNtfnCanReceive_CL cap)" apply (simp add:cap_lift_def Let_def split: if_split_asm) apply (subst to_bool_bf_to_bool_mask, clarsimp simp: cap_lift_thread_cap mask_def word_bw_assocs)+ apply simp done lemma to_bool_reply_cap_bf: "cap_lift c = Some (Cap_reply_cap cap) \<Longrightarrow> to_bool (capReplyMaster_CL cap) = to_bool_bf (capReplyMaster_CL cap) \<and> to_bool (capReplyCanGrant_CL cap) = to_bool_bf (capReplyCanGrant_CL cap)" apply (simp add: cap_lift_def Let_def split: if_split_asm) apply (subst to_bool_bf_to_bool_mask, clarsimp simp: cap_lift_thread_cap mask_def word_bw_assocs)+ apply simp done lemma to_bool_ep_cap_bf: "cap_lift c = Some (Cap_endpoint_cap cap) \<Longrightarrow> to_bool (capCanSend_CL cap) = to_bool_bf (capCanSend_CL cap) \<and> to_bool (capCanReceive_CL cap) = to_bool_bf (capCanReceive_CL cap) \<and> to_bool (capCanGrant_CL cap) = to_bool_bf (capCanGrant_CL cap) \<and> to_bool (capCanGrantReply_CL cap) = to_bool_bf (capCanGrantReply_CL cap)" apply (simp add:cap_lift_def Let_def split: if_split_asm) apply (subst to_bool_bf_to_bool_mask, clarsimp simp: cap_lift_thread_cap mask_def word_bw_assocs)+ apply simp done lemma isArchCap_spec: "\<forall>s. \<Gamma>\<turnstile> {s} Call isArchCap_'proc \<lbrace>\<acute>ret__unsigned_long = from_bool (isArchCap_tag (cap_get_tag (cap_' s)))\<rbrace>" apply vcg apply (clarsimp simp: from_bool_def isArchCap_tag_def bool.split) done lemma maskCapRights_ccorres [corres]: "ccorres ccap_relation ret__struct_cap_C_' \<top> (UNIV \<inter> \<lbrace>ccap_relation cap \<acute>cap\<rbrace> \<inter> \<lbrace>ccap_rights_relation R \<acute>cap_rights\<rbrace>) [] (return (RetypeDecls_H.maskCapRights R cap)) (Call maskCapRights_'proc)" apply (cinit' lift: cap_' cap_rights_') apply csymbr apply (simp add: maskCapRights_cap_cases cap_get_tag_isCap del: Collect_const) apply wpc apply (simp add: Collect_const_mem from_bool_def) apply csymbr apply (simp add: cap_get_tag_isCap isCap_simps del: Collect_const) apply (simp add: ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV]) apply (rule allI) apply (rule conseqPre) apply vcg apply clarsimp apply (simp add: cap_get_tag_isCap isCap_simps return_def) apply (simp add: Collect_const_mem from_bool_def) apply csymbr apply (simp add: cap_get_tag_isCap isCap_simps del: Collect_const) apply (simp add: ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV]) apply (rule allI) apply (rule conseqPre) apply vcg apply (clarsimp simp: return_def) apply (simp add: Collect_const_mem from_bool_def) apply csymbr apply (simp add: cap_get_tag_isCap isCap_simps del: Collect_const) apply (simp add: ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV]) apply (rule allI) apply (rule conseqPre) apply vcg apply clarsimp apply (simp add: cap_get_tag_isCap isCap_simps return_def) apply (rule imp_ignore) apply (rule imp_ignore) apply (rule imp_ignore) apply (rule imp_ignore) apply (rule imp_ignore) apply clarsimp apply (unfold ccap_relation_def)[1] apply (simp add: cap_notification_cap_lift [THEN iffD1]) apply (clarsimp simp: cap_to_H_def) apply (simp add: map_option_case split: option.splits) apply (clarsimp simp add: cap_to_H_def Let_def split: cap_CL.splits if_split_asm) apply (simp add: cap_notification_cap_lift_def) apply (simp add: ccap_rights_relation_def cap_rights_to_H_def to_bool_ntfn_cap_bf to_bool_mask_to_bool_bf to_bool_cap_rights_bf) apply (simp add: Collect_const_mem from_bool_def) apply csymbr apply (simp add: cap_get_tag_isCap isCap_simps ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV]) apply (rule allI) apply (rule conseqPre) apply vcg apply (clarsimp simp: cap_get_tag_isCap isCap_simps return_def) apply (simp add: Collect_const_mem from_bool_def) apply csymbr apply (simp add: cap_get_tag_isCap isCap_simps ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV]) apply (rule allI) apply (rule conseqPre) apply vcg apply clarsimp apply (simp add: cap_get_tag_isCap isCap_simps return_def) apply (rule imp_ignore) apply (rule imp_ignore) apply (rule imp_ignore) apply (rule imp_ignore) apply (rule imp_ignore) apply (rule imp_ignore) apply (rule imp_ignore) apply (rule imp_ignore) apply clarsimp apply (unfold ccap_relation_def)[1] apply (simp add: cap_endpoint_cap_lift [THEN iffD1]) apply (clarsimp simp: cap_to_H_def) apply (simp add: map_option_case split: option.splits) apply (clarsimp simp add: cap_to_H_def Let_def split: cap_CL.splits if_split_asm) apply (simp add: cap_endpoint_cap_lift_def) apply (simp add: ccap_rights_relation_def cap_rights_to_H_def to_bool_ep_cap_bf to_bool_mask_to_bool_bf to_bool_cap_rights_bf) apply (simp add: Collect_const_mem from_bool_def) apply csymbr apply (simp add: cap_get_tag_isCap isCap_simps del: Collect_const) apply (simp add: ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV]) apply (rule allI) apply (rule conseqPre) apply vcg apply (clarsimp simp: return_def) apply (simp add: Collect_const_mem from_bool_def) apply csymbr apply (simp add: cap_get_tag_isCap isCap_simps ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV]) apply (rule allI) apply (rule conseqPre) apply vcg apply (clarsimp simp: cap_get_tag_isCap isCap_simps return_def) apply (simp add: Collect_const_mem from_bool_def) apply (subst bind_return [symmetric]) apply (rule ccorres_split_throws) apply ctac apply (rule_tac P=\<top> and P'="\<lbrace>\<acute>ret__struct_cap_C = ret__struct_cap_C\<rbrace>" in ccorres_inst) apply (rule ccorres_from_vcg_throws) apply (clarsimp simp: return_def) apply (rule conseqPre) apply vcg apply clarsimp apply wp apply vcg apply vcg apply (simp add: Collect_const_mem from_bool_def) apply csymbr apply (simp add: cap_get_tag_isCap isCap_simps del: Collect_const) apply ccorres_rewrite apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV]) apply (rule allI) apply (rule conseqPre) apply vcg apply (simp add: cap_get_tag_isCap isCap_simps return_def) apply clarsimp apply (unfold ccap_relation_def)[1] apply (simp add: cap_reply_cap_lift [THEN iffD1]) apply (clarsimp simp: cap_to_H_def) apply (simp add: map_option_case split: option.splits) apply (clarsimp simp add: cap_to_H_def Let_def split: cap_CL.splits if_split_asm) apply (simp add: cap_reply_cap_lift_def) apply (simp add: ccap_rights_relation_def cap_rights_to_H_def to_bool_reply_cap_bf to_bool_mask_to_bool_bf[simplified] to_bool_cap_rights_bf) apply (simp add: Collect_const_mem from_bool_def) apply csymbr apply (simp add: cap_get_tag_isCap isCap_simps del: Collect_const) apply (simp add: ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV]) apply (rule allI) apply (rule conseqPre) apply vcg apply (clarsimp simp: return_def) apply (simp add: Collect_const_mem from_bool_def) apply csymbr apply (simp add: cap_get_tag_isCap isCap_simps del: Collect_const) apply (simp add: ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV]) apply (rule allI) apply (rule conseqPre) apply vcg apply clarsimp apply (simp add: cap_get_tag_isCap isCap_simps return_def) apply (simp add: Collect_const_mem from_bool_def) apply csymbr apply (simp add: cap_get_tag_isCap isCap_simps del: Collect_const) apply (simp add: ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws [where P=\<top> and P'=UNIV]) apply (rule allI) apply (rule conseqPre) apply vcg apply (clarsimp simp: return_def) apply clarsimp done abbreviation "lookupCap_xf \<equiv> liftxf errstate lookupCap_ret_C.status_C lookupCap_ret_C.cap_C ret__struct_lookupCap_ret_C_'" lemma ccorres_return_cte_cteCap [corres]: fixes ptr' :: "cstate \<Rightarrow> cte_C ptr" assumes r1: "\<And>s s' g. (s, s') \<in> rf_sr \<Longrightarrow> (s, xfu g s') \<in> rf_sr" and xf_xfu: "\<And>s g. xf (xfu g s) = g s" shows "ccorres ccap_relation xf (\<lambda>s. ctes_of s ptr = Some cte) {s. ptr_val (ptr' s) = ptr} hs (return (cteCap cte)) (Basic (\<lambda>s. xfu (\<lambda>_. h_val (hrs_mem (t_hrs_' (globals s))) (Ptr &(ptr' s \<rightarrow>[''cap_C'']))) s))" apply (rule ccorres_return) apply (rule conseqPre) apply vcg apply (clarsimp simp: xf_xfu ccap_relation_def) apply rule apply (erule r1) apply (drule (1) rf_sr_ctes_of_clift) apply (clarsimp simp: typ_heap_simps) apply (simp add: c_valid_cte_def) done lemma ccorres_return_cte_mdbnode [corres]: fixes ptr' :: "cstate \<Rightarrow> cte_C ptr" assumes r1: "\<And>s s' g. (s, s') \<in> rf_sr \<Longrightarrow> (s, xfu g s') \<in> rf_sr" and xf_xfu: "\<And>s g. xf (xfu g s) = g s" shows "ccorres cmdbnode_relation xf (\<lambda>s. ctes_of s ptr = Some cte) {s. ptr_val (ptr' s) = ptr} hs (return (cteMDBNode cte)) (Basic (\<lambda>s. xfu (\<lambda>_. h_val (hrs_mem (t_hrs_' (globals s))) (Ptr &(ptr' s \<rightarrow>[''cteMDBNode_C'']))) s))" apply (rule ccorres_from_vcg) apply (rule allI, rule conseqPre, vcg) apply (clarsimp simp add: return_def xf_xfu) apply (frule (1) rf_sr_ctes_of_clift) apply (clarsimp simp: typ_heap_simps) apply (erule r1) done (* FIXME: MOVE *) lemma heap_update_field_ext: "\<lbrakk>field_ti TYPE('a :: packed_type) f = Some t; c_guard p; export_uinfo t = export_uinfo (typ_info_t TYPE('b :: packed_type))\<rbrakk> \<Longrightarrow> heap_update (Ptr &(p\<rightarrow>f) :: 'b ptr) = (\<lambda>v hp. heap_update p (update_ti t (to_bytes_p v) (h_val hp p)) hp)" apply (rule ext, rule ext) apply (erule (2) heap_update_field) done lemma ccorres_updateCap [corres]: fixes ptr :: "cstate \<Rightarrow> cte_C ptr" and val :: "cstate \<Rightarrow> cap_C" shows "ccorres dc xfdc \<top> ({s. ccap_relation cap (val s)} \<inter> {s. ptr s = Ptr dest}) hs (updateCap dest cap) (Basic (\<lambda>s. globals_update (t_hrs_'_update (hrs_mem_update (heap_update (Ptr &(ptr s\<rightarrow>[''cap_C''])) (val s)))) s))" unfolding updateCap_def apply (cinitlift ptr) apply (erule ssubst) apply (rule ccorres_guard_imp2) apply (rule ccorres_pre_getCTE) apply (rule_tac P = "\<lambda>s. ctes_of s dest = Some rva" in ccorres_from_vcg [where P' = "{s. ccap_relation cap (val s)}"]) apply (rule allI) apply (rule conseqPre) apply vcg apply clarsimp apply (rule fst_setCTE [OF ctes_of_cte_at], assumption) apply (erule bexI [rotated]) apply (clarsimp simp: cte_wp_at_ctes_of) apply (frule (1) rf_sr_ctes_of_clift) apply (clarsimp simp add: rf_sr_def cstate_relation_def Let_def cpspace_relation_def cvariable_array_map_const_add_map_option[where f="tcb_no_ctes_proj"]) apply (simp add:typ_heap_simps) apply (rule conjI) apply (erule (3) cpspace_cte_relation_upd_capI) apply (frule_tac f="ksPSpace" in arg_cong) apply (erule_tac t = s' in ssubst) apply simp apply (simp add: heap_to_user_data_def heap_to_device_data_def) apply (rule conjI) apply (erule (1) setCTE_tcb_case) subgoal by (simp add: carch_state_relation_def cmachine_state_relation_def typ_heap_simps) by clarsimp lemma ccorres_updateMDB_const [corres]: fixes ptr :: "cstate \<Rightarrow> cte_C ptr" and val :: "cstate \<Rightarrow> mdb_node_C" shows "ccorres dc xfdc (\<lambda>_. dest \<noteq> 0) ({s. cmdbnode_relation m (val s)} \<inter> {s. ptr s = Ptr dest}) hs (updateMDB dest (const m)) (Basic (\<lambda>s. globals_update (t_hrs_'_update (hrs_mem_update (heap_update (Ptr &(ptr s\<rightarrow>[''cteMDBNode_C''])) (val s)))) s))" unfolding updateMDB_def apply (cinitlift ptr) apply (erule ssubst) apply (rule ccorres_gen_asm [where G = \<top>, simplified]) apply (simp only: Let_def) apply simp apply (rule ccorres_guard_imp2) apply (rule ccorres_pre_getCTE) apply (rule_tac P = "\<lambda>s. ctes_of s dest = Some cte" in ccorres_from_vcg [where P' = "{s. cmdbnode_relation m (val s)}"]) apply (rule allI) apply (rule conseqPre) apply vcg apply clarsimp apply (rule fst_setCTE [OF ctes_of_cte_at], assumption ) apply (erule bexI [rotated]) apply (frule (1) rf_sr_ctes_of_clift) apply (clarsimp simp add: rf_sr_def cstate_relation_def typ_heap_simps Let_def cpspace_relation_def cvariable_array_map_const_add_map_option[where f="tcb_no_ctes_proj"]) apply (rule conjI) apply (erule (3) cspace_cte_relation_upd_mdbI) apply (erule_tac t = s' in ssubst) apply (simp add: heap_to_user_data_def) apply (rule conjI) apply (erule (1) setCTE_tcb_case) apply (simp add: carch_state_relation_def cmachine_state_relation_def typ_heap_simps) apply (clarsimp) done lemma cap_lift_capNtfnBadge_mask_eq: "cap_lift cap = Some (Cap_notification_cap ec) \<Longrightarrow> capNtfnBadge_CL ec && mask 28 = capNtfnBadge_CL ec" unfolding cap_lift_def by (fastforce simp: Let_def mask_def word_bw_assocs split: if_split_asm) lemma cap_lift_capEPBadge_mask_eq: "cap_lift cap = Some (Cap_endpoint_cap ec) \<Longrightarrow> capEPBadge_CL ec && mask 28 = capEPBadge_CL ec" unfolding cap_lift_def by (fastforce simp: Let_def mask_def word_bw_assocs split: if_split_asm) lemma Arch_isCapRevocable_spec: "\<forall>s. \<Gamma>\<turnstile> {\<sigma>. s = \<sigma> \<and> True} Call Arch_isCapRevocable_'proc {t. \<forall>c c'. ccap_relation c (derivedCap_' s) \<and> ccap_relation c' (srcCap_' s) \<longrightarrow> ret__unsigned_long_' t = from_bool (Arch.isCapRevocable c c')}" apply vcg by (auto simp: false_def from_bool_def) method revokable'_hammer = solves \<open>(simp add: cap_get_tag_isCap isCap_simps ccorres_cond_iffs from_bool_def true_def false_def, rule ccorres_guard_imp, rule ccorres_return_C; clarsimp)\<close> lemma revokable_ccorres: "ccorres (\<lambda>a c. from_bool a = c) ret__unsigned_long_' (\<lambda>_. capMasterCap cap = capMasterCap parent \<or> is_simple_cap' cap) (UNIV \<inter> {s. ccap_relation cap (derivedCap_' s)} \<inter> {s. ccap_relation parent (srcCap_' s)}) hs (return (revokable' parent cap)) (Call isCapRevocable_'proc)" apply (rule ccorres_gen_asm[where G=\<top>, simplified]) apply (cinit' lift: derivedCap_' srcCap_' simp: revokable'_def) \<comment> \<open>Clear up Arch cap case\<close> apply csymbr apply (clarsimp simp: cap_get_tag_isCap simp del: Collect_const) apply (rule ccorres_Cond_rhs_Seq) apply (rule ccorres_rhs_assoc) apply (clarsimp simp: isCap_simps) apply csymbr apply (drule mp, fastforce) apply ccorres_rewrite apply (rule ccorres_return_C, clarsimp+) apply csymbr apply (rule_tac P'=UNIV and P=\<top> in ccorres_inst) apply (cases cap) \<comment> \<open>Uninteresting caps\<close> apply revokable'_hammer+ \<comment> \<open>NotificationCap\<close> apply (simp add: cap_get_tag_isCap isCap_simps ccorres_cond_iffs from_bool_def true_def false_def) apply (rule ccorres_guard_imp, (rule ccorres_rhs_assoc)+, csymbr, csymbr) apply (rule ccorres_return_C, clarsimp+) apply (frule_tac cap'1=srcCap in cap_get_tag_NotificationCap[THEN iffD1]) apply (clarsimp simp: cap_get_tag_isCap isCap_simps is_simple_cap'_def) apply (frule_tac cap'1=derivedCap in cap_get_tag_NotificationCap[THEN iffD1]) apply (clarsimp simp: cap_get_tag_isCap isCap_simps) apply (fastforce simp: cap_get_tag_isCap isCap_simps) \<comment> \<open>IRQHandlerCap\<close> apply (simp add: cap_get_tag_isCap isCap_simps ccorres_cond_iffs from_bool_def true_def false_def) apply (rule ccorres_guard_imp, csymbr) apply (rule ccorres_return_C, clarsimp+) apply (fastforce simp: cap_get_tag_isCap isCap_simps) \<comment> \<open>EndpointCap\<close> apply (simp add: cap_get_tag_isCap isCap_simps ccorres_cond_iffs from_bool_def true_def false_def) apply (rule ccorres_guard_imp, (rule ccorres_rhs_assoc)+, csymbr, csymbr) apply (rule ccorres_return_C, clarsimp+) apply (frule_tac cap'1=srcCap in cap_get_tag_EndpointCap[THEN iffD1]) apply (clarsimp simp: cap_get_tag_isCap isCap_simps is_simple_cap'_def) apply (frule_tac cap'1=derivedCap in cap_get_tag_EndpointCap[THEN iffD1]) apply (clarsimp simp: cap_get_tag_isCap isCap_simps) apply (fastforce simp: cap_get_tag_isCap isCap_simps) \<comment> \<open>Other Caps\<close> by (revokable'_hammer | fastforce simp: isCap_simps)+ lemma cteInsert_ccorres_mdb_helper: "\<lbrakk>cmdbnode_relation rva srcMDB; from_bool rvc = (newCapIsRevocable :: word32); srcSlot = Ptr src\<rbrakk> \<Longrightarrow> ccorres cmdbnode_relation newMDB_' (K (is_aligned src 3)) UNIV hs (return (mdbFirstBadged_update (\<lambda>_. rvc) (mdbRevocable_update (\<lambda>_. rvc) (mdbPrev_update (\<lambda>_. src) rva)))) (\<acute>newMDB :== CALL mdb_node_set_mdbPrev(srcMDB, ptr_val srcSlot);; \<acute>newMDB :== CALL mdb_node_set_mdbRevocable(\<acute>newMDB, newCapIsRevocable);; \<acute>newMDB :== CALL mdb_node_set_mdbFirstBadged(\<acute>newMDB, newCapIsRevocable))" apply (rule ccorres_from_vcg) apply (rule allI) apply (rule conseqPre) apply vcg apply (clarsimp simp: return_def mask_Suc_0) apply (simp add: cmdbnode_relation_def) done lemma ccorres_updateMDB_set_mdbNext [corres]: "src=src' \<Longrightarrow> ccorres dc xfdc ((\<lambda>_. src \<noteq> 0 \<and> (dest\<noteq>0 \<longrightarrow> is_aligned dest 3))) ({s. mdb_node_ptr_' s = Ptr &((Ptr src' :: cte_C ptr)\<rightarrow>[''cteMDBNode_C''])} \<inter> {s. v32_' s = dest}) [] (updateMDB src (mdbNext_update (\<lambda>_. dest))) (Call mdb_node_ptr_set_mdbNext_'proc)" unfolding updateMDB_def apply (hypsubst) apply (rule ccorres_gen_asm [where G = \<top>, simplified]) apply (simp only: Let_def) apply simp apply (rule ccorres_guard_imp2) apply (rule ccorres_pre_getCTE [where P = "\<lambda>cte s. ctes_of s src' = Some cte" and P' = "\<lambda>_. (\<lbrace>\<acute>mdb_node_ptr = Ptr &((Ptr src' :: cte_C ptr)\<rightarrow>[''cteMDBNode_C''])\<rbrace> \<inter> \<lbrace>\<acute>v32 = dest\<rbrace>)"]) apply (rule ccorres_from_spec_modifies_heap) apply (rule mdb_node_ptr_set_mdbNext_spec) apply (rule mdb_node_ptr_set_mdbNext_modifies) apply simp apply clarsimp apply (rule rf_sr_cte_at_valid) apply simp apply (erule ctes_of_cte_at) apply assumption apply clarsimp apply (frule (1) rf_sr_ctes_of_clift) apply (clarsimp simp: typ_heap_simps) apply (rule fst_setCTE [OF ctes_of_cte_at], assumption) apply (erule bexI [rotated]) apply (clarsimp simp add: rf_sr_def cstate_relation_def Let_def cpspace_relation_def cte_wp_at_ctes_of heap_to_user_data_def cvariable_array_map_const_add_map_option[where f="tcb_no_ctes_proj"] typ_heap_simps') apply (rule conjI) apply (erule (2) cspace_cte_relation_upd_mdbI) apply (simp add: cmdbnode_relation_def) subgoal for _ s' by (cases "v32_' s' = 0"; clarsimp intro: word_gt_0) apply (erule_tac t = s'a in ssubst) apply simp apply (rule conjI) apply (erule (1) setCTE_tcb_case) subgoal by (simp add: carch_state_relation_def cmachine_state_relation_def typ_heap_simps h_t_valid_clift_Some_iff) apply clarsimp done lemma ccorres_updateMDB_set_mdbPrev [corres]: "src=src' \<Longrightarrow> ccorres dc xfdc ((\<lambda>_. src \<noteq> 0 \<and> (dest\<noteq>0 \<longrightarrow>is_aligned dest 3)) ) ({s. mdb_node_ptr_' s = Ptr &((Ptr src' :: cte_C ptr)\<rightarrow>[''cteMDBNode_C''])} \<inter> {s. v32_' s = dest}) [] (updateMDB src (mdbPrev_update (\<lambda>_. dest))) (Call mdb_node_ptr_set_mdbPrev_'proc)" unfolding updateMDB_def apply (hypsubst) apply (rule ccorres_gen_asm [where G = \<top>, simplified]) apply (simp only: Let_def) apply simp apply (rule ccorres_guard_imp2) apply (rule ccorres_pre_getCTE [where P = "\<lambda>cte s. ctes_of s src' = Some cte" and P' = "\<lambda>_. (\<lbrace>\<acute>mdb_node_ptr = Ptr &((Ptr src' :: cte_C ptr)\<rightarrow>[''cteMDBNode_C''])\<rbrace> \<inter> \<lbrace>\<acute>v32 = dest\<rbrace>)"]) apply (rule ccorres_from_spec_modifies_heap) apply (rule mdb_node_ptr_set_mdbPrev_spec) apply (rule mdb_node_ptr_set_mdbPrev_modifies) apply simp apply clarsimp apply (rule rf_sr_cte_at_valid) apply simp apply (erule ctes_of_cte_at) apply assumption apply (clarsimp simp: cte_wp_at_ctes_of) apply (frule (1) rf_sr_ctes_of_clift) apply (clarsimp simp: typ_heap_simps) apply (rule fst_setCTE [OF ctes_of_cte_at], assumption) apply (erule bexI [rotated]) apply (clarsimp simp add: rf_sr_def cstate_relation_def Let_def cpspace_relation_def cte_wp_at_ctes_of heap_to_user_data_def cvariable_array_map_const_add_map_option[where f="tcb_no_ctes_proj"] typ_heap_simps') apply (rule conjI) apply (erule (2) cspace_cte_relation_upd_mdbI) apply (simp add: cmdbnode_relation_def) subgoal for _ s' by (cases "v32_' s' = 0"; clarsimp intro: word_gt_0) apply (erule_tac t = s'a in ssubst) apply (simp add: carch_state_relation_def cmachine_state_relation_def h_t_valid_clift_Some_iff typ_heap_simps') apply (erule (1) setCTE_tcb_case) apply clarsimp done lemma ccorres_updateMDB_skip: "ccorres dc xfdc (\<top> and (\<lambda>_. n = 0)) UNIV hs (updateMDB n f) SKIP" unfolding updateMDB_def apply (rule ccorres_gen_asm) apply simp apply (rule ccorres_return) apply simp apply vcg done definition "is_simple_cap_tag (tag :: word32) \<equiv> tag \<noteq> scast cap_null_cap \<and> tag \<noteq> scast cap_irq_control_cap \<and> tag \<noteq> scast cap_untyped_cap \<and> tag \<noteq> scast cap_reply_cap \<and> tag \<noteq> scast cap_endpoint_cap \<and> tag \<noteq> scast cap_notification_cap \<and> tag \<noteq> scast cap_thread_cap \<and> tag \<noteq> scast cap_cnode_cap \<and> tag \<noteq> scast cap_zombie_cap \<and> tag \<noteq> scast cap_small_frame_cap \<and> tag \<noteq> scast cap_frame_cap" definition "cteInsert_newCapIsRevocable_if newCap srcCap \<equiv> (if (cap_get_tag newCap = scast cap_endpoint_cap) then (if (capEPBadge_CL (cap_endpoint_cap_lift newCap) = capEPBadge_CL (cap_endpoint_cap_lift srcCap)) then 0 else 1) else if (cap_get_tag newCap = scast cap_notification_cap) then (if (capNtfnBadge_CL (cap_notification_cap_lift newCap) = capNtfnBadge_CL (cap_notification_cap_lift srcCap)) then 0 else 1) else if (cap_get_tag newCap = scast cap_irq_handler_cap) then (if cap_get_tag srcCap = scast cap_irq_control_cap then 1 else 0) else if (cap_get_tag newCap = scast cap_untyped_cap) then 1 else 0)" lemma cteInsert_if_helper: assumes cgt: "rv = cap_get_tag newCap" and rul: "\<And>s g. (s \<in> Q) = (s\<lparr> ret__unsigned_' := undefined, unsigned_eret_2_':= undefined \<rparr> \<in> Q')" shows "\<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> {s. (cap_get_tag srcCap = cap_get_tag newCap \<or> is_simple_cap_tag (cap_get_tag newCap)) \<and> (s\<lparr>newCapIsRevocable_' := cteInsert_newCapIsRevocable_if newCap srcCap\<rparr> \<in> Q)} (IF rv = scast cap_endpoint_cap THEN \<acute>ret__unsigned :== CALL cap_endpoint_cap_get_capEPBadge(newCap);; \<acute>unsigned_eret_2 :== CALL cap_endpoint_cap_get_capEPBadge(srcCap);; \<acute>newCapIsRevocable :== (if \<acute>ret__unsigned \<noteq> \<acute>unsigned_eret_2 then 1 else 0) ELSE IF rv = scast cap_notification_cap THEN \<acute>ret__unsigned :== CALL cap_notification_cap_get_capNtfnBadge(newCap);; \<acute>unsigned_eret_2 :== CALL cap_notification_cap_get_capNtfnBadge(srcCap);; \<acute>newCapIsRevocable :== (if \<acute>ret__unsigned \<noteq> \<acute>unsigned_eret_2 then 1 else 0) ELSE IF rv = scast cap_irq_handler_cap THEN \<acute>ret__unsigned :== CALL cap_get_capType(srcCap);; \<acute>newCapIsRevocable :== (if \<acute>ret__unsigned = scast cap_irq_control_cap then 1 else 0) ELSE IF rv = scast cap_untyped_cap THEN \<acute>newCapIsRevocable :== scast true ELSE \<acute>newCapIsRevocable :== scast false FI FI FI FI) Q" unfolding cteInsert_newCapIsRevocable_if_def apply (unfold cgt) apply (rule conseqPre) apply vcg apply (clarsimp simp: true_def false_def is_simple_cap_tag_def cong: if_cong) apply (simp add: cap_tag_defs) apply (intro allI conjI impI) apply (clarsimp simp: rul)+ done lemma forget_Q': "(x \<in> Q) = (y \<in> Q) \<Longrightarrow> (x \<in> Q) = (y \<in> Q)" . lemmas cteInsert_if_helper' = cteInsert_if_helper [OF _ forget_Q'] (* Useful: apply (tactic {* let val _ = reset CtacImpl.trace_ceqv; val _ = reset CtacImpl.trace_ctac in all_tac end; *}) *) declare word_neq_0_conv [simp del] schematic_goal ccap_relation_tag_Master: "\<And>ccap. \<lbrakk> ccap_relation cap ccap \<rbrakk> \<Longrightarrow> cap_get_tag ccap = case_capability ?a ?b ?c ?d ?e ?f ?g (case_arch_capability ?aa ?ab (\<lambda>dev ptr rghts sz data. if sz = ARMSmallPage then scast cap_small_frame_cap else scast cap_frame_cap) ?ad ?ae ?af) ?h ?i ?j ?k (capMasterCap cap)" by (fastforce simp: ccap_relation_def map_option_Some_eq2 Let_def cap_lift_def cap_to_H_def split: if_split_asm) lemma ccap_relation_is_derived_tag_equal: "\<lbrakk> is_derived' cs p cap cap'; ccap_relation cap ccap; ccap_relation cap' ccap' \<rbrakk> \<Longrightarrow> cap_get_tag ccap' = cap_get_tag ccap" unfolding badge_derived'_def is_derived'_def by (clarsimp simp: ccap_relation_tag_Master) lemma ccap_relation_Master_tags_eq: "\<lbrakk> capMasterCap cap = capMasterCap cap'; ccap_relation cap ccap; ccap_relation cap' ccap' \<rbrakk> \<Longrightarrow> cap_get_tag ccap' = cap_get_tag ccap" by (clarsimp simp: ccap_relation_tag_Master) lemma is_simple_cap_get_tag_relation: "ccap_relation cap ccap \<Longrightarrow> is_simple_cap_tag (cap_get_tag ccap) = is_simple_cap' cap" apply (simp add: is_simple_cap_tag_def is_simple_cap'_def cap_get_tag_isCap) apply (auto simp: isCap_simps) done lemma setUntypedCapAsFull_cte_at_wp [wp]: "\<lbrace> cte_at' x \<rbrace> setUntypedCapAsFull rvb cap src \<lbrace> \<lambda>_. cte_at' x \<rbrace>" apply (clarsimp simp: setUntypedCapAsFull_def) apply wp done lemma valid_cap_untyped_inv: "valid_cap' (UntypedCap d r n f) s \<Longrightarrow> n \<ge> minUntypedSizeBits \<and> is_aligned (of_nat f :: word32) minUntypedSizeBits \<and> n \<le> maxUntypedSizeBits \<and> n < word_bits" apply (clarsimp simp:valid_cap'_def capAligned_def) done lemma update_freeIndex': assumes i'_align: "is_aligned (of_nat i' :: machine_word) minUntypedSizeBits" assumes sz_bound: "sz \<le> maxUntypedSizeBits" assumes i'_bound: "i' \<le> 2 ^ sz" shows "ccorres dc xfdc (cte_wp_at' (\<lambda>cte. \<exists>i. cteCap cte = UntypedCap d p sz i) srcSlot) (UNIV \<inter> \<lbrace>\<acute>cap_ptr = cap_Ptr &(cte_Ptr srcSlot\<rightarrow>[''cap_C''])\<rbrace> \<inter> \<lbrace>\<acute>v32 = of_nat i' >> minUntypedSizeBits\<rbrace>) [] (updateCap srcSlot (UntypedCap d p sz i')) (Call cap_untyped_cap_ptr_set_capFreeIndex_'proc)" proof - note i'_bound_concrete = order_trans[OF i'_bound power_increasing[OF sz_bound], simplified untypedBits_defs, simplified] have i'_bound_word: "(of_nat i' :: machine_word) \<le> 2 ^ maxUntypedSizeBits" using order_trans[OF i'_bound power_increasing[OF sz_bound], simplified] by (simp add: word_of_nat_le untypedBits_defs) note option.case_cong[cong] if_cong[cong] show ?thesis apply (cinit lift: cap_ptr_' v32_') apply (rule ccorres_pre_getCTE) apply (rule_tac P="\<lambda>s. ctes_of s srcSlot = Some rv \<and> (\<exists>i. cteCap rv = UntypedCap d p sz i)" in ccorres_from_vcg[where P' = UNIV]) apply (rule allI) apply (rule conseqPre) apply vcg apply (clarsimp simp: guard_simps) apply (intro conjI) apply (frule (1) rf_sr_ctes_of_clift) apply (clarsimp simp: typ_heap_simps) apply (frule (1) rf_sr_ctes_of_clift) apply (clarsimp simp: split_def) apply (simp add: hrs_htd_def typ_heap_simps) apply (rule fst_setCTE[OF ctes_of_cte_at], assumption) apply (erule bexI[rotated], clarsimp) apply (frule (1) rf_sr_ctes_of_clift) apply (clarsimp simp: rf_sr_def cstate_relation_def Let_def cvariable_array_map_const_add_map_option[where f="tcb_no_ctes_proj"]) apply (simp add: cpspace_relation_def) apply (clarsimp simp: typ_heap_simps') apply (rule conjI) apply (erule (2) cpspace_cte_relation_upd_capI) apply (simp only: cte_lift_def split: option.splits; simp) apply (simp add: cap_to_H_def Let_def split: cap_CL.splits if_split_asm) apply (case_tac y) apply (simp add: cap_lift_def Let_def split: if_split_asm) apply (case_tac cte', simp) apply (clarsimp simp: ccap_relation_def cap_lift_def cap_get_tag_def cap_to_H_def) apply (thin_tac _)+ apply (simp add: mask_def to_bool_and_1 nth_shiftr word_ao_dist and.assoc) apply (rule inj_onD[OF word_unat.Abs_inj_on[where 'a=machine_word_len]], simp) apply (cut_tac i'_align i'_bound_word) apply (simp add: is_aligned_mask) apply word_bitwise subgoal by (simp add: word_size untypedBits_defs mask_def) apply (cut_tac i'_bound_concrete) subgoal by (simp add: unats_def) subgoal by (simp add: word_unat.Rep[where 'a=machine_word_len, simplified]) apply (erule_tac t = s' in ssubst) apply clarsimp apply (rule conjI) subgoal by (erule (1) setCTE_tcb_case) subgoal by (simp add: carch_state_relation_def cmachine_state_relation_def typ_heap_simps') by (clarsimp simp:cte_wp_at_ctes_of) qed lemma update_freeIndex: "ccorres dc xfdc (valid_objs' and cte_wp_at' (\<lambda>cte. \<exists>i. cteCap cte = UntypedCap d p sz i) srcSlot and (\<lambda>_. is_aligned (of_nat i' :: word32) minUntypedSizeBits \<and> i' \<le> 2 ^ sz)) (UNIV \<inter> \<lbrace>\<acute>cap_ptr = cap_Ptr &(cte_Ptr srcSlot\<rightarrow>[''cap_C''])\<rbrace> \<inter> \<lbrace>\<acute>v32 = of_nat i' >> minUntypedSizeBits\<rbrace>) [] (updateCap srcSlot (UntypedCap d p sz i')) (Call cap_untyped_cap_ptr_set_capFreeIndex_'proc)" apply (rule ccorres_assume_pre, rule ccorres_guard_imp) apply (rule update_freeIndex'; clarsimp simp: cte_wp_at_ctes_of) apply (case_tac cte; clarsimp dest!: ctes_of_valid_cap' simp: valid_cap'_def) by auto (* FIXME: move *) lemma ccorres_cases: assumes P: " P \<Longrightarrow> ccorres r xf G G' hs a b" assumes notP: "\<not>P \<Longrightarrow> ccorres r xf H H' hs a b" shows "ccorres r xf (\<lambda>s. (P \<longrightarrow> G s) \<and> (\<not>P \<longrightarrow> H s)) ({s. P \<longrightarrow> s \<in> G'} \<inter> {s. \<not>P \<longrightarrow> s \<in> H'}) hs a b" apply (cases P, auto simp: P notP) done lemma capBlockSize_CL_maxSize: " \<lbrakk> cap_get_tag c = scast cap_untyped_cap \<rbrakk> \<Longrightarrow> capBlockSize_CL (cap_untyped_cap_lift c) < 0x20" apply (clarsimp simp: cap_untyped_cap_lift_def) apply (clarsimp simp: cap_lift_def) apply (clarsimp simp: cap_untyped_cap_def cap_null_cap_def) apply (rule word_and_less') apply (simp add: mask_def) done lemma setUntypedCapAsFull_ccorres [corres]: notes if_split [split del] notes Collect_const [simp del] notes Collect_True [simp] Collect_False [simp] shows "ccorres dc xfdc ((cte_wp_at' (\<lambda>c. (cteCap c) = srcCap) srcSlot) and valid_mdb' and pspace_aligned' and valid_objs' and (K (isUntypedCap newCap \<longrightarrow> (minUntypedSizeBits \<le> (capBlockSize newCap)))) and (K (isUntypedCap srcCap \<longrightarrow> (minUntypedSizeBits \<le> capBlockSize srcCap)))) (UNIV \<inter> {s. ccap_relation srcCap (srcCap_' s)} \<inter> {s. ccap_relation newCap (newCap_' s)} \<inter> {s. srcSlot_' s = Ptr srcSlot}) [] (setUntypedCapAsFull srcCap newCap srcSlot) (Call setUntypedCapAsFull_'proc)" apply (cinit lift: srcCap_' newCap_' srcSlot_') apply (rule ccorres_if_lhs) apply (clarsimp simp: isCap_simps) apply csymbr apply csymbr apply (simp add: if_then_0_else_1 if_then_1_else_0 cap_get_tag_isCap_unfolded_H_cap) apply (rule ccorres_rhs_assoc)+ apply csymbr apply csymbr apply (simp add: cap_get_tag_isCap_unfolded_H_cap ccorres_cond_univ_iff) apply (rule ccorres_rhs_assoc)+ apply csymbr apply csymbr apply csymbr apply (frule cap_get_tag_to_H(9)) apply (simp add: cap_get_tag_isCap_unfolded_H_cap) apply (rotate_tac 1) apply (frule cap_get_tag_to_H(9)) apply (simp add: cap_get_tag_isCap_unfolded_H_cap) apply simp apply (rule ccorres_rhs_assoc)+ apply csymbr apply csymbr apply csymbr apply (simp add: ccorres_cond_univ_iff) apply csymbr+ apply (rule ccorres_move_c_guard_cte) apply (rule ccorres_Guard) apply (rule ccorres_call) apply (rule update_freeIndex [unfolded dc_def]) apply simp apply simp apply simp apply clarsimp apply (csymbr) apply (csymbr) apply (simp add: cap_get_tag_isCap) apply (rule ccorres_Cond_rhs_Seq) apply (rule ccorres_rhs_assoc)+ apply csymbr apply csymbr apply (simp add: cap_get_tag_isCap) apply (rule ccorres_Cond_rhs) apply (rule ccorres_rhs_assoc)+ apply csymbr apply csymbr apply csymbr apply (rule ccorres_cases [where P="capPtr srcCap = capPtr newCap"]) apply (clarsimp simp: cap_get_tag_isCap[symmetric] cap_get_tag_UntypedCap split: if_split_asm) apply (rule ccorres_rhs_assoc)+ apply csymbr apply csymbr apply csymbr apply (clarsimp simp: cap_get_tag_to_H cap_get_tag_UntypedCap split: if_split_asm) apply (rule ccorres_cond_false) apply (rule ccorres_return_Skip [unfolded dc_def]) apply (clarsimp simp: cap_get_tag_isCap[symmetric] cap_get_tag_UntypedCap split: if_split_asm) apply (rule ccorres_cond_false) apply (rule ccorres_return_Skip [unfolded dc_def]) apply (rule ccorres_return_Skip [unfolded dc_def]) apply clarsimp apply (rule ccorres_cond_false) apply (rule ccorres_return_Skip [unfolded dc_def]) apply (clarsimp simp: cap_get_tag_isCap[symmetric] cap_get_tag_UntypedCap) apply (frule(1) cte_wp_at_valid_objs_valid_cap') apply (clarsimp simp: untypedBits_defs) apply (intro conjI impI allI) apply (erule cte_wp_at_weakenE') apply (clarsimp simp: cap_get_tag_isCap[symmetric] cap_get_tag_UntypedCap split: if_split_asm) apply clarsimp apply (drule valid_cap_untyped_inv,clarsimp simp:max_free_index_def) apply (rule is_aligned_weaken) apply (rule is_aligned_shiftl_self[unfolded shiftl_t2n,where p = 1,simplified]) apply assumption apply (clarsimp simp: max_free_index_def shiftL_nat valid_cap'_def capAligned_def) apply (simp add:power_minus_is_div unat_sub word_le_nat_alt t2p_shiftr_32) apply clarsimp apply (erule cte_wp_at_weakenE', simp) apply clarsimp apply (drule valid_cap_untyped_inv) apply (clarsimp simp:max_free_index_def t2p_shiftr_32 unat_sub word_le_nat_alt) apply (clarsimp simp:field_simps) apply (rule word_less_imp_diff_less) apply (subst (asm) eq_commute, fastforce simp: unat_sub word_le_nat_alt) apply (rule capBlockSize_CL_maxSize) apply (clarsimp simp: cap_get_tag_UntypedCap) apply (clarsimp simp: cap_get_tag_isCap_unfolded_H_cap) done lemma ccte_lift: "\<lbrakk>(s, s') \<in> rf_sr; cslift s' (cte_Ptr p) = Some cte'; cte_lift cte' = Some y; c_valid_cte cte'\<rbrakk> \<Longrightarrow> ctes_of s p = Some (cte_to_H (the (cte_lift cte')))" apply (clarsimp simp:rf_sr_def cstate_relation_def Let_def cpspace_relation_def) apply (drule(1) cmap_relation_cs_atD) apply simp apply (clarsimp simp:ccte_relation_def) done lemma cmdb_node_relation_mdbNext: "cmdbnode_relation n n' \<Longrightarrow> mdbNext_CL (mdb_node_lift n') = mdbNext n" by (simp add:cmdbnode_relation_def) lemma cslift_ptr_safe: "cslift x ptr = Some a \<Longrightarrow> ptr_safe ptr (hrs_htd (t_hrs_' (globals x)))" apply (rule_tac h = "fst (t_hrs_' (globals x))" in lift_t_ptr_safe[where g = c_guard]) apply (fastforce simp add:typ_heap_simps hrs_htd_def) done lemma ccorres_move_ptr_safe: "ccorres_underlying rf_sr \<Gamma> r xf arrel axf A C' hs a c \<Longrightarrow> ccorres_underlying rf_sr \<Gamma> r xf arrel axf (A and K (dest = cte_Ptr (ptr_val dest)) and cte_wp_at' (\<lambda>_. True) (ptr_val dest)) (C' \<inter> \<lbrace>True\<rbrace>) hs a (Guard MemorySafety \<lbrace>ptr_safe (dest) (hrs_htd \<acute>t_hrs) \<rbrace> c)" apply (rule ccorres_guard_imp2) apply (rule ccorres_Guard) apply simp apply (clarsimp simp:cte_wp_at_ctes_of) apply (drule(1) rf_sr_ctes_of_clift) apply (case_tac dest) apply (clarsimp simp:ptr_coerce_def) apply (erule cslift_ptr_safe) done lemma ccorres_move_ptr_safe_Seq: "ccorres_underlying rf_sr \<Gamma> r xf arrel axf A C' hs a (c;;d) \<Longrightarrow> ccorres_underlying rf_sr \<Gamma> r xf arrel axf (A and cte_wp_at' (\<lambda>_. True) (ptr_val dest) and K (dest = cte_Ptr (ptr_val dest))) (C' \<inter> \<lbrace>True\<rbrace>) hs a (Guard MemorySafety \<lbrace>ptr_safe (dest) (hrs_htd \<acute>t_hrs) \<rbrace> c;;d)" apply (rule ccorres_guard_imp2) apply (rule ccorres_Guard_Seq) apply simp apply (clarsimp simp:cte_wp_at_ctes_of) apply (drule(1) rf_sr_ctes_of_clift) apply clarsimp apply (erule cslift_ptr_safe) done lemmas ccorres_move_guard_ptr_safe = ccorres_move_ptr_safe_Seq ccorres_move_ptr_safe lemma cteInsert_ccorres: "ccorres dc xfdc (cte_wp_at' (\<lambda>scte. capMasterCap (cteCap scte) = capMasterCap cap \<or> is_simple_cap' cap) src and valid_mdb' and valid_objs' and pspace_aligned' and (valid_cap' cap) and (\<lambda>s. cte_wp_at' (\<lambda>c. True) src s)) (UNIV \<inter> {s. destSlot_' s = Ptr dest} \<inter> {s. srcSlot_' s = Ptr src} \<inter> {s. ccap_relation cap (newCap_' s)} \<inter> {s. destSlot_' s = Ptr dest} \<inter> {s. srcSlot_' s = Ptr src} \<inter> {s. ccap_relation cap (newCap_' s)}) [] (cteInsert cap src dest) (Call cteInsert_'proc)" apply (cinit (no_ignore_call) lift: destSlot_' srcSlot_' newCap_' simp del: return_bind simp add: Collect_const) apply (rule ccorres_move_c_guard_cte) apply (ctac pre: ccorres_pre_getCTE) apply (rule ccorres_move_c_guard_cte) apply (ctac pre: ccorres_pre_getCTE) apply (ctac(no_vcg) add: revokable_ccorres) apply (ctac (c_lines 3) add: cteInsert_ccorres_mdb_helper) apply (simp del: Collect_const) apply (rule ccorres_pre_getCTE ccorres_assert)+ apply (ctac add: setUntypedCapAsFull_ccorres) apply (rule ccorres_move_c_guard_cte) apply (ctac) apply (rule ccorres_move_c_guard_cte) apply ctac apply (rule ccorres_move_c_guard_cte) apply (ctac(no_vcg)) apply csymbr apply (erule_tac t = ret__unsigned in ssubst) apply (rule ccorres_cond_both [where R = \<top>, simplified]) apply (erule mdbNext_not_zero_eq) apply csymbr apply simp apply (rule ccorres_move_c_guard_cte) apply (simp add:dc_def[symmetric]) apply (ctac ccorres:ccorres_updateMDB_set_mdbPrev) apply (simp add:dc_def[symmetric]) apply (ctac ccorres: ccorres_updateMDB_skip) apply (wp static_imp_wp)+ apply (clarsimp simp: Collect_const_mem dc_def split del: if_split) apply vcg apply (wp static_imp_wp) apply (clarsimp simp: Collect_const_mem dc_def split del: if_split) apply vcg apply (clarsimp simp:cmdb_node_relation_mdbNext) apply (wp setUntypedCapAsFull_cte_at_wp static_imp_wp) apply (clarsimp simp: Collect_const_mem dc_def split del: if_split) apply (vcg exspec=setUntypedCapAsFull_modifies) apply wp apply vcg apply wp apply wp apply vcg apply wp apply vcg apply (simp add: Collect_const_mem split del: if_split) \<comment> \<open>Takes a while\<close> apply (rule conjI) apply (clarsimp simp: conj_comms cte_wp_at_ctes_of) apply (intro conjI) apply clarsimp apply simp apply simp apply clarsimp apply (rule conjI) apply (clarsimp simp: isUntypedCap_def split: capability.split_asm) apply (frule valid_cap_untyped_inv) apply clarsimp apply (rule conjI) apply (case_tac ctea) apply (clarsimp simp: isUntypedCap_def split: capability.splits) apply (frule valid_cap_untyped_inv[OF ctes_of_valid_cap']) apply fastforce apply clarsimp+ apply (drule valid_dlist_nextD) apply (simp add:valid_mdb'_def valid_mdb_ctes_def) apply simp apply clarsimp apply (clarsimp simp: map_comp_Some_iff cte_wp_at_ctes_of split del: if_split) apply (clarsimp simp: typ_heap_simps c_guard_clift split_def) apply (clarsimp simp: is_simple_cap_get_tag_relation ccte_relation_ccap_relation cmdb_node_relation_mdbNext[symmetric]) done (****************************************************************************) (* *) (* Lemmas dealing with updateMDB on Haskell side and IF-THEN-ELSE on C side *) (* *) (****************************************************************************) lemma updateMDB_mdbNext_set_mdbPrev: "\<lbrakk> slotc = Ptr slota; cmdbnode_relation mdba mdbc\<rbrakk> \<Longrightarrow> ccorres dc xfdc ( \<lambda>s. is_aligned (mdbNext mdba) 3 \<and> (slota\<noteq>0\<longrightarrow>is_aligned slota 3)) UNIV hs (updateMDB (mdbNext mdba) (mdbPrev_update (\<lambda>_. slota))) (IF mdbNext_CL (mdb_node_lift mdbc) \<noteq> 0 THEN Guard C_Guard \<lbrace>hrs_htd \<acute>t_hrs \<Turnstile>\<^sub>t (Ptr (mdbNext_CL (mdb_node_lift mdbc)) :: cte_C ptr)\<rbrace> (call (\<lambda>ta. ta(| mdb_node_ptr_' := Ptr &(Ptr (mdbNext_CL (mdb_node_lift mdbc)):: cte_C ptr \<rightarrow>[''cteMDBNode_C'']), v32_' := ptr_val slotc |)) mdb_node_ptr_set_mdbPrev_'proc (\<lambda>s t. s\<lparr> globals := globals t \<rparr>) (\<lambda>ta s'. Basic (\<lambda>a. a))) FI)" apply (rule ccorres_guard_imp2) \<comment> \<open>replace preconditions by schematics\<close> \<comment> \<open>Main Goal\<close> apply (rule ccorres_cond_both [where R="\<lambda>_.True", simplified]) \<comment> \<open>generates 3 subgoals (one for 'then', one for 'else')\<close> \<comment> \<open>***instanciate the condition***\<close> apply (rule mdbNext_not_zero_eq) apply assumption \<comment> \<open>***cond True: ptr \<noteq> 0***\<close> apply (rule ccorres_updateMDB_cte_at) apply (ctac add: ccorres_updateMDB_set_mdbPrev) apply (ctac ccorres: ccorres_updateMDB_skip) \<comment> \<open>instanciate generalized preconditions\<close> apply (case_tac "mdbNext_CL (mdb_node_lift mdbc)=0") \<comment> \<open>Next is zero\<close> apply (clarsimp simp: cmdbnode_relation_def) \<comment> \<open>Next is not zero\<close> apply (clarsimp simp: cmdbnode_relation_def cte_wp_at_ctes_of) done lemma updateMDB_mdbPrev_set_mdbNext: "\<lbrakk> slotc = Ptr slota; cmdbnode_relation mdba mdbc\<rbrakk> \<Longrightarrow> ccorres dc xfdc ( \<lambda>s. (is_aligned (mdbPrev mdba) 3 \<and> (slota\<noteq>0\<longrightarrow>is_aligned slota 3))) UNIV hs (updateMDB (mdbPrev mdba) (mdbNext_update (\<lambda>_. slota))) (IF mdbPrev_CL (mdb_node_lift mdbc) \<noteq> 0 THEN Guard C_Guard \<lbrace>hrs_htd \<acute>t_hrs \<Turnstile>\<^sub>t (Ptr (mdbPrev_CL (mdb_node_lift mdbc)):: cte_C ptr)\<rbrace> (call (\<lambda>ta. ta(| mdb_node_ptr_' := Ptr &(Ptr (mdbPrev_CL (mdb_node_lift mdbc)):: cte_C ptr \<rightarrow>[''cteMDBNode_C'']), v32_' := ptr_val slotc |)) mdb_node_ptr_set_mdbNext_'proc (\<lambda>s t. s\<lparr> globals := globals t \<rparr>) (\<lambda>ta s'. Basic (\<lambda>a. a))) FI)" apply (rule ccorres_guard_imp2) \<comment> \<open>replace preconditions by schematics\<close> \<comment> \<open>Main Goal\<close> apply (rule ccorres_cond_both[where R="\<lambda>_.True", simplified]) \<comment> \<open>generates 3 subgoals (one for 'then', one for 'else')\<close> \<comment> \<open>***instanciate the condition***\<close> apply (rule mdbPrev_not_zero_eq) apply assumption \<comment> \<open>***cond True: ptr \<noteq> 0***\<close> apply (rule ccorres_updateMDB_cte_at) apply (ctac add: ccorres_updateMDB_set_mdbNext) \<comment> \<open>-- ccorres_call generates 4 subgoals, the 3 last being solved by simp\<close> \<comment> \<open>***cond False: ptr = 0***\<close> apply (ctac ccorres: ccorres_updateMDB_skip) \<comment> \<open>instanciate generalized preconditions\<close> apply (case_tac "mdbPrev_CL (mdb_node_lift mdbc)=0") \<comment> \<open>Next is zero\<close> apply (clarsimp simp: cmdbnode_relation_def) \<comment> \<open>Next is not zero\<close> apply (clarsimp simp: cte_wp_at_ctes_of cmdbnode_relation_def) done (************************************************************************) (* *) (* cteMove_ccorres ******************************************************) (* *) (************************************************************************) lemma is_aligned_3_prev: "\<lbrakk> valid_mdb' s; pspace_aligned' s; ctes_of s p = Some cte \<rbrakk> \<Longrightarrow> is_aligned (mdbPrev (cteMDBNode cte)) 3" apply (cases "mdbPrev (cteMDBNode cte) = 0", simp) apply (drule (2) valid_mdb_ctes_of_prev) apply (clarsimp simp: cte_wp_at_ctes_of) done lemma is_aligned_3_next: "\<lbrakk> valid_mdb' s; pspace_aligned' s; ctes_of s p = Some cte \<rbrakk> \<Longrightarrow> is_aligned (mdbNext (cteMDBNode cte)) 3" apply (cases "mdbNext (cteMDBNode cte) = 0", simp) apply (drule (2) valid_mdb_ctes_of_next) apply (clarsimp simp: cte_wp_at_ctes_of) done lemma cteMove_ccorres: "ccorres dc xfdc (valid_mdb' and pspace_aligned' ) (UNIV \<inter> {s. destSlot_' s = Ptr dest} \<inter> {s. srcSlot_' s = Ptr src} \<inter> {s. ccap_relation cap (newCap_' s)}) [] (cteMove cap src dest) (Call cteMove_'proc)" apply (cinit (no_ignore_call) lift: destSlot_' srcSlot_' newCap_' simp del: return_bind) apply (ctac pre: ccorres_pre_getCTE ccorres_assert iffD2 [OF ccorres_seq_skip]) apply (ctac+, csymbr+)+ apply (erule_tac t = ret__unsigned in ssubst) apply (ctac add: updateMDB_mdbPrev_set_mdbNext) apply csymbr apply csymbr apply (erule_tac t = ret__unsigned in ssubst) apply (rule updateMDB_mdbNext_set_mdbPrev) apply simp apply simp apply (wp, vcg)+ apply (rule conjI) apply (clarsimp simp: cte_wp_at_ctes_of) apply (intro conjI, simp+) apply (erule (2) is_aligned_3_prev) apply (erule (2) is_aligned_3_next) apply (clarsimp simp: dc_def split del: if_split) apply (simp add: ccap_relation_NullCap_iff) apply (clarsimp simp add: cmdbnode_relation_def mdb_node_to_H_def nullMDBNode_def false_def to_bool_def) done lemma cteMove_ccorres_verbose: "ccorres dc xfdc (valid_mdb' and pspace_aligned' ) (UNIV \<inter> {s. destSlot_' s = Ptr dest} \<inter> {s. srcSlot_' s = Ptr src} \<inter> {s. ccap_relation cap (newCap_' s)}) [] (cteMove cap src dest) (Call cteMove_'proc)" apply (cinit (no_ignore_call) lift: destSlot_' srcSlot_' newCap_' simp del: return_bind) (* previous line replaces all the following: unfolding cteMove_def -- "unfolds Haskell side" apply (rule ccorres_Call) -- "unfolds C side" apply (rule cteMove_impl [unfolded cteMove_body_def]) -- "retrieves the C body definition" apply (rule ccorres_rhs_assoc)+ -- "re-associates C sequences to the right: i0;(the rest)" apply (simp del: return_bind Int_UNIV_left) -- "gets rid of SKIP and print all haskells instruction as y \<leftarrow> \<dots>" apply (cinitlift destSlot_' srcSlot_' newCap_') apply (rule ccorres_guard_imp2) -- "replaces the preconditions by schematics (to be instanciated along the proof)" -- " \<Rightarrow> creates 2 subgoals (1 for main proof and 1 for ''conjunction of " -- " preconditions implies conjunction of generalized (schematics) guards'')" -- "Start proofs" apply csymbr -- "Remove undefined" apply csymbr apply csymbr *) \<comment> \<open>***Main goal***\<close> \<comment> \<open>--- instruction: oldCTE \<leftarrow> getCTE dest; ---\<close> \<comment> \<open>--- y \<leftarrow> assert (cteCap oldCTE = capability.NullCap); ---\<close> \<comment> \<open>--- y \<leftarrow> assert (mdbPrev (cteMDBNode oldCTE) = nullPointer \<and> mdbNext (...)); ---\<close> apply (ctac pre: ccorres_pre_getCTE ccorres_assert iffD2 [OF ccorres_seq_skip]) \<comment> \<open>ccorres_Guard_Seq puts the C guards into the precondition\<close> \<comment> \<open>ccorres_getCTE applies the corres proof for getCTE\<close> \<comment> \<open>ccorres_assert add the asserted proposition to the precondition\<close> \<comment> \<open>iffD2 [\<dots>] removes the SKIPS\<close> \<comment> \<open>implicit symbolic execution of return\<close> \<comment> \<open>\<Rightarrow> 2 new subgoals for return (in addition to Main Goal)\<close> \<comment> \<open>1. pre/post for Haskell side of return\<close> \<comment> \<open>2. pre/post for C side of return\<close> \<comment> \<open>(rq: ccorress_getCTE eta expands everything... )\<close> \<comment> \<open>***Main Goal of return***\<close> \<comment> \<open>--- instruction: y \<leftarrow> updateCap dest cap ---\<close> apply ctac \<comment> \<open>implicit symbolic execution \<Rightarrow> 2 new subgoals for 1st updateCap\<close> \<comment> \<open>***Main Goal***\<close> \<comment> \<open>--- instruction: y \<leftarrow> updateCap src capability.NullCap; (but with CALL on C side)\<close> apply csymbr \<comment> \<open>symb exec of C instruction CALL to create Null Cap\<close> \<comment> \<open>--- instruction: y \<leftarrow> updateCap src capability.NullCap; (no CALL on C side)\<close> apply ctac \<comment> \<open>implicit symbolic execution \<Rightarrow> 2 new subgoals for 2st updateCap\<close> \<comment> \<open>***Main Goal***\<close> \<comment> \<open>--- instruction: y \<leftarrow> updateMDB dest (const rv); ---\<close> \<comment> \<open>if not ctac won't work, because of the eta-expansion\<dots>\<close> apply ctac \<comment> \<open>implicit symbolic execution \<Rightarrow> 2 new subgoals for 1st updateMDB\<close> \<comment> \<open>***Main Goal***\<close> \<comment> \<open>--- instruction: y \<leftarrow> updateMDB dest (const nullMDBNode); (but with CALL on C side) ---\<close> apply csymbr \<comment> \<open>symb exec of C instruction CALL to create Null MDB\<close> \<comment> \<open>--- instruction: y \<leftarrow> updateMDB dest (const nullMDBNode); (no CALL on C side) ---\<close> apply ctac \<comment> \<open>implicit symbolic execution \<Rightarrow> 2 new subgoals for 2nd updateMDB\<close> \<comment> \<open>***Main Goal***\<close> \<comment> \<open>--- instruction: y <- updateMDB (mdbPrev rv) (mdbNext_update (%_. dest); (but with CALL on C side) ---\<close> apply csymbr \<comment> \<open>symb exec of C instruction CALL to mdbPrev\<close> \<comment> \<open>--- instruction: y <- updateMDB (mdbPrev rv) (mdbNext_update (%_. dest); (no CALL on C side) ---\<close> \<comment> \<open>--- (IF instruction in the C side) ---\<close> apply (erule_tac t = ret__unsigned in ssubst) apply csymbr apply (ctac add: updateMDB_mdbPrev_set_mdbNext) \<comment> \<open>***the correspondance proof for the rest***\<close> \<comment> \<open>--- instruction: updateMDB (mdbNext rv) (mdbPrev_update (%_. dest)) (but with CALL on C side) ---\<close> apply csymbr \<comment> \<open>symb exec of C instruction CALL to mdbNext\<close> \<comment> \<open>--- instruction: updateMDB (mdbNext rv) (mdbPrev_update (%_. dest)) (no CALL on C side) ---\<close> \<comment> \<open>--- (IF instruction in the C side) ---\<close> apply (erule_tac t = ret__unsigned in ssubst) apply csymbr apply (rule updateMDB_mdbNext_set_mdbPrev) apply simp apply simp \<comment> \<open>***the pre/post for Haskell side\<close> apply wp \<comment> \<open>***the pre/post for C side\<close> apply vcg \<comment> \<open>***pre/post for Haskell side of 2nd updateMDB***\<close> apply wp \<comment> \<open>***pre/post for C side of 2nd updateMDB***\<close> apply vcg \<comment> \<open>***pre/post for Haskell side of 1st updateMDB***\<close> apply wp \<comment> \<open>***pre/post for C side of 1st updateMDB***\<close> apply vcg \<comment> \<open>***pre/post for Haskell side of 2st updateCap***\<close> apply wp \<comment> \<open>***pre/post for C side of 2st updateCap***\<close> apply vcg \<comment> \<open>***pre/post for Haskell side of 1st updateCap***\<close> apply wp \<comment> \<open>***pre/post for C side of 1st updateCap***\<close> apply vcg \<comment> \<open>***pre/post for Haskell side of return***\<close> apply wp \<comment> \<open>***pre/post for C side of return***\<close> apply vcg \<comment> \<open>********************\<close> \<comment> \<open>*** LAST SUBGOAL ***\<close> \<comment> \<open>********************\<close> \<comment> \<open>***conjunction of generalised precondition ***\<close> apply (rule conjI) \<comment> \<open>***--------------------------------***\<close> \<comment> \<open>***Haskell generalised precondition***\<close> \<comment> \<open>***--------------------------------***\<close> \<comment> \<open>(complicated conjunction with many cte_at' and src\<noteq>0 \<dots>)\<close> apply (clarsimp simp: cte_wp_at_ctes_of) \<comment> \<open>cte_wp_at_ctes_of replaces (cte_at' p s) in the goal by\<close> \<comment> \<open>(\<exists>cte.ctes_of s p = Some cte) which is in the hypotheses\<close> \<comment> \<open>ctes_of s (?ptr908 ...) = Some scte \<and> ...\<close> apply (rule conjI, assumption) \<comment> \<open>instanciates the schematic with src\<close> \<comment> \<open>(mdbPrev \<dots> \<noteq> 0 \<longrightarrow> (\<exists>cte. ctes_of s (mdbPrev \<dots>) = Some cte) \<and> is_aligned (mdbPrev \<dots>) 3)\<close> \<comment> \<open>\<and> (mdbNext \<dots> \<noteq> 0 \<longrightarrow> (\<exists>cte. ctes_of s (mdbNext \<dots>) = Some cte) \<and> is_aligned (mdbNext \<dots>) 3)\<close> apply (rule conjI) apply (erule (2) is_aligned_3_prev) apply (erule (2) is_aligned_3_next) \<comment> \<open>***--------------------------***\<close> \<comment> \<open>***C generalised precondition***\<close> \<comment> \<open>***--------------------------***\<close> apply (unfold dc_def) apply (clarsimp simp: ccap_relation_NullCap_iff split del: if_split) \<comment> \<open>cmdbnode_relation nullMDBNode va\<close> apply (simp add: cmdbnode_relation_def) apply (simp add: mdb_node_to_H_def) apply (simp add: nullMDBNode_def) apply (simp add: false_def to_bool_def) done (************************************************************************) (* *) (* lemmas used in cteSwap_ccorres ***************************************) (* *) (************************************************************************) (*---------------------------------------------------------------------------------------*) (* corres lemma for return of mdbnode but 'safer' than ccorres_return_cte_mdbnode ------ *) (*---------------------------------------------------------------------------------------*) lemma ccorres_return_cte_mdbnode_safer: fixes ptr' :: "cstate \<Rightarrow> cte_C ptr" assumes r1: "\<And>s s' g. (s, s') \<in> rf_sr \<Longrightarrow> (s, xfu g s') \<in> rf_sr" and xf_xfu: "\<And>s g. xf (xfu g s) = g s" shows "ccorres cmdbnode_relation xf (\<lambda>s. \<exists> cte'. ctes_of s ptr = Some cte' \<and> cteMDBNode cte = cteMDBNode cte') {s. ptr_val (ptr' s) = ptr} hs (return (cteMDBNode cte)) (Basic (\<lambda>s. xfu (\<lambda>_. h_val (hrs_mem (t_hrs_' (globals s))) (Ptr &(ptr' s \<rightarrow>[''cteMDBNode_C'']))) s))" apply (rule ccorres_from_vcg) apply (rule allI, rule conseqPre, vcg) apply (clarsimp simp add: return_def) apply rule apply (erule r1) apply (simp add: xf_xfu) apply (drule (1) rf_sr_ctes_of_clift) apply (clarsimp simp: typ_heap_simps) done (*-----------------------------------------------------------------------*) (* lemmas about map and hrs_mem -----------------------------------------*) (*-----------------------------------------------------------------------*) declare modify_map_exists_cte[simp] (*------------------------------------------------------------------------------*) (* lemmas about pointer equality given valid_mdb (prev\<noteq>next, prev\<noteq>myself, etc) *) (*------------------------------------------------------------------------------*) lemma valid_mdb_Prev_neq_Next: "\<lbrakk> valid_mdb' s; ctes_of s p = Some cte; mdbPrev (cteMDBNode cte) \<noteq> 0 \<rbrakk> \<Longrightarrow> (mdbNext (cteMDBNode cte)) \<noteq> (mdbPrev (cteMDBNode cte))" apply (simp add: valid_mdb'_def) apply (simp add: valid_mdb_ctes_def) apply (elim conjE) apply (drule (1) mdb_chain_0_no_loops) apply (simp add: valid_dlist_def) apply (erule_tac x=p in allE) apply (erule_tac x=cte in allE) apply (simp add: Let_def) apply clarsimp apply (drule_tac s="mdbNext (cteMDBNode cte)" in sym) apply simp apply (simp add: no_loops_def) apply (erule_tac x= "(mdbNext (cteMDBNode cte))" in allE) apply (erule notE, rule trancl_trans) apply (rule r_into_trancl) apply (simp add: mdb_next_unfold) apply (rule r_into_trancl) apply (simp add: mdb_next_unfold) done lemma valid_mdb_Prev_neq_itself: "\<lbrakk> valid_mdb' s; ctes_of s p = Some cte \<rbrakk> \<Longrightarrow> (mdbPrev (cteMDBNode cte)) \<noteq> p" apply (unfold valid_mdb'_def) apply (simp add: CSpace_I.no_self_loop_prev) done lemma valid_mdb_Next_neq_itself: "\<lbrakk> valid_mdb' s; ctes_of s p = Some cte \<rbrakk> \<Longrightarrow> (mdbNext (cteMDBNode cte)) \<noteq> p" apply (unfold valid_mdb'_def) apply (simp add: CSpace_I.no_self_loop_next) done lemma valid_mdb_not_same_Next : "\<lbrakk> valid_mdb' s; p\<noteq>p'; ctes_of s p = Some cte; ctes_of s p' = Some cte'; (mdbNext (cteMDBNode cte))\<noteq>0 \<or> (mdbNext (cteMDBNode cte'))\<noteq>0 \<rbrakk> \<Longrightarrow> (mdbNext (cteMDBNode cte)) \<noteq> (mdbNext (cteMDBNode cte')) " apply (clarsimp) apply (case_tac cte, clarsimp) apply (rename_tac capability mdbnode) apply (case_tac cte', clarsimp) apply (subgoal_tac "mdb_ptr (ctes_of s) p capability mdbnode") apply (drule (2) mdb_ptr.p_nextD) apply clarsimp apply (unfold mdb_ptr_def vmdb_def mdb_ptr_axioms_def valid_mdb'_def, simp) done lemma valid_mdb_not_same_Prev : "\<lbrakk> valid_mdb' s; p\<noteq>p'; ctes_of s p = Some cte; ctes_of s p' = Some cte'; (mdbPrev (cteMDBNode cte))\<noteq>0 \<or> (mdbPrev (cteMDBNode cte'))\<noteq>0 \<rbrakk> \<Longrightarrow> (mdbPrev (cteMDBNode cte)) \<noteq> (mdbPrev (cteMDBNode cte')) " apply (clarsimp) apply (case_tac cte, clarsimp) apply (rename_tac capability mdbnode) apply (case_tac cte', clarsimp) apply (subgoal_tac "mdb_ptr (ctes_of s) p capability mdbnode") apply (drule (2) mdb_ptr.p_prevD) apply clarsimp apply (unfold mdb_ptr_def vmdb_def mdb_ptr_axioms_def valid_mdb'_def, simp) done (*---------------------------------------------------------------------------------*) (* lemmas to simplify the big last goal on C side to avoid proving things twice ---*) (*---------------------------------------------------------------------------------*) lemma c_guard_and_h_t_valid_eq_h_t_valid: "(POINTER \<noteq> 0 \<longrightarrow> c_guard ((Ptr &(Ptr POINTER ::cte_C ptr \<rightarrow>[''cteMDBNode_C''])) ::mdb_node_C ptr) \<and> s' \<Turnstile>\<^sub>c (Ptr (POINTER)::cte_C ptr)) = (POINTER \<noteq> 0 \<longrightarrow> s' \<Turnstile>\<^sub>c (Ptr (POINTER)::cte_C ptr))" apply (rule iffI, clarsimp+) apply (rule c_guard_field_lvalue) apply (rule c_guard_h_t_valid, assumption) apply (fastforce simp: typ_uinfo_t_def)+ done lemma c_guard_and_h_t_valid_and_rest_eq_h_t_valid_and_rest: "(POINTER \<noteq> 0 \<longrightarrow> c_guard ((Ptr &(Ptr POINTER ::cte_C ptr \<rightarrow>[''cteMDBNode_C''])) ::mdb_node_C ptr) \<and> s' \<Turnstile>\<^sub>c (Ptr (POINTER)::cte_C ptr) \<and> REST) = (POINTER \<noteq> 0 \<longrightarrow> s' \<Turnstile>\<^sub>c (Ptr (POINTER)::cte_C ptr) \<and> REST)" apply (rule iffI, clarsimp+) apply (rule c_guard_field_lvalue) apply (rule c_guard_h_t_valid, assumption) apply (fastforce simp: typ_uinfo_t_def)+ done (************************************************************************) (* *) (* cteSwap_ccorres ******************************************************) (* *) (************************************************************************) (* FIXME: the cte_ats aren't required here, can be shown using ccorres_guard_from_wp *) lemma cteSwap_ccorres: "ccorres dc xfdc (cte_at' slot and cte_at' slot' and valid_mdb' and pspace_aligned' and (\<lambda>_. slot \<noteq> slot')) (UNIV \<inter> {s. slot1_' s = Ptr slot} \<inter> {s. slot2_' s = Ptr slot'} \<inter> {s. ccap_relation cap1 (cap1_' s)} \<inter> {s. ccap_relation cap2 (cap2_' s)}) [] (cteSwap cap1 slot cap2 slot') (Call cteSwap_'proc)" apply (cinit (no_ignore_call) lift: slot1_' slot2_' cap1_' cap2_' simp del: return_bind) (* the previous line stands for all the following: unfolding cteSwap_def apply (rule ccorres_Call) apply (rule cteSwap_impl [unfolded cteSwap_body_def]) apply (rule ccorres_rhs_assoc)+ apply (simp del: return_bind Int_UNIV_left) apply (cinitlift slot1_' slot2_' cap1_' cap2_') apply (erule ssubst)+ apply (rule ccorres_guard_imp2) -- "We will need the abstract guards to solve the conc. guard obligations" *) \<comment> \<open>Start proofs\<close> \<comment> \<open>***Main goal***\<close> \<comment> \<open>--- instruction: cte1 \<leftarrow> getCTE slot; ---\<close> \<comment> \<open>--- y \<leftarrow> updateCap slot cap2 ---\<close> \<comment> \<open>--- y \<leftarrow> updateCap slot' cap1; ---\<close> \<comment> \<open>--- mdb1 \<leftarrow> return (cteMDBNode cte1); ---\<close> \<comment> \<open>Start proofs\<close> apply (ctac (no_vcg) pre: ccorres_pre_getCTE ccorres_move_guard_ptr_safe add: ccorres_return_cte_mdbnode_safer [where ptr="slot"])+ \<comment> \<open>generates maingoal + 2 subgoals (Haskell pre/post and C pre/post) for each instruction (except getCTE)\<close> \<comment> \<open>***Main Goal***\<close> \<comment> \<open>--- instruction: y <- updateMDB (mdbPrev rvc) (mdbNext_update (%_. slot')) ---\<close> apply csymbr apply csymbr \<comment> \<open>added by sjw \<dots>\<close> apply (erule_tac t = ret__unsigned in ssubst) apply (ctac (no_vcg) add: updateMDB_mdbPrev_set_mdbNext) apply csymbr apply csymbr apply (erule_tac t = ret__unsigned in ssubst) apply (ctac (no_vcg) add: updateMDB_mdbNext_set_mdbPrev) apply (rule ccorres_move_c_guard_cte) apply (ctac (no_vcg) pre: ccorres_getCTE ccorres_move_guard_ptr_safe add: ccorres_return_cte_mdbnode [where ptr = slot'] ccorres_move_guard_ptr_safe )+ apply csymbr apply csymbr apply (erule_tac t = ret__unsigned in ssubst) apply (ctac (no_vcg) add: updateMDB_mdbPrev_set_mdbNext) apply csymbr apply csymbr apply (erule_tac t = ret__unsigned in ssubst) apply (ctac (no_vcg) add: updateMDB_mdbNext_set_mdbPrev) (* apply (rule ccorres_split_nothrow [where xf'=xfdc]) -- "***the correspondance proof for 1st instruction***" apply (erule_tac t = prev_ptr in ssubst) apply (rule updateMDB_mdbPrev_set_mdbNext, rule refl, assumption) -- "***the ceqv proof***" apply ceqv -- "***the correspondance proof for the rest***" -- "--- instruction: updateMDB (mdbNext rvc) (mdbPrev_update (%_. slot')) ---" apply csymbr apply (rule ccorres_split_nothrow [where xf'=xfdc]) -- "***the correspondance proof for 1st instruction***" apply (erule_tac t = next_ptr in ssubst) apply (rule updateMDB_mdbNext_set_mdbPrev, rule refl, assumption) -- "***the ceqv proof***" apply ceqv -- "***the correspondance proof for the rest***" -- "--- instruction: cte2 \<leftarrow> getCTE slot'; ---" -- "--- mdb2 \<leftarrow> return (cteMDBNode cte2); ---" -- "--- y <- updateMDB slot (const mdb2); ---" -- "--- y <- updateMDB slot' (const rvc); ---" apply (ctac pre: ccorres_getCTE)+ -- "generates maingoal + 2 subgoals (Haskell pre/post and C pre/post) for each instruction (except getCTE)" -- "Main Goal" -- "---instruction: y <- updateMDB (mdbPrev mdb2) (mdbNext_update (%_. slot)) --" apply csymbr apply (rule ccorres_split_nothrow [where xf'=xfdc]) -- "***the correspondance proof for 1st instruction***" apply (erule_tac t = prev_ptr in ssubst) apply (rule updateMDB_mdbPrev_set_mdbNext, rule refl, assumption) -- "***the ceqv proof***" apply ceqv -- "***the correspondance proof for the rest***" -- "--- instruction: updateMDB (mdbNext rvg) (mdbPrev_update (%_. slot)) ---" apply csymbr apply (erule_tac t = next_ptr in ssubst) apply (rule updateMDB_mdbNext_set_mdbPrev, rule refl, assumption) *) \<comment> \<open>***Haskell pre/post for updateMDB (mdbPrev rvg) (mdbNext_update (%_. slot))\<close> apply wp \<comment> \<open>***C pre/post for updateMDB (mdbPrev rvg) (mdbNext_update (%_. slot))\<close> apply simp \<comment> \<open>***Haskell pre/post for updateMDB slot' (const rvc)\<close> apply wp \<comment> \<open>***C pre/post for updateMDB slot' (const rvc)\<close> apply simp \<comment> \<open>***Haskell pre/post for updateMDB slot (const mdb2)\<close> apply wp \<comment> \<open>***C pre/post for updateMDB slot (const mdb2)\<close> apply simp \<comment> \<open>***Haskell pre/post for return (cteMDBNode cte2) ***\<close> apply wp \<comment> \<open>***C pre/post for return (cteMDBNode cte2) ***\<close> apply simp \<comment> \<open>***Haskell pre/post for updateMDB (mdbPrev rvc) (mdbPrev_update (%_. slot'))\<close> apply (clarsimp simp : cte_wp_at_ctes_of) apply wp \<comment> \<open>***C pre/post for updateMDB (mdbPrev rvc) (mdbPrev_update (%_. slot'))\<close> apply simp \<comment> \<open>***Haskell pre/post for updateMDB (mdbPrev rvc) (mdbNext_update (%_. slot'))\<close> apply wp \<comment> \<open>***C pre/post for updateMDB (mdbPrev rvc) (mdbNext_update (%_. slot'))\<close> apply simp \<comment> \<open>***Haskell pre/post for return (cteMDBNode cte1) ***\<close> apply wp \<comment> \<open>***C pre/post for return (cteMDBNode cte1) ***\<close> apply simp \<comment> \<open>***Haskell pre/post for (updateCap slot' cap1) ***\<close> apply (clarsimp simp : cte_wp_at_ctes_of) apply (wp updateCap_ctes_of_wp) \<comment> \<open>***C pre/post for (updateCap slot' cap1) ***\<close> apply simp \<comment> \<open>***Haskell pre/post for (updateCap slot cap2) ***\<close> apply (clarsimp simp : cte_wp_at_ctes_of) apply (wp updateCap_ctes_of_wp) \<comment> \<open>***C pre/post for (updateCap slot cap2) ***\<close> apply simp \<comment> \<open>********************\<close> \<comment> \<open>*** LAST SUBGOAL ***\<close> \<comment> \<open>********************\<close> \<comment> \<open>***conjunction of generalised precondition ***\<close> apply (rule conjI) \<comment> \<open>***--------------------------------***\<close> \<comment> \<open>***Haskell generalised precondition***\<close> \<comment> \<open>***--------------------------------***\<close> apply (clarsimp simp: cte_wp_at_ctes_of) apply (frule (2) is_aligned_3_prev [where p = slot]) apply (frule (2) is_aligned_3_next [where p = slot]) apply simp apply (intro conjI impI) \<comment> \<open>\<exists>cte'. modify_map (\<dots>) slot = Some cte' \<and> cteMDBNode ctea = cteMDBNode cte'\<close> apply (simp add: modify_map_if) apply (case_tac ctea) apply simp apply (cases "(slot'=slot)", simp+) \<comment> \<open>no_0 (ctes_of s)\<close> apply (simp add: valid_mdb'_def) apply (erule valid_mdb_ctesE) apply assumption \<comment> \<open>\<forall>cte. modify_map (modify_map \<dots>) slot' = Some cte \<longrightarrow> \<dots>\<close> apply (rule allI) apply (rule impI) \<comment> \<open>modify_map (modify_map \<dots>) (?P3540 \<dots>) = Some cte\<close> \<comment> \<open>\<dots>\<longrightarrow> (\<exists>ctea. ctes_of s (mdbPrev (cteMDBNode cte)) = Some ctea) \<and> is_aligned (mdbPrev (cteMDBNode cte)) 3\<close> \<comment> \<open>Important: we need the first part to prove the second \<Longrightarrow> we need conj_cong\<close> apply (clarsimp simp: modify_map_if cong: if_cong split: if_split_asm) apply (erule disjE) apply clarsimp apply clarsimp apply (drule (2) is_aligned_3_next) apply simp apply (erule disjE) apply clarsimp apply (drule (2) is_aligned_3_prev) apply simp apply clarsimp apply (frule (2) is_aligned_3_prev) apply (frule (2) is_aligned_3_next) apply simp \<comment> \<open>***--------------------------***\<close> \<comment> \<open>***C generalised precondition***\<close> \<comment> \<open>***--------------------------***\<close> apply clarsimp done (* todo change in cteMove (\<lambda>s. ctes_of s src = Some scte) *) (************************************************************************) (* *) (* lemmas used in emptySlot_ccorres *************************************) (* *) (************************************************************************) declare if_split [split del] (* rq CALL mdb_node_ptr_set_mdbNext_'proc \<dots>) is a printing bug one should write CALL mdb_node_ptr_set_mdbNext *) lemma not_NullCap_eq_not_cap_null_cap: " \<lbrakk>ccap_relation cap cap' ; (s, s') \<in> rf_sr \<rbrakk> \<Longrightarrow> (cap \<noteq> NullCap) = (s' \<in> {_. (cap_get_tag cap' \<noteq> scast cap_null_cap)})" apply (rule iffI) apply (case_tac "cap_get_tag cap' \<noteq> scast cap_null_cap", clarsimp+) apply (erule notE) apply (simp add: cap_get_tag_NullCap) apply (case_tac "cap_get_tag cap' \<noteq> scast cap_null_cap") apply (rule notI) apply (erule notE) apply (simp add: cap_get_tag_NullCap) apply clarsimp done lemma mdbPrev_CL_mdb_node_lift_mask [simp]: "mdbPrev_CL (mdb_node_lift mdbNode) && ~~ mask 3 = mdbPrev_CL (mdb_node_lift mdbNode)" apply (simp add: mdb_node_lift_def mask_def word_bw_assocs) done lemma emptySlot_helper: fixes mdbNode defines "nextmdb \<equiv> Ptr &(Ptr ((mdbNext_CL (mdb_node_lift mdbNode)))::cte_C ptr\<rightarrow>[''cteMDBNode_C'']) :: mdb_node_C ptr" defines "nextcte \<equiv> Ptr ((mdbNext_CL (mdb_node_lift mdbNode)))::cte_C ptr" shows "\<lbrakk>cmdbnode_relation rva mdbNode\<rbrakk> \<Longrightarrow> ccorres dc xfdc \<top> UNIV hs (updateMDB (mdbNext rva) (\<lambda>mdb. mdbFirstBadged_update (\<lambda>_. mdbFirstBadged mdb \<or> mdbFirstBadged rva) (mdbPrev_update (\<lambda>_. mdbPrev rva) mdb))) (IF mdbNext_CL (mdb_node_lift mdbNode) \<noteq> 0 THEN Guard C_Guard \<lbrace>hrs_htd \<acute>t_hrs \<Turnstile>\<^sub>t nextcte\<rbrace> (CALL mdb_node_ptr_set_mdbPrev(nextmdb, ptr_val (Ptr (mdbPrev_CL (mdb_node_lift mdbNode))))) FI;; IF mdbNext_CL (mdb_node_lift mdbNode) \<noteq> 0 THEN Guard C_Guard \<lbrace>hrs_htd \<acute>t_hrs \<Turnstile>\<^sub>t nextcte\<rbrace> (\<acute>ret__unsigned :== CALL mdb_node_get_mdbFirstBadged(h_val (hrs_mem \<acute>t_hrs) nextmdb));; \<acute>ret__int :== (if \<acute>ret__unsigned \<noteq> 0 then 1 else 0);; IF \<acute>ret__int \<noteq> 0 THEN SKIP ELSE \<acute>ret__unsigned :== CALL mdb_node_get_mdbFirstBadged(mdbNode);; \<acute>ret__int :== (if \<acute>ret__unsigned \<noteq> 0 then 1 else 0) FI;; Guard C_Guard \<lbrace>hrs_htd \<acute>t_hrs \<Turnstile>\<^sub>t nextcte\<rbrace> (CALL mdb_node_ptr_set_mdbFirstBadged(nextmdb,scast \<acute>ret__int)) FI)" apply (rule ccorres_guard_imp2) apply (rule ccorres_updateMDB_cte_at) apply (subgoal_tac "mdbNext rva=(mdbNext_CL (mdb_node_lift mdbNode))") prefer 2 apply (simp add: cmdbnode_relation_def) apply (case_tac "mdbNext rva \<noteq> 0") apply (case_tac "mdbNext_CL (mdb_node_lift mdbNode) = 0", simp) \<comment> \<open>case where mdbNext rva \<noteq> 0 and mdbNext_CL (mdb_node_lift mdbNode) \<noteq> 0\<close> apply (unfold updateMDB_def) apply (clarsimp simp: Let_def) apply (rule ccorres_pre_getCTE [where P = "\<lambda>cte s. ctes_of s (mdbNext rva) = Some cte" and P' = "\<lambda>_. UNIV"]) apply (rule ccorres_from_vcg) apply (rule allI) apply (rule conseqPre, vcg) apply clarsimp apply (frule(1) rf_sr_ctes_of_clift) apply (clarsimp simp: typ_heap_simps' nextmdb_def nextcte_def) apply (intro conjI impI allI) \<comment> \<open>\<dots> \<exists>x\<in>fst \<dots>\<close> apply clarsimp apply (rule fst_setCTE [OF ctes_of_cte_at], assumption ) apply (erule bexI [rotated]) apply (frule (1) rf_sr_ctes_of_clift) apply (clarsimp simp add: rf_sr_def cstate_relation_def typ_heap_simps Let_def cpspace_relation_def) apply (rule conjI) prefer 2 apply (erule_tac t = s' in ssubst) apply (simp add: carch_state_relation_def cmachine_state_relation_def h_t_valid_clift_Some_iff cvariable_array_map_const_add_map_option[where f="tcb_no_ctes_proj"] typ_heap_simps' cong: lifth_update) apply (erule (1) setCTE_tcb_case) apply (erule (2) cspace_cte_relation_upd_mdbI) apply (simp add: cmdbnode_relation_def) apply (simp add: mdb_node_to_H_def) apply (subgoal_tac "mdbFirstBadged_CL (mdb_node_lift mdbNode) && mask (Suc 0) = mdbFirstBadged_CL (mdb_node_lift mdbNode)") prefer 2 subgoal by (simp add: mdb_node_lift_def mask_def word_bw_assocs) apply (subgoal_tac "mdbFirstBadged_CL (cteMDBNode_CL y) && mask (Suc 0) = mdbFirstBadged_CL (cteMDBNode_CL y)") prefer 2 apply (drule cteMDBNode_CL_lift [symmetric]) subgoal by (simp add: mdb_node_lift_def mask_def word_bw_assocs) subgoal by (simp add: to_bool_def mask_def) \<comment> \<open>\<dots> \<exists>x\<in>fst \<dots>\<close> apply clarsimp apply (rule fst_setCTE [OF ctes_of_cte_at], assumption ) apply (erule bexI [rotated]) apply (frule (1) rf_sr_ctes_of_clift) apply (clarsimp simp add: rf_sr_def cstate_relation_def typ_heap_simps Let_def cpspace_relation_def) apply (rule conjI) prefer 2 apply (erule_tac t = s' in ssubst) apply (simp add: carch_state_relation_def cmachine_state_relation_def h_t_valid_clift_Some_iff cvariable_array_map_const_add_map_option[where f="tcb_no_ctes_proj"] typ_heap_simps' cong: lifth_update) apply (erule (1) setCTE_tcb_case) apply (erule (2) cspace_cte_relation_upd_mdbI) apply (simp add: cmdbnode_relation_def) apply (simp add: mdb_node_to_H_def) apply (subgoal_tac "mdbFirstBadged_CL (mdb_node_lift mdbNode) && mask (Suc 0) = mdbFirstBadged_CL (mdb_node_lift mdbNode)") prefer 2 subgoal by (simp add: mdb_node_lift_def mask_def word_bw_assocs) apply (subgoal_tac "mdbFirstBadged_CL (cteMDBNode_CL y) && mask (Suc 0) = mdbFirstBadged_CL (cteMDBNode_CL y)") prefer 2 apply (drule cteMDBNode_CL_lift [symmetric]) subgoal by (simp add: mdb_node_lift_def mask_def word_bw_assocs) apply (simp add: to_bool_def mask_def split: if_split) \<comment> \<open>trivial case where mdbNext rva = 0\<close> apply (simp add:ccorres_cond_empty_iff) apply (rule ccorres_guard_imp2) apply (rule ccorres_return_Skip) apply simp apply (clarsimp simp: cmdbnode_relation_def) done (************************************************************************) (* *) (* emptySlot_ccorres ****************************************************) (* *) (************************************************************************) (* ML "set CtacImpl.trace_ctac"*) lemma mdbNext_CL_mdb_node_lift_eq_mdbNext: "cmdbnode_relation n n' \<Longrightarrow> (mdbNext_CL (mdb_node_lift n')) =(mdbNext n)" by (erule cmdbnode_relationE, fastforce simp: mdbNext_to_H) lemma mdbPrev_CL_mdb_node_lift_eq_mdbPrev: "cmdbnode_relation n n' \<Longrightarrow> (mdbPrev_CL (mdb_node_lift n')) =(mdbPrev n)" by (erule cmdbnode_relationE, fastforce simp: mdbNext_to_H) lemma mdbNext_not_zero_eq_simpler: "cmdbnode_relation n n' \<Longrightarrow> (mdbNext n \<noteq> 0) = (mdbNext_CL (mdb_node_lift n') \<noteq> 0)" apply clarsimp apply (erule cmdbnode_relationE) apply (fastforce simp: mdbNext_to_H) done lemma mdbPrev_not_zero_eq_simpler: "cmdbnode_relation n n' \<Longrightarrow> (mdbPrev n \<noteq> 0) = (mdbPrev_CL (mdb_node_lift n') \<noteq> 0)" apply clarsimp apply (erule cmdbnode_relationE) apply (fastforce simp: mdbPrev_to_H) done lemma h_t_valid_and_cslift_and_c_guard_field_mdbPrev_CL: " \<lbrakk>(s, s') \<in> rf_sr; cte_at' slot s; valid_mdb' s; cslift s' (Ptr slot) = Some cte'\<rbrakk> \<Longrightarrow> (mdbPrev_CL (mdb_node_lift (cteMDBNode_C cte')) \<noteq> 0) \<longrightarrow> s' \<Turnstile>\<^sub>c ( Ptr (mdbPrev_CL (mdb_node_lift (cteMDBNode_C cte'))) :: cte_C ptr) \<and> (\<exists> cten. cslift s' (Ptr (mdbPrev_CL (mdb_node_lift (cteMDBNode_C cte'))) :: cte_C ptr) = Some cten) \<and> c_guard (Ptr &(Ptr (mdbPrev_CL (mdb_node_lift (cteMDBNode_C cte')))::cte_C ptr\<rightarrow>[''cteMDBNode_C'']) :: mdb_node_C ptr)" apply (clarsimp simp: cte_wp_at_ctes_of) apply (drule (1) valid_mdb_ctes_of_prev) apply (frule (2) rf_sr_cte_relation) apply (drule ccte_relation_cmdbnode_relation) apply (simp add: mdbPrev_not_zero_eq_simpler) apply (clarsimp simp: cte_wp_at_ctes_of) apply (drule (1) rf_sr_ctes_of_clift [rotated])+ apply (clarsimp simp: typ_heap_simps) apply (rule c_guard_field_lvalue [rotated]) apply (fastforce simp: typ_uinfo_t_def)+ apply (rule c_guard_clift) apply (simp add: typ_heap_simps) done lemma h_t_valid_and_cslift_and_c_guard_field_mdbNext_CL: " \<lbrakk>(s, s') \<in> rf_sr; cte_at' slot s; valid_mdb' s; cslift s' (Ptr slot) = Some cte'\<rbrakk> \<Longrightarrow> (mdbNext_CL (mdb_node_lift (cteMDBNode_C cte')) \<noteq> 0) \<longrightarrow> s' \<Turnstile>\<^sub>c ( Ptr (mdbNext_CL (mdb_node_lift (cteMDBNode_C cte'))) :: cte_C ptr) \<and> (\<exists> cten. cslift s' (Ptr (mdbNext_CL (mdb_node_lift (cteMDBNode_C cte'))) :: cte_C ptr) = Some cten) \<and> c_guard (Ptr &(Ptr (mdbNext_CL (mdb_node_lift (cteMDBNode_C cte')))::cte_C ptr\<rightarrow>[''cteMDBNode_C'']) :: mdb_node_C ptr)" apply (clarsimp simp: cte_wp_at_ctes_of) apply (drule (1) valid_mdb_ctes_of_next) apply (frule (2) rf_sr_cte_relation) apply (drule ccte_relation_cmdbnode_relation) apply (simp add: mdbNext_not_zero_eq_simpler) apply (clarsimp simp: cte_wp_at_ctes_of) apply (drule (1) rf_sr_ctes_of_clift [rotated])+ apply (clarsimp simp: typ_heap_simps) apply (rule c_guard_field_lvalue [rotated]) apply (fastforce simp: typ_uinfo_t_def)+ apply (rule c_guard_clift) apply (simp add: typ_heap_simps) done lemma valid_mdb_Prev_neq_Next_better: "\<lbrakk> valid_mdb' s; ctes_of s p = Some cte \<rbrakk> \<Longrightarrow> mdbPrev (cteMDBNode cte) \<noteq> 0 \<longrightarrow> (mdbNext (cteMDBNode cte)) \<noteq> (mdbPrev (cteMDBNode cte))" apply (rule impI) apply (simp add: valid_mdb'_def) apply (simp add: valid_mdb_ctes_def) apply (elim conjE) apply (drule (1) mdb_chain_0_no_loops) apply (simp add: valid_dlist_def) apply (erule_tac x=p in allE) apply (erule_tac x=cte in allE) apply (simp add: Let_def) apply clarsimp apply (drule_tac s="mdbNext (cteMDBNode cte)" in sym) apply simp apply (simp add: no_loops_def) apply (erule_tac x= "(mdbNext (cteMDBNode cte))" in allE) apply (erule notE, rule trancl_trans) apply (rule r_into_trancl) apply (simp add: mdb_next_unfold) apply (rule r_into_trancl) apply (simp add: mdb_next_unfold) done (* TODO: move *) definition irq_opt_relation_def: "irq_opt_relation (airq :: (10 word) option) (cirq :: machine_word) \<equiv> case airq of Some irq \<Rightarrow> (cirq = ucast irq \<and> irq \<noteq> scast irqInvalid \<and> ucast irq \<le> (scast Kernel_C.maxIRQ :: machine_word)) | None \<Rightarrow> cirq = ucast irqInvalid" declare unat_ucast_up_simp[simp] lemma setIRQState_ccorres: "ccorres dc xfdc (\<top> and (\<lambda>s. ucast irq \<le> (scast Kernel_C.maxIRQ :: machine_word))) (UNIV \<inter> {s. irqState_' s = irqstate_to_C irqState} \<inter> {s. irq_' s = (ucast irq :: machine_word)} ) [] (setIRQState irqState irq) (Call setIRQState_'proc )" apply (rule ccorres_gen_asm) apply (cinit simp del: return_bind) apply (rule ccorres_symb_exec_l) apply simp apply (rule_tac r'="dc" and xf'="xfdc" in ccorres_split_nothrow) apply (rule_tac P= "\<lambda>s. st = (ksInterruptState s)" and P'= "(UNIV \<inter> {s. irqState_' s = irqstate_to_C irqState} \<inter> {s. irq_' s = ucast irq} )" in ccorres_from_vcg) apply (rule allI, rule conseqPre, vcg) apply (clarsimp simp: setInterruptState_def) apply (clarsimp simp: simpler_modify_def) apply (clarsimp simp: rf_sr_def cstate_relation_def Let_def carch_state_relation_def cmachine_state_relation_def) apply (simp add: cinterrupt_relation_def Kernel_C.maxIRQ_def) apply (clarsimp simp: word_sless_msb_less order_le_less_trans unat_ucast_no_overflow_le word_le_nat_alt ucast_ucast_b split: if_split ) apply ceqv apply (ctac add: maskInterrupt_ccorres) apply wp apply vcg apply wp apply (simp add: getInterruptState_def gets_def) apply wp apply (simp add: empty_fail_def getInterruptState_def simpler_gets_def) apply clarsimp apply (simp add: from_bool_def) apply (cases irqState, simp_all) apply (simp add: Kernel_C.IRQSignal_def Kernel_C.IRQInactive_def) apply (simp add: Kernel_C.IRQTimer_def Kernel_C.IRQInactive_def) apply (simp add: Kernel_C.IRQInactive_def Kernel_C.IRQReserved_def) done lemma deletedIRQHandler_ccorres: "ccorres dc xfdc (\<lambda>s. ucast irq \<le> (scast Kernel_C.maxIRQ :: machine_word)) (UNIV\<inter> {s. irq_' s = ucast irq}) [] (deletedIRQHandler irq) (Call deletedIRQHandler_'proc )" apply (cinit simp del: return_bind) apply (ctac add: setIRQState_ccorres) apply clarsimp done lemmas ccorres_split_noop_lhs = ccorres_split_nothrow[where c=Skip, OF _ ceqv_refl _ _ hoarep.Skip, simplified ccorres_seq_skip] (* FIXME: to SR_Lemmas *) lemma region_is_bytes_subset: "region_is_bytes' ptr sz htd \<Longrightarrow> {ptr' ..+ sz'} \<subseteq> {ptr ..+ sz} \<Longrightarrow> region_is_bytes' ptr' sz' htd" by (auto simp: region_is_bytes'_def) lemma region_actually_is_bytes_subset: "region_actually_is_bytes' ptr sz htd \<Longrightarrow> {ptr' ..+ sz'} \<subseteq> {ptr ..+ sz} \<Longrightarrow> region_actually_is_bytes' ptr' sz' htd" by (auto simp: region_actually_is_bytes'_def) lemma intvl_both_le: "\<lbrakk> a \<le> x; unat x + y \<le> unat a + b \<rbrakk> \<Longrightarrow> {x ..+ y} \<le> {a ..+ b}" apply (rule order_trans[OF _ intvl_sub_offset[where x="x - a"]]) apply (simp, rule order_refl) apply unat_arith done lemma untypedZeroRange_idx_forward_helper: "isUntypedCap cap \<Longrightarrow> capFreeIndex cap \<le> idx \<Longrightarrow> idx \<le> 2 ^ capBlockSize cap \<Longrightarrow> valid_cap' cap s \<Longrightarrow> (case (untypedZeroRange cap, untypedZeroRange (capFreeIndex_update (\<lambda>_. idx) cap)) of (Some (a, b), Some (a', b')) \<Rightarrow> {a' ..+ unat (b' + 1 - a')} \<subseteq> {a ..+ unat (b + 1 - a)} | _ \<Rightarrow> True)" apply (clarsimp split: option.split) apply (clarsimp simp: untypedZeroRange_def max_free_index_def Let_def isCap_simps valid_cap_simps' capAligned_def untypedBits_defs split: if_split_asm) apply (erule subsetD[rotated], rule intvl_both_le) apply (clarsimp simp: getFreeRef_def) apply (rule word_plus_mono_right) apply (rule PackedTypes.of_nat_mono_maybe_le) apply (erule order_le_less_trans, rule power_strict_increasing, simp_all) apply (erule is_aligned_no_wrap') apply (rule word_of_nat_less, simp) apply (simp add: getFreeRef_def) apply (simp add: unat_plus_simple[THEN iffD1, OF is_aligned_no_wrap'] word_of_nat_less) apply (simp add: word_of_nat_le unat_sub order_le_less_trans[OF _ power_strict_increasing] unat_of_nat_eq[where 'a=32, folded word_bits_def]) done lemma intvl_close_Un: "y = x + of_nat n \<Longrightarrow> ({x ..+ n} \<union> {y ..+ m}) = {x ..+ n + m}" apply ((simp add: intvl_def, safe, simp_all, simp_all only: of_nat_add[symmetric]); (rule exI, strengthen refl)) apply simp_all apply (rule ccontr) apply (drule_tac x="k - n" in spec) apply simp done lemma untypedZeroRange_idx_backward_helper: "isUntypedCap cap \<Longrightarrow> idx \<le> capFreeIndex cap \<Longrightarrow> idx \<le> 2 ^ capBlockSize cap \<Longrightarrow> valid_cap' cap s \<Longrightarrow> (case untypedZeroRange (capFreeIndex_update (\<lambda>_. idx) cap) of None \<Rightarrow> True | Some (a', b') \<Rightarrow> {a' ..+ unat (b' + 1 - a')} \<subseteq> {capPtr cap + of_nat idx ..+ (capFreeIndex cap - idx)} \<union> (case untypedZeroRange cap of Some (a, b) \<Rightarrow> {a ..+ unat (b + 1 - a)} | None \<Rightarrow> {}) )" apply (clarsimp split: option.split, intro impI conjI allI) apply (rule intvl_both_le; clarsimp simp: untypedZeroRange_def max_free_index_def Let_def isCap_simps valid_cap_simps' capAligned_def split: if_split_asm) apply (clarsimp simp: getFreeRef_def) apply (clarsimp simp: getFreeRef_def) apply (simp add: word_of_nat_le unat_sub order_le_less_trans[OF _ power_strict_increasing] unat_of_nat_eq[where 'a=32, folded word_bits_def]) apply (subst intvl_close_Un) apply (clarsimp simp: untypedZeroRange_def max_free_index_def Let_def getFreeRef_def split: if_split_asm) apply (clarsimp simp: untypedZeroRange_def max_free_index_def Let_def getFreeRef_def isCap_simps valid_cap_simps' split: if_split_asm) apply (simp add: word_of_nat_le unat_sub capAligned_def order_le_less_trans[OF _ power_strict_increasing] order_le_less_trans[where x=idx] unat_of_nat_eq[where 'a=32, folded word_bits_def]) done lemma ctes_of_untyped_zero_rf_sr_case: "\<lbrakk> ctes_of s p = Some cte; (s, s') \<in> rf_sr; untyped_ranges_zero' s \<rbrakk> \<Longrightarrow> case untypedZeroRange (cteCap cte) of None \<Rightarrow> True | Some (start, end) \<Rightarrow> region_actually_is_zero_bytes start (unat ((end + 1) - start)) s'" by (simp split: option.split add: ctes_of_untyped_zero_rf_sr) lemma gsUntypedZeroRanges_update_helper: "(\<sigma>, s) \<in> rf_sr \<Longrightarrow> (zero_ranges_are_zero (gsUntypedZeroRanges \<sigma>) (t_hrs_' (globals s)) \<longrightarrow> zero_ranges_are_zero (f (gsUntypedZeroRanges \<sigma>)) (t_hrs_' (globals s))) \<Longrightarrow> (gsUntypedZeroRanges_update f \<sigma>, s) \<in> rf_sr" by (clarsimp simp: rf_sr_def cstate_relation_def Let_def) lemma heap_list_zero_Ball_intvl: "heap_list_is_zero hmem ptr n = (\<forall>x \<in> {ptr ..+ n}. hmem x = 0)" apply safe apply (erule heap_list_h_eq_better) apply (simp add: heap_list_rpbs) apply (rule trans[OF heap_list_h_eq2 heap_list_rpbs]) apply simp done lemma untypedZeroRange_not_device: "untypedZeroRange cap = Some r \<Longrightarrow> \<not> capIsDevice cap" by (clarsimp simp: untypedZeroRange_def cong: if_cong) lemma updateTrackedFreeIndex_noop_ccorres: "ccorres dc xfdc (cte_wp_at' ((\<lambda>cap. isUntypedCap cap \<and> idx \<le> 2 ^ capBlockSize cap \<and> (capFreeIndex cap \<le> idx \<or> cap' = cap)) o cteCap) slot and valid_objs' and untyped_ranges_zero') {s. \<not> capIsDevice cap' \<longrightarrow> region_actually_is_zero_bytes (capPtr cap' + of_nat idx) (capFreeIndex cap' - idx) s} hs (updateTrackedFreeIndex slot idx) Skip" (is "ccorres dc xfdc ?P ?P' _ _ _") apply (simp add: updateTrackedFreeIndex_def getSlotCap_def) apply (rule ccorres_guard_imp) apply (rule ccorres_pre_getCTE[where P="\<lambda>rv. cte_wp_at' ((=) rv) slot and ?P" and P'="K ?P'"]) apply (rule ccorres_from_vcg) apply (rule allI, rule conseqPre, vcg) apply (clarsimp simp: cte_wp_at_ctes_of) apply (frule(1) ctes_of_valid') apply (frule(2) ctes_of_untyped_zero_rf_sr_case) apply (clarsimp simp: simpler_modify_def bind_def cte_wp_at_ctes_of) apply (erule gsUntypedZeroRanges_update_helper) apply (clarsimp simp: zero_ranges_are_zero_def split: if_split) apply (case_tac "(a, b) \<in> gsUntypedZeroRanges \<sigma>") apply (drule(1) bspec, simp) apply (erule disjE_L) apply (frule(3) untypedZeroRange_idx_forward_helper) apply (clarsimp simp: isCap_simps valid_cap_simps') apply (case_tac "untypedZeroRange (cteCap cte)") apply (clarsimp simp: untypedZeroRange_def valid_cap_simps' max_free_index_def Let_def split: if_split_asm) apply clarsimp apply (thin_tac "\<not> capIsDevice cap' \<longrightarrow> P" for P) apply (clarsimp split: option.split_asm) apply (subst region_actually_is_bytes_subset, simp+) apply (subst heap_list_is_zero_mono2, simp+) apply (frule untypedZeroRange_idx_backward_helper[where idx=idx], simp+) apply (clarsimp simp: isCap_simps valid_cap_simps') apply (clarsimp split: option.split_asm) apply (clarsimp dest!: untypedZeroRange_not_device) apply (subst region_actually_is_bytes_subset, simp+) apply (subst heap_list_is_zero_mono2, simp+) apply (simp add: region_actually_is_bytes'_def heap_list_zero_Ball_intvl) apply (clarsimp dest!: untypedZeroRange_not_device) apply blast apply (clarsimp simp: cte_wp_at_ctes_of) apply clarsimp done lemma updateTrackedFreeIndex_forward_noop_ccorres: "ccorres dc xfdc (cte_wp_at' ((\<lambda>cap. isUntypedCap cap \<and> capFreeIndex cap \<le> idx \<and> idx \<le> 2 ^ capBlockSize cap) o cteCap) slot and valid_objs' and untyped_ranges_zero') UNIV hs (updateTrackedFreeIndex slot idx) Skip" (is "ccorres dc xfdc ?P UNIV _ _ _") apply (rule ccorres_name_pre) apply (rule ccorres_guard_imp2, rule_tac cap'="cteCap (the (ctes_of s slot))" in updateTrackedFreeIndex_noop_ccorres) apply (clarsimp simp: cte_wp_at_ctes_of region_actually_is_bytes'_def) done lemma clearUntypedFreeIndex_noop_ccorres: "ccorres dc xfdc (valid_objs' and untyped_ranges_zero') UNIV hs (clearUntypedFreeIndex p) Skip" apply (simp add: clearUntypedFreeIndex_def getSlotCap_def) apply (rule ccorres_guard_imp) apply (rule ccorres_pre_getCTE[where P="\<lambda>rv. cte_wp_at' ((=) rv) p and valid_objs' and untyped_ranges_zero'" and P'="K UNIV"]) apply (case_tac "cteCap cte", simp_all add: ccorres_guard_imp[OF ccorres_return_Skip])[1] apply (rule ccorres_guard_imp, rule updateTrackedFreeIndex_forward_noop_ccorres) apply (clarsimp simp: cte_wp_at_ctes_of max_free_index_def) apply (frule(1) Finalise_R.ctes_of_valid') apply (clarsimp simp: valid_cap_simps') apply simp apply (clarsimp simp: cte_wp_at_ctes_of) apply simp done lemma Arch_postCapDeletion_ccorres: "ccorres dc xfdc \<top> (UNIV \<inter> {s. ccap_relation (ArchObjectCap acap) (cap_' s)}) hs (ARM_HYP_H.postCapDeletion acap) (Call Arch_postCapDeletion_'proc)" apply (cinit lift: cap_') apply (rule ccorres_return_Skip) by simp lemma not_irq_or_arch_cap_case: "\<lbrakk>\<not>isIRQHandlerCap cap; \<not> isArchCap \<top> cap\<rbrakk> \<Longrightarrow> (case cap of IRQHandlerCap irq \<Rightarrow> f irq | ArchObjectCap acap \<Rightarrow> g acap | _ \<Rightarrow> h) = h" by (case_tac cap; clarsimp simp: isCap_simps) definition arch_cleanup_info_wf' :: "arch_capability \<Rightarrow> bool" where "arch_cleanup_info_wf' acap \<equiv> True" definition cleanup_info_wf' :: "capability \<Rightarrow> bool" where "cleanup_info_wf' cap \<equiv> case cap of IRQHandlerCap irq \<Rightarrow> UCAST(10\<rightarrow>machine_word_len) irq \<le> SCAST(32 signed\<rightarrow>machine_word_len) Kernel_C.maxIRQ | ArchObjectCap acap \<Rightarrow> arch_cleanup_info_wf' acap | _ \<Rightarrow> True" lemma postCapDeletion_ccorres: "cleanup_info_wf' cap \<Longrightarrow> ccorres dc xfdc \<top> (UNIV \<inter> {s. ccap_relation cap (cap_' s)}) hs (postCapDeletion cap) (Call postCapDeletion_'proc)" supply Collect_const[simp del] apply (cinit lift: cap_' simp: Retype_H.postCapDeletion_def) apply csymbr apply (clarsimp simp: cap_get_tag_isCap) apply (rule ccorres_Cond_rhs) apply (clarsimp simp: isCap_simps ) apply (rule ccorres_symb_exec_r) apply (rule_tac xf'=irq_' in ccorres_abstract, ceqv) apply (rule_tac P="rv' = ucast (capIRQ cap)" in ccorres_gen_asm2) apply (fold dc_def) apply (frule cap_get_tag_to_H, solves \<open>clarsimp simp: cap_get_tag_isCap_unfolded_H_cap\<close>) apply (clarsimp simp: cap_irq_handler_cap_lift) apply (ctac(no_vcg) add: deletedIRQHandler_ccorres) apply vcg apply (rule conseqPre, vcg) apply clarsimp apply csymbr apply (clarsimp simp: cap_get_tag_isCap) apply (rule ccorres_Cond_rhs) apply (wpc; clarsimp simp: isCap_simps) apply (ctac(no_vcg) add: Arch_postCapDeletion_ccorres[unfolded dc_def]) apply (simp add: not_irq_or_arch_cap_case) apply (rule ccorres_return_Skip[unfolded dc_def])+ apply clarsimp apply (rule conjI, clarsimp simp: isCap_simps Kernel_C.maxIRQ_def) apply (frule cap_get_tag_isCap_unfolded_H_cap(5)) apply (clarsimp simp: cap_irq_handler_cap_lift ccap_relation_def cap_to_H_def cleanup_info_wf'_def maxIRQ_def Kernel_C.maxIRQ_def) apply (rule conjI, clarsimp simp: isCap_simps) apply (rule conjI[rotated], clarsimp simp: isCap_simps) apply (clarsimp simp: isCap_simps) apply (frule cap_get_tag_isCap_unfolded_H_cap(5)) apply (clarsimp simp: cap_irq_handler_cap_lift ccap_relation_def cap_to_H_def cleanup_info_wf'_def c_valid_cap_def cl_valid_cap_def mask_def) apply (clarsimp simp: word_size Kernel_C.maxIRQ_def maxIRQ_def) by word_bitwise lemma emptySlot_ccorres: "ccorres dc xfdc (valid_mdb' and valid_objs' and pspace_aligned' and untyped_ranges_zero') (UNIV \<inter> {s. slot_' s = Ptr slot} \<inter> {s. ccap_relation info (cleanupInfo_' s) \<and> cleanup_info_wf' info} ) [] (emptySlot slot info) (Call emptySlot_'proc)" supply if_cong[cong] apply (cinit lift: slot_' cleanupInfo_' simp: case_Null_If) \<comment> \<open>--- handle the clearUntypedFreeIndex\<close> apply (rule ccorres_split_noop_lhs, rule clearUntypedFreeIndex_noop_ccorres) \<comment> \<open>--- instruction: newCTE \<leftarrow> getCTE slot; ---\<close> apply (rule ccorres_pre_getCTE) \<comment> \<open>--- instruction: CALL on C side\<close> apply (rule ccorres_move_c_guard_cte) apply csymbr apply (rule ccorres_abstract_cleanup) apply (rename_tac cap_tag) apply (rule_tac P="(cap_tag = scast cap_null_cap) = (cteCap newCTE = NullCap)" in ccorres_gen_asm2) apply (simp del: Collect_const) \<comment> \<open>--- instruction: if-then-else / IF-THEN-ELSE\<close> apply (rule ccorres_cond2'[where R=\<top>]) \<comment> \<open>*** link between abstract and concrete conditionals ***\<close> apply (clarsimp split: if_split) \<comment> \<open>*** proof for the 'else' branch (return () and SKIP) ***\<close> prefer 2 apply (ctac add: ccorres_return_Skip[unfolded dc_def]) \<comment> \<open>*** proof for the 'then' branch ***\<close> \<comment> \<open>---instructions: multiple on C side, including mdbNode fetch\<close> apply (rule ccorres_rhs_assoc)+ \<comment> \<open>we have to do it here because the first assoc did not apply inside the then block\<close> apply (rule ccorres_move_c_guard_cte | csymbr)+ apply (rule ccorres_symb_exec_r) apply (rule_tac xf'="mdbNode_'" in ccorres_abstract, ceqv) apply (rename_tac "cmdbNode") apply (rule_tac P="cmdbnode_relation (cteMDBNode newCTE) cmdbNode" in ccorres_gen_asm2) apply csymbr+ \<comment> \<open>--- instruction: updateMDB (mdbPrev rva) (mdbNext_update \<dots>) but with Ptr\<dots>\<noteq> NULL on C side\<close> apply (simp only:Ptr_not_null_pointer_not_zero) \<comment> \<open>replaces Ptr p \<noteq> NULL with p\<noteq>0\<close> \<comment> \<open>--- instruction: y \<leftarrow> updateMDB (mdbPrev rva) (mdbNext_update (\<lambda>_. mdbNext rva))\<close> apply (ctac (no_simp, no_vcg) pre:ccorres_move_guard_ptr_safe add: updateMDB_mdbPrev_set_mdbNext) \<comment> \<open>here ctac alone does not apply because the subgoal generated by the rule are not solvable by simp\<close> \<comment> \<open>so we have to use (no_simp) (or apply (rule ccorres_split_nothrow))\<close> apply (simp add: cmdbnode_relation_def) apply assumption \<comment> \<open>*** Main goal ***\<close> \<comment> \<open>--- instruction: updateMDB (mdbNext rva) (\<lambda>mdb. mdbFirstBadged_update (\<lambda>_. mdbFirstBadged mdb \<or> mdbFirstBadged rva) (mdbPrev_update (\<lambda>_. mdbPrev rva) mdb));\<close> apply (rule ccorres_rhs_assoc2 ) \<comment> \<open>to group the 2 first C instrutions together\<close> apply (ctac (no_vcg) add: emptySlot_helper) \<comment> \<open>--- instruction: y \<leftarrow> updateCap slot capability.NullCap;\<close> apply (simp del: Collect_const) apply csymbr apply (ctac (no_vcg) pre:ccorres_move_guard_ptr_safe) apply csymbr apply (rule ccorres_move_c_guard_cte) \<comment> \<open>--- instruction y \<leftarrow> updateMDB slot (\<lambda>a. nullMDBNode);\<close> apply (ctac (no_vcg) pre: ccorres_move_guard_ptr_safe add: ccorres_updateMDB_const [unfolded const_def]) \<comment> \<open>the post_cap_deletion case\<close> apply (ctac(no_vcg) add: postCapDeletion_ccorres [unfolded dc_def]) \<comment> \<open>Haskell pre/post for y \<leftarrow> updateMDB slot (\<lambda>a. nullMDBNode);\<close> apply wp \<comment> \<open>C pre/post for y \<leftarrow> updateMDB slot (\<lambda>a. nullMDBNode);\<close> apply simp \<comment> \<open>C pre/post for the 2nd CALL\<close> \<comment> \<open>Haskell pre/post for y \<leftarrow> updateCap slot capability.NullCap;\<close> apply wp \<comment> \<open>C pre/post for y \<leftarrow> updateCap slot capability.NullCap;\<close> apply (simp add: Collect_const_mem cmdbnode_relation_def mdb_node_to_H_def nullMDBNode_def false_def) \<comment> \<open>Haskell pre/post for the two nested updates\<close> apply wp \<comment> \<open>C pre/post for the two nested updates\<close> apply (simp add: Collect_const_mem ccap_relation_NullCap_iff) \<comment> \<open>Haskell pre/post for (updateMDB (mdbPrev rva) (mdbNext_update (\<lambda>_. mdbNext rva)))\<close> apply (simp, wp) \<comment> \<open>C pre/post for (updateMDB (mdbPrev rva) (mdbNext_update (\<lambda>_. mdbNext rva)))\<close> apply simp+ apply vcg apply (rule conseqPre, vcg) apply clarsimp apply simp apply (wp hoare_vcg_all_lift hoare_vcg_imp_lift) \<comment> \<open>final precondition proof\<close> apply (clarsimp simp: typ_heap_simps Collect_const_mem cte_wp_at_ctes_of) apply (rule conjI) \<comment> \<open>Haskell side\<close> apply (simp add: is_aligned_3_prev is_aligned_3_next) \<comment> \<open>C side\<close> apply (clarsimp simp: map_comp_Some_iff typ_heap_simps) apply (subst cap_get_tag_isCap) apply (rule ccte_relation_ccap_relation) apply (simp add: ccte_relation_def c_valid_cte_def cl_valid_cte_def c_valid_cap_def) apply simp done (************************************************************************) (* *) (* capSwapForDelete_ccorres *********************************************) (* *) (************************************************************************) lemma ccorres_return_void_C: "ccorres dc xfdc \<top> UNIV (SKIP # hs) (return rv) (return_void_C)" apply (rule ccorres_from_vcg_throws) apply (simp add: return_def) apply (rule allI, rule conseqPre) apply vcg apply simp done declare Collect_const [simp del] lemma capSwapForDelete_ccorres: "ccorres dc xfdc (valid_mdb' and pspace_aligned') (UNIV \<inter> {s. slot1_' s = Ptr slot1} \<inter> {s. slot2_' s = Ptr slot2}) [] (capSwapForDelete slot1 slot2) (Call capSwapForDelete_'proc)" apply (cinit lift: slot1_' slot2_' simp del: return_bind) \<comment> \<open>***Main goal***\<close> \<comment> \<open>--- instruction: when (slot1 \<noteq> slot2) \<dots> / IF Ptr slot1 = Ptr slot2 THEN \<dots>\<close> apply (simp add:when_def) apply (rule ccorres_if_cond_throws2 [where Q = \<top> and Q' = \<top>]) apply (case_tac "slot1=slot2", simp+) apply (rule ccorres_return_void_C [simplified dc_def]) \<comment> \<open>***Main goal***\<close> \<comment> \<open>--- ccorres goal with 2 affectations (cap1 and cap2) on both on Haskell and C\<close> \<comment> \<open>--- \<Longrightarrow> execute each part independently\<close> apply (simp add: liftM_def cong: call_ignore_cong) apply (rule ccorres_pre_getCTE)+ apply (rule ccorres_move_c_guard_cte, rule ccorres_symb_exec_r)+ \<comment> \<open>***Main goal***\<close> apply (ctac (no_vcg) add: cteSwap_ccorres [unfolded dc_def] ) \<comment> \<open>C Hoare triple for \<acute>cap2 :== \<dots>\<close> apply vcg \<comment> \<open>C existential Hoare triple for \<acute>cap2 :== \<dots>\<close> apply simp apply (rule conseqPre) apply vcg apply simp \<comment> \<open>C Hoare triple for \<acute>cap1 :== \<dots>\<close> apply vcg \<comment> \<open>C existential Hoare triple for \<acute>cap1 :== \<dots>\<close> apply simp apply (rule conseqPre) apply vcg apply simp \<comment> \<open>Hoare triple for return_void\<close> apply vcg \<comment> \<open>***Generalized preconditions***\<close> apply simp apply (clarsimp simp: cte_wp_at_ctes_of map_comp_Some_iff typ_heap_simps ccap_relation_def) apply (simp add: cl_valid_cte_def c_valid_cap_def) done declare Collect_const [simp add] (************************************************************************) (* *) (* Arch_sameRegionAs_ccorres ********************************************) (* *) (************************************************************************) lemma cap_get_tag_PageCap_small_frame: "ccap_relation cap cap' \<Longrightarrow> (cap_get_tag cap' = scast cap_small_frame_cap) = (cap = capability.ArchObjectCap (PageCap (to_bool ((cap_small_frame_cap_CL.capFIsDevice_CL (cap_small_frame_cap_lift cap')))) (cap_small_frame_cap_CL.capFBasePtr_CL (cap_small_frame_cap_lift cap')) (vmrights_to_H (cap_small_frame_cap_CL.capFVMRights_CL (cap_small_frame_cap_lift cap'))) vmpage_size.ARMSmallPage (if cap_small_frame_cap_CL.capFMappedASIDHigh_CL (cap_small_frame_cap_lift cap') = 0 \<and> cap_small_frame_cap_CL.capFMappedASIDLow_CL (cap_small_frame_cap_lift cap') = 0 then None else Some ((cap_small_frame_cap_CL.capFMappedASIDHigh_CL (cap_small_frame_cap_lift cap') << asid_low_bits) + cap_small_frame_cap_CL.capFMappedASIDLow_CL (cap_small_frame_cap_lift cap'), cap_small_frame_cap_CL.capFMappedAddress_CL (cap_small_frame_cap_lift cap')))))" apply (rule iffI) apply (erule ccap_relationE) apply (clarsimp simp add: cap_lifts cap_to_H_def Let_def split: if_split) apply (simp add: cap_get_tag_isCap isCap_simps pageSize_def) done lemma cap_get_tag_PageCap_frame: "ccap_relation cap cap' \<Longrightarrow> (cap_get_tag cap' = scast cap_frame_cap) = (cap = capability.ArchObjectCap (PageCap (to_bool (cap_frame_cap_CL.capFIsDevice_CL (cap_frame_cap_lift cap'))) (cap_frame_cap_CL.capFBasePtr_CL (cap_frame_cap_lift cap')) (vmrights_to_H (cap_frame_cap_CL.capFVMRights_CL (cap_frame_cap_lift cap'))) (framesize_to_H (capFSize_CL (cap_frame_cap_lift cap'))) (if cap_frame_cap_CL.capFMappedASIDHigh_CL (cap_frame_cap_lift cap') = 0 \<and> cap_frame_cap_CL.capFMappedASIDLow_CL (cap_frame_cap_lift cap') = 0 then None else Some ((cap_frame_cap_CL.capFMappedASIDHigh_CL (cap_frame_cap_lift cap') << asid_low_bits) + cap_frame_cap_CL.capFMappedASIDLow_CL (cap_frame_cap_lift cap'), cap_frame_cap_CL.capFMappedAddress_CL (cap_frame_cap_lift cap')))))" apply (rule iffI) apply (erule ccap_relationE) apply (clarsimp simp add: cap_lifts cap_to_H_def Let_def split: if_split) apply (simp add: cap_get_tag_isCap isCap_simps pageSize_def) done lemma is_aligned_small_frame_cap_lift: "cap_get_tag cap = scast cap_small_frame_cap \<Longrightarrow> is_aligned (cap_small_frame_cap_CL.capFBasePtr_CL (cap_small_frame_cap_lift cap)) 12" by (simp add: cap_small_frame_cap_lift_def cap_lift_small_frame_cap) lemma fff_is_pageBits: "(0xFFF :: word32) = 2 ^ pageBits - 1" by (simp add: pageBits_def) (* used? *) lemma valid_cap'_PageCap_is_aligned: "valid_cap' (ArchObjectCap (arch_capability.PageCap d w r sz option)) t \<Longrightarrow> is_aligned w (pageBitsForSize sz)" apply (simp add: valid_cap'_def capAligned_def) done lemma gen_framesize_to_H_is_framesize_to_H_if_not_ARMSmallPage: " c\<noteq>scast Kernel_C.ARMSmallPage \<Longrightarrow>gen_framesize_to_H c = framesize_to_H c" by (simp add: gen_framesize_to_H_def framesize_to_H_def) lemma Arch_sameRegionAs_spec: "\<forall>capa capb. \<Gamma> \<turnstile> \<lbrace> ccap_relation (ArchObjectCap capa) \<acute>cap_a \<and> ccap_relation (ArchObjectCap capb) \<acute>cap_b \<rbrace> Call Arch_sameRegionAs_'proc \<lbrace> \<acute>ret__unsigned_long = from_bool (Arch.sameRegionAs capa capb) \<rbrace>" supply if_cong[cong] apply vcg apply clarsimp apply (simp add: if_then_1_else_0 cong: imp_cong conj_cong) apply (simp add: ARM_HYP_H.sameRegionAs_def) subgoal for capa capb cap_b cap_a apply (cases capa; simp add: cap_get_tag_isCap_unfolded_H_cap isCap_simps) (* FIXME: add 1 indent, 1 extra VCPU goal appeared *) \<comment> \<open>capa is ASIDPoolCap\<close> apply (cases capb; simp add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs from_bool_def false_def) \<comment> \<open>capb is also ASIDPoolCap\<close> apply (frule cap_get_tag_isCap_unfolded_H_cap(13)[where cap'=cap_a]) apply (frule cap_get_tag_isCap_unfolded_H_cap(13)[where cap'=cap_b]) apply (frule cap_get_tag_isCap_unfolded_H_cap) apply (simp add: ccap_relation_def map_option_case) apply (simp add: cap_asid_pool_cap_lift) apply (simp add: cap_to_H_def) apply (cases "capASIDPool_CL (cap_asid_pool_cap_lift cap_a) = capASIDPool_CL (cap_asid_pool_cap_lift cap_b)"; simp) \<comment> \<open>capb is ASIDControlCap\<close> subgoal for \<dots> vmpage_size option apply clarsimp apply (cases "vmpage_size=ARMSmallPage") apply (frule cap_get_tag_isCap_unfolded_H_cap(16)[where cap'=cap_b], assumption, simp add: cap_tag_defs) apply (frule cap_get_tag_isCap_unfolded_H_cap(17)[where cap'=cap_b], assumption, simp add: cap_tag_defs) done \<comment> \<open>capa is ASIDControlCap\<close> apply (cases capb; simp add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs from_bool_def false_def true_def) \<comment> \<open>capb is PageCap\<close> subgoal for \<dots> vmpage_size option apply (case_tac "vmpage_size=ARMSmallPage") apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(16), assumption, simp add: cap_tag_defs) apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(17), assumption, simp add: cap_tag_defs) done \<comment> \<open>capa is PageCap\<close> subgoal for \<dots> vmpage_size option apply (cases "vmpage_size=ARMSmallPage") \<comment> \<open>capa is a small frame\<close> apply (frule cap_get_tag_isCap_unfolded_H_cap(16)[where cap' = cap_a], assumption) apply (cases capb; simp add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs from_bool_def false_def true_def) \<comment> \<open>capb is PageCap\<close> subgoal for \<dots> vmpage_sizea optiona apply (cases "vmpage_sizea=ARMSmallPage") \<comment> \<open>capb is a small frame\<close> apply (frule cap_get_tag_isCap_unfolded_H_cap(16)[where cap'=cap_b], assumption, simp add: cap_tag_defs) apply (intro conjI) apply (simp add:Kernel_C.ARMSmallPage_def) apply (simp add: gen_framesize_to_H_def) apply (simp add:Kernel_C.ARMSmallPage_def) apply (simp add: gen_framesize_to_H_def) apply (simp add: Let_def) apply (simp add: cap_get_tag_PageCap_small_frame [unfolded cap_tag_defs, simplified]) apply (thin_tac "ccap_relation x cap_b" for x) apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(16)[simplified], simp) apply (simp add: cap_get_tag_PageCap_small_frame) apply (thin_tac "ccap_relation x cap_a" for x) apply clarsimp apply (simp add: if_0_1_eq) apply (simp add: Kernel_C.ARMSmallPage_def gen_framesize_to_H_def) apply (simp add: field_simps) \<comment> \<open>capb is a frame\<close> apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(17), assumption, simp add: cap_tag_defs) apply (intro conjI) apply (simp add:Kernel_C.ARMSmallPage_def) apply (simp add: gen_framesize_to_H_def) subgoal by (simp add:cap_frame_cap_lift_def cap_lift_def cap_tag_defs mask_def word_bw_assocs) apply (simp add: pageBitsForSize_def) apply (cases "gen_framesize_to_H (capFSize_CL (cap_frame_cap_lift cap_b))"; simp) apply (subgoal_tac "capFSize_CL (cap_frame_cap_lift cap_b) \<noteq> scast Kernel_C.ARMSmallPage") prefer 2 apply (drule ccap_relation_c_valid_cap[where c'= cap_b]) apply (simp add: cap_frame_cap_lift [unfolded cap_tag_defs, simplified]) apply (simp add: c_valid_cap_def cl_valid_cap_def) apply (simp add: Let_def) apply (simp add: cap_get_tag_PageCap_frame [unfolded cap_tag_defs, simplified]) apply (thin_tac "ccap_relation x cap_b" for x) apply (frule cap_get_tag_isCap_unfolded_H_cap(16)[simplified, where cap'=cap_a], simp) apply (simp add: cap_get_tag_PageCap_small_frame) apply (thin_tac "ccap_relation x cap_a" for x) apply clarsimp apply (simp add: if_0_1_eq) apply (cut_tac x="(pageBitsForSize (gen_framesize_to_H (capFSize_CL (cap_frame_cap_lift cap_b))))" in unat_of_nat32) apply (simp add: pageBitsForSize_def) apply (case_tac "gen_framesize_to_H (capFSize_CL (cap_frame_cap_lift cap_b))", simp_all add: word_bits_def)[1] apply clarsimp apply (simp add: gen_framesize_to_H_is_framesize_to_H_if_not_ARMSmallPage) apply (simp add: Kernel_C.ARMSmallPage_def gen_framesize_to_H_def) by (simp add: field_simps) \<comment> \<open>capa is a frame\<close> apply (frule cap_get_tag_isCap_unfolded_H_cap(17)[where cap' = cap_a], assumption) apply (subgoal_tac "capFSize_CL (cap_frame_cap_lift cap_a) && mask 2 = capFSize_CL (cap_frame_cap_lift cap_a)") prefer 2 subgoal by (simp add:cap_frame_cap_lift_def cap_lift_def cap_tag_defs mask_def word_bw_assocs) apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(17)[simplified], simp) apply (subgoal_tac "capFSize_CL (cap_frame_cap_lift cap_a) \<noteq> scast Kernel_C.ARMSmallPage") prefer 2 apply (drule_tac c'=cap_a in ccap_relation_c_valid_cap) apply (simp add: cap_frame_cap_lift) apply (simp add: c_valid_cap_def cl_valid_cap_def) apply (cases capb; simp add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs from_bool_def false_def true_def) \<comment> \<open>capb is PageCap\<close> subgoal for \<dots> vmpage_sizea optiona apply (cases "vmpage_sizea=ARMSmallPage") \<comment> \<open>capb is a small frame\<close> apply (frule cap_get_tag_isCap_unfolded_H_cap(16)[where cap'=cap_b], assumption, simp add: cap_tag_defs) apply (simp add: Let_def) apply (intro conjI) apply (simp add: pageBitsForSize_def) apply (cases "gen_framesize_to_H (capFSize_CL (cap_frame_cap_lift cap_a))"; simp) apply (simp add: mask_def Kernel_C.ARMSmallPage_def) apply (simp add: Kernel_C.ARMSmallPage_def gen_framesize_to_H_def) apply (frule cap_get_tag_isCap_unfolded_H_cap(17)[simplified, where cap'=cap_a], simp) apply (simp add: cap_tag_defs) apply (simp add: cap_get_tag_PageCap_small_frame [unfolded cap_tag_defs, simplified]) apply (simp add: cap_get_tag_PageCap_frame [unfolded cap_tag_defs, simplified]) apply (clarsimp simp: if_distrib [where f=scast]) apply (thin_tac "ccap_relation x y" for x y)+ apply (simp add: if_0_1_eq) apply (cut_tac x="(pageBitsForSize (gen_framesize_to_H (capFSize_CL (cap_frame_cap_lift cap_a))))" in unat_of_nat32) apply (simp add: pageBitsForSize_def) apply (cases "gen_framesize_to_H (capFSize_CL (cap_frame_cap_lift cap_a))"; simp add: word_bits_def) apply clarsimp apply (simp add: gen_framesize_to_H_is_framesize_to_H_if_not_ARMSmallPage) apply (simp add: Kernel_C.ARMSmallPage_def gen_framesize_to_H_def) apply (simp add: field_simps) \<comment> \<open>capb is a frame\<close> apply (frule cap_get_tag_isCap_unfolded_H_cap(17)[where cap'=cap_b], assumption, simp add: cap_tag_defs) apply (subgoal_tac "capFSize_CL (cap_frame_cap_lift cap_b) \<noteq> scast Kernel_C.ARMSmallPage") prefer 2 apply (drule ccap_relation_c_valid_cap [unfolded cap_tag_defs, where c'=cap_b]) apply (simp add: cap_frame_cap_lift [unfolded cap_tag_defs, simplified]) apply (simp add: c_valid_cap_def cl_valid_cap_def) apply (frule cap_get_tag_isCap_unfolded_H_cap(17)[simplified, where cap'=cap_a], simp) apply (simp add: cap_tag_defs) apply (drule (1) iffD1 [OF cap_get_tag_PageCap_frame [unfolded cap_tag_defs, simplified]])+ apply clarify apply (intro conjI) apply (simp add: pageBitsForSize_def) apply (cases "gen_framesize_to_H (capFSize_CL (cap_frame_cap_lift cap_a))"; simp) subgoal by (simp add: cap_frame_cap_lift_def cap_lift_def cap_tag_defs mask_def word_bw_assocs) apply (simp add: pageBitsForSize_def) apply (case_tac "gen_framesize_to_H (capFSize_CL (cap_frame_cap_lift cap_b))"; simp) apply (simp add: Let_def) apply (simp add: if_0_1_eq if_distrib [where f=scast]) apply (cut_tac x="(pageBitsForSize (gen_framesize_to_H (capFSize_CL (cap_frame_cap_lift cap_a))))" in unat_of_nat32) apply (simp add: pageBitsForSize_def) apply (cases "gen_framesize_to_H (capFSize_CL (cap_frame_cap_lift cap_a))"; simp add: word_bits_def) apply clarsimp apply (cut_tac x="(pageBitsForSize (gen_framesize_to_H (capFSize_CL (cap_frame_cap_lift cap_b))))" in unat_of_nat32) apply (simp add: pageBitsForSize_def) apply (cases "gen_framesize_to_H (capFSize_CL (cap_frame_cap_lift cap_b))"; simp add: word_bits_def) apply clarsimp apply (simp add: gen_framesize_to_H_is_framesize_to_H_if_not_ARMSmallPage) by (simp add: field_simps) done \<comment> \<open>capa is PageTableCap\<close> apply (cases capb; simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs from_bool_def false_def true_def) \<comment> \<open>capb is PageCap\<close> subgoal for \<dots> vmpage_size option apply (cases "vmpage_size=ARMSmallPage") apply (frule cap_get_tag_isCap_unfolded_H_cap(16)[where cap'=cap_b], assumption, simp add: cap_tag_defs) by (frule cap_get_tag_isCap_unfolded_H_cap(17)[where cap'=cap_b], assumption, simp add: cap_tag_defs) \<comment> \<open>capb is a PageTableCap\<close> subgoal apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(14)) apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(14)) apply (frule cap_get_tag_isCap_unfolded_H_cap) apply (simp add: ccap_relation_def map_option_case) apply (simp add: cap_page_table_cap_lift) apply (simp add: cap_to_H_def) by (cases "capPTBasePtr_CL (cap_page_table_cap_lift cap_a) = capPTBasePtr_CL (cap_page_table_cap_lift cap_b)"; simp) \<comment> \<open>capa is PageDirectoryCap\<close> apply (cases capb; simp add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs from_bool_def false_def true_def) \<comment> \<open>capb is PageCap\<close> subgoal for \<dots> vmpage_size option apply (cases "vmpage_size=ARMSmallPage") apply (frule cap_get_tag_isCap_unfolded_H_cap(16)[where cap'=cap_b], assumption, simp add: cap_tag_defs) by (frule cap_get_tag_isCap_unfolded_H_cap(17)[where cap'=cap_b], assumption, simp add: cap_tag_defs) \<comment> \<open>capb is a PageDirectoryCap\<close> subgoal apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(15)) apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(15)) apply (frule cap_get_tag_isCap_unfolded_H_cap) apply (simp add: ccap_relation_def map_option_case) apply (simp add: cap_page_directory_cap_lift) apply (simp add: cap_to_H_def) by (cases "capPDBasePtr_CL (cap_page_directory_cap_lift cap_a) = capPDBasePtr_CL (cap_page_directory_cap_lift cap_b)"; simp) \<comment> \<open>capa is VCPUCap\<close> apply (cases capb; simp add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs from_bool_def false_def true_def) \<comment> \<open>capb is PageCap\<close> subgoal for \<dots> vmpage_size option apply (cases "vmpage_size=ARMSmallPage") apply (frule cap_get_tag_isCap_unfolded_H_cap(16)[where cap'=cap_b], assumption, simp add: cap_tag_defs) by (frule cap_get_tag_isCap_unfolded_H_cap(17)[where cap'=cap_b], assumption, simp add: cap_tag_defs) \<comment> \<open>capb is VCPUCap\<close> subgoal apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(20)) apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(20)) apply (frule cap_get_tag_isCap_unfolded_H_cap) apply (simp add: ccap_relation_def map_option_case) apply (simp add: cap_vcpu_cap_lift) apply (simp add: cap_to_H_def) by (cases "capVCPUPtr_CL (cap_vcpu_cap_lift cap_a) = capVCPUPtr_CL (cap_vcpu_cap_lift cap_b)"; simp) done done definition generic_frame_cap_get_capFSize_CL :: "cap_CL option \<Rightarrow> word32" where "generic_frame_cap_get_capFSize_CL \<equiv> \<lambda>cap. case cap of Some (Cap_small_frame_cap c) \<Rightarrow> scast Kernel_C.ARMSmallPage | Some (Cap_frame_cap c) \<Rightarrow> cap_frame_cap_CL.capFSize_CL c | Some _ \<Rightarrow> 0" lemma generic_frame_cap_get_capFSize_spec: "\<forall>s. \<Gamma> \<turnstile> \<lbrace>s. cap_get_tag \<acute>cap = scast cap_small_frame_cap \<or> cap_get_tag \<acute>cap = scast cap_frame_cap\<rbrace> \<acute>ret__unsigned_long :== PROC generic_frame_cap_get_capFSize(\<acute>cap) \<lbrace>\<acute>ret__unsigned_long = generic_frame_cap_get_capFSize_CL (cap_lift \<^bsup>s\<^esup>cap)\<rbrace>" apply vcg apply (clarsimp simp: generic_frame_cap_get_capFSize_CL_def) apply (intro conjI impI) apply (clarsimp simp: cap_lift_small_frame_cap cap_small_frame_cap_lift_def) apply (clarsimp simp: cap_lift_frame_cap cap_frame_cap_lift_def) apply (clarsimp simp: cap_lifts [THEN sym]) done definition generic_frame_cap_get_capFBasePtr_CL :: "cap_CL option \<Rightarrow> word32" where "generic_frame_cap_get_capFBasePtr_CL \<equiv> \<lambda>cap. case cap of Some (Cap_small_frame_cap c) \<Rightarrow> cap_small_frame_cap_CL.capFBasePtr_CL c | Some (Cap_frame_cap c) \<Rightarrow> cap_frame_cap_CL.capFBasePtr_CL c | Some _ \<Rightarrow> 0" lemma generic_frame_cap_get_capFBasePtr_spec: "\<forall>s. \<Gamma> \<turnstile> \<lbrace>s. cap_get_tag \<acute>cap = scast cap_small_frame_cap \<or> cap_get_tag \<acute>cap = scast cap_frame_cap\<rbrace> \<acute>ret__unsigned_long :== PROC generic_frame_cap_get_capFBasePtr(\<acute>cap) \<lbrace>\<acute>ret__unsigned_long = generic_frame_cap_get_capFBasePtr_CL (cap_lift \<^bsup>s\<^esup>cap)\<rbrace>" apply vcg apply (clarsimp simp: generic_frame_cap_get_capFBasePtr_CL_def) apply (intro conjI impI) apply (clarsimp simp: cap_lift_small_frame_cap cap_small_frame_cap_lift_def) apply (clarsimp simp: cap_lift_frame_cap cap_frame_cap_lift_def) apply (clarsimp simp: cap_lifts [THEN sym]) done definition "generic_frame_cap_get_capFIsDevice_CL \<equiv> \<lambda>cap. case cap of Some (Cap_small_frame_cap c) \<Rightarrow> cap_small_frame_cap_CL.capFIsDevice_CL c | Some (Cap_frame_cap c) \<Rightarrow> cap_frame_cap_CL.capFIsDevice_CL c | Some _ \<Rightarrow> 0 | None \<Rightarrow> 0" lemma generic_frame_cap_get_capFIsDevice_spec: "\<forall>s. \<Gamma> \<turnstile> \<lbrace>s. cap_get_tag \<acute>cap = scast cap_small_frame_cap \<or> cap_get_tag \<acute>cap = scast cap_frame_cap\<rbrace> \<acute>ret__unsigned_long :== PROC generic_frame_cap_get_capFIsDevice(\<acute>cap) \<lbrace>\<acute>ret__unsigned_long = generic_frame_cap_get_capFIsDevice_CL (cap_lift \<^bsup>s\<^esup>cap)\<rbrace>" apply (rule allI, rule conseqPre, vcg) apply (clarsimp simp: generic_frame_cap_get_capFIsDevice_CL_def) apply (intro conjI impI) apply (clarsimp simp: cap_lift_small_frame_cap cap_small_frame_cap_lift_def) apply (clarsimp simp: cap_lift_frame_cap cap_frame_cap_lift_def) apply (clarsimp simp: cap_lifts [THEN sym]) by (clarsimp simp: generic_frame_cap_get_capFIsDevice_CL_def cap_lift_small_frame_cap cap_lift_frame_cap cap_small_frame_cap_lift_def cap_frame_cap_lift_def) definition "generic_frame_cap_get_capFVMRights_CL \<equiv> \<lambda>cap. case cap of Some (Cap_small_frame_cap c) \<Rightarrow> cap_small_frame_cap_CL.capFVMRights_CL c | Some (Cap_frame_cap c) \<Rightarrow> cap_frame_cap_CL.capFVMRights_CL c | Some _ \<Rightarrow> 0 | None \<Rightarrow> 0" lemma generic_frame_cap_get_capFVMRights_spec: "\<forall>s. \<Gamma> \<turnstile> {s} Call generic_frame_cap_get_capFVMRights_'proc {t. ret__unsigned_long_' t = generic_frame_cap_get_capFVMRights_CL (cap_lift (cap_' s))}" apply (rule allI, rule conseqPre, vcg) apply (clarsimp simp: generic_frame_cap_get_capFVMRights_CL_def cap_lift_small_frame_cap cap_lift_frame_cap cap_small_frame_cap_lift_def cap_frame_cap_lift_def) by (simp add: cap_lift_def Let_def Kernel_C.VMNoAccess_def split: if_split) (* combination of cap_get_capSizeBits + cap_get_archCapSizeBits from C *) definition get_capSizeBits_CL :: "cap_CL option \<Rightarrow> nat" where "get_capSizeBits_CL \<equiv> \<lambda>cap. case cap of Some (Cap_untyped_cap c) \<Rightarrow> unat (cap_untyped_cap_CL.capBlockSize_CL c) | Some (Cap_endpoint_cap c) \<Rightarrow> 4 | Some (Cap_notification_cap c) \<Rightarrow> 4 | Some (Cap_cnode_cap c) \<Rightarrow> unat (capCNodeRadix_CL c) + 4 | Some (Cap_thread_cap c) \<Rightarrow> 9 | Some (Cap_small_frame_cap c) \<Rightarrow> 12 | Some (Cap_frame_cap c) \<Rightarrow> pageBitsForSize (gen_framesize_to_H $ generic_frame_cap_get_capFSize_CL cap) | Some (Cap_page_table_cap c) \<Rightarrow> 12 | Some (Cap_page_directory_cap c) \<Rightarrow> 14 | Some (Cap_asid_pool_cap c) \<Rightarrow> 12 | Some (Cap_zombie_cap c) \<Rightarrow> let type = cap_zombie_cap_CL.capZombieType_CL c in if isZombieTCB_C type then 9 else unat (type && mask 5) + 4 | Some (Cap_vcpu_cap c) \<Rightarrow> 12 | _ \<Rightarrow> 0" lemma frame_cap_size [simp]: "cap_get_tag cap = scast cap_frame_cap \<Longrightarrow> cap_frame_cap_CL.capFSize_CL (cap_frame_cap_lift cap) && mask 2 = cap_frame_cap_CL.capFSize_CL (cap_frame_cap_lift cap)" apply (simp add: cap_frame_cap_lift_def) by (simp add: cap_lift_def cap_tag_defs mask_def word_bw_assocs) lemma generic_frame_cap_size[simp]: "cap_get_tag cap = scast cap_frame_cap \<or> cap_get_tag cap = scast cap_small_frame_cap \<Longrightarrow> generic_frame_cap_get_capFSize_CL (cap_lift cap) && mask 2 = generic_frame_cap_get_capFSize_CL (cap_lift cap)" apply (simp add: generic_frame_cap_get_capFSize_CL_def) apply (erule disjE) subgoal by (simp add: cap_lift_def cap_tag_defs mask_def word_bw_assocs) by (simp add: cap_lift_def cap_tag_defs mask_def Kernel_C.ARMSmallPage_def) lemma cap_get_capSizeBits_spec: "\<forall>s. \<Gamma> \<turnstile> {s} \<acute>ret__unsigned_long :== PROC cap_get_capSizeBits(\<acute>cap) \<lbrace>\<acute>ret__unsigned_long = of_nat (get_capSizeBits_CL (cap_lift \<^bsup>s\<^esup>cap))\<rbrace>" apply vcg apply (clarsimp simp: get_capSizeBits_CL_def) apply (intro conjI impI) apply (clarsimp simp: cap_lifts gen_framesize_to_H_def generic_frame_cap_get_capFSize_CL_def cap_lift_asid_control_cap cap_lift_irq_control_cap cap_lift_null_cap Kernel_C.asidLowBits_def asid_low_bits_def word_sle_def Let_def mask_def isZombieTCB_C_def ZombieTCB_C_def cap_lift_domain_cap cap_lift_vcpu_cap dest!: sym [where t = "cap_get_tag cap" for cap])+ (* slow *) by (case_tac "cap_lift cap", simp_all, case_tac "a", auto simp: cap_lift_def cap_tag_defs Let_def cap_small_frame_cap_lift_def cap_frame_cap_lift_def cap_endpoint_cap_lift_def cap_notification_cap_lift_def cap_cnode_cap_lift_def cap_thread_cap_lift_def cap_zombie_cap_lift_def cap_page_table_cap_lift_def cap_page_directory_cap_lift_def cap_asid_pool_cap_lift_def cap_vcpu_cap_lift_def cap_untyped_cap_lift_def split: if_split_asm) lemma ccap_relation_get_capSizeBits_physical: notes unfolds = ccap_relation_def get_capSizeBits_CL_def cap_lift_def cap_tag_defs cap_to_H_def objBits_simps' Let_def field_simps mask_def asid_low_bits_def ARM_HYP_H.capUntypedSize_def machine_bits_defs shows "\<lbrakk> ccap_relation hcap ccap; capClass hcap = PhysicalClass; capAligned hcap \<rbrakk> \<Longrightarrow> 2 ^ get_capSizeBits_CL (cap_lift ccap) = capUntypedSize hcap" apply (case_tac hcap, simp_all) defer 4 (* zombie caps second last *) defer 4 (* arch caps last *) apply ((frule cap_get_tag_isCap_unfolded_H_cap, clarsimp simp: unfolds split: if_split_asm)+)[5] (* SOMEONE FIX SUBGOAL PLZ *) apply (frule cap_get_tag_isCap_unfolded_H_cap) apply (clarsimp simp: unfolds split: if_split_asm) apply (rule arg_cong [OF less_mask_eq[where n=5, unfolded mask_def, simplified]]) apply (simp add: capAligned_def objBits_simps word_bits_conv word_less_nat_alt) subgoal for arch_capability apply (cases arch_capability; simp) defer 2 (* page caps last *) apply (fold_subgoals (prefix))[4] subgoal premises prems by ((frule cap_get_tag_isCap_unfolded_H_cap, clarsimp simp: unfolds split: if_split_asm)+) apply (rename_tac vmpage_size option) apply (case_tac "vmpage_size = ARMSmallPage", simp_all) apply (frule cap_get_tag_isCap_unfolded_H_cap(16), simp) subgoal by (clarsimp simp: unfolds split: if_split_asm) by (frule cap_get_tag_isCap_unfolded_H_cap(17), simp, clarsimp simp: unfolds pageBitsForSize_spec gen_framesize_to_H_def c_valid_cap_def cl_valid_cap_def framesize_to_H_def generic_frame_cap_get_capFSize_CL_def split: if_split_asm)+ done lemma ccap_relation_get_capSizeBits_untyped: "\<lbrakk> ccap_relation (UntypedCap d word bits idx) ccap \<rbrakk> \<Longrightarrow> get_capSizeBits_CL (cap_lift ccap) = bits" apply (frule cap_get_tag_isCap_unfolded_H_cap) by (clarsimp simp: get_capSizeBits_CL_def ccap_relation_def map_option_case cap_to_H_def cap_lift_def cap_tag_defs) definition get_capZombieBits_CL :: "cap_zombie_cap_CL \<Rightarrow> word32" where "get_capZombieBits_CL \<equiv> \<lambda>cap. let type = cap_zombie_cap_CL.capZombieType_CL cap in if isZombieTCB_C type then 4 else type && mask 5" lemma get_capSizeBits_valid_shift: "\<lbrakk> ccap_relation hcap ccap; capAligned hcap \<rbrakk> \<Longrightarrow> get_capSizeBits_CL (cap_lift ccap) < 32" unfolding get_capSizeBits_CL_def apply (cases hcap; simp add: cap_get_tag_isCap_unfolded_H_cap cap_lift_def cap_tag_defs) (* zombie *) apply (clarsimp simp: Let_def split: if_split) apply (frule cap_get_tag_isCap_unfolded_H_cap) apply (clarsimp simp: ccap_relation_def map_option_Some_eq2 cap_lift_zombie_cap cap_to_H_def Let_def capAligned_def objBits_simps' word_bits_conv) apply (subst less_mask_eq, simp add: word_less_nat_alt, assumption) (* arch *) apply (rename_tac arch_capability) apply (case_tac arch_capability, simp_all add: cap_get_tag_isCap_unfolded_H_cap cap_lift_def cap_tag_defs asid_low_bits_def) apply (rename_tac vmpage_size option) apply (case_tac vmpage_size, simp_all add: cap_get_tag_isCap_unfolded_H_cap cap_lift_def cap_tag_defs pageBitsForSize_def) apply (clarsimp split: vmpage_size.split)+ (* untyped *) apply (frule cap_get_tag_isCap_unfolded_H_cap) apply (clarsimp simp: cap_lift_def cap_tag_defs mask_def) apply (subgoal_tac "index (cap_C.words_C ccap) 1 && 0x1F \<le> 0x1F") apply (simp add: unat_arith_simps) apply (simp add: word_and_le1) (* cnode *) apply (frule cap_get_tag_isCap_unfolded_H_cap) apply (clarsimp simp: ccap_relation_def map_option_Some_eq2 cap_lift_cnode_cap cap_to_H_def Let_def capAligned_def objBits_simps' word_bits_conv) done lemma get_capSizeBits_valid_shift_word: "\<lbrakk> ccap_relation hcap ccap; capAligned hcap \<rbrakk> \<Longrightarrow> of_nat (get_capSizeBits_CL (cap_lift ccap)) < (0x20::word32)" apply (subgoal_tac "of_nat (get_capSizeBits_CL (cap_lift ccap)) < (of_nat 32::word32)", simp) apply (rule of_nat_mono_maybe, simp+) apply (simp add: get_capSizeBits_valid_shift) done lemma cap_zombie_cap_get_capZombieBits_spec: "\<forall>s. \<Gamma> \<turnstile> \<lbrace>s. cap_get_tag \<acute>cap = scast cap_zombie_cap \<rbrace> \<acute>ret__unsigned_long :== PROC cap_zombie_cap_get_capZombieBits(\<acute>cap) \<lbrace>\<acute>ret__unsigned_long = get_capZombieBits_CL (cap_zombie_cap_lift \<^bsup>s\<^esup>cap)\<rbrace>" apply vcg apply (clarsimp simp: get_capZombieBits_CL_def word_sle_def mask_def isZombieTCB_C_def ZombieTCB_C_def Let_def) done definition get_capZombiePtr_CL :: "cap_zombie_cap_CL \<Rightarrow> word32" where "get_capZombiePtr_CL \<equiv> \<lambda>cap. let radix = unat (get_capZombieBits_CL cap) in cap_zombie_cap_CL.capZombieID_CL cap && ~~ (mask (radix+1))" lemma cap_zombie_cap_get_capZombiePtr_spec: "\<forall>s. \<Gamma> \<turnstile> \<lbrace>s. cap_get_tag \<acute>cap = scast cap_zombie_cap \<and> get_capZombieBits_CL (cap_zombie_cap_lift \<acute>cap) < 0x1F \<rbrace> \<acute>ret__unsigned_long :== PROC cap_zombie_cap_get_capZombiePtr(\<acute>cap) \<lbrace>\<acute>ret__unsigned_long = get_capZombiePtr_CL (cap_zombie_cap_lift \<^bsup>s\<^esup>cap)\<rbrace>" apply vcg apply (clarsimp simp: get_capZombiePtr_CL_def word_sle_def mask_def isZombieTCB_C_def ZombieTCB_C_def Let_def) apply (intro conjI) apply (simp add: word_add_less_mono1[where k=1 and j="0x1F", simplified]) apply (subst unat_plus_if_size) apply (clarsimp split: if_split) apply (clarsimp simp: get_capZombieBits_CL_def Let_def word_size split: if_split if_split_asm) apply (subgoal_tac "unat (capZombieType_CL (cap_zombie_cap_lift cap) && mask 5) < unat ((2::word32) ^ 5)") apply (clarsimp simp: shiftl_eq_mult) apply (rule unat_mono) apply (rule and_mask_less_size) apply (clarsimp simp: word_size) done definition get_capPtr_CL :: "cap_CL option \<Rightarrow> unit ptr" where "get_capPtr_CL \<equiv> \<lambda>cap. Ptr (case cap of Some (Cap_untyped_cap c) \<Rightarrow> cap_untyped_cap_CL.capPtr_CL c | Some (Cap_endpoint_cap c) \<Rightarrow> cap_endpoint_cap_CL.capEPPtr_CL c | Some (Cap_notification_cap c) \<Rightarrow> cap_notification_cap_CL.capNtfnPtr_CL c | Some (Cap_cnode_cap c) \<Rightarrow> cap_cnode_cap_CL.capCNodePtr_CL c | Some (Cap_thread_cap c) \<Rightarrow> (cap_thread_cap_CL.capTCBPtr_CL c && ~~ mask (objBits (undefined :: tcb))) | Some (Cap_small_frame_cap c) \<Rightarrow> cap_small_frame_cap_CL.capFBasePtr_CL c | Some (Cap_frame_cap c) \<Rightarrow> cap_frame_cap_CL.capFBasePtr_CL c | Some (Cap_page_table_cap c) \<Rightarrow> cap_page_table_cap_CL.capPTBasePtr_CL c | Some (Cap_page_directory_cap c) \<Rightarrow> cap_page_directory_cap_CL.capPDBasePtr_CL c | Some (Cap_asid_pool_cap c) \<Rightarrow> cap_asid_pool_cap_CL.capASIDPool_CL c | Some (Cap_zombie_cap c) \<Rightarrow> get_capZombiePtr_CL c | Some (Cap_vcpu_cap c) \<Rightarrow> cap_vcpu_cap_CL.capVCPUPtr_CL c | _ \<Rightarrow> 0)" lemma cap_get_capPtr_spec: "\<forall>s. \<Gamma> \<turnstile> \<lbrace>s. (cap_get_tag \<acute>cap = scast cap_zombie_cap \<longrightarrow> get_capZombieBits_CL (cap_zombie_cap_lift \<acute>cap) < 0x1F)\<rbrace> \<acute>ret__ptr_to_void :== PROC cap_get_capPtr(\<acute>cap) \<lbrace>\<acute>ret__ptr_to_void = get_capPtr_CL (cap_lift \<^bsup>s\<^esup>cap)\<rbrace>" apply vcg apply (clarsimp simp: get_capPtr_CL_def generic_frame_cap_get_capFBasePtr_CL_def) apply (intro impI conjI) apply (clarsimp simp: cap_lifts pageBitsForSize_def cap_lift_asid_control_cap word_sle_def cap_lift_irq_control_cap cap_lift_null_cap mask_def objBits_simps' cap_lift_domain_cap ptr_add_assertion_positive dest!: sym [where t = "cap_get_tag cap" for cap] split: vmpage_size.splits)+ (* XXX: slow. there should be a rule for this *) by (case_tac "cap_lift cap", simp_all, case_tac "a", auto simp: cap_lift_def cap_tag_defs Let_def cap_small_frame_cap_lift_def cap_frame_cap_lift_def cap_endpoint_cap_lift_def cap_notification_cap_lift_def cap_cnode_cap_lift_def cap_thread_cap_lift_def cap_zombie_cap_lift_def cap_page_table_cap_lift_def cap_page_directory_cap_lift_def cap_asid_pool_cap_lift_def cap_untyped_cap_lift_def cap_vcpu_cap_lift_def split: if_split_asm) definition get_capIsPhysical_CL :: "cap_CL option \<Rightarrow> bool" where "get_capIsPhysical_CL \<equiv> \<lambda>cap. (case cap of Some (Cap_untyped_cap c) \<Rightarrow> True | Some (Cap_endpoint_cap c) \<Rightarrow> True | Some (Cap_notification_cap c) \<Rightarrow> True | Some (Cap_cnode_cap c) \<Rightarrow> True | Some (Cap_thread_cap c) \<Rightarrow> True | Some (Cap_small_frame_cap c) \<Rightarrow> True | Some (Cap_frame_cap c) \<Rightarrow> True | Some (Cap_page_table_cap c) \<Rightarrow> True | Some (Cap_page_directory_cap c) \<Rightarrow> True | Some (Cap_asid_pool_cap c) \<Rightarrow> True | Some (Cap_zombie_cap c) \<Rightarrow> True | Some (Cap_vcpu_cap c) \<Rightarrow> True | _ \<Rightarrow> False)" lemma cap_get_capIsPhysical_spec: "\<forall>s. \<Gamma> \<turnstile> {s} Call cap_get_capIsPhysical_'proc \<lbrace>\<acute>ret__unsigned_long = from_bool (get_capIsPhysical_CL (cap_lift \<^bsup>s\<^esup>cap))\<rbrace>" apply vcg apply (clarsimp simp: get_capIsPhysical_CL_def) apply (intro impI conjI) apply (clarsimp simp: cap_lifts pageBitsForSize_def cap_lift_asid_control_cap word_sle_def cap_lift_irq_control_cap cap_lift_null_cap mask_def objBits_simps cap_lift_domain_cap ptr_add_assertion_positive from_bool_def true_def false_def dest!: sym [where t = "cap_get_tag cap" for cap] split: vmpage_size.splits)+ (* XXX: slow. there should be a rule for this *) by (case_tac "cap_lift cap", simp_all, case_tac a, auto simp: cap_lift_def cap_tag_defs Let_def cap_small_frame_cap_lift_def cap_frame_cap_lift_def cap_endpoint_cap_lift_def cap_notification_cap_lift_def cap_cnode_cap_lift_def cap_thread_cap_lift_def cap_zombie_cap_lift_def cap_page_table_cap_lift_def cap_page_directory_cap_lift_def cap_asid_pool_cap_lift_def cap_untyped_cap_lift_def cap_vcpu_cap_lift_def split: if_split_asm) lemma ccap_relation_get_capPtr_not_physical: "\<lbrakk> ccap_relation hcap ccap; capClass hcap \<noteq> PhysicalClass \<rbrakk> \<Longrightarrow> get_capPtr_CL (cap_lift ccap) = Ptr 0" by (clarsimp simp: ccap_relation_def get_capPtr_CL_def cap_to_H_def Let_def split: option.split cap_CL.split_asm if_split_asm) lemma ccap_relation_get_capIsPhysical: "ccap_relation hcap ccap \<Longrightarrow> isPhysicalCap hcap = get_capIsPhysical_CL (cap_lift ccap)" apply (case_tac hcap; clarsimp simp: cap_lifts cap_lift_domain_cap cap_lift_null_cap cap_lift_irq_control_cap cap_to_H_def get_capIsPhysical_CL_def dest!: cap_get_tag_isCap_unfolded_H_cap) apply (rename_tac arch_cap) apply (case_tac arch_cap; clarsimp simp: cap_lifts cap_lift_asid_control_cap dest!: cap_get_tag_isCap_unfolded_H_cap) apply (rename_tac p R sz asid) apply (case_tac sz) apply (drule (1) cap_get_tag_isCap_unfolded_H_cap(16), clarsimp simp: cap_lifts) apply (drule cap_get_tag_isCap_unfolded_H_cap(17), simp, clarsimp simp: cap_lifts)+ done lemma ctcb_ptr_to_tcb_ptr_mask': "is_aligned (ctcb_ptr_to_tcb_ptr (tcb_Ptr x)) (objBits (undefined :: tcb)) \<Longrightarrow> ctcb_ptr_to_tcb_ptr (tcb_Ptr x) = x && ~~ mask (objBits (undefined :: tcb))" apply (simp add: ctcb_ptr_to_tcb_ptr_def) apply (drule_tac d=ctcb_offset in is_aligned_add_helper) apply (simp add: objBits_simps' ctcb_offset_defs) apply simp done lemmas ctcb_ptr_to_tcb_ptr_mask = ctcb_ptr_to_tcb_ptr_mask'[simplified objBits_simps, simplified] lemma ccap_relation_get_capPtr_physical: notes unfolds = ccap_relation_def get_capPtr_CL_def cap_lift_def cap_tag_defs cap_to_H_def get_capZombiePtr_CL_def get_capZombieBits_CL_def Let_def objBits_simps capAligned_def shows "\<lbrakk> ccap_relation hcap ccap; capClass hcap = PhysicalClass; capAligned hcap \<rbrakk> \<Longrightarrow> get_capPtr_CL (cap_lift ccap) = Ptr (capUntypedPtr hcap)" apply (cases hcap; simp add: isCap_simps) defer 4 defer 4 apply ((frule cap_get_tag_isCap_unfolded_H_cap, clarsimp simp: unfolds split: if_split_asm dest!: ctcb_ptr_to_tcb_ptr_mask)+)[5] apply (frule cap_get_tag_isCap_unfolded_H_cap) apply (clarsimp simp: unfolds split: if_split_asm dest!: ctcb_ptr_to_tcb_ptr_mask) apply (rule arg_cong [OF less_mask_eq]) apply (simp add: capAligned_def word_bits_conv objBits_simps word_less_nat_alt) subgoal for arch_capability apply (cases arch_capability; simp) defer 2 (* page caps last *) apply (fold_subgoals (prefix))[4] subgoal by ((frule cap_get_tag_isCap_unfolded_H_cap, clarsimp simp: unfolds split: if_split_asm)+) defer subgoal for \<dots> vmpage_size option apply (cases "vmpage_size = ARMSmallPage"; simp?) apply (frule cap_get_tag_isCap_unfolded_H_cap(16), simp) subgoal by (clarsimp simp: unfolds split: if_split_asm) by (frule cap_get_tag_isCap_unfolded_H_cap(17), simp, clarsimp simp: unfolds cap_tag_defs cap_to_H_def split: if_split_asm)+ done done lemma ccap_relation_get_capPtr_untyped: "\<lbrakk> ccap_relation (UntypedCap d word bits idx) ccap \<rbrakk> \<Longrightarrow> get_capPtr_CL (cap_lift ccap) = Ptr word" apply (frule cap_get_tag_isCap_unfolded_H_cap) by (clarsimp simp: get_capPtr_CL_def ccap_relation_def map_option_case cap_to_H_def cap_lift_def cap_tag_defs) lemma cap_get_tag_isArchCap_unfolded_H_cap: "ccap_relation (capability.ArchObjectCap a_cap) cap' \<Longrightarrow> (isArchCap_tag (cap_get_tag cap'))" apply (frule cap_get_tag_isCap(11), simp) done lemma sameRegionAs_spec: "\<forall>capa capb. \<Gamma> \<turnstile> \<lbrace>ccap_relation capa \<acute>cap_a \<and> ccap_relation capb \<acute>cap_b \<and> capAligned capb \<and> (\<exists>s. s \<turnstile>' capa)\<rbrace> Call sameRegionAs_'proc \<lbrace> \<acute>ret__unsigned_long = from_bool (sameRegionAs capa capb) \<rbrace>" apply vcg apply clarsimp apply (simp add: sameRegionAs_def isArchCap_tag_def2) apply (case_tac capa, simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_simps) \<comment> \<open>capa is a ThreadCap\<close> apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs from_bool_def false_def)[1] apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(1)) apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(1)) apply (simp add: ccap_relation_def map_option_case) apply (simp add: cap_thread_cap_lift) apply (simp add: cap_to_H_def) apply (clarsimp simp: case_bool_If ctcb_ptr_to_tcb_ptr_def if_distrib cong: if_cong) apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap) apply (clarsimp simp: isArchCap_tag_def2) \<comment> \<open>capa is a NullCap\<close> apply (simp add: cap_tag_defs from_bool_def false_def) \<comment> \<open>capa is an NotificationCap\<close> apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs from_bool_def false_def)[1] apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(3)) apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(3)) apply (simp add: ccap_relation_def map_option_case) apply (simp add: cap_notification_cap_lift) apply (simp add: cap_to_H_def) apply (clarsimp split: if_split) apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap) apply (clarsimp simp: isArchCap_tag_def2) \<comment> \<open>capa is an IRQHandlerCap\<close> apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs from_bool_def false_def)[1] apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(5)) apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(5)) apply (simp add: ccap_relation_def map_option_case) apply (simp add: cap_irq_handler_cap_lift) apply (simp add: cap_to_H_def) apply (clarsimp simp: up_ucast_inj_eq c_valid_cap_def cl_valid_cap_def mask_twice split: if_split bool.split | intro impI conjI | simp )+ apply (drule ucast_ucast_mask_eq, simp) apply (simp add: ucast_ucast_mask) apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap) apply (clarsimp simp: isArchCap_tag_def2) \<comment> \<open>capa is an EndpointCap\<close> apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs from_bool_def false_def)[1] apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(4)) apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(4)) apply (simp add: ccap_relation_def map_option_case) apply (simp add: cap_endpoint_cap_lift) apply (simp add: cap_to_H_def) apply (clarsimp split: if_split) apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap) apply (clarsimp simp: isArchCap_tag_def2) \<comment> \<open>capa is a DomainCap\<close> apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs from_bool_def false_def true_def)[1] apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap) apply (fastforce simp: isArchCap_tag_def2 split: if_split) \<comment> \<open>capa is a Zombie\<close> apply (simp add: cap_tag_defs from_bool_def false_def) \<comment> \<open>capa is an Arch object cap\<close> apply (frule_tac cap'=cap_a in cap_get_tag_isArchCap_unfolded_H_cap) apply (clarsimp simp: isArchCap_tag_def2 cap_tag_defs linorder_not_less [THEN sym]) apply (rule conjI, clarsimp, rule impI)+ apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs from_bool_def false_def)[1] \<comment> \<open>capb is an Arch object cap\<close> apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap) apply (fastforce simp: isArchCap_tag_def2 cap_tag_defs linorder_not_less [THEN sym]) \<comment> \<open>capa is a ReplyCap\<close> apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs from_bool_def false_def)[1] apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap) apply (clarsimp simp: isArchCap_tag_def2) apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(8)) apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(8)) apply (simp add: ccap_relation_def map_option_case) apply (simp add: cap_reply_cap_lift) apply (simp add: cap_to_H_def ctcb_ptr_to_tcb_ptr_def) apply (clarsimp split: if_split) \<comment> \<open>capa is an UntypedCap\<close> apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(9)) apply (intro conjI) apply (rule impI, intro conjI) apply (rule impI, drule(1) cap_get_tag_to_H)+ apply (clarsimp simp: capAligned_def word_bits_conv objBits_simps' get_capZombieBits_CL_def Let_def word_less_nat_alt less_mask_eq true_def split: if_split_asm) apply (subgoal_tac "capBlockSize_CL (cap_untyped_cap_lift cap_a) \<le> 0x1F") apply (simp add: word_le_make_less) apply (simp add: cap_untyped_cap_lift_def cap_lift_def cap_tag_defs word_and_le1 mask_def) apply (clarsimp simp: get_capSizeBits_valid_shift_word) apply (clarsimp simp: from_bool_def Let_def split: if_split bool.splits) apply (subst unat_of_nat32, clarsimp simp: unat_of_nat32 word_bits_def dest!: get_capSizeBits_valid_shift)+ apply (clarsimp simp: ccap_relation_get_capPtr_physical ccap_relation_get_capPtr_untyped ccap_relation_get_capIsPhysical[symmetric] ccap_relation_get_capSizeBits_physical ccap_relation_get_capSizeBits_untyped) apply (intro conjI impI) apply ((clarsimp simp: ccap_relation_def map_option_case cap_untyped_cap_lift cap_to_H_def field_simps valid_cap'_def)+)[4] apply (rule impI, simp add: from_bool_0 ccap_relation_get_capIsPhysical[symmetric]) apply (simp add: from_bool_def false_def) \<comment> \<open>capa is a CNodeCap\<close> apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs from_bool_def false_def)[1] apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap) apply (clarsimp simp: isArchCap_tag_def2) apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(10)) apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(10)) apply (simp add: ccap_relation_def map_option_case) apply (simp add: cap_cnode_cap_lift) apply (simp add: cap_to_H_def) apply (clarsimp split: if_split bool.split) \<comment> \<open>capa is an IRQControlCap\<close> apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs from_bool_def false_def true_def)[1] apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap) apply (fastforce simp: isArchCap_tag_def2 split: if_split) done lemma gen_framesize_to_H_eq: "\<lbrakk> a \<le> 3; b \<le> 3 \<rbrakk> \<Longrightarrow> (gen_framesize_to_H a = gen_framesize_to_H b) = (a = b)" by (fastforce simp: gen_framesize_to_H_def Kernel_C.ARMSmallPage_def Kernel_C.ARMLargePage_def Kernel_C.ARMSection_def word_le_make_less split: if_split dest: word_less_cases) lemma framesize_to_H_eq: "\<lbrakk> a \<le> 3; b \<le> 3; a \<noteq> 0; b \<noteq> 0 \<rbrakk> \<Longrightarrow> (framesize_to_H a = framesize_to_H b) = (a = b)" by (fastforce simp: framesize_to_H_def Kernel_C.ARMSmallPage_def Kernel_C.ARMLargePage_def Kernel_C.ARMSection_def word_le_make_less split: if_split dest: word_less_cases) lemma capFSize_range: "\<And>cap. cap_get_tag cap = scast cap_frame_cap \<Longrightarrow> capFSize_CL (cap_frame_cap_lift cap) \<le> 3" apply (simp add: cap_frame_cap_lift_def) apply (simp add: cap_lift_def cap_tag_defs word_and_le1 mask_def) done lemma Arch_sameObjectAs_spec: "\<forall>capa capb. \<Gamma> \<turnstile> \<lbrace>ccap_relation (ArchObjectCap capa) \<acute>cap_a \<and> ccap_relation (ArchObjectCap capb) \<acute>cap_b \<and> capAligned (ArchObjectCap capa) \<and> capAligned (ArchObjectCap capb) \<rbrace> Call Arch_sameObjectAs_'proc \<lbrace> \<acute>ret__unsigned_long = from_bool (Arch.sameObjectAs capa capb) \<rbrace>" apply vcg apply (clarsimp simp: ARM_HYP_H.sameObjectAs_def) apply (case_tac capa, simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_defs cap_tag_defs) apply fastforce+ apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_defs cap_tag_defs) apply fastforce+ apply (rename_tac vmpage_size opt d w r vmpage_sizea opt') apply (case_tac "vmpage_size = ARMSmallPage", simp_all add: cap_get_tag_isCap_unfolded_H_cap cap_tag_defs)[1] apply (rename_tac vmpage_sizea optiona) apply (case_tac "vmpage_sizea = ARMSmallPage", simp_all add: cap_get_tag_isCap_unfolded_H_cap cap_tag_defs false_def from_bool_def)[1] apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(16), simp) apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(16), simp) apply (simp add: ccap_relation_def map_option_case) apply (simp add: cap_small_frame_cap_lift) apply (clarsimp simp: cap_to_H_def capAligned_def to_bool_def from_bool_def split: if_split bool.split dest!: is_aligned_no_overflow) apply (case_tac "vmpage_sizea = ARMSmallPage", simp_all add: cap_get_tag_isCap_unfolded_H_cap cap_tag_defs false_def from_bool_def)[1] apply (frule_tac cap'=cap_a in cap_get_tag_isCap_unfolded_H_cap(17), simp) apply (frule_tac cap'=cap_b in cap_get_tag_isCap_unfolded_H_cap(17), simp) apply (simp add: ccap_relation_def map_option_case) apply (simp add: cap_frame_cap_lift) apply (clarsimp simp: cap_to_H_def capAligned_def from_bool_def c_valid_cap_def cl_valid_cap_def Kernel_C.ARMSmallPage_def split: if_split bool.split vmpage_size.split_asm dest!: is_aligned_no_overflow) apply (simp add: framesize_to_H_eq capFSize_range to_bool_def cap_frame_cap_lift [symmetric]) apply fastforce+ done lemma sameObjectAs_spec: "\<forall>capa capb. \<Gamma> \<turnstile> \<lbrace>ccap_relation capa \<acute>cap_a \<and> ccap_relation capb \<acute>cap_b \<and> capAligned capa \<and> capAligned capb \<and> (\<exists>s. s \<turnstile>' capa)\<rbrace> Call sameObjectAs_'proc \<lbrace> \<acute>ret__unsigned_long = from_bool (sameObjectAs capa capb) \<rbrace>" apply vcg apply (clarsimp simp: sameObjectAs_def isArchCap_tag_def2) apply (case_tac capa, simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs from_bool_def false_def) apply fastforce+ \<comment> \<open>capa is an arch cap\<close> apply (frule cap_get_tag_isArchCap_unfolded_H_cap) apply (simp add: isArchCap_tag_def2) apply (rule conjI, rule impI, clarsimp, rule impI)+ apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs)[1] apply ((fastforce)+)[7] \<comment> \<open>capb is an arch cap\<close> apply (frule_tac cap'=cap_b in cap_get_tag_isArchCap_unfolded_H_cap) apply (fastforce simp: isArchCap_tag_def2 linorder_not_less [symmetric])+ \<comment> \<open>capa is an irq handler cap\<close> apply (case_tac capb, simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_simps cap_tag_defs) apply fastforce+ \<comment> \<open>capb is an arch cap\<close> apply (frule cap_get_tag_isArchCap_unfolded_H_cap) apply (fastforce simp: isArchCap_tag_def2)+ done lemma sameRegionAs_EndpointCap: shows "\<lbrakk>ccap_relation capa capc; RetypeDecls_H.sameRegionAs (capability.EndpointCap p b cs cr cg cgr) capa\<rbrakk> \<Longrightarrow> cap_get_tag capc = scast cap_endpoint_cap" apply (simp add: sameRegionAs_def Let_def) apply (case_tac capa; simp add: isUntypedCap_def isEndpointCap_def isNotificationCap_def isCNodeCap_def isThreadCap_def isReplyCap_def isIRQControlCap_def isIRQHandlerCap_def isArchObjectCap_def) apply (clarsimp simp: ccap_relation_def map_option_case) apply (case_tac "cap_lift capc"; simp) apply (simp add: cap_to_H_def) apply (case_tac a; simp) apply (simp add:cap_endpoint_cap_lift cap_endpoint_cap_lift_def) apply (rename_tac zombie_cap) apply (case_tac "isZombieTCB_C (capZombieType_CL zombie_cap)"; simp add: Let_def) done lemma sameRegionAs_NotificationCap: shows "\<lbrakk>ccap_relation capa capc; RetypeDecls_H.sameRegionAs (capability.NotificationCap x y z u ) capa\<rbrakk> \<Longrightarrow> cap_get_tag capc = scast cap_notification_cap" apply (simp add: sameRegionAs_def Let_def) apply (case_tac capa; simp add: isUntypedCap_def isEndpointCap_def isNotificationCap_def isCNodeCap_def isThreadCap_def isReplyCap_def isIRQControlCap_def isIRQHandlerCap_def isArchObjectCap_def) apply (clarsimp simp: ccap_relation_def map_option_case) apply (case_tac "cap_lift capc"; simp) apply (simp add: cap_to_H_def) apply (case_tac a; simp) apply (simp add: cap_notification_cap_lift cap_notification_cap_lift_def) apply (rename_tac zombie_cap) apply (case_tac "isZombieTCB_C (capZombieType_CL zombie_cap)"; simp add: Let_def) done lemma isMDBParentOf_spec: notes option.case_cong_weak [cong] if_cong[cong] shows "\<forall>ctea cte_a cteb cte_b. \<Gamma> \<turnstile> {s. cslift s (cte_a_' s) = Some cte_a \<and> ccte_relation ctea cte_a \<and> cslift s (cte_b_' s) = Some cte_b \<and> ccte_relation cteb cte_b \<and> capAligned (cteCap cteb) \<and> (\<exists>s. s \<turnstile>' (cteCap ctea)) } Call isMDBParentOf_'proc \<lbrace> \<acute>ret__unsigned_long = from_bool (isMDBParentOf ctea cteb) \<rbrace>" apply (intro allI, rule conseqPre) apply vcg apply (clarsimp simp: isMDBParentOf_def) apply (frule_tac cte=ctea in ccte_relation_ccap_relation) apply (frule_tac cte=cteb in ccte_relation_ccap_relation) apply (rule conjI, clarsimp simp: typ_heap_simps dest!: lift_t_g) apply (intro conjI impI) apply (simp add: ccte_relation_def map_option_case) apply (simp add: cte_lift_def) apply (clarsimp simp: cte_to_H_def mdb_node_to_H_def split: option.split_asm) apply (clarsimp simp: Let_def false_def from_bool_def to_bool_def split: if_split bool.splits) apply ((clarsimp simp: typ_heap_simps dest!: lift_t_g)+)[3] apply (rule_tac x="cteCap ctea" in exI, rule conjI) apply (clarsimp simp: ccte_relation_ccap_relation typ_heap_simps dest!: lift_t_g) apply (rule_tac x="cteCap cteb" in exI, rule conjI) apply (clarsimp simp: ccte_relation_ccap_relation typ_heap_simps dest!: lift_t_g) apply (clarsimp simp: ccte_relation_def map_option_case) apply (simp add: cte_lift_def) apply (clarsimp simp: cte_to_H_def mdb_node_to_H_def split: option.split_asm) apply (rule conjI, fastforce) \<comment> \<open>Ex (valid_cap' (cteCap ctea))\<close> apply (rule impI, rule conjI) \<comment> \<open>sameRegionAs = 0\<close> apply (rule impI) apply (clarsimp simp: from_bool_def false_def split: if_split bool.splits) \<comment> \<open>sameRegionAs \<noteq> 0\<close> apply (clarsimp simp: from_bool_def false_def) apply (case_tac "RetypeDecls_H.sameRegionAs (cap_to_H x2b) (cap_to_H x2c)") prefer 2 apply clarsimp apply (clarsimp cong:bool.case_cong if_cong simp: typ_heap_simps) apply (rule conjI) \<comment> \<open>cap_get_tag of cte_a is an endpoint\<close> apply clarsimp apply (frule cap_get_tag_EndpointCap) apply simp apply (clarsimp simp: to_bool_def isNotificationCap_def isEndpointCap_def true_def) \<comment> \<open>badge of A is not 0 now\<close> apply (subgoal_tac "cap_get_tag (cte_C.cap_C cte_b) = scast cap_endpoint_cap") \<comment> \<open>needed also after\<close> prefer 2 apply (rule sameRegionAs_EndpointCap, assumption+) apply (clarsimp simp: if_1_0_0 typ_heap_simps' Let_def case_bool_If) apply (frule_tac cap="(cap_to_H x2c)" in cap_get_tag_EndpointCap) apply (clarsimp split: if_split_asm simp: if_distrib [where f=scast]) apply (clarsimp, rule conjI) \<comment> \<open>cap_get_tag of cte_a is an notification\<close> apply clarsimp apply (frule cap_get_tag_NotificationCap) apply simp apply (clarsimp simp: to_bool_def isNotificationCap_def isEndpointCap_def true_def) \<comment> \<open>badge of A is not 0 now\<close> apply (subgoal_tac "cap_get_tag (cte_C.cap_C cte_b) = scast cap_notification_cap") \<comment> \<open>needed also after\<close> prefer 2 apply (rule sameRegionAs_NotificationCap, assumption+) apply (rule conjI, simp) apply clarsimp apply (simp add: Let_def case_bool_If) apply (frule_tac cap="(cap_to_H x2c)" in cap_get_tag_NotificationCap) apply clarsimp \<comment> \<open>main goal\<close> apply clarsimp apply (simp add: to_bool_def) apply (subgoal_tac "(\<not> (isEndpointCap (cap_to_H x2b))) \<and> ( \<not> (isNotificationCap (cap_to_H x2b)))") apply (clarsimp simp: true_def) apply (rule conjI) apply (clarsimp simp: cap_get_tag_isCap [symmetric])+ done lemma updateCapData_spec: "\<forall>cap. \<Gamma> \<turnstile> \<lbrace> ccap_relation cap \<acute>cap \<and> preserve = to_bool (\<acute>preserve) \<and> newData = \<acute>newData\<rbrace> Call updateCapData_'proc \<lbrace> ccap_relation (updateCapData preserve newData cap) \<acute>ret__struct_cap_C \<rbrace>" supply if_cong[cong] apply (rule allI, rule conseqPre) apply vcg apply (clarsimp simp: if_1_0_0) apply (simp add: updateCapData_def) apply (case_tac cap, simp_all add: cap_get_tag_isCap_unfolded_H_cap isCap_simps from_bool_def isArchCap_tag_def2 cap_tag_defs Let_def) \<comment> \<open>NotificationCap\<close> apply clarsimp apply (frule cap_get_tag_isCap_unfolded_H_cap(3)) apply (frule (1) iffD1[OF cap_get_tag_NotificationCap]) apply clarsimp apply (intro conjI impI) \<comment> \<open>preserve is zero and capNtfnBadge_CL \<dots> = 0\<close> apply clarsimp apply (clarsimp simp:cap_notification_cap_lift_def cap_lift_def cap_tag_defs) apply (simp add: ccap_relation_def cap_lift_def cap_tag_defs cap_to_H_def) \<comment> \<open>preserve is zero and capNtfnBadge_CL \<dots> \<noteq> 0\<close> apply clarsimp apply (simp add: ccap_relation_NullCap_iff cap_tag_defs) \<comment> \<open>preserve is not zero\<close> apply clarsimp apply (simp add: to_bool_def) apply (case_tac "preserve_' x = 0 \<and> capNtfnBadge_CL (cap_notification_cap_lift (cap_' x))= 0", clarsimp) apply (simp add: if_not_P) apply (simp add: ccap_relation_NullCap_iff cap_tag_defs) \<comment> \<open>EndpointCap\<close> apply clarsimp apply (frule cap_get_tag_isCap_unfolded_H_cap(4)) apply (frule (1) iffD1[OF cap_get_tag_EndpointCap]) apply clarsimp apply (intro impI conjI) \<comment> \<open>preserve is zero and capNtfnBadge_CL \<dots> = 0\<close> apply clarsimp apply (clarsimp simp:cap_endpoint_cap_lift_def cap_lift_def cap_tag_defs) apply (simp add: ccap_relation_def cap_lift_def cap_tag_defs cap_to_H_def) \<comment> \<open>preserve is zero and capNtfnBadge_CL \<dots> \<noteq> 0\<close> apply clarsimp apply (simp add: ccap_relation_NullCap_iff cap_tag_defs) \<comment> \<open>preserve is not zero\<close> apply clarsimp apply (simp add: to_bool_def) apply (case_tac "preserve_' x = 0 \<and> capEPBadge_CL (cap_endpoint_cap_lift (cap_' x))= 0", clarsimp) apply (simp add: if_not_P) apply (simp add: ccap_relation_NullCap_iff cap_tag_defs) \<comment> \<open>ArchObjectCap\<close> apply clarsimp apply (frule cap_get_tag_isArchCap_unfolded_H_cap) apply (simp add: isArchCap_tag_def2) apply (simp add: ARM_HYP_H.updateCapData_def) \<comment> \<open>CNodeCap\<close> apply (clarsimp simp: cteRightsBits_def cteGuardBits_def) apply (frule cap_get_tag_isCap_unfolded_H_cap(10)) apply (frule (1) iffD1[OF cap_get_tag_CNodeCap]) apply clarsimp apply (thin_tac "ccap_relation x y" for x y) apply (thin_tac "ret__unsigned_long_' t = v" for t v)+ apply (simp add: seL4_CNode_CapData_lift_def fupdate_def word_size word_less_nat_alt mask_def cong: if_cong) apply (simp only: unat_word_ariths(1)) apply (rule ssubst [OF nat_mod_eq' [where n = "2 ^ len_of TYPE(32)"]]) \<comment> \<open>unat (\<dots> && 0x1F) + unat (\<dots> mod 0x20) < 2 ^ len_of TYPE(32)\<close> apply (rule order_le_less_trans, rule add_le_mono) apply (rule word_le_nat_alt[THEN iffD1]) apply (rule word_and_le1) apply (simp add: cap_cnode_cap_lift_def cap_lift_cnode_cap) apply (rule word_le_nat_alt[THEN iffD1]) apply (rule word_and_le1) apply (simp add: mask_def) apply (simp add: word_sle_def) apply (rule conjI, clarsimp simp: ccap_relation_NullCap_iff cap_tag_defs) apply clarsimp apply (rule conjI) apply (rule unat_less_power[where sz=5, simplified], simp add: word_bits_def) apply (rule and_mask_less'[where n=5, unfolded mask_def, simplified], simp) apply clarsimp apply (simp add: ccap_relation_def c_valid_cap_def cl_valid_cap_def cap_lift_cnode_cap cap_tag_defs cap_to_H_simps cap_cnode_cap_lift_def) apply (simp add: word_bw_assocs word_bw_comms word_bw_lcs) done abbreviation "deriveCap_xf \<equiv> liftxf errstate deriveCap_ret_C.status_C deriveCap_ret_C.cap_C ret__struct_deriveCap_ret_C_'" lemma ensureNoChildren_ccorres: "ccorres (syscall_error_rel \<currency> dc) (liftxf errstate id undefined ret__unsigned_long_') (\<lambda>s. valid_objs' s \<and> valid_mdb' s) (UNIV \<inter> \<lbrace>slot = ptr_val (\<acute>slot)\<rbrace>) [] (ensureNoChildren slot) (Call ensureNoChildren_'proc)" apply (cinit lift: slot_') apply (rule ccorres_liftE_Seq) apply (rule ccorres_getCTE) apply (rule ccorres_move_c_guard_cte) apply (rule_tac P= "\<lambda> s. valid_objs' s \<and> valid_mdb' s \<and> ctes_of s (ptr_val slota) = Some cte" and P' =UNIV in ccorres_from_vcg_throws) apply (rule allI, rule conseqPre, vcg) apply clarsimp apply (frule (1) rf_sr_ctes_of_clift, clarsimp) apply (simp add: typ_heap_simps) apply (clarsimp simp: whenE_def throwError_def return_def nullPointer_def liftE_bindE) apply (clarsimp simp: returnOk_def return_def) \<comment> \<open>solve the case where mdbNext is zero\<close> \<comment> \<open>main goal\<close> apply (simp add: ccte_relation_def) apply (frule_tac cte="cte_to_H y" in valid_mdb_ctes_of_next, simp+) apply (clarsimp simp: cte_wp_at_ctes_of) apply (frule_tac cte=cte in rf_sr_ctes_of_clift, assumption, clarsimp) apply (rule conjI) apply (frule_tac cte="(cte_to_H ya)" in ctes_of_valid', assumption, simp) apply (rule valid_capAligned, assumption) apply (rule conjI) apply (frule_tac cte="(cte_to_H y)" in ctes_of_valid', assumption, simp) apply blast apply clarsimp apply (rule conjI) \<comment> \<open>isMDBParentOf is not zero\<close> apply clarsimp apply (simp add: from_bool_def) apply (case_tac "isMDBParentOf (cte_to_H y) (cte_to_H ya)", simp_all)[1] apply (simp add: bind_def) apply (simp add: split_paired_Bex) apply (clarsimp simp: in_getCTE_cte_wp_at') apply (simp add: cte_wp_at_ctes_of) apply (simp add: syscall_error_rel_def EXCEPTION_NONE_def EXCEPTION_SYSCALL_ERROR_def) apply (simp add: syscall_error_to_H_cases(9)) \<comment> \<open>isMDBParentOf is zero\<close> apply clarsimp apply (simp add: from_bool_def) apply (case_tac "isMDBParentOf (cte_to_H y) (cte_to_H ya)", simp_all)[1] apply (simp add: bind_def) apply (simp add: split_paired_Bex) apply (clarsimp simp: in_getCTE_cte_wp_at') apply (simp add: cte_wp_at_ctes_of) apply (simp add: returnOk_def return_def) \<comment> \<open>last goal\<close> apply clarsimp apply (simp add: cte_wp_at_ctes_of) done lemma cap_small_frame_cap_set_capFMappedASID_spec: "\<forall>s. \<Gamma> \<turnstile> \<lbrace>s. cap_get_tag \<^bsup>s\<^esup>cap = scast cap_small_frame_cap\<rbrace> Call cap_small_frame_cap_set_capFMappedASID_'proc \<lbrace>cap_small_frame_cap_lift \<acute>ret__struct_cap_C = cap_small_frame_cap_lift \<^bsup>s\<^esup>cap \<lparr> cap_small_frame_cap_CL.capFMappedASIDHigh_CL := (\<^bsup>s\<^esup>asid >> asidLowBits) && mask asidHighBits, cap_small_frame_cap_CL.capFMappedASIDLow_CL := \<^bsup>s\<^esup>asid && mask asidLowBits \<rparr> \<and> cap_get_tag \<acute>ret__struct_cap_C = scast cap_small_frame_cap\<rbrace>" apply vcg by (clarsimp simp: Kernel_C.asidLowBits_def word_sle_def Kernel_C.asidHighBits_def asid_low_bits_def asid_high_bits_def mask_def) lemma cap_frame_cap_set_capFMappedASID_spec: "\<forall>s. \<Gamma> \<turnstile> \<lbrace>s. cap_get_tag \<^bsup>s\<^esup>cap = scast cap_frame_cap\<rbrace> Call cap_frame_cap_set_capFMappedASID_'proc \<lbrace>cap_frame_cap_lift \<acute>ret__struct_cap_C = cap_frame_cap_lift \<^bsup>s\<^esup>cap \<lparr> cap_frame_cap_CL.capFMappedASIDHigh_CL := (\<^bsup>s\<^esup>asid >> asidLowBits) && mask asidHighBits, cap_frame_cap_CL.capFMappedASIDLow_CL := \<^bsup>s\<^esup>asid && mask asidLowBits \<rparr> \<and> cap_get_tag \<acute>ret__struct_cap_C = scast cap_frame_cap\<rbrace>" apply vcg by (clarsimp simp: Kernel_C.asidLowBits_def word_sle_def Kernel_C.asidHighBits_def asid_low_bits_def asid_high_bits_def mask_def) lemma Arch_deriveCap_ccorres: "ccorres (syscall_error_rel \<currency> (ccap_relation)) deriveCap_xf \<top> (UNIV \<inter> {s. ccap_relation (ArchObjectCap cap) (cap_' s)}) [] (Arch.deriveCap slot cap) (Call Arch_deriveCap_'proc)" apply (cinit lift: cap_') apply csymbr apply (unfold ARM_HYP_H.deriveCap_def Let_def) apply (fold case_bool_If) apply wpc apply (clarsimp simp: cap_get_tag_isCap_ArchObject ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV]) apply (rule allI, rule conseqPre, vcg) apply clarsimp apply (rule context_conjI) apply (simp add: cap_get_tag_isCap_ArchObject) apply (clarsimp simp: returnOk_def return_def) subgoal by (simp add: ccap_relation_def cap_lift_def Let_def cap_tag_defs cap_to_H_def cap_page_table_cap_lift_def) apply wpc apply (clarsimp simp: cap_get_tag_isCap_ArchObject ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV]) apply (rule allI, rule conseqPre, vcg) apply clarsimp apply (rule context_conjI) apply (simp add: cap_get_tag_isCap_ArchObject) apply (clarsimp simp: throwError_def return_def errstate_def syscall_error_rel_def syscall_error_to_H_cases exception_defs) subgoal by (simp add: ccap_relation_def cap_lift_def Let_def cap_tag_defs cap_to_H_def to_bool_def cap_page_table_cap_lift_def split: if_split_asm) apply wpc apply (clarsimp simp: cap_get_tag_isCap_ArchObject ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV]) apply (rule allI, rule conseqPre, vcg) apply clarsimp apply (rule context_conjI) apply (simp add: cap_get_tag_isCap_ArchObject) apply (clarsimp simp: returnOk_def return_def) subgoal by (simp add: ccap_relation_def cap_lift_def Let_def cap_tag_defs cap_to_H_def cap_page_directory_cap_lift_def) apply wpc apply (clarsimp simp: cap_get_tag_isCap_ArchObject ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV]) apply (rule allI, rule conseqPre, vcg) apply clarsimp apply (rule context_conjI) apply (simp add: cap_get_tag_isCap_ArchObject) apply (clarsimp simp: throwError_def return_def errstate_def syscall_error_rel_def syscall_error_to_H_cases exception_defs) subgoal by (simp add: ccap_relation_def cap_lift_def Let_def cap_tag_defs cap_to_H_def to_bool_def cap_page_directory_cap_lift_def split: if_split_asm) apply wpc apply (clarsimp simp: cap_get_tag_isCap_ArchObject ccorres_cond_iffs) apply (case_tac "capVPSize cap = ARMSmallPage") apply (clarsimp simp: ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV]) apply (rule allI, rule conseqPre, vcg) apply clarsimp apply (rule context_conjI) apply (simp add: cap_get_tag_isCap_ArchObject) apply (clarsimp simp: returnOk_def return_def isCap_simps) subgoal by (simp add: ccap_relation_def cap_lift_def Let_def cap_tag_defs cap_to_H_def to_bool_def cap_small_frame_cap_lift_def asidInvalid_def) apply (clarsimp simp: ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV]) apply (rule allI, rule conseqPre, vcg) apply clarsimp apply (rule context_conjI) apply (simp add: cap_get_tag_isCap_ArchObject) apply (clarsimp simp: returnOk_def return_def isCap_simps) subgoal by (simp add: ccap_relation_def cap_lift_def Let_def cap_tag_defs cap_to_H_def to_bool_def cap_frame_cap_lift_def asidInvalid_def c_valid_cap_def cl_valid_cap_def) apply (simp add: cap_get_tag_isCap_ArchObject ccorres_cond_iffs) apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV]) apply (rule allI, rule conseqPre, vcg) apply (clarsimp simp: returnOk_def return_def subset_iff split: bool.split) apply (cases cap, simp_all add: isCap_simps)[1] apply clarsimp done lemma isArchCap_T_isArchObjectCap: "isArchCap \<top> = isArchObjectCap" by (rule ext, auto simp: isCap_simps) lemma deriveCap_ccorres': "ccorres (syscall_error_rel \<currency> ccap_relation) deriveCap_xf (valid_objs' and valid_mdb') (UNIV \<inter> {s. ccap_relation cap (cap_' s)} \<inter> {s. slot_' s = Ptr slot}) [] (deriveCap slot cap) (Call deriveCap_'proc)" apply (cinit lift: cap_' slot_') apply csymbr apply (fold case_bool_If) apply wpc apply (clarsimp simp: cap_get_tag_isCap isCap_simps from_bool_def) apply csymbr apply (clarsimp simp: cap_get_tag_isCap) apply (rule ccorres_from_vcg_throws [where P=\<top> and P' = UNIV]) apply (simp add: returnOk_def return_def ccap_relation_NullCap_iff) apply (rule allI, rule conseqPre) apply vcg apply clarsimp apply wpc apply (clarsimp simp: isCap_simps cap_get_tag_isCap from_bool_def) apply csymbr apply (clarsimp simp: isCap_simps cap_get_tag_isCap) apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV]) apply (rule allI, rule conseqPre, vcg) apply (clarsimp simp: returnOk_def return_def ccap_relation_NullCap_iff) apply wpc apply (clarsimp simp: isCap_simps cap_get_tag_isCap from_bool_def) apply csymbr apply (clarsimp simp: isCap_simps cap_get_tag_isCap) apply (rule ccorres_rhs_assoc)+ apply ctac_print_xf apply (rule ccorres_split_nothrow_call_novcgE [where xf'="ret__unsigned_long_'"]) apply (rule ensureNoChildren_ccorres) apply simp+ apply ceqv apply simp apply (rule_tac P'="\<lbrace>\<acute>ret__unsigned_long = scast EXCEPTION_NONE\<rbrace>" in ccorres_from_vcg_throws[where P=\<top>]) apply (rule allI, rule conseqPre, vcg) apply (clarsimp simp: return_def returnOk_def) apply simp apply (rule_tac P'="{s. ret__unsigned_long_' s = rv' \<and> errstate s = err'}" in ccorres_from_vcg_throws[where P=\<top>]) apply (rule allI, rule conseqPre, vcg) apply (clarsimp simp: throwError_def return_def errstate_def) apply wp apply wpc apply (clarsimp simp: isCap_simps cap_get_tag_isCap from_bool_def) apply csymbr apply (clarsimp simp: isCap_simps cap_get_tag_isCap) apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV]) apply (rule allI, rule conseqPre, vcg) apply (clarsimp simp: returnOk_def return_def ccap_relation_NullCap_iff) apply wpc apply (rule ccorres_split_throws[rotated]) apply (clarsimp simp: cap_get_tag_isCap liftME_def Let_def isArchCap_T_isArchObjectCap) apply vcg apply (clarsimp simp: cap_get_tag_isCap liftME_def Let_def isArchCap_T_isArchObjectCap ccorres_cond_univ_iff from_bool_def) apply (rule ccorres_add_returnOk) apply (rule ccorres_split_nothrow_call_novcgE [where xf'=ret__struct_deriveCap_ret_C_']) apply (rule Arch_deriveCap_ccorres) apply simp+ apply (rule ceqv_refl) apply (rule_tac P'="\<lbrace>\<acute>ret__struct_deriveCap_ret_C = rv'\<rbrace>" in ccorres_from_vcg_throws[where P=\<top>]) apply (rule allI, rule conseqPre, vcg) apply (clarsimp simp: return_def returnOk_def) apply (rule_tac P'="{s. (ret__struct_deriveCap_ret_C_' s) = rv' \<and> errstate s = err'}" in ccorres_from_vcg_throws[where P=\<top>]) apply (rule allI, rule conseqPre, vcg) apply (clarsimp simp: return_def throwError_def) apply wp apply (simp add: cap_get_tag_isCap isArchCap_T_isArchObjectCap from_bool_def) apply csymbr apply (simp add: cap_get_tag_isCap) apply (rule ccorres_from_vcg_throws[where P=\<top> and P'=UNIV]) apply (rule allI, rule conseqPre, vcg) apply (clarsimp simp: return_def returnOk_def) apply (clarsimp simp: errstate_def isCap_simps Collect_const_mem from_bool_0 cap_get_tag_isArchCap_unfolded_H_cap) done lemma deriveCap_ccorres: "ccorres (syscall_error_rel \<currency> ccap_relation) deriveCap_xf (invs') (UNIV \<inter> {s. ccap_relation cap (cap_' s)} \<inter> {s. slot_' s = Ptr slot}) [] (deriveCap slot cap) (Call deriveCap_'proc)" apply (rule ccorres_guard_imp2, rule deriveCap_ccorres') apply fastforce done lemma ensureEmptySlot_ccorres: "ccorres (syscall_error_rel \<currency> dc) (liftxf errstate id undefined ret__unsigned_long_') \<top> (UNIV \<inter> \<lbrace>slot = ptr_val (\<acute>slot)\<rbrace>) [] (ensureEmptySlot slot) (Call ensureEmptySlot_'proc)" apply (cinit lift: slot_') apply (rule ccorres_liftE_Seq) apply (rule ccorres_getCTE) apply (rule ccorres_move_c_guard_cte) apply (rule_tac P= "\<lambda> s. ctes_of s (ptr_val slota) = Some cte" and P' =UNIV in ccorres_from_vcg_throws) apply (rule allI, rule conseqPre, vcg) apply clarsimp apply (frule (1) rf_sr_ctes_of_clift, clarsimp) apply (simp add: typ_heap_simps) apply (rule conjI) apply (clarsimp simp: unlessE_def throwError_def return_def) apply (subgoal_tac "cap_to_H (cap_CL y) \<noteq> capability.NullCap") apply simp apply (simp add: syscall_error_rel_def EXCEPTION_NONE_def EXCEPTION_SYSCALL_ERROR_def) apply (rule syscall_error_to_H_cases(8)) apply simp apply (subst cap_get_tag_NullCap [symmetric]) prefer 2 apply assumption apply (simp add: ccap_relation_def c_valid_cte_def) apply (clarsimp simp: unlessE_def throwError_def return_def) apply (subgoal_tac "cap_to_H (cap_CL y) = capability.NullCap") apply simp apply (simp add: returnOk_def return_def) apply (subst cap_get_tag_NullCap [symmetric]) prefer 2 apply assumption apply (simp add: ccap_relation_def c_valid_cte_def) apply clarsimp apply (simp add: cte_wp_at_ctes_of) done lemma (in kernel_m) updateMDB_set_mdbPrev: "ccorres dc xfdc ( \<lambda>s. is_aligned ptr 3 \<and> (slota\<noteq>0 \<longrightarrow> is_aligned slota 3)) {s. slotc = slota } hs (updateMDB ptr (mdbPrev_update (\<lambda>_. slota))) (IF ptr \<noteq> 0 THEN Guard C_Guard \<lbrace>hrs_htd \<acute>t_hrs \<Turnstile>\<^sub>t (Ptr ptr:: cte_C ptr)\<rbrace> (call (\<lambda>ta. ta(| mdb_node_ptr_' := Ptr &(Ptr ptr:: cte_C ptr \<rightarrow>[''cteMDBNode_C'']), v32_' := slotc |)) mdb_node_ptr_set_mdbPrev_'proc (\<lambda>s t. s\<lparr> globals := globals t \<rparr>) (\<lambda>ta s'. Basic (\<lambda>a. a))) FI)" apply (rule ccorres_guard_imp2) \<comment> \<open>replace preconditions by schematics\<close> \<comment> \<open>Main Goal\<close> apply (rule ccorres_Cond_rhs) apply (rule ccorres_updateMDB_cte_at) apply (ctac add: ccorres_updateMDB_set_mdbPrev) apply (ctac ccorres: ccorres_updateMDB_skip) apply (simp) done lemma (in kernel_m) updateMDB_set_mdbNext: "ccorres dc xfdc ( \<lambda>s. is_aligned ptr 3 \<and> (slota\<noteq>0 \<longrightarrow> is_aligned slota 3)) {s. slotc = slota} hs (updateMDB ptr (mdbNext_update (\<lambda>_. slota))) (IF ptr \<noteq> 0 THEN Guard C_Guard \<lbrace>hrs_htd \<acute>t_hrs \<Turnstile>\<^sub>t (Ptr ptr:: cte_C ptr)\<rbrace> (call (\<lambda>ta. ta(| mdb_node_ptr_' := Ptr &(Ptr ptr:: cte_C ptr \<rightarrow>[''cteMDBNode_C'']), v32_' := slotc |)) mdb_node_ptr_set_mdbNext_'proc (\<lambda>s t. s\<lparr> globals := globals t \<rparr>) (\<lambda>ta s'. Basic (\<lambda>a. a))) FI)" apply (rule ccorres_guard_imp2) \<comment> \<open>replace preconditions by schematics\<close> \<comment> \<open>Main Goal\<close> apply (rule ccorres_Cond_rhs) apply (rule ccorres_updateMDB_cte_at) apply (ctac add: ccorres_updateMDB_set_mdbNext) apply (ctac ccorres: ccorres_updateMDB_skip) apply simp done end end
[STATEMENT] lemma drop_bit_word_minus_numeral [simp]: \<open>drop_bit (numeral n) (- numeral k) = (word_of_int (drop_bit (numeral n) (take_bit LENGTH('a) (- numeral k))) :: 'a::len word)\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. drop_bit (numeral n) (- numeral k) = word_of_int (drop_bit (numeral n) (take_bit LENGTH('a) (- numeral k))) [PROOF STEP] by transfer simp
import tactic /-------------------------------------------------------------------------- ``have`` If ``f`` is a term of type ``P → Q`` and ``hp`` is a term of type ``P``, then ``have hq := f hp ,`` creates the hypothesis ``hq : Q`` . ``refine`` If the target of the current goal is ``Q`` and ``f`` is a term of type ``P → Q``, then ``refine f _,`` changes target to ``P``. Delete the ``sorry,`` below and replace them with a legitimate proof. --------------------------------------------------------------------------/ example (P Q R : Prop) (hp : P) (f : P → Q) (g : Q → R) : R := begin sorry, end example (P Q R S T U: Type) (hpq : P → Q) (hqr : Q → R) (hqt : Q → T) (hst : S → T) (htu : T → U) : P → U := begin sorry, end
using StructJuMP m = StructuredModel(num_scenarios=p) n = 10 @variable(m, x[1:n] >= 0) @variable(m, y[1:n] >= 0) for i in 1:n @constraint(m, x[i] - y[i] <= i) end p = 3 q = 2 for s = 1:p bl = StructuredModel(parent=m, num_scenarios=2, id=s) @variable(bl, z[1:n] >= 0) @constraint(bl, x + sum(z[i] for i=1:n) .== 1) for t = 1:q bll = StructuredModel(parent=bl, id=t) @variable(bll, w[1:n] >= 0) @constraint(bll, sum(w[i] for i=1:n if iseven(i)) == 1) par = parent(bll) @constraint(bll, sum(z[i] for i=1:n) - sum(w[i] for i=1:n) >= 0) @constraint(bll, sum(z[i] for i=1:n) >= 0) @constraint(bll, 0 >= sum(w[i] for i=1:n)) end end @constraint(m, sum(z for bl in children(m), z=getVar(bl,:z)) == 1) #sum(indx for cond(indx)) (models[indx].y[1] + x[1]) = 0
[STATEMENT] theorem TBtheorem5a_empty: assumes "(eout P E) \<or> (eout Q E)" and "subcomponents PQ = {P,Q}" and "correctCompositionOut PQ" and "loc PQ = {}" shows "eout PQ E" [PROOF STATE] proof (prove) goal (1 subgoal): 1. eout PQ E [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: eout P E \<or> eout Q E subcomponents PQ = {P, Q} correctCompositionOut PQ loc PQ = {} goal (1 subgoal): 1. eout PQ E [PROOF STEP] by (simp add: eout_def correctCompositionOut_def, auto)
If $\gamma$ is a valid path, then $-\gamma$ is a valid path.
! Compile and run: make program phys395_hw3_optimization use q1_roots use q3_minima use q5_fit implicit none print * call q1() call q3() call q5() end program phys395_hw3_optimization
{-# OPTIONS --cubical --safe --postfix-projections #-} module Categories.Exercises where open import Prelude open import Categories open Category ⦃ ... ⦄ open import Categories.Product open Product public open HasProducts ⦃ ... ⦄ public -- module _ {ℓ₁} {ℓ₂} ⦃ c : Category ℓ₁ ℓ₂ ⦄ ⦃ hp : HasProducts c ⦄ where -- ex17 : (t : Terminal) (x : Ob) → Product.obj (product (fst t) x) ≅ x -- ex17 t x .fst = proj₂ (product (fst t) x) -- ex17 t x .snd .fst = ump (product (fst t) x) (t .snd .fst) Id .fst -- ex17 t x .snd .snd .fst = let p = ump (product (fst t) x) (t .snd .fst) Id .snd .snd ({!!} , {!!}) in {!!} -- ex17 t x .snd .snd .snd = {!!}
# Copyright (c) 2018-2021, Carnegie Mellon University # See LICENSE for details Class(SMP_Unparser, SMP_UnparseMixin, CUnparserProg); Class(SMP_MacroUnparser, SMP_UnparseMixin, CMacroUnparserProg); Class(OpenMP_Unparser, OpenMP_UnparseMixin, CUnparserProg); Class(OpenMP_MacroUnparser, OpenMP_UnparseMixin, CMacroUnparserProg); # suggested values: bufIters=64 (16 for older machines), maxRank=1 (larger value increases search space) # Example: opts := InitGTLibgen(64, 1) # InitGTLibgen := function(bufIters, maxRank, useComplex) local opts; LibgenHardcodeStrides(); opts := CopyFields(InitLibgen(When(useComplex, CplxLibgenDefaults, LibgenDefaults)), rec( useDeref := true, breakdownRules := rec( GT := [ CopyFields(GT_Base, rec(maxSize := 32)), CopyFields(GT_BufReshape, rec(bufIters := bufIters)), CopyFields(GT_DFT_CT, rec(minSize := 33, maxRank := maxRank)), GT_NthLoop, GT_Par ], DFT := [ CopyFields(DFT_CT, rec(maxSize:=32)), CopyFields(DFT_GT_CT, rec(minSize:=32)), DFT_Base ], InfoNt := [Info_Base]) )); opts.formulaStrategies.preRC := [ HfuncSumsRules ]; return opts; end; InitSMPGTLibgen := function(bufIters, maxRank, useComplex, useOpenMP) local opts; opts := CopyFields(InitGTLibgen(bufIters, maxRank, useComplex), rec( unparser := Cond( useComplex and useOpenMP, OpenMP_MacroUnparser, useComplex and not useOpenMP, SMP_MacroUnparser, not useComplex and useOpenMP, OpenMP_Unparser, not useComplex and not useOpenMP, SMP_Unparser))); opts.formulaStrategies.sigmaSpl := [ MergedRuleSet(StandardSumsRules,RulesSMP), HfuncSumsRules ]; opts.formulaStrategies.rc := opts.formulaStrategies.sigmaSpl; if not useOpenMP then opts.subParams := [var("num_threads", TInt), var("tid", TInt)]; opts.profile := When(LocalConfig.osinfo.isWindows(), LocalConfig.cpuinfo.profile.threads(), profiler.default_profiles.linux_x86_threads ); fi; return opts; end;
Require Import List Logic Nat Arith Bool Omega Classical. Require Import Compare_dec EqNat Decidable ListDec FinFun. Require Fin. Import ListNotations. From Block Require Import lib definitions. Definition Ramsey_of {X : Type} (r s : nat) (H_r : r > 0) (H_s : s > 0) (rk : nat) (d : X) := forall l : list X, length l = rk -> forall f : X -> X -> bool, (exists bl : list X, length bl = r /\ subseq bl l /\ forall i j : nat, i < j < r -> f (nth i bl d) (nth j bl d) = true) \/ (exists bl : list X, length bl = s /\ subseq bl l /\ forall i j : nat, i < j < s -> f (nth i bl d) (nth j bl d) = false). Definition Ramsey_of_prop {X : Type} (r s : nat) (H_r : r > 0) (H_s : s > 0) (rk : nat) (d : X) := forall l : list X, length l = rk -> forall P : X -> X -> Prop, (exists bl : list X, length bl = r /\ subseq bl l /\ forall i j : nat, i < j < r -> P (nth i bl d) (nth j bl d)) \/ (exists bl : list X, length bl = s /\ subseq bl l /\ forall i j : nat, i < j < s -> ~ P (nth i bl d) (nth j bl d)). Lemma one : 1 > 0. Proof. omega. Qed. Theorem Ramsey_of_one {X : Type} : forall (k : nat) (H_k : k > 0) (d : X), Ramsey_of 1 k one H_k 1 d /\ Ramsey_of k 1 H_k one 1 d. Proof. intros k H_k d; split; red; repeat split; try omega; intros l H_l f. - left. exists l. split. assumption. split. apply subseq_refl. intros. omega. - right. exists l. split. assumption. split. apply subseq_refl. intros. omega. Qed. Theorem Ramsey_of_one_prop {X : Type} : forall (k : nat) (H_k : k > 0) (d : X), Ramsey_of_prop 1 k one H_k 1 d /\ Ramsey_of_prop k 1 H_k one 1 d. Proof. intros k H_k d; split; red; repeat split; try omega; intros l H_l f. - left. exists l. split. assumption. split. apply subseq_refl. intros. omega. - right. exists l. split. assumption. split. apply subseq_refl. intros. omega. Qed. Theorem Ramsey_inductive_step {X : Type} : forall (r s : nat) (H_r : r > 0) (H_s : s > 0) (d : X), exists rk : nat, Ramsey_of r s H_r H_s rk d. Proof. intros r s. remember (r + s) as k. revert r s Heqk. induction k as [|k IHk] using strong_induction; intros. - symmetry in Heqk; apply plus_is_O in Heqk. destruct Heqk; subst. inversion H_r. - destruct r as [|r]. inversion H_r. destruct s as [|s]. inversion H_s. destruct r as [|r]. (* Pseudo base case, when r = 1 *) exists 1. apply (Ramsey_of_one (S s) H_s d). (* Pseudo base case, when s = 1 *) destruct s as [|s]. exists 1. apply (Ramsey_of_one (S (S r)) H_r d). (* Finally, everything is big enough *) destruct k. omega. destruct k. omega. (* Both (S r) and (S s) are greater than or equal to 1, and therefore (S (S k)) is greater than or equal to two *) (* Reminder : r = S r, s = S s, k = S (S k) *) spec IHk (S k). spec IHk. omega. assert (IHk_copy := IHk). spec IHk (S r) (S (S s)). spec IHk_copy (S (S r)) (S s). spec IHk. omega. spec IHk_copy. omega. assert (H_pre1 : S r > 0) by omega. spec IHk H_pre1 H_s. spec IHk_copy H_r. assert (H_pre2 : S s > 0) by omega. spec IHk_copy H_pre2. spec IHk d. spec IHk_copy d. destruct IHk as [rk1 IHk1]. destruct IHk_copy as [rk2 IHk2]. exists (rk1 + rk2); red; intros l H_l f. red in IHk1, IHk2. destruct l as [|v l_rest]. (* Inversioning the base case list *) + unfold length in H_l. symmetry in H_l. apply plus_is_O in H_l. destruct H_l; subst. spec IHk1 ([] : list X). spec IHk1. reflexivity. spec IHk1 f. destruct IHk1; destruct H as [bl_absurd [absurd_length [absurd_subseq _]]]; assert (bl_absurd = []) by (apply (subseq_nil_nil); assumption); subst; simpl in absurd_length; inversion absurd_length. + (* Now we have a pivot vertex *) remember (filter (fun n => f v n) l_rest) as M. remember (filter (fun n => negb (f v n)) l_rest) as N. assert (length M + length N = length l_rest). { subst; apply filter_length. } simpl in H_l. assert (length M >= rk1 \/ length N >= rk2) by omega. destruct H0 as [red | blue]. * (* In the case that M has a red K_(S s) *) clear IHk2. assert (H_get := get_subseq M rk1 red). assert (H_trans : subseq M l_rest) by (subst M; apply (filter_subseq_correct')). destruct H_get as [red_list [H_red_length H_red_subseq]]. spec IHk1 red_list H_red_length f. destruct IHk1 as [left | right]. ** destruct left as [bl [bl_length [bl_subseq bl_color]]]. left. exists (v :: bl). repeat split. simpl; omega. apply subseq_hm. do 2 (eapply subseq_trans; eauto). (* Boom! *) intros. destruct j. omega. destruct i. (* When we're looking at the head, i.e. v *) { simpl. subst M. assert (subseq bl (filter (fun n => f v n) l_rest)). eapply subseq_trans; eauto. apply subseq_incl in H1. spec H1 (nth j bl d). spec H1. apply nth_In. omega. apply filter_In in H1. destruct H1 as [_ goal]. exact goal. } spec bl_color i j. spec bl_color. omega. simpl. assumption. ** destruct right as [bl [bl_length [bl_subseq bl_color]]]. right. exists bl. repeat split. assumption. apply subseq_hn. do 2 (eapply subseq_trans; eauto). assumption. * (* In the case that N has a blue K_r *) clear IHk1. assert (H_get := get_subseq N rk2 blue). assert (H_trans : subseq N l_rest) by (subst N; apply (filter_subseq_correct')). destruct H_get as [blue_list [H_blue_length H_blue_subseq]]. spec IHk2 blue_list H_blue_length f. destruct IHk2 as [left | right]. ** destruct left as [bl [bl_length [bl_subseq bl_color]]]. left. exists bl. repeat split. assumption. apply subseq_hn. do 2 (eapply subseq_trans; eauto). assumption. ** destruct right as [bl [bl_length [bl_subseq bl_color]]]. right. exists (v :: bl). repeat split. simpl; omega. apply subseq_hm. do 2 (eapply subseq_trans; eauto). (* Boom! *) intros. destruct j. omega. destruct i. simpl. subst M. { simpl. subst N. assert (subseq bl (filter (fun n => negb (f v n)) l_rest)). eapply subseq_trans; eauto. apply subseq_incl in H1. spec H1 (nth j bl d). spec H1. apply nth_In. omega. apply filter_In in H1. destruct H1 as [_ goal]. apply negb_true_iff in goal. exact goal. } spec bl_color i j. spec bl_color. omega. simpl. assumption. Qed. Print Assumptions Ramsey_inductive_step. (* This requires no additional axioms *) (* Ramsey in Prop *) Lemma filterprop_vanilla : forall X (P : X -> Prop) (L : list X), exists L', forall x, In x L' <-> (In x L /\ P x). Proof. induction L. exists nil. split. inversion 1. intros [? _]. inversion H. destruct IHL as [L' ?]. destruct (classic (P a)). exists (a :: L'). split; intros. destruct H1. split. left. assumption. subst. assumption. split. right. apply H in H1. destruct H1. assumption. apply H in H1. destruct H1. assumption. destruct H1. destruct H1. left. assumption. right. apply H. split; assumption. exists L'. split; intros. apply H in H1. destruct H1. split. right. assumption. assumption. apply H. destruct H1. destruct H1. subst. contradiction. split; assumption. Qed. Lemma filterprop_armed : forall X (P : X -> Prop) (L : list X), forall (Q : list X -> Prop) (f : list X -> list X) (H_correct : forall l : list X, Q (f l) /\ (forall w, In w (f l) <-> In w l)), exists L', Q L' /\ forall x, In x L' <-> (In x L /\ P x). Proof. intros. destruct (filterprop_vanilla X P L) as [L_vanilla about_L_vanilla]. exists (f L_vanilla). spec H_correct L_vanilla. destruct H_correct. split. assumption. intro; split; intro. apply about_L_vanilla. apply H0. assumption. apply about_L_vanilla in H1. spec H0 x. apply H0. assumption. Qed. Lemma filterprop_vanilla_dep : forall X (D : X -> Prop) (P : {x | D x} -> Prop) (L : list {x | D x}), exists L', (* sublist L' L /\ *) forall x, In x L' <-> (In x L /\ P x). Proof. induction L. exists nil. split. inversion 1. intros [? _]. inversion H. destruct IHL as [L' ?]. destruct (classic (P a)). exists (a :: L'). split; intros. destruct H1. split. left. assumption. subst. assumption. split. right. apply H in H1. destruct H1. assumption. apply H in H1. destruct H1. assumption. destruct H1. destruct H1. left. assumption. right. apply H. split; assumption. exists L'. split; intros. apply H in H1. destruct H1. split. right. assumption. assumption. apply H. destruct H1. destruct H1. subst. contradiction. split; assumption. Qed. Theorem filterprop_subseq_both : forall (X : Type) (P : X -> Prop) (L : list X), exists L' L'': list X, length L' + length L'' = length L /\ subseq L' L /\ subseq L'' L /\ (forall x : X, In x L' <-> In x L /\ P x) /\ (forall x : X, In x L'' <-> In x L /\ ~ P x). Proof. induction L as [|hd tl IHL]. + exists nil, nil. repeat split. apply subseq_nil. apply subseq_nil. inversion H. inversion H. intros [absurd _]; inversion absurd. inversion H. inversion H. intros [absurd _]; inversion absurd. + destruct IHL as [L' [L'' [H_length [H_subseq' [H_subseq'' [H_in1 H_in2]]]]]]. destruct (classic (P hd)). * exists (hd :: L'), L''. repeat split. simpl; omega. now apply subseq_hm. now apply subseq_hn. destruct H0 as [H_eq | H_tl]. subst. apply in_eq. apply H_in1 in H_tl. destruct H_tl as [goal _]. right; assumption. destruct H0 as [H_eq | H_tl]. subst; assumption. apply H_in1 in H_tl. destruct H_tl as [_ goal]; assumption. intro. destruct H0 as [[H_eq | H_tl] H_P]. subst. apply in_eq. right. apply H_in1. split; assumption. apply H_in2 in H0. destruct H0 as [goal _]; right; assumption. apply H_in2 in H0; destruct H0 as [_ goal]; assumption. intros [H_in H_notP]. apply H_in2. destruct H_in as [H_eq | H_tl]. subst. contradiction. split; assumption. * exists L', (hd :: L''). repeat split. simpl; omega. now apply subseq_hn. now apply subseq_hm. apply H_in1 in H0. destruct H0 as [goal _]; right; assumption. apply H_in1 in H0. destruct H0 as [_ goal]; assumption. intros [H_in H_P]. destruct H_in as [H_eq | H_tl]. subst. contradiction. apply H_in1. split; assumption. destruct H0 as [H_eq | H_tl]. subst. apply in_eq. apply H_in2 in H_tl. destruct H_tl as [goal _]; right; assumption. destruct H0 as [H_eq | H_tl]. subst. assumption. apply H_in2 in H_tl. destruct H_tl as [_ goal]; assumption. intros [H_in H_notP]. destruct H_in as [H_eq | H_tl]. subst. apply in_eq. right. apply H_in2. tauto. Qed. Theorem Ramsey_inductive_step_prop {X : Type} : forall (r s : nat) (H_r : r > 0) (H_s : s > 0) (d : X), exists rk : nat, Ramsey_of_prop r s H_r H_s rk d. Proof. intros r s. remember (r + s) as k. revert r s Heqk. induction k as [|k IHk] using strong_induction; intros. - symmetry in Heqk; apply plus_is_O in Heqk. destruct Heqk; subst. inversion H_r. - destruct r as [|r]. inversion H_r. destruct s as [|s]. inversion H_s. destruct r as [|r]. (* Pseudo base case, when r = 1 *) exists 1. apply (Ramsey_of_one_prop (S s) H_s d). (* Pseudo base case, when s = 1 *) destruct s as [|s]. exists 1. apply (Ramsey_of_one_prop (S (S r)) H_r d). (* Finally, everything is big enough *) destruct k. omega. destruct k. omega. (* Both (S r) and (S s) are greater than or equal to 1, and therefore (S (S k)) is greater than or equal to two *) (* Reminder : r = S r, s = S s, k = S (S k) *) spec IHk (S k). spec IHk. omega. assert (IHk_copy := IHk). spec IHk (S r) (S (S s)). spec IHk_copy (S (S r)) (S s). spec IHk. omega. spec IHk_copy. omega. assert (H_pre1 : S r > 0) by omega. spec IHk H_pre1 H_s. spec IHk_copy H_r. assert (H_pre2 : S s > 0) by omega. spec IHk_copy H_pre2. spec IHk d. spec IHk_copy d. destruct IHk as [rk1 IHk1]. destruct IHk_copy as [rk2 IHk2]. exists (rk1 + rk2); red; intros l H_l f. red in IHk1, IHk2. destruct l as [|v l_rest]. (* Inversioning the base case list *) + unfold length in H_l. symmetry in H_l. apply plus_is_O in H_l. destruct H_l; subst. spec IHk1 ([] : list X). spec IHk1. reflexivity. spec IHk1 f. destruct IHk1; destruct H as [bl_absurd [absurd_length [absurd_subseq _]]]; assert (bl_absurd = []) by (apply (subseq_nil_nil); assumption); subst; simpl in absurd_length; inversion absurd_length. + (* Now we have a pivot vertex *) assert (H_list := filterprop_subseq_both _ (f v) l_rest). destruct H_list as [M [N [MN_length [M_subseq [N_subseq [H_trans H_trans']]]]]]. simpl in H_l. assert (length M >= rk1 \/ length N >= rk2) by omega. destruct H as [red | blue]. * (* In the case that M has a red K_(S s) *) clear IHk2. assert (H_get := get_subseq M rk1 red). destruct H_get as [red_list [H_red_length H_red_subseq]]. spec IHk1 red_list H_red_length f. destruct IHk1 as [left | right]. ** destruct left as [bl [bl_length [bl_subseq bl_color]]]. left. exists (v :: bl). repeat split. simpl; omega. apply subseq_hm. do 2 (eapply subseq_trans; eauto). (* Boom! *) intros. destruct j. omega. destruct i. (* When we're looking at the head, i.e. v *) { simpl. apply H_trans. apply subseq_incl in H_red_subseq. spec H_red_subseq (nth j bl d). apply H_red_subseq. apply subseq_incl in bl_subseq. spec bl_subseq (nth j bl d). apply bl_subseq. apply nth_In. omega. } spec bl_color i j. spec bl_color. omega. simpl. assumption. ** destruct right as [bl [bl_length [bl_subseq bl_color]]]. right. exists bl. repeat split. assumption. apply subseq_hn. do 2 (eapply subseq_trans; eauto). assumption. * (* In the case that N has a blue K_r *) clear IHk1. assert (H_get := get_subseq N rk2 blue). destruct H_get as [blue_list [H_blue_length H_blue_subseq]]. spec IHk2 blue_list H_blue_length f. destruct IHk2 as [left | right]. ** destruct left as [bl [bl_length [bl_subseq bl_color]]]. left. exists bl. repeat split. assumption. apply subseq_hn. do 2 (eapply subseq_trans; eauto). assumption. ** destruct right as [bl [bl_length [bl_subseq bl_color]]]. right. exists (v :: bl). repeat split. simpl; omega. apply subseq_hm. do 2 (eapply subseq_trans; eauto). (* Boom! *) intros. destruct j. omega. destruct i. simpl. { simpl. apply H_trans'. apply subseq_incl in H_blue_subseq. spec H_blue_subseq (nth j bl d). apply H_blue_subseq. apply subseq_incl in bl_subseq. spec bl_subseq (nth j bl d). apply bl_subseq. apply nth_In. omega. } spec bl_color i j. spec bl_color. omega. simpl. assumption. Qed. Theorem Ramsey_single : forall (k : nat), k > 0 -> exists rk : nat, rk >= k /\ forall l : list nat, length l = rk -> forall f : nat -> nat -> bool, (exists bl : list nat, length bl = k /\ subseq bl l /\ forall i j : nat, i < j < k -> f (nth i bl d) (nth j bl d) = true) \/ (exists bl : list nat, length bl = k /\ subseq bl l /\ forall i j : nat, i < j < k -> f (nth i bl d) (nth j bl d) = false). Proof. intros k H_gt_zero. assert (H_one := @Ramsey_of_one nat). assert (H_step := @Ramsey_inductive_step nat). spec H_one k H_gt_zero d. specialize (H_step k k H_gt_zero H_gt_zero d). destruct k. inversion H_gt_zero. destruct k. destruct H_one as [rk H_one]. exists 1. split. omega. exact H_one. destruct H_step as [rk H_step]. assert (rk >= S (S k) \/ rk < S (S k)) by omega. destruct H as [yes | no]. exists rk. split. assumption. assumption. exists rk. clear H_one. red in H_step. spec H_step (iota 0 rk). spec H_step. apply length_iota. spec H_step (fun i j : nat => true). destruct H_step. destruct H. destruct H. destruct H0. apply short_subseq_inversion in H0. inversion H0. rewrite H. rewrite length_iota. assumption. destruct H. destruct H. destruct H0. apply short_subseq_inversion in H0. inversion H0. rewrite H. rewrite length_iota; assumption. Qed. Theorem Ramsey_single_prop : forall (k : nat), k > 0 -> exists rk : nat, rk >= k /\ forall l : list nat, length l = rk -> forall f : nat -> nat -> Prop, (exists bl : list nat, length bl = k /\ subseq bl l /\ forall i j : nat, i < j < k -> f (nth i bl d) (nth j bl d)) \/ (exists bl : list nat, length bl = k /\ subseq bl l /\ forall i j : nat, i < j < k -> ~ f (nth i bl d) (nth j bl d)). Proof. intros k H_gt_zero. assert (H_one := @Ramsey_of_one_prop nat). assert (H_step := @Ramsey_inductive_step_prop nat). spec H_one k H_gt_zero d. specialize (H_step k k H_gt_zero H_gt_zero d). destruct k. inversion H_gt_zero. destruct k. exists 1. split. omega. destruct H_one. assumption. destruct H_step as [rk H_step]. assert (rk >= S (S k) \/ rk < S (S k)) by omega. destruct H as [yes | no]. exists rk. split. assumption. assumption. exists rk. clear H_one. red in H_step. spec H_step (iota 0 rk). spec H_step. apply length_iota. spec H_step (fun i j : nat => True). destruct H_step. destruct H. destruct H. destruct H0. apply short_subseq_inversion in H0. inversion H0. rewrite H. rewrite length_iota. assumption. destruct H. destruct H. destruct H0. apply short_subseq_inversion in H0. inversion H0. rewrite H. rewrite length_iota; assumption. Qed. Theorem Theorem_of_Ramsey_duo : forall (k : block_pumping_constant), exists rk : block_pumping_constant, rk >= k /\ forall w : word, forall bps : breakpoint_set rk w, forall (P : nat -> nat -> Prop) (f : nat -> nat -> bool) (H : forall i j, (f i j = true <-> P i j) /\ (f i j = false <-> ~ P i j)), exists bps' : breakpoint_set k w, sublist bps' bps /\ ((forall bp1 bp2 : breakpoint bps', bp1 < bp2 -> (P bp1 bp2)) \/ (forall bp1 bp2 : breakpoint bps', bp1 < bp2 -> ~ (P bp1 bp2))). Proof. intro k. assert (H_ramsey := Ramsey_single k). destruct k as [k about_k]; unfold p_predicate in about_k. spec H_ramsey. simpl; omega. destruct H_ramsey as [rk [rk_fact H_ramsey]]. simpl in rk_fact. assert (about_rk : rk >= 2). omega. exists (exist p_predicate rk about_rk). split. simpl. assumption. intros w bps P f f_correct. destruct bps as [bps [bps_length [bps_incr bps_last]]]. simpl in *. spec H_ramsey bps bps_length f. destruct H_ramsey as [yes | no]. - destruct yes as [bps_yes [bps_yes_length [bps_yes_subseq yes]]]. assert (breakpoint_set_predicate bps_yes w (exist _ k about_k)). { repeat split. simpl. assumption. now apply (subseq_incr bps). assert (H_trans := about_subseq_last bps_yes bps d). spec H_trans. rewrite bps_yes_length; omega. spec H_trans. rewrite bps_length; omega. spec H_trans. assumption. spec H_trans. exact bps_yes_subseq. now apply (le_trans (last bps_yes d) (last bps d) (length w)). } exists (exist _ bps_yes H); simpl in *. split. apply subseq_incl in bps_yes_subseq. assumption. left. intros. destruct bp1 as [bp1 about_bp1]; destruct bp2 as [bp2 about_bp2]; unfold breakpoint_predicate in *. simpl in *. apply (In_nth _ _ d) in about_bp1. apply (In_nth _ _ d) in about_bp2. destruct about_bp1 as [i [i_pos i_eq]]. destruct about_bp2 as [j [j_pos j_eq]]. spec yes i j. spec yes. rewrite bps_yes_length in i_pos, j_pos. split. eapply increasing_nth_lt. destruct H as [_ [bps_yes_incr bps_yes_last]]. exact bps_yes_incr. rewrite bps_yes_length; assumption. rewrite bps_yes_length; assumption. rewrite i_eq, j_eq. assumption. assumption. spec f_correct (nth i bps_yes d) (nth j bps_yes d). rewrite <- i_eq. rewrite <- j_eq. destruct f_correct as [f_correct _]. apply f_correct. assumption. - destruct no as [bps_no [bps_no_length [bps_no_subseq no]]]. assert (breakpoint_set_predicate bps_no w (exist _ k about_k)). { repeat split. simpl. assumption. now apply (subseq_incr bps). assert (H_trans := about_subseq_last bps_no bps d). spec H_trans. rewrite bps_no_length; omega. spec H_trans. rewrite bps_length; omega. spec H_trans. assumption. spec H_trans. exact bps_no_subseq. now apply (le_trans (last bps_no d) (last bps d) (length w)). } exists (exist _ bps_no H); simpl in *. split. apply subseq_incl in bps_no_subseq. assumption. right. intros. destruct bp1 as [bp1 about_bp1]; destruct bp2 as [bp2 about_bp2]; unfold breakpoint_predicate in *. simpl in *. apply (In_nth _ _ d) in about_bp1. apply (In_nth _ _ d) in about_bp2. destruct about_bp1 as [i [i_pos i_eq]]. destruct about_bp2 as [j [j_pos j_eq]]. spec no i j. spec no. rewrite bps_no_length in i_pos, j_pos. split. eapply increasing_nth_lt. destruct H as [_ [bps_no_incr bps_no_last]]. exact bps_no_incr. rewrite bps_no_length; assumption. rewrite bps_no_length; assumption. rewrite i_eq, j_eq. assumption. assumption. spec f_correct (nth i bps_no d) (nth j bps_no d). rewrite <- i_eq. rewrite <- j_eq. destruct f_correct as [_ f_correct]. apply f_correct. assumption. Qed. Theorem Theorem_of_Ramsey_duo_prop : forall (k : block_pumping_constant), exists rk : block_pumping_constant, rk >= k /\ forall w : word, forall bps : breakpoint_set rk w, forall (P : nat -> nat -> Prop), exists bps' : breakpoint_set k w, sublist bps' bps /\ ((forall bp1 bp2 : breakpoint bps', bp1 < bp2 -> (P bp1 bp2)) \/ (forall bp1 bp2 : breakpoint bps', bp1 < bp2 -> ~ (P bp1 bp2))). Proof. intro k. assert (H_ramsey := Ramsey_single_prop k). destruct k as [k about_k]; unfold p_predicate in about_k. spec H_ramsey. simpl; omega. destruct H_ramsey as [rk [rk_fact H_ramsey]]. simpl in rk_fact. assert (about_rk : rk >= 2). omega. exists (exist p_predicate rk about_rk). split. simpl. assumption. intros w bps P. destruct bps as [bps [bps_length [bps_incr bps_last]]]. simpl in *. spec H_ramsey bps bps_length P. destruct H_ramsey as [yes | no]. - destruct yes as [bps_yes [bps_yes_length [bps_yes_subseq yes]]]. assert (breakpoint_set_predicate bps_yes w (exist _ k about_k)). { repeat split. simpl. assumption. now apply (subseq_incr bps). assert (H_trans := about_subseq_last bps_yes bps d). spec H_trans. rewrite bps_yes_length; omega. spec H_trans. rewrite bps_length; omega. spec H_trans. assumption. spec H_trans. exact bps_yes_subseq. now apply (le_trans (last bps_yes d) (last bps d) (length w)). } exists (exist _ bps_yes H); simpl in *. split. apply subseq_incl in bps_yes_subseq. assumption. left. intros. destruct bp1 as [bp1 about_bp1]; destruct bp2 as [bp2 about_bp2]; unfold breakpoint_predicate in *. simpl in *. apply (In_nth _ _ d) in about_bp1. apply (In_nth _ _ d) in about_bp2. destruct about_bp1 as [i [i_pos i_eq]]. destruct about_bp2 as [j [j_pos j_eq]]. spec yes i j. spec yes. rewrite bps_yes_length in i_pos, j_pos. split. eapply increasing_nth_lt. destruct H as [_ [bps_yes_incr bps_yes_last]]. exact bps_yes_incr. rewrite bps_yes_length; assumption. rewrite bps_yes_length; assumption. rewrite i_eq, j_eq. assumption. assumption. rewrite <- i_eq. rewrite <- j_eq. apply yes. - destruct no as [bps_no [bps_no_length [bps_no_subseq no]]]. assert (breakpoint_set_predicate bps_no w (exist _ k about_k)). { repeat split. simpl. assumption. now apply (subseq_incr bps). assert (H_trans := about_subseq_last bps_no bps d). spec H_trans. rewrite bps_no_length; omega. spec H_trans. rewrite bps_length; omega. spec H_trans. assumption. spec H_trans. exact bps_no_subseq. now apply (le_trans (last bps_no d) (last bps d) (length w)). } exists (exist _ bps_no H); simpl in *. split. apply subseq_incl in bps_no_subseq. assumption. right. intros. destruct bp1 as [bp1 about_bp1]; destruct bp2 as [bp2 about_bp2]; unfold breakpoint_predicate in *. simpl in *. apply (In_nth _ _ d) in about_bp1. apply (In_nth _ _ d) in about_bp2. destruct about_bp1 as [i [i_pos i_eq]]. destruct about_bp2 as [j [j_pos j_eq]]. spec no i j. spec no. rewrite bps_no_length in i_pos, j_pos. split. eapply increasing_nth_lt. destruct H as [_ [bps_no_incr bps_no_last]]. exact bps_no_incr. rewrite bps_no_length; assumption. rewrite bps_no_length; assumption. rewrite i_eq, j_eq. assumption. assumption. rewrite <- i_eq. rewrite <- j_eq. apply no. Qed.
\documentstyle[11pt]{book} \hfuzz 10.0pt \begin{document} \chapter{MULTI/PLEX} \section{Introduction} This document describes MULTI/PLEX, a software component for automatically constructing parsers and generators from a single high-level BNF language specification. This allows the rapid development of translators and front- and back-ends for CAD tools. PLEX, a lexical analyzer generator for Prolog is a subsystem of MULTI/PLEX. MULTI/PLEX frees the translator developer to concentrate on the issues of semantic equivalence by automating the construction of tokenizers, parsers, and printers and manages the common data structures. These tasks are accomplished by dynamically transforming language specifications into Prolog programs and executing them. Unlike previous compiler-compilers MULTI/PLEX does not require intermediate compilation steps. New parsers and generators can be constructed and executed at runtime from user modifiable language specifications. Many engineering specification and data languages have been created in recent years. Such proliferation is probably a necessary characteristic of such a fertile period of advancing technology, but it requires a massive software development effort to build the necessary translators. The magnitude of this effort goes largely unnoticed because it is considered to be a minor part of a CAD environment. While each individual translator may not seem important, the number of such translators is quite large. There are several reasons why CAD software organizations have not taken a general approach to this problem: \begin{itemize} \item{} A general translation capability would make it easy for customers to defect to other tool sets. \item{} It is cheaper in the short term to create only the specific translator needed at the moment. \item{} A widely varying range of quality is required from these translators. In some cases, a simple hack which works only on certain data files may be sufficient. \item{} Usually only one direction of translation is needed for a given pair of languages. \end{itemize} Previous work has shown that Prolog is a good language for developing multi-lingual translators [Reintjes87]. Unfortunately, adding a new language in this previous translation system required work by an experienced Prolog programmer. Even the relatively simple task of writing an efficient tokenizer requires the programmer to consider such issues as indexing, determinism, the efficiency of arithmetic tests and non-backtrackable I/O. The lack of widespread literacy in logic programming means that few programmers are available to work on such systems. This system both acknowledges this lack of literacy and works toward eliminating it. While this translator does not require its users to become proficient in Prolog, it does give them a logical language in which to specify the information about the languages to be translated. This specification language is a superset of Prolog in the same way that YACC and LEX are supersets of C. That is, most of the difficult aspects of lexical and syntax analysis are handled at a high level, but the native language, in this case Prolog, is available for general programming. While MULTIPLEX can streamline the process of building tokenizers, parsers, and generators in Prolog, the architecture of this program was only partially motivated by software engineering considerations. We are also fulfilling a legal requirement by decoupling the language description from the body of the translation system. This program was developed to translate circuit synthesis library models from one vendor to another. Unfortunately, each of these vendors consider the syntactic details of their language to be proprietary information. Thus, if our translation program contained specific information about these languages, we could not distribute the program without a myriad of licensing (and presumably, royalty) agreements. In short, for legal purposes, the translation program cannot embody any specific information about the languages it is to translate. Stated bluntly, this might be enough to discourage anyone from undertaking such a project. However, this restriction provided the needed motivation to design MULTIPLEX as a kind of ``translation synthesizer''. Therefore, not only are there not be enough Prolog programmers to produce front- and back-ends for all of the necessary languages, but it would literally be against the law to sell a translator that was so constructed. Once we had the requirement that the language-specific information be external to the program, this led naturally toward efforts to make these specifications as concise and simple as possible. Figure 1 shows how MULTIPLEX performs a translation by using the information in language specification files. \def\boxone#1{ \put(19,30){\line(1,0){67}} % horiz top \put(19,0){\line(1,0){67}} % horiz bottom \put(20,0){\line(0,1){30}} % vert left \put(85,0){\line(0,1){30}} % vert right \put(25,15){#1} } \def\boxtwo#1#2{ \put(19,30){\line(1,0){80}} % horiz top \put(19,0){\line(1,0){80}} % horiz bottom \put(20,0){\line(0,1){30}} % vert left \put(98,0){\line(0,1){30}} % vert right \put(25,17){#1} \put(25,7){#2} } \def\circleone#1#2{\circle{#1}\put(-17,-4){#2}} \def\circletwo#1#2#3{\circle{#1}\put(-17,0){#2}\put(-15,20){#3}} \picture(200,150)(-70,0) \put(90,90){\vector(0,-1){15}} \put(90,30){\vector(0,1){15}} \put(20,60){\vector(1,0){30}} \put(130,60){\vector(1,0){30}} \linethickness{2pt} \put(0,60){\circleone{40}{Data A}} \put(30,90){\boxtwo{\ Spec File}{\ Language A}} \put(30,45){\boxtwo{MULTIPLEX}{\ \ Translator}} \put(30,0){\boxtwo{\ Spec File}{\ Language B}} \put(180,60){\circleone{40}{Data B}} \endpicture \vskip 1.0cm \centerline{\bf Figure 1. MULTIPLEX Translation Data Flow} \vskip 0.2cm \subsection{MULTIPLEX BNF} We refer to the MULTIPLEX specification language as BNF because of its similarity with this standard form. Prolog DCG's and YACC syntax are characterized by the way they hide the list of tokens being parsed. We go one step further and hide the parse-tree as well, thus making our language a purer form of syntax for which the Backus-Naur (nee Normal) Form has become a standard notation. We stray from pure BNF with a single built-in goal which relates the information in the syntax to the ``hidden'' parse-tree (actually, there are many other built-in functions that the user can employ, such as those for syntax errors, to stray ever farther from pure BNF). A MULTIPLEX specification consists of one or more lexical specifications (called lexicons) which look suspiciously like rules for the UNIX LEX utility [Lesk75]. The primary difference is that the actions are written in Prolog rather than ``C''. We allow multiple lexicons because of the multi-level nature of many languages (discussed in section 4.3) and also because a single grammar might cover data from a number of different files, each with different lexical conventions. The lexical specification is followed by the grammar rules which take the form of BNF with special calls which relate the data in the language to an internal structure. These calls will either insert or extract information from the underlying data structure depending upon whether the grammar is being used to parse or generate a description. Because we wish to parse and generate languages from a single specification, cuts and if-then-else structures are noticeably absent. \subsection{Comparison with LEX, YACC and AWK} LEX, YACC, and AWK are three of the primary language processing tools associated with UNIX systems. LEX and YACC are universally used for building front-ends for complex language processing programs, such as compilers, while AWK is frequently used for simple translation and filtering tasks. AWK is usually described as a user-programmable filter and LEX and YACC as tools to build compilers. But filters and compilers simply define two ends of the spectrum of translators. Even GREP can described as a translator which converts a file containing general patterns of text, to a specific subset of that file. In this spectrum of functionality from simple filters to compilers these programs perform many of the same tasks. AWK, with its fixed lexical analyzer, might be thought of as less powerful than tools built with LEX and YACC. At the same time it is more convenient to use because it eliminates the intermediate compilation steps. MULTIPLEX implements the general aspects of LEX and YACC while having the dynamic characteristics of AWK. In addition, its YACC-like grammar definition specifies a generator (or pretty-printer) for each language as well as a parser. It thus improves upon its predecessors in the following ways: \begin{itemize} \item{} It eliminates intermediate file and compilation steps by providing an end-user language which specifies and drives the translation task. \item{} Lexical and grammatical information are combined in a single specification. \item{} It constructs generators as well as parsers from the grammatical specifications. \item{} It allows any number of lexical analyzers and parsers to coexist in a single application. \end{itemize} \section{The MULTIPLEX Program} The specification file contains the information necessary to read data in a specific format. The definitions in this file can express all of the ways in which such library models might be different. The translation system itself provides a simple data structure which serves as a repository for the information which is common to these languages. Because we are dealing with Hardware Description languages, this includes the general concepts of delay constraints, combinatorial, and sequential machine descriptions. The specification file and the MULTI/PLEX program thus interact on three fronts. First, lexical definitons in the specification file define the tokenizers to scan the input data file. Second, the BNF-style grammar rules in the specification define the file access and grammatical structure of the data and relate this to the internal data structure. More detail on PLEX, the lexical analyzer generator can be found in the PLEX documentation. \subsection{The BNF Grammar Rules} The user writes MULTI/PLEX grammar rules to define the language and relate the data objects to generic data-types which will be common to all such inter-translatable languages. These grammar rules frequently contain calls to MULTIPLEX built-in functions. In addition to {\tt update//1} which accesses the internal data structure, we have hierarchy management commands {\tt up//0} and {\tt down//1} and the formatting commands: {\tt newline//0}, {\tt indent//0}, and {\tt undent//0}. A built-in programmable expression parser ({\tt expression//1}) is also built into MULTIPLEX. An example set of grammar rules is given below: \begin{verbatim} lang_file ::= file(name.xyz,xyz), cell. cell ::= down(Name), cell(Name), up. cell(Name) ::= [ Type ], [ '(' ], arguments(Params), [')'], [ begin, Name ], statements, [ end ], optional([Name]), [';'], update(cell_info(Type,Params)). statements ::= value_attribute, statements. statements ::= cell, statements. statements ::= []. value_attribute ::= [ Type, :, Name ], value(V), [ ';' ], update(value_attribute(Type,Name,V)). value(Vs) ::= [ '(' ], arguments(Vs). value(V) ::= [ V ]. arguments([]) ::= [')']. arguments(V) ::= [V, ')']. arguments([V|Vs]) ::= [V], more_values(Vs). \end{verbatim} \section{Using MULTIPLEX to Build Translators} This section describes how to use MULTIPLEX, a program which automatically constructs and then executes simple translators from a declarative specification of the languages involved. It automates the construction of tokenizers and parsers and provides management of common data structures, freeing the user to concentrate on the issues of semantic equivalence. This is accomplished by dynamically transforming language specifications into Prolog programs and executing them. Unlike most other language processing tools, this program does not require intermediate compilation steps. The MULTIPLEX system is a highly flexible tool which can be used in three distinct ways. It can be used directly as a simple translator, it can be used analogously to LEX [Lesk75] and YACC [Johnson78] to generate Prolog source code for lexical analyzers, parsers, and pretty-printers, or it can be used as a subroutine library in building complex translators or compilers which have dynamic language handling capabilities. A dynamic language handling tool is one which does not require compilation steps. Thus AWK is an example of a dynamic tool whereas LEX and YACC are not. \subsection{MULTIPLEX as a translator} As a stand-alone program, MULTIPLEX will create parsers and generators from a pair of language specifications and then translate a data file from one language to the other. The parsers and generators communicate by accessing the internal database with the same interface. When parsing, the {\tt update//1} predicate is used to store information into the common data structure. When printing, it is used to retrieve information which then drives the ``reverse-grammar'' which generates the textual form of a language. The primary difference between the parser and generator is {\it when} they call {\tt update//1}. The generator calls {\tt update//1} first to see if there is any data to drive the grammar rule describing the output text while the parser calls {\tt update//1} only after it has successfully parsed a grammatical structure and wishes to save the information. The command-line to perform a translation between EDIF and Synopsys format would be: \begin{verbatim} % multiplex source.edif target.syn \end{verbatim} This use of MULTIPLEX assumes the existence of {\tt edif.spec} and {\tt syn.spec} containing declarative descriptions of these two languages. Most importantly, it assumes these descriptions are compatible in the sense that all references to the internal representation use common identifiers. In this way, information stored during the parsing of EDIF can be looked-up during the Synopsys generation. As an example of this, consider files describing the German and Spanish languages. For a translation to succeed these definitions must have a common identifier for identifying an element of data. While each of the languages contain the notion of gender, it is unnecessary to store this information in the database. In fact, we specifically exclude this information from the database because gender is a property of a language, and is generally not an important part of the underlying information. For example, because ``cat'' is feminine in german and masculine in spanish, preserving the gender would result in an incorrect translation. The specifications for German and Spanish which will correctly translate {\it die Katze} to {\it el gato} are given below. \begin{figure}[htb] \begin{verbatim} german lexicon "[A-Za-z]+" is Wort if (text(T),name(Wort,T)) ; "[ ,\t\n]" is R if switch(german,R). german ::= file('name.german',german), subjekt, beliebige_subjekte. beliebige_subjekte ::= subjekt, beliebige_subjekte. beliebige_subjekte ::= []. subjekt ::= artikel(Gender), hauptwort(N,Gender), update(subject(N)). hauptwort(dog, maennlich) ::= [ 'Hund' ]. hauptwort(cat, weiblich) ::= [ 'Katze' ]. artikel(mannlich) ::= [ der ]. artikel(weiblich) ::= [ die ]. artikel(saechlich) ::= [ das ]. \end{verbatim} \caption{MULTI/PLEX Grammar for German} \end{figure} \begin{figure}[htb] \begin{verbatim} spanish lexicon "[a-z]+" is Palabra if (text(T), name(Palabra,T)); "[ ,\t\n]" is R if switch(spanish,R). spanish ::= file('name.sp',spanish), sujeto, sujetivos_opcionales. sujecto ::= articulo(Gender), nombre(N,Gender), update(subject(N)). sujetivos_opcionales ::= sujeto, sujetivos_opcionales. sujetivos_opcionales ::= []. nombre(dog, masculino) ::= [ perro ]. nombre(cat, masculino) ::= [ gato ]. articulo(masculino) ::= [ el ]. articulo(feminino) ::= [ la ]. \end{verbatim} \caption{MULTI/PLEX Specification for Spanish} \end{figure} In this case, the corresponding English words (subject, dog and cat) are the common identifiers. Note that keywords (e.g., {\tt subject}) as well as the data ({\tt cat, dog}) must be compatible between languages. This simple model works best when the languages represent identical levels of detail and have corresponding statements and sub-elements. However, we cannot expect translation to consist of a one-for-one rewriting of statements. In general, a translation also requires computation (cf. [Tofte90]). Because the specification language is Prolog, general predicates can be included in the language specification and executed as part of the parser or generator. A more general feature to reconcile differences between the structure of input and output languages was developed in [Reintjes87] and this is also available within MULTIPLEX. \subsection{MULTIPLEX as a compiler-compiler} For a translation between two highly complex or widely differing languages, a programmer will need more control over the translation process. Because multiplex always creates a tokenizer, parser, and generator for each language it uses, we can ask multiplex simply to print the source code for these modules. Then the user can compile these modules into a specialized program of his or her own design. MULTIPLEX can be asked to perform like LEX, YACC, or a previously undefined program which produces pretty-printers. In other words, to produce source code defining tokenizer, parser, or pretty-printer subroutines. MULTIPLEX can be used in the following ways. \begin{itemize} \item{\bf multiplex -lex xyz} Generates a lexical analyzer from the description in {\tt xyz.spec}. This lexical analyzer will be written into the file {\tt xyz\_lex.pl}. \item{\bf multiplex -parser xyz} Produces a parser for the language described in {\tt xyz.spec}. This file will be named {\tt xyz\_parse.pl} and will contain predicates in a module named {\tt xyz\_parse}. \item{\bf multiplex -printer xyz} Creates a printer for the language described in {\tt xyz.spec}. This file will be named {\tt xyz\_print.pl} and will contain predicates in a module named {\tt xyz\_print}. \item{\bf multiplex -all xyz} Produces all three of the above files simultaneously. \end{itemize} To understand the relationship between these first two uses of MULTIPLEX, imagine that we want to produce a specialized translator which can read only EDIF and produce descriptions in only Synopsys format. We may wish to deliver a tool with this diminished capability for any number of reasons. For example: \begin{enumerate} \item{} We do not want the customer to have a general translation capability. \item{} We do not want to require the user to have the language specification files loaded on the system (remember that MULTIPLEX must open and read the files {\tt edif.spec} and {\tt syn.spec}). \item{} We do not want the user to have access to the language specification files because they contain proprietary information. \item{} We do not want the translator to spend the start-up time reading the language descriptions. Because we know which languages will be required, we want them pre-loaded. Furthermore, we know that this particular translator (EDIF $\rightarrow$ Synopsys) will not require a pretty-printer for EDIF or a parser for Synopsys. \item{} We gain a performance advantage by pre-compiling the language handling modules. \end{enumerate} \subsection{Using MULTIPLEX to build Higher-Order tools} We might describe MULTIPLEX as a high-order tool because it performs operations on a language defined at runtime. Similar tools, more complex than mere translators, can be built by using MULTIPLEX as a starting point. A user-defined program which uses MULTIPLEX in this way can be defined as follows: \begin{verbatim} :- use_module(library(multiplex)). runtime_entry(start) :- unix(argv(Args)), multiplex_set_options(Args, Rest), my_set_options(Rest, InFile, OutFile), multiplex_input(InFile, Data), my_algorithm(Data, ProcessedData), multiplex_output(OutFile, ProcessedData). \end{verbatim} The user can define {\tt my\_set\_options/2} and {\tt my\_algorithm/2} and depend upon MULTIPLEX to construct and execute the parser and printer. The predicates {\tt multiplex\_input/2} and {\tt multiplex\_output/2} construct and then call the parser/generator code. The user can direct MULTIPLEX to build the parser/generator (without executing it) by calling {\tt multiplex\_build/1} with the name of the language. Once a language has been loaded in this fashion it will not be re-loaded subsequent calls to {\tt multiplex\_build/1} or {\tt multiplex\_input(output)/2}. A more complex translator, which does ``feature mapping'' between structurally diverse languages, can be built by using MULTIPLEX as a {\it module} and specifying a transformation function which will turn the input parse-tree into the necessary output parse-tree. The {\it parse-tree} is simply a list containing either the primitive data elements {\tt ID:Type:Value} or the hierarchical objects {\tt subcell(ID,ListofObjects)}. \begin{verbatim} :- use_module(library(multi)). :- use_module(library(strings), [concat_atom/2]). runtime_entry(start) :- unix(argv(Args)), multiplex_set_options(Args, [In, Out]), multiplex_suffix(In, _, InLang), multiplex_input(In, Data), multiplex_suffix(Out,_,OutLang), transform(InLang, OutLang, Data, TData), multiplex_output(Out, TData). runtime_entry(start) :- format('Usage: translate ~a ~a ~a~n', [ '[-Cv]','input.lang1', 'output.lang2' ]). \end{verbatim} \begin{verbatim} transform(In, Out) --> compatible(hierarchy_model, In, Out), compatible(timing_model, In, Out), compatible(naming_model, In, Out). \end{verbatim} The first subgoal in {\tt transform//2} simply reverses the parse-tree. This needs to be done even if the input language is identical to the output language because we built the parse tree back-to-front. \begin{verbatim} compatible(_, X, X, D, D) :- !. compatible(Relation, In, Out, DIn, DOut) :- Test1 =.. [Relation, In, R1], Test2 =.. [Relation, Out, R2], call(Test1), call(Test2), ( R1 == R2 -> DIn = DOut ; reconcile_by(R1, R2, Function), Transform =.. [Function, DIn, DOut], ( call(Transform) -> true ; message_hook('transform error'(Function,In,Out),_,_) ) ). \end{verbatim} The first clause of {\tt compatible/5} states that a language is always compatible with itself. This corresponds to the use of this tool as a syntax checker, back-annotation tool, or pretty-printer. The next clause determines if a particular feature is shared by these (different) languages or if there is a reconciliation function which will make the input structure compatible with the output structure. We can add a wealth of information to this translator by including facts about different language features and ways to reconcile {\it differences between these features} (in contrast to the total differences between the languages). These facts and functions can be built into the translator or brought in as part of the language specification files. This organization is similar to the one developed earlier for the AUNT translator [Reintjes87]. \begin{verbatim} hierarchy_model(syn, one_level). hierarchy_model(fpdl, one_level). hierarchy_model(spice, flat). hierarchy_model(edif, multi_level). \end{verbatim} \begin{verbatim} naming_model(_, normal). \end{verbatim} \begin{verbatim} timing_model(syn, clock). timing_model(fpdl, clock). timing_model(foresight, fixed). timing_model(vhdl, delta). timing_model(dsl, zero_delay). \end{verbatim} \begin{verbatim} reconcile_by(multi_level, one_level, flatten1). reconcile_by(multi_level, flat, flatten). reconcile_by(synopsys, zero_delay, remove_delay). reconcile_by(zero_delay, synopsys, insert_delay). \end{verbatim} \section{The MULTIPLEX Program} The specification file contains the information necessary to read data in a specific format. The definitions in this file can express all of the ways in which such library models might be different. The translation system itself provides a simple data structure which serves as a repository for the information which is common to these languages. Because we are dealing with Hardware Description languages, this includes the general concepts of delay constraints, combinatorial, and sequential machine descriptions. The specification file and the MULTI/PLEX program thus interact on three fronts. First, lexical definitons in the specification file define the tokenizers to scan the input data file. Second, the BNF-style grammar rules in the specification define the file access and grammatical structure of the data and relate this to the internal data structure. More detail on PLEX, the lexical analyzer generator can be found in the PLEX documentation. \subsection{The BNF Grammar Rules} The user writes MULTI/PLEX grammar rules to define the language and relate the data objects to generic data-types which will be common to all such inter-translatable languages. These grammar rules frequently contain calls to MULTIPLEX built-in functions. In addition to {\tt update//1} which accesses the internal data structure, we have hierarchy management commands {\tt up//0} and {\tt down//1} and the formatting commands: {\tt newline//0}, {\tt indent//0}, and {\tt undent//0}. A built-in programmable expression parser ({\tt expression//1}) is also built into MULTIPLEX. An example set of grammar rules is given below: \begin{verbatim} lang_file ::= file(name.xyz,xyz), cell. cell ::= down(Subcell), cell(Name), up, update(subcell(Name, cell, Subcell). cell(Name) ::= [ Type ], [ '(' ], arguments(Params), [')'], [ begin, Name ], statements, [ end ], optional([Name]), [';'], update(cell_info(Type,Name,Params)). statements ::= value_attribute, statements(Data). statements ::= cell, statements(Data). statements ::= []. value_attribute ::= [ Type, :, Name ], value(V), [ ';' ], update(value_attribute(Type,Name,V)). value(Vs) ::= [ '(' ], arguments(Vs). value(V) ::= [ V ]. arguments([]) ::= [')']. arguments(V) ::= [V, ')']. arguments([V|Vs]) ::= [V], more_values(Vs). \end{verbatim} As an example of these grammar transformations the {\tt more\_values//1} rule is split into predictive parser and text generator versions, both of which are completely deterministic. \begin{verbatim} in_more_values(Vs) --> [X], in_more_values1(X,Vs). in_more_values1(',',[V|Vs]) --> [V], in_more_values(Vs). in_more_values1(')',[]) --> []. \end{verbatim} \begin{verbatim} out_more_values([]) --> ")". out_more_values([V|Vs]) --> [0',|Cs], { my_name(V,Cs) }, out_more_values(Vs). \end{verbatim} \subsection{Internal Data Representation} The {\tt update(s)//1} routines in the grammar specification are used to insert or extract specific bits in the data structure representing the file to be translated. Because we do not want to distinguish between lookup and and assignment, we have a dictionary similar to that described by [Warren80]. This data structure can contain primitive or hierarchical data elements. A primitive data element is any Prolog term, while a hierarchical data-type is usually a term like {\tt subcell(Name, Type, Children)} Where {\tt Children} is also the argument to a {\tt down/1} call which moves the grammar down into a lower-level of hierarchy. The hierarchical capabilities of this generalized ``dictionary'' function allows the user to manage complex ``scoping'' information along with the basic data elements, all without requiring direct manipulations of the Prolog structures. The ``built-ins'' to support this access are {\tt update(s)//1}, {\tt seq\_update(s)/1}, and {\tt examine(s)//1}. The latter being an example of non-intrusive access -- e.g one that doesn't remove the data element during printing. During parsing, {\tt examine//1} acts the same as {\tt update//1}. This data structure is currently a simple list of whatever terms are defined by the user. This document provides some guidelines for selecting these structures. By using a standard methodology, we are more likely to create a set of compatible parser/generator components. For example, when using the hierarchy control non-terminals, we recommend using the term {\tt subcell(Name, Type, Subcell)} to store the subcells created by the hierachy commands. This use of hierarchy is demonstrated in the {\tt cell//0} rule in the grammar above. Like the normal expansion of DCGs, the term-expansion performed by MULTI/PLEX adds two arguments for the data-structure (the {\it parse-tree}, in traditional terms). By limiting access to this structure to a procedural interface, we ensure that we can transform a grammar into a generator. The {\tt update//1} access routines add information to this structure during parsing and extract the information during printing. In addition to adding the data arguments to all user-defined grammar rules, we will remove the special goals {\tt newline//0}, {\tt indent//0}, and {\tt undent//0} from the parsing version and convert literals and tokens to character strings for the printing version. The directives {\tt down/1} and {\tt up/0} create a hierarchical structure. Finally, we must delay the {\tt update//1} goals in the parser and advance them in the printer so that the data is inserted or extracted appropriately depending upon the intended direction of the grammar. This tool depends heavily on the module system. The principle advantage of this is that we can preserve the predicate names in the user's grammar while insuring that different grammars do not interfere with each other. This tool is designed to be a language ``multiplexer'' with numerous parsers and generators active at one time. There are three parts to a grammar rule and the order of these three parts are different for parsers and printers. A parser rule consists of grammar terminals and non-terminals, followed by user code to process the data ({\tt user//1} goals), and finally data-base updates. In a printer, this order is reversed and we have data-base access routines first, then the user code, followed by the grammar terminals and non-terminals which actually produce the text. As an example, we give the following rule and its transformations. \begin{verbatim} % MULTI/PLEX BNF rule ::= keyword(K), [:], value(V), user(norm_value(V, NV)), update(keyword(K,NV)). \end{verbatim} \begin{verbatim} % PARSER rule(D0, D, T0, T) :- keyword(K,D0, D1, T0, T1), D1 = [:|D2], value(V,D2, D2, T1, T2), % Parse tokens { norm_value(V,NV) }, % Compute NV from V update(keyword(K,NV),D2, D). % Add to data-base \end{verbatim} \begin{verbatim} % PRINTER rule(D0, D, Chs0, Chs) :- update(keyword(K,NV), D0, D), % Extract from data-base { norm_value(V,NV) }, % Compute V from NV keyword(K, D1, D2, Chs0, Chs1), append(":",Chs2, Chs1), value(V, D2, D, Chs2, Chs). % Produce Text \end{verbatim} The term-expansion produces the different goal orderings according to the following algorithm. To produce a parse-clause, it sweeps the user code toward the end of the clause body, then sweeps the data base updates to the end of the clause, so they will be immediately after the {\tt user/1} goals. To produce the print clause, it sweeps the {\tt user/1} goals to the front and then sweeps the data-base updates to be in front of them. \subsection{Data Management} The greatest difficulty in building a universal translator is to design the data structures and data management routines. We allow the person writing language specifications to use any representation they want for individual items. The system currently maintains these items in a list but this could be changed to improve efficiency without requiring changes to the language specifications. The {\tt update//1} goals manage the primary data structure representing the information being translated. The bi-directionality of this data structure makes it similar to the compiler dictionary described by [Warren80]. \section{Advanced Features} The next two sections describe MULTIPLEX facilities for handling multi-level languages, tokenizing input files, and the related facilities for general expression parsing. \subsection{File I/O: The Tokenizer and Printer} Calls to tokenizers are made from the {\tt file//2} goals in the grammar. When the user specifies a file name and a lexicon, the file is tokenized by that tokenizer before being passed to the parser. By allowing file specification and tokenizers to be part of the grammar, a grammar spanning many files and many different lexicons can be defined. Tokenizing the file includes optional macro-preprocessing, for example, in ``C'' or Verilog. If the language specification contains no ``macro'' definitions, {\tt process\_macros/3} simply returns the token-list. The corresponding predicate in the printer sends the output to the specified file {\it after} the textual form of the language has been produced by the grammar. \subsection{Parsing Multi-level Languages} Some languages achieve a superficial simplicity by embedding complex constructions inside quoted strings. We describe these as multi-level languages. Two examples are the {\it Foresight} language from NuThena and the synthesis library format of Synopsys. In the case of {\it Foresight}, its LISP syntax is undisturbed by the ADA-like {\it MINISPEC} language that lurks within. Similarly, the Synopsys language defines the boolean function of a cell with the following syntax: \begin{verbatim} function: "a + b'c" \end{verbatim} The surface grammar of this statement is just: \begin{verbatim} statement ::= [function, :, quote(double(S)),';']. \end{verbatim} With this rule, we can ``parse'' a Synopsys library without dealing with the complexities of this boolean expression. But at some point we will need to parse the expression within the string {\tt S}. Like the {\it MINISPEC} language in Foresight, there must be another part of the tool which interprets this string. Because many powerful languages are not multi-level (VHDL, Verilog) we want MULTIPLEX to span these levels transparently and derive the complete information of the language. This poses several problems. We cannot assume that the the same lexical rules apply to the embedded language. Thus, we need to specify which {\tt lexicon} to use. We introduce {\tt parse\_string//2} which has the form: \begin{verbatim} parse_string(Lexicon, Rule) \end{verbatim} By including this in a grammar rule, we can interrupt the normal token stream, interpret the next token as a user-defined {\tt String} type containing a character string. We extract this character string, apply the tokenizer identified by {\tt Lexicon} and parse this token list with {\tt Rule}. After this non-terminal is processed, the appropriate variables in {\tt Rule} (if any) will have the parsed structure and the original token list of the parent language will once again be in effect. To use this feature to analyze the {\tt function:} statement in a Synopsys library, we say: \begin{verbatim} statement ::= [function, :], parse_string(syn, expression(F)), [';']. \end{verbatim} \subsection{Facilities for Expression Parsing} In two of the languages we've considered, embedded languages are used for the representation of boolean expressions. Synopsys, for example represents the function for a library cell: \begin{verbatim} function: "(a + b')' ((c b)+a')(d+e')" \end{verbatim} This string contains a complex expression syntax with a postfix unary operator (') and an implicit binary operator which has stronger precedence than the {\tt +} operator. If the user can specify the precedence, fixity, and appearance of all operators, together with a rule for primary expressions, MULTIPLEX will correctly parse all expressions. This feature addresses two important difficulties in language-based tool development. Documentation for many industrial languages frequently gives little or no guidance for implementing expression parsers. When such documents include BNF rules for expression syntax, the definitions are often left-recursive, and thus unsuitable for a recursive descent parser. For these reasons we do not want the language-spec writer to spend time defining complex rules for expressions. Because all expression parsers have similar features, different types of expressions can be distinguished by specifying a few facts about the language. For a relatively simple language (FPDL) the specification is: \begin{verbatim} operator(200,xfy, or) ::= ['|']. operator(300,xfy, and) ::= ['&']. operator(100, fx, not) ::= ['~']. primary(Expr) ::= ['('], expression(E), [')']. primary(V) ::= value(V). \end{verbatim} \centerline{\bf Figure 3: Example operator and primary expressions definition} \vskip 0.2cm With these definitions ({\tt value/1} is defined elsewhere in the user specification), a call to the MULTIPLEX built-in grammar rule {\tt expression(E)} will parse expressions like: \begin{verbatim} A & 1 & ~B | ((A | B & C) & ~(A|B)& | 0) \end{verbatim} To define a language with function expressions in which the function arguments can also be expressions, we need write only: \begin{verbatim} primary(function(F,As)) ::= name(F), ['('], arguments(As). arguments([]) ::= [')']. arguments([A|As]) ::= expression(A), more_args(As). more_args([]) ::= [')']. more_args([A|As]) ::= [','], expression(A), more_args(As). \end{verbatim} The problems presented by the Synopsys language (the implicit AND operator, postfix and prefix NOT operator) are easily handled by this system. The following definitions will work: \begin{verbatim} operator(200,xfy, or) ::= [+]. operator(300,xfy, and) ::= [*]. operator(300, xy, and) ::= []. operator(100, xf, not) ::= ['''']. \end{verbatim} \centerline{\bf Figure 4: Operators for Logic Formula with Implicit AND} \vskip 0.2cm Note that the Synopsys language also contains an explicit AND operator (*) and so we include this rule before the "empty AND" rule. Internally, these are represented identically as {\tt expr(Left,and,Right)} and when the textual form of the language is being produced, the first rule is used causing the (*) operator to appear explicitly in all generated formula. The operator specifications in MULTIPLEX are similar to those in Prolog, even in the choice of the argument order for {\tt (Precedence, Fixity, Operator)}. The most important difference is the addition of the {\tt xy} fixity specification defining the implied, or invisible, operator. Clearly, a language can have only one implied operator, such as AND in logical formula and multiplication in arithmetic formulas. \section{Future Work} We have created a language-independent translation system which can construct and execute specialized translators with no need for separate compilation steps. This program is used by DASIX/Intergraph to translate VLSI synthesis model libraries. Although this program was developed as a translator, it could be used as a front- and back-end of any tool to compile, analyze, and verify formal languages. The stand-alone program {\tt multiplex} functions as three separate tools to create tokenizers, parsers, or pretty-printers from language specifications. These tools, here embedded in the MULTIPLEX program, improve on their predecessors (LEX and YACC) in the following ways: \begin{itemize} \item{} Automatic generation of printers (text generators) complements the support for tokenizers and parsers. \item{} Any number of tokenizer/parser/generators can co-exist because of the unique naming of synthesized predicates. \item{} Intermediate compilation steps are eliminated -- the program proceeds immediately from reading the language spec to parsing the language. \end{itemize} The design of this program depended heavily on Prolog features such as user-defined term-expansion, grammar rule notation, and the ability to modify Prolog syntax through operator definitions. The program could not exist in its present form without Prolog's ability to manipulate code as data, and to do this immediately prior to execution. This project fulfilled the requirement that the language descriptions be ``externalized'', but much can be done to both simplify and extend the expressiveness of these descriptions. At present, the user must avoid left-recursive grammar rules and though rules may backtrack, they must be deterministic in the sense that they have only one solution if the {\tt -C} optimization is to be used. In the future we may find that complex languages require us to re-order clauses as well as goals to achieve complete bi-directionality. This would require a technique more general than term-expansion in order to operate on predicates rather than clauses. The program transformation techniques described here can provide non-expert programmers with special purpose languages which are easier to use than Prolog. Although these languages are less powerful than Prolog, they can greatly widen the audience for logic programming. The use of Prolog syntax for the external specification language simplifies the design of this tool and encourages us to consider the general use of Prolog as an embedded (user oriented) language in CAD systems. \end{document}
export mis1 """ Solving MIS problem with simple branching algorithm. """ function mis1(eg::EliminateGraph) N = nv(eg) if N == 0 return 0 else vmin, dmin = mindegree_vertex(eg) return 1 + neighborcover_mapreduce(y->eliminate(mis1, eg, NeighborCover(y)), max, eg, vmin) end end
(* Banach-Tarski paradox. *) Require Import Utf8 List Relations NPeano Wf_nat. Import ListNotations. Require Import Misc. Inductive letter := la | lb. Inductive free_elem := FE : letter → bool → free_elem. Notation "'ạ'" := (FE la false). Notation "'ạ⁻¹'" := (FE la true). Notation "'ḅ'" := (FE lb false). Notation "'ḅ⁻¹'" := (FE lb true). Definition negf '(FE t d) := FE t (negb d). Theorem letter_dec : ∀ l1 l2 : letter, {l1 = l2} + {l1 ≠ l2}. Proof. intros. now destruct l1, l2; try (now left); right. Defined. Theorem free_elem_dec : ∀ e₁ e₂ : free_elem, { e₁ = e₂ } + { e₁ ≠ e₂ }. Proof. intros. destruct e₁ as (t₁, d₁). destruct e₂ as (t₂, d₂). destruct (letter_dec t₁ t₂) as [H₁| H₁]; [ subst t₂ | ]. destruct (Bool.bool_dec d₁ d₂) as [H₂| H₂]; [ subst d₂ | ]. now left. right; intros H; apply H₂. now injection H. right; intros H; apply H₁. now injection H. Qed. Theorem letter_dec_diag : ∀ t, letter_dec t t = left (eq_refl _). Proof. intros t. destruct (letter_dec t t) as [p| p]; [ | exfalso; now apply p ]. destruct t; refine (match p with eq_refl => eq_refl end). Qed. Definition letter_opp '(FE l₁ d₁) '(FE l₂ d₂) := if letter_dec l₁ l₂ then if Bool.bool_dec d₁ d₂ then False else True else False. Theorem letter_opp_dec : ∀ e₁ e₂, {letter_opp e₁ e₂} + {not (letter_opp e₁ e₂)}. Proof. intros. destruct e₁ as (x₁, d₁). destruct e₂ as (x₂, d₂); simpl. destruct (letter_dec x₁ x₂) as [Hx| Hx]. destruct (Bool.bool_dec d₁ d₂) as [Hd| Hd]; [ | left; constructor ]. now right. now right. Defined. Theorem letter_opp_inv : ∀ x d, letter_opp (FE x d) (FE x (negb d)). Proof. intros. unfold letter_opp. rewrite letter_dec_diag, bool_dec_negb_r. constructor. Qed. Theorem letter_opp_iff : ∀ x₁ d₁ x₂ d₂, letter_opp (FE x₁ d₁) (FE x₂ d₂) ↔ x₁ = x₂ ∧ d₂ = negb d₁. Proof. intros x₁ d₁ x₂ d₂. split; intros H. unfold letter_opp in H. destruct (letter_dec x₁ x₂) as [H₁| H₁]; [ | easy ]. split; [ easy | ]. destruct (Bool.bool_dec d₁ d₂) as [H₂| H₂]; [ easy | ]. now apply neq_negb, not_eq_sym. destruct H; subst x₂ d₂. apply letter_opp_inv. Qed. Theorem letter_opp_negf : ∀ e₁ e₂, letter_opp e₁ e₂ ↔ e₁ = negf e₂. Proof. intros. destruct e₁ as (t₁, d₁). destruct e₂ as (t₂, d₂). split; intros H. apply letter_opp_iff in H. destruct H; subst t₂ d₂; simpl. now rewrite Bool.negb_involutive. injection H; intros; subst; simpl. rewrite letter_dec_diag, bool_dec_negb_l. constructor. Qed. Theorem no_fixpoint_negf : ∀ e, negf e ≠ e. Proof. intros * H. destruct e as (t, d). injection H. apply Bool.no_fixpoint_negb. Qed. Theorem negf_involutive : ∀ e, negf (negf e) = e. Proof. intros (t, d); simpl. now rewrite Bool.negb_involutive. Qed. Theorem letter_opp_negf_r : ∀ e, letter_opp e (negf e). Proof. intros. apply letter_opp_negf. now rewrite negf_involutive. Qed. Theorem letter_opp_sym : ∀ e₁ e₂, letter_opp e₁ e₂ → letter_opp e₂ e₁. Proof. intros * H. apply letter_opp_negf in H. subst e₁. apply letter_opp_negf_r. Qed. Theorem negf_eq_eq : ∀ e₁ e₂, negf e₁ = negf e₂ → e₁ = e₂. Proof. intros e₁ e₂ Hn. destruct e₁ as (t₁, d₁). destruct e₂ as (t₂, d₂). simpl in Hn. injection Hn; intros H₁ H₂; subst. now apply negb_eq_eq in H₁; subst d₁. Qed.
(* Copyright 2014 Cornell University Copyright 2015 Cornell University Copyright 2016 Cornell University Copyright 2017 Cornell University This file is part of VPrl (the Verified Nuprl project). VPrl 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. VPrl 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 VPrl. If not, see <http://www.gnu.org/licenses/>. Websites: http://nuprl.org/html/verification/ http://nuprl.org/html/Nuprl2Coq https://github.com/vrahli/NuprlInCoq Authors: Abhishek Anand & Vincent Rahli *) Require Export Coq.Logic.ConstructiveEpsilon. Require Export stronger_continuity_defs. Require Export stronger_continuity_defs0. Require Export per_props_atom. Require Export terms5. Require Export per_props_nat2. Lemma equality_mkc_union_tnat_unit {o} : forall lib (a b : @CTerm o), equality lib a b (mkc_union mkc_tnat mkc_unit) <=> ({k : nat , ccequivc lib a (mkc_inl (mkc_nat k)) # ccequivc lib b (mkc_inl (mkc_nat k))} {+} (ccequivc lib a (mkc_inr mkc_axiom) # ccequivc lib b (mkc_inr mkc_axiom))). Proof. introv. rw @equality_mkc_union. split; intro k; exrepnd; repndors; exrepnd; spcast; dands; eauto 3 with slow. - allrw @equality_in_tnat. allunfold @equality_of_nat; exrepnd; spcast. left. exists k; dands; spcast. + eapply cequivc_trans;[apply computes_to_valc_implies_cequivc; exact k2|]. apply cequivc_mkc_inl_if. apply computes_to_valc_implies_cequivc; auto. + eapply cequivc_trans;[apply computes_to_valc_implies_cequivc; exact k4|]. apply cequivc_mkc_inl_if. apply computes_to_valc_implies_cequivc; auto. - allrw @equality_in_unit; repnd; spcast. right; dands; spcast. + eapply cequivc_trans;[apply computes_to_valc_implies_cequivc; exact k2|]. apply cequivc_mkc_inr_if. apply computes_to_valc_implies_cequivc; auto. + eapply cequivc_trans;[apply computes_to_valc_implies_cequivc; exact k4|]. apply cequivc_mkc_inr_if. apply computes_to_valc_implies_cequivc; auto. - left. apply cequivc_sym in k2; apply cequivc_mkc_inl_implies in k2. apply cequivc_sym in k1; apply cequivc_mkc_inl_implies in k1. exrepnd. exists b1 b0; dands; spcast; auto. eapply equality_respects_cequivc_left;[exact k4|]. eapply equality_respects_cequivc_right;[exact k3|]. apply equality_in_tnat. unfold equality_of_nat. exists k0; dands; spcast; auto; apply computes_to_valc_refl; eauto 3 with slow. - right. apply cequivc_sym in k0; apply cequivc_mkc_inr_implies in k0. apply cequivc_sym in k; apply cequivc_mkc_inr_implies in k. exrepnd. exists b1 b0; dands; spcast; auto. eapply equality_respects_cequivc_left;[exact k3|]. eapply equality_respects_cequivc_right;[exact k1|]. apply equality_in_unit. dands; spcast; apply computes_to_valc_refl; eauto 3 with slow. Qed. Lemma equality_in_mkc_texc {o} : forall lib (a b N E : @CTerm o), equality lib a b (mkc_texc N E) <=> {n1 : CTerm , {n2 : CTerm , {e1 : CTerm , {e2 : CTerm , a ===e>(lib,n1) e1 # b ===e>(lib,n2) e2 # equality lib n1 n2 N # equality lib e1 e2 E }}}}. Proof. introv. split; introv k; exrepnd; spcast. - unfold equality in k; exrepnd. inversion k1; subst; try not_univ. clear k1. match goal with | [ H : per_texc _ _ _ _ _ |- _ ] => rename H into p end. allunfold @per_texc; exrepnd; spcast; computes_to_value_isvalue. apply p1 in k0. unfold per_texc_eq in k0; exrepnd; spcast. exists n1 n2 e1 e2; dands; spcast; auto. + eapply eq_equality1; eauto. + eapply eq_equality1; eauto. - allunfold @equality; exrepnd. rename eq0 into eqn. rename eq into eqe. exists (per_texc_eq lib eqn eqe). dands; auto. + apply CL_texc. unfold per_texc. exists eqn eqe N N E E. dands; spcast; auto; try (apply computes_to_valc_refl; apply iscvalue_mkc_texc). + unfold per_texc_eq. exists n1 n2 e1 e2; dands; spcast; auto. Qed. Lemma tequality_mkc_texc {o} : forall lib (N1 E1 N2 E2 : @CTerm o), tequality lib (mkc_texc N1 E1) (mkc_texc N2 E2) <=> (tequality lib N1 N2 # tequality lib E1 E2). Proof. introv; split; intro teq; repnd. - unfold tequality in teq; exrepnd. inversion teq0; try not_univ; allunfold @per_texc; exrepnd. computes_to_value_isvalue; sp; try (complete (spcast; sp)). + exists eqn; sp. + exists eqe; sp. - unfold tequality in teq0; exrepnd. rename eq into eqn. unfold tequality in teq; exrepnd. rename eq into eqe. exists (per_texc_eq lib eqn eqe); apply CL_texc; unfold per_texc. exists eqn eqe N1 N2 E1 E2; sp; spcast; try (apply computes_to_valc_refl; apply iscvalue_mkc_texc). Qed. Lemma disjoint_nat_exc {o} : forall lib (a b : @CTerm o), disjoint_types lib mkc_tnat (mkc_texc a b). Proof. introv mem; repnd. allrw @equality_in_tnat. allunfold @equality_of_nat; exrepnd; spcast; GC. allrw @equality_in_mkc_texc; exrepnd; spcast. eapply computes_to_valc_and_excc_false in mem0; eauto. Qed. Lemma tequality_mkc_singleton_uatom {o} : forall lib (n1 n2 : @get_patom_set o), tequality lib (mkc_singleton_uatom n1) (mkc_singleton_uatom n2) <=> n1 = n2. Proof. introv. unfold mkc_singleton_uatom. rw @tequality_set; split; introv k; repnd; subst; tcsp. - clear k0. pose proof (k (mkc_utoken n1) (mkc_utoken n1)) as h; clear k. autodimp h hyp. { apply equality_in_uatom_iff. exists n1; dands; spcast; try (apply computes_to_valc_refl; apply iscvalue_mkc_utoken). } allrw @mkcv_cequiv_substc. allrw @mkc_var_substc. allrw @mkcv_utoken_substc. allrw @tequality_mkc_cequiv. destruct h as [h h2]; clear h2. autodimp h hyp; spcast; eauto 3 with slow. allrw @cequivc_mkc_utoken; auto. - dands;[apply tequality_uatom|]. introv e. apply equality_in_uatom_iff in e; exrepnd; spcast. allrw @mkcv_cequiv_substc. allrw @mkc_var_substc. allrw @mkcv_utoken_substc. allrw @tequality_mkc_cequiv. allapply @computes_to_valc_implies_cequivc. split; intro k; spcast. + eapply cequivc_trans in k;[|apply cequivc_sym;exact e1]. allrw @cequivc_mkc_utoken; subst; auto. + eapply cequivc_trans in k;[|apply cequivc_sym;exact e0]. allrw @cequivc_mkc_utoken; subst; auto. Qed. Lemma tequality_mkc_ntexc {o} : forall lib n1 n2 (E1 E2 : @CTerm o), tequality lib (mkc_ntexc n1 E1) (mkc_ntexc n2 E2) <=> (n1 = n2 # tequality lib E1 E2). Proof. introv. unfold mkc_ntexc. rw @tequality_mkc_texc. rw @tequality_mkc_singleton_uatom; auto. Qed. Lemma type_mkc_ntexc {o} : forall lib n (E : @CTerm o), type lib (mkc_ntexc n E) <=> (type lib E). Proof. introv. rw @tequality_mkc_ntexc; split; sp. Qed. Lemma inhabited_type_mkc_cequiv {o} : forall lib (t1 t2 : @CTerm o), inhabited_type lib (mkc_cequiv t1 t2) <=> ccequivc lib t1 t2. Proof. introv. unfold inhabited_type; split; introv k; exrepnd. - allunfold @member; allunfold @equality; allunfold @nuprl; exrepnd. inversion k0; subst; try not_univ. allunfold @per_cequiv; sp. uncast; computes_to_value_isvalue. discover; sp. - exists (@mkc_axiom o). apply member_cequiv_iff; auto. Qed. Lemma equality_in_mkc_singleton_uatom {o} : forall lib a b (n : @get_patom_set o), equality lib a b (mkc_singleton_uatom n) <=> (a ===>(lib) (mkc_utoken n) # b ===>(lib) (mkc_utoken n)). Proof. introv. unfold mkc_singleton_uatom. rw @equality_in_set. allrw @mkcv_cequiv_substc. allrw @mkc_var_substc. allrw @mkcv_utoken_substc. allrw @inhabited_type_mkc_cequiv. allrw @equality_in_uatom_iff. split; intro k; exrepnd; spcast; dands; tcsp. - eapply close_type_sys_per_ffatom.cequivc_utoken in k;[|exact k1]. apply computes_to_valc_isvalue_eq in k; try (eqconstr k); eauto 3 with slow. dands; spcast; auto. - eapply close_type_sys_per_ffatom.cequivc_utoken in k;[|exact k1]. apply computes_to_valc_isvalue_eq in k; try (eqconstr k); eauto 3 with slow. dands; spcast; auto. - introv e. allrw @mkcv_cequiv_substc. allrw @mkc_var_substc. allrw @mkcv_utoken_substc. allrw @equality_in_uatom_iff; exrepnd; spcast. apply tequality_mkc_cequiv. allapply @computes_to_valc_implies_cequivc. split; intro h; spcast. + eapply cequivc_trans in h;[|apply cequivc_sym;exact e1]. allrw @cequivc_mkc_utoken; subst; auto. + eapply cequivc_trans in h;[|apply cequivc_sym;exact e0]. allrw @cequivc_mkc_utoken; subst; auto. - exists n; dands; spcast; auto. - spcast. allapply @computes_to_valc_implies_cequivc; auto. Qed. Lemma equality_in_mkc_ntexc {o} : forall lib n (a b E : @CTerm o), equality lib a b (mkc_ntexc n E) <=> {n1 : CTerm , {n2 : CTerm , {e1 : CTerm , {e2 : CTerm , n1 ===>(lib) (mkc_utoken n) # n2 ===>(lib) (mkc_utoken n) # a ===e>(lib,n1) e1 # b ===e>(lib,n2) e2 # equality lib e1 e2 E }}}}. Proof. introv. rw @equality_in_mkc_texc; split; intro k; exrepnd; spcast. - allrw @equality_in_mkc_singleton_uatom; repnd; spcast. exists n1 n2 e1 e2; dands; spcast; auto. - exists n1 n2 e1 e2; dands; spcast; auto. allrw @equality_in_mkc_singleton_uatom; dands; spcast; auto. Qed. Lemma equality_in_natE {o} : forall lib n (a b : @CTerm o), equality lib a b (natE n) <=> (equality_of_nat lib a b {+} (ccequivc lib a (spexcc n) # ccequivc lib b (spexcc n))). Proof. introv. unfold natE, with_nexc_c. pose proof (equality_in_disjoint_bunion lib a b mkc_tnat (mkc_ntexc n mkc_unit)) as h. autodimp h hyp. { unfold mkc_ntexc; apply disjoint_nat_exc. } rw h; clear h. rw @type_mkc_ntexc. split; intro k; repnd; dands; eauto 3 with slow; repndors; tcsp; allrw @equality_in_tnat; allrw @equality_in_mkc_ntexc; exrepnd; spcast; tcsp; allrw @equality_in_unit; repnd; spcast. - allapply @computes_to_excc_implies_cequivc. allapply @computes_to_valc_implies_cequivc. right; dands; spcast. + eapply cequivc_trans;[exact k5|]. unfold spexc. apply cequivc_mkc_exception; auto. + eapply cequivc_trans;[exact k6|]. unfold spexc. apply cequivc_mkc_exception; auto. - left; allrw @equality_in_tnat; auto. - right; allrw @equality_in_mkc_ntexc. allunfold @spexc. apply cequivc_sym in k0; apply cequivc_sym in k. apply cequivc_exception_implies in k0. apply cequivc_exception_implies in k. exrepnd. allapply @cequivc_axiom_implies. allapply @cequivc_utoken_implies. exists x0 x c0 c; dands; spcast; auto. allrw @equality_in_unit; dands; spcast; auto. Qed. Lemma dec_reduces_ksteps_excc {o} : forall lib k (t v : @CTerm o), (forall x, decidable (x = get_cterm v)) -> decidable (reduces_ksteps_excc lib t v k). Proof. introv d. destruct_cterms; allsimpl. pose proof (dec_reduces_in_atmost_k_steps_exc lib k x0 x d) as h. destruct h as [h|h];[left|right]. - spcast; tcsp. - intro r; spcast; tcsp. Qed. Lemma reduces_ksteps_excc_spexcc_decompose {o} : forall lib (k : nat) a (t : @CTerm o), reduces_ksteps_excc lib t (spexcc a) k -> {k1 : nat & {k2 : nat & {k3 : nat & {a' : CTerm & {e' : CTerm & k1 + k2 + k3 <= k # reduces_in_atmost_k_stepsc lib t (mkc_exception a' e') k1 # reduces_in_atmost_k_stepsc lib a' (mkc_utoken a) k2 # reduces_in_atmost_k_stepsc lib e' mkc_axiom k3 }}}}}. Proof. introv r. pose proof (dec_reduces_in_atmost_k_steps_excc lib k t (spexcc a)) as h; allsimpl. try (fold (spexc a) in h). autodimp h hyp; eauto 3 with slow. destruct h as [d|d]. - apply reduces_in_atmost_k_steps_excc_decompose in d; eauto 2 with slow. - provefalse; spcast; sp. Qed. Lemma reduces_ksteps_excc_impossible1 {o} : forall lib k1 k2 (t : @CTerm o) a n, reduces_ksteps_excc lib t (spexcc a) k1 -> reduces_ksteps_excc lib t (mkc_nat n) k2 -> False. Proof. introv r1 r2; spcast. eapply reduces_in_atmost_k_steps_excc_impossible1 in r1; eauto. Qed. Lemma dec_reduces_ksteps_excc_nat {o} : forall lib k (t : @CTerm o), decidable {n : nat & reduces_ksteps_excc lib t (mkc_nat n) k}. Proof. introv; destruct_cterms; allsimpl. pose proof (dec_reduces_in_atmost_k_steps_exc_nat lib k x) as h. destruct h as [h|h];[left|right]. - exrepnd; exists n; spcast; tcsp. - intro r; exrepnd; destruct h; exists n; spcast; tcsp. Qed. Lemma equality_in_natE_implies {o} : forall lib (t u : @CTerm o) a, equality lib t u (natE a) -> equality_of_nat_tt lib t u [+] (cequivc lib t (spexcc a) # cequivc lib u (spexcc a)). Proof. introv equ. assert {k : nat , {m : nat , (reduces_ksteps_excc lib t (mkc_nat m) k # reduces_ksteps_excc lib u (mkc_nat m) k) {+} (reduces_ksteps_excc lib t (spexcc a) k # reduces_ksteps_excc lib u (spexcc a) k)}} as j. { apply equality_in_natE in equ. repndors. - unfold equality_of_nat in equ; exrepnd; spcast. allrw @computes_to_valc_iff_reduces_in_atmost_k_stepsc; exrepnd. exists (Peano.max k0 k1) k. left; dands; spcast. + apply (reduces_in_atmost_k_stepsc_le _ _ _ _ (Peano.max k0 k1)) in equ4; eauto 3 with slow; try (apply Nat.le_max_l; auto). apply reduces_in_atmost_k_steps_excc_can in equ4; tcsp. + apply (reduces_in_atmost_k_stepsc_le _ _ _ _ (Peano.max k0 k1)) in equ2; eauto 3 with slow; try (apply Nat.le_max_r; auto). apply reduces_in_atmost_k_steps_excc_can in equ2; tcsp. - repnd; spcast. apply cequivc_spexcc in equ0. apply cequivc_spexcc in equ. exrepnd. allrw @computes_to_valc_iff_reduces_in_atmost_k_stepsc; exrepnd. allrw @computes_to_excc_iff_reduces_in_atmost_k_stepsc; exrepnd. exists (Peano.max (k3 + k + k0) (k4 + k1 + k2)) 0. right; dands; spcast. + apply (reduces_in_atmost_k_steps_excc_le_exc _ (k3 + k + k0)); eauto 3 with slow; tcsp; try (apply Nat.le_max_l; auto). pose proof (reduces_in_atmost_k_steps_excc_exception lib k k0 n0 e0 (mkc_utoken a) mkc_axiom) as h. repeat (autodimp h hyp); tcsp; exrepnd. pose proof (reduces_in_atmost_k_steps_excc_trans2 lib k3 i t (mkc_exception n0 e0) (mkc_exception (mkc_utoken a) mkc_axiom)) as q. repeat (autodimp q hyp); exrepnd. apply (reduces_in_atmost_k_steps_excc_le_exc _ i0); tcsp; try omega. + apply (reduces_in_atmost_k_steps_excc_le_exc _ (k4 + k1 + k2)); eauto 3 with slow; tcsp; try (apply Nat.le_max_r; auto). pose proof (reduces_in_atmost_k_steps_excc_exception lib k1 k2 n e (mkc_utoken a) mkc_axiom) as h. repeat (autodimp h hyp); tcsp; exrepnd. pose proof (reduces_in_atmost_k_steps_excc_trans2 lib k4 i u (mkc_exception n e) (mkc_exception (mkc_utoken a) mkc_axiom)) as q. repeat (autodimp q hyp); exrepnd. apply (reduces_in_atmost_k_steps_excc_le_exc _ i0); tcsp; try omega. } apply (constructive_indefinite_ground_description nat (fun x => x) (fun x => x)) in j; auto. { exrepnd. apply (constructive_indefinite_ground_description nat (fun x => x) (fun x => x)) in j0; auto. - exrepnd. pose proof (dec_reduces_ksteps_excc lib x t (mkc_nat x0)) as h. autodimp h hyp; simpl; eauto 3 with slow. pose proof (dec_reduces_ksteps_excc lib x t (spexcc a)) as q. autodimp q hyp; simpl; try (fold (spexc a)); eauto 3 with slow. pose proof (dec_reduces_ksteps_excc lib x u (mkc_nat x0)) as j. autodimp j hyp; simpl; eauto 3 with slow. pose proof (dec_reduces_ksteps_excc lib x u (spexcc a)) as l. autodimp l hyp; simpl; try (fold (spexc a)); eauto 3 with slow. destruct h as [h|h]; destruct q as [q|q]; destruct j as [j|j]; destruct l as [l|l]; try (complete (eapply reduces_ksteps_excc_impossible1 in h;[|exact q]; tcsp)); try (complete (eapply reduces_ksteps_excc_impossible1 in j;[|exact l]; eauto; tcsp)); try (complete (provefalse; repndors; repnd; tcsp)). { left; exists x0; dands; split; simpl; eauto 3 with slow; exists x; spcast; apply reduces_in_atmost_k_steps_excc_can_implies in h; apply reduces_in_atmost_k_steps_excc_can_implies in j; allunfold @reduces_in_atmost_k_stepsc; allsimpl; allrw @get_cterm_apply; tcsp. } { right. apply reduces_ksteps_excc_spexcc_decompose in q. apply reduces_ksteps_excc_spexcc_decompose in l. exrepnd. allunfold @reduces_in_atmost_k_stepsc; allsimpl. allrw @get_cterm_apply; allsimpl. allrw @get_cterm_mkc_exception; allsimpl. dands; apply cequiv_spexc_if; try (apply isprog_apply); try (apply isprog_mk_nat); eauto 3 with slow. - exists (get_cterm a'0) (get_cterm e'0); dands; eauto 3 with slow. unfold computes_to_exception; exists k0; auto. - exists (get_cterm a') (get_cterm e'); dands; eauto 3 with slow. unfold computes_to_exception; exists k1; auto. } - clear j0. introv. pose proof (dec_reduces_ksteps_excc lib x t (mkc_nat x0)) as h. autodimp h hyp; simpl; eauto 3 with slow. pose proof (dec_reduces_ksteps_excc lib x t (spexcc a)) as q. autodimp q hyp; simpl; try (fold (spexc a)); eauto 3 with slow. pose proof (dec_reduces_ksteps_excc lib x u (mkc_nat x0)) as j. autodimp j hyp; simpl; eauto 3 with slow. pose proof (dec_reduces_ksteps_excc lib x u (spexcc a)) as l. autodimp l hyp; simpl; try (fold (spexc a)); eauto 3 with slow. destruct h as [h|h]; destruct q as [q|q]; destruct j as [j|j]; destruct l as [l|l]; tcsp; try (complete (right; intro xx; repndors; repnd; tcsp)). } { clear j; introv. pose proof (dec_reduces_ksteps_excc_nat lib x t) as h. pose proof (dec_reduces_ksteps_excc lib x t (spexcc a)) as q. autodimp q hyp; simpl; try (fold (spexc a)); eauto 3 with slow. pose proof (dec_reduces_ksteps_excc_nat lib x u) as j. pose proof (dec_reduces_ksteps_excc lib x u (spexcc a)) as l. autodimp l hyp; simpl; try (fold (spexc a)); eauto 3 with slow. destruct h as [h|h]; destruct q as [q|q]; destruct j as [j|j]; destruct l as [l|l]; exrepnd; try (destruct (deq_nat n0 n) as [d|d]); subst; tcsp; try (complete (eapply reduces_ksteps_excc_impossible1 in h0; eauto; tcsp)); try (complete (eapply reduces_ksteps_excc_impossible1 in j0; eauto; tcsp)); try (complete (provefalse; repndors; repnd; tcsp)); try (complete (right; intro xx; exrepnd; repndors; repnd; tcsp; try (complete (destruct h; eexists; eauto)); try (complete (destruct j; eexists; eauto)))); try (complete (left; exists n; left; tcsp)); try (complete (left; exists 0; right; tcsp)). right; intro xx; exrepnd; repndors; repnd; tcsp; spcast. allunfold @reduces_in_atmost_k_steps_excc; allsimpl. allunfold @reduces_in_atmost_k_steps_exc. rw xx1 in h0. rw xx0 in j0. inversion h0. inversion j0. allapply Znat.Nat2Z.inj; subst; tcsp. } Qed. Lemma tequality_with_nexc_c {o} : forall lib a1 a2 (T1 T2 E1 E2 : @CTerm o), tequality lib (with_nexc_c a1 T1 E1) (with_nexc_c a2 T2 E2) <=> (a1 = a2 # tequality lib T1 T2 # tequality lib E1 E2). Proof. introv. unfold with_nexc_c. rw @tequality_bunion. rw @tequality_mkc_texc. rw @tequality_mkc_singleton_uatom. split; sp. Qed. Lemma tequality_natE {o} : forall lib (a1 a2 : @get_patom_set o), tequality lib (natE a1) (natE a2) <=> a1 = a2. Proof. introv. unfold natE. rw @tequality_with_nexc_c. allrw @fold_type. split; intro k; repnd; dands; eauto with slow. Qed. Lemma type_natE {o} : forall lib (a : @get_patom_set o), type lib (natE a). Proof. introv. rw @tequality_natE; auto. Qed. Hint Resolve type_natE : slow. Lemma disjoint_nat_unit {o}: forall (lib : @library o), disjoint_types lib mkc_tnat mkc_unit. Proof. introv mem; repnd. allrw @equality_in_tnat. allrw @equality_in_unit. allunfold @equality_of_nat; exrepnd; spcast; GC. computes_to_eqval. Qed. Hint Resolve disjoint_nat_unit : slow. Lemma member_bunion_nat_unit_implies_cis_spcan_not_atom {o} : forall lib (t : @CTerm o) a, member lib t (mkc_bunion mkc_tnat mkc_unit) -> cis_spcan_not_atom lib t a. Proof. introv mem. apply @equality_in_disjoint_bunion in mem; eauto 3 with slow. repnd. clear mem0 mem1. repndors. - apply equality_in_tnat in mem. unfold equality_of_nat in mem; exrepnd; spcast. exists (@mkc_nat o k); dands; spcast; simpl; tcsp. - apply equality_in_unit in mem; repnd; spcast. exists (@mkc_axiom o); dands; spcast; simpl; tcsp. Qed.
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.nat.choose algebra.big_operators open nat finset /-- The binomial theorem -/ theorem add_pow {α : Type*} [comm_semiring α] (x y : α) : ∀ n : ℕ, (x + y) ^ n = (range (succ n)).sum (λ m, x ^ m * y ^ (n - m) * choose n m) | 0 := by simp | (succ n) := have h₁ : x * (x ^ n * y ^ (n - n) * choose n n) = x ^ succ n * y ^ (succ n - succ n) * choose (succ n) (succ n), by simp [_root_.pow_succ, mul_assoc, mul_comm, mul_left_comm], have h₂ : y * (x^0 * y^(n - 0) * choose n 0) = x^0 * y^(succ n - 0) * choose (succ n) 0, by simp [_root_.pow_succ, mul_assoc, mul_comm, mul_left_comm], have h₃ : (range n).sum (λ m, x * (x ^ m * y ^ (n - m) * choose n m) + y * (x ^ succ m * y ^ (n - succ m) * choose n (succ m))) = (range n).sum (λ m, x ^ succ m * y ^ (succ n - succ m) * ↑(choose (succ n) (succ m))), from finset.sum_congr rfl $ λ m hm, begin simp only [mul_assoc, mul_left_comm y, mul_left_comm (y ^ (n - succ m)), mul_comm y], rw [← _root_.pow_succ', add_one, ← succ_sub (mem_range.1 hm)], simp [choose_succ_succ, mul_comm, mul_assoc, mul_left_comm, add_mul, mul_add, _root_.pow_succ] end, by rw [_root_.pow_succ, add_pow, add_mul, finset.mul_sum, finset.mul_sum, sum_range_succ, sum_range_succ', sum_range_succ, sum_range_succ', add_assoc, ← add_assoc ((range n).sum _), ← finset.sum_add_distrib, h₁, h₂, h₃]
\hypertarget{lab-02-variables-arrays-and-scripts}{% \section{Lab 02: Variables, Arrays, and Scripts}\label{lab-02-variables-arrays-and-scripts}} \hypertarget{variables}{% \subsection{Variables}\label{variables}} \begin{frame}{} \protect\hypertarget{section}{} Variables help us represent quantities or expressions in order to make their use and re-use more convenient. \end{frame} \begin{frame}[fragile]{Naming Variables} \protect\hypertarget{naming-variables}{} \begin{itemize}[<+->] \tightlist \item Must start with a letter. \item Followed by letters (a-z, A-Z) or numbers (0-9) or underscores (\_). \item Maximum 65 characters (excluding the .m extension). \item Must not be the same as any MATLAB reserved word. \item Space is not permitted. \item Case sensitive, i.e., \texttt{a\ \textasciitilde{}=\ A}. \end{itemize} \end{frame} \begin{frame}[fragile]{Naming Variables} \protect\hypertarget{naming-variables-1}{} \begin{itemize}[<+->] \tightlist \item Be as descriptive as possible with your variable names. \item Avoid built-in function/variable names (reserved keywords) such as \texttt{pi}, \texttt{sin}, \texttt{exp}, etc. \item Check if a name is already in use: \texttt{which\ variableName} or \texttt{exist\ variableName}. \end{itemize} \end{frame} \begin{frame}{Naming Conventions} \protect\hypertarget{naming-conventions}{} \begin{itemize}[<+->] \tightlist \item snake\_case: writing compound words or phrases in which the elements are separated with one underscore character (\_) and no spaces, e.g.~``foo\_bar''. \item camelCase: writing compound words or phrases such that each word or abbreviation in the middle of the phrase begins with a capital letter, with no intervening spaces or punctuation, e.g.~``fooBar'' \item Other conventions: Hungarian notation, positional notation, etc. \item Reference: \url{https://en.wikipedia.org/wiki/Naming_convention_(programming)} \end{itemize} \end{frame} \begin{frame}{Default Variable Definitions} \protect\hypertarget{default-variable-definitions}{} \begin{table}[!hbtp] \begin{tabular}{rl} Command & Description \\ \hline \texttt{pi} & variable defining $\pi$ \\ \texttt{i} or \texttt{1i} & imaginary number $i = \sqrt{-1}$ \\ \texttt{j} or \texttt{1j} & imaginary number $j = \sqrt{-1}$ \end{tabular} \end{table} \end{frame} \hypertarget{arrays}{% \subsection{Arrays}\label{arrays}} \begin{frame}[fragile]{Array, Vector, and Matrix} \protect\hypertarget{array-vector-and-matrix}{} \begin{itemize}[<+->] \tightlist \item An array is a data form that can hold several values, all of one type. \item A vector is a \(1\)-D array: we can define row vectors, column vectors. \item A matrix is a \(2\)-D array. \item Also, we can define \(N\)-D array. \item The general notation for a vector or matrix is a list of values enclosed in square brackets \texttt{{[}{]}} separated by commas (space) or semi-colons (or the combination). \end{itemize} \end{frame} \begin{frame}[fragile]{Vector: \texttt{{[}{]}}} \protect\hypertarget{vector}{} \begin{itemize}[<+->] \item Row vector: \(x = \begin{bmatrix} 1 & 2 & 3 & 4 \end{bmatrix}\) \begin{verbatim} x = [1,2,3,4] x = [1 2 3 4] \end{verbatim} \item Column vector: \(y = \begin{bmatrix} 1 \\ 2 \\ 3 \\ 4 \end{bmatrix}\) or \(y = \begin{bmatrix} 1 & 2 & 3 & 4\end{bmatrix}^{\top}\) or \(y = x^{\top}\). \begin{verbatim} y = [1;2;3;4] y = transpose([1 2 3 4]) y = [1 2 3 4]' y = x' y = x(:) \end{verbatim} Note: \texttt{\textquotesingle{}} and \texttt{.\textquotesingle{}} are the infix notation for \texttt{ctrasnpose}, \texttt{transpose} operation. \end{itemize} \end{frame} \begin{frame}[fragile]{Vector: \texttt{linspace} vs.~\texttt{colon}} \protect\hypertarget{vector-linspace-vs.-colon}{} \begin{itemize}[<+->] \item \texttt{linspace(from,\ to,\ n)} generates \texttt{n} points between \texttt{from} (inclusive) and \texttt{to} (inclusive). For example, \texttt{a\ =\ linspace(2,\ 6,\ 5)\ \ \%\ same\ as\ a\ =\ {[}2\ 3\ 4\ 5\ 6{]}} \item \texttt{colon(from,\ step,\ upper\_bound)} generates points between \texttt{from} (inclusive) and \texttt{upper\_bound} (may not be inclusive) with spacing \texttt{step}. For example, \begin{verbatim} a = colon(2, 1, 6) % same as a = [2 3 4 5 6] a = colon(2, 2, 6) % same as a = [2 4 6] a = colon(2, 1, 7) % same as a = [2 3 4 5 6 7] a = colon(2, 2, 7) % same as a = [2 4 6] \end{verbatim} \item \texttt{from:step:upper\_bound} is same as \texttt{colon(from,\ step,\ upper\_bound)}. \end{itemize} \end{frame} \begin{frame}[fragile]{Vector: \texttt{linspace} vs.~\texttt{colon}} \protect\hypertarget{vector-linspace-vs.-colon-1}{} \begin{itemize}[<+->] \tightlist \item \texttt{linspace(from,\ to,\ n)} is equivalent to \texttt{colon(from,\ (to\ -\ from)\ /\ (n\ -\ 1),\ to)} \item \texttt{colon(from,\ step,\ upper\_bound)} is equivalent to \texttt{linspace(from,\ floor((upper\_bound\ -\ from)\ /\ step)\ *\ step\ +\ from,\ floor((upper\_bound\ -\ from)\ /\ step))} \item Use \texttt{linspace} when the number of points is given. \item Use \texttt{colon} when the spacing/step size is given. \end{itemize} \end{frame} \begin{frame}[fragile]{Matrix: \texttt{{[}{]}}} \protect\hypertarget{matrix}{} Define a \(2 \times 3\) matrix \(A = \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{bmatrix}\) \begin{verbatim} A = [1,2,3;4,5,6] \end{verbatim} or \begin{verbatim} row1 = [1,2,3] row2 = [4,5,6] A = [row1;row2] \end{verbatim} or \begin{verbatim} col1 = [1;4] col2 = [2;5] col3 = [3;6] A = [col1,col2,col3] \end{verbatim} \end{frame} \begin{frame}[fragile]{Matrix: \texttt{zeros}, \texttt{ones}, \texttt{eye}, \texttt{rand}, \texttt{randn}, \texttt{magic}} \protect\hypertarget{matrix-zeros-ones-eye-rand-randn-magic}{} \begin{itemize}[<+->] \item \texttt{zeros(m,\ n)}: define a \texttt{m}-by-\texttt{n} matrix with zeros. \begin{verbatim} zeroRowVec = zeros(5, 1) zeroColVec = zeros(1, 5) zeroMatrix = zeros(5, 5) zeroMatrix = zeros(5) \end{verbatim} \item \texttt{ones(m,\ n)}: define a \texttt{m}-by-\texttt{n} matrix with ones. \item \texttt{eye(m,\ n)}: define a \texttt{m}-by-\texttt{n} matrix with diagonals being ones. \item \texttt{rand(m,\ n)}: define a \texttt{m}-by-\texttt{n} matrix with uniformly distributed numbers. \item \texttt{randn(m,\ n)}: define a \texttt{m}-by-\texttt{n} matrix with normally distributed numbers. \item \texttt{magic(n)}: define a \texttt{n}-by-\texttt{n} magic square with row sum, column sum and diagonal sum being equal. \end{itemize} \end{frame} \begin{frame}[fragile]{Dimension: \texttt{size}, \texttt{length}, \texttt{reshape}} \protect\hypertarget{dimension-size-length-reshape}{} \begin{itemize}[<+->] \item \texttt{size(array)}: size of \texttt{array}. If \texttt{array} is \texttt{n}-dimensional, \texttt{size} will return a vector of length \texttt{n}. \item \texttt{size(array,\ 1)}: number of rows of \texttt{array}. \item \texttt{size(array,\ 2)}: number of columns of \texttt{array}. \item \texttt{length(vec)}: length of vector \texttt{vec}, equivalent to \texttt{max(size(vec))}. \item \texttt{reshape(array,\ dim1,\ dim2,\ dim3,\ ...)}. \begin{verbatim} rowVec = 1:8 matrix = reshape(rowVec, 2, 4) % same as matrix = [1,3,5,7;2,4,6,8] \end{verbatim} \item \texttt{reshape(array,\ prod(size(array)),\ 1)} is same as \texttt{array(:)}. \end{itemize} \end{frame} \begin{frame}[fragile]{\(N\)-D array: \texttt{reshape}} \protect\hypertarget{n-d-array-reshape}{} Define 3-D array: \begin{verbatim} rowVec = 1:8 array = reshape(rowVec, 2, 2, 2); length(size(array)) % check the dimension \end{verbatim} \end{frame} \begin{frame}[fragile]{1-D Array: Slicing} \protect\hypertarget{d-array-slicing}{} \begin{itemize}[<+->] \item Define a row vector \texttt{rowVec}: \begin{verbatim} rowVec = [2,4,6,8,10] rowVec = linspace(2,10,5) rowVec = colon(2,2,10) % or rowVec = 2:2:10 \end{verbatim} \item \texttt{array(i)}: the \texttt{i}-th entry of \texttt{array}, where \texttt{i} is called the index: \begin{table}[!hbtp] \centering \begin{tabular}{cccccc} \toprule \verb|i| & 1 & 2 & 3 & 4 & 5 \\ \midrule \verb|rowVec(i)| & 2 & 4 & 6 & 8 & 10 \\ \bottomrule \end{tabular} \end{table} \end{itemize} \end{frame} \begin{frame}[fragile]{1-D Array: Slicing} \protect\hypertarget{d-array-slicing-1}{} \begin{table}[!hbtp] \centering \begin{tabular}{cccccc} \toprule \verb|i| & 1 & 2 & 3 & 4 & 5 \\ \midrule \verb|rowVec(i)| & 2 & 4 & 6 & 8 & 10 \\ \bottomrule \end{tabular} \end{table} \begin{itemize}[<+->] \item Extract one entry from a vector: For example, to extract \texttt{6} from \texttt{rowVec} and assign it to \texttt{x}: \texttt{x\ =\ rowVec(3)} \item Extract multiple entries from a vector: For example, to extract \texttt{2}, \texttt{6}, \texttt{8} from \texttt{rowVec} and assign it to \texttt{x}: \texttt{x\ =\ rowVec({[}1,3,4{]})} \item Extract multiple continguous entries from a vector: For example, to extract \texttt{4}, \texttt{6}, \texttt{8} from \texttt{rowVec} and assign it to \texttt{x}: \begin{verbatim} x = rowVec([2,3,4]) x = rowVec(2:4) \end{verbatim} \end{itemize} \end{frame} \begin{frame}[fragile]{2-D array: Slicing} \protect\hypertarget{d-array-slicing-2}{} \begin{itemize}[<+->] \item Define a matrix \texttt{mat} \begin{verbatim} mat = reshape(1:8, 2, 4) \end{verbatim} \item \texttt{array(i,\ j)}: the entry of \texttt{array} at row \texttt{i} and column \texttt{j}, where \texttt{i} is colled row index, \texttt{j} is called column index: \begin{table}[!hbtp] \centering \begin{tabular}{c|cccc} \toprule \diagbox{\texttt{i}}{\texttt{mat(i, j)}}{\texttt{j}} & 1 & 2 & 3 & 4 \\ \hline 1 & 1 & 3 & 5 & 7 \\ 2 & 2 & 4 & 6 & 8 \\ \bottomrule \end{tabular} \end{table} \end{itemize} \end{frame} \begin{frame}[fragile]{2-D array: Slicing} \protect\hypertarget{d-array-slicing-3}{} \begin{table}[!hbtp] \centering \begin{tabular}{c|cccc} \toprule \diagbox{\texttt{i}}{\texttt{mat(i, j)}}{\texttt{j}} & 1 & 2 & 3 & 4 \\ \hline 1 & 1 & 3 & 5 & 7 \\ 2 & 2 & 4 & 6 & 8 \\ \bottomrule \end{tabular} \end{table} Extract multiple rows and multiple columns from \texttt{mat}: For example, to extract entries at row \texttt{1}, row \texttt{2}, and column \texttt{2}, column \texttt{4}: \begin{verbatim} A = mat([1,2], [2,4]) A = mat(1:2, [2,4]) A = mat(1:end, [2,4]) A = mat(:, [2,4]) \end{verbatim} \end{frame} \begin{frame}[fragile]{Generate a \(3\)-D Array using Slicing} \protect\hypertarget{generate-a-3-d-array-using-slicing}{} \begin{verbatim} slice1 = [1,2;3,4] slice2 = [5,6;7,8] C(:,:,1) = slice1 C(:,:,2) = slice2 \end{verbatim} \end{frame} \begin{frame}[fragile]{Concatenate Arrays} \protect\hypertarget{concatenate-arrays}{} \begin{verbatim} row1 = [1,2,3] row2 = [4,5,6] rowVec = [row1,row2] % rowVec = [1,2,3,4,5,6] matrix = [row1;row2] % matrix = [1,2,3;4,5,6] matrix1 = [matrix1;matrix2] % same as matrix1 = [1,2,3;4,5,6;1,2,3;4,5,6] matrix2 = [matrix1,matrix2] % same as matrix2 = [1,2,3,1,2,3;4,5,6,4,5,6] \end{verbatim} \end{frame} \begin{frame}[fragile]{1-D Array: Append/Delete Element} \protect\hypertarget{d-array-appenddelete-element}{} \begin{verbatim} % 1-D array rowVec = 1:5 rowVec(end + 1) = 6 % append 6 to rowVec rowVec = [rowVec,7] % append 7 to rowVec rowVec(5) = [] % delete 5 from rowVec rowVec(2:4) = [] % delete 2, 3, 4 from rowVec \end{verbatim} \end{frame} \begin{frame}[fragile]{2-D Array: Append/Delete Element} \protect\hypertarget{d-array-appenddelete-element-1}{} \begin{verbatim} % 2-D array matrix = magic(5) matrix(:, end + 1) = 1:5 % append a column vector matrix = [matrix,[6:10]'] % append a column vector matrix(end + 1, :) = 1:7 % append a row vector matrix = [matrix;8:14] % append a row vector matrix(:,6) = [] % delete column 2 matrix(:,3:5) = [] % delete column 3, 4, 5 matrix(2:4,:) = [] % delete row 2, 3, 4 \end{verbatim} \end{frame} \begin{frame}[fragile]{Char Array vs.~String Array} \protect\hypertarget{char-array-vs.-string-array}{} \begin{verbatim} str = "abc" arrayOfChars1 = 'abc' arrayOfChars2 = ['a','b','c'] arrayOfChars1 == arrayOfChars2 % return logical 1 (true) arrayOfChars1 == str % return logical 1 (true) class(str) % string class(arrayOfChars1) % char [arrayOfChars1,arrayOfChars2] % return 'abcabc' [arrayOfChars1;arrayOfChars2] % return ['abc';'abc'] [str,str] % return ["abc","abc"] [str;str] % return ["abc";"abc"] \end{verbatim} \end{frame} \begin{frame}[fragile]{Cell Array: array of elements of different types} \protect\hypertarget{cell-array-array-of-elements-of-different-types}{} \begin{itemize}[<+->] \item \texttt{cell(n)}: create 1-D cell array of length \texttt{n} \item \texttt{cell(m,n)}: create 2-D cell array of size \texttt{m} by \texttt{n} \item Create a cell array of types \texttt{char}, \texttt{string}, \texttt{double}: \begin{verbatim} cellArray = {[1,2,3], "abc", 'def'} cellArray{1} % return [1,2,3] cellArray{2} % return "abc" cellArray{3} % return 'def' cellArray{4} = 'ghi' cellArray{4} % return 'ghi' \end{verbatim} \end{itemize} \end{frame} \begin{frame}[fragile]{Array Operations: 1-D Array} \protect\hypertarget{array-operations-1-d-array}{} \begin{itemize}[<+->] \tightlist \item \texttt{sum(vec)}/\texttt{prod(vec)}: sum/product of all elements of \texttt{vec}. \item \texttt{max(vec)}/\texttt{min(vec)}: maximum/minimum of \texttt{vec}. \item \texttt{rowVec\ =\ rowVec1\ .*\ rowVec2}: elementwise multiplication, where \texttt{rowVec(i)\ =\ rowVec1(i)\ *\ rowVec2(i)}. \item \texttt{rowVec\ .*\ colVec}: Kronecker product. If \texttt{rowVec} has length \texttt{m} and \texttt{colVec} has length \texttt{n}, then the resulting matrix is \texttt{m}-by-\texttt{n}. \item \texttt{dot(vec1,\ vec2)}: dot product of \texttt{vec1} and \texttt{vec2}, \texttt{vec1} and \texttt{vec2} must be of the same length. \item \texttt{sum(rowVec1\ .*\ rowVec2)}: \texttt{dot(rowVec1,\ rowVec2)}. \item \texttt{rowVec1\ *\ rowVec2\textquotesingle{}}: \texttt{dot(rowVec1,\ rowVec2)}. \item \texttt{indices\ =\ find(vec\ \textgreater{}\ n)}: find indices of elements greater than \texttt{n} in \texttt{vec}. Note: \texttt{\textgreater{}} can also be \texttt{\textless{}}, \texttt{==}. \end{itemize} \end{frame} \begin{frame}[fragile]{Array Operations: 2-D Array} \protect\hypertarget{array-operations-2-d-array}{} \begin{itemize}[<+->] \tightlist \item \texttt{mat\ =\ mat1\ .*\ mat2}: elementwise multiplication, where \texttt{mat(i,\ j)\ =\ mat1(i,\ j)\ *\ mat2(i,\ j)}. \item \texttt{mat\ =\ mat1\ *\ mat2}: matrix multiplication, where \texttt{mat1} is \texttt{m}-by-\texttt{p}, \texttt{mat2} is \texttt{p}-by-\texttt{n}, and \texttt{mat} is \texttt{m}-by-\texttt{n}. \item \texttt{sum/prod(mat,\ \textquotesingle{}all\textquotesingle{})}: sum/product of all elements of \texttt{mat}. \item \texttt{sum/prod(mat,\ 1)}: column sums/products. \item \texttt{sum/prod(mat,\ 2)}: row sums/products. \item \texttt{max/min(mat,\ {[}{]},\ \textquotesingle{}all\textquotesingle{})}: maximum/minimum of \texttt{mat}. \item \texttt{max/min(mat,\ {[}{]},\ 1)}: column maximums/minimums. \item \texttt{max/min(mat,\ {[}{]},\ 2)}: row maximums/minimums. \item \texttt{{[}row,\ col{]}\ =\ find(mat\ \textgreater{}\ n)}: find indices of elements greater than \texttt{n} in \texttt{mat}, \texttt{row}/\texttt{col} stores row/column indices. \end{itemize} \end{frame} \begin{frame}[fragile]{Array Operations: 2-D Array} \protect\hypertarget{array-operations-2-d-array-1}{} \begin{itemize}[<+->] \tightlist \item \texttt{{[}V,\ D{]}\ =\ eig(mat)}: \texttt{V(:,\ i)} and \texttt{D(i,\ i)} are the \texttt{i}-th eigenvector and eigenvalue of \texttt{mat}. \item \texttt{d\ =\ diag(mat,\ k)}: extract \texttt{k}-th diagonal elements that is above (\texttt{k\ \textgreater{}\ 0}) / below (\texttt{k\ \textless{}\ 0}) the main diagonal. \item \texttt{mat\ =\ diag(d,\ k)}: construct a matrix with \texttt{k}-th diagonal elements being \texttt{d}. \item \texttt{mat\ =\ diag(diag(mat,\ k))}: set elements to zero except the \texttt{k}-th diagonal elements. \item \texttt{fliplr(mat)}: flip \texttt{mat} in left/right direction. \item \texttt{flipud(mat)}: flip \texttt{mat} in up/down direction. \item \texttt{rot90(mat,\ k)}: rotate \texttt{mat} \texttt{k\ *\ 90} degrees. \end{itemize} \end{frame} \begin{frame}[fragile]{Application: Image Processing} \protect\hypertarget{application-image-processing}{} \begin{itemize}[<+->] \item A grayscale image is a 2-D array of pixels, each pixel has a integer value that represent depth of color. \item A colored image is a 3-D array of pixels with RGB channels, each channel is a 2-D array. \item \texttt{img\ =\ imread(filename)}: read image from graphics file \texttt{filename} and assign it \texttt{img}. \item \texttt{imshow(img)}: display image \texttt{img} in handle graphics figure. \item \texttt{imwrite(img,\ filename)}: write image \texttt{img} to graphics file named \texttt{filename}. \begin{verbatim} uw = imread('UW.png'); uwFlipud = flipud(uw); imshow(uwFlipud); imwrite(uwFlipud, 'UW_flipud.png'); \end{verbatim} \end{itemize} \end{frame} \begin{frame}{Summary} \protect\hypertarget{summary}{} \begin{table}[!hbtp] \begin{tabular}{rl} Command & Description \\ \hline \texttt{transpose} or \texttt{'} & Non-conjugate transpose of a vector \\ \texttt{linspace} & Linearly spaced vector \\ \texttt{logspace} & Logarithmically spaced vector \\ \texttt{colon} or \texttt{:} & Colon \\ \texttt{zeros} & Zeros array \\ \texttt{ones} & Ones array \\ \texttt{eye} & Identity matrix \\ \texttt{rand} & Uniformly distributed pseudorandom numbers \\ \texttt{randn} & Normally distributed pseudorandom numbers \\ \texttt{magic} & Magic square \\ \texttt{size} & Size of array \\ \texttt{length} & Length of vector \\ \texttt{reshape} & Reshape array \\ \end{tabular} \end{table} \end{frame} \begin{frame}{Summary} \protect\hypertarget{summary-1}{} \begin{table}[!hbtp] \begin{tabular}{rl} Command & Description \\ \hline \texttt{diag} & Diagonal matrices and diagonals of a matrix \\ \texttt{cell} & Create cell array \\ \texttt{sum}/\texttt{prod} & Sum/Product of elements \\ \texttt{min}/\texttt{max} & Minimum/Maximum of elements \\ \texttt{dot} & Vector dot product \\ \texttt{find} & Find indices of nonzero elements \\ \texttt{eig} & Find eigenvalues and eigenvectors \\ \texttt{diag} & Diagonal matrices and diagonals of a matrix \\ \texttt{fliplr}/\texttt{flipud} & Flip an array \\ \texttt{rot90} & Rotate an array 90 degrees \\ \texttt{imread}/\texttt{imwrite} & Read/Write image from graphics file \\ \texttt{imshow} & display image in Handle Graphics figure \\ \texttt{uint8} & Convert to unsigned 8-bit integer \\ \end{tabular} \end{table} \end{frame} \begin{frame}{Additional Commands} \protect\hypertarget{additional-commands}{} \begin{table}[!hbtp] \begin{tabular}{rl} Command & Description \\ \hline \texttt{iskeyword} & Check if input is a keyword \\ \texttt{who} & List current variables \\ \texttt{whos} & List current variables, long form \\ \texttt{which} & Locate functions and files \\ \texttt{clear} & Clear variables and functions from memory \\ \texttt{clc} & Clear command window \\ \texttt{clf} & Clear current figure \\ \texttt{close} & Close figure \\ \texttt{exist} & Check existence of variable/script/function/folder/class \\ \texttt{disp} & Display array \\ \end{tabular} \end{table} \end{frame} \hypertarget{script-files}{% \subsection{Script Files}\label{script-files}} \begin{frame}{} \protect\hypertarget{section-1}{} A script file is simply a file that contains a chain of commands that you edit in a separate window, then execute with a single mouse click or command. This is where we can define variables, perform calculations and leave comments to remind us what the file calculates. \end{frame} \begin{frame}{File Naming Conventions} \protect\hypertarget{file-naming-conventions}{} \begin{itemize}[<+->] \tightlist \item Start with a letter, followed by letters or numbers or underscore, maximum 63 characters (excluding the .m extension), and must not be the same as any MATLAB reserved word. \item None of the conventions matter to MATLAB itself: they only matter to the people writing the code, and the people maintaining the code (usually a much harder task), and to the people paying for the code (you'd be amazed how much gets written into contract specifications.) \item Reference: \url{https://www.mathworks.com/matlabcentral/answers/30223-what-are-the-rules-for-naming-script-files} \end{itemize} \end{frame} \begin{frame}[fragile]{Put Comments to Your Script File} \protect\hypertarget{put-comments-to-your-script-file}{} \begin{verbatim} % MATH 3341, Semester Year % Lab 02: Variables, Arrays, and Scripts % Author: first_name last_name % Date: mm/dd/yyyy \end{verbatim} \end{frame} \begin{frame}{Useful MATLAB Shortcuts} \protect\hypertarget{useful-matlab-shortcuts}{} \begin{itemize}[<+->] \tightlist \item Windows shortcuts \begin{itemize}[<+->] \tightlist \item Press \fbox{\texttt{Ctrl}} + \fbox{\texttt{A}} to select all \item Press \fbox{\texttt{Ctrl}} + \fbox{\texttt{I}} to adjust indentation \item Press \fbox{\texttt{Ctrl}} + \fbox{\texttt{R}} to comment \item Press \fbox{\texttt{Ctrl}} + \fbox{\texttt{T}} to uncomment \end{itemize} \item macOS shortcuts \begin{itemize}[<+->] \tightlist \item Press \fbox{\texttt{command}} + \fbox{\texttt{A}} to select all \item Press \fbox{\texttt{command}} + \fbox{\texttt{I}} to adjust indentation \item Press \fbox{\texttt{command}} + \fbox{\texttt{/}} to comment \item Press \fbox{\texttt{command}} + \fbox{\texttt{T}} to uncomment \end{itemize} \end{itemize} \end{frame} \hypertarget{primer}{% \subsection{\texorpdfstring{\LaTeX~Primer}{~Primer}}\label{primer}} \begin{frame}[fragile]{\texttt{table} Environment} \protect\hypertarget{table-environment}{} \begin{verbatim} \begin{table}[!hbtp] \caption{This is a table} \begin{tabular}{rcl} \toprule Column 1 & Column 2 & Column 3 \\ \midrule 1 & 1 & 1 \\ 12 & 12 & 12 \\ 123 & 123 & 123 \\ \bottomrule \end{tabular} \end{table} \end{verbatim} \end{frame} \begin{frame}{\texttt{table} Environment} \protect\hypertarget{table-environment-1}{} \begin{table}[!hbtp] \caption{This is a table} \begin{tabular}{rcl} \toprule Column 1 & Column 2 & Column 3 \\ \midrule 1 & 1 & 1 \\ 12 & 12 & 12 \\ 123 & 123 & 123 \\ \bottomrule \end{tabular} \end{table} \end{frame} \begin{frame}[fragile]{\texttt{figure} Environment} \protect\hypertarget{figure-environment}{} \begin{verbatim} \begin{figure}[!hbtp] \centering \includegraphics[height=0.3\textheight]{figure.pdf} \caption{Plot of $\sin{x}$} \label{fig:sin} \end{figure} \end{verbatim} generates \begin{figure}[!hbtp] \centering \includegraphics[height=0.3\textheight]{figure.pdf} \caption{Plot of $\sin{x}$} \label{fig:sin} \end{figure} \end{frame} \begin{frame}[fragile]{\texttt{\textbackslash{}left} and \texttt{\textbackslash{}right} vs.~\texttt{\textbackslash{}big}, \texttt{\textbackslash{}Big}, \texttt{\textbackslash{}Bigg}} \protect\hypertarget{left-and-right-vs.-big-big-bigg}{} \begin{verbatim} \begin{align*} \|x\|_2 & = \big(\sum_{i = 1}^{n} x_i^2 \big)^{1/2}, \|x\|_2 = \Big(\sum_{i = 1}^{n} x_i^2 \Big)^{1/2}, \\ \|x\|_2 & = \Bigg(\sum_{i = 1}^{n} x_i^2 \Bigg)^{1/2}, \|x\|_2 = \left(\sum_{i = 1}^{n} x_i^2 \right)^{1/2}. \end{align*} \end{verbatim} generates \begin{align*} \|x\|_2 & = \big(\sum_{i = 1}^{n} x_i^2 \big)^{1/2}, \|x\|_2 = \Big(\sum_{i = 1}^{n} x_i^2 \Big)^{1/2}, \\ \|x\|_2 & = \Bigg(\sum_{i = 1}^{n} x_i^2 \Bigg)^{1/2}, \|x\|_2 = \left(\sum_{i = 1}^{n} x_i^2 \right)^{1/2}. \end{align*} \end{frame} \begin{frame}[fragile]{Links} \protect\hypertarget{links}{} \begin{verbatim} \href{https://www.google.com}{Google} \end{verbatim} \href{https://www.google.com}{Google} Or simply \begin{verbatim} \url{https://www.google.com} \end{verbatim} \url{https://www.google.com} \end{frame} \begin{frame}[fragile]{\texttt{case} Environment} \protect\hypertarget{case-environment}{} \begin{verbatim} $$ f(x) = \begin{cases} 5 x + 4 & \text{if~} x \leq 1, \\ 3 x^2 + 6 & \text{if~} x > 1 \end{cases} $$ \end{verbatim} generates \[ f(x) = \begin{cases} 5 x + 4 & \text{if~} x \leq 1, \\ 3 x^2 + 6 & \text{if~} x > 1 \end{cases} \] \end{frame} \begin{frame}[fragile]{Cross-Reference} \protect\hypertarget{cross-reference}{} \begin{verbatim} \begin{equation} \label{eq:ls} A \mathbf{x} = \mathbf{b}. \end{equation} The expression \eqref{eq:ls} is a linear system. \end{verbatim} generates \begin{equation} \label{eq:ls} A \mathbf{x} = \mathbf{b}. \end{equation} The expression \eqref{eq:ls} is a linear system. \end{frame} \begin{frame}[fragile]{Cross-Reference} \protect\hypertarget{cross-reference-1}{} \begin{verbatim} \begin{table}[!hbtp] \caption{$y = 2x$} \label{tab:xy} \begin{tabular}{cc} \toprule $x$ & $y$ \\ \midrule $6$ & $12$ \\ $7$ & $14$ \\ $8$ & $16$ \\ \bottomrule \end{tabular} \end{table} Table \ref{tab:xy} gives the result of $y = 2x$. \end{verbatim} \end{frame} \begin{frame}{Cross-Reference} \protect\hypertarget{cross-reference-2}{} \begin{table}[!hbtp] \caption{$y = 2x$} \label{tab:xy} \begin{tabular}{cc} \toprule $x$ & $y$ \\ \midrule $6$ & $12$ \\ $7$ & $14$ \\ $8$ & $16$ \\ \bottomrule \end{tabular} \end{table} Table \ref{tab:xy} gives the result of \(y = 2x\). \end{frame}
(* This program is free software; you can redistribute it and/or *) (* modify it under the terms of the GNU Lesser General Public License *) (* as published by the Free Software Foundation; either version 2.1 *) (* of the License, or (at your option) any later version. *) (* *) (* This program is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU General Public License for more details. *) (* *) (* You should have received a copy of the GNU Lesser General Public *) (* License along with this program; if not, write to the Free *) (* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *) (* 02110-1301 USA *) Require Import Bool. Require Import Sumbool. Require Import Arith. Require Import ZArith NArith Nnat Ndec Ndigits. From IntMap Require Import Map. From IntMap Require Import Allmaps. Require Import List. Require Import Wf_nat. Require Import misc. Require Import bool_fun. Require Import myMap. Require Import config. Require Import alloc. Require Import make. Section BDD_neg. Variable gc : BDDconfig -> list ad -> BDDconfig. Hypothesis gc_is_OK : gc_OK gc. Fixpoint BDDneg_1 (cfg : BDDconfig) (ul : list ad) (node : ad) (bound : nat) {struct bound} : BDDconfig * ad := match bound with | O => (* Error *) (initBDDconfig, BDDzero) | S bound' => match MapGet _ (negm_of_cfg cfg) node with | Some node' => (cfg, node') | None => match MapGet _ (fst cfg) node with | None => if Neqb node BDDzero then (BDDneg_memo_put cfg BDDzero BDDone, BDDone) else (BDDneg_memo_put cfg BDDone BDDzero, BDDzero) | Some (x, (l, r)) => match BDDneg_1 cfg ul l bound' with | (cfgl, nodel) => match BDDneg_1 cfgl (nodel :: ul) r bound' with | (cfgr, noder) => match BDDmake gc cfgr x nodel noder (noder :: nodel :: ul) with | (cfg', node') => (BDDneg_memo_put cfg' node node', node') end end end end end end. Lemma BDDneg_1_lemma : forall (bound : nat) (cfg : BDDconfig) (ul : list ad) (node : ad), nat_of_N (node_height cfg node) < bound -> BDDconfig_OK cfg -> used_list_OK cfg ul -> used_node' cfg ul node -> BDDconfig_OK (fst (BDDneg_1 cfg ul node bound)) /\ config_node_OK (fst (BDDneg_1 cfg ul node bound)) (snd (BDDneg_1 cfg ul node bound)) /\ used_nodes_preserved cfg (fst (BDDneg_1 cfg ul node bound)) ul /\ Neqb (node_height (fst (BDDneg_1 cfg ul node bound)) (snd (BDDneg_1 cfg ul node bound))) (node_height cfg node) = true /\ bool_fun_eq (bool_fun_of_BDD (fst (BDDneg_1 cfg ul node bound)) (snd (BDDneg_1 cfg ul node bound))) (bool_fun_neg (bool_fun_of_BDD cfg node)). Proof. simple induction bound. intros. absurd (nat_of_N (node_height cfg node) < 0). apply lt_n_O. assumption. simpl in |- *. intros. elim (option_sum _ (MapGet _ (negm_of_cfg cfg) node)). intro y. elim y; clear y; intros node' H4. rewrite H4. simpl in |- *. elim (negm_of_cfg_OK _ H1 node node' H4). intros. split. assumption. split. inversion H6. inversion H8. assumption. split. apply used_nodes_preserved_refl. split. exact (proj1 (proj2 H6)). exact (proj2 (proj2 H6)). intro y. rewrite y. elim (option_sum _ (MapGet (BDDvar * (ad * ad)) (fst cfg) node)). intro y0. elim y0; clear y0. intro x; elim x; clear x; intros x x0; elim x0; clear x0; intros l r H4. rewrite H4. elim (prod_sum _ _ (BDDneg_1 cfg ul l n)). intros cfgl H5. elim H5; clear H5. intros nodel H5. rewrite H5. elim (prod_sum _ _ (BDDneg_1 cfgl (nodel :: ul) r n)). intros cfgr H6. elim H6; clear H6; intros noder H6. rewrite H6. elim (prod_sum _ _ (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))). intros cfg' H7; elim H7; clear H7; intros node' H7. rewrite H7. simpl in |- *. cut (nat_of_N (node_height cfg l) < n). cut (nat_of_N (node_height cfg r) < n). intros. cut (used_node' cfg ul l). cut (used_node' cfg ul r). intros. cut (BDDconfig_OK cfgl /\ config_node_OK cfgl nodel /\ used_nodes_preserved cfg cfgl ul /\ Neqb (node_height cfgl nodel) (node_height cfg l) = true /\ bool_fun_eq (bool_fun_of_BDD cfgl nodel) (bool_fun_neg (bool_fun_of_BDD cfg l))). intro. elim H12; clear H12; intros. elim H13; clear H13; intros. elim H14; clear H14; intros. elim H15; clear H15; intros. cut (config_node_OK cfg l). cut (config_node_OK cfg r). intros. cut (used_list_OK cfgl ul). intro. cut (used_list_OK cfgl (nodel :: ul)). intro. cut (used_node' cfgl ul r). intro. cut (used_node' cfgl (r :: ul) r). intro. cut (BDDconfig_OK cfgr /\ config_node_OK cfgr noder /\ used_nodes_preserved cfgl cfgr (nodel :: ul) /\ Neqb (node_height cfgr noder) (node_height cfgl r) = true /\ bool_fun_eq (bool_fun_of_BDD cfgr noder) (bool_fun_neg (bool_fun_of_BDD cfgl r))). intros. elim H23; clear H23; intros. elim H24; clear H24; intros. elim H25; clear H25; intros. elim H26; clear H26; intros. cut (used_list_OK cfgr (nodel :: ul)). intro. cut (used_list_OK cfgr (noder :: nodel :: ul)). intro. cut (used_node' cfgr (noder :: nodel :: ul) nodel). cut (used_node' cfgr (noder :: nodel :: ul) noder). intros. cut (forall (xl : BDDvar) (ll rl : ad), MapGet _ (fst cfgr) nodel = Some (xl, (ll, rl)) -> BDDcompare xl x = Datatypes.Lt). cut (forall (xr : BDDvar) (lr rr : ad), MapGet _ (fst cfgr) noder = Some (xr, (lr, rr)) -> BDDcompare xr x = Datatypes.Lt). intros. cut (BDDconfig_OK cfg'). cut (used_nodes_preserved cfgr cfg' (noder :: nodel :: ul)). cut (config_node_OK cfg' node'). cut (bool_fun_eq (bool_fun_of_BDD cfg' node') (bool_fun_if x (bool_fun_of_BDD cfgr noder) (bool_fun_of_BDD cfgr nodel))). cut (Neqb (node_height cfg' node') (ad_S x) = true). intros. cut (config_node_OK cfg' node). intro. cut (nodes_preserved cfg' (BDDneg_memo_put cfg' node node')). intro. cut (BDDconfig_OK (BDDneg_memo_put cfg' node node')). intro. split. assumption. split. apply nodes_preserved_config_node_OK with (cfg1 := cfg'). assumption. assumption. split. apply used_nodes_preserved_trans with (cfg2 := cfgr). assumption. apply used_nodes_preserved_trans with (cfg2 := cfgl). assumption. assumption. apply used_nodes_preserved_cons with (node := nodel). assumption. apply used_nodes_preserved_trans with (cfg2 := cfg'). assumption. apply used_nodes_preserved_cons with (node := nodel). apply used_nodes_preserved_cons with (node := noder). assumption. apply nodes_preserved_used_nodes_preserved. assumption. rewrite (Neqb_complete (node_height (BDDneg_memo_put cfg' node node') node') (node_height cfg' node')). split. rewrite (Neqb_complete _ _ H34). unfold node_height in |- *. unfold bs_node_height in |- *. rewrite H4. apply Neqb_correct. apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfg' node'). apply nodes_preserved_bool_fun. assumption. assumption. assumption. assumption. apply bool_fun_eq_trans with (bf2 := bool_fun_if x (bool_fun_of_BDD cfgr noder) (bool_fun_of_BDD cfgr nodel)). assumption. apply bool_fun_eq_trans with (bf2 := bool_fun_if x (bool_fun_neg (bool_fun_of_BDD cfg r)) (bool_fun_neg (bool_fun_of_BDD cfg l))). apply bool_fun_if_preserves_eq. apply bool_fun_eq_trans with (bf2 := bool_fun_neg (bool_fun_of_BDD cfgl r)). assumption. apply bool_fun_neg_preserves_eq. apply used_nodes_preserved'_bool_fun with (ul := ul). assumption. assumption. assumption. assumption. assumption. apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfgl nodel). apply used_nodes_preserved'_bool_fun with (ul := nodel :: ul). assumption. assumption. assumption. assumption. apply used_node'_cons_node_ul. assumption. apply bool_fun_eq_sym. apply bool_fun_eq_trans with (bf2 := bool_fun_neg (bool_fun_if x (bool_fun_of_BDD cfg r) (bool_fun_of_BDD cfg l))). apply bool_fun_neg_preserves_eq. apply bool_fun_of_BDD_int. assumption. assumption. apply bool_fun_neg_orthogonal. apply nodes_preserved_node_height_eq. assumption. assumption. assumption. assumption. apply BDDnegm_put_OK. assumption. assumption. assumption. rewrite (Neqb_complete _ _ H34). rewrite (Neqb_complete (node_height cfg' node) (node_height cfg node)). unfold node_height in |- *. unfold bs_node_height in |- *. rewrite H4. apply Neqb_correct. apply used_nodes_preserved'_node_height_eq with (ul := ul). assumption. assumption. apply used_nodes_preserved_trans with (cfg2 := cfgl). assumption. assumption. apply used_nodes_preserved_trans with (cfg2 := cfgr). assumption. apply used_nodes_preserved_cons with (node := nodel). assumption. apply used_nodes_preserved_cons with (node := nodel). apply used_nodes_preserved_cons with (node := noder). assumption. assumption. assumption. apply bool_fun_eq_trans with (bf2 := bool_fun_if x (bool_fun_of_BDD cfgr noder) (bool_fun_of_BDD cfgr nodel)). assumption. apply bool_fun_eq_trans with (bf2 := bool_fun_if x (bool_fun_neg (bool_fun_of_BDD cfg r)) (bool_fun_neg (bool_fun_of_BDD cfg l))). apply bool_fun_if_preserves_eq. apply bool_fun_eq_trans with (bf2 := bool_fun_neg (bool_fun_of_BDD cfgl r)). assumption. apply bool_fun_neg_preserves_eq. apply used_nodes_preserved'_bool_fun with (ul := ul). assumption. assumption. assumption. assumption. assumption. apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfgl nodel). apply used_nodes_preserved'_bool_fun with (ul := nodel :: ul). assumption. assumption. assumption. assumption. apply used_node'_cons_node_ul. assumption. apply bool_fun_eq_trans with (bf2 := bool_fun_neg (bool_fun_of_BDD cfg node)). apply bool_fun_eq_trans with (bf2 := bool_fun_neg (bool_fun_if x (bool_fun_of_BDD cfg r) (bool_fun_of_BDD cfg l))). apply bool_fun_eq_sym. apply bool_fun_neg_orthogonal. apply bool_fun_neg_preserves_eq. apply bool_fun_eq_sym. apply bool_fun_of_BDD_int. assumption. assumption. apply bool_fun_neg_preserves_eq. apply bool_fun_eq_sym. apply used_nodes_preserved'_bool_fun with (ul := ul). assumption. assumption. apply used_nodes_preserved_trans with (cfg2 := cfgl). assumption. assumption. apply used_nodes_preserved_trans with (cfg2 := cfgr). assumption. apply used_nodes_preserved_cons with (node := nodel). assumption. apply used_nodes_preserved_cons with (node := nodel). apply used_nodes_preserved_cons with (node := noder). assumption. assumption. assumption. apply BDDnegm_put_nodes_preserved. apply used_nodes_preserved_node_OK' with (ul := ul) (cfg := cfg). assumption. assumption. assumption. apply used_nodes_preserved_trans with (cfg2 := cfgl). assumption. assumption. apply used_nodes_preserved_trans with (cfg2 := cfgr). assumption. apply used_nodes_preserved_cons with (node := nodel). assumption. apply used_nodes_preserved_cons with (node := nodel). apply used_nodes_preserved_cons with (node := noder). assumption. replace cfg' with (fst (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))). replace node' with (snd (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))). apply BDDmake_node_height_eq. assumption. intros. apply not_true_is_false. unfold not in |- *; intro. apply eq_true_false_abs with (b := Neqb l r). apply BDDunique with (cfg := cfg). assumption. assumption. assumption. apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfgl r). apply bool_fun_eq_neg_eq. apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfgl nodel). apply bool_fun_eq_sym. assumption. apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfgr nodel). apply bool_fun_eq_sym. apply used_nodes_preserved'_bool_fun with (ul := nodel :: ul). assumption. assumption. assumption. assumption. apply used_node'_cons_node_ul. rewrite (Neqb_complete _ _ H34). assumption. apply used_nodes_preserved'_bool_fun with (ul := ul). assumption. assumption. assumption. assumption. assumption. apply low_high_neq with (cfg := cfg) (node := node) (x := x). assumption. assumption. rewrite H7. reflexivity. rewrite H7. reflexivity. replace cfg' with (fst (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))). replace node' with (snd (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))). apply BDDmake_bool_fun. assumption. assumption. assumption. assumption. assumption. assumption. assumption. rewrite H7. reflexivity. rewrite H7. reflexivity. replace cfg' with (fst (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))). replace node' with (snd (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))). apply BDDmake_node_OK. assumption. assumption. assumption. assumption. assumption. assumption. assumption. rewrite H7. reflexivity. rewrite H7. reflexivity. replace cfg' with (fst (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))). replace node' with (snd (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))). apply BDDmake_preserves_used_nodes. assumption. assumption. assumption. rewrite H7. reflexivity. rewrite H7. reflexivity. replace cfg' with (fst (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))). apply BDDmake_keeps_config_OK. assumption. assumption. assumption. assumption. assumption. assumption. assumption. rewrite H7. reflexivity. intros. rewrite (ad_S_compare xr x). replace (ad_S xr) with (bs_node_height (fst cfgr) noder). replace (ad_S x) with (bs_node_height (fst cfg) node). unfold node_height in H26. rewrite (Neqb_complete _ _ H26). cut (Neqb (node_height cfgl r) (node_height cfg r) = true). intro. unfold node_height in H33. rewrite (Neqb_complete _ _ H33). apply bs_node_height_right with (x := x) (l := l). exact (proj1 H1). assumption. apply used_nodes_preserved'_node_height_eq with (ul := ul). assumption. assumption. assumption. assumption. assumption. unfold bs_node_height in |- *. rewrite H4. reflexivity. unfold bs_node_height in |- *. rewrite H32. reflexivity. intros. rewrite (ad_S_compare xl x). replace (ad_S xl) with (bs_node_height (fst cfgr) nodel). replace (ad_S x) with (bs_node_height (fst cfg) node). cut (Neqb (node_height cfgr nodel) (node_height cfgl nodel) = true). intro. unfold node_height in H33. rewrite (Neqb_complete _ _ H33). unfold node_height in H15. rewrite (Neqb_complete _ _ H15). apply bs_node_height_left with (x := x) (r := r). exact (proj1 H1). assumption. apply used_nodes_preserved'_node_height_eq with (ul := nodel :: ul). assumption. assumption. assumption. assumption. apply used_node'_cons_node_ul. unfold bs_node_height in |- *. rewrite H4. reflexivity. unfold bs_node_height in |- *. rewrite H32. reflexivity. apply used_node'_cons_node_ul. apply used_node'_cons_node'_ul. apply used_node'_cons_node_ul. apply node_OK_list_OK. assumption. assumption. apply used_nodes_preserved_list_OK with (cfg := cfgl). assumption. assumption. replace cfgr with (fst (BDDneg_1 cfgl (nodel :: ul) r n)). replace noder with (snd (BDDneg_1 cfgl (nodel :: ul) r n)). apply H. apply lt_trans_1 with (y := nat_of_N (node_height cfg node)). cut (Neqb (node_height cfgl r) (node_height cfg r) = true). intro. rewrite (Neqb_complete _ _ H23). apply BDDcompare_lt. unfold node_height in |- *. apply bs_node_height_right with (x := x) (l := l). exact (proj1 H1). assumption. apply used_nodes_preserved'_node_height_eq with (ul := ul). assumption. assumption. assumption. assumption. assumption. assumption. assumption. assumption. apply used_node'_cons_node'_ul. assumption. rewrite H6. reflexivity. rewrite H6. reflexivity. apply used_node'_cons_node_ul. apply used_nodes_preserved_used_node' with (cfg := cfg). assumption. assumption. assumption. apply node_OK_list_OK. assumption. assumption. apply used_nodes_preserved_list_OK with (cfg := cfg). assumption. assumption. apply used_node'_OK with (ul := ul). assumption. assumption. assumption. apply used_node'_OK with (ul := ul). assumption. assumption. assumption. replace cfgl with (fst (BDDneg_1 cfg ul l n)). replace nodel with (snd (BDDneg_1 cfg ul l n)). apply H. apply lt_trans_1 with (y := nat_of_N (node_height cfg node)). apply BDDcompare_lt. unfold node_height in |- *. apply bs_node_height_left with (x := x) (r := r). exact (proj1 H1). assumption. assumption. assumption. assumption. assumption. rewrite H5. reflexivity. rewrite H5. reflexivity. apply high_used' with (x := x) (l := l) (node := node). assumption. assumption. assumption. apply low_used' with (x := x) (r := r) (node := node). assumption. assumption. assumption. apply lt_trans_1 with (y := nat_of_N (node_height cfg node)). apply BDDcompare_lt. unfold node_height in |- *. apply bs_node_height_right with (x := x) (l := l). exact (proj1 H1). assumption. assumption. apply lt_trans_1 with (y := nat_of_N (node_height cfg node)). apply BDDcompare_lt. unfold node_height in |- *. apply bs_node_height_left with (x := x) (r := r). exact (proj1 H1). assumption. assumption. intro y0. rewrite y0. elim (sumbool_of_bool (Neqb node BDDzero)). intro y1. rewrite y1. rewrite (Neqb_complete _ _ y1). simpl in |- *. cut (BDDconfig_OK (BDDneg_memo_put cfg BDDzero BDDone)). intro. split. assumption. cut (nodes_preserved cfg (BDDneg_memo_put cfg BDDzero BDDone)). intro. split. apply nodes_preserved_config_node_OK with (cfg1 := cfg). assumption. apply one_OK. split. apply nodes_preserved_used_nodes_preserved. assumption. split. rewrite <- (Neqb_complete (node_height cfg BDDone) (node_height cfg BDDzero)) . apply nodes_preserved_node_height_eq. assumption. assumption. assumption. apply one_OK. rewrite (Neqb_complete _ _ (node_height_zero _ H1)). rewrite (Neqb_complete _ _ (node_height_one _ H1)). reflexivity. apply bool_fun_eq_trans with (bf2 := bool_fun_one). apply bool_fun_of_BDD_one. assumption. apply bool_fun_eq_trans with (bf2 := bool_fun_neg bool_fun_zero). apply bool_fun_eq_sym. exact bool_fun_neg_zero. apply bool_fun_neg_preserves_eq. apply bool_fun_eq_sym. apply bool_fun_of_BDD_zero. assumption. apply BDDnegm_put_nodes_preserved. apply BDDnegm_put_OK. assumption. apply zero_OK. apply one_OK. rewrite (Neqb_complete _ _ (node_height_zero _ H1)). rewrite (Neqb_complete _ _ (node_height_one _ H1)). reflexivity. apply bool_fun_eq_trans with (bf2 := bool_fun_neg bool_fun_zero). apply bool_fun_of_BDD_one. assumption. apply bool_fun_neg_preserves_eq. apply bool_fun_eq_sym. apply bool_fun_of_BDD_zero. assumption. intro y1. rewrite y1. simpl in |- *. cut (BDDconfig_OK (BDDneg_memo_put cfg BDDone BDDzero)). intro. split. assumption. cut (nodes_preserved cfg (BDDneg_memo_put cfg BDDone BDDzero)). intro. split. apply nodes_preserved_config_node_OK with (cfg1 := cfg). assumption. apply zero_OK. split. apply nodes_preserved_used_nodes_preserved. assumption. elim (used_node'_OK cfg ul node H1 H2 H3). intro. rewrite H6 in y1. simpl in y1. discriminate. intro. elim H6. intro. rewrite H7. split. rewrite <- (Neqb_complete (node_height cfg BDDzero) (node_height cfg BDDone)) . apply nodes_preserved_node_height_eq. assumption. assumption. assumption. apply zero_OK. rewrite (Neqb_complete _ _ (node_height_zero _ H1)). rewrite (Neqb_complete _ _ (node_height_one _ H1)). reflexivity. apply bool_fun_eq_trans with (bf2 := bool_fun_zero). apply bool_fun_of_BDD_zero. assumption. apply bool_fun_eq_trans with (bf2 := bool_fun_neg bool_fun_one). apply bool_fun_eq_sym. exact bool_fun_neg_one. apply bool_fun_neg_preserves_eq. apply bool_fun_eq_sym. apply bool_fun_of_BDD_one. assumption. intro. unfold in_dom in H7. rewrite y0 in H7. discriminate. apply BDDnegm_put_nodes_preserved. apply BDDnegm_put_OK. assumption. apply one_OK. apply zero_OK. rewrite (Neqb_complete _ _ (node_height_zero _ H1)). rewrite (Neqb_complete _ _ (node_height_one _ H1)). reflexivity. apply bool_fun_eq_trans with (bf2 := bool_fun_neg bool_fun_one). apply bool_fun_of_BDD_zero. assumption. apply bool_fun_neg_preserves_eq. apply bool_fun_eq_sym. apply bool_fun_of_BDD_one. assumption. Qed. End BDD_neg.
{-# OPTIONS --exact-split #-} {-# OPTIONS --no-sized-types #-} {-# OPTIONS --no-universe-polymorphism #-} {-# OPTIONS --without-K #-} ------------------------------------------------------------------------------ -- The translation from pattern matching equations to equational -- axioms requires some care because the pattern matching equations -- are processed from top to bottom and from left to right. -- From: Herbert P. Sander. A logic of functional programs with an -- application to concurrency. PhD thesis, Chalmers University of -- Technology and University of Gothenburg, Department of Computer -- Sciences, 1992. pp. 12-13. ------------------------------------------------------------------------------ module Berry.Berry where infix 7 _≡_ postulate D : Set zero loop : D succ : D → D data _≡_ (x : D) : D → Set where refl : x ≡ x -- For example, the translation of the Haskell function -- f ∷ Nat → Nat → Nat → Nat -- f Zero (Succ Zero) x = Succ Zero -- f (Succ Zero) x Zero = Succ (Succ Zero) -- f x Zero (Succ Zero) = Succ (Succ (Succ Zero)) -- to the equational axioms postulate f : D → D → D → D f-eq₁ : ∀ x → f zero (succ zero) x ≡ succ zero f-eq₂ : ∀ x → f (succ zero) x zero ≡ succ (succ zero) f-eq₃ : ∀ x → f x zero (succ zero) ≡ succ (succ (succ zero)) {-# ATP axioms f-eq₁ f-eq₂ f-eq₃ #-} -- is not correct, because using the Haskell equations we have -- -- f loop zero (succ zero) = *** Non-terminating *** -- -- but using the equational axioms we can proof that postulate bad : f loop zero (succ zero) ≡ succ (succ (succ zero)) {-# ATP prove bad #-}
A function $f$ is continuous at $a$ if and only if the function $h \mapsto f(a + h)$ is continuous at $0$.
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel, Rémy Degenne -/ import analysis.special_functions.pow import analysis.special_functions.complex.log_deriv import analysis.calculus.extend_deriv import analysis.special_functions.log.deriv import analysis.special_functions.trigonometric.deriv /-! # Derivatives of power function on `ℂ`, `ℝ`, `ℝ≥0`, and `ℝ≥0∞` We also prove differentiability and provide derivatives for the power functions `x ^ y`. -/ noncomputable theory open_locale classical real topology nnreal ennreal filter open filter namespace complex lemma has_strict_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) : has_strict_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p := begin have A : p.1 ≠ 0, by { intro h, simpa [h, lt_irrefl] using hp }, have : (λ x : ℂ × ℂ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2)), from ((is_open_ne.preimage continuous_fst).eventually_mem A).mono (λ p hp, cpow_def_of_ne_zero hp _), rw [cpow_sub _ _ A, cpow_one, mul_div_left_comm, mul_smul, mul_smul, ← smul_add], refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm, simpa only [cpow_def_of_ne_zero A, div_eq_mul_inv, mul_smul, add_comm] using ((has_strict_fderiv_at_fst.clog hp).mul has_strict_fderiv_at_snd).cexp end lemma has_strict_fderiv_at_cpow' {x y : ℂ} (hp : 0 < x.re ∨ x.im ≠ 0) : has_strict_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((y * x ^ (y - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (x ^ y * log x) • continuous_linear_map.snd ℂ ℂ ℂ) (x, y) := @has_strict_fderiv_at_cpow (x, y) hp lemma has_strict_deriv_at_const_cpow {x y : ℂ} (h : x ≠ 0 ∨ y ≠ 0) : has_strict_deriv_at (λ y, x ^ y) (x ^ y * log x) y := begin rcases em (x = 0) with rfl|hx, { replace h := h.neg_resolve_left rfl, rw [log_zero, mul_zero], refine (has_strict_deriv_at_const _ 0).congr_of_eventually_eq _, exact (is_open_ne.eventually_mem h).mono (λ y hy, (zero_cpow hy).symm) }, { simpa only [cpow_def_of_ne_zero hx, mul_one] using ((has_strict_deriv_at_id y).const_mul (log x)).cexp } end lemma has_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) : has_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p := (has_strict_fderiv_at_cpow hp).has_fderiv_at end complex section fderiv open complex variables {E : Type*} [normed_add_comm_group E] [normed_space ℂ E] {f g : E → ℂ} {f' g' : E →L[ℂ] ℂ} {x : E} {s : set E} {c : ℂ} lemma has_strict_fderiv_at.cpow (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := by convert (@has_strict_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg) lemma has_strict_fderiv_at.const_cpow (hf : has_strict_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_strict_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_cpow h0).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.cpow (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg) lemma has_fderiv_at.const_cpow (hf : has_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_at x hf lemma has_fderiv_within_at.cpow (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_within_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') s x := by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp_has_fderiv_within_at x (hf.prod hg) lemma has_fderiv_within_at.const_cpow (hf : has_fderiv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_fderiv_within_at (λ x, c ^ f x) ((c ^ f x * log c) • f') s x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_within_at x hf lemma differentiable_at.cpow (hf : differentiable_at ℂ f x) (hg : differentiable_at ℂ g x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_at ℂ (λ x, f x ^ g x) x := (hf.has_fderiv_at.cpow hg.has_fderiv_at h0).differentiable_at lemma differentiable_at.const_cpow (hf : differentiable_at ℂ f x) (h0 : c ≠ 0 ∨ f x ≠ 0) : differentiable_at ℂ (λ x, c ^ f x) x := (hf.has_fderiv_at.const_cpow h0).differentiable_at lemma differentiable_within_at.cpow (hf : differentiable_within_at ℂ f s x) (hg : differentiable_within_at ℂ g s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_within_at ℂ (λ x, f x ^ g x) s x := (hf.has_fderiv_within_at.cpow hg.has_fderiv_within_at h0).differentiable_within_at lemma differentiable_within_at.const_cpow (hf : differentiable_within_at ℂ f s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : differentiable_within_at ℂ (λ x, c ^ f x) s x := (hf.has_fderiv_within_at.const_cpow h0).differentiable_within_at end fderiv section deriv open complex variables {f g : ℂ → ℂ} {s : set ℂ} {f' g' x c : ℂ} /-- A private lemma that rewrites the output of lemmas like `has_fderiv_at.cpow` to the form expected by lemmas like `has_deriv_at.cpow`. -/ private lemma aux : ((g x * f x ^ (g x - 1)) • (1 : ℂ →L[ℂ] ℂ).smul_right f' + (f x ^ g x * log (f x)) • (1 : ℂ →L[ℂ] ℂ).smul_right g') 1 = g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g' := by simp only [algebra.id.smul_eq_mul, one_mul, continuous_linear_map.one_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul'] lemma has_strict_deriv_at.cpow (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x := by simpa only [aux] using (hf.cpow hg h0).has_strict_deriv_at lemma has_strict_deriv_at.const_cpow (hf : has_strict_deriv_at f f' x) (h : c ≠ 0 ∨ f x ≠ 0) : has_strict_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x := (has_strict_deriv_at_const_cpow h).comp x hf lemma complex.has_strict_deriv_at_cpow_const (h : 0 < x.re ∨ x.im ≠ 0) : has_strict_deriv_at (λ z : ℂ, z ^ c) (c * x ^ (c - 1)) x := by simpa only [mul_zero, add_zero, mul_one] using (has_strict_deriv_at_id x).cpow (has_strict_deriv_at_const x c) h lemma has_strict_deriv_at.cpow_const (hf : has_strict_deriv_at f f' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x := (complex.has_strict_deriv_at_cpow_const h0).comp x hf lemma has_deriv_at.cpow (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x := by simpa only [aux] using (hf.has_fderiv_at.cpow hg h0).has_deriv_at lemma has_deriv_at.const_cpow (hf : has_deriv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp x hf lemma has_deriv_at.cpow_const (hf : has_deriv_at f f' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x := (complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp x hf lemma has_deriv_within_at.cpow (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') s x := by simpa only [aux] using (hf.has_fderiv_within_at.cpow hg h0).has_deriv_within_at lemma has_deriv_within_at.const_cpow (hf : has_deriv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_deriv_within_at (λ x, c ^ f x) (c ^ f x * log c * f') s x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_deriv_within_at x hf lemma has_deriv_within_at.cpow_const (hf : has_deriv_within_at f f' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') s x := (complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp_has_deriv_within_at x hf /-- Although `λ x, x ^ r` for fixed `r` is *not* complex-differentiable along the negative real line, it is still real-differentiable, and the derivative is what one would formally expect. -/ lemma has_deriv_at_of_real_cpow {x : ℝ} (hx : x ≠ 0) {r : ℂ} (hr : r ≠ -1) : has_deriv_at (λ y:ℝ, (y:ℂ) ^ (r + 1) / (r + 1)) (x ^ r) x := begin rw [ne.def, ←add_eq_zero_iff_eq_neg, ←ne.def] at hr, rcases lt_or_gt_of_ne hx.symm with hx | hx, { -- easy case : `0 < x` convert (((has_deriv_at_id (x:ℂ)).cpow_const _).div_const (r + 1)).comp_of_real, { rw [add_sub_cancel, id.def, mul_one, mul_comm, mul_div_cancel _ hr] }, { rw [id.def, of_real_re], exact or.inl hx } }, { -- harder case : `x < 0` have : ∀ᶠ (y:ℝ) in nhds x, (y:ℂ) ^ (r + 1) / (r + 1) = (-y:ℂ) ^ (r + 1) * exp (π * I * (r + 1)) / (r + 1), { refine filter.eventually_of_mem (Iio_mem_nhds hx) (λ y hy, _), rw of_real_cpow_of_nonpos (le_of_lt hy) }, refine has_deriv_at.congr_of_eventually_eq _ this, rw of_real_cpow_of_nonpos (le_of_lt hx), suffices : has_deriv_at (λ (y : ℝ), (-↑y) ^ (r + 1) * exp (↑π * I * (r + 1))) ((r + 1) * (-↑x) ^ r * exp (↑π * I * r)) x, { convert this.div_const (r + 1) using 1, conv_rhs { rw [mul_assoc, mul_comm, mul_div_cancel _ hr] } }, rw [mul_add ((π:ℂ) * _), mul_one, exp_add, exp_pi_mul_I, mul_comm (_ : ℂ) (-1 : ℂ), neg_one_mul], simp_rw [mul_neg, ←neg_mul, ←of_real_neg], suffices : has_deriv_at (λ (y : ℝ), (↑-y) ^ (r + 1)) (-(r + 1) * (↑-x) ^ r) x, { convert this.neg.mul_const _, ring }, suffices : has_deriv_at (λ (y : ℝ), (↑y) ^ (r + 1)) ((r + 1) * (↑-x) ^ r) (-x), { convert @has_deriv_at.scomp ℝ _ ℂ _ _ x ℝ _ _ _ _ _ _ _ _ this (has_deriv_at_neg x) using 1, rw [real_smul, of_real_neg 1, of_real_one], ring }, suffices : has_deriv_at (λ (y : ℂ), y ^ (r + 1)) ((r + 1) * (↑-x) ^ r) (↑-x), { exact this.comp_of_real }, conv in ((↑_) ^ _) { rw (by ring : r = (r + 1) - 1) }, convert (has_deriv_at_id ((-x : ℝ) : ℂ)).cpow_const _ using 1, { simp }, { left, rwa [id.def, of_real_re, neg_pos] } }, end end deriv namespace real variables {x y z : ℝ} /-- `(x, y) ↦ x ^ y` is strictly differentiable at `p : ℝ × ℝ` such that `0 < p.fst`. -/ lemma has_strict_fderiv_at_rpow_of_pos (p : ℝ × ℝ) (hp : 0 < p.1) : has_strict_fderiv_at (λ x : ℝ × ℝ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℝ ℝ ℝ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℝ ℝ ℝ) p := begin have : (λ x : ℝ × ℝ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2)), from (continuous_at_fst.eventually (lt_mem_nhds hp)).mono (λ p hp, rpow_def_of_pos hp _), refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm, convert ((has_strict_fderiv_at_fst.log hp.ne').mul has_strict_fderiv_at_snd).exp, rw [rpow_sub_one hp.ne', ← rpow_def_of_pos hp, smul_add, smul_smul, mul_div_left_comm, div_eq_mul_inv, smul_smul, smul_smul, mul_assoc, add_comm] end /-- `(x, y) ↦ x ^ y` is strictly differentiable at `p : ℝ × ℝ` such that `p.fst < 0`. -/ lemma has_strict_fderiv_at_rpow_of_neg (p : ℝ × ℝ) (hp : p.1 < 0) : has_strict_fderiv_at (λ x : ℝ × ℝ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℝ ℝ ℝ + (p.1 ^ p.2 * log p.1 - exp (log p.1 * p.2) * sin (p.2 * π) * π) • continuous_linear_map.snd ℝ ℝ ℝ) p := begin have : (λ x : ℝ × ℝ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2) * cos (x.2 * π)), from (continuous_at_fst.eventually (gt_mem_nhds hp)).mono (λ p hp, rpow_def_of_neg hp _), refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm, convert ((has_strict_fderiv_at_fst.log hp.ne).mul has_strict_fderiv_at_snd).exp.mul (has_strict_fderiv_at_snd.mul_const _).cos using 1, simp_rw [rpow_sub_one hp.ne, smul_add, ← add_assoc, smul_smul, ← add_smul, ← mul_assoc, mul_comm (cos _), ← rpow_def_of_neg hp], rw [div_eq_mul_inv, add_comm], congr' 2; ring end /-- The function `λ (x, y), x ^ y` is infinitely smooth at `(x, y)` unless `x = 0`. -/ lemma cont_diff_at_rpow_of_ne (p : ℝ × ℝ) (hp : p.1 ≠ 0) {n : ℕ∞} : cont_diff_at ℝ n (λ p : ℝ × ℝ, p.1 ^ p.2) p := begin cases hp.lt_or_lt with hneg hpos, exacts [(((cont_diff_at_fst.log hneg.ne).mul cont_diff_at_snd).exp.mul (cont_diff_at_snd.mul cont_diff_at_const).cos).congr_of_eventually_eq ((continuous_at_fst.eventually (gt_mem_nhds hneg)).mono (λ p hp, rpow_def_of_neg hp _)), ((cont_diff_at_fst.log hpos.ne').mul cont_diff_at_snd).exp.congr_of_eventually_eq ((continuous_at_fst.eventually (lt_mem_nhds hpos)).mono (λ p hp, rpow_def_of_pos hp _))] end lemma differentiable_at_rpow_of_ne (p : ℝ × ℝ) (hp : p.1 ≠ 0) : differentiable_at ℝ (λ p : ℝ × ℝ, p.1 ^ p.2) p := (cont_diff_at_rpow_of_ne p hp).differentiable_at le_rfl lemma _root_.has_strict_deriv_at.rpow {f g : ℝ → ℝ} {f' g' : ℝ} (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) (h : 0 < f x) : has_strict_deriv_at (λ x, f x ^ g x) (f' * g x * (f x) ^ (g x - 1) + g' * f x ^ g x * log (f x)) x := begin convert (has_strict_fderiv_at_rpow_of_pos ((λ x, (f x, g x)) x) h).comp_has_strict_deriv_at _ (hf.prod hg) using 1, simp [mul_assoc, mul_comm, mul_left_comm] end lemma has_strict_deriv_at_rpow_const_of_ne {x : ℝ} (hx : x ≠ 0) (p : ℝ) : has_strict_deriv_at (λ x, x ^ p) (p * x ^ (p - 1)) x := begin cases hx.lt_or_lt with hx hx, { have := (has_strict_fderiv_at_rpow_of_neg (x, p) hx).comp_has_strict_deriv_at x ((has_strict_deriv_at_id x).prod (has_strict_deriv_at_const _ _)), convert this, simp }, { simpa using (has_strict_deriv_at_id x).rpow (has_strict_deriv_at_const x p) hx } end lemma has_strict_deriv_at_const_rpow {a : ℝ} (ha : 0 < a) (x : ℝ) : has_strict_deriv_at (λ x, a ^ x) (a ^ x * log a) x := by simpa using (has_strict_deriv_at_const _ _).rpow (has_strict_deriv_at_id x) ha /-- This lemma says that `λ x, a ^ x` is strictly differentiable for `a < 0`. Note that these values of `a` are outside of the "official" domain of `a ^ x`, and we may redefine `a ^ x` for negative `a` if some other definition will be more convenient. -/ lemma has_strict_deriv_at_const_rpow_of_neg {a x : ℝ} (ha : a < 0) : has_strict_deriv_at (λ x, a ^ x) (a ^ x * log a - exp (log a * x) * sin (x * π) * π) x := by simpa using (has_strict_fderiv_at_rpow_of_neg (a, x) ha).comp_has_strict_deriv_at x ((has_strict_deriv_at_const _ _).prod (has_strict_deriv_at_id _)) end real namespace real variables {z x y : ℝ} lemma has_deriv_at_rpow_const {x p : ℝ} (h : x ≠ 0 ∨ 1 ≤ p) : has_deriv_at (λ x, x ^ p) (p * x ^ (p - 1)) x := begin rcases ne_or_eq x 0 with hx | rfl, { exact (has_strict_deriv_at_rpow_const_of_ne hx _).has_deriv_at }, replace h : 1 ≤ p := h.neg_resolve_left rfl, apply has_deriv_at_of_has_deriv_at_of_ne (λ x hx, (has_strict_deriv_at_rpow_const_of_ne hx p).has_deriv_at), exacts [continuous_at_id.rpow_const (or.inr (zero_le_one.trans h)), continuous_at_const.mul (continuous_at_id.rpow_const (or.inr (sub_nonneg.2 h)))] end lemma differentiable_rpow_const {p : ℝ} (hp : 1 ≤ p) : differentiable ℝ (λ x : ℝ, x ^ p) := λ x, (has_deriv_at_rpow_const (or.inr hp)).differentiable_at lemma deriv_rpow_const {x p : ℝ} (h : x ≠ 0 ∨ 1 ≤ p) : deriv (λ x : ℝ, x ^ p) x = p * x ^ (p - 1) := (has_deriv_at_rpow_const h).deriv lemma deriv_rpow_const' {p : ℝ} (h : 1 ≤ p) : deriv (λ x : ℝ, x ^ p) = λ x, p * x ^ (p - 1) := funext $ λ x, deriv_rpow_const (or.inr h) lemma cont_diff_at_rpow_const_of_ne {x p : ℝ} {n : ℕ∞} (h : x ≠ 0) : cont_diff_at ℝ n (λ x, x ^ p) x := (cont_diff_at_rpow_of_ne (x, p) h).comp x (cont_diff_at_id.prod cont_diff_at_const) lemma cont_diff_rpow_const_of_le {p : ℝ} {n : ℕ} (h : ↑n ≤ p) : cont_diff ℝ n (λ x : ℝ, x ^ p) := begin induction n with n ihn generalizing p, { exact cont_diff_zero.2 (continuous_id.rpow_const (λ x, by exact_mod_cast or.inr h)) }, { have h1 : 1 ≤ p, from le_trans (by simp) h, rw [nat.cast_succ, ← le_sub_iff_add_le] at h, rw [cont_diff_succ_iff_deriv, deriv_rpow_const' h1], refine ⟨differentiable_rpow_const h1, cont_diff_const.mul (ihn h)⟩ } end lemma cont_diff_at_rpow_const_of_le {x p : ℝ} {n : ℕ} (h : ↑n ≤ p) : cont_diff_at ℝ n (λ x : ℝ, x ^ p) x := (cont_diff_rpow_const_of_le h).cont_diff_at lemma has_strict_deriv_at_rpow_const {x p : ℝ} (hx : x ≠ 0 ∨ 1 ≤ p) : has_strict_deriv_at (λ x, x ^ p) (p * x ^ (p - 1)) x := cont_diff_at.has_strict_deriv_at' (cont_diff_at_rpow_const (by rwa nat.cast_one)) (has_deriv_at_rpow_const hx) le_rfl end real section differentiability open real section fderiv variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] {f g : E → ℝ} {f' g' : E →L[ℝ] ℝ} {x : E} {s : set E} {c p : ℝ} {n : ℕ∞} lemma has_fderiv_within_at.rpow (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) (h : 0 < f x) : has_fderiv_within_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') s x := (has_strict_fderiv_at_rpow_of_pos (f x, g x) h).has_fderiv_at.comp_has_fderiv_within_at x (hf.prod hg) lemma has_fderiv_at.rpow (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) (h : 0 < f x) : has_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := (has_strict_fderiv_at_rpow_of_pos (f x, g x) h).has_fderiv_at.comp x (hf.prod hg) lemma has_strict_fderiv_at.rpow (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) (h : 0 < f x) : has_strict_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := (has_strict_fderiv_at_rpow_of_pos (f x, g x) h).comp x (hf.prod hg) lemma differentiable_within_at.rpow (hf : differentiable_within_at ℝ f s x) (hg : differentiable_within_at ℝ g s x) (h : f x ≠ 0) : differentiable_within_at ℝ (λ x, f x ^ g x) s x := (differentiable_at_rpow_of_ne (f x, g x) h).comp_differentiable_within_at x (hf.prod hg) lemma differentiable_at.rpow (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) (h : f x ≠ 0) : differentiable_at ℝ (λ x, f x ^ g x) x := (differentiable_at_rpow_of_ne (f x, g x) h).comp x (hf.prod hg) lemma differentiable_on.rpow (hf : differentiable_on ℝ f s) (hg : differentiable_on ℝ g s) (h : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λ x, f x ^ g x) s := λ x hx, (hf x hx).rpow (hg x hx) (h x hx) lemma differentiable.rpow (hf : differentiable ℝ f) (hg : differentiable ℝ g) (h : ∀ x, f x ≠ 0) : differentiable ℝ (λ x, f x ^ g x) := λ x, (hf x).rpow (hg x) (h x) lemma has_fderiv_within_at.rpow_const (hf : has_fderiv_within_at f f' s x) (h : f x ≠ 0 ∨ 1 ≤ p) : has_fderiv_within_at (λ x, f x ^ p) ((p * f x ^ (p - 1)) • f') s x := (has_deriv_at_rpow_const h).comp_has_fderiv_within_at x hf lemma has_fderiv_at.rpow_const (hf : has_fderiv_at f f' x) (h : f x ≠ 0 ∨ 1 ≤ p) : has_fderiv_at (λ x, f x ^ p) ((p * f x ^ (p - 1)) • f') x := (has_deriv_at_rpow_const h).comp_has_fderiv_at x hf lemma has_strict_fderiv_at.rpow_const (hf : has_strict_fderiv_at f f' x) (h : f x ≠ 0 ∨ 1 ≤ p) : has_strict_fderiv_at (λ x, f x ^ p) ((p * f x ^ (p - 1)) • f') x := (has_strict_deriv_at_rpow_const h).comp_has_strict_fderiv_at x hf lemma differentiable_within_at.rpow_const (hf : differentiable_within_at ℝ f s x) (h : f x ≠ 0 ∨ 1 ≤ p) : differentiable_within_at ℝ (λ x, f x ^ p) s x := (hf.has_fderiv_within_at.rpow_const h).differentiable_within_at @[simp] lemma differentiable_at.rpow_const (hf : differentiable_at ℝ f x) (h : f x ≠ 0 ∨ 1 ≤ p) : differentiable_at ℝ (λ x, f x ^ p) x := (hf.has_fderiv_at.rpow_const h).differentiable_at lemma differentiable_on.rpow_const (hf : differentiable_on ℝ f s) (h : ∀ x ∈ s, f x ≠ 0 ∨ 1 ≤ p) : differentiable_on ℝ (λ x, f x ^ p) s := λ x hx, (hf x hx).rpow_const (h x hx) lemma differentiable.rpow_const (hf : differentiable ℝ f) (h : ∀ x, f x ≠ 0 ∨ 1 ≤ p) : differentiable ℝ (λ x, f x ^ p) := λ x, (hf x).rpow_const (h x) lemma has_fderiv_within_at.const_rpow (hf : has_fderiv_within_at f f' s x) (hc : 0 < c) : has_fderiv_within_at (λ x, c ^ f x) ((c ^ f x * log c) • f') s x := (has_strict_deriv_at_const_rpow hc (f x)).has_deriv_at.comp_has_fderiv_within_at x hf lemma has_fderiv_at.const_rpow (hf : has_fderiv_at f f' x) (hc : 0 < c) : has_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_rpow hc (f x)).has_deriv_at.comp_has_fderiv_at x hf lemma has_strict_fderiv_at.const_rpow (hf : has_strict_fderiv_at f f' x) (hc : 0 < c) : has_strict_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_rpow hc (f x)).comp_has_strict_fderiv_at x hf lemma cont_diff_within_at.rpow (hf : cont_diff_within_at ℝ n f s x) (hg : cont_diff_within_at ℝ n g s x) (h : f x ≠ 0) : cont_diff_within_at ℝ n (λ x, f x ^ g x) s x := (cont_diff_at_rpow_of_ne (f x, g x) h).comp_cont_diff_within_at x (hf.prod hg) lemma cont_diff_at.rpow (hf : cont_diff_at ℝ n f x) (hg : cont_diff_at ℝ n g x) (h : f x ≠ 0) : cont_diff_at ℝ n (λ x, f x ^ g x) x := (cont_diff_at_rpow_of_ne (f x, g x) h).comp x (hf.prod hg) lemma cont_diff_on.rpow (hf : cont_diff_on ℝ n f s) (hg : cont_diff_on ℝ n g s) (h : ∀ x ∈ s, f x ≠ 0) : cont_diff_on ℝ n (λ x, f x ^ g x) s := λ x hx, (hf x hx).rpow (hg x hx) (h x hx) lemma cont_diff.rpow (hf : cont_diff ℝ n f) (hg : cont_diff ℝ n g) (h : ∀ x, f x ≠ 0) : cont_diff ℝ n (λ x, f x ^ g x) := cont_diff_iff_cont_diff_at.mpr $ λ x, hf.cont_diff_at.rpow hg.cont_diff_at (h x) lemma cont_diff_within_at.rpow_const_of_ne (hf : cont_diff_within_at ℝ n f s x) (h : f x ≠ 0) : cont_diff_within_at ℝ n (λ x, f x ^ p) s x := hf.rpow cont_diff_within_at_const h lemma cont_diff_at.rpow_const_of_ne (hf : cont_diff_at ℝ n f x) (h : f x ≠ 0) : cont_diff_at ℝ n (λ x, f x ^ p) x := hf.rpow cont_diff_at_const h lemma cont_diff_on.rpow_const_of_ne (hf : cont_diff_on ℝ n f s) (h : ∀ x ∈ s, f x ≠ 0) : cont_diff_on ℝ n (λ x, f x ^ p) s := λ x hx, (hf x hx).rpow_const_of_ne (h x hx) lemma cont_diff.rpow_const_of_ne (hf : cont_diff ℝ n f) (h : ∀ x, f x ≠ 0) : cont_diff ℝ n (λ x, f x ^ p) := hf.rpow cont_diff_const h variable {m : ℕ} lemma cont_diff_within_at.rpow_const_of_le (hf : cont_diff_within_at ℝ m f s x) (h : ↑m ≤ p) : cont_diff_within_at ℝ m (λ x, f x ^ p) s x := (cont_diff_at_rpow_const_of_le h).comp_cont_diff_within_at x hf lemma cont_diff_at.rpow_const_of_le (hf : cont_diff_at ℝ m f x) (h : ↑m ≤ p) : cont_diff_at ℝ m (λ x, f x ^ p) x := by { rw ← cont_diff_within_at_univ at *, exact hf.rpow_const_of_le h } lemma cont_diff_on.rpow_const_of_le (hf : cont_diff_on ℝ m f s) (h : ↑m ≤ p) : cont_diff_on ℝ m (λ x, f x ^ p) s := λ x hx, (hf x hx).rpow_const_of_le h lemma cont_diff.rpow_const_of_le (hf : cont_diff ℝ m f) (h : ↑m ≤ p) : cont_diff ℝ m (λ x, f x ^ p) := cont_diff_iff_cont_diff_at.mpr $ λ x, hf.cont_diff_at.rpow_const_of_le h end fderiv section deriv variables {f g : ℝ → ℝ} {f' g' x y p : ℝ} {s : set ℝ} lemma has_deriv_within_at.rpow (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) (h : 0 < f x) : has_deriv_within_at (λ x, f x ^ g x) (f' * g x * (f x) ^ (g x - 1) + g' * f x ^ g x * log (f x)) s x := begin convert (hf.has_fderiv_within_at.rpow hg.has_fderiv_within_at h).has_deriv_within_at using 1, dsimp, ring end lemma has_deriv_at.rpow (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) (h : 0 < f x) : has_deriv_at (λ x, f x ^ g x) (f' * g x * (f x) ^ (g x - 1) + g' * f x ^ g x * log (f x)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow hg h end lemma has_deriv_within_at.rpow_const (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0 ∨ 1 ≤ p) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x) ^ (p - 1)) s x := begin convert (has_deriv_at_rpow_const hx).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow_const (hf : has_deriv_at f f' x) (hx : f x ≠ 0 ∨ 1 ≤ p) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow_const hx end lemma deriv_within_rpow_const (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0 ∨ 1 ≤ p) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x) ^ p) s x = (deriv_within f s x) * p * (f x) ^ (p - 1) := (hf.has_deriv_within_at.rpow_const hx).deriv_within hxs @[simp] lemma deriv_rpow_const (hf : differentiable_at ℝ f x) (hx : f x ≠ 0 ∨ 1 ≤ p) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow_const hx).deriv end deriv end differentiability section limits open real filter /-- The function `(1 + t/x) ^ x` tends to `exp t` at `+∞`. -/ lemma tendsto_one_plus_div_rpow_exp (t : ℝ) : tendsto (λ (x : ℝ), (1 + t / x) ^ x) at_top (𝓝 (exp t)) := begin apply ((real.continuous_exp.tendsto _).comp (tendsto_mul_log_one_plus_div_at_top t)).congr' _, have h₁ : (1:ℝ)/2 < 1 := by linarith, have h₂ : tendsto (λ x : ℝ, 1 + t / x) at_top (𝓝 1) := by simpa using (tendsto_inv_at_top_zero.const_mul t).const_add 1, refine (eventually_ge_of_tendsto_gt h₁ h₂).mono (λ x hx, _), have hx' : 0 < 1 + t / x := by linarith, simp [mul_comm x, exp_mul, exp_log hx'], end /-- The function `(1 + t/x) ^ x` tends to `exp t` at `+∞` for naturals `x`. -/ lemma tendsto_one_plus_div_pow_exp (t : ℝ) : tendsto (λ (x : ℕ), (1 + t / (x:ℝ)) ^ x) at_top (𝓝 (real.exp t)) := ((tendsto_one_plus_div_rpow_exp t).comp tendsto_coe_nat_at_top_at_top).congr (by simp) end limits
import GMLInit.Data.Basic import GMLInit.Data.Nat namespace Int attribute [local eliminator] Nat.recDiag protected abbrev mk := Int.subNatNat scoped infix:55 " ⊖ " => Int.mk theorem zero_mk_zero : 0 ⊖ 0 = 0 := rfl theorem zero_mk_succ (n) : (0 ⊖ n + 1) = Int.negSucc n := rfl theorem succ_mk_zero (m) : (m + 1 ⊖ 0) = Int.ofNat (m+1) := by rw [Int.mk, Int.subNatNat, Nat.zero_sub, Nat.sub_zero] theorem succ_mk_succ (m n) : (m + 1 ⊖ n + 1) = (m ⊖ n) := by rw [Int.mk, Int.subNatNat, Int.subNatNat, Nat.succ_sub_succ, Nat.succ_sub_succ] theorem mk_zero (m) : (m ⊖ 0) = ofNat m := by rw [Int.mk, Int.subNatNat, Nat.zero_sub, Nat.sub_zero] theorem zero_mk (n) : (0 ⊖ n) = negOfNat n := match n with | 0 => rfl | _+1 => rfl theorem one_mk_zero : (1 ⊖ 0) = 1 := rfl protected def recMk.{u} {motive : Int → Sort u} (mk : (m n : Nat) → motive (m ⊖ n)) : (i : Int) → motive i | Int.ofNat m => mk_zero m ▸ mk m 0 | Int.negSucc n => mk 0 (n + 1) protected def recMkOn.{u} {motive : Int → Sort u} (i : Int) (mk : (m n : Nat) → motive (m ⊖ n)) : motive i := Int.recMk mk i protected def casesMkOn.{u} {motive : Int → Sort u} (i : Int) (mk : (m n : Nat) → motive (m ⊖ n)) : motive i := Int.recMk mk i -- asseert theorem add_zero (x : Int) : x + 0 = x -- assert theorem zero_add (x : Int) : 0 + x = x theorem mk_self (m) : (m ⊖ m) = 0 := by induction m with | zero => rfl | succ m ih => rw [succ_mk_succ]; exact ih theorem add_mk_add_left (k m n) : (k + m ⊖ k + n) = (m ⊖ n) := by induction k with | zero => rw [Nat.zero_add, Nat.zero_add] | succ k ih => rw [Nat.succ_add', Nat.succ_add', succ_mk_succ]; exact ih theorem add_mk_add_right (k m n) : (m + k ⊖ n + k) = (m ⊖ n) := by induction k with | zero => rw [Nat.add_zero, Nat.add_zero] | succ k ih => rw [Nat.add_succ' m k, Nat.add_succ' n k, succ_mk_succ]; exact ih theorem mk_add_ofNat (m n k) : (m ⊖ n) + ofNat k = (m + k ⊖ n) := by induction m, n with | zero_zero => rw [zero_mk_zero, Int.zero_add, Nat.zero_add, mk_zero] | zero_succ n => rw [zero_mk_succ, Nat.zero_add]; rfl | succ_zero m => rw [succ_mk_zero, mk_zero]; rfl | succ_succ m n ih => rw [succ_mk_succ, Nat.succ_add', succ_mk_succ, ih] theorem mk_add_negSucc (m n k) : (m ⊖ n) + negSucc k = (m ⊖ n + k + 1) := by induction m, n with | zero_zero => rw [zero_mk_zero, Int.zero_add, Nat.zero_add]; rfl | zero_succ n => rw [zero_mk_succ, zero_mk_succ, Nat.succ_add']; rfl | succ_zero m => rw [succ_mk_zero, Nat.zero_add]; rfl | succ_succ m n ih => rw [succ_mk_succ, Nat.succ_add', succ_mk_succ]; exact ih theorem mk_add_mk (m₁ n₁ m₂ n₂) : (m₁ ⊖ n₁) + (m₂ ⊖ n₂) = (m₁ + m₂ ⊖ n₁ + n₂) := by induction m₂, n₂ with | zero_zero => rw [zero_mk_zero, Int.add_zero, Nat.add_zero, Nat.add_zero] | zero_succ n₂ => rw [zero_mk_succ, Nat.add_succ', mk_add_negSucc]; rfl | succ_zero m₂ => rw [mk_zero, mk_add_ofNat]; rfl | succ_succ m₂ n₂ ih => rw [succ_mk_succ, Nat.add_succ' m₁ m₂, Nat.add_succ' n₁ n₂, succ_mk_succ]; exact ih theorem neg_mk (m n) : -(m ⊖ n) = (n ⊖ m) := by induction m, n with | zero_zero => rw [zero_mk_zero]; rfl | zero_succ n => rw [zero_mk_succ, succ_mk_zero]; rfl | succ_zero m => rw [succ_mk_zero, zero_mk_succ]; rfl | succ_succ m n ih => rw [succ_mk_succ, succ_mk_succ]; exact ih theorem mk_sub_mk (m₁ n₁ m₂ n₂) : (m₁ ⊖ n₁) - (m₂ ⊖ n₂) = (m₁ + n₂ ⊖ n₁ + m₂) := show (m₁ ⊖ n₁) + -(m₂ ⊖ n₂) = (m₁ + n₂ ⊖ n₁ + m₂) by rw [neg_mk, mk_add_mk] theorem nonNeg_mk (m n) : NonNeg (m ⊖ n) ↔ n ≤ m := by induction m, n with | zero_zero => rw [zero_mk_zero] constr · intro; reflexivity · intro; apply NonNeg.mk | zero_succ n => rw [zero_mk_succ] constr · intro; contradiction · intro; contradiction | succ_zero m => rw [succ_mk_zero] constr · intro; apply Nat.zero_le · intro; apply NonNeg.mk | succ_succ m n ih => rw [succ_mk_succ] rw [Nat.succ_le_succ_iff_le] exact ih theorem mk_le_mk (m₁ n₁ m₂ n₂) : (m₁ ⊖ n₁) ≤ (m₂ ⊖ n₂) ↔ n₂ + m₁ ≤ m₂ + n₁ := by simp only [LE.le, Int.le] rw [mk_sub_mk, nonNeg_mk] reflexivity theorem mk_lt_mk (m₁ n₁ m₂ n₂) : (m₁ ⊖ n₁) < (m₂ ⊖ n₂) ↔ n₂ + m₁ < m₂ + n₁ := by simp only [LT.lt, Int.lt, Nat.lt] rw [←one_mk_zero, mk_add_mk, mk_le_mk, Nat.add_succ, Nat.add_zero] reflexivity -- assert theorem add_assoc (i j k : Int) : (i + j) + k = i + (j + k) -- assert theorem add_comm (i j : Int) : i + j = j + i -- assert theorem add_left_comm (i j k : Int) : i + (j + k) = j + (i + k) -- assert theorem add_right_comm (i j k : Int) : (i + j) + k = (i + k) + j protected theorem add_cross_comm (i₁ i₂ j₁ j₂ : Int) : (i₁ + i₂) + (j₁ + j₂) = (i₁ + j₁) + (i₂ + j₂) := calc _ = i₁ + (i₂ + (j₁ + j₂)) := by rw [Int.add_assoc] _ = i₁ + (j₁ + (i₂ + j₂)) := by rw [Int.add_left_comm i₂ j₁ j₂] _ = (i₁ + j₁) + (i₂ + j₂) := by rw [Int.add_assoc] -- assert theorem neg_zero : -0 = 0 -- assert theorem neg_neg (i : Int) : -(-i) = i -- assert theorem neg_add (i j : Int) : -(i + j) = -i + -j protected theorem add_neg_self_left (i : Int) : -i + i = 0 := by cases i using Int.casesMkOn with | mk mi ni => rw [neg_mk, mk_add_mk, Nat.add_comm mi ni, mk_self] protected theorem add_neg_self_right (i : Int) : i + -i = 0 := by cases i using Int.casesMkOn with | mk mi ni => rw [neg_mk, mk_add_mk, Nat.add_comm mi ni, mk_self] protected theorem sub_eq (i j : Int) : i - j = i + -j := rfl -- assert theorem sub_zero (i : Int) : i - 0 = i -- assert theorem zero_sub (i : Int) : 0 - i = -i -- assert theorem sub_self (i : Int) : i - i = 0 -- assert theorem add_sub_assoc (i j k : Int) : (i + j) - k = i + (j - k) protected theorem sub_add_assoc (i j k : Int) : (i - j) + k = i - (j - k) := calc _ = (i + -j) + k := by rw [Int.sub_eq] _ = i + (-j + k) := by rw [Int.add_assoc] _ = i + (-j + -(-k)) := by rw [Int.neg_neg] _ = i + -(j + -k) := by rw [Int.neg_add] _ = i - (j - k) := by rw [Int.sub_eq, Int.sub_eq] -- assert theorem add_sub_cancel (i j : Int) : (i + j) - j = i -- assert theorem sub_add_cancel (i j : Int) : (i - j) + j = i -- assert theorem neg_sub (i j : Int) : -(i - j) = j - i protected theorem add_left_cancel' (i : Int) {j k : Int} (h : i + j = i + k) : j = k := calc _ = 0 + j := by rw [Int.zero_add] _ = (-i + i) + j := by rw [Int.add_neg_self_left] _ = -i + (i + j) := by rw [Int.add_assoc] _ = -i + (i + k) := by rw [h] _ = (-i + i) + k := by rw [Int.add_assoc] _ = 0 + k := by rw [Int.add_neg_self_left] _ = k := by rw [Int.zero_add] protected theorem add_right_cancel' (i : Int) {j k : Int} (h : j + i = k + i) : j = k := calc _ = j + 0 := by rw [Int.add_zero] _ = j + (i + -i) := by rw [Int.add_neg_self_right] _ = (j + i) + -i := by rw [Int.add_assoc] _ = (k + i) + -i := by rw [h] _ = k + (i + -i) := by rw [Int.add_assoc] _ = k + 0 := by rw [Int.add_neg_self_right] _ = k := by rw [Int.add_zero] -- assert theorem mul_zero (i : Int) : i * 0 = 0 -- assert theorem zero_mul (i : Int) : 0 * i = 0 -- assert theorem mul_one (i : Int) : i * 1 = i -- assert theorem one_mul (i : Int) : 1 * i = i theorem mk_mul_ofNat (m n k) : (m ⊖ n) * ofNat k = (m * k ⊖ n * k) := by induction m, n with | zero_zero => rw [Nat.zero_mul, zero_mk_zero, Int.zero_mul] | zero_succ n => rw [Nat.zero_mul, zero_mk, zero_mk]; rfl | succ_zero m => rw [Nat.zero_mul, mk_zero, mk_zero]; rfl | succ_succ m n ih => rw [Nat.succ_mul, Nat.succ_mul, succ_mk_succ, add_mk_add_right]; exact ih theorem mk_mul_negSucc (m n k) : (m ⊖ n) * negSucc k = (n * (k + 1) ⊖ m * (k + 1)) := by induction m, n with | zero_zero => rw [Nat.zero_mul, zero_mk_zero, Int.zero_mul] | zero_succ n => rw [Nat.zero_mul, zero_mk, mk_zero]; rfl | succ_zero m => rw [Nat.zero_mul, mk_zero, zero_mk]; rfl | succ_succ m n ih => rw [Nat.succ_mul, Nat.succ_mul, succ_mk_succ, add_mk_add_right]; exact ih theorem mk_mul_mk (m₁ n₁ m₂ n₂) : (m₁ ⊖ n₁) * (m₂ ⊖ n₂) = (m₁ * m₂ + n₁ * n₂ ⊖ m₁ * n₂ + n₁ * m₂) := by induction m₂, n₂ with | zero_zero => simp only [Nat.zero_mul, Nat.mul_zero, Nat.add_zero, Nat.zero_add, zero_mk_zero, Int.mul_zero] | zero_succ n₂ => simp only [Nat.zero_mul, Nat.mul_zero, Nat.add_zero, Nat.zero_add, zero_mk_succ, mk_mul_negSucc] | succ_zero m₂ => simp only [Nat.zero_mul, Nat.mul_zero, Nat.add_zero, Nat.zero_add, succ_mk_zero, mk_mul_ofNat, Nat.mul_comm] | succ_succ m₂ n₂ ih => simp only [Nat.mul_succ, Nat.succ_mul]; rw [succ_mk_succ, Nat.add_cross_comm _ m₁ _ n₁, Nat.add_cross_comm _ m₁ _ n₁, add_mk_add_right]; exact ih -- assert theorem mul_assoc (i j k : Int) : (i * j) * k = i * (j * k) -- assert theorem mul_comm (i j : Int) : i * j = j * i -- assert theorem mul_left_comm (i j k : Int) : i * (j * k) = j * (i * k) -- assert theorem mul_right_comm (i j k : Int) : (i * j) * k = (i * k) * j protected theorem mul_cross_comm (i₁ i₂ j₁ j₂ : Int) : (i₁ * i₂) * (j₁ * j₂) = (i₁ * j₁) * (i₂ * j₂) := calc _ = i₁ * (i₂ * (j₁ * j₂)) := by rw [Int.mul_assoc] _ = i₁ * (j₁ * (i₂ * j₂)) := by rw [Int.mul_left_comm i₂ j₁ j₂] _ = (i₁ * j₁) * (i₂ * j₂) := by rw [Int.mul_assoc] -- assert theorem mul_neg (i j : Int) : i * (-j) = -(i * j) -- assert theorem neg_mul (i j : Int) : (-i) * j = -(i * j) -- assert theorem mul_add (i j k : Int) : i * (j + k) = i * j + i * k) -- assert theorem add_mul (i j k : Int) : (i + j) * k = i * k + j * k] -- assert theorem mul_sub (i j k : Int) : i * (j - k) = i * j - i * k -- assert theorem sub_mul (i j k : Int) : (i - j) * k = i * k - j * k theorem le.intro' (i : Int) (k : Nat) : i ≤ i + k := show (NonNeg ((i+k)-i)) by rw [Int.sub_eq, Int.add_right_comm, Int.add_neg_self_right, Int.zero_add] apply NonNeg.mk theorem le.dest' {i j : Int} : i ≤ j → ∃ (k : Nat), j = i + ofNat k := by intro (h : NonNeg (j - i)) match hk : j - i with | ofNat k => exists k; rw [←hk, Int.sub_eq, Int.add_left_comm, Int.add_neg_self_right, Int.add_zero] | negSucc _ => rw [hk] at h; contradiction -- assert theorem le_refl (i : Int) : i ≤ i -- assert theorem le_trans {i j k : Int} : i ≤ j → j ≤ k → i ≤ k -- assert theorem le_antisymm {i j : Int} : i ≤ j → j ≤ i → i = j -- assert theorem le_total (i j : Int) : i ≤ j ∨ j ≤ i -- assert theorem add_le_add_left {i j : Int} : i ≤ j → ∀ (k : Int), k + i ≤ k + j -- assert theorem add_le_add_right {i j : Int} : i ≤ j → ∀ (k : Int), i + k ≤ j + k -- assert theorem sub_le_sub_right {i j : Int} : i ≤ j → ∀ (k : Int), i - k ≤ j - k -- assert theorem le_of_add_le_add_right {i j k : Int} (h : i + k ≤ j + k) : i ≤ j -- assert theorem le_of_add_le_add_left {i j k : Int} (h : i + j ≤ i + k) : j ≤ k protected theorem le_succ_self (i : Int) : i ≤ i + 1 := le.intro' .. protected theorem lt_iff_succ_le (i j : Int) : i < j ↔ i + 1 ≤ j := Iff.rfl protected theorem le_iff_lt_succ (i j : Int) : i ≤ j ↔ i < j + 1 := by rw [Int.lt_iff_succ_le] constr · apply Int.add_le_add_right (c:=1) · apply Int.le_of_add_le_add_right -- assert theorem le_of_lt {i j : Int} : i < j → i ≤ j -- assert theorem lt_of_lt_of_le {i j k : Int} : i < j → j ≤ k → i < k -- assert theorem lt_of_le_of_lt {i j k : Int} : i ≤ j → j < k → i < k -- assert theorem lt_irrefl (i : Int) : ¬ i < i -- assert theorem lt_trans {i j k : Int} : i < j → j < k → i < k protected theorem le_or_gt (i j : Int) : i ≤ j ∨ j < i := by induction i using Int.casesMkOn with | mk mi ni => induction j using Int.casesMkOn with | mk mj nj => rw [mk_le_mk, mk_lt_mk] rw [Nat.add_comm mi, Nat.add_comm mj] exact Nat.le_or_gt .. protected theorem lt_or_ge (i j : Int) : i < j ∨ j ≤ i := by cases Int.le_or_gt j i with | inl h => right; exact h | inr h => left; exact h theorem lt_or_eq_of_le {i j : Int} : i ≤ j → i < j ∨ i = j := by intro hle match le.dest' hle with | ⟨0, (h : j = i + 0)⟩ => right rw [h, Int.add_zero] | ⟨n+1, (h : j = i + (ofNat n + 1))⟩ => left rw [Int.lt_iff_succ_le] rw [h, ←Int.add_assoc, Int.add_right_comm] apply Int.le.intro' protected theorem lt_of_le_of_ne {i j : Int} : i ≤ j → i ≠ j → i < j := by intro hle hne cases lt_or_eq_of_le hle with | inl hlt => exact hlt | inr heq => absurd heq; exact hne protected theorem lt_connex {i j : Int} : i ≠ j → i < j ∨ j < i := by intro hne cases Int.le_or_gt i j with | inl hle => left; apply Int.lt_of_le_of_ne hle hne | inr hgt => right; exact hgt protected theorem lt_compare {i j : Int} : i < j → ∀ (k : Int), i < k ∨ k < j := by intro hij k cases Int.le_or_gt k i with | inl hle => right; exact Int.lt_of_le_of_lt hle hij | inr hgt => left; exact hgt instance : Relation.Reflexive (α:=Int) (.≤.) := ⟨Int.le_refl⟩ instance : Relation.Transitive (α:=Int) (.≤.) := ⟨Int.le_trans⟩ instance : Relation.Antisymmetric (α:=Int) (.≤.) := ⟨Int.le_antisymm⟩ instance : Relation.Total (α:=Int) (.≤.) := ⟨Int.le_total⟩ instance : Relation.Irreflexive (α:=Int) (.<.) := ⟨Int.lt_irrefl⟩ instance : Relation.Transitive (α:=Int) (.<.) := ⟨Int.lt_trans⟩ instance : Relation.Comparison (α:=Int) (.<.) := ⟨Int.lt_compare⟩ instance : Relation.Connex (α:=Int) (.<.) := ⟨Int.lt_connex⟩ instance : Relation.HTransitive (α:=Int) (.≤.) (.<.) (.<.) := ⟨Int.lt_of_le_of_lt⟩ instance : Relation.HTransitive (α:=Int) (.<.) (.≤.) (.<.) := ⟨Int.lt_of_lt_of_le⟩ end Int
[STATEMENT] lemma drop_bit_of_nat: "drop_bit n (of_nat m) = of_nat (drop_bit n m)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. drop_bit n (of_nat m) = of_nat (drop_bit n m) [PROOF STEP] by (simp add: drop_bit_eq_div Bit_Operations.drop_bit_eq_div of_nat_div [of m "2 ^ n"])
import category_theory.limits.shapes.pullbacks /-! Thanks to Markus Himmel for suggesting this question. -/ open category_theory open category_theory.limits /-! Let C be a category, X and Y be objects and f : X ⟶ Y be a morphism. Show that f is an epimorphism if and only if the diagram X --f--→ Y | | f 𝟙 | | ↓ ↓ Y --𝟙--→ Y is a pushout. -/ universes v u variables {C : Type u} [category.{v} C] def pushout_of_epi {X Y : C} (f : X ⟶ Y) [epi f] : is_colimit (pushout_cocone.mk (𝟙 Y) (𝟙 Y) rfl : pushout_cocone f f) := -- Hint: you can start a proof with `fapply pushout_cocone.is_colimit.mk` -- to save a little bit of work over just building a `is_colimit` structure directly. begin fapply pushout_cocone.is_colimit.mk, { intro s, apply s.ι.app walking_span.left, }, { tidy, }, { tidy, /- we clearly need to use that `f` is an epi here!-/ sorry }, { tidy, } end theorem epi_of_pushout {X Y : C} (f : X ⟶ Y) (is_colim : is_colimit (pushout_cocone.mk (𝟙 Y) (𝟙 Y) rfl : pushout_cocone f f)) : epi f := { left_cancellation := λ Z g h hf, begin let a := pushout_cocone.mk _ _ hf, have hg : is_colim.desc a = g, sorry, have hh : is_colim.desc a = h, sorry, rw [←hg, ←hh], end }
State Before: α : Type ?u.462750 β : Type ?u.462753 ι : Type ?u.462756 m : ℝ f : ℕ → ℕ hm : 1 < m fi : ∀ (i : ℕ), i ≤ f i ⊢ Summable fun i => 1 / m ^ f i State After: α : Type ?u.462750 β : Type ?u.462753 ι : Type ?u.462756 m : ℝ f : ℕ → ℕ hm : 1 < m fi : ∀ (i : ℕ), i ≤ f i a : ℕ ⊢ 1 / m ^ f a ≤ (1 / m) ^ a Tactic: refine' summable_of_nonneg_of_le (fun a => one_div_nonneg.mpr (pow_nonneg (zero_le_one.trans hm.le) _)) (fun a => _) (summable_geometric_of_lt_1 (one_div_nonneg.mpr (zero_le_one.trans hm.le)) ((one_div_lt (zero_lt_one.trans hm) zero_lt_one).mpr (one_div_one.le.trans_lt hm))) State Before: α : Type ?u.462750 β : Type ?u.462753 ι : Type ?u.462756 m : ℝ f : ℕ → ℕ hm : 1 < m fi : ∀ (i : ℕ), i ≤ f i a : ℕ ⊢ 1 / m ^ f a ≤ (1 / m) ^ a State After: α : Type ?u.462750 β : Type ?u.462753 ι : Type ?u.462756 m : ℝ f : ℕ → ℕ hm : 1 < m fi : ∀ (i : ℕ), i ≤ f i a : ℕ ⊢ 1 / m ^ f a ≤ 1 / m ^ a Tactic: rw [div_pow, one_pow] State Before: α : Type ?u.462750 β : Type ?u.462753 ι : Type ?u.462756 m : ℝ f : ℕ → ℕ hm : 1 < m fi : ∀ (i : ℕ), i ≤ f i a : ℕ ⊢ 1 / m ^ f a ≤ 1 / m ^ a State After: no goals Tactic: refine' (one_div_le_one_div _ _).mpr (pow_le_pow hm.le (fi a)) <;> exact pow_pos (zero_lt_one.trans hm) _
% pop_expica() - export ICA weights or inverse matrix % % Usage: % >> pop_expica( EEG, whichica); % a window pops up % >> pop_expica( EEG, whichica, filename ); % % Inputs: % EEG - EEGLAB dataset % whichica - ['weights'|'inv'] export ica 'weights' or ica inverse % matrix ('inv'). Note: for 'weights', the function % export the product of the sphere and weights matrix. % filename - text file name % % Author: Arnaud Delorme, CNL / Salk Institute, Mai 14, 2003 % % See also: pop_export() % Copyright (C) Mai 14, 2003, Arnaud Delorme, Salk Institute, [email protected] % % 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 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function com = pop_expica(EEG, whichica, filename); com = ''; if nargin < 1 help pop_expica; return; end; if nargin < 2 whichica = 'weights'; end; switch lower(whichica) case {'weights' 'inv'}, ; otherwise error('Unrecognized option for ''whichica'' parameter'); end; if nargin < 3 % ask user [filename, filepath] = uiputfile('*.*', [ 'File name for ' ... fastif(strcmpi(whichica, 'inv'), 'inverse', 'weight') ' matrix -- pop_expica()']); drawnow; if filename == 0 return; end; filename = [filepath filename]; end; % save datas % ---------- if strcmpi(whichica, 'inv') tmpmat = double(EEG.icawinv); else tmpmat = double(EEG.icaweights*EEG.icasphere); end; save(filename, '-ascii', 'tmpmat'); com = sprintf('pop_expica(%s, ''%s'', ''%s'');', inputname(1), whichica, filename); return;
module Core.SchemeEval -- Top level interface to the scheme based evaluator -- Drops back to the default slow evaluator if scheme isn't available import Core.Context import Core.Core import Core.Env import Core.Normalise import public Core.SchemeEval.Compile import public Core.SchemeEval.Evaluate import public Core.SchemeEval.Quote import public Core.SchemeEval.ToScheme import Core.TT {- Summary: SObj vars ...is a scheme object with the scheme representation of the result of evaluating a term vars SNF vars ...corresponds to NF vars, and is an inspectable version of the above. Evaluation is call by value, but there has not yet been any evaluation under lambdas 'Evaluate.seval' gets you an SObj from a Term - this involves compiling all the relevant definitions to scheme code first. We make a note of what we've compiled to scheme so we don't have to do it more than once. `Evaluate.toSNF` gets you an SNF from an SObj `Quote.quote` gets you back to a Term from an SNF `snf` gets you directly to an SNF from a Term `snormalise` packages up the whole process All of this works only on a back end which can call scheme directly, and with the relevant support files (currently: Chez) -} snormaliseMode : {auto c : Ref Ctxt Defs} -> {vars : _} -> SchemeMode -> Env Term vars -> Term vars -> Core (Term vars) snormaliseMode mode env tm = do defs <- get Ctxt True <- initialiseSchemeEval | _ => normalise defs env tm sval <- seval mode env tm quoteObj sval export snormalise : {auto c : Ref Ctxt Defs} -> {vars : _} -> Env Term vars -> Term vars -> Core (Term vars) snormalise = snormaliseMode BlockExport export snormaliseAll : {auto c : Ref Ctxt Defs} -> {vars : _} -> Env Term vars -> Term vars -> Core (Term vars) snormaliseAll = snormaliseMode EvalAll export snf : {auto c : Ref Ctxt Defs} -> {vars : _} -> Env Term vars -> Term vars -> Core (SNF vars) snf env tm = do True <- initialiseSchemeEval | _ => throw (InternalError "Scheme evaluator not available") sval <- seval BlockExport env tm toSNF sval export snfAll : {auto c : Ref Ctxt Defs} -> {vars : _} -> Env Term vars -> Term vars -> Core (SNF vars) snfAll env tm = do True <- initialiseSchemeEval | _ => throw (InternalError "Scheme evaluator not available") sval <- seval EvalAll env tm toSNF sval
[STATEMENT] lemma mapM_return: assumes "mapM f xs = return ys" shows "ys = map (run \<circ> f) xs \<and> (\<forall>x\<in>set xs. \<forall>e. f x \<noteq> error e)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ys = map (projr \<circ> f) xs \<and> (\<forall>x\<in>set xs. \<forall>e. f x \<noteq> Inl e) [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: mapM f xs = Inr ys goal (1 subgoal): 1. ys = map (projr \<circ> f) xs \<and> (\<forall>x\<in>set xs. \<forall>e. f x \<noteq> Inl e) [PROOF STEP] proof (induct xs arbitrary: ys) [PROOF STATE] proof (state) goal (2 subgoals): 1. \<And>ys. mapM f [] = Inr ys \<Longrightarrow> ys = map (projr \<circ> f) [] \<and> (\<forall>x\<in>set []. \<forall>e. f x \<noteq> Inl e) 2. \<And>a xs ys. \<lbrakk>\<And>ys. mapM f xs = Inr ys \<Longrightarrow> ys = map (projr \<circ> f) xs \<and> (\<forall>x\<in>set xs. \<forall>e. f x \<noteq> Inl e); mapM f (a # xs) = Inr ys\<rbrakk> \<Longrightarrow> ys = map (projr \<circ> f) (a # xs) \<and> (\<forall>x\<in>set (a # xs). \<forall>e. f x \<noteq> Inl e) [PROOF STEP] case (Cons x xs ys) [PROOF STATE] proof (state) this: mapM f xs = Inr ?ys \<Longrightarrow> ?ys = map (projr \<circ> f) xs \<and> (\<forall>x\<in>set xs. \<forall>e. f x \<noteq> Inl e) mapM f (x # xs) = Inr ys goal (2 subgoals): 1. \<And>ys. mapM f [] = Inr ys \<Longrightarrow> ys = map (projr \<circ> f) [] \<and> (\<forall>x\<in>set []. \<forall>e. f x \<noteq> Inl e) 2. \<And>a xs ys. \<lbrakk>\<And>ys. mapM f xs = Inr ys \<Longrightarrow> ys = map (projr \<circ> f) xs \<and> (\<forall>x\<in>set xs. \<forall>e. f x \<noteq> Inl e); mapM f (a # xs) = Inr ys\<rbrakk> \<Longrightarrow> ys = map (projr \<circ> f) (a # xs) \<and> (\<forall>x\<in>set (a # xs). \<forall>e. f x \<noteq> Inl e) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: mapM f xs = Inr ?ys \<Longrightarrow> ?ys = map (projr \<circ> f) xs \<and> (\<forall>x\<in>set xs. \<forall>e. f x \<noteq> Inl e) mapM f (x # xs) = Inr ys [PROOF STEP] show ?case [PROOF STATE] proof (prove) using this: mapM f xs = Inr ?ys \<Longrightarrow> ?ys = map (projr \<circ> f) xs \<and> (\<forall>x\<in>set xs. \<forall>e. f x \<noteq> Inl e) mapM f (x # xs) = Inr ys goal (1 subgoal): 1. ys = map (projr \<circ> f) (x # xs) \<and> (\<forall>x\<in>set (x # xs). \<forall>e. f x \<noteq> Inl e) [PROOF STEP] by (cases "f x", simp, cases "mapM f xs", simp_all) [PROOF STATE] proof (state) this: ys = map (projr \<circ> f) (x # xs) \<and> (\<forall>x\<in>set (x # xs). \<forall>e. f x \<noteq> Inl e) goal (1 subgoal): 1. \<And>ys. mapM f [] = Inr ys \<Longrightarrow> ys = map (projr \<circ> f) [] \<and> (\<forall>x\<in>set []. \<forall>e. f x \<noteq> Inl e) [PROOF STEP] qed simp
# 18 PDEs: Waves (See *Computational Physics* Ch 21 and *Computational Modeling* Ch 6.5.) ## Background: waves on a string Assume a 1D string of length $L$ with mass density per unit length $\rho$ along the $x$ direction. It is held under constant tension $T$ (force per unit length). Ignore frictional forces and the tension is so high that we can ignore sagging due to gravity. ### 1D wave equation The string is displaced in the $y$ direction from its rest position, i.e., the displacement $y(x, t)$ is a function of space $x$ and time $t$. For small relative displacements $y(x, t)/L \ll 1$ and therefore small slopes $\partial y/\partial x$ we can describe $y(x, t)$ with a *linear* equation of motion: Newton's second law applied to short elements of the string with length $\Delta x$ and mass $\Delta m = \rho \Delta x$: the left hand side contains the *restoring force* that opposes the displacement, the right hand side is the acceleration of the string element: \begin{align} \sum F_{y}(x) &= \Delta m\, a(x, t)\\ T \sin\theta(x+\Delta x) - T \sin\theta(x) &= \rho \Delta x \frac{\partial^2 y(x, t)}{\partial t^2} \end{align} The angle $\theta$ measures by how much the string is bent away from the resting configuration. Because we assume small relative displacements, the angles are small ($\theta \ll 1$) and we can make the small angle approximation $$ \sin\theta \approx \tan\theta = \frac{\partial y}{\partial x} $$ and hence \begin{align} T \left.\frac{\partial y}{\partial x}\right|_{x+\Delta x} - T \left.\frac{\partial y}{\partial x}\right|_{x} &= \rho \Delta x \frac{\partial^2 y(x, t)}{\partial t^2}\\ \frac{T \left.\frac{\partial y}{\partial x}\right|_{x+\Delta x} - T \left.\frac{\partial y}{\partial x}\right|_{x}}{\Delta x} &= \rho \frac{\partial^2 y}{\partial t^2} \end{align} or in the limit $\Delta x \rightarrow 0$ a linear hyperbolic PDE results: \begin{gather} \frac{\partial^2 y(x, t)}{\partial x^2} = \frac{1}{c^2} \frac{\partial^2 y(x, t)}{\partial t^2}, \quad c = \sqrt{\frac{T}{\rho}} \end{gather} where $c$ has the dimension of a velocity. This is the (linear) **wave equation**. ### General solution: waves General solutions are propagating waves: If $f(x)$ is a solution at $t=0$ then $$ y_{\mp}(x, t) = f(x \mp ct) $$ are also solutions at later $t > 0$. Because of linearity, any linear combination is also a solution, so the most general solution contains both right and left propagating waves $$ y(x, t) = A f(x - ct) + B g(x + ct) $$ (If $f$ and/or $g$ are present depends on the initial conditions.) In three dimensions the wave equation is $$ \boldsymbol{\nabla}^2 y(\mathbf{x}, t) - \frac{1}{c^2} \frac{\partial^2 y(\mathbf{x}, t)}{\partial t^2} = 0\ $$ ### Boundary and initial conditions * The boundary conditions could be that the ends are fixed $$y(0, t) = y(L, t) = 0$$ * The *initial condition* is a shape for the string, e.g., a Gaussian at the center $$ y(x, t=0) = g(x) = y_0 \frac{1}{\sqrt{2\pi\sigma}} \exp\left[-\frac{(x - x_0)^2}{2\sigma^2}\right] $$ at time 0. * Because the wave equation is *second order in time* we need a second initial condition, for instance, the string is released from rest: $$ \frac{\partial y(x, t=0)}{\partial t} = 0 $$ (The derivative, i.e., the initial displacement velocity is provided.) ### Analytical solution Solve (as always) with *separation of variables*. $$ y(x, t) = X(x) T(t) $$ and this yields the general solution (with boundary conditions of fixed string ends and initial condition of zero velocity) as a superposition of normal modes $$ y(x, t) = \sum_{n=0}^{+\infty} B_n \sin k_n x\, \cos\omega_n t, \quad \omega_n = ck_n,\ k_n = n \frac{2\pi}{L} = n k_0. $$ (The angular frequency $\omega$ and the wave vector $k$ are determined from the boundary conditions.) The coefficients $B_n$ are obtained from the initial shape: $$ y(x, t=0) = \sum_{n=0}^{+\infty} B_n \sin n k_0 x = g(x) $$ In principle one can use the fact that $\int_0^L dx \sin m k_0 x \, \sin n k_0 x = \pi \delta_{mn}$ (orthogonality) to calculate the coefficients: \begin{align} \int_0^L dx \sin m k_0 x \sum_{n=0}^{+\infty} B_n \sin n k_0 x &= \int_0^L dx \sin(m k_0 x) \, g(x)\\ \pi \sum_{n=0}^{+\infty} B_n \delta_{mn} &= \dots \\ B_m &= \pi^{-1} \dots \end{align} (but the analytical solution is ugly and I cannot be bothered to put it down here.) ## Numerical solution 1. discretize wave equation 2. time stepping: leap frog algorithm (iterate) Use the central difference approximation for the second order derivatives: \begin{align} \frac{\partial^2 y}{\partial t^2} &\approx \frac{y(x, t+\Delta t) + y(x, t-\Delta t) - 2y(x, t)}{\Delta t ^2} = \frac{y_{i, j+1} + y_{i, j-1} - 2y_{i,j}}{\Delta t^2}\\ \frac{\partial^2 y}{\partial x^2} &\approx \frac{y(x+\Delta x, t) + y(x-\Delta x, t) - 2y(x, t)}{\Delta x ^2} = \frac{y_{i+1, j} + y_{i-1, j} - 2y_{i,j}}{\Delta x^2} \end{align} and substitute into the wave equation to yield the *discretized* wave equation: $$ \frac{y_{i+1, j} + y_{i-1, j} - 2y_{i,j}}{\Delta x^2} = \frac{1}{c^2} \frac{y_{i, j+1} + y_{i, j-1} - 2y_{i,j}}{\Delta t^2} $$ Re-arrange so that the future terms $j+1$ can be calculated from the present $j$ and past $j-1$ terms: $$ y_{i,j+1} = 2(1 - \beta^2)y_{i,j} - y_{i, j-1} + \beta^2 (y_{i+1,j} + y_{i-1,j}), \quad \beta := \frac{c}{\Delta x/\Delta t} $$ This is the time stepping algorithm for the wave equation. ## Numerical implementation ```python # if you have plotting problems, try # %matplotlib inline %matplotlib notebook import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D plt.style.use('ggplot') ``` ### Student version ```python L = 0.5 # m Nx = 50 Nt = 100 Dx = L/Nx Dt = 1e-4 # s rho = 1.5e-2 # kg/m tension = 150 # N c = np.sqrt(tension/rho) # TODO: calculate beta beta = c*Dt/Dx beta2 = beta**2 print("c = {0} m/s".format(c)) print("Dx = {0} m, Dt = {1} s, Dx/Dt = {2} m/s".format(Dx, Dt, Dx/Dt)) print("beta = {}".format(beta)) X = np.linspace(0, L, Nx+1) # need N+1! def gaussian(x, y0=0.05, x0=L/2, sigma=0.1*L): return y0/np.sqrt(2*np.pi*sigma) * np.exp(-(x-x0)**2/(2*sigma**2)) # displacements at j-1, j, j+1 y0 = np.zeros_like(X) y1 = np.zeros_like(y0) y2 = np.zeros_like(y0) # save array y_t = np.zeros((Nt+1, Nx+1)) # boundary conditions y0[0] = y0[-1] = y1[0] = y1[-1] = 0 y2[:] = y0 # initial conditions: velocity 0, i.e. no difference between y0 and y1 y0[1:-1] = y1[1:-1] = gaussian(X)[1:-1] # save initial t_index = 0 y_t[t_index, :] = y0 t_index += 1 y_t[t_index, :] = y1 for jt in range(2, Nt): y2[1:-1] = 2*(1-beta2)*y1[1:-1] - y0[1:-1] + beta2*(y1[2:] + y1[:-2]) y0[:], y1[:] = y1, y2 t_index += 1 y_t[t_index, :] = y2 print("Iteration {0:5d}".format(jt), end="\r") else: print("Completed {0:5d} iterations: t={1} s".format(jt, jt*Dt)) ``` c = 100.0 m/s Dx = 0.01 m, Dt = 0.0001 s, Dx/Dt = 100.0 m/s beta = 1.0 Completed 99 iterations: t=0.0099 s ### Fancy version Package as a function and can use `step` to only save every `step` time steps. ```python def wave(L=0.5, Nx=50, Dt=1e-4, Nt=100, step=1, rho=1.5e-2, tension=150.): Dx = L/Nx #rho = 1.5e-2 # kg/m #tension = 150 # N c = np.sqrt(tension/rho) beta = c*Dt/Dx beta2 = beta**2 print("c = {0} m/s".format(c)) print("Dx = {0} m, Dt = {1} s, Dx/Dt = {2} m/s".format(Dx, Dt, Dx/Dt)) print("beta = {}".format(beta)) X = np.linspace(0, L, Nx+1) # need N+1! def gaussian(x, y0=0.05, x0=L/2, sigma=0.1*L): return y0/np.sqrt(2*np.pi*sigma) * np.exp(-(x-x0)**2/(2*sigma**2)) # displacements at j-1, j, j+1 y0 = np.zeros_like(X) y1 = np.zeros_like(y0) y2 = np.zeros_like(y0) # save array y_t = np.zeros((int(np.ceil(Nt/step)) + 1, Nx+1)) # boundary conditions y0[0] = y0[-1] = y1[0] = y1[-1] = 0 y2[:] = y0 # initial conditions: velocity 0, i.e. no difference between y0 and y1 y0[1:-1] = y1[1:-1] = gaussian(X)[1:-1] # save initial t_index = 0 y_t[t_index, :] = y0 if step == 1: t_index += 1 y_t[t_index, :] = y1 for jt in range(2, Nt): y2[1:-1] = 2*(1-beta2)*y1[1:-1] - y0[1:-1] + beta2*(y1[2:] + y1[:-2]) y0[:], y1[:] = y1, y2 if jt % step == 0 or jt == Nt-1: t_index += 1 y_t[t_index, :] = y2 print("Iteration {0:5d}".format(jt), end="\r") else: print("Completed {0:5d} iterations: t={1} s".format(jt, jt*Dt)) return y_t, X, Dx, Dt, step ``` ```python y_t, X, Dx, Dt, step = wave() ``` c = 100.0 m/s Dx = 0.01 m, Dt = 0.0001 s, Dx/Dt = 100.0 m/s beta = 1.0 Completed 99 iterations: t=0.0099 s ### 1D plot Plot the output in the save array `y_t`. Vary the time steps that you look at with `y_t[start:end]`. We indicate time by color changing. ```python ax = plt.subplot(111) ax.set_prop_cycle("color", [plt.cm.viridis(i) for i in np.linspace(0, 1, len(y_t))]) ax.plot(X, y_t[:40].T, alpha=0.5); ``` <IPython.core.display.Javascript object> ### 1D Animation For 1D animation to work in a Jupyter notebook, use ```python %matplotlib notebook ``` If no animations are visible, restart kernel and execute the `%matplotlib notebook` cell as the very first one in the notebook. We use `matplotlib.animation` to look at movies of our solution: ```python import matplotlib.animation as animation ``` Generate one full period: ```python y_t, X, Dx, Dt, step = wave(Nt=100) ``` c = 100.0 m/s Dx = 0.01 m, Dt = 0.0001 s, Dx/Dt = 100.0 m/s beta = 1.0 Completed 99 iterations: t=0.0099 s The `update_wave()` function simply re-draws our image for every `frame`. ```python y_limits = 1.05*y_t.min(), 1.05*y_t.max() fig1 = plt.figure(figsize=(5,5)) ax = fig1.add_subplot(111) ax.set_aspect(1) def update_wave(frame, data): global ax, Dt, y_limits ax.clear() ax.set_xlabel("x (m)") ax.set_ylabel("y (m)") ax.plot(X, data[frame]) ax.set_ylim(y_limits) ax.text(0.1, 0.9, "t = {0:3.1f} ms".format(frame*Dt*1e3), transform=ax.transAxes) wave_anim = animation.FuncAnimation(fig1, update_wave, frames=len(y_t), fargs=(y_t,), interval=30, blit=True, repeat_delay=100) ``` <IPython.core.display.Javascript object> If you have ffmpeg installed then you can export to a MP4 movie file: ```python wave_anim.save("string.mp4", fps=30, dpi=300) ``` The whole video can be incoroporated into an html page (uses the HTML5 `<video>` tag). ```python with open("string.html", "w") as html: html.write(wave_anim.to_html5_video()) ``` ```python ``` ### 3D plot (Uses functions from previous lessons.) ```python def plot_y(y_t, Dt, Dx, step=1): T, X = np.meshgrid(range(y_t.shape[0]), range(y_t.shape[1])) Y = y_t.T[X, T] # intepret index 0 as "t" and index 1 as "x", but plot x along axis 1 and t along axis 2 fig = plt.figure() ax = fig.add_subplot(111, projection="3d") ax.plot_wireframe(X*Dx, T*Dt*step, Y) ax.set_ylabel(r"time $t$ (s)") ax.set_xlabel(r"position $x$ (m)") ax.set_zlabel(r"displacement $y$ (m)") fig.tight_layout() return ax def plot_surf(y_t, Dt, Dx, step=1, filename=None, offset=-1, zlabel=r'displacement', elevation=40, azimuth=-20, cmap=plt.cm.coolwarm): """Plot y_t as a 3D plot with contour plot underneath. Arguments --------- y_t : 2D array displacement y(t, x) filename : string or None, optional (default: None) If `None` then show the figure and return the axes object. If a string is given (like "contour.png") it will only plot to the filename and close the figure but return the filename. offset : float, optional (default: 20) position the 2D contour plot by offset along the Z direction under the minimum Z value zlabel : string, optional label for the Z axis and color scale bar elevation : float, optional choose elevation for initial viewpoint azimuth : float, optional chooze azimuth angle for initial viewpoint """ t = np.arange(y_t.shape[0], dtype=int) x = np.arange(y_t.shape[1], dtype=int) T, X = np.meshgrid(t, x) Y = y_t.T[X, T] fig = plt.figure() ax = fig.add_subplot(111, projection='3d') surf = ax.plot_surface(X*Dx, T*Dt*step, Y, cmap=cmap, rstride=1, cstride=1, alpha=1) cset = ax.contourf(X*Dx, T*Dt*step, Y, 20, zdir='z', offset=offset+Y.min(), cmap=cmap) ax.set_xlabel('x') ax.set_ylabel('t') ax.set_zlabel(zlabel) ax.set_zlim(offset + Y.min(), Y.max()) ax.view_init(elev=elevation, azim=azimuth) cb = fig.colorbar(surf, shrink=0.5, aspect=5) cb.set_label(zlabel) if filename: fig.savefig(filename) plt.close(fig) return filename else: return ax ``` ```python plot_y(y_t, Dt, Dx) ``` <IPython.core.display.Javascript object> <matplotlib.axes._subplots.Axes3DSubplot at 0x11a44d780> ```python plot_surf(y_t, Dt, Dx, offset=-0.04, cmap=plt.cm.coolwarm) ``` <IPython.core.display.Javascript object> <matplotlib.axes._subplots.Axes3DSubplot at 0x11c27b390> ## von Neumann stability analysis: Courant condition Assume that the solutions of the discretized equation can be written as normal modes $$ y_{m,j} = \xi(k)^j e^{ikm\Delta x}, \quad t=j\Delta t,\ x=m\Delta x $$ The time stepping algorith is stable if $$ |\xi(k)| < 1 $$ Insert normal modes into the discretized equation $$ y_{i,j+1} = 2(1 - \beta^2)y_{i,j} - y_{i, j-1} + \beta^2 (y_{i+1,j} + y_{i-1,j}), \quad \beta := \frac{c}{\Delta x/\Delta t} $$ and simplify (use $1-\cos x = 2\sin^2\frac{x}{2}$): $$ \xi^2 - 2(1-2\beta^2 s^2)\xi + 1 = 0, \quad s=\sin(k\Delta x/2) $$ The characteristic equation has roots $$ \xi_{\pm} = 1 - 2\beta^2 s^2 \pm \sqrt{(1-2\beta^2 s^2)^2 - 1}. $$ It has one root for $$ \left|1-2\beta^2 s^2\right| = 1, $$ i.e., for $$ \beta s = 1 $$ We have two real roots for $$ \left|1-2\beta^2 s^2\right| < 1 \\ \beta s > 1 $$ but one of the roots is always $|\xi| > 1$ and hence these solutions will diverge and not be stable. For $$ \left|1-2\beta^2 s^2\right| ≥ 1 \\ \beta s ≤ 1 $$ the roots will be *complex conjugates of each other* $$ \xi_\pm = 1 - 2\beta^2s^2 \pm i\sqrt{1-(1-2\beta^2s^2)^2} $$ and the *magnitude* $$ |\xi_{\pm}|^2 = (1 - 2\beta^2s^2)^2 - (1-(1-2\beta^2s^2)^2) = 1 $$ is unity: Thus the solutions will not grow and will be *stable* for $$ \beta s ≤ 1\\ \frac{c}{\frac{\Delta x}{\Delta t}} \sin\frac{k \Delta x}{2} ≤ 1 $$ Assuming the "worst case" for the $\sin$ factor (namely, 1), the **condition for stability** is $$ c ≤ \frac{\Delta x}{\Delta t} $$ or $$ \beta ≤ 1. $$ This is also known as the **Courant condition**. When written as $$ \Delta t ≤ \frac{\Delta x}{c} $$ it means that the time step $\Delta t$ (for a given $\Delta x$) must be *smaller than the time that the wave takes to travel one grid step*. ## Simplified simulation The above example used real numbers for a cello string. Below is bare-bones where we just set $\beta$. ```python L = 10.0 Nx = 100 Nt = 200 step = 1 Dx = L/Nx beta2 = 1.0 X = np.linspace(0, L, Nx+1) # need N+1! def gaussian(x): return np.exp(-(x-5)**2) # displacements at j-1, j, j+1 y0 = np.zeros_like(X) y1 = np.zeros_like(y0) y2 = np.zeros_like(y0) # save array y_t = np.zeros((int(np.ceil(Nt/step)) + 1, Nx+1)) # boundary conditions y0[0] = y0[-1] = y1[0] = y1[-1] = 0 y2[:] = y0 # initial conditions: velocity 0, i.e. no difference between y0 and y1 y0[:] = y1[:] = gaussian(X) # save initial t_index = 0 y_t[t_index, :] = y0 if step == 1: t_index += 1 y_t[t_index, :] = y1 for jt in range(2, Nt): y2[1:-1] = 2*(1-beta2)*y1[1:-1] - y0[1:-1] + beta2*(y1[2:] + y1[:-2]) y0[:], y1[:] = y1, y2 if jt % step == 0 or jt == Nt-1: t_index += 1 y_t[t_index, :] = y2 print("Iteration {0:5d}".format(jt), end="\r") else: print("Completed {0:5d} iterations: t={1} s".format(jt, jt*Dt)) ``` Completed 199 iterations: t=199 s ```python %matplotlib inline ``` ```python ax = plt.subplot(111) ax.set_prop_cycle("color", [plt.cm.viridis_r(i) for i in np.linspace(0, 1, len(y_t))]) ax.plot(X, y_t.T); ```
#define BOOST_TEST_MODULE TUrlTemplateGenerator #define BOOST_TEST_DYN_LINK 1 #include <iostream> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/test/unit_test.hpp> #include <newbase/NFmiPoint.h> #include <macgyver/TypeName.h> #include <macgyver/Exception.h> #include "UrlTemplateGenerator.h" using namespace boost::unit_test; test_suite* init_unit_test_suite(int argc, char* argv[]) { const char* name = "UrlTemplateGenerator tester"; unit_test_log.set_threshold_level(log_messages); framework::master_test_suite().p_name.value = name; BOOST_TEST_MESSAGE(""); BOOST_TEST_MESSAGE(name); BOOST_TEST_MESSAGE(std::string(std::strlen(name), '=')); return NULL; } using namespace SmartMet::Plugin::WFS; namespace { void output_exception_info(const std::exception& err) { std::cerr << "C++ exception of type " << Fmi::get_type_name(&err) << " catched: " << err.what() << std::endl; } } #define LOG(x) \ try \ { \ x; \ } \ catch (const std::exception& err) \ { \ output_exception_info(err); \ throw; \ } std::vector<std::string> get_param(const std::string name, const std::multimap<std::string, std::string>* param_map) { std::vector<std::string> result; auto range = param_map->equal_range(name); for (auto it = range.first; it != range.second; ++it) { result.push_back(it->second); } return result; } BOOST_AUTO_TEST_CASE(test_template_url_generator_1) { BOOST_TEST_MESSAGE("+ [Test template URL generator (single constant parameter)]"); std::vector<std::string> params; params.push_back("foo=bar"); std::multimap<std::string, std::string> param_map; std::string result; boost::shared_ptr<UrlTemplateGenerator> test; BOOST_REQUIRE_NO_THROW( test.reset(new UrlTemplateGenerator("http://www.example.com/test", params))); BOOST_REQUIRE_NO_THROW(result = test->generate(boost::bind(&get_param, ::_1, &param_map))); BOOST_CHECK_EQUAL(std::string("http://www.example.com/test?foo=bar"), result); BOOST_REQUIRE_NO_THROW( test.reset(new UrlTemplateGenerator("http://www.example.com/test?", params))); BOOST_REQUIRE_NO_THROW(result = test->generate(boost::bind(&get_param, ::_1, &param_map))); BOOST_CHECK_EQUAL(std::string("http://www.example.com/test?foo=bar"), result); } BOOST_AUTO_TEST_CASE(test_template_url_generator_2) { BOOST_TEST_MESSAGE("+ [Test template URL generator (single parameter reference)]"); std::vector<std::string> params; params.push_back("${foo}"); std::multimap<std::string, std::string> param_map; std::string result; boost::shared_ptr<UrlTemplateGenerator> test; BOOST_REQUIRE_NO_THROW( test.reset(new UrlTemplateGenerator("http://www.example.com/test", params))); const auto& pm = test->get_content(); BOOST_REQUIRE_EQUAL(1, (int)pm.size()); BOOST_REQUIRE(pm.at(0).type() == typeid(UrlTemplateGenerator::ParamRef)); BOOST_REQUIRE_NO_THROW(result = test->generate(boost::bind(&get_param, ::_1, &param_map))); // std::cout << result << std::endl; BOOST_CHECK_EQUAL(std::string("http://www.example.com/test?foo="), result); param_map.insert(std::make_pair("foo", "bar")); BOOST_REQUIRE_NO_THROW(result = test->generate(boost::bind(&get_param, ::_1, &param_map))); BOOST_CHECK_EQUAL(std::string("http://www.example.com/test?foo=bar"), result); } BOOST_AUTO_TEST_CASE(test_template_url_generator_3) { BOOST_TEST_MESSAGE("+ [Test template URL generator (several parameters)]"); std::vector<std::string> params; params.push_back("${a1}"); params.push_back("${?a2}"); params.push_back("b1=f=oo"); std::multimap<std::string, std::string> param_map; param_map.insert(std::make_pair("a1", "A1")); std::string result; boost::shared_ptr<UrlTemplateGenerator> test; BOOST_REQUIRE_NO_THROW( test.reset(new UrlTemplateGenerator("http://www.example.com/test", params))); const auto& pm = test->get_content(); BOOST_REQUIRE_EQUAL(3, (int)pm.size()); BOOST_REQUIRE(pm.at(0).type() == typeid(UrlTemplateGenerator::ParamRef)); BOOST_REQUIRE(pm.at(1).type() == typeid(UrlTemplateGenerator::ParamRef)); BOOST_REQUIRE(pm.at(2).type() == typeid(UrlTemplateGenerator::StringParam)); BOOST_REQUIRE_NO_THROW(result = test->generate(boost::bind(&get_param, ::_1, &param_map))); // std::cout << result << std::endl; BOOST_CHECK_EQUAL(std::string("http://www.example.com/test?a1=A1&b1=f%3Doo"), result); param_map.insert(std::make_pair("a2", "A2")); BOOST_REQUIRE_NO_THROW(result = test->generate(boost::bind(&get_param, ::_1, &param_map))); BOOST_CHECK_EQUAL(std::string("http://www.example.com/test?a1=A1&a2=A2&b1=f%3Doo"), result); } BOOST_AUTO_TEST_CASE(test_template_url_generator_4) { BOOST_TEST_MESSAGE("+ [Test template URL generator (repeated parameters)]"); std::vector<std::string> params; params.push_back("${a1}"); params.push_back("${*a2}"); params.push_back("b1=f=oo"); std::multimap<std::string, std::string> param_map; param_map.insert(std::make_pair("a1", "A1")); param_map.insert(std::make_pair("a2", "A2A")); param_map.insert(std::make_pair("a2", "A2B")); std::string result; boost::shared_ptr<UrlTemplateGenerator> test; BOOST_REQUIRE_NO_THROW( test.reset(new UrlTemplateGenerator("http://www.example.com/test", params))); const auto& pm = test->get_content(); BOOST_REQUIRE_EQUAL(3, (int)pm.size()); BOOST_REQUIRE(pm.at(0).type() == typeid(UrlTemplateGenerator::ParamRef)); BOOST_REQUIRE(pm.at(1).type() == typeid(UrlTemplateGenerator::ParamRef)); BOOST_REQUIRE(pm.at(2).type() == typeid(UrlTemplateGenerator::StringParam)); BOOST_REQUIRE_NO_THROW(result = test->generate(boost::bind(&get_param, ::_1, &param_map))); BOOST_CHECK_EQUAL(std::string("http://www.example.com/test?a1=A1&a2=A2A&a2=A2B&b1=f%3Doo"), result); } BOOST_AUTO_TEST_CASE(test_template_url_generator_5) { BOOST_TEST_MESSAGE("+ [Test template URL generator (parameters already in original URL)]"); std::vector<std::string> params; params.push_back("foo=bar"); std::multimap<std::string, std::string> param_map; std::string result; boost::shared_ptr<UrlTemplateGenerator> test; BOOST_REQUIRE_NO_THROW( test.reset(new UrlTemplateGenerator("http://www.example.com/test?a1=A1", params))); BOOST_REQUIRE_NO_THROW(result = test->generate(boost::bind(&get_param, ::_1, &param_map))); BOOST_CHECK_EQUAL(std::string("http://www.example.com/test?a1=A1&foo=bar"), result); BOOST_REQUIRE_NO_THROW( test.reset(new UrlTemplateGenerator("http://www.example.com/test?a1=A1&", params))); BOOST_REQUIRE_NO_THROW(result = test->generate(boost::bind(&get_param, ::_1, &param_map))); BOOST_CHECK_EQUAL(std::string("http://www.example.com/test?a1=A1&foo=bar"), result); } BOOST_AUTO_TEST_CASE(test_template_url_generator_6) { BOOST_TEST_MESSAGE("+ [Test template URL generator (evaluate text value)]"); std::vector<std::string> params; params.push_back("${a1}"); params.push_back("${*a2}"); params.push_back("b1=foo-${a1}-bar"); std::multimap<std::string, std::string> param_map; param_map.insert(std::make_pair("a1", "A1")); param_map.insert(std::make_pair("a2", "A2A")); param_map.insert(std::make_pair("a2", "A2B")); std::string result; boost::shared_ptr<UrlTemplateGenerator> test; BOOST_REQUIRE_NO_THROW( test.reset(new UrlTemplateGenerator("http://www.example.com/test", params))); const auto& pm = test->get_content(); BOOST_REQUIRE_EQUAL(3, (int)pm.size()); BOOST_REQUIRE(pm.at(0).type() == typeid(UrlTemplateGenerator::ParamRef)); BOOST_REQUIRE(pm.at(1).type() == typeid(UrlTemplateGenerator::ParamRef)); BOOST_REQUIRE(pm.at(2).type() == typeid(UrlTemplateGenerator::StringParam)); BOOST_REQUIRE_NO_THROW(LOG(result = test->generate(boost::bind(&get_param, ::_1, &param_map)))); BOOST_CHECK_EQUAL(std::string("http://www.example.com/test?a1=A1&a2=A2A&a2=A2B&b1=foo-A1-bar"), result); } BOOST_AUTO_TEST_CASE(test_template_url_generator_7) { BOOST_TEST_MESSAGE("+ [Test substituting values in the original URL]"); std::vector<std::string> params; std::multimap<std::string, std::string> param_map; param_map.insert(std::make_pair("a1", "A1")); param_map.insert(std::make_pair("a2", "A2A")); param_map.insert(std::make_pair("a3", "A3A")); param_map.insert(std::make_pair("a3", "A3B")); std::string result; boost::shared_ptr<UrlTemplateGenerator> test; BOOST_REQUIRE_NO_THROW( test.reset(new UrlTemplateGenerator("http://www.example.com/test/${a1}/${a2}/foo", params))); const auto& pm = test->get_content(); BOOST_REQUIRE_EQUAL(0, (int)pm.size()); BOOST_REQUIRE_NO_THROW(LOG(result = test->generate(boost::bind(&get_param, ::_1, &param_map)))); BOOST_CHECK_EQUAL(std::string("http://www.example.com/test/A1/A2A/foo"), result); } BOOST_AUTO_TEST_CASE(test_template_url_generator_8) { BOOST_TEST_MESSAGE("+ [Test substituting values in the original URL (bad)]"); std::vector<std::string> params; std::multimap<std::string, std::string> param_map; param_map.insert(std::make_pair("a1", "A1")); param_map.insert(std::make_pair("a2", "A2A")); param_map.insert(std::make_pair("a3", "A3A")); param_map.insert(std::make_pair("a3", "A3B")); std::string result; boost::shared_ptr<UrlTemplateGenerator> test; BOOST_REQUIRE_NO_THROW( test.reset(new UrlTemplateGenerator("http://www.example.com/test/${a1}/${a3}/foo", params))); const auto& pm = test->get_content(); BOOST_REQUIRE_EQUAL(0, (int)pm.size()); BOOST_REQUIRE_THROW(result = test->generate(boost::bind(&get_param, ::_1, &param_map)), Fmi::Exception); }
[STATEMENT] lemma iT_Mult_0: "I \<noteq> {} \<Longrightarrow> I \<otimes> 0 = [\<dots>0]" [PROOF STATE] proof (prove) goal (1 subgoal): 1. I \<noteq> {} \<Longrightarrow> I \<otimes> 0 = [\<dots>0] [PROOF STEP] by (fastforce simp add: iTILL_def iT_Mult_def)
(*<*) (* Author: Kyndylan Nienhuis *) theory StoreData imports "UnpredictableBehaviour" "ExceptionFlag" "ExecutionStep" begin (*>*) section \<open>Semantics of @{const StoreDataAction}}\<close> named_theorems SemanticsStoreDataI method SemanticsStoreData uses intro = HoareTriple intro: intro SemanticsStoreDataI[THEN HoareTriple_post_weakening] declare nonExceptionCase_exceptions [SemanticsStoreDataI] definition AddressIsDataWritable :: "Capability \<Rightarrow> (VirtualAddress \<times> AccessType \<Rightarrow> PhysicalAddress option) \<Rightarrow> PhysicalAddress \<Rightarrow> PhysicalAddress \<Rightarrow> bool" where "AddressIsDataWritable authCap addrTrans a l \<equiv> Permit_Store (getPerms authCap) \<and> getTag authCap \<and> \<not> getSealed authCap \<and> l \<noteq> 0 \<and> (\<forall>a'\<in>Region a l. \<exists>vAddr\<in>RegionOfCap authCap. addrTrans (vAddr, STORE) = Some a')" definition SemanticsStoreDataPost where "SemanticsStoreDataPost authCap addrTrans a l cap \<equiv> bind (read_state (getMemCap (GetCapAddress a))) (\<lambda>cap'. return (getTag cap' \<longrightarrow> cap' = cap)) \<and>\<^sub>b return (AddressIsDataWritable authCap addrTrans a l)" lemma Commute_SemanticsStoreDataPost[Commute_compositeI]: assumes "Commute (read_state (getMemCap (GetCapAddress a))) m" shows "Commute (SemanticsStoreDataPost authCap addrTrans a l cap) m" unfolding SemanticsStoreDataPost_def by (Commute intro: assms) lemma SemanticsStoreData_WriteData_aux: fixes a :: PhysicalAddress shows "HoareTriple (read_state (getMemCap (GetCapAddress a)) =\<^sub>b return cap) (WriteData v) (\<lambda>_. bind (read_state (getMemCap (GetCapAddress a))) (\<lambda>cap'. return (getTag cap' \<longrightarrow> cap' = cap)))" unfolding WriteData_alt_def by HoareTriple auto lemma UndefinedCase_WriteData: shows "IsInvariant (read_state isUnpredictable) (WriteData v)" by Invariant lemma SemanticsStoreData_AdjustEndian_aux: shows "IsInvariant (read_state (getMemCap (GetCapAddress a)) =\<^sub>b return cap) (AdjustEndian v)" by HoareTriple lemma SemanticsStoreData_StoreMemoryCap_unpred: shows "HoareTriple ((return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b return ((case v of (memType, accessLength, _, needAlign, vAddr, _) \<Rightarrow> (needAlign \<and> memType = accessLength \<and> \<not> unat vAddr mod 8 + unat accessLength < 8) \<or> (addrTrans (vAddr, STORE) = None)))) (StoreMemoryCap v) (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable)" proof - note AdjustEndian_intro = HoareTriple_weakest_pre_disj[OF ExceptionSignalled_AdjustEndian UndefinedCase_AdjustEndian] note intros = AdjustEndian_intro HoareTriple_DefinedAddressTranslation[where p="\<lambda>x. return False"] show ?thesis unfolding StoreMemoryCap_alt_def by (HoareTriple intro: intros[THEN HoareTriple_post_weakening]) (auto simp: getTranslateAddrFunc_def dest!: isAligned_max_length) qed lemma SemanticsStoreData_StoreMemoryCap_mem: fixes a' :: PhysicalAddress shows "HoareTriple (read_state (getMemCap (GetCapAddress a)) =\<^sub>b return cap) (StoreMemoryCap v) (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable \<or>\<^sub>b bind (read_state (getMemCap (GetCapAddress a))) (\<lambda>cap'. return (getTag cap' \<longrightarrow> cap' = cap)))" proof - note AdjustEndian_intro = HoareTriple_weakest_pre_disj[OF SemanticsStoreData_AdjustEndian_aux[where a=a and cap=cap] HoareTriple_weakest_pre_disj[OF UndefinedCase_AdjustEndian ExceptionSignalled_AdjustEndian]] note WriteData_intro = HoareTriple_weakest_pre_disj[OF SemanticsStoreData_WriteData_aux[where a=a and cap=cap] HoareTriple_weakest_pre_disj[OF UndefinedCase_WriteData ExceptionSignalled_WriteData]] note intros = AdjustEndian_intro WriteData_intro HoareTriple_DefinedAddressTranslation [where p="\<lambda>x. read_state (getMemCap (GetCapAddress a)) =\<^sub>b return cap"] show ?thesis unfolding StoreMemoryCap_alt_def by (HoareTriple intro: intros[THEN HoareTriple_post_weakening]) qed lemmas SemanticsStoreData_StoreMemoryCap = HoareTriple_weakest_pre_disj[OF SemanticsStoreData_StoreMemoryCap_unpred[where addrTrans=addrTrans] HoareTriple_weakest_pre_conj[OF SemanticsStoreData_StoreMemoryCap_mem[where cap=cap and a=a] IsInvariant_constant[where x="AddressIsDataWritable authCap addrTrans a l"]]] for cap authCap addrTrans a l lemma SemanticsStoreData_StoreMemory_aux: shows "HoareTriple ((return authCap =\<^sub>b read_state getDDC) \<and>\<^sub>b (return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b (return cap =\<^sub>b read_state (getMemCap (GetCapAddress a))) \<and>\<^sub>b return ((case v of (memType, accessLength, needAlign, _, vAddr, _) \<Rightarrow> (a = the (addrTrans (vAddr, STORE))) \<and> (l = ucast accessLength + 1) \<and> ((needAlign \<and> memType = accessLength) \<or> unat vAddr mod 8 + unat accessLength < 8)))) (StoreMemory v) (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable \<or>\<^sub>b SemanticsStoreDataPost authCap addrTrans a l cap)" proof - note [SemanticsStoreDataI] = SemanticsStoreData_StoreMemoryCap [where addrTrans=addrTrans and cap=cap and a=a and l=l and authCap=authCap] note TranslateNearbyAddress = TranslateNearbyAddress_LegacyInstructions[where pAddr=a] have [simp]: "ucast (x::3 word) \<noteq> (max_word::40 word)" (is "?l \<noteq> ?r") for x using test_bit_size[where w=x and n=4] by (auto simp: nth_ucast word_size dest!: test_bit_cong[where x=4]) show ?thesis unfolding StoreMemory_alt_def unfolding SemanticsStoreDataPost_def by SemanticsStoreData (auto simp: not_le not_less max_word_wrap_eq getTranslateAddrFunc_def AddressIsDataWritable_def elim!: TranslateNearbyAddress) qed lemmas SemanticsStoreData_StoreMemory = HoareTriple_weakest_pre_conj[OF SemanticsStoreData_StoreMemory_aux IsInvariant_constant[where x=authAccessible]] for authAccessible lemma SemanticsStoreData_StoreCap: shows "HoareTriple ((return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b return ((case v of (vAddr, cap, cond) \<Rightarrow> addrTrans (vAddr, STORE) = None))) (StoreCap v) (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable)" unfolding StoreCap_alt_def by (HoareTriple intro: HoareTriple_DefinedAddressTranslation [where p="\<lambda>x. return False", THEN HoareTriple_post_weakening]) (auto simp: getTranslateAddrFunc_def) lemma SemanticsStoreAndRestrict_dfn'SB [SemanticsStoreDataI]: shows "HoareTriple ((return authCap =\<^sub>b read_state (getCapReg auth)) \<and>\<^sub>b (return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b (return cap =\<^sub>b read_state (getMemCap (GetCapAddress a))) \<and>\<^sub>b (return authAccessible =\<^sub>b read_state (getRegisterIsAccessible auth)) \<and>\<^sub>b bind (SBActions v) (\<lambda>prov. return (StoreDataAction auth a l \<in> prov))) (dfn'SB v) (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable \<or>\<^sub>b SemanticsStoreDataPost authCap addrTrans a l cap \<and>\<^sub>b return authAccessible)" proof - note [SemanticsStoreDataI] = SemanticsStoreData_StoreMemory[where authAccessible=authAccessible] show ?thesis unfolding dfn'SB_alt_def SBActions_def unfolding LegacyStoreActions_def LegacyStorePhysicalAddress_def LegacyStoreVirtualAddress_def unfolding BYTE_def HALFWORD_def WORD_def DOUBLEWORD_def unfolding CheckBranch_alt_def getVirtualAddress_alt_def by SemanticsStoreData (auto simp: getTranslateAddrFunc_def split: option.splits) qed lemma SemanticsStoreAndRestrict_dfn'SH [SemanticsStoreDataI]: shows "HoareTriple ((return authCap =\<^sub>b read_state (getCapReg auth)) \<and>\<^sub>b (return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b (return cap =\<^sub>b read_state (getMemCap (GetCapAddress a))) \<and>\<^sub>b (return authAccessible =\<^sub>b read_state (getRegisterIsAccessible auth)) \<and>\<^sub>b bind (SHActions v) (\<lambda>prov. return (StoreDataAction auth a l \<in> prov))) (dfn'SH v) (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable \<or>\<^sub>b SemanticsStoreDataPost authCap addrTrans a l cap \<and>\<^sub>b return authAccessible)" proof - note [SemanticsStoreDataI] = SemanticsStoreData_StoreMemory[where authAccessible=authAccessible] show ?thesis unfolding dfn'SH_alt_def SHActions_def unfolding LegacyStoreActions_def LegacyStorePhysicalAddress_def LegacyStoreVirtualAddress_def unfolding BYTE_def HALFWORD_def WORD_def DOUBLEWORD_def unfolding CheckBranch_alt_def getVirtualAddress_alt_def by SemanticsStoreData (auto simp: getTranslateAddrFunc_def split: option.splits) qed lemma SemanticsStoreAndRestrict_dfn'SW [SemanticsStoreDataI]: shows "HoareTriple ((return authCap =\<^sub>b read_state (getCapReg auth)) \<and>\<^sub>b (return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b (return cap =\<^sub>b read_state (getMemCap (GetCapAddress a))) \<and>\<^sub>b (return authAccessible =\<^sub>b read_state (getRegisterIsAccessible auth)) \<and>\<^sub>b bind (SWActions v) (\<lambda>prov. return (StoreDataAction auth a l \<in> prov))) (dfn'SW v) (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable \<or>\<^sub>b SemanticsStoreDataPost authCap addrTrans a l cap \<and>\<^sub>b return authAccessible)" proof - note [SemanticsStoreDataI] = SemanticsStoreData_StoreMemory[where authAccessible=authAccessible] show ?thesis unfolding dfn'SW_alt_def SWActions_def storeWord_alt_def unfolding LegacyStoreActions_def LegacyStorePhysicalAddress_def LegacyStoreVirtualAddress_def unfolding BYTE_def HALFWORD_def WORD_def DOUBLEWORD_def unfolding CheckBranch_alt_def getVirtualAddress_alt_def by SemanticsStoreData (auto simp: getTranslateAddrFunc_def split: option.splits) qed lemma SemanticsStoreAndRestrict_dfn'SD [SemanticsStoreDataI]: shows "HoareTriple ((return authCap =\<^sub>b read_state (getCapReg auth)) \<and>\<^sub>b (return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b (return cap =\<^sub>b read_state (getMemCap (GetCapAddress a))) \<and>\<^sub>b (return authAccessible =\<^sub>b read_state (getRegisterIsAccessible auth)) \<and>\<^sub>b bind (SDActions v) (\<lambda>prov. return (StoreDataAction auth a l \<in> prov))) (dfn'SD v) (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable \<or>\<^sub>b SemanticsStoreDataPost authCap addrTrans a l cap \<and>\<^sub>b return authAccessible)" proof - note [SemanticsStoreDataI] = SemanticsStoreData_StoreMemory[where authAccessible=authAccessible] show ?thesis unfolding dfn'SD_alt_def SDActions_def storeDoubleword_alt_def unfolding LegacyStoreActions_def LegacyStorePhysicalAddress_def LegacyStoreVirtualAddress_def unfolding BYTE_def HALFWORD_def WORD_def DOUBLEWORD_def unfolding CheckBranch_alt_def getVirtualAddress_alt_def by SemanticsStoreData (auto simp: getTranslateAddrFunc_def split: option.splits) qed lemma SemanticsStoreAndRestrict_dfn'SC [SemanticsStoreDataI]: shows "HoareTriple ((return authCap =\<^sub>b read_state (getCapReg auth)) \<and>\<^sub>b (return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b (return cap =\<^sub>b read_state (getMemCap (GetCapAddress a))) \<and>\<^sub>b (return authAccessible =\<^sub>b read_state (getRegisterIsAccessible auth)) \<and>\<^sub>b bind (SCActions v) (\<lambda>prov. return (StoreDataAction auth a l \<in> prov))) (dfn'SC v) (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable \<or>\<^sub>b SemanticsStoreDataPost authCap addrTrans a l cap \<and>\<^sub>b return authAccessible)" proof - note [SemanticsStoreDataI] = SemanticsStoreData_StoreMemory[where authAccessible=authAccessible] show ?thesis unfolding dfn'SC_alt_def SCActions_def storeWord_alt_def unfolding LegacyStoreActions_def LegacyStorePhysicalAddress_def LegacyStoreVirtualAddress_def unfolding BYTE_def HALFWORD_def WORD_def DOUBLEWORD_def unfolding CheckBranch_alt_def getVirtualAddress_alt_def by SemanticsStoreData (auto simp: getTranslateAddrFunc_def split: option.splits) qed lemma SemanticsStoreAndRestrict_dfn'SCD [SemanticsStoreDataI]: shows "HoareTriple ((return authCap =\<^sub>b read_state (getCapReg auth)) \<and>\<^sub>b (return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b (return cap =\<^sub>b read_state (getMemCap (GetCapAddress a))) \<and>\<^sub>b (return authAccessible =\<^sub>b read_state (getRegisterIsAccessible auth)) \<and>\<^sub>b bind (SCDActions v) (\<lambda>prov. return (StoreDataAction auth a l \<in> prov))) (dfn'SCD v) (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable \<or>\<^sub>b SemanticsStoreDataPost authCap addrTrans a l cap \<and>\<^sub>b return authAccessible)" proof - note [SemanticsStoreDataI] = SemanticsStoreData_StoreMemory[where authAccessible=authAccessible] show ?thesis unfolding dfn'SCD_alt_def SCDActions_def storeDoubleword_alt_def unfolding LegacyStoreActions_def LegacyStorePhysicalAddress_def LegacyStoreVirtualAddress_def unfolding BYTE_def HALFWORD_def WORD_def DOUBLEWORD_def unfolding CheckBranch_alt_def getVirtualAddress_alt_def by SemanticsStoreData (auto simp: getTranslateAddrFunc_def split: option.splits) qed lemma SemanticsStoreAndRestrict_dfn'SWL [SemanticsStoreDataI]: shows "HoareTriple ((return authCap =\<^sub>b read_state (getCapReg auth)) \<and>\<^sub>b (return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b (return cap =\<^sub>b read_state (getMemCap (GetCapAddress a))) \<and>\<^sub>b (read_state getCP0ConfigBE) \<and>\<^sub>b (\<not>\<^sub>b read_state getCP0StatusRE) \<and>\<^sub>b (return authAccessible =\<^sub>b read_state (getRegisterIsAccessible auth)) \<and>\<^sub>b bind (SWLActions v) (\<lambda>prov. return (StoreDataAction auth a l \<in> prov))) (dfn'SWL v) (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable \<or>\<^sub>b SemanticsStoreDataPost authCap addrTrans a l cap \<and>\<^sub>b return authAccessible)" proof - note [SemanticsStoreDataI] = SemanticsStoreData_StoreMemory[where authAccessible=authAccessible] show ?thesis unfolding dfn'SWL_alt_def SWLActions_def unfolding LegacyStoreActions_def LegacyStorePhysicalAddress_def LegacyStoreVirtualAddress_def unfolding BYTE_def HALFWORD_def WORD_def DOUBLEWORD_def unfolding CheckBranch_alt_def getVirtualAddress_alt_def unfolding BigEndianMem_alt_def BigEndianCPU_alt_def ReverseEndian_alt_def by SemanticsStoreData (auto simp: getTranslateAddrFunc_def ucast_and ucast_not unat_not unat_and_mask unat_max_word word_bool_alg.conj_disj_distrib2 split: option.splits) qed lemma SemanticsStoreAndRestrict_dfn'SWR [SemanticsStoreDataI]: shows "HoareTriple ((return authCap =\<^sub>b read_state (getCapReg auth)) \<and>\<^sub>b (return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b (return cap =\<^sub>b read_state (getMemCap (GetCapAddress a))) \<and>\<^sub>b (read_state getCP0ConfigBE) \<and>\<^sub>b (\<not>\<^sub>b read_state getCP0StatusRE) \<and>\<^sub>b (return authAccessible =\<^sub>b read_state (getRegisterIsAccessible auth)) \<and>\<^sub>b bind (SWRActions v) (\<lambda>prov. return (StoreDataAction auth a l \<in> prov))) (dfn'SWR v) (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable \<or>\<^sub>b SemanticsStoreDataPost authCap addrTrans a l cap \<and>\<^sub>b return authAccessible)" proof - note [SemanticsStoreDataI] = SemanticsStoreData_StoreMemory[where authAccessible=authAccessible] have [simp]: "x AND - 4 = x AND NOT mask 2" for x :: "'a::len word" unfolding word_not_alt max_word_minus mask_def by simp have [simp]: "3 - (NOT x AND mask 2) = x AND mask 2" for x :: "'a::len word" using mask_minus_word_and_mask[where x="NOT x" and n=2] unfolding mask_def by simp have "(4::nat) dvd 8" by arith note [simp] = mod_mod_cancel[OF this] have "4 * x mod 8 \<le> 4" for x :: nat by arith from add_le_less_mono[where d=4, OF this] have [simp]: "4 * x mod 8 + y mod 4 < 8" for x y :: nat by simp show ?thesis unfolding dfn'SWR_alt_def SWRActions_def unfolding LegacyStoreActions_def LegacyStorePhysicalAddress_def LegacyStoreVirtualAddress_def unfolding BYTE_def HALFWORD_def WORD_def DOUBLEWORD_def unfolding CheckBranch_alt_def getVirtualAddress_alt_def unfolding BigEndianMem_alt_def BigEndianCPU_alt_def ReverseEndian_alt_def by SemanticsStoreData (auto simp: getTranslateAddrFunc_def ucast_and ucast_not unat_not unat_and_mask unat_and_not_mask unat_max_word word_bool_alg.conj_disj_distrib2 split: option.splits) qed lemma SemanticsStoreAndRestrict_dfn'SDL [SemanticsStoreDataI]: shows "HoareTriple ((return authCap =\<^sub>b read_state (getCapReg auth)) \<and>\<^sub>b (return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b (return cap =\<^sub>b read_state (getMemCap (GetCapAddress a))) \<and>\<^sub>b (read_state getCP0ConfigBE) \<and>\<^sub>b (\<not>\<^sub>b read_state getCP0StatusRE) \<and>\<^sub>b (return authAccessible =\<^sub>b read_state (getRegisterIsAccessible auth)) \<and>\<^sub>b bind (SDLActions v) (\<lambda>prov. return (StoreDataAction auth a l \<in> prov))) (dfn'SDL v) (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable \<or>\<^sub>b SemanticsStoreDataPost authCap addrTrans a l cap \<and>\<^sub>b return authAccessible)" proof - note [SemanticsStoreDataI] = SemanticsStoreData_StoreMemory[where authAccessible=authAccessible] have unat_mod_8_less: "unat x mod 8 < n" if "NOT ucast x = y" "unat (NOT y) < n" for x :: "64 word" and y :: "3 word" and n using arg_cong[where f=unat, OF that(1)] that(2) unfolding unat_not unat_ucast unat_and_mask unat_max_word by simp have unat_mod_8_zero: "unat x mod 8 = 0" if "NOT ucast x = y" "unat (NOT y) = 0" for x :: "64 word" and y :: "3 word" using unat_mod_8_less[where n=1] that by simp have not_ucast_mask_3: "(NOT ucast x::'a::len word) AND mask 3 = ucast y" if "NOT ucast x = y" for x :: "64 word" and y :: "3 word" using arg_cong[where f="ucast::3 word \<Rightarrow> 'a word", OF that] by (simp add: ucast_not word_bool_alg.conj_disj_distrib2) have word_3_exhaustive: "x = 7" if "x \<noteq> 6" "x \<noteq> 5" "x \<noteq> 4" "x \<noteq> 3" "x \<noteq> 2" "x \<noteq> 1" "x \<noteq> 0" for x :: "3 word" using exhaustive_3_word that by auto show ?thesis unfolding dfn'SDL_alt_def SDLActions_def unfolding LegacyStoreActions_def LegacyStorePhysicalAddress_def LegacyStoreVirtualAddress_def unfolding BYTE_def HALFWORD_def WORD_def DOUBLEWORD_def unfolding CheckBranch_alt_def getVirtualAddress_alt_def unfolding BigEndianMem_alt_def BigEndianCPU_alt_def ReverseEndian_alt_def by SemanticsStoreData (auto simp: getTranslateAddrFunc_def unat_and_mask not_ucast_mask_3 numeral_2_eq_2 word_bool_alg.conj_disj_distrib2 dest!: word_3_exhaustive elim!: unat_mod_8_less unat_mod_8_zero split: option.splits) qed lemma SemanticsStoreAndRestrict_dfn'SDR [SemanticsStoreDataI]: shows "HoareTriple ((return authCap =\<^sub>b read_state (getCapReg auth)) \<and>\<^sub>b (return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b (return cap =\<^sub>b read_state (getMemCap (GetCapAddress a))) \<and>\<^sub>b (read_state getCP0ConfigBE) \<and>\<^sub>b (\<not>\<^sub>b read_state getCP0StatusRE) \<and>\<^sub>b (return authAccessible =\<^sub>b read_state (getRegisterIsAccessible auth)) \<and>\<^sub>b bind (SDRActions v) (\<lambda>prov. return (StoreDataAction auth a l \<in> prov))) (dfn'SDR v) (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable \<or>\<^sub>b SemanticsStoreDataPost authCap addrTrans a l cap \<and>\<^sub>b return authAccessible)" proof - note [SemanticsStoreDataI] = SemanticsStoreData_StoreMemory[where authAccessible=authAccessible] have [simp]: "x AND - 8 = x AND NOT mask 3" for x :: "'a::len word" unfolding word_not_alt max_word_minus mask_def by simp have [simp]: "7 - (NOT x) = x" for x :: "3 word" unfolding word_not_alt max_word_def by simp have ucast_mask_3: "(ucast x::40 word) AND mask 3 = ucast (NOT y)" if "NOT ucast x = y" for x :: "64 word" and y :: "3 word" using arg_cong[where f="\<lambda>x. ucast (NOT x)::40 word", OF that] by (simp add: word_bool_alg.conj_disj_distrib2 ucast_not) have [simp]: "(-1::3 word) = 7" "(-2::3 word) = 6" "(-3::3 word) = 5" "(-4::3 word) = 4" "(-5::3 word) = 3" "(-6::3 word) = 2" "(-7::3 word) = 1" "(-8::3 word) = 0" by simp_all have [intro!]: "mask 3 = 7" unfolding mask_def by auto show ?thesis unfolding dfn'SDR_alt_def SDRActions_def unfolding LegacyStoreActions_def LegacyStorePhysicalAddress_def LegacyStoreVirtualAddress_def unfolding BYTE_def HALFWORD_def WORD_def DOUBLEWORD_def unfolding CheckBranch_alt_def getVirtualAddress_alt_def unfolding BigEndianMem_alt_def BigEndianCPU_alt_def ReverseEndian_alt_def by SemanticsStoreData (auto simp: getTranslateAddrFunc_def unat_and_not_mask unat_and_mask mask_plus_one word_bool_alg.conj_disj_distrib2 dest!: ucast_mask_3 split: option.splits) qed lemma SemanticsStoreAndRestrict_dfn'CStore [SemanticsStoreDataI]: shows "HoareTriple ((return authCap =\<^sub>b read_state (getCapReg auth)) \<and>\<^sub>b (return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b (return cap =\<^sub>b read_state (getMemCap (GetCapAddress a))) \<and>\<^sub>b (return authAccessible =\<^sub>b read_state (getRegisterIsAccessible auth)) \<and>\<^sub>b bind (CStoreActions v) (\<lambda>prov. return (StoreDataAction auth a l \<in> prov))) (dfn'CStore v) (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable \<or>\<^sub>b SemanticsStoreDataPost authCap addrTrans a l cap \<and>\<^sub>b return authAccessible)" proof - note [SemanticsStoreDataI] = HoareTriple_weakest_pre_disj[OF SemanticsStoreData_StoreMemoryCap_unpred[where addrTrans=addrTrans] HoareTriple_weakest_pre_conj[OF SemanticsStoreData_StoreMemoryCap_mem[where cap=cap and a=a] IsInvariant_constant[where x="AddressIsDataWritable authCap addrTrans a l \<and> authAccessible"]]] have "n mod 32 \<le> n mod 8 + 24" for n :: nat proof - have "n mod 32 = (n mod 32 mod 8) + 8 * (n mod 32 div 8)" by simp also have "... \<le> (n mod 8) + 24" using mod_mod_cancel[where a=n and b=32 and c=8] by auto finally show ?thesis . qed hence *: "n mod 32 \<le> m" if "n mod 8 + 24 \<le> m" for m n :: nat by (rule order.trans[OF _ that]) show ?thesis unfolding dfn'CStore_alt_def CStoreActions_def store_alt_def unfolding CStorePhysicalAddress_def CStoreVirtualAddress_def unfolding SemanticsStoreDataPost_def by SemanticsStoreData (cases rule: exhaustive_2_word[where x="case v of (_, _, _, _, t) \<Rightarrow> t"], auto simp: not_le not_less unat_mask unat_max_word getTranslateAddrFunc_def AddressIsDataWritable_def intro!: * elim!: TranslateNearbyAddress[where accessLength=1] TranslateNearbyAddress[where accessLength=2] TranslateNearbyAddress[where accessLength=4] TranslateNearbyAddress[where accessLength=8]) qed lemma SemanticsStoreAndRestrict_dfn'CSCx [SemanticsStoreDataI]: shows "HoareTriple ((return authCap =\<^sub>b read_state (getCapReg auth)) \<and>\<^sub>b (return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b (return cap =\<^sub>b read_state (getMemCap (GetCapAddress a))) \<and>\<^sub>b (return authAccessible =\<^sub>b read_state (getRegisterIsAccessible auth)) \<and>\<^sub>b bind (CSCxActions v) (\<lambda>prov. return (StoreDataAction auth a l \<in> prov))) (dfn'CSCx v) (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable \<or>\<^sub>b SemanticsStoreDataPost authCap addrTrans a l cap \<and>\<^sub>b return authAccessible)" proof - note [SemanticsStoreDataI] = HoareTriple_weakest_pre_disj[OF SemanticsStoreData_StoreMemoryCap_unpred[where addrTrans=addrTrans] HoareTriple_weakest_pre_conj[OF SemanticsStoreData_StoreMemoryCap_mem[where cap=cap and a=a] IsInvariant_constant[where x="AddressIsDataWritable authCap addrTrans a l \<and> authAccessible"]]] have "n mod 32 \<le> n mod 8 + 24" for n :: nat proof - have "n mod 32 = (n mod 32 mod 8) + 8 * (n mod 32 div 8)" by simp also have "... \<le> (n mod 8) + 24" using mod_mod_cancel[where a=n and b=32 and c=8] by auto finally show ?thesis . qed hence *: "n mod 32 \<le> m" if "n mod 8 + 24 \<le> m" for m n :: nat by (rule order.trans[OF _ that]) show ?thesis unfolding dfn'CSCx_alt_def CSCxActions_def store_alt_def unfolding CSCxPhysicalAddress_def CSCxVirtualAddress_def unfolding SemanticsStoreDataPost_def by SemanticsStoreData (cases rule: exhaustive_2_word[where x="case v of (_, _, _, t) \<Rightarrow> t"], auto simp: not_le not_less unat_mask unat_max_word getTranslateAddrFunc_def AddressIsDataWritable_def intro!: * elim!: TranslateNearbyAddress[where accessLength=1] TranslateNearbyAddress[where accessLength=2] TranslateNearbyAddress[where accessLength=4] TranslateNearbyAddress[where accessLength=8]) qed lemma SemanticsStoreData_Run_aux: shows "HoareTriple ((return authCap =\<^sub>b read_state (getCapReg auth)) \<and>\<^sub>b (return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b (return cap =\<^sub>b read_state (getMemCap (GetCapAddress a))) \<and>\<^sub>b (read_state getCP0ConfigBE) \<and>\<^sub>b (\<not>\<^sub>b read_state getCP0StatusRE) \<and>\<^sub>b (return authAccessible =\<^sub>b read_state (getRegisterIsAccessible auth)) \<and>\<^sub>b bind (RunActions v) (\<lambda>prov. return (StoreDataAction auth a l \<in> prov))) (Run v) (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable \<or>\<^sub>b SemanticsStoreDataPost authCap addrTrans a l cap \<and>\<^sub>b return authAccessible)" unfolding Run_alt_def RunActions_def by (HoareTriple_cases; rule HoareTriple_pre_strengthening, rule SemanticsStoreDataI HoareTriple_weakest_pre_any, solves \<open>auto simp: ValueAndStatePart_simp\<close>) lemmas SemanticsStoreData_Run = HoareTriple_weakest_pre_disj[OF SemanticsStoreData_Run_aux UndefinedCase_Run] lemma SemanticsStoreData_Fetch: fixes auth a a' l authCap cap addrTrans authAccessible defines "p \<equiv> \<lambda>w. (return authCap =\<^sub>b read_state (getCapReg auth)) \<and>\<^sub>b (return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b (return cap =\<^sub>b read_state (getMemCap (GetCapAddress a))) \<and>\<^sub>b (read_state getCP0ConfigBE) \<and>\<^sub>b (\<not>\<^sub>b read_state getCP0StatusRE) \<and>\<^sub>b (return authAccessible =\<^sub>b read_state (getRegisterIsAccessible auth)) \<and>\<^sub>b bind (RunActions (Decode w)) (\<lambda>ac. return (StoreDataAction auth a l \<in> ac))" shows "HoareTriple (bind NextInstruction (case_option (return True) p)) Fetch (\<lambda>b. case b of None \<Rightarrow> read_state getExceptionSignalled | Some y \<Rightarrow> read_state isUnpredictable \<or>\<^sub>b p y)" unfolding p_def by (intro HoareTriple_Fetch) Commute+ lemma SemanticsStoreData_NextWithGhostState: shows "HoareTriple ((return authCap =\<^sub>b read_state (getCapReg auth)) \<and>\<^sub>b (return addrTrans =\<^sub>b read_state getTranslateAddrFunc) \<and>\<^sub>b (return cap =\<^sub>b read_state (getMemCap (GetCapAddress a))) \<and>\<^sub>b (read_state getCP0ConfigBE) \<and>\<^sub>b (\<not>\<^sub>b read_state getCP0StatusRE) \<and>\<^sub>b (return authAccessible =\<^sub>b read_state (getRegisterIsAccessible auth)) \<and>\<^sub>b bind DomainActions (\<lambda>ac. return (StoreDataAction auth a l \<in> ac))) NextWithGhostState (\<lambda>_. read_state getExceptionSignalled \<or>\<^sub>b read_state isUnpredictable \<or>\<^sub>b SemanticsStoreDataPost authCap addrTrans a l cap \<and>\<^sub>b return authAccessible)" proof - note [SemanticsStoreDataI] = SemanticsStoreData_Run[where auth=auth and a=a and l=l and authCap=authCap and cap=cap and addrTrans=addrTrans and authAccessible=authAccessible] note [SemanticsStoreDataI] = SemanticsStoreData_Fetch[where auth=auth and a=a and l=l and authCap=authCap and cap=cap and addrTrans=addrTrans and authAccessible=authAccessible] show ?thesis unfolding NextWithGhostState_def DomainActions_def by (SemanticsStoreData intro: UndefinedCase_TakeBranch) (auto split: option.splits) qed theorem SemanticsStoreData: assumes prov: "StoreDataAction auth a l \<in> actions" and suc: "(PreserveDomain actions, s') \<in> SemanticsCheriMips s" and valid: "getStateIsValid s" shows "Permit_Store (getPerms (getCapReg auth s))" "getTag (getCapReg auth s)" "\<not> getSealed (getCapReg auth s)" "getRegisterIsAccessible auth s" "Region a l \<subseteq> getTranslateAddresses (RegionOfCap (getCapReg auth s)) STORE s" "getTag (getMemCap (GetCapAddress a) s') \<Longrightarrow> getMemCap (GetCapAddress a) s' = getMemCap (GetCapAddress a) s" "l \<noteq> 0" using assms using SemanticsStoreData_NextWithGhostState [where auth=auth and a=a and l=l and addrTrans="\<lambda>v. getTranslateAddr v s" and authCap="getCapReg auth s" and cap="getMemCap (GetCapAddress a) s" and authAccessible="getRegisterIsAccessible auth s", THEN HoareTripleE[where s=s]] unfolding SemanticsStoreDataPost_def AddressIsDataWritable_def unfolding getTranslateAddrFunc_def getTranslateAddresses_def unfolding StateIsValid_def unfolding SemanticsCheriMips_def Next_NextWithGhostState NextNonExceptionStep_def by (auto simp: ValueAndStatePart_simp split: if_splits option.splits) corollary StoreDataInstantiation: assumes "(lbl, s') \<in> SemanticsCheriMips s" shows "StoreDataProp s lbl s'" unfolding StoreDataProp_def using assms SemanticsStoreData by metis (*<*) end (*>*)
# Bayesian Statistics Bayes rule $$ p(\theta| D) = \frac{p(D|\theta)p(\theta)}{p(D)} $$ However, in the samples that we will soon see it is far more convenient to write the above as $$ p(\theta| D) \propto p(D|\theta)p(\theta) $$ since $p(D)$ is a constant **that does not depend on $\theta$**. However, we Bayesian analysis is far more involved in solving the following integral: $$ p(D^*|D) = \int p(D^*|\theta)p(\theta|D) d\theta $$ We denote $D^*$ to be test data, $D$ to be the train set and $\theta$ to be a hidden parameter. This can often be thought of as doing model averaging if $p(\theta|D)$ is thought of as a weighting function. ## Coin Tossing Example Suppose we have a biased coin where the true probability of landing heads is 0.6. We assume however, (for some odd reason that it is biased towards landing tails). A suitable prior for this would be a beta distribution which has the following functional form: $$ p(\theta) = \frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha + \beta)}\theta^{\alpha - 1}(1-\theta)^{\beta - 1} $$ and the distribution looks like (https://en.wikipedia.org/wiki/Beta_distribution): Since we believe it is left skewed we will choose $\alpha < \beta$. Let $\alpha = 2$, $\beta = 3$ and hence, **this forms our prior distribution**. Assume that after 10 coin tosses we observe 7 heads and 3 tails. Each (individual) coin toss is distributed as a bernoulli distribution, conditional on $\theta$, the probability of achieving a heads. At this point a frequentist method (I don't mean this in a derogative fashion) would state that the probability of receiving a heads is 0.7. The likelihood of the data can be states as follows: $$ p(y_1, \cdots, y_{10}| \theta) = \prod_{i=1}^{10} p(y_i|\theta)$$ since each draw is independent **given $\theta$** where, $p(y_i|\theta) = \theta^{1(y_i=1)}(1-\theta)^{1(y_i=0)}$. Hence in our example, the likelihood $ p(y_1, \cdots, y_{10}| \theta) = \theta^7(1-\theta)^3$. **Keep in mind that $\theta$ is considered fixed as far as the likelihood is concerned**, hence it is a bernoullii distribution, **not a beta distribution**. ### The posterior \begin{align} p(\theta | y) \propto & \quad p(y|\theta) p(\theta) \\ \propto & \quad \theta^7(1-\theta)^3 \theta^2(1-\theta)^3 = \theta^{9}(1-\theta)^6 \end{align} The normalising constant is irrelevant as we can see that the posterior $p(\theta | y)$ is a beta distribution simply by looking at its functional form. In fact the normalising constant (also known as the partition function) is simply, $$\int_0^1 \theta^{9}(1-\theta)^6 d\theta$$ since all probability distributions integrate out to one. In this case this turns out to be $\frac{\Gamma(9)\Gamma(6)}{\Gamma(15)}$. What is far more important to recognise than the normalising constant is that $\theta \sim Be(9, 6)$. ### The probability of $p(y^*=1|y)$ \begin{align} p(y^*=1|y) &= \int p(y^*=1|\theta)p(\theta|y) d\theta \end{align} A frequentist method would have chosen the Maximum-A-Posteriori (MAP) estimate and plugged into $\theta$ without integrating it out. $$ \begin{align} p(y^*=1|y) &= \int p(y^*=1|\theta)p(\theta|y) d\theta \\ &= \int \theta \frac{\Gamma(15)}{\Gamma(9)\Gamma(6)} \theta^{9}(1-\theta)^6 d\theta\\ &= \frac{\Gamma(15)}{\Gamma(9)\Gamma(6)} \int\theta^{10}(1-\theta)^6 d\theta\\ &= \frac{\Gamma(15)}{\Gamma(9)\Gamma(6)} \frac{\Gamma(10)\Gamma(6)}{\Gamma(16)} \int\frac{\Gamma(16)}{\Gamma(10)\Gamma(6)}\theta^{10}(1-\theta)^6 d\theta \\ &= \frac{\Gamma(15)}{\Gamma(9)\Gamma(6)} \frac{\Gamma(10)\Gamma(6)}{\Gamma(16)} \quad 1 \\ &= \frac{9}{15} \end{align} $$ Note the rule $\Gamma(n) = (n-1)\Gamma(n-1)$ was used. ```python import pandas as pd import numpy as np import matplotlib.pyplot as plt import pymc3 as pm from scipy.special import gamma %matplotlib inline ``` ```python alpha = 2 beta = 3 y_obs = np.zeros(10) y_obs[:7] = 1 niter = 10000 with pm.Model() as model: θ = pm.Beta('θ', alpha=alpha, beta=beta) y = pm.Bernoulli('y', p=θ, observed=y_obs) trace = pm.sample(niter) ``` Auto-assigning NUTS sampler... Initializing NUTS using ADVI... Average Loss = 8.1227: 1%| | 1292/200000 [00:00<00:15, 12915.73it/s] Convergence archived at 2500 Interrupted at 2,500 [1%]: Average Loss = 7.9508 100%|██████████| 100500/100500 [00:37<00:00, 2691.01it/s] ```python # norm_const = gamma(9)*gamma(6)/gamma(15) theta = np.linspace(0,1,1000) post_theta = (theta**9)*(1-theta)**6 C = np.sum(post_theta*(theta[1]-theta[0])) post_theta = post_theta/C ``` ```python plt.hist(trace['θ'][1000:],100, normed='true') plt.plot(theta, post_theta) plt.show() ``` $$\int \theta p(\theta | y) d\theta \approx \sum_{\theta\sim p(\theta|y)} \theta$$ ```python np.mean(trace['θ'][1000:]) ``` 0.59970305353900688 ```python ``` ```python ``` ```python ``` ```python ```
/* * Copyright 2011 Mario Mulansky * Copyright 2012 Karsten Ahnert * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or * copy at http://www.boost.org/LICENSE_1_0.txt) */ #include <boost/array.hpp> //#include <boost/numeric/odeint/stepper/explicit_generic_rk.hpp> #include <boost/numeric/odeint/stepper/runge_kutta4.hpp> #include <boost/numeric/odeint/algebra/array_algebra.hpp> #include "rk_performance_test_case.hpp" #include "lorenz.hpp" using namespace boost::numeric::odeint; typedef boost::array< double , 3 > state_type; /* typedef explicit_generic_rk< 4 , 4 , state_type , double , state_type , double , array_algebra > rk4_type; typedef rk4_type::coef_a_type coef_a_type; typedef rk4_type::coef_b_type coef_b_type; typedef rk4_type::coef_c_type coef_c_type; const boost::array< double , 1 > a1 = {{ 0.5 }}; const boost::array< double , 2 > a2 = {{ 0.0 , 0.5 }}; const boost::array< double , 3 > a3 = {{ 0.0 , 0.0 , 1.0 }}; const coef_a_type a = fusion::make_vector( a1 , a2 , a3 ); const coef_b_type b = {{ 1.0/6 , 1.0/3 , 1.0/3 , 1.0/6 }}; const coef_c_type c = {{ 0.0 , 0.5 , 0.5 , 1.0 }}; */ typedef runge_kutta4< state_type , double , state_type , double , array_algebra > rk4_type; class rk4_wrapper { public: rk4_wrapper() // : m_stepper( a , b , c ) {} void reset_init_cond() { m_x[0] = 10.0 * rand() / RAND_MAX; m_x[1] = 10.0 * rand() / RAND_MAX; m_x[2] = 10.0 * rand() / RAND_MAX; m_t = 0.0; } inline void do_step( const double dt ) { m_stepper.do_step( lorenz(), m_x , m_t , dt ); } double state( const size_t i ) const { return m_x[i]; } private: state_type m_x; double m_t; rk4_type m_stepper; }; int main() { srand( 12312354 ); rk4_wrapper stepper; run( stepper ); }
For any polynomial $p$ and any number $a$, we have $p(x) \cdot (a + xq(x)) = ap(x) + x(p(x) \cdot q(x))$.
#include <stdio.h> #include <gsl/gsl_sf_bessel.h> int main(void) { double x = 5.0; double y = gsl_sf_bessel_J0(x); printf("J0(%g) = %.18e\n", x, y); return 0; }
{-# OPTIONS --without-K --safe #-} module Cats.Category.Setoids.Facts where open import Cats.Category.Setoids.Facts.Exponential public using (hasExponentials) open import Cats.Category.Setoids.Facts.Initial public using (hasInitial) open import Cats.Category.Setoids.Facts.Limit public using (complete) open import Cats.Category.Setoids.Facts.Product public using (hasProducts ; hasBinaryProducts ; hasFiniteProducts) open import Cats.Category.Setoids.Facts.Terminal public using (hasTerminal) open import Cats.Category open import Cats.Category.Setoids using (Setoids) instance isCCC : ∀ {l} → IsCCC (Setoids l l) isCCC = record {}