Datasets:
AI4M
/

text
stringlengths
0
3.34M
/*************************************************************************** misc.h - description ------------------- copyright : (C) 2005 by MOUSSA email : [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. * * * ***************************************************************************/ #ifndef MISC_H #define MISC_H #include "config.h" #include <gsl/gsl_math.h> #include <gsl/gsl_monte.h> #include <gsl/gsl_monte_plain.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> ////////////////////////////////////////////////////////////////////////////// template<class T> void Add_vectors(T *vec1, T *vec2, T *result, int size); template<class T> void Add_vectors(T *vec1, T *vec2, T *result, int size){ for(int i=0; i<size; i++){ result[i] = vec1[i]+vec2[i]; } } ////////////////////////////////////////////////////////////////////////////// template<class T> void Mult_vector_const(T *vec, T c, T *result, int size); template<class T> void Mult_vector_const(T *vec, T c, T *result, int size){ for(int i=0; i<size; i++){ result[i] = vec[i]*c; } } ////////////////////////////////////////////////////////////////////////////// template<class T>void assign_value(T *vec, T c, int size); template<class T>void assign_value(T *vec, T c, int size){ for(int i = 0; i<size; i++) vec[i] = c; } ////////////////////////////////////////////////////////////////////////////// template<class T>void copy_vectors(T *src, T *dest, int size); template<class T>void copy_vectors(T *src, T *dest, int size){ for(int i = 0; i<size; i++){ dest[i] = src[i]; } } ////////////////////////////////////////////////////////////////////////////// template<class T> int is_overlaping(T *vec1, T *vec2, int size); template<class T> int is_overlaping(T *vec1, T *vec2, int size){ for(int i = 0; i<size; i++){ if((fabs(vec1[i])>1e-6)&&(fabs(vec2[i])>1e-6)) return true; } return false; } ////////////////////////////////////////////////////////////////////////////// template<class T> void print_vector(T *vec, int size); template<class T> void print_vector(T *vec, int size){ for(int i = 0; i<size; i++){ if(vec[i]>0.0) std::cout<<vec[i]<<std::endl; } } ////////////////////////////////////////////////////////////////////////////// template<class T> bool AllOnes(T *vec, int size); template<class T> bool AllOnes(T *vec, int size){ for(int i = 0; i < size; i++) if(fabs(vec[i]) < 1e-6) return false; return true; } ////////////////////////////////////////////////////////////////////////////// int gettoken(char[30], FILE *); bool FileName(char[30], char *); void theta_phi_bounds(Triangle_3 tr, double *mintheta, double *maxtheta, double *minphi, double *maxphi); void SphericalHarmonic(int, int, double, double, gsl_complex *); #endif
VR Transpoint is an experienced, diversified and skilled logistics provider – both on rail and road. Together with our clients and partners we develop new services to support their core business. In addition to transports, we tailor the whole logistics chain with its supplementary services, from plant to port and back. We bring efficiency and flexibility to logistics by combining rail and road transportations into one smooth entity. This is what we simply call “Rail & Road”. We create logistics that also add value to our clients’ clients. VR Transpoint is a part of VR Group, its growing and evolving professional in logistics. VR Group is a versatile, environmentally friendly and responsible travel, logistics and infrastructure engineering service company.
# Homework 3: Three-Body Problem (20 points) Group Members: Julius Franke (el442, [email protected]), Erik Meister (kd400, [email protected]), Eugen Dizer (qo452, [email protected]) Due on Friday, 15.05.2020. ```python #Load standard libraries import numpy as np import matplotlib.pyplot as plt %matplotlib inline ``` ## $4^{th}$ Order Runge-Kutta Method (RK4) ```python def rk4_step(y0, x0, f, h): ''' Simple python implementation for one RK4 step. Inputs: y_0 - M x 1 numpy array specifying all variables of the ODE at the current time step x_0 - current time step f - function that calculates the derivates of all variables of the ODE h - time step size Output: yp1 - M x 1 numpy array of variables at time step x0 + h xp1 - time step x0+h ''' k1 = h * f(y0) k2 = h * f(y0 + k1/2) k3 = h * f(y0 + k2/2) k4 = h * f(y0 + k3) xp1 = x0 + h yp1 = y0 + 1/6*(k1 + 2*k2 + 2*k3 + k4) return(yp1,xp1) def rk4(y0, x0, f, h, n): ''' Simple implementation of RK4 Inputs: y_0 - M x 1 numpy array specifying all variables of the ODE at the current time step x_0 - current time step f - function that calculates the derivates of all variables of the ODE h - time step size n - number of steps Output: yn - N+1 x M numpy array with the results of the integration for every time step (includes y0) xn - N+1 x 1 numpy array with the time step value (includes start x0) ''' yn = np.zeros((n+1, y0.shape[0])) xn = np.zeros(n+1) yn[0,:] = y0 xn[0] = x0 for n in np.arange(1,n+1,1): yn[n,:], xn[n] = rk4_step(y0 = yn[n-1,:], x0 = xn[n-1], f = f, h = h) return(yn, xn) # Be advised that the integration can take a while for large values of n (e.g >=10^5). ``` ## Introduction: The Three-Body Problem The gravitational three-body problem is described by the Newtonian equations of motion: \begin{align} \ddot{\mathbf{r}}_1 &= - G m_2 \frac{\mathbf{r}_1 - \mathbf{r}_2}{\left\vert \mathbf{r}_1 - \mathbf{r}_2 \right\vert^3} - G m_3 \frac{\mathbf{r}_1 - \mathbf{r}_3}{\left\vert \mathbf{r}_1 - \mathbf{r}_3 \right\vert^3} , \\ \ddot{\mathbf{r}}_2 &= - G m_3 \frac{\mathbf{r}_2 - \mathbf{r}_3}{\left\vert \mathbf{r}_2 - \mathbf{r}_3 \right\vert^3} - G m_1 \frac{\mathbf{r}_2 - \mathbf{r}_1}{\left\vert \mathbf{r}_2 - \mathbf{r}_1 \right\vert^3} , \\ \ddot{\mathbf{r}}_3 &= - G m_1 \frac{\mathbf{r}_3 - \mathbf{r}_1}{\left\vert \mathbf{r}_3 - \mathbf{r}_1 \right\vert^3} - G m_2 \frac{\mathbf{r}_3 - \mathbf{r}_2}{\left\vert \mathbf{r}_3 - \mathbf{r}_2 \right\vert^3} , \end{align} where $\mathbf{r}_i = (x_i, y_i)$ is the position vector of the masses $m_i$. To apply the Runge-Kutta Method to solve this system, we transform it to six first order ODEs. ### a) In a first step, set the masses of all three bodies to $m_1 = m_2 = m_3 = 1$ and select the following initial conditions for $y(0)$: \begin{align} (y_1, y_2) &= (-0.97000436, 0.24308753) \\ (y_3, y_4) &= (-0.46620368, -0.43236573) \\ (y_5, y_6) &= (0.97000436, -0.24308753) \\ (y_7, y_8) &= (-0.46620368, -0.43236573) \\ (y_9, y_{10}) &= (0.0, 0.0) \\ (y_{11}, y_{12}) &= (0.93240737, 0.86473146) \end{align} ### Here, $y_{1+4i}$ and $y_{2+4i}$ are the initial coordinates and $y_{3+4i}$ and $y_{4+4i}$ the initial velocities for the objects $i = 0, 1$ and $2$. Try to integrate with a step size $h$ between 0.01 and 0.001 and plot the result. ```python G = 1 m1 = 1 m2 = 1 m3 = 1 #Initial conditions y1 = [-0.97000436, 0.24308753] v1 = [-0.46620368, -0.43236573] y2 = [0.97000436, -0.24308753] v2 = [-0.46620368, -0.43236573] y3 = [0.0, 0.0] v3 = [0.93240737, 0.86473146] y0 = np.array(y1 + v1 + y2 + v2 + y3 + v3) #Define norm of a 2-vector def norm_of_vector(x): return np.sqrt(x[0]**2 + x[1]**2) #Define derivatives of all variables, when getting the M x 1 array of all variables y def derivative_of_y1(y): v1 = y[2:4] return list(v1) def derivative_of_v1(y): y1 = y[0:2] y2 = y[4:6] y3 = y[8:10] return list(-G*m2*(y1 - y2)/norm_of_vector(y1-y2)**3 - G*m3*(y1 - y3)/norm_of_vector(y1-y3)**3) def derivative_of_y2(y): v2 = y[6:8] return list(v2) def derivative_of_v2(y): y1 = y[0:2] y2 = y[4:6] y3 = y[8:10] return list(-G*m3*(y2 - y3)/norm_of_vector(y2-y3)**3 - G*m1*(y2 - y1)/norm_of_vector(y2-y1)**3) def derivative_of_y3(y): v3 = y[10:12] return list(v3) def derivative_of_v3(y): y1 = y[0:2] y2 = y[4:6] y3 = y[8:10] return list(-G*m1*(y3 - y1)/norm_of_vector(y3-y1)**3 - G*m2*(y3 - y2)/norm_of_vector(y3-y2)**3) #Define function that calculates the derivates of all variables of the ODE def f(y): return np.array(derivative_of_y1(y) + derivative_of_v1(y) + derivative_of_y2(y) + derivative_of_v2(y) + derivative_of_y3(y) + derivative_of_v3(y)) ``` ```python #Choose steps size h h = 0.005 y, x = rk4(y0, 0, f, h, 500) pos1_x = [] pos1_y = [] for i in range(len(y)): pos1_x.append(y[i][0]) pos1_y.append(y[i][1]) pos2_x = [] pos2_y = [] for i in range(len(y)): pos2_x.append(y[i][4]) pos2_y.append(y[i][5]) pos3_x = [] pos3_y = [] for i in range(len(y)): pos3_x.append(y[i][8]) pos3_y.append(y[i][9]) #Plot trajectory plt.title('Three-Body-Solution with $h =$ ' + str(h)) plt.xlabel(r'x') plt.ylabel(r'y') plt.plot(pos1_x, pos1_y, linewidth=1.0, linestyle="-", label='m1 = 1') plt.plot(pos2_x, pos2_y, linewidth=1.0, linestyle="-", label='m2 = 1') plt.plot(pos3_x, pos3_y, linewidth=1.0, linestyle="-", label='m3 = 1') plt.legend() plt.show() ``` ### b) Now consider a different problem. Choose the masses of the three bodies to be $m_1 = 3$, $m_2 = 4$ and $m_3 = 5$, and place them at the corners of a right triangle (one angle is $90^{\circ}$) with edge lengths of $l_1 = 3$, $l_2 = 4$ and $l_3 = 5$, such that $m_1$ is opposite to the edge $l_1$, $m_2$ opposite to $l_2$, and $m_3$ opposite to $l_3$. Set the initial velocities to zero. This is the Meissel-Burrau problem. We recommend to place the origin of your coordinate system into the center of mass of the system. ```python #Initial conditions m1 = 3 m2 = 4 m3 = 5 #Initial conditions, place the origin of your coordinate system into the center of mass of the system y1 = [-1, 3] v1 = [0.0, 0.0] y2 = [2, -1] v2 = [0.0, 0.0] y3 = [-1, -1] v3 = [0.0, 0.0] y0 = np.array(y1 + v1 + y2 + v2 + y3 + v3) ``` ### Use the Runge-Kutta-4 integrator to follow the time evolution of the system until it dissolves. Record the points in time when two bodies have minimum separation and store this data in a file. Investigate the behavior of the system for different integration steps $h$, starting with $h = 0.1$. How small does $h$ need to be in order to obtain reliable estimates for the time of the first five closest encounters. ```python #Choose step size h h = 0.0001 y, x = rk4(y0, 0, f, h, 80000) pos1_x = [] pos1_y = [] for i in range(len(y)): pos1_x.append(y[i][0]) pos1_y.append(y[i][1]) pos2_x = [] pos2_y = [] for i in range(len(y)): pos2_x.append(y[i][4]) pos2_y.append(y[i][5]) pos3_x = [] pos3_y = [] for i in range(len(y)): pos3_x.append(y[i][8]) pos3_y.append(y[i][9]) ``` ```python plt.title('Three-Body-Solution with $h =$ ' + str(h)) plt.xlabel(r'x') plt.ylabel(r'y') plt.plot(pos1_x, pos1_y, linewidth=1.0, linestyle="-", label='m1 = 3') plt.plot(pos2_x, pos2_y, linewidth=1.0, linestyle="-", label='m2 = 4') plt.plot(pos3_x, pos3_y, linewidth=1.0, linestyle="-", label='m3 = 5') plt.legend() plt.show() ``` ```python ################################################################################ distance23 = [] for t in range(len(pos1_x)): distance = np.sqrt((pos2_x[t]-pos3_x[t])**2 + (pos2_y[t]-pos3_y[t])**2) distance23.append(distance) index = distance23.index(min(distance23)) t = x[index] print(t) print(min(distance23)) ################################################################################# ``` 1.8793 0.0097873762765 ### Plot for different step sizes $h$: ```python #We choose the time steps h1 = 0.1 h2 = 0.01 h3 = 0.001 h4 = 0.0001 ``` ### (i) the trajectories of the three bodies in the orbital plane. ```python #Solve for the coordinates of the masses for different step sizes and constant integration time T=8 def solve_for_position(h): y, x = rk4(y0, 0, f, h, int(8/h)) pos1_x = [] pos1_y = [] for i in range(len(y)): pos1_x.append(y[i][0]) pos1_y.append(y[i][1]) pos2_x = [] pos2_y = [] for i in range(len(y)): pos2_x.append(y[i][4]) pos2_y.append(y[i][5]) pos3_x = [] pos3_y = [] for i in range(len(y)): pos3_x.append(y[i][8]) pos3_y.append(y[i][9]) return (pos1_x, pos1_y, pos2_x, pos2_y, pos3_x, pos3_y) positions1 = solve_for_position(h1) positions2 = solve_for_position(h2) positions3 = solve_for_position(h3) positions4 = solve_for_position(h4) ``` ```python #Plot trajectories fig, axs = plt.subplots(2, 2, figsize=(12,10)) axs[0,0].plot(positions1[0], positions1[1], linewidth=1.0, linestyle="-", label='m1 = 3') axs[0,0].plot(positions1[2], positions1[3], linewidth=1.0, linestyle="-", label='m2 = 4') axs[0,0].plot(positions1[4], positions1[5], linewidth=1.0, linestyle="-", label='m3 = 5') axs[0,0].set_title('Three-Body-Solution with $h =$ ' + str(h1)) axs[0,0].legend() axs[1,0].plot(positions2[0], positions2[1], linewidth=1.0, linestyle="-", label='m1 = 3') axs[1,0].plot(positions2[2], positions2[3], linewidth=1.0, linestyle="-", label='m2 = 4') axs[1,0].plot(positions2[4], positions2[5], linewidth=1.0, linestyle="-", label='m3 = 5') axs[1,0].set_title('Three-Body-Solution with $h =$ ' + str(h2)) axs[1,0].legend() axs[0,1].plot(positions3[0], positions3[1], linewidth=1.0, linestyle="-", label='m1 = 3') axs[0,1].plot(positions3[2], positions3[3], linewidth=1.0, linestyle="-", label='m2 = 4') axs[0,1].plot(positions3[4], positions3[5], linewidth=1.0, linestyle="-", label='m3 = 5') axs[0,1].set_title('Three-Body-Solution with $h =$ ' + str(h3)) axs[0,1].legend() axs[1,1].plot(positions4[0], positions4[1], linewidth=1.0, linestyle="-", label='m1 = 3') axs[1,1].plot(positions4[2], positions4[3], linewidth=1.0, linestyle="-", label='m2 = 4') axs[1,1].plot(positions4[4], positions4[5], linewidth=1.0, linestyle="-", label='m3 = 5') axs[1,1].set_title('Three-Body-Solution with $h =$ ' + str(h4)) axs[1,1].legend() for ax in axs.flat: ax.set(xlabel='x', ylabel='y') ``` ### (ii) the mutual distances of the three bodies in logarithmic scaling as function of time (linear). ```python #Distance between m1 and m2 distance12 = [] for t in range(len(positions1[0])): distance = np.sqrt((positions1[0][t]-positions1[2][t])**2 + (positions1[1][t]-positions1[3][t])**2) distance12.append(distance) #Distance between m1 and m3 distance13 = [] for t in range(len(positions1[0])): distance = np.sqrt((positions1[0][t]-positions1[4][t])**2 + (positions1[1][t]-positions1[5][t])**2) distance13.append(distance) #Distance between m2 and m3 distance23 = [] for t in range(len(positions1[0])): distance = np.sqrt((positions1[2][t]-positions1[4][t])**2 + (positions1[3][t]-positions1[5][t])**2) distance23.append(distance) x1 = rk4(y0, 0, f, h1, int(8/h1))[1] plt.title('Distances with $h =$' + str(h1)) plt.xlabel(r'Time') plt.ylabel(r'Distance') plt.plot(x1, distance12, linewidth=1.0, linestyle="-", label='Distance 1 - 2') plt.plot(x1, distance13, linewidth=1.0, linestyle="-", label='Distance 1 - 3') plt.plot(x1, distance23, linewidth=1.0, linestyle="-", label='Distance 2 - 3') plt.yscale('log') plt.legend() plt.show() ``` ```python #Distance between m1 and m2 distance12 = [] for t in range(len(positions2[0])): distance = np.sqrt((positions2[0][t]-positions2[2][t])**2 + (positions2[1][t]-positions2[3][t])**2) distance12.append(distance) #Distance between m1 and m3 distance13 = [] for t in range(len(positions2[0])): distance = np.sqrt((positions2[0][t]-positions2[4][t])**2 + (positions2[1][t]-positions2[5][t])**2) distance13.append(distance) #Distance between m2 and m3 distance23 = [] for t in range(len(positions2[0])): distance = np.sqrt((positions2[2][t]-positions2[4][t])**2 + (positions2[3][t]-positions2[5][t])**2) distance23.append(distance) x2 = rk4(y0, 0, f, h2, int(8/h2))[1] plt.title('Distances with $h =$' + str(h2)) plt.xlabel(r'Time') plt.ylabel(r'Distance') plt.plot(x2, distance12, linewidth=1.0, linestyle="-", label='Distance 1 - 2') plt.plot(x2, distance13, linewidth=1.0, linestyle="-", label='Distance 1 - 3') plt.plot(x2, distance23, linewidth=1.0, linestyle="-", label='Distance 2 - 3') plt.yscale('log') plt.legend() plt.show() ``` ```python #Distance between m1 and m2 distance12 = [] for t in range(len(positions3[0])): distance = np.sqrt((positions3[0][t]-positions3[2][t])**2 + (positions3[1][t]-positions3[3][t])**2) distance12.append(distance) #Distance between m1 and m3 distance13 = [] for t in range(len(positions3[0])): distance = np.sqrt((positions3[0][t]-positions3[4][t])**2 + (positions3[1][t]-positions3[5][t])**2) distance13.append(distance) #Distance between m2 and m3 distance23 = [] for t in range(len(positions3[0])): distance = np.sqrt((positions3[2][t]-positions3[4][t])**2 + (positions3[3][t]-positions3[5][t])**2) distance23.append(distance) x3 = rk4(y0, 0, f, h3, int(8/h3))[1] plt.title('Distances with $h =$' + str(h3)) plt.xlabel(r'Time') plt.ylabel(r'Distance') plt.plot(x3, distance12, linewidth=1.0, linestyle="-", label='Distance 1 - 2') plt.plot(x3, distance13, linewidth=1.0, linestyle="-", label='Distance 1 - 3') plt.plot(x3, distance23, linewidth=1.0, linestyle="-", label='Distance 2 - 3') plt.yscale('log') plt.legend() plt.show() ``` ```python #Distance between m1 and m2 distance12 = [] for t in range(len(positions4[0])): distance = np.sqrt((positions4[0][t]-positions4[2][t])**2 + (positions4[1][t]-positions4[3][t])**2) distance12.append(distance) #Distance between m1 and m3 distance13 = [] for t in range(len(positions4[0])): distance = np.sqrt((positions4[0][t]-positions4[4][t])**2 + (positions4[1][t]-positions4[5][t])**2) distance13.append(distance) #Distance between m2 and m3 distance23 = [] for t in range(len(positions4[0])): distance = np.sqrt((positions4[2][t]-positions4[4][t])**2 + (positions4[3][t]-positions4[5][t])**2) distance23.append(distance) x4 = rk4(y0, 0, f, h4, int(8/h4))[1] plt.title('Distances with $h =$' + str(h4)) plt.xlabel(r'Time') plt.ylabel(r'Distance') plt.plot(x4, distance12, linewidth=1.0, linestyle="-", label='Distance 1 - 2') plt.plot(x4, distance13, linewidth=1.0, linestyle="-", label='Distance 1 - 3') plt.plot(x4, distance23, linewidth=1.0, linestyle="-", label='Distance 2 - 3') plt.yscale('log') plt.legend() plt.show() ``` ### (iii) the error of the total energy of the system in logarithmic scaling as function of time (linear). ```python #Didn't had so much time ```
#ifndef AVECADO_GENERALIZER_HPP #define AVECADO_GENERALIZER_HPP #include "post_process/izer_base.hpp" #include <boost/property_tree/ptree.hpp> namespace pt = boost::property_tree; namespace avecado { namespace post_process { /** * Create a new instance of "generalizer", a post-process that * runs a selected generalization algorithm on feature geometries. */ izer_ptr create_generalizer(pt::ptree const& config); } // namespace post_process } // namespace avecado #endif // AVECADO_GENERALIZER_HPP
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.locally_finite /-! # Finite intervals of naturals > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves that `ℕ` is a `locally_finite_order` and calculates the cardinality of its intervals as finsets and fintypes. ## TODO Some lemmas can be generalized using `ordered_group`, `canonically_ordered_monoid` or `succ_order` and subsequently be moved upstream to `data.finset.locally_finite`. -/ open finset nat instance : locally_finite_order ℕ := { finset_Icc := λ a b, ⟨list.range' a (b + 1 - a), list.nodup_range' _ _⟩, finset_Ico := λ a b, ⟨list.range' a (b - a), list.nodup_range' _ _⟩, finset_Ioc := λ a b, ⟨list.range' (a + 1) (b - a), list.nodup_range' _ _⟩, finset_Ioo := λ a b, ⟨list.range' (a + 1) (b - a - 1), list.nodup_range' _ _⟩, finset_mem_Icc := λ a b x, begin rw [finset.mem_mk, multiset.mem_coe, list.mem_range'], cases le_or_lt a b, { rw [add_tsub_cancel_of_le (nat.lt_succ_of_le h).le, nat.lt_succ_iff] }, { rw [tsub_eq_zero_iff_le.2 (succ_le_of_lt h), add_zero], exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.trans hx.2)) } end, finset_mem_Ico := λ a b x, begin rw [finset.mem_mk, multiset.mem_coe, list.mem_range'], cases le_or_lt a b, { rw [add_tsub_cancel_of_le h] }, { rw [tsub_eq_zero_iff_le.2 h.le, add_zero], exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.trans hx.2.le)) } end, finset_mem_Ioc := λ a b x, begin rw [finset.mem_mk, multiset.mem_coe, list.mem_range'], cases le_or_lt a b, { rw [←succ_sub_succ, add_tsub_cancel_of_le (succ_le_succ h), nat.lt_succ_iff, nat.succ_le_iff] }, { rw [tsub_eq_zero_iff_le.2 h.le, add_zero], exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.le.trans hx.2)) } end, finset_mem_Ioo := λ a b x, begin rw [finset.mem_mk, multiset.mem_coe, list.mem_range', ← tsub_add_eq_tsub_tsub], cases le_or_lt (a + 1) b, { rw [add_tsub_cancel_of_le h, nat.succ_le_iff] }, { rw [tsub_eq_zero_iff_le.2 h.le, add_zero], exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.trans hx.2)) } end } variables (a b c : ℕ) namespace nat lemma Icc_eq_range' : Icc a b = ⟨list.range' a (b + 1 - a), list.nodup_range' _ _⟩ := rfl lemma Ico_eq_range' : Ico a b = ⟨list.range' a (b - a), list.nodup_range' _ _⟩ := rfl lemma Ioc_eq_range' : Ioc a b = ⟨list.range' (a + 1) (b - a), list.nodup_range' _ _⟩ := rfl lemma Ioo_eq_range' : Ioo a b = ⟨list.range' (a + 1) (b - a - 1), list.nodup_range' _ _⟩ := rfl lemma Iio_eq_range : Iio = range := by { ext b x, rw [mem_Iio, mem_range] } @[simp] lemma Ico_zero_eq_range : Ico 0 = range := by rw [←bot_eq_zero, ←Iio_eq_Ico, Iio_eq_range] lemma _root_.finset.range_eq_Ico : range = Ico 0 := Ico_zero_eq_range.symm @[simp] lemma card_Icc : (Icc a b).card = b + 1 - a := list.length_range' _ _ @[simp] lemma card_Ico : (Ico a b).card = b - a := list.length_range' _ _ @[simp] lemma card_Ioc : (Ioc a b).card = b - a := list.length_range' _ _ @[simp] lemma card_Ioo : (Ioo a b).card = b - a - 1 := list.length_range' _ _ @[simp] lemma card_Iic : (Iic b).card = b + 1 := by rw [Iic_eq_Icc, card_Icc, bot_eq_zero, tsub_zero] @[simp] lemma card_Iio : (Iio b).card = b := by rw [Iio_eq_Ico, card_Ico, bot_eq_zero, tsub_zero] @[simp] lemma card_fintype_Icc : fintype.card (set.Icc a b) = b + 1 - a := by rw [fintype.card_of_finset, card_Icc] @[simp] lemma card_fintype_Ico : fintype.card (set.Ico a b) = b - a := by rw [fintype.card_of_finset, card_Ico] @[simp] lemma card_fintype_Ioc : fintype.card (set.Ioc a b) = b - a := by rw [fintype.card_of_finset, card_Ioc] @[simp] lemma card_fintype_Ioo : fintype.card (set.Ioo a b) = b - a - 1 := by rw [fintype.card_of_finset, card_Ioo] @[simp] lemma card_fintype_Iic : fintype.card (set.Iic b) = b + 1 := by rw [fintype.card_of_finset, card_Iic] @[simp] lemma card_fintype_Iio : fintype.card (set.Iio b) = b := by rw [fintype.card_of_finset, card_Iio] -- TODO@Yaël: Generalize all the following lemmas to `succ_order` lemma Icc_succ_left : Icc a.succ b = Ioc a b := by { ext x, rw [mem_Icc, mem_Ioc, succ_le_iff] } lemma Ico_succ_right : Ico a b.succ = Icc a b := by { ext x, rw [mem_Ico, mem_Icc, lt_succ_iff] } lemma Ico_succ_left : Ico a.succ b = Ioo a b := by { ext x, rw [mem_Ico, mem_Ioo, succ_le_iff] } lemma Icc_pred_right {b : ℕ} (h : 0 < b) : Icc a (b - 1) = Ico a b := by { ext x, rw [mem_Icc, mem_Ico, lt_iff_le_pred h] } lemma Ico_succ_succ : Ico a.succ b.succ = Ioc a b := by { ext x, rw [mem_Ico, mem_Ioc, succ_le_iff, lt_succ_iff] } @[simp] lemma Ico_succ_singleton : Ico a (a + 1) = {a} := by rw [Ico_succ_right, Icc_self] @[simp] lemma Ico_pred_singleton {a : ℕ} (h : 0 < a) : Ico (a - 1) a = {a - 1} := by rw [←Icc_pred_right _ h, Icc_self] @[simp] lemma Ioc_succ_singleton : Ioc b (b + 1) = {b+1} := by rw [← nat.Icc_succ_left, Icc_self] variables {a b c} lemma Ico_succ_right_eq_insert_Ico (h : a ≤ b) : Ico a (b + 1) = insert b (Ico a b) := by rw [Ico_succ_right, ←Ico_insert_right h] lemma Ico_insert_succ_left (h : a < b) : insert a (Ico a.succ b) = Ico a b := by rw [Ico_succ_left, ←Ioo_insert_left h] lemma image_sub_const_Ico (h : c ≤ a) : (Ico a b).image (λ x, x - c) = Ico (a - c) (b - c) := begin ext x, rw mem_image, split, { rintro ⟨x, hx, rfl⟩, rw [mem_Ico] at ⊢ hx, exact ⟨tsub_le_tsub_right hx.1 _, tsub_lt_tsub_right_of_le (h.trans hx.1) hx.2⟩ }, { rintro h, refine ⟨x + c, _, add_tsub_cancel_right _ _⟩, rw mem_Ico at ⊢ h, exact ⟨tsub_le_iff_right.1 h.1, lt_tsub_iff_right.1 h.2⟩ } end lemma Ico_image_const_sub_eq_Ico (hac : a ≤ c) : (Ico a b).image (λ x, c - x) = Ico (c + 1 - b) (c + 1 - a) := begin ext x, rw [mem_image, mem_Ico], split, { rintro ⟨x, hx, rfl⟩, rw mem_Ico at hx, refine ⟨_, ((tsub_le_tsub_iff_left hac).2 hx.1).trans_lt ((tsub_lt_tsub_iff_right hac).2 (nat.lt_succ_self _))⟩, cases lt_or_le c b, { rw tsub_eq_zero_iff_le.mpr (succ_le_of_lt h), exact zero_le _ }, { rw ←succ_sub_succ c, exact (tsub_le_tsub_iff_left (succ_le_succ $ hx.2.le.trans h)).2 hx.2 } }, { rintro ⟨hb, ha⟩, rw [lt_tsub_iff_left, lt_succ_iff] at ha, have hx : x ≤ c := (nat.le_add_left _ _).trans ha, refine ⟨c - x, _, tsub_tsub_cancel_of_le hx⟩, { rw mem_Ico, exact ⟨le_tsub_of_add_le_right ha, (tsub_lt_iff_left hx).2 $ succ_le_iff.1 $ tsub_le_iff_right.1 hb⟩ } } end lemma Ico_succ_left_eq_erase_Ico : Ico a.succ b = erase (Ico a b) a := begin ext x, rw [Ico_succ_left, mem_erase, mem_Ico, mem_Ioo, ←and_assoc, ne_comm, and_comm (a ≠ x), lt_iff_le_and_ne], end lemma mod_inj_on_Ico (n a : ℕ) : set.inj_on (% a) (finset.Ico n (n+a)) := begin induction n with n ih, { simp only [zero_add, nat_zero_eq_zero, Ico_zero_eq_range], rintro k hk l hl (hkl : k % a = l % a), simp only [finset.mem_range, finset.mem_coe] at hk hl, rwa [mod_eq_of_lt hk, mod_eq_of_lt hl] at hkl, }, rw [Ico_succ_left_eq_erase_Ico, succ_add, Ico_succ_right_eq_insert_Ico le_self_add], rintro k hk l hl (hkl : k % a = l % a), have ha : 0 < a, { by_contra ha, simp only [not_lt, nonpos_iff_eq_zero] at ha, simpa [ha] using hk }, simp only [finset.mem_coe, finset.mem_insert, finset.mem_erase] at hk hl, rcases hk with ⟨hkn, (rfl|hk)⟩; rcases hl with ⟨hln, (rfl|hl)⟩, { refl }, { rw add_mod_right at hkl, refine (hln $ ih hl _ hkl.symm).elim, simp only [lt_add_iff_pos_right, set.left_mem_Ico, finset.coe_Ico, ha], }, { rw add_mod_right at hkl, suffices : k = n, { contradiction }, refine ih hk _ hkl, simp only [lt_add_iff_pos_right, set.left_mem_Ico, finset.coe_Ico, ha], }, { refine ih _ _ hkl; simp only [finset.mem_coe, hk, hl], }, end /-- Note that while this lemma cannot be easily generalized to a type class, it holds for ℤ as well. See `int.image_Ico_mod` for the ℤ version. -/ lemma image_Ico_mod (n a : ℕ) : (Ico n (n+a)).image (% a) = range a := begin obtain rfl | ha := eq_or_ne a 0, { rw [range_zero, add_zero, Ico_self, image_empty], }, ext i, simp only [mem_image, exists_prop, mem_range, mem_Ico], split, { rintro ⟨i, h, rfl⟩, exact mod_lt i ha.bot_lt }, intro hia, have hn := nat.mod_add_div n a, obtain hi | hi := lt_or_le i (n % a), { refine ⟨i + a * (n/a + 1), ⟨_, _⟩, _⟩, { rw [add_comm (n/a), mul_add, mul_one, ← add_assoc], refine hn.symm.le.trans (add_le_add_right _ _), simpa only [zero_add] using add_le_add (zero_le i) (nat.mod_lt n ha.bot_lt).le, }, { refine lt_of_lt_of_le (add_lt_add_right hi (a * (n/a + 1))) _, rw [mul_add, mul_one, ← add_assoc, hn], }, { rw [nat.add_mul_mod_self_left, nat.mod_eq_of_lt hia], } }, { refine ⟨i + a * (n/a), ⟨_, _⟩, _⟩, { exact hn.symm.le.trans (add_le_add_right hi _), }, { rw [add_comm n a], refine add_lt_add_of_lt_of_le hia (le_trans _ hn.le), simp only [zero_le, le_add_iff_nonneg_left], }, { rw [nat.add_mul_mod_self_left, nat.mod_eq_of_lt hia], } }, end section multiset open multiset lemma multiset_Ico_map_mod (n a : ℕ) : (multiset.Ico n (n+a)).map (% a) = range a := begin convert congr_arg finset.val (image_Ico_mod n a), refine ((nodup_map_iff_inj_on (finset.Ico _ _).nodup).2 $ _).dedup.symm, exact mod_inj_on_Ico _ _, end end multiset end nat namespace finset lemma range_image_pred_top_sub (n : ℕ) : (finset.range n).image (λ j, n - 1 - j) = finset.range n := begin cases n, { rw [range_zero, image_empty] }, { rw [finset.range_eq_Ico, nat.Ico_image_const_sub_eq_Ico (zero_le _)], simp_rw [succ_sub_succ, tsub_zero, tsub_self] } end lemma range_add_eq_union : range (a + b) = range a ∪ (range b).map (add_left_embedding a) := begin rw [finset.range_eq_Ico, map_eq_image], convert (Ico_union_Ico_eq_Ico a.zero_le le_self_add).symm, exact image_add_left_Ico _ _ _, end end finset section induction variables {P : ℕ → Prop} (h : ∀ n, P (n + 1) → P n) include h lemma nat.decreasing_induction_of_not_bdd_above (hP : ¬ bdd_above {x | P x}) (n : ℕ) : P n := let ⟨m, hm, hl⟩ := not_bdd_above_iff.1 hP n in decreasing_induction h hl.le hm lemma nat.decreasing_induction_of_infinite (hP : {x | P x}.infinite) (n : ℕ) : P n := nat.decreasing_induction_of_not_bdd_above h (mt bdd_above.finite hP) n lemma nat.cauchy_induction' (seed : ℕ) (hs : P seed) (hi : ∀ x, seed ≤ x → P x → ∃ y, x < y ∧ P y) (n : ℕ) : P n := begin apply nat.decreasing_induction_of_infinite h (λ hf, _), obtain ⟨m, hP, hm⟩ := hf.exists_maximal_wrt id _ ⟨seed, hs⟩, obtain ⟨y, hl, hy⟩ := hi m (le_of_not_lt $ λ hl, hl.ne $ hm seed hs hl.le) hP, exact hl.ne (hm y hy hl.le), end lemma nat.cauchy_induction (seed : ℕ) (hs : P seed) (f : ℕ → ℕ) (hf : ∀ x, seed ≤ x → P x → x < f x ∧ P (f x)) (n : ℕ) : P n := seed.cauchy_induction' h hs (λ x hl hx, ⟨f x, hf x hl hx⟩) n lemma nat.cauchy_induction_mul (k seed : ℕ) (hk : 1 < k) (hs : P seed.succ) (hm : ∀ x, seed < x → P x → P (k * x)) (n : ℕ) : P n := begin apply nat.cauchy_induction h _ hs ((*) k) (λ x hl hP, ⟨_, hm x hl hP⟩), convert (mul_lt_mul_right $ seed.succ_pos.trans_le hl).2 hk, rw one_mul, end lemma nat.cauchy_induction_two_mul (seed : ℕ) (hs : P seed.succ) (hm : ∀ x, seed < x → P x → P (2 * x)) (n : ℕ) : P n := nat.cauchy_induction_mul h 2 seed one_lt_two hs hm n end induction
Formal statement is: lemma sigma_algebra_iff: "sigma_algebra \<Omega> M \<longleftrightarrow> algebra \<Omega> M \<and> (\<forall>A. range A \<subseteq> M \<longrightarrow> (\<Union>i::nat. A i) \<in> M)" Informal statement is: A collection of subsets of a set $\Omega$ is a $\sigma$-algebra if and only if it is an algebra and the countable union of any sequence of sets in the collection is also in the collection.
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.ring_theory.witt_vector.basic import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Teichmüller lifts This file defines `witt_vector.teichmuller`, a monoid hom `R →* 𝕎 R`, which embeds `r : R` as the `0`-th component of a Witt vector whose other coefficients are `0`. ## Main declarations - `witt_vector.teichmuller`: the Teichmuller map. - `witt_vector.map_teichmuller`: `witt_vector.teichmuller` is a natural transformation. - `witt_vector.ghost_component_teichmuller`: the `n`-th ghost component of `witt_vector.teichmuller p r` is `r ^ p ^ n`. -/ namespace witt_vector /-- The underlying function of the monoid hom `witt_vector.teichmuller`. The `0`-th coefficient of `teichmuller_fun p r` is `r`, and all others are `0`. -/ def teichmuller_fun (p : ℕ) {R : Type u_1} [comm_ring R] (r : R) : witt_vector p R := sorry /-! ## `teichmuller` is a monoid homomorphism On ghost components, it is clear that `teichmuller_fun` is a monoid homomorphism. But in general the ghost map is not injective. We follow the same strategy as for proving that the the ring operations on `𝕎 R` satisfy the ring axioms. 1. We first prove it for rings `R` where `p` is invertible, because then the ghost map is in fact an isomorphism. 2. After that, we derive the result for `mv_polynomial R ℤ`, 3. and from that we can prove the result for arbitrary `R`. -/ /-- The Teichmüller lift of an element of `R` to `𝕎 R`. The `0`-th coefficient of `teichmuller p r` is `r`, and all others are `0`. This is a monoid homomorphism. -/ def teichmuller (p : ℕ) {R : Type u_1} [hp : fact (nat.prime p)] [comm_ring R] : R →* witt_vector p R := monoid_hom.mk (teichmuller_fun p) sorry sorry @[simp] theorem teichmuller_coeff_zero (p : ℕ) {R : Type u_1} [hp : fact (nat.prime p)] [comm_ring R] (r : R) : coeff (coe_fn (teichmuller p) r) 0 = r := rfl @[simp] theorem teichmuller_coeff_pos (p : ℕ) {R : Type u_1} [hp : fact (nat.prime p)] [comm_ring R] (r : R) (n : ℕ) (hn : 0 < n) : coeff (coe_fn (teichmuller p) r) n = 0 := sorry @[simp] theorem teichmuller_zero (p : ℕ) {R : Type u_1} [hp : fact (nat.prime p)] [comm_ring R] : coe_fn (teichmuller p) 0 = 0 := sorry /-- `teichmuller` is a natural transformation. -/ @[simp] theorem map_teichmuller (p : ℕ) {R : Type u_1} {S : Type u_2} [hp : fact (nat.prime p)] [comm_ring R] [comm_ring S] (f : R →+* S) (r : R) : coe_fn (map f) (coe_fn (teichmuller p) r) = coe_fn (teichmuller p) (coe_fn f r) := map_teichmuller_fun p f r /-- The `n`-th ghost component of `teichmuller p r` is `r ^ p ^ n`. -/ @[simp] theorem ghost_component_teichmuller (p : ℕ) {R : Type u_1} [hp : fact (nat.prime p)] [comm_ring R] (r : R) (n : ℕ) : coe_fn (ghost_component n) (coe_fn (teichmuller p) r) = r ^ p ^ n := ghost_component_teichmuller_fun p r n end Mathlib
#ifndef __NEURALNETWORK_INCLUDED__ #define __NEURALNETWORK_INCLUDED__ #ifdef __APPLE__ #include <Accelerate/Accelerate.h> #else #include <cblas.h> #endif #include <string> #include "Frame.h" using namespace std; struct Matrix { double* data; int rows; int cols; }; class NeuralNetwork { public: NeuralNetwork(string theta1_filename, string theta2_filename); ~NeuralNetwork(); double* predict(Frame* frame); private: Matrix theta1_; Matrix theta2_; }; Matrix read2DMatrixFromFile(string filename); double sigmoid(double x); #endif
[STATEMENT] lemma sorted_hd_last: "\<lbrakk>sorted l; l\<noteq>[]\<rbrakk> \<Longrightarrow> hd l \<le> last l" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>sorted l; l \<noteq> []\<rbrakk> \<Longrightarrow> hd l \<le> last l [PROOF STEP] by (metis eq_iff hd_Cons_tl last_in_set not_hd_in_tl sorted_wrt.simps(2))
$\frac{{\partial {1}}}{{\partial {2}}}$ ```python # 如果对带有一个变量或是未赋值语句的cell执行操作,Jupyter将会自动打印该变量而无需一个输出语句。 from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" #默认为'last' # display(Math(latex_s))和display(Latex(latex_s))输出的是latex类型, # display(Markdown(latex_s))输出的是markdown # 推荐markdown和Latex;而Math只支持纯latex from IPython.display import display,Latex, SVG, Math, Markdown ``` ```python 1 2 x = 3 x ``` 1 2 3 ```python s_1 = r"$\frac{{\partial {}}}{{\partial {}}}$".format(1, 2) a = 13.49 b = 2.2544223 P = 302.99 V = 90.02 s_2 = rf"""\ # xx Dims: ${a}m \times{b:5.2}m$ Area: ${P}m^2$ Volume: ${V}m^3$ """ ``` ```python # 只能作为最后一个输出,才能显示 Latex(s_1) ``` $\frac{\partial 1}{\partial 2}$ ```python tobj1_1= Markdown(s_1) tobj1_2= Math(s_1) tobj1_3= Latex(s_1) display(tobj1_1) display(tobj1_2) display(tobj1_3) ``` $\frac{\partial 1}{\partial 2}$ $\displaystyle \frac{\partial 1}{\partial 2}$ $\frac{\partial 1}{\partial 2}$ ```python tobj2_1=Markdown(s_2) tobj2_2=Math(s_2) tobj2_3= Latex(s_2) display(tobj2_1) display(tobj2_2) display(tobj2_3) ``` \ # xx Dims: $13.49m \times 2.3m$ Area: $302.99m^2$ Volume: $90.02m^3$ $\displaystyle \ # xx Dims: $13.49m \times 2.3m$ Area: $302.99m^2$ Volume: $90.02m^3$ $ \ # xx Dims: $13.49m \times 2.3m$ Area: $302.99m^2$ Volume: $90.02m^3$ ```python # https://docs.sympy.org/dev/tutorial/printing.html from sympy import MatrixSymbol, Inverse, symbols, Determinant, Trace, Derivative from sympy import sqrt,latex,Integral,pprint,init_printing x = symbols("x") y = symbols("y") s = "1+2**(x+y)" latex(eval(s)) # prints '$1 + {2}^{x + y}$' # Integral是积分的意思 print(latex(Integral(sqrt(1/x), x))) pprint(Integral(sqrt(1/x), x), use_unicode=True) ``` ```python import math import latexify # 写pi而不是math.pi,就可以了 @latexify.with_latex def f_1(x): if x==1: return 1 elif x==2: return 2 else: return f_1(x-1) + f_1(x-2) print(f_1) ``` \mathrm{f_1}(x)\triangleq \left\{ \begin{array}{ll} 1, & \mathrm{if} \ x=1 \\ 2, & \mathrm{if} \ x=2 \\ \mathrm{f_1}\left(x - 1\right) + \mathrm{f_1}\left(x - 2\right), & \mathrm{otherwise} \end{array} \right. ```python %matplotlib inline import matplotlib.pyplot as plt plt.rcParams['text.usetex'] = True plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath} \usepackage{amsfonts}' # plt.rcParams.update({ # #'font.size': 8, # #'text.usetex': True, # 'text.latex.preamble': [r'\usepackage{amsmath}', #for \text command # r'\usepackage{amsfonts}', # \mathbb is provided by the LaTeX package amsfonts # ] # }) # 参数'text.latex.preamble' or 'pgf.preamble'(这两个不是同一个参数) 以前是用数组,现在用字符串 # 罗马体 operatorname -> mbox or mathrm # https://matplotlib.org/stable/tutorials/text/mathtext.html # matplotlib.rcParams['text.latex.unicode'] = True # matplotlib.rcParams['text.latex.preamble'] = [ # '\\usepackage{CJK}', # r'\AtBeginDocument{\begin{CJK}{UTF8}{gbsn}}', # r'\AtEndDocument{\end{CJK}}', # ] # Matplotlib中文显示和Latex #import matplotlib.font_manager as mf # 导入字体管理器 #my_font= mf.FontProperties(fname='C://Windows//Fonts/simsun.ttc') # 加载字体 def show_latex(eqn:int, latex_s:str , validated:bool): fig, ax = plt.subplots(figsize=(20, 0.7)) #latex_s = r"$\alpha _ { 1 } ^ { r } \gamma _ { 1 } + \dots + \alpha _ { N } ^ { r } \gamma _ { N } = 0 \quad ( r = 1 , . . . , R ) ,$" plt.text(0.01, 0.5, "({})".format(eqn), ha='left', va='center', fontsize=20) #水平和垂直方向居中对齐 plt.text(0.5, 0.5, latex_s, ha='center', va='center', fontsize=20) if validated: plt.text(0.97, 0.5, r"ok", ha='right', va='center', fontsize=20, color = "g") else: plt.text(0.97, 0.5, r"error", ha='right', va='center', fontsize=20, color = "r") # 隐藏框线 ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) # 隐藏坐标轴的刻度信息 plt.xticks([]) plt.yticks([]) show_latex(1,s_1,True) show_latex(1,s_1,False) ```
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import analysis.inner_product_space.projection import analysis.normed_space.dual import analysis.normed_space.star.basic /-! # The Fréchet-Riesz representation theorem We consider an inner product space `E` over `𝕜`, which is either `ℝ` or `ℂ`. We define `to_dual_map`, a conjugate-linear isometric embedding of `E` into its dual, which maps an element `x` of the space to `λ y, ⟪x, y⟫`. Under the hypothesis of completeness (i.e., for Hilbert spaces), we upgrade this to `to_dual`, a conjugate-linear isometric *equivalence* of `E` onto its dual; that is, we establish the surjectivity of `to_dual_map`. This is the Fréchet-Riesz representation theorem: every element of the dual of a Hilbert space `E` has the form `λ u, ⟪x, u⟫` for some `x : E`. For a bounded sesquilinear form `B : E →L⋆[𝕜] E →L[𝕜] 𝕜`, we define a map `inner_product_space.continuous_linear_map_of_bilin B : E →L[𝕜] E`, given by substituting `E →L[𝕜] 𝕜` with `E` using `to_dual`. ## References * [M. Einsiedler and T. Ward, *Functional Analysis, Spectral Theory, and Applications*] [EinsiedlerWard2017] ## Tags dual, Fréchet-Riesz -/ noncomputable theory open_locale classical complex_conjugate universes u v namespace inner_product_space open is_R_or_C continuous_linear_map variables (𝕜 : Type*) variables (E : Type*) [is_R_or_C 𝕜] [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 E _ x y local postfix `†`:90 := star_ring_end _ /-- An element `x` of an inner product space `E` induces an element of the dual space `dual 𝕜 E`, the map `λ y, ⟪x, y⟫`; moreover this operation is a conjugate-linear isometric embedding of `E` into `dual 𝕜 E`. If `E` is complete, this operation is surjective, hence a conjugate-linear isometric equivalence; see `to_dual`. -/ def to_dual_map : E →ₗᵢ⋆[𝕜] normed_space.dual 𝕜 E := { norm_map' := λ _, innerSL_apply_norm, ..innerSL } variables {E} @[simp] lemma to_dual_map_apply {x y : E} : to_dual_map 𝕜 E x y = ⟪x, y⟫ := rfl variable (𝕜) include 𝕜 lemma ext_inner_left {x y : E} (h : ∀ v, ⟪v, x⟫ = ⟪v, y⟫) : x = y := begin apply (to_dual_map 𝕜 E).map_eq_iff.mp, ext v, rw [to_dual_map_apply, to_dual_map_apply, ←inner_conj_sym], nth_rewrite_rhs 0 [←inner_conj_sym], exact congr_arg conj (h v) end lemma ext_inner_right {x y : E} (h : ∀ v, ⟪x, v⟫ = ⟪y, v⟫) : x = y := begin refine ext_inner_left 𝕜 (λ v, _), rw [←inner_conj_sym], nth_rewrite_rhs 0 [←inner_conj_sym], exact congr_arg conj (h v) end omit 𝕜 variable {𝕜} lemma ext_inner_left_basis {ι : Type*} {x y : E} (b : basis ι 𝕜 E) (h : ∀ i : ι, ⟪b i, x⟫ = ⟪b i, y⟫) : x = y := begin apply (to_dual_map 𝕜 E).map_eq_iff.mp, refine (function.injective.eq_iff continuous_linear_map.coe_injective).mp (basis.ext b _), intro i, simp only [to_dual_map_apply, continuous_linear_map.coe_coe], rw [←inner_conj_sym], nth_rewrite_rhs 0 [←inner_conj_sym], exact congr_arg conj (h i) end lemma ext_inner_right_basis {ι : Type*} {x y : E} (b : basis ι 𝕜 E) (h : ∀ i : ι, ⟪x, b i⟫ = ⟪y, b i⟫) : x = y := begin refine ext_inner_left_basis b (λ i, _), rw [←inner_conj_sym], nth_rewrite_rhs 0 [←inner_conj_sym], exact congr_arg conj (h i) end variables (𝕜) (E) [complete_space E] /-- Fréchet-Riesz representation: any `ℓ` in the dual of a Hilbert space `E` is of the form `λ u, ⟪y, u⟫` for some `y : E`, i.e. `to_dual_map` is surjective. -/ def to_dual : E ≃ₗᵢ⋆[𝕜] normed_space.dual 𝕜 E := linear_isometry_equiv.of_surjective (to_dual_map 𝕜 E) begin intros ℓ, set Y := ker ℓ with hY, by_cases htriv : Y = ⊤, { have hℓ : ℓ = 0, { have h' := linear_map.ker_eq_top.mp htriv, rw [←coe_zero] at h', apply coe_injective, exact h' }, exact ⟨0, by simp [hℓ]⟩ }, { rw [← submodule.orthogonal_eq_bot_iff] at htriv, change Yᗮ ≠ ⊥ at htriv, rw [submodule.ne_bot_iff] at htriv, obtain ⟨z : E, hz : z ∈ Yᗮ, z_ne_0 : z ≠ 0⟩ := htriv, refine ⟨((ℓ z)† / ⟪z, z⟫) • z, _⟩, ext x, have h₁ : (ℓ z) • x - (ℓ x) • z ∈ Y, { rw [mem_ker, map_sub, map_smul, map_smul, algebra.id.smul_eq_mul, algebra.id.smul_eq_mul, mul_comm], exact sub_self (ℓ x * ℓ z) }, have h₂ : (ℓ z) * ⟪z, x⟫ = (ℓ x) * ⟪z, z⟫, { have h₃ := calc 0 = ⟪z, (ℓ z) • x - (ℓ x) • z⟫ : by { rw [(Y.mem_orthogonal' z).mp hz], exact h₁ } ... = ⟪z, (ℓ z) • x⟫ - ⟪z, (ℓ x) • z⟫ : by rw [inner_sub_right] ... = (ℓ z) * ⟪z, x⟫ - (ℓ x) * ⟪z, z⟫ : by simp [inner_smul_right], exact sub_eq_zero.mp (eq.symm h₃) }, have h₄ := calc ⟪((ℓ z)† / ⟪z, z⟫) • z, x⟫ = (ℓ z) / ⟪z, z⟫ * ⟪z, x⟫ : by simp [inner_smul_left, ring_hom.map_div, conj_conj] ... = (ℓ z) * ⟪z, x⟫ / ⟪z, z⟫ : by rw [←div_mul_eq_mul_div] ... = (ℓ x) * ⟪z, z⟫ / ⟪z, z⟫ : by rw [h₂] ... = ℓ x : begin have : ⟪z, z⟫ ≠ 0, { change z = 0 → false at z_ne_0, rwa ←inner_self_eq_zero at z_ne_0 }, field_simp [this] end, exact h₄ } end variables {𝕜} {E} @[simp] lemma to_dual_apply {x y : E} : to_dual 𝕜 E x y = ⟪x, y⟫ := rfl @[simp] lemma to_dual_symm_apply {x : E} {y : normed_space.dual 𝕜 E} : ⟪(to_dual 𝕜 E).symm y, x⟫ = y x := begin rw ← to_dual_apply, simp only [linear_isometry_equiv.apply_symm_apply], end variables {E 𝕜} /-- Maps a bounded sesquilinear form to its continuous linear map, given by interpreting the form as a map `B : E →L⋆[𝕜] normed_space.dual 𝕜 E` and dualizing the result using `to_dual`. -/ def continuous_linear_map_of_bilin (B : E →L⋆[𝕜] E →L[𝕜] 𝕜) : E →L[𝕜] E := comp (to_dual 𝕜 E).symm.to_continuous_linear_equiv.to_continuous_linear_map B local postfix `♯`:1025 := continuous_linear_map_of_bilin variables (B : E →L⋆[𝕜] E →L[𝕜] 𝕜) @[simp] lemma continuous_linear_map_of_bilin_apply (v w : E) : ⟪(B♯ v), w⟫ = B v w := by simp [continuous_linear_map_of_bilin] lemma unique_continuous_linear_map_of_bilin {v f : E} (is_lax_milgram : (∀ w, ⟪f, w⟫ = B v w)) : f = B♯ v := begin refine ext_inner_right 𝕜 _, intro w, rw continuous_linear_map_of_bilin_apply, exact is_lax_milgram w, end end inner_product_space
module btls-certs where open import Data.Word8 using (Word8) renaming (primWord8fromNat to to𝕎) open import Data.ByteString using (ByteString; Strict; Lazy; pack) open import Data.ByteString.Primitive using (∣List∣≡∣Strict∣) open import Data.ByteVec using (ByteVec) open import Data.Nat using (ℕ; zero; suc; _<_; z≤n; s≤s; _≤?_; _∸_) open import Data.Nat.DivMod using (_divMod_; result) open import Data.Fin using (Fin; toℕ) open import Data.Vec using (Vec; toList; tabulate) open import Data.List using (List; []; _∷_; length; _++_; take) open import Data.Product using (Σ; _,_; proj₁) open import Relation.Nullary using (Dec; yes; no) open import Relation.Binary.PropositionalEquality using (_≡_; refl; sym; trans) import Data.ByteString.IO as BSIO open import IO open import Function using (_∘_) open import ASN1.Util using (base256) import ASN1.BER as BER import ASN1.X509 open import Bee2.Crypto.Belt using (beltHash) open import Bee2.Crypto.Bign using (Pri; Pub; Sig; bignCalcPubkey; bignSign2) b : ℕ → List Word8 b n = toList (tabulate {n} (to𝕎 ∘ toℕ)) b256 = b 256 x : (len : ℕ) → ℕ → Σ (List Word8) (λ l → len ≡ length l) x zero n = [] , refl x (suc len) n with n divMod 256 ... | result q r _ with x len q ... | ns , refl = (to𝕎 (toℕ r) ∷ ns) , refl mkPri : ℕ → Pri mkPri n with x 32 n ... | (ns , prf) = (pack ns) , sym (trans (∣List∣≡∣Strict∣ ns (p prf 32<2³¹)) (sym prf)) where p : ∀ {u v k} → (u≡v : u ≡ v) → u < k → v < k p refl u<k = u<k 32<2³¹ : 32 < _ 32<2³¹ = s≤s (s≤s (s≤s (s≤s (s≤s (s≤s (s≤s (s≤s ( s≤s (s≤s (s≤s (s≤s (s≤s (s≤s (s≤s (s≤s ( s≤s (s≤s (s≤s (s≤s (s≤s (s≤s (s≤s (s≤s ( s≤s (s≤s (s≤s (s≤s (s≤s (s≤s (s≤s (s≤s ( s≤s z≤n)))))))))))))))))))))))))))))))) ca-pri : Pri ca-pri = mkPri 17 ca-pub : Pub ca-pub = bignCalcPubkey ca-pri sign : Pri → ByteString Strict → ByteString Strict sign pri = proj₁ ∘ bignSign2 pri ∘ beltHash ca-cert : ByteString Lazy ca-cert = BER.encode′ cert where open ASN1.X509.mkCert "issuer" "subject" "20170101000000Z" "20190101000000Z" (proj₁ ca-pub) (sign ca-pri) main = run (BSIO.writeBinaryFile "ca.pkc" ca-cert)
# generalise this into coupler-specific function abstract type AbstractCheck end struct ConservationCheck{A} <: AbstractCheck ρe_tot_atmos::A ρe_tot_slab::A end function check_conservation_callback(cs, atmos_sim, slab_sim) atmos_sim.domain.center_space.vertical_topology.mesh.domain Δz_1 = parent(ClimaCore.Fields.coordinate_field(atmos_sim.domain.face_space).z)[2] - parent(ClimaCore.Fields.coordinate_field(atmos_sim.domain.face_space).z)[1] atmos_field = atmos_sim.integrator.u.c.ρe # J slab_field = get_slab_energy(slab_sim, slab_sim.integrator.u.T_sfc) ./ Δz_1 # J [NB: sum of the boundary field inherits the depth from the first atmospheric layer, which ≂̸ slab depth] ρe_tot_atmos = sum(atmos_field) ρe_tot_slab = sum(slab_field) push!(cs.ρe_tot_atmos, ρe_tot_atmos) push!(cs.ρe_tot_slab, ρe_tot_slab) end get_slab_energy(slab_sim, T_sfc) = slab_sim.params.ρ .* slab_sim.params.c .* T_sfc .* slab_sim.params.h #[NB: upon initialisation FT(275) was subtracted from T_0] using ClimaCorePlots function plot(CS::ConservationCheck) diff_ρe_tot_atmos = CS.ρe_tot_atmos .- CS.ρe_tot_atmos[3] diff_ρe_tot_slab = (CS.ρe_tot_slab .- CS.ρe_tot_slab[3]) Plots.plot(diff_ρe_tot_atmos, label = "atmos") Plots.plot!(diff_ρe_tot_slab, label = "slab") tot = diff_ρe_tot_atmos .+ diff_ρe_tot_slab Plots.plot!(tot .- tot[1], label = "tot") end function conservation_plot(atmos_sim, slab_sim, solu_atm, solu_slab, figname = "tst_c.png") atmos_e = [sum(u.c.ρe) for u in solu_atm] # J z = parent(ClimaCore.Fields.coordinate_field(atmos_sim.domain.face_space).z) Δz_1 = z[2] - z[1] slab_e = [sum(get_slab_energy(slab_sim, u)) for u in solu_slab] # J [NB: sum of the boundary field inherits the depth from the first atmospheric layer, which ≂̸ slab depth] diff_ρe_tot_atmos = atmos_e .- atmos_e[3] diff_ρe_tot_slab = (slab_e .- slab_e[3]) Plots.plot(diff_ρe_tot_atmos, label = "atmos") Plots.plot!(diff_ρe_tot_slab, label = "slab") tot = diff_ρe_tot_atmos .+ diff_ρe_tot_slab Plots.plot!(tot .- tot[1], label = "tot", xlabel = "time [s]", ylabel = "energy(t) - energy(t=0) [s]") Plots.savefig(figname) end
#include <boost/python.hpp> #include <boost/cstdint.hpp> #include <Magick++/Drawable.h> #include <Magick++.h> using namespace boost::python; namespace { struct Magick_DrawablePolyline_Wrapper: Magick::DrawablePolyline { Magick_DrawablePolyline_Wrapper(PyObject* py_self_, const Magick::CoordinateList& p0): Magick::DrawablePolyline(p0), py_self(py_self_) {} Magick_DrawablePolyline_Wrapper(PyObject* py_self_, const Magick::DrawablePolyline& p0): Magick::DrawablePolyline(p0), py_self(py_self_) {} PyObject* py_self; }; } void __DrawablePolyline() { class_< Magick::DrawablePolyline, bases<Magick::DrawableBase>, Magick_DrawablePolyline_Wrapper >("DrawablePolyline", init< const Magick::CoordinateList& >()) .def(init< const Magick::DrawablePolyline& >()) ; }
Formal statement is: lemma pdivmod_pdivmodrel: "eucl_rel_poly p q (r, s) \<longleftrightarrow> (p div q, p mod q) = (r, s)" Informal statement is: The Euclidean relation between two polynomials $p$ and $q$ is equivalent to the equality of the quotient and remainder of $p$ divided by $q$.
/- LoVe Homework 10: Denotational Semantics -/ import .love10_denotational_semantics_demo namespace LoVe /- Denotational semantics are well suited to functional programming. In this exercise, we will study some representations of functional programs in Lean and their denotational semantics. -/ /- The `nondet` type represents functional programs that can perform nondeterministic computations: A program can choose between many different computation paths / return values. Returning no results at all is represented by `fail`, and nondeterministic choice between two alternatives (identified by the `bool` values `tt` and `ff`) is represented by `choice`. -/ inductive nondet (α : Type) : Type | pure : α → nondet | fail {} : nondet | choice : (bool → nondet) → nondet namespace nondet /- Question 1: The `nondet` Monad -/ /- The `nondet` inductive type forms a monad. The `pure` operator is `nondet.pure`; `bind` is as follows: -/ def bind {α β : Type} : nondet α → (α → nondet β) → nondet β | (pure x) f := f x | fail f := fail | (choice k) f := choice (λb, bind (k b) f) instance : has_pure nondet := { pure := @pure } instance : has_bind nondet := { bind := @bind } /- 1.1. Prove the monadic laws (lecture 6) for `nondet`. Hint: To prove `f = g` from `∀x, f x = g x`, use the theorem `funext`. -/ lemma pure_bind {α β : Type} (x : α) (f : α → nondet β) : pure x >>= f = f x := sorry lemma bind_pure {α : Type} : ∀mx : nondet α, mx >>= pure = mx := sorry lemma bind_assoc {α β γ : Type} : ∀(mx : nondet α) (f : α → nondet β) (g : β → nondet γ), ((mx >>= f) >>= g) = (mx >>= (λa, f a >>= g)) := sorry /- The function `portmanteau` computes a portmanteau of two lists: A portmanteau of `xs` and `ys` has `xs` as a prefix and `ys` as a suffix, and they overlap. We use `starts_with xs ys` to test that `ys` has `xs` as a prefix. -/ def starts_with : list ℕ → list ℕ → bool | (x :: xs) [] := ff | [] ys := tt | (x :: xs) (y :: ys) := (x = y) && starts_with xs ys #eval starts_with [1, 2] [1, 2, 3] #eval starts_with [1, 2, 3] [1, 2] def portmanteau : list ℕ → list ℕ → list (list ℕ) | [] ys := [] | (x :: xs) ys := list.map (list.cons x) (portmanteau xs ys) ++ (if starts_with (x :: xs) ys then [ys] else []) /- Here are some examples of portmanteaux: -/ #reduce portmanteau [0, 1, 2, 3] [2, 3, 4] #reduce portmanteau [0, 1] [2, 3, 4] #reduce portmanteau [0, 1, 2, 1, 2] [1, 2, 1, 2, 3, 4] /- 1.2 (**optional**). Translate the `portmanteau` program from the `list` monad to the `nondet` monad. -/ def nondet_portmanteau : list ℕ → list ℕ → nondet (list ℕ) := sorry /- Question 2: Nondeterminism, Denotationally -/ /- 2.1. Give a denotational semantics for `nondet`, mapping it into a `list` of all results. `pure` returns one result, `fail` returns zero, and `choice` combines the results of either alternative. -/ def list_sem {α : Type} : nondet α → list α := sorry /- Check that the following lines give the same output as for `portmanteau`: -/ #reduce list_sem (nondet_portmanteau [0, 1, 2, 3] [2, 3, 4]) #reduce list_sem (nondet_portmanteau [0, 1] [2, 3, 4]) #reduce list_sem (nondet_portmanteau [0, 1, 2, 1, 2] [1, 2, 1, 2, 3, 4]) /- 2.2. Often, we are not interested in getting all outcomes, just the first successful one. Give a semantics for `nondet` that produces the first successful result, if any. -/ def option_sem {α : Type} : nondet α → option α := sorry /- 2.3. Prove the theorem `list_option_compat` below, showing that the two semantics you defined are compatible. -/ lemma head'_orelse_eq_head'_append {α : Type} (xs ys : list α) : (list.head' xs <|> list.head' ys) = list.head' (xs ++ ys) := by induction xs; simp theorem list_option_compat {α : Type} : ∀mx : nondet α, option_sem mx = list.head' (list_sem mx) := sorry /- Question 3 (**optional**). Nondeterminism, Operationally -/ /- We can define the following big-step operational semantics for `nondet`: -/ inductive big_step {α : Type} : nondet α → α → Prop | pure {x : α} : big_step (pure x) x | choice_l {k : bool → nondet α} {x : α} : big_step (k ff) x → big_step (choice k) x | choice_r {k : bool → nondet α} {x : α} : big_step (k tt) x → big_step (choice k) x -- there is no case for `fail` notation mx `⟹` x := big_step mx x /- 3.1 (**optional**). Prove the following lemma. The lemma states that `choice` has the semantics of "angelic nondeterminism": If there is a computational path that leads to some `x`, the `choice` operator will produce this `x`. -/ lemma choice_existential {α : Type} (x : α) (k : bool → nondet α) : nondet.choice k ⟹ x ↔ ∃b, k b ⟹ x := sorry /- 3.2 (**optional**). Prove the compatibility between denotational and operational semantics. -/ theorem den_op_compat {α : Type} : ∀(x : α) (mx : nondet α), x ∈ list_sem mx ↔ mx ⟹ x := sorry end nondet end LoVe
Require Import CodeProofDeps. Require Import Ident. Require Import Constants. Require Import RData. Require Import EventReplay. Require Import MoverTypes. Require Import CommonLib. Require Import BaremoreSMC.Spec. Require Import AbsAccessor.Spec. Require Import RmiAux2.Layer. Require Import RmiOps.Code.granule_delegate_ops. Require Import RmiOps.LowSpecs.granule_delegate_ops. Local Open Scope Z_scope. Section CodeProof. Context `{real_params: RealParams}. Context {memb} `{Hmemx: Mem.MemoryModelX memb}. Context `{Hmwd: UseMemWithData memb}. Let mem := mwd (cdata RData). Context `{Hstencil: Stencil}. Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}. Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}. Let L : compatlayer (cdata RData) := _smc_mark_realm ↦ gensem smc_mark_realm_spec ⊕ _granule_set_state ↦ gensem granule_set_state_spec ⊕ _granule_memzero ↦ gensem granule_memzero_spec ⊕ _granule_unlock ↦ gensem granule_unlock_spec . Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L. Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L. Section BodyProof. Context `{Hwb: WritableBlockOps}. Variable (sc: stencil). Variables (ge: genv) (STENCIL_MATCHES: stencil_matches sc ge). Variable b_smc_mark_realm: block. Hypothesis h_smc_mark_realm_s : Genv.find_symbol ge _smc_mark_realm = Some b_smc_mark_realm. Hypothesis h_smc_mark_realm_p : Genv.find_funct_ptr ge b_smc_mark_realm = Some (External (EF_external _smc_mark_realm (signature_of_type (Tcons tulong Tnil) tvoid cc_default)) (Tcons tulong Tnil) tvoid cc_default). Local Opaque smc_mark_realm_spec. Variable b_granule_set_state: block. Hypothesis h_granule_set_state_s : Genv.find_symbol ge _granule_set_state = Some b_granule_set_state. Hypothesis h_granule_set_state_p : Genv.find_funct_ptr ge b_granule_set_state = Some (External (EF_external _granule_set_state (signature_of_type (Tcons Tptr (Tcons tuint Tnil)) tvoid cc_default)) (Tcons Tptr (Tcons tuint Tnil)) tvoid cc_default). Local Opaque granule_set_state_spec. Variable b_granule_memzero: block. Hypothesis h_granule_memzero_s : Genv.find_symbol ge _granule_memzero = Some b_granule_memzero. Hypothesis h_granule_memzero_p : Genv.find_funct_ptr ge b_granule_memzero = Some (External (EF_external _granule_memzero (signature_of_type (Tcons Tptr (Tcons tuint Tnil)) tvoid cc_default)) (Tcons Tptr (Tcons tuint Tnil)) tvoid cc_default). Local Opaque granule_memzero_spec. Variable b_granule_unlock: block. Hypothesis h_granule_unlock_s : Genv.find_symbol ge _granule_unlock = Some b_granule_unlock. Hypothesis h_granule_unlock_p : Genv.find_funct_ptr ge b_granule_unlock = Some (External (EF_external _granule_unlock (signature_of_type (Tcons Tptr Tnil) tvoid cc_default)) (Tcons Tptr Tnil) tvoid cc_default). Local Opaque granule_unlock_spec. Lemma granule_delegate_ops_body_correct: forall m d d' env le g_base g_offset addr (Henv: env = PTree.empty _) (Hinv: high_level_invariant d) (HPTg: PTree.get _g le = Some (Vptr g_base (Int.repr g_offset))) (HPTaddr: PTree.get _addr le = Some (Vlong addr)) (Hspec: granule_delegate_ops_spec0 (g_base, g_offset) (VZ64 (Int64.unsigned addr)) d = Some d'), exists le', (exec_stmt ge env le ((m, d): mem) granule_delegate_ops_body E0 le' (m, d') Out_normal). Proof. solve_code_proof Hspec granule_delegate_ops_body; eexists; solve_proof_low. Qed. End BodyProof. End CodeProof.
(* Title: thys/StrongCopyTM.thy Author: Franz Regensburger (FABR) 02/2022 *) subsubsection \<open>A Turing machine that duplicates its input iff the input is a single numeral\<close> theory StrongCopyTM imports WeakCopyTM begin text \<open>If we run \<open>tm_strong_copy\<close> on a single numeral, it behaves like the original weak version \<open>tm_weak_copy\<close>. However, if we run the strong machine on an empty list, the result is an empty list. If we run the machine on a list with more than two numerals, this strong variant will just return the first numeral of the list (a singleton list). Thus, the result will be a list of two numerals only if we run it on a singleton list. This is exactly the property, we need for the reduction of problem \<open>K1\<close> to problem \<open>H1\<close>. \<close> (* ---------- tm_skip_first_arg ---------- *) (* let tm_skip_first_arg = from_raw [ (L,0),(R,2), -- 1 on Bk stop and delegate to tm_erase_right_then_dblBk_left, on Oc investigate further (R,3),(R,2), -- 2 'go right until Bk': on Bk check for further args, on Oc continue loop 'go right until Bk' (L,4),(WO,0), -- 3 on 2nd Bk go for OK path, on Oc delegate to tm_erase_right_then_dblBk_left -- (L,5),(L,5), -- 4 skip 1st Bk -- (R,0),(L,5) -- 5 'go left until Bk': on 2nd Bk stop, on Oc continue loop 'go left until Bk' ] *) definition tm_skip_first_arg :: "instr list" where "tm_skip_first_arg \<equiv> [ (L,0),(R,2), (R,3),(R,2), (L,4),(WO,0), (L,5),(L,5), (R,0),(L,5) ]" (* Prove partial correctness and termination for tm_skip_first_arg *) (* ERROR case: length nl = 0 *) lemma tm_skip_first_arg_correct_Nil: "\<lbrace>\<lambda>tap. tap = ([], [])\<rbrace> tm_skip_first_arg \<lbrace>\<lambda>tap. tap = ([], [Bk]) \<rbrace>" proof - have "steps0 (1, [], []) tm_skip_first_arg 1 = (0::nat, [], [Bk])" by (simp add: step.simps steps.simps numeral_eqs_upto_12 tm_skip_first_arg_def) then show ?thesis by (smt Hoare_haltI holds_for.simps is_final_eq) qed corollary tm_skip_first_arg_correct_Nil': "length nl = 0 \<Longrightarrow> \<lbrace>\<lambda>tap. tap = ([], <nl::nat list> )\<rbrace> tm_skip_first_arg \<lbrace>\<lambda>tap. tap = ([], [Bk]) \<rbrace>" using tm_skip_first_arg_correct_Nil by (simp add: tm_skip_first_arg_correct_Nil ) (* OK cases: length nl = 1 *) (* ctxrunTM tm_skip_first_arg (1, [], [Oc]) 0: [] _1_ [Oc] => 1: [Oc] _2_ [] => 2: [Oc,Bk] _3_ [] => 3: [Oc] _4_ [Bk] => 4: [] _5_ [Oc,Bk] => 5: [] _5_ [Bk,Oc,Bk] => 6: [Bk] _0_ [Oc,Bk] ctxrunTM tm_skip_first_arg (1, [], [Oc, Oc, Oc, Oc]) 0: [] _1_ [Oc,Oc,Oc,Oc] => 1: [Oc] _2_ [Oc,Oc,Oc] => 2: [Oc,Oc] _2_ [Oc,Oc] => 3: [Oc,Oc,Oc] _2_ [Oc] => 4: [Oc,Oc,Oc,Oc] _2_ [] => 5: [Oc,Oc,Oc,Oc,Bk] _3_ [] => 6: [Oc,Oc,Oc,Oc] _4_ [Bk] => 7: [Oc,Oc,Oc] _5_ [Oc,Bk] => 8: [Oc,Oc] _5_ [Oc,Oc,Bk] => 9: [Oc] _5_ [Oc,Oc,Oc,Bk] => 10: [] _5_ [Oc,Oc,Oc,Oc,Bk] => 11: [] _5_ [Bk,Oc,Oc,Oc,Oc,Bk] => 12: [Bk] _0_ [Oc,Oc,Oc,Oc,Bk] *) fun inv_tm_skip_first_arg_len_eq_1_s0 :: "nat \<Rightarrow> tape \<Rightarrow> bool" and inv_tm_skip_first_arg_len_eq_1_s1 :: "nat \<Rightarrow> tape \<Rightarrow> bool" and inv_tm_skip_first_arg_len_eq_1_s2 :: "nat \<Rightarrow> tape \<Rightarrow> bool" and inv_tm_skip_first_arg_len_eq_1_s3 :: "nat \<Rightarrow> tape \<Rightarrow> bool" and inv_tm_skip_first_arg_len_eq_1_s4 :: "nat \<Rightarrow> tape \<Rightarrow> bool" and inv_tm_skip_first_arg_len_eq_1_s5 :: "nat \<Rightarrow> tape \<Rightarrow> bool" where "inv_tm_skip_first_arg_len_eq_1_s0 n (l, r) = ( l = [Bk] \<and> r = Oc \<up> (Suc n) @ [Bk])" | "inv_tm_skip_first_arg_len_eq_1_s1 n (l, r) = ( l = [] \<and> r = Oc \<up> Suc n)" | "inv_tm_skip_first_arg_len_eq_1_s2 n (l, r) = (\<exists>n1 n2. l = Oc \<up> (Suc n1) \<and> r = Oc \<up> n2 \<and> Suc n1 + n2 = Suc n)" | "inv_tm_skip_first_arg_len_eq_1_s3 n (l, r) = ( l = Bk # Oc \<up> (Suc n) \<and> r = [])" | "inv_tm_skip_first_arg_len_eq_1_s4 n (l, r) = ( l = Oc \<up> (Suc n) \<and> r = [Bk])" | "inv_tm_skip_first_arg_len_eq_1_s5 n (l, r) = (\<exists>n1 n2. (l = Oc \<up> Suc n1 \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n1 + Suc n2 = Suc n) \<or> (l = [] \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n) \<or> (l = [] \<and> r = Bk # Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n) )" fun inv_tm_skip_first_arg_len_eq_1 :: "nat \<Rightarrow> config \<Rightarrow> bool" where "inv_tm_skip_first_arg_len_eq_1 n (s, tap) = (if s = 0 then inv_tm_skip_first_arg_len_eq_1_s0 n tap else if s = 1 then inv_tm_skip_first_arg_len_eq_1_s1 n tap else if s = 2 then inv_tm_skip_first_arg_len_eq_1_s2 n tap else if s = 3 then inv_tm_skip_first_arg_len_eq_1_s3 n tap else if s = 4 then inv_tm_skip_first_arg_len_eq_1_s4 n tap else if s = 5 then inv_tm_skip_first_arg_len_eq_1_s5 n tap else False)" lemma tm_skip_first_arg_len_eq_1_cases: fixes s::nat assumes "inv_tm_skip_first_arg_len_eq_1 n (s,l,r)" and "s=0 \<Longrightarrow> P" and "s=1 \<Longrightarrow> P" and "s=2 \<Longrightarrow> P" and "s=3 \<Longrightarrow> P" and "s=4 \<Longrightarrow> P" and "s=5 \<Longrightarrow> P" shows "P" proof - have "s < 6" proof (rule ccontr) assume "\<not> s < 6" with \<open>inv_tm_skip_first_arg_len_eq_1 n (s,l,r)\<close> show False by auto qed then have "s = 0 \<or> s = 1 \<or> s = 2 \<or> s = 3 \<or> s = 4 \<or> s = 5" by auto with assms show ?thesis by auto qed lemma inv_tm_skip_first_arg_len_eq_1_step: assumes "inv_tm_skip_first_arg_len_eq_1 n cf" shows "inv_tm_skip_first_arg_len_eq_1 n (step0 cf tm_skip_first_arg)" proof (cases cf) case (fields s l r) then have cf_cases: "cf = (s, l, r)" . show "inv_tm_skip_first_arg_len_eq_1 n (step0 cf tm_skip_first_arg)" proof (rule tm_skip_first_arg_len_eq_1_cases) from cf_cases and assms show "inv_tm_skip_first_arg_len_eq_1 n (s, l, r)" by auto next assume "s = 0" with cf_cases and assms show ?thesis by (auto simp add: tm_skip_first_arg_def) next assume "s = 1" show ?thesis proof - have "inv_tm_skip_first_arg_len_eq_1 n (step0 (1, l, r) tm_skip_first_arg)" proof (cases r) case Nil then have "r = []" . with assms and cf_cases and \<open>s = 1\<close> show ?thesis by (auto simp add: tm_skip_first_arg_def step.simps steps.simps) next case (Cons a rs) then have "r = a # rs" . show ?thesis proof (cases a) next case Bk then have "a = Bk" . with assms and \<open>r = a # rs\<close> and cf_cases and \<open>s = 1\<close> show ?thesis by (auto simp add: tm_skip_first_arg_def step.simps steps.simps) next case Oc then have "a = Oc" . with assms and \<open>r = a # rs\<close> and cf_cases and \<open>s = 1\<close> show ?thesis by (auto simp add: tm_skip_first_arg_def step.simps steps.simps) qed qed with cf_cases and \<open>s=1\<close> show ?thesis by auto qed next assume "s = 2" show ?thesis proof - have "inv_tm_skip_first_arg_len_eq_1 n (step0 (2, l, r) tm_skip_first_arg)" proof (cases r) case Nil then have "r = []" . with assms and cf_cases and \<open>s = 2\<close> have "inv_tm_skip_first_arg_len_eq_1_s2 n (l, r)" by auto then have "(\<exists>n1 n2. l = Oc \<up> (Suc n1) \<and> r = Oc \<up> n2 \<and> Suc n1 + n2 = Suc n)" by (auto simp add: tm_skip_first_arg_def step.simps steps.simps) then obtain n1 n2 where w_n1_n2: "l = Oc \<up> (Suc n1) \<and> r = Oc \<up> n2 \<and> Suc n1 + n2 = Suc n" by blast with \<open>r = []\<close> have "n2 = 0" by auto then have "step0 (2, Oc \<up> (Suc n1), Oc \<up> n2) tm_skip_first_arg = (3, Bk # Oc \<up> (Suc n1), [])" by (simp add: tm_skip_first_arg_def step.simps steps.simps numeral_eqs_upto_12) moreover with \<open>n2 = 0\<close> and w_n1_n2 have "inv_tm_skip_first_arg_len_eq_1 n (3, Bk # Oc \<up> (Suc n1), [])" by fastforce ultimately show ?thesis using w_n1_n2 by auto next case (Cons a rs) then have "r = a # rs" . show ?thesis proof (cases a) case Bk (* not possible due to invariant in state 2 *) then have "a = Bk" . with assms and \<open>r = a # rs\<close> and cf_cases and \<open>s = 2\<close> show ?thesis by (auto simp add: tm_skip_first_arg_def step.simps steps.simps) next case Oc then have "a = Oc" . with assms and cf_cases and \<open>s = 2\<close> have "inv_tm_skip_first_arg_len_eq_1_s2 n (l, r)" by auto then have "\<exists>n1 n2. l = Oc \<up> (Suc n1) \<and> r = Oc \<up> n2 \<and> Suc n1 + n2 = Suc n" by (auto simp add: tm_skip_first_arg_def step.simps steps.simps) then obtain n1 n2 where w_n1_n2: "l = Oc \<up> (Suc n1) \<and> r = Oc \<up> n2 \<and> Suc n1 + n2 = Suc n" by blast with \<open>r = a # rs\<close> and \<open>a = Oc\<close> have "Oc # rs = Oc \<up> n2" by auto then have "n2 > 0" by (meson Cons_replicate_eq) then have "step0 (2, Oc \<up> (Suc n1), Oc \<up> n2) tm_skip_first_arg = (2, Oc # Oc \<up> (Suc n1), Oc \<up> (n2-1))" by (simp add: tm_skip_first_arg_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_skip_first_arg_len_eq_1 n (2, Oc # Oc \<up> (Suc n1), Oc \<up> (n2-1))" proof - from \<open>n2 > 0\<close> and w_n1_n2 have "Oc # Oc \<up> (Suc n1) = Oc \<up> (Suc (Suc n1)) \<and> Oc \<up> (n2-1) = Oc \<up> (n2-1) \<and> Suc (Suc n1) + (n2-1) = Suc n" by auto then have "(\<exists>n1' n2'. Oc # Oc \<up> (Suc n1) = Oc \<up> (Suc n1') \<and> Oc \<up> (n2-1) = Oc \<up> n2' \<and> Suc n1' + n2' = Suc n)" by auto then show "inv_tm_skip_first_arg_len_eq_1 n (2, Oc # Oc \<up> (Suc n1), Oc \<up> (n2-1))" by auto qed ultimately show ?thesis using assms and \<open>r = a # rs\<close> and cf_cases and \<open>s = 2\<close> and w_n1_n2 by auto qed qed with cf_cases and \<open>s=2\<close> show ?thesis by auto qed next assume "s = 3" show ?thesis proof - have "inv_tm_skip_first_arg_len_eq_1 n (step0 (3, l, r) tm_skip_first_arg)" proof (cases r) case Nil then have "r = []" . with assms and cf_cases and \<open>s = 3\<close> have "inv_tm_skip_first_arg_len_eq_1_s3 n (l, r)" by auto then have "l = Bk # Oc \<up> (Suc n) \<and> r = []" by auto then have "step0 (3, Bk # Oc \<up> (Suc n), []) tm_skip_first_arg = (4, Oc \<up> (Suc n), [Bk])" by (simp add: tm_skip_first_arg_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_skip_first_arg_len_eq_1 n (4, Oc \<up> (Suc n), [Bk])" by fastforce ultimately show ?thesis using \<open>l = Bk # Oc \<up> (Suc n) \<and> r = []\<close> by auto next case (Cons a rs) (* not possible due to invariant in state 3 *) then have "r = a # rs" . with assms and cf_cases and \<open>s = 3\<close> have "inv_tm_skip_first_arg_len_eq_1_s3 n (l, r)" by auto then have "l = Bk # Oc \<up> (Suc n) \<and> r = []" by auto with \<open>r = a # rs\<close> have False by auto then show ?thesis by auto qed with cf_cases and \<open>s=3\<close> show ?thesis by auto qed next assume "s = 4" show ?thesis proof - have "inv_tm_skip_first_arg_len_eq_1 n (step0 (4, l, r) tm_skip_first_arg)" proof (cases r) case Nil (* not possible due to invariant in state 4 *) then have "r = []" . with assms and cf_cases and \<open>s = 4\<close> show ?thesis by (auto simp add: tm_skip_first_arg_def step.simps steps.simps) next case (Cons a rs) then have "r = a # rs" . show ?thesis proof (cases a) next case Bk then have "a = Bk" . with assms and \<open>r = a # rs\<close> and cf_cases and \<open>s = 4\<close> have "inv_tm_skip_first_arg_len_eq_1_s4 n (l, r)" by auto then have "l = Oc \<up> (Suc n) \<and> r = [Bk]" by auto then have F0: "step0 (4, Oc \<up> (Suc n), [Bk]) tm_skip_first_arg = (5, Oc \<up> n, Oc \<up> (Suc 0) @ [Bk])" by (simp add: tm_skip_first_arg_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_skip_first_arg_len_eq_1_s5 n (Oc \<up> n, Oc \<up> (Suc 0) @ [Bk])" proof (cases n) case 0 then have "n=0" . then have "inv_tm_skip_first_arg_len_eq_1_s5 0 ([], Oc \<up> (Suc 0) @ [Bk])" by auto moreover with \<open>n=0\<close> have "(5, Oc \<up> n, Oc \<up> (Suc 0) @ [Bk]) = (5, [], Oc \<up> (Suc 0) @ [Bk])" by auto ultimately show ?thesis by auto next case (Suc n') then have "n = Suc n'" . then have "(5, Oc \<up> n, Oc \<up> (Suc 0) @ [Bk]) = (5, Oc \<up> Suc n', Oc \<up> (Suc 0) @ [Bk])" by auto with \<open>n=Suc n'\<close> have "Suc n' + Suc 0 = Suc n" by arith then have "(Oc \<up> Suc n' = Oc \<up> Suc n' \<and> Oc \<up> (Suc 0) @ [Bk] = Oc \<up> Suc 0 @ [Bk] \<and> Suc n' + Suc 0 = Suc n)" by auto with \<open>(5, Oc \<up> n, Oc \<up> (Suc 0) @ [Bk]) = (5, Oc \<up> Suc n', Oc \<up> (Suc 0) @ [Bk])\<close> show ?thesis by (simp add: Suc \<open>Suc n' + Suc 0 = Suc n\<close>) qed then have "inv_tm_skip_first_arg_len_eq_1 n (5, Oc \<up> n, Oc \<up> (Suc 0) @ [Bk])" by auto ultimately show ?thesis using \<open>l = Oc \<up> (Suc n) \<and> r = [Bk]\<close> by auto next case Oc (* not possible due to invariant in state 4 *) then have "a = Oc" . with assms and \<open>r = a # rs\<close> and cf_cases and \<open>s = 4\<close> show ?thesis by (auto simp add: tm_skip_first_arg_def step.simps steps.simps) qed qed with cf_cases and \<open>s=4\<close> show ?thesis by auto qed next assume "s = 5" show ?thesis proof - have "inv_tm_skip_first_arg_len_eq_1 n (step0 (5, l, r) tm_skip_first_arg)" proof (cases r) case Nil (* not possible due to invariant in state 5 *) then have "r = []" . with assms and cf_cases and \<open>s = 5\<close> show ?thesis by (auto simp add: tm_skip_first_arg_def step.simps steps.simps) next case (Cons a rs) then have "r = a # rs" . show ?thesis proof (cases a) case Bk then have "a = Bk" . with assms and \<open>r = a # rs\<close> and cf_cases and \<open>s = 5\<close> have "inv_tm_skip_first_arg_len_eq_1_s5 n (l, r)" by auto then have "\<exists>n1 n2. (l = Oc \<up> Suc n1 \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n1 + Suc n2 = Suc n) \<or> (l = [] \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n) \<or> (l = [] \<and> r = Bk # Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n)" by (auto simp add: tm_skip_first_arg_def step.simps steps.simps) then obtain n1 n2 where w_n1_n2: "(l = Oc \<up> Suc n1 \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n1 + Suc n2 = Suc n) \<or> (l = [] \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n) \<or> (l = [] \<and> r = Bk # Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n)" by blast with \<open>a = Bk\<close> and \<open>r = a # rs\<close> have "l = [] \<and> r = Bk # Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n" by auto then have "step0 (5, [], Bk#Oc \<up> Suc n2 @ [Bk]) tm_skip_first_arg = (0, [Bk], Oc \<up> Suc n2 @ [Bk])" by (simp add: tm_skip_first_arg_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_skip_first_arg_len_eq_1 n (0, [Bk], Oc \<up> Suc n @ [Bk])" proof - have "inv_tm_skip_first_arg_len_eq_1_s0 n ([Bk], Oc \<up> Suc n @ [Bk])" by (simp) then show "inv_tm_skip_first_arg_len_eq_1 n (0, [Bk], Oc \<up> Suc n @ [Bk])" by auto qed ultimately show ?thesis using assms and \<open>a = Bk\<close> and \<open>r = a # rs\<close> and cf_cases and \<open>s = 5\<close> and \<open>l = [] \<and> r = Bk # Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n\<close> by (simp) next case Oc then have "a = Oc" . with assms and \<open>r = a # rs\<close> and cf_cases and \<open>s = 5\<close> have "inv_tm_skip_first_arg_len_eq_1_s5 n (l, r)" by auto then have "\<exists>n1 n2. (l = Oc \<up> Suc n1 \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n1 + Suc n2 = Suc n) \<or> (l = [] \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n) \<or> (l = [] \<and> r = Bk # Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n)" by (auto simp add: tm_skip_first_arg_def step.simps steps.simps) then obtain n1 n2 where w_n1_n2: "(l = Oc \<up> Suc n1 \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n1 + Suc n2 = Suc n) \<or> (l = [] \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n) \<or> (l = [] \<and> r = Bk # Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n)" by blast with \<open>a = Oc\<close> and \<open>r = a # rs\<close> have "(l = Oc \<up> Suc n1 \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n1 + Suc n2 = Suc n) \<or> (l = [] \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n)" by auto then show ?thesis proof assume "l = Oc \<up> Suc n1 \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n1 + Suc n2 = Suc n" then have "step0 (5, l, r) tm_skip_first_arg = (5, Oc \<up> n1 , Oc \<up> Suc (Suc n2) @ [Bk])" by (simp add: tm_skip_first_arg_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_skip_first_arg_len_eq_1 n (5, Oc \<up> n1 , Oc \<up> Suc (Suc n2) @ [Bk])" proof - from \<open>l = Oc \<up> Suc n1 \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n1 + Suc n2 = Suc n\<close> have "inv_tm_skip_first_arg_len_eq_1_s5 n (Oc \<up> n1, Oc \<up> Suc (Suc n2) @ [Bk])" by (cases n1) auto then show "inv_tm_skip_first_arg_len_eq_1 n (5, Oc \<up> n1 , Oc \<up> Suc (Suc n2) @ [Bk])" by auto qed ultimately show "inv_tm_skip_first_arg_len_eq_1 n (step0 (5, l, r) tm_skip_first_arg)" by auto next assume "l = [] \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n" then have "step0 (5, l, r) tm_skip_first_arg = (5, [], Bk # Oc \<up> Suc n2 @ [Bk])" by (simp add: tm_skip_first_arg_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_skip_first_arg_len_eq_1 n (step0 (5, l, r) tm_skip_first_arg)" proof - from \<open>l = [] \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n\<close> have "inv_tm_skip_first_arg_len_eq_1_s5 n (l, r)" by simp then show "inv_tm_skip_first_arg_len_eq_1 n (step0 (5, l, r) tm_skip_first_arg)" using \<open>l = [] \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n\<close> and \<open>step0 (5, l, r) tm_skip_first_arg = (5, [], Bk # Oc \<up> Suc n2 @ [Bk])\<close> by simp qed ultimately show ?thesis using assms and \<open>a = Oc\<close> and \<open>r = a # rs\<close> and cf_cases and \<open>s = 5\<close> and \<open>l = [] \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n\<close> by (simp ) qed qed qed with cf_cases and \<open>s=5\<close> show ?thesis by auto qed qed qed lemma inv_tm_skip_first_arg_len_eq_1_steps: assumes "inv_tm_skip_first_arg_len_eq_1 n cf" shows "inv_tm_skip_first_arg_len_eq_1 n (steps0 cf tm_skip_first_arg stp)" proof (induct stp) case 0 with assms show ?case by (auto simp add: inv_tm_skip_first_arg_len_eq_1_step step.simps steps.simps) next case (Suc stp) with assms show ?case using inv_tm_skip_first_arg_len_eq_1_step step_red by auto qed lemma tm_skip_first_arg_len_eq_1_partial_correctness: assumes "\<exists>stp. is_final (steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp)" shows "\<lbrace> \<lambda>tap. tap = ([], <[n::nat]>) \<rbrace> tm_skip_first_arg \<lbrace> \<lambda>tap. tap = ([Bk], <[n::nat]> @[Bk]) \<rbrace>" proof (rule Hoare_consequence) show "(\<lambda>tap. tap = ([], <[n::nat]>)) \<mapsto> (\<lambda>tap. tap = ([], <[n::nat]>))" by auto next show "inv_tm_skip_first_arg_len_eq_1_s0 n \<mapsto> (\<lambda>tap. tap = ([Bk], <[n::nat]> @ [Bk]))" by (simp add: assert_imp_def tape_of_list_def tape_of_nat_def) next show "\<lbrace>\<lambda>tap. tap = ([], <[n]>)\<rbrace> tm_skip_first_arg \<lbrace>inv_tm_skip_first_arg_len_eq_1_s0 n\<rbrace>" proof (rule Hoare_haltI) fix l::"cell list" fix r:: "cell list" assume major: "(l, r) = ([], <[n]>)" show "\<exists>stp. is_final (steps0 (1, l, r) tm_skip_first_arg stp) \<and> inv_tm_skip_first_arg_len_eq_1_s0 n holds_for steps0 (1, l, r) tm_skip_first_arg stp" proof - from major and assms have "\<exists>stp. is_final (steps0 (1, l, r) tm_skip_first_arg stp)" by auto then obtain stp where w_stp: "is_final (steps0 (1, l, r) tm_skip_first_arg stp)" by blast moreover have "inv_tm_skip_first_arg_len_eq_1_s0 n holds_for steps0 (1, l, r) tm_skip_first_arg stp" proof - have "inv_tm_skip_first_arg_len_eq_1 n (1, l, r)" by (simp add: major tape_of_list_def tape_of_nat_def) then have "inv_tm_skip_first_arg_len_eq_1 n (steps0 (1, l, r) tm_skip_first_arg stp)" using inv_tm_skip_first_arg_len_eq_1_steps by auto then show ?thesis by (smt holds_for.elims(3) inv_tm_skip_first_arg_len_eq_1.simps is_final_eq w_stp) qed ultimately show ?thesis by auto qed qed qed (* --- now, we prove termination of tm_skip_first_arg on singleton lists --- *) (* Lexicographic orders (See List.measures) quote: "These are useful for termination proofs" lemma in_measures[simp]: "(x, y) \<in> measures [] = False" "(x, y) \<in> measures (f # fs) = (f x < f y \<or> (f x = f y \<and> (x, y) \<in> measures fs))" *) (* Assemble a lexicographic measure function *) definition measure_tm_skip_first_arg_len_eq_1 :: "(config \<times> config) set" where "measure_tm_skip_first_arg_len_eq_1 = measures [ \<lambda>(s, l, r). (if s = 0 then 0 else 5 - s), \<lambda>(s, l, r). (if s = 2 then length r else 0), \<lambda>(s, l, r). (if s = 5 then length l + (if hd r = Oc then 2 else 1) else 0) ]" lemma wf_measure_tm_skip_first_arg_len_eq_1: "wf measure_tm_skip_first_arg_len_eq_1" unfolding measure_tm_skip_first_arg_len_eq_1_def by (auto) lemma measure_tm_skip_first_arg_len_eq_1_induct [case_names Step]: "\<lbrakk>\<And>n. \<not> P (f n) \<Longrightarrow> (f (Suc n), (f n)) \<in> measure_tm_skip_first_arg_len_eq_1\<rbrakk> \<Longrightarrow> \<exists>n. P (f n)" using wf_measure_tm_skip_first_arg_len_eq_1 by (metis wf_iff_no_infinite_down_chain) (* Machine tm_skip_first_arg always halts on a singleton list *) lemma tm_skip_first_arg_len_eq_1_halts: "\<exists>stp. is_final (steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp)" proof (induct rule: measure_tm_skip_first_arg_len_eq_1_induct) case (Step stp) then have not_final: "\<not> is_final (steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp)" . have INV: "inv_tm_skip_first_arg_len_eq_1 n (steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp)" proof (rule_tac inv_tm_skip_first_arg_len_eq_1_steps) show "inv_tm_skip_first_arg_len_eq_1 n (1, [], <[n::nat]>)" by (simp add: tape_of_list_def tape_of_nat_def ) qed have SUC_STEP_RED: "steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp) = step0 (steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp) tm_skip_first_arg" by (rule step_red) show "( steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp), steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp ) \<in> measure_tm_skip_first_arg_len_eq_1" proof (cases "steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp") case (fields s l r) then have cf_cases: "steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (s, l, r)" . show ?thesis proof (rule tm_skip_first_arg_len_eq_1_cases) from INV and cf_cases show "inv_tm_skip_first_arg_len_eq_1 n (s, l, r)" by auto next assume "s=0" (* not possible *) with cf_cases not_final show ?thesis by auto next assume "s=1" show ?thesis proof (cases r) case Nil then have "r = []" . with cf_cases and \<open>s=1\<close> have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (1, l, [])" by auto with INV have False by auto (* not possible due to invariant in s=1 *) then show ?thesis by auto next case (Cons a rs) then have "r = a # rs" . show ?thesis proof (cases "a") case Bk then have "a=Bk" . with cf_cases and \<open>s=1\<close> and \<open>r = a # rs\<close> have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (1, l, Bk#rs)" by auto with INV have False by auto (* not possible due to invariant in s=1 *) then show ?thesis by auto next case Oc then have "a=Oc" . with cf_cases and \<open>s=1\<close> and \<open>r = a # rs\<close> have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (1, l, Oc#rs)" by auto with SUC_STEP_RED have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp) = step0 (1, l, Oc#rs) tm_skip_first_arg" by auto also have "... = (2,Oc#l,rs)" by (auto simp add: tm_skip_first_arg_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp) = (2,Oc#l,rs)" by auto with \<open>steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (1, l, Oc#rs)\<close> show ?thesis by (auto simp add: measure_tm_skip_first_arg_len_eq_1_def) qed qed next assume "s=2" show ?thesis proof - from cf_cases and \<open>s=2\<close> have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (2, l, r)" by auto with cf_cases and \<open>s=2\<close> and INV have "(\<exists>n1 n2. l = Oc \<up> (Suc n1) \<and> r = Oc \<up> n2 \<and> Suc n1 + n2 = Suc n)" by auto then have "(\<exists>n2. r = Oc \<up> n2)" by blast then obtain n2 where w_n2: "r = Oc \<up> n2" by blast show ?thesis proof (cases n2) case 0 then have "n2 = 0" . with w_n2 have "r = []" by auto with \<open>steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (2, l, r)\<close> have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (2, l, [])" by auto with SUC_STEP_RED have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp) = step0 (2, l, []) tm_skip_first_arg" by auto also have "... = (3,Bk#l,[])" by (auto simp add: tm_skip_first_arg_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp) = (3,Bk#l,[])" by auto with \<open>steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (2, l, [])\<close> show ?thesis by (auto simp add: measure_tm_skip_first_arg_len_eq_1_def) next case (Suc n2') then have "n2 = Suc n2'" . with w_n2 have "r = Oc \<up> Suc n2'" by auto with \<open>steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (2, l, r)\<close> have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (2, l, Oc#Oc \<up> n2')" by auto with SUC_STEP_RED have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp) = step0 (2, l, Oc#Oc \<up> n2') tm_skip_first_arg" by auto also have "... = (2,Oc#l,Oc \<up> n2')" by (auto simp add: tm_skip_first_arg_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp) = (2,Oc#l,Oc \<up> n2')" by auto with \<open>steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (2, l, Oc#Oc \<up> n2')\<close> show ?thesis by (auto simp add: measure_tm_skip_first_arg_len_eq_1_def) qed qed next assume "s=3" show ?thesis proof - from cf_cases and \<open>s=3\<close> have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (3, l, r)" by auto with cf_cases and \<open>s=3\<close> and INV have "l = Bk # Oc \<up> (Suc n) \<and> r = []" by auto with \<open>steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (3, l, r)\<close> have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (3, Bk # Oc \<up> (Suc n), [])" by auto with SUC_STEP_RED have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp) = step0 (3, Bk # Oc \<up> (Suc n), []) tm_skip_first_arg" by auto also have "... = (4,Oc \<up> (Suc n),[Bk])" by (auto simp add: tm_skip_first_arg_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp) = (4,Oc \<up> (Suc n),[Bk])" by auto with \<open>steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (3, Bk # Oc \<up> (Suc n), [])\<close> show ?thesis by (auto simp add: measure_tm_skip_first_arg_len_eq_1_def) qed next assume "s=4" show ?thesis proof - from cf_cases and \<open>s=4\<close> have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (4, l, r)" by auto with cf_cases and \<open>s=4\<close> and INV have "l = Oc \<up> (Suc n) \<and> r = [Bk]" by auto with \<open>steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (4, l, r)\<close> have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (4, Oc \<up> (Suc n), [Bk])" by auto with SUC_STEP_RED have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp) = step0 (4, Oc \<up> (Suc n), [Bk]) tm_skip_first_arg" by auto also have "... = (5,Oc \<up> n,[Oc, Bk])" by (auto simp add: tm_skip_first_arg_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp) = (5,Oc \<up> n,[Oc, Bk])" by auto with \<open>steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (4, Oc \<up> (Suc n), [Bk])\<close> show ?thesis by (auto simp add: measure_tm_skip_first_arg_len_eq_1_def) qed next assume "s=5" show ?thesis proof - from cf_cases and \<open>s=5\<close> have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (5, l, r)" by auto with cf_cases and \<open>s=5\<close> and INV have "(\<exists>n1 n2. (l = Oc \<up> Suc n1 \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n1 + Suc n2 = Suc n) \<or> (l = [] \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n) \<or> (l = [] \<and> r = Bk # Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n) )" by auto then obtain n1 n2 where w_n1_n2: "(l = Oc \<up> Suc n1 \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n1 + Suc n2 = Suc n) \<or> (l = [] \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n) \<or> (l = [] \<and> r = Bk # Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n)" by blast then show ?thesis proof assume "l = Oc \<up> Suc n1 \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n1 + Suc n2 = Suc n" with \<open>steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (5, l, r)\<close> have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (5, Oc \<up> Suc n1, Oc \<up> Suc n2 @ [Bk])" by auto with SUC_STEP_RED have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp) = step0 (5, Oc \<up> Suc n1, Oc \<up> Suc n2 @ [Bk]) tm_skip_first_arg" by auto also have "... = (5,Oc \<up> n1,Oc#Oc \<up> Suc n2 @ [Bk])" by (auto simp add: tm_skip_first_arg_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp) = (5,Oc \<up> n1,Oc#Oc \<up> Suc n2 @ [Bk])" by auto with \<open>steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (5, Oc \<up> Suc n1, Oc \<up> Suc n2 @ [Bk])\<close> show ?thesis by (auto simp add: measure_tm_skip_first_arg_len_eq_1_def) next assume "l = [] \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n \<or> l = [] \<and> r = Bk # Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n" then show ?thesis proof assume "l = [] \<and> r = Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n" with \<open>steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (5, l, r)\<close> have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (5, [], Oc \<up> Suc n2 @ [Bk])" by auto with SUC_STEP_RED have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp) = step0 (5, [], Oc \<up> Suc n2 @ [Bk]) tm_skip_first_arg" by auto also have "... = (5,[],Bk#Oc \<up> Suc n2 @ [Bk])" by (auto simp add: tm_skip_first_arg_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp) = (5,[],Bk#Oc \<up> Suc n2 @ [Bk])" by auto with \<open>steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (5, [], Oc \<up> Suc n2 @ [Bk])\<close> show ?thesis by (auto simp add: measure_tm_skip_first_arg_len_eq_1_def) next assume "l = [] \<and> r = Bk # Oc \<up> Suc n2 @ [Bk] \<and> Suc n2 = Suc n" with \<open>steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (5, l, r)\<close> have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (5, [], Bk # Oc \<up> Suc n2 @ [Bk])" by auto with SUC_STEP_RED have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp) = step0 (5, [], Bk # Oc \<up> Suc n2 @ [Bk]) tm_skip_first_arg" by auto also have "... = (0,[Bk], Oc \<up> Suc n2 @ [Bk])" by (auto simp add: tm_skip_first_arg_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [], <[n::nat]>) tm_skip_first_arg (Suc stp) = (0,[Bk], Oc \<up> Suc n2 @ [Bk])" by auto with \<open>steps0 (1, [], <[n::nat]>) tm_skip_first_arg stp = (5, [], Bk # Oc \<up> Suc n2 @ [Bk])\<close> show ?thesis by (auto simp add: measure_tm_skip_first_arg_len_eq_1_def) qed qed qed qed qed qed lemma tm_skip_first_arg_len_eq_1_total_correctness: "\<lbrace> \<lambda>tap. tap = ([], <[n::nat]>)\<rbrace> tm_skip_first_arg \<lbrace> \<lambda>tap. tap = ([Bk], <[n::nat]> @[Bk])\<rbrace>" proof (rule tm_skip_first_arg_len_eq_1_partial_correctness) show "\<exists>stp. is_final (steps0 (1, [], <[n]>) tm_skip_first_arg stp)" using tm_skip_first_arg_len_eq_1_halts by auto qed lemma tm_skip_first_arg_len_eq_1_total_correctness': "length nl = 1 \<Longrightarrow> \<lbrace>\<lambda>tap. tap = ([], <nl::nat list> )\<rbrace> tm_skip_first_arg \<lbrace> \<lambda>tap. tap = ([Bk], <[hd nl]> @[Bk])\<rbrace>" proof - assume "length nl = 1" then have "nl = [hd nl]" by (metis One_nat_def diff_Suc_1 length_0_conv length_greater_0_conv length_tl list.distinct(1) list.expand list.sel(1) list.sel(3) list.size(3) zero_neq_one) moreover have "\<lbrace> \<lambda>tap. tap = ([], <[hd nl]>)\<rbrace> tm_skip_first_arg \<lbrace> \<lambda>tap. tap = ([Bk], <[hd nl]> @[Bk])\<rbrace>" by (rule tm_skip_first_arg_len_eq_1_total_correctness) ultimately show ?thesis by (simp add: Hoare_haltE Hoare_haltI tape_of_list_def) qed (* ERROR cases: length nl > 1 *) (* ctxrunTM tm_skip_first_arg (1,[],[Oc, Bk, Oc]) 0: [] _1_ [Oc,Bk,Oc] => 1: [Oc] _2_ [Bk,Oc] => 2: [Oc,Bk] _3_ [Oc] => 3: [Oc,Bk] _0_ [Oc] ctxrunTM tm_skip_first_arg (1,[],[Oc,Oc, Bk, Oc,Oc]) 0: [] _1_ [Oc,Oc,Bk,Oc,Oc] => 1: [Oc] _2_ [Oc,Bk,Oc,Oc] => 2: [Oc,Oc] _2_ [Bk,Oc,Oc] => 3: [Oc,Oc,Bk] _3_ [Oc,Oc] => 4: [Oc,Oc,Bk] _0_ [Oc,Oc] ctxrunTM tm_skip_first_arg (1,[],[Oc,Oc,Oc, Bk, Oc,Oc]) 0: [] _1_ [Oc,Oc,Oc,Bk,Oc,Oc] => 1: [Oc] _2_ [Oc,Oc,Bk,Oc,Oc] => 2: [Oc,Oc] _2_ [Oc,Bk,Oc,Oc] => 3: [Oc,Oc,Oc] _2_ [Bk,Oc,Oc] => 4: [Oc,Oc,Oc,Bk] _3_ [Oc,Oc] => 5: [Oc,Oc,Oc,Bk] _0_ [Oc,Oc] ctxrunTM tm_skip_first_arg (1, [], [Oc,Oc,Bk, Oc,Bk, Oc,Oc]) 0: [] _1_ [Oc,Oc,Bk,Oc,Bk,Oc,Oc] => 1: [Oc] _2_ [Oc,Bk,Oc,Bk,Oc,Oc] => 2: [Oc,Oc] _2_ [Bk,Oc,Bk,Oc,Oc] => 3: [Bk,Oc,Oc] _3_ [Oc,Bk,Oc,Oc] => 4: [Bk,Oc,Oc] _0_ [Oc,Bk,Oc,Oc] *) fun inv_tm_skip_first_arg_len_gt_1_s0 :: "nat \<Rightarrow> nat list \<Rightarrow> tape \<Rightarrow> bool" and inv_tm_skip_first_arg_len_gt_1_s1 :: "nat \<Rightarrow> nat list\<Rightarrow> tape \<Rightarrow> bool" and inv_tm_skip_first_arg_len_gt_1_s2 :: "nat \<Rightarrow> nat list\<Rightarrow> tape \<Rightarrow> bool" and inv_tm_skip_first_arg_len_gt_1_s3 :: "nat \<Rightarrow> nat list\<Rightarrow> tape \<Rightarrow> bool" where "inv_tm_skip_first_arg_len_gt_1_s1 n ns (l, r) = ( l = [] \<and> r = Oc \<up> Suc n @ [Bk] @ (<ns::nat list>) )" | "inv_tm_skip_first_arg_len_gt_1_s2 n ns (l, r) = (\<exists>n1 n2. l = Oc \<up> (Suc n1) \<and> r = Oc \<up> n2 @ [Bk] @ (<ns::nat list>) \<and> Suc n1 + n2 = Suc n)" | "inv_tm_skip_first_arg_len_gt_1_s3 n ns (l, r) = ( l = Bk # Oc \<up> (Suc n) \<and> r = (<ns::nat list>) )" | "inv_tm_skip_first_arg_len_gt_1_s0 n ns (l, r) = ( l = Bk# Oc \<up> (Suc n) \<and> r = (<ns::nat list>) )" fun inv_tm_skip_first_arg_len_gt_1 :: "nat \<Rightarrow> nat list \<Rightarrow> config \<Rightarrow> bool" where "inv_tm_skip_first_arg_len_gt_1 n ns (s, tap) = (if s = 0 then inv_tm_skip_first_arg_len_gt_1_s0 n ns tap else if s = 1 then inv_tm_skip_first_arg_len_gt_1_s1 n ns tap else if s = 2 then inv_tm_skip_first_arg_len_gt_1_s2 n ns tap else if s = 3 then inv_tm_skip_first_arg_len_gt_1_s3 n ns tap else False)" lemma tm_skip_first_arg_len_gt_1_cases: fixes s::nat assumes "inv_tm_skip_first_arg_len_gt_1 n ns (s,l,r)" and "s=0 \<Longrightarrow> P" and "s=1 \<Longrightarrow> P" and "s=2 \<Longrightarrow> P" and "s=3 \<Longrightarrow> P" and "s=4 \<Longrightarrow> P" and "s=5 \<Longrightarrow> P" shows "P" proof - have "s < 6" proof (rule ccontr) assume "\<not> s < 6" with \<open>inv_tm_skip_first_arg_len_gt_1 n ns (s,l,r)\<close> show False by auto qed then have "s = 0 \<or> s = 1 \<or> s = 2 \<or> s = 3 \<or> s = 4 \<or> s = 5" by auto with assms show ?thesis by auto qed lemma inv_tm_skip_first_arg_len_gt_1_step: assumes "length ns > 0" and "inv_tm_skip_first_arg_len_gt_1 n ns cf" shows "inv_tm_skip_first_arg_len_gt_1 n ns (step0 cf tm_skip_first_arg)" proof (cases cf) case (fields s l r) then have cf_cases: "cf = (s, l, r)" . show "inv_tm_skip_first_arg_len_gt_1 n ns (step0 cf tm_skip_first_arg)" proof (rule tm_skip_first_arg_len_gt_1_cases) from cf_cases and assms show "inv_tm_skip_first_arg_len_gt_1 n ns (s, l, r)" by auto next assume "s = 0" with cf_cases and assms show ?thesis by (auto simp add: tm_skip_first_arg_def) next assume "s = 4" with cf_cases and assms show ?thesis by (auto simp add: tm_skip_first_arg_def) next assume "s = 5" with cf_cases and assms show ?thesis by (auto simp add: tm_skip_first_arg_def) next assume "s = 1" with cf_cases and assms have "l = [] \<and> r = Oc \<up> Suc n @ [Bk] @ (<ns::nat list>)" by auto with assms and cf_cases and \<open>s = 1\<close> show ?thesis by (auto simp add: tm_skip_first_arg_def step.simps steps.simps) next assume "s = 2" with cf_cases and assms have "(\<exists>n1 n2. l = Oc \<up> (Suc n1) \<and> r = Oc \<up> n2 @ [Bk] @ (<ns::nat list>) \<and> Suc n1 + n2 = Suc n)" by auto then obtain n1 n2 where w_n1_n2: "l = Oc \<up> (Suc n1) \<and> r = Oc \<up> n2 @ [Bk] @ (<ns::nat list>) \<and> Suc n1 + n2 = Suc n" by blast show ?thesis proof (cases n2) case 0 then have "n2 = 0" . with w_n1_n2 have "l = Oc \<up> (Suc n1) \<and> r = [Bk] @ (<ns::nat list>) \<and> Suc n1 = Suc n" by auto then have "step0 (2, Oc \<up> (Suc n1), [Bk] @ (<ns::nat list>)) tm_skip_first_arg = (3, Bk # Oc \<up> (Suc n1), (<ns::nat list>))" by (simp add: tm_skip_first_arg_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_skip_first_arg_len_gt_1 n ns (3, Bk # Oc \<up> (Suc n1), (<ns::nat list>))" proof - from \<open>l = Oc \<up> (Suc n1) \<and> r = [Bk] @ (<ns::nat list>) \<and> Suc n1 = Suc n\<close> have "Oc \<up> (Suc n1) = Oc \<up> (Suc n1) \<and> Bk # Oc \<up> (Suc n1) = Bk#Oc#Oc \<up> n1 \<and> Suc n1 + 0 = Suc n" by auto then show "inv_tm_skip_first_arg_len_gt_1 n ns (3, Bk # Oc \<up> (Suc n1), (<ns::nat list>))" by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 2\<close> and w_n1_n2 by auto next case (Suc n2') then have "n2 = Suc n2'" . with w_n1_n2 have "l = Oc \<up> (Suc n1) \<and> r = Oc \<up> Suc n2' @ [Bk] @ (<ns::nat list>) \<and> Suc n1 + n2 = Suc n" by auto then have "step0 (2, Oc \<up> (Suc n1), Oc \<up> Suc n2' @ [Bk] @ (<ns::nat list>)) tm_skip_first_arg = (2, Oc # Oc \<up> (Suc n1), Oc \<up> n2' @ [Bk] @ (<ns::nat list>))" by (simp add: tm_skip_first_arg_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_skip_first_arg_len_gt_1 n ns (2, Oc # Oc \<up> (Suc n1), Oc \<up> n2' @ [Bk] @ (<ns::nat list>))" proof - from \<open>l = Oc \<up> (Suc n1) \<and> r = Oc \<up> Suc n2' @ [Bk] @ (<ns::nat list>) \<and> Suc n1 + n2 = Suc n\<close> have "Oc # Oc \<up> (Suc n1) = Oc \<up> Suc (Suc n1) \<and> Oc \<up> n2' @ [Bk] @ (<ns::nat list>) = Oc \<up> n2' @ [Bk] @ (<ns::nat list>) \<and> Suc (Suc n1) + n2' = Suc n" by (simp add: Suc add_Suc_shift) then show "inv_tm_skip_first_arg_len_gt_1 n ns (2, Oc # Oc \<up> (Suc n1), Oc \<up> n2' @ [Bk] @ (<ns::nat list>))" by force qed ultimately show ?thesis using assms and cf_cases and \<open>s = 2\<close> and w_n1_n2 using \<open>l = Oc \<up> (Suc n1) \<and> r = Oc \<up> Suc n2' @ [Bk] @ (<ns::nat list>) \<and> Suc n1 + n2 = Suc n\<close> by force qed next assume "s = 3" with cf_cases and assms have unpackedINV: "l = Bk # Oc \<up> (Suc n) \<and> r = (<ns::nat list>)" by auto moreover with \<open>length ns > 0\<close> have "(ns::nat list) \<noteq> [] \<and> hd (<ns::nat list>) = Oc" using numeral_list_head_is_Oc by force moreover from this have "<ns::nat list> = Oc#(tl (<ns::nat list>))" by (metis append_Nil list.exhaust_sel tape_of_list_empty unique_Bk_postfix_numeral_list_Nil) ultimately have "step0 (3, Bk # Oc \<up> (Suc n), (<ns::nat list>)) tm_skip_first_arg = (0, Bk # Oc \<up> (Suc n), (<ns::nat list>))" proof - from \<open><ns> = Oc # tl (<ns>)\<close> have "step0 (3, Bk # Oc \<up> (Suc n), (<ns::nat list>)) tm_skip_first_arg = step0 (3, Bk # Oc \<up> (Suc n), Oc # tl (<ns>)) tm_skip_first_arg" by auto also have "... = (0, Bk # Oc \<up> (Suc n), Oc # tl (<ns>))" by (simp add: tm_skip_first_arg_def step.simps steps.simps numeral_eqs_upto_12) also with \<open><ns> = Oc # tl (<ns>)\<close> have "... = (0, Bk # Oc \<up> (Suc n), (<ns::nat list>))" by auto finally show "step0 (3, Bk # Oc \<up> (Suc n), (<ns::nat list>)) tm_skip_first_arg = (0, Bk # Oc \<up> (Suc n), (<ns::nat list>))" by auto qed moreover with \<open>l = Bk # Oc \<up> (Suc n) \<and> r = (<ns::nat list>)\<close> have "inv_tm_skip_first_arg_len_gt_1 n ns (0, Bk # Oc \<up> (Suc n), (<ns::nat list>))" by auto ultimately show ?thesis using assms and cf_cases and \<open>s = 3\<close> and unpackedINV by auto qed qed lemma inv_tm_skip_first_arg_len_gt_1_steps: assumes "length ns > 0" and "inv_tm_skip_first_arg_len_gt_1 n ns cf" shows "inv_tm_skip_first_arg_len_gt_1 n ns (steps0 cf tm_skip_first_arg stp)" proof (induct stp) case 0 with assms show ?case by (auto simp add: inv_tm_skip_first_arg_len_gt_1_step step.simps steps.simps) next case (Suc stp) with assms show ?case using inv_tm_skip_first_arg_len_gt_1_step step_red by auto qed lemma tm_skip_first_arg_len_gt_1_partial_correctness: assumes "\<exists>stp. is_final (steps0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns::nat list>) ) tm_skip_first_arg stp)" and "0 < length ns" shows "\<lbrace>\<lambda>tap. tap = ([], Oc \<up> Suc n @ [Bk] @ (<ns::nat list>) ) \<rbrace> tm_skip_first_arg \<lbrace> \<lambda>tap. tap = (Bk# Oc \<up> Suc n, (<ns::nat list>) ) \<rbrace>" proof (rule Hoare_consequence) show " (\<lambda>tap. tap = ([], Oc \<up> Suc n @ [Bk] @ (<ns::nat list>))) \<mapsto> (\<lambda>tap. tap = ([], Oc \<up> Suc n @ [Bk] @ (<ns::nat list>)))" by (simp add: assert_imp_def tape_of_nat_def) next show "inv_tm_skip_first_arg_len_gt_1_s0 n ns \<mapsto> (\<lambda>tap. tap = (Bk # Oc \<up> Suc n, <ns>))" using assert_imp_def inv_tm_skip_first_arg_len_gt_1_s0.simps rev_numeral tape_of_nat_def by auto next show "\<lbrace>\<lambda>tap. tap = ([], Oc \<up> Suc n @ [Bk] @ <ns>)\<rbrace> tm_skip_first_arg \<lbrace>inv_tm_skip_first_arg_len_gt_1_s0 n ns\<rbrace>" proof (rule Hoare_haltI) fix l::"cell list" fix r:: "cell list" assume major: "(l, r) = ([], Oc \<up> Suc n @ [Bk] @ <ns::nat list>)" show "\<exists>stp. is_final (steps0 (1, l, r) tm_skip_first_arg stp) \<and> inv_tm_skip_first_arg_len_gt_1_s0 n ns holds_for steps0 (1, l, r) tm_skip_first_arg stp" proof - from major and assms have "\<exists>stp. is_final (steps0 (1, l, r) tm_skip_first_arg stp)" by auto then obtain stp where w_stp: "is_final (steps0 (1, l, r) tm_skip_first_arg stp)" by blast moreover have "inv_tm_skip_first_arg_len_gt_1_s0 n ns holds_for steps0 (1, l, r) tm_skip_first_arg stp" proof - have "inv_tm_skip_first_arg_len_gt_1 n ns (1, l, r)" by (simp add: major tape_of_list_def tape_of_nat_def) with assms have "inv_tm_skip_first_arg_len_gt_1 n ns (steps0 (1, l, r) tm_skip_first_arg stp)" using inv_tm_skip_first_arg_len_gt_1_steps by auto then show ?thesis by (smt holds_for.elims(3) inv_tm_skip_first_arg_len_gt_1.simps is_final_eq w_stp) qed ultimately show ?thesis by auto qed qed qed (* --- now, we prove termination of tm_skip_first_arg on arguments containing more than one numeral --- *) (* Lexicographic orders (See List.measures) quote: "These are useful for termination proofs" lemma in_measures[simp]: "(x, y) \<in> measures [] = False" "(x, y) \<in> measures (f # fs) = (f x < f y \<or> (f x = f y \<and> (x, y) \<in> measures fs))" *) (* Assemble a lexicographic measure function *) definition measure_tm_skip_first_arg_len_gt_1 :: "(config \<times> config) set" where "measure_tm_skip_first_arg_len_gt_1 = measures [ \<lambda>(s, l, r). (if s = 0 then 0 else 4 - s), \<lambda>(s, l, r). (if s = 2 then length r else 0) ]" lemma wf_measure_tm_skip_first_arg_len_gt_1: "wf measure_tm_skip_first_arg_len_gt_1" unfolding measure_tm_skip_first_arg_len_gt_1_def by (auto) lemma measure_tm_skip_first_arg_len_gt_1_induct [case_names Step]: "\<lbrakk>\<And>n. \<not> P (f n) \<Longrightarrow> (f (Suc n), (f n)) \<in> measure_tm_skip_first_arg_len_gt_1\<rbrakk> \<Longrightarrow> \<exists>n. P (f n)" using wf_measure_tm_skip_first_arg_len_gt_1 by (metis wf_iff_no_infinite_down_chain) lemma tm_skip_first_arg_len_gt_1_halts: "0 < length ns \<Longrightarrow> \<exists>stp. is_final (steps0 (1, [], Oc \<up> Suc n @ [Bk] @ <ns::nat list>) tm_skip_first_arg stp)" proof - assume A: "0 < length ns" show "\<exists>stp. is_final (steps0 (1, [], Oc \<up> Suc n @ [Bk] @ <ns::nat list>) tm_skip_first_arg stp)" proof (induct rule: measure_tm_skip_first_arg_len_gt_1_induct) case (Step stp) then have not_final: "\<not> is_final (steps0 (1, [], Oc \<up> Suc n @ [Bk] @ <ns>) tm_skip_first_arg stp)" . have INV: "inv_tm_skip_first_arg_len_gt_1 n ns (steps0 (1, [], Oc \<up> Suc n @ [Bk] @ <ns>) tm_skip_first_arg stp)" proof (rule_tac inv_tm_skip_first_arg_len_gt_1_steps) from A show "0 < length ns " . then show "inv_tm_skip_first_arg_len_gt_1 n ns (1, [], Oc \<up> Suc n @ [Bk] @ <ns>)" by (simp add: tape_of_list_def tape_of_nat_def) qed have SUC_STEP_RED: "steps0 (1, [], Oc \<up> Suc n @ [Bk] @ <ns>) tm_skip_first_arg (Suc stp) = step0 (steps0 (1, [], Oc \<up> Suc n @ [Bk] @ <ns>) tm_skip_first_arg stp) tm_skip_first_arg" by (rule step_red) show "( steps0 (1, [], Oc \<up> Suc n @ [Bk] @ <ns>) tm_skip_first_arg (Suc stp), steps0 (1, [], Oc \<up> Suc n @ [Bk] @ <ns>) tm_skip_first_arg stp ) \<in> measure_tm_skip_first_arg_len_gt_1" proof (cases "steps0 (1, [], Oc \<up> Suc n @ [Bk] @ <ns>) tm_skip_first_arg stp") case (fields s l r2) then have cf_cases: "steps0 (1, [], Oc \<up> Suc n @ [Bk] @ <ns>) tm_skip_first_arg stp = (s, l, r2)" . show ?thesis proof (rule tm_skip_first_arg_len_gt_1_cases) from INV and cf_cases show "inv_tm_skip_first_arg_len_gt_1 n ns (s, l, r2)" by auto next assume "s=0" (* not possible *) with cf_cases not_final show ?thesis by auto next assume "s=4" (* not possible *) with cf_cases not_final INV show ?thesis by auto next assume "s=5" (* not possible *) with cf_cases not_final INV show ?thesis by auto next assume "s=1" show ?thesis proof - from cf_cases and \<open>s=1\<close> have "steps0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg stp = (1, l, r2)" by auto with cf_cases and \<open>s=1\<close> and INV have unpackedINV: "l = [] \<and> r2 = Oc \<up> Suc n @ [Bk] @ (<ns>)" by auto with cf_cases and \<open>s=1\<close> and SUC_STEP_RED have "steps0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg (Suc stp) = step0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg" by auto also have "... = (2,[Oc],Oc \<up> n @ [Bk] @ (<ns>))" by (auto simp add: tm_skip_first_arg_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg (Suc stp) = (2,[Oc],Oc \<up> n @ [Bk] @ (<ns>))" by auto with \<open>steps0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg stp = (1, l, r2)\<close> show ?thesis by (auto simp add: measure_tm_skip_first_arg_len_gt_1_def) qed next assume "s=2" show ?thesis proof - from cf_cases and \<open>s=2\<close> have "steps0 (1, [],Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg stp = (2, l, r2)" by auto with cf_cases and \<open>s=2\<close> and INV have "(\<exists>n1 n2. l = Oc \<up> (Suc n1) \<and> r2 = Oc \<up> n2 @ [Bk] @ (<ns::nat list>) \<and> Suc n1 + n2 = Suc n)" by auto then obtain n1 n2 where w_n1_n2: "l = Oc \<up> (Suc n1) \<and> r2 = Oc \<up> n2 @ [Bk] @ (<ns::nat list>) \<and> Suc n1 + n2 = Suc n" by blast show ?thesis proof (cases n2) case 0 then have "n2 = 0" . with w_n1_n2 have "r2 = [Bk] @ (<ns::nat list>)" by auto with \<open>steps0 (1, [],Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg stp = (2, l, r2)\<close> have "steps0 (1, [],Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg stp = (2, l, [Bk] @ (<ns::nat list>))" by auto with SUC_STEP_RED have "steps0 (1, [],Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg (Suc stp) = step0 (2, l, [Bk] @ (<ns::nat list>)) tm_skip_first_arg" by auto also have "... = (3,Bk#l,(<ns>))" by (auto simp add: tm_skip_first_arg_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [],Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg (Suc stp) = (3,Bk#l,(<ns>))" by auto with \<open>steps0 (1, [],Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg stp = (2, l, [Bk] @ (<ns::nat list>))\<close> show ?thesis by (auto simp add: measure_tm_skip_first_arg_len_gt_1_def) next case (Suc n2') then have "n2 = Suc n2'" . with w_n1_n2 have "r2 = Oc \<up> Suc n2'@Bk#(<ns>)" by auto with \<open>steps0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg stp = (2, l, r2)\<close> have "steps0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg stp = (2, l, Oc \<up> Suc n2'@Bk#(<ns>))" by auto with SUC_STEP_RED have "steps0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg (Suc stp) = step0 (2, l, Oc \<up> Suc n2'@Bk#(<ns>)) tm_skip_first_arg" by auto also have "... = (2,Oc#l,Oc \<up> n2'@Bk#(<ns>))" by (auto simp add: tm_skip_first_arg_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg (Suc stp) = (2,Oc#l,Oc \<up> n2'@Bk#(<ns>))" by auto with \<open>steps0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg stp = (2, l, Oc \<up> Suc n2'@Bk#(<ns>))\<close> show ?thesis by (auto simp add: measure_tm_skip_first_arg_len_gt_1_def) qed qed next assume "s=3" show ?thesis proof - from cf_cases and \<open>s=3\<close> have "steps0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg stp = (3, l, r2)" by auto with cf_cases and \<open>s=3\<close> and INV have unpacked_INV: "l = Bk # Oc \<up> (Suc n) \<and> r2 = (<ns::nat list>)" by auto with \<open>steps0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg stp = (3, l, r2)\<close> have "steps0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg stp = (3, Bk # Oc \<up> (Suc n), (<ns::nat list>))" by auto with SUC_STEP_RED have "steps0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg (Suc stp) = step0 (3, Bk # Oc \<up> (Suc n), (<ns::nat list>)) tm_skip_first_arg" by auto also have "... = (0, Bk # Oc \<up> (Suc n),(<ns::nat list>))" proof - from \<open>length ns > 0\<close> have "(ns::nat list) \<noteq> [] \<and> hd (<ns::nat list>) = Oc" using numeral_list_head_is_Oc by force then have "<ns::nat list> = Oc#(tl (<ns::nat list>))" by (metis append_Nil list.exhaust_sel tape_of_list_empty unique_Bk_postfix_numeral_list_Nil) then have "step0 (3, Bk # Oc \<up> (Suc n), (<ns::nat list>)) tm_skip_first_arg = step0 (3, Bk # Oc \<up> (Suc n), Oc#(tl (<ns::nat list>))) tm_skip_first_arg" by auto also have "... = (0, Bk # Oc \<up> (Suc n), Oc#(tl (<ns::nat list>)))" by (auto simp add: tm_skip_first_arg_def numeral_eqs_upto_12 step.simps steps.simps) also with \<open><ns::nat list> = Oc#(tl (<ns::nat list>))\<close> have "... = (0, Bk # Oc \<up> (Suc n), <ns::nat list>)" by auto finally show "step0 (3, Bk # Oc \<up> (Suc n), (<ns::nat list>)) tm_skip_first_arg = (0, Bk # Oc \<up> (Suc n), <ns::nat list>)" by auto qed finally have "steps0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg (Suc stp) = (0, Bk # Oc \<up> (Suc n),(<ns::nat list>))" by auto with \<open>steps0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns>)) tm_skip_first_arg stp = (3, Bk # Oc \<up> (Suc n), (<ns::nat list>))\<close> show ?thesis by (auto simp add: measure_tm_skip_first_arg_len_gt_1_def) qed qed qed qed qed lemma tm_skip_first_arg_len_gt_1_total_correctness_pre: assumes "0 < length ns" shows "\<lbrace>\<lambda>tap. tap = ([], Oc \<up> Suc n @ [Bk] @ (<ns::nat list>) ) \<rbrace> tm_skip_first_arg \<lbrace> \<lambda>tap. tap = (Bk# Oc \<up> Suc n, (<ns::nat list>) ) \<rbrace>" proof (rule tm_skip_first_arg_len_gt_1_partial_correctness) from assms show "0 < length ns" . from assms show "\<exists>stp. is_final (steps0 (1, [], Oc \<up> Suc n @ [Bk] @ (<ns::nat list>) ) tm_skip_first_arg stp)" using tm_skip_first_arg_len_gt_1_halts by auto qed lemma tm_skip_first_arg_len_gt_1_total_correctness: assumes "1 < length (nl::nat list)" shows "\<lbrace>\<lambda>tap. tap = ([], <nl::nat list> )\<rbrace> tm_skip_first_arg \<lbrace> \<lambda>tap. tap = (Bk# <rev [hd nl]>, <tl nl>) \<rbrace>" proof - from assms have major: "(nl::nat list) = hd nl # tl nl" by (metis list.exhaust_sel list.size(3) not_one_less_zero) from assms have "tl nl \<noteq> []" using list_length_tl_neq_Nil by auto from assms have "(nl::nat list) \<noteq> []" by auto from \<open>(nl::nat list) = hd nl # tl nl\<close> have "<nl::nat list> = <hd nl # tl nl>" by auto also with \<open>tl nl \<noteq> []\<close> have "... = <hd nl> @ [Bk] @ (<tl nl>)" by (simp add: tape_of_nat_list_cons_eq) also with \<open>(nl::nat list) \<noteq> []\<close> have "... = Oc \<up> Suc (hd nl) @ [Bk] @ (<tl nl>)" using tape_of_nat_def by blast finally have "<nl::nat list> = Oc \<up> Suc (hd nl) @ [Bk] @ (<tl nl>)" by auto from \<open>tl nl \<noteq> []\<close> have "0 < length (tl nl)" using length_greater_0_conv by blast with assms have "\<lbrace>\<lambda>tap. tap = ([], Oc \<up> Suc (hd nl) @ [Bk] @ (<tl nl>) ) \<rbrace> tm_skip_first_arg \<lbrace> \<lambda>tap. tap = (Bk# Oc \<up> Suc (hd nl), (<tl nl>) ) \<rbrace>" using tm_skip_first_arg_len_gt_1_total_correctness_pre by force with \<open><nl::nat list> = Oc \<up> Suc (hd nl) @ [Bk] @ (<tl nl>)\<close> have "\<lbrace>\<lambda>tap. tap = ([], <nl::nat list> ) \<rbrace> tm_skip_first_arg \<lbrace> \<lambda>tap. tap = (Bk# Oc \<up> Suc (hd nl), (<tl nl>) ) \<rbrace>" by force moreover have "<rev [hd nl]> = Oc \<up> Suc (hd nl)" by (simp add: tape_of_list_def tape_of_nat_def) ultimately show ?thesis by (simp add: rev_numeral rev_numeral_list tape_of_list_def ) qed (* ---------- tm_erase_right_then_dblBk_left ---------- *) (* We will prove: -- DO_NOTHING path, the eraser should do nothing lemma tm_erase_right_then_dblBk_left_dnp_total_correctness: "\<lbrace> \<lambda>tap. tap = ([], r ) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. tap = ([Bk,Bk], r ) \<rbrace>" -- ERASE path lemma tm_erase_right_then_dblBk_left_erp_total_correctness_one_arg: assumes "1 \<le> length (nl::nat list)" shows "\<lbrace> \<lambda>tap. tap = (Bk# rev(<hd nl>), <tl nl>) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. \<exists>rex. tap = ([], [Bk,Bk] @ (<hd nl>) @ [Bk] @ Bk \<up> rex ) \<rbrace>" *) (* Test runs for the formulation of invariants: * * See file EngineeringOf_StrongCopy2.hs for more test runs * ctxrunTM tm_erase_right_then_dblBk_left (1, [Bk,Oc], [Oc]) 0: [Bk,Oc] _1_ [Oc] => 1: [Oc] _2_ [Bk,Oc] => 2: [] _3_ [Oc,Bk,Oc] => 3: [Oc] _5_ [Bk,Oc] => 4: [Bk,Oc] _6_ [Oc] => 5: [Bk,Oc] _6_ [Bk] => 6: [Bk,Bk,Oc] _7_ [] => 7: [Bk,Bk,Bk,Oc] _9_ [] => 8: [Bk,Bk,Oc] _10_ [Bk] => 9: [Bk,Oc] _10_ [Bk,Bk] => 10: [Oc] _10_ [Bk,Bk,Bk] => 11: [] _10_ [Oc,Bk,Bk,Bk] => 12: [] _11_ [Bk,Oc,Bk,Bk,Bk] => 13: [] _12_ [Bk,Bk,Oc,Bk,Bk,Bk] => 14: [] _0_ [Bk,Bk,Oc,Bk,Bk,Bk] ctxrunTM tm_erase_right_then_dblBk_left (1, [Bk,Oc,Oc], [Oc,Oc,Oc]) 0: [Bk,Oc,Oc] _1_ [Oc,Oc,Oc] => 1: [Oc,Oc] _2_ [Bk,Oc,Oc,Oc] => 2: [Oc] _3_ [Oc,Bk,Oc,Oc,Oc] => 3: [Oc,Oc] _5_ [Bk,Oc,Oc,Oc] => 4: [Bk,Oc,Oc] _6_ [Oc,Oc,Oc] => 5: [Bk,Oc,Oc] _6_ [Bk,Oc,Oc] => 6: [Bk,Bk,Oc,Oc] _7_ [Oc,Oc] => 7: [Bk,Bk,Oc,Oc] _8_ [Bk,Oc] => 8: [Bk,Bk,Bk,Oc,Oc] _7_ [Oc] => 9: [Bk,Bk,Bk,Oc,Oc] _8_ [Bk] => 10: [Bk,Bk,Bk,Bk,Oc,Oc] _7_ [] => 11: [Bk,Bk,Bk,Bk,Bk,Oc,Oc] _9_ [] => 12: [Bk,Bk,Bk,Bk,Oc,Oc] _10_ [Bk] => 13: [Bk,Bk,Bk,Oc,Oc] _10_ [Bk,Bk] => 14: [Bk,Bk,Oc,Oc] _10_ [Bk,Bk,Bk] => 15: [Bk,Oc,Oc] _10_ [Bk,Bk,Bk,Bk] => 16: [Oc,Oc] _10_ [Bk,Bk,Bk,Bk,Bk] => 17: [Oc] _10_ [Oc,Bk,Bk,Bk,Bk,Bk] => 18: [] _11_ [Oc,Oc,Bk,Bk,Bk,Bk,Bk] => 19: [] _11_ [Bk,Oc,Oc,Bk,Bk,Bk,Bk,Bk] => 20: [] _12_ [Bk,Bk,Oc,Oc,Bk,Bk,Bk,Bk,Bk] => 21: [] _0_ [Bk,Bk,Oc,Oc,Bk,Bk,Bk,Bk,Bk] *) (* Commented definition of tm_erase_right_then_dblBk_left let tm_erase_right_then_dblBk_left = from_raw [ -- 'check the left tape': (L, 2),(L, 2), -- 1 one step left (L, 3),(R, 5), -- 2 on Bk do one more step left, on Oc right towards 'check the right tape' (R, 4),(R, 5), -- 3 on 2nd Bk right to towards termination, on Oc right towards 'check the right tape' (R, 0),(R, 0), -- 4 one step right and terminate (R, 6),(R, 6), -- 5 one more step right to erase path -- 'check the right tape': (R, 7),(WB,6), -- 6 on Bk goto loop 'erase all to the right', on Oc erase -- (R, 9),(WB,8), -- 7 loop 'erase all to the right': on Bk leave loop, on Oc erase (R, 7),(R, 7), -- 8 move right and continue loop 'erase all to the right' (L,10),(WB,8), -- 9 on 2nd Bk start loop 'move to left until Oc', on Oc continue 'erase all to the right' -- (L,10),(L,11), -- 10 loop 'move to left until Oc': on Bk continue loop 'move to left until Oc', on Oc goto loop 'move left until DblBk' -- (L,12),(L,11), -- 11 loop 'move left until DblBk': on 1st Bk move once more to the left, on Oc continue loop 'move left until DblBk' (WB,0),(L,11) -- 12 on 2nd Bk stop, on Oc (possible in generic case) continue loop 'move left until DblBk' ] -- Note: -- In a more generic context, the 'move left until DblBk' may see an Oc in state 12. -- However, in our context of tm_check_for_one_arg there cannot be an Oc in state 12. *) definition tm_erase_right_then_dblBk_left :: "instr list" where "tm_erase_right_then_dblBk_left \<equiv> [ (L, 2),(L, 2), (L, 3),(R, 5), (R, 4),(R, 5), (R, 0),(R, 0), (R, 6),(R, 6), (R, 7),(WB,6), (R, 9),(WB,8), (R, 7),(R, 7), (L,10),(WB,8), (L,10),(L,11), (L,12),(L,11), (WB,0),(L,11) ]" (* Partial and total correctness for tm_erase_right_then_dblBk_left * * The leading 2 symbols on the left tape are used to differentiate! * * [Bk,Bk] \<longrightarrow> DO NOTHING path * [Bk,Oc] \<longrightarrow> ERASE path * *) (* ----------------------------------------------------------------- *) (* DO NOTHING path tm_erase_right_then_dblBk_left_dnp *) (* Sequence of states on the DO NOTHING path: 1,2,3 then 4, 0 *) (* ----------------------------------------------------------------- *) (* * "\<lbrace> \<lambda>tap. tap = ([], r ) \<rbrace> * tm_erase_right_then_dblBk_left * \<lbrace> \<lambda>tap. tap = ([Bk,Bk], r ) \<rbrace>" *) (* Definition of invariants for the DO_NOTHING path *) fun inv_tm_erase_right_then_dblBk_left_dnp_s0 :: "(cell list) \<Rightarrow> tape \<Rightarrow> bool" and inv_tm_erase_right_then_dblBk_left_dnp_s1 :: "(cell list) \<Rightarrow> tape \<Rightarrow> bool" and inv_tm_erase_right_then_dblBk_left_dnp_s2 :: "(cell list) \<Rightarrow> tape \<Rightarrow> bool" and inv_tm_erase_right_then_dblBk_left_dnp_s3 :: "(cell list) \<Rightarrow> tape \<Rightarrow> bool" and inv_tm_erase_right_then_dblBk_left_dnp_s4 :: "(cell list) \<Rightarrow> tape \<Rightarrow> bool" where "inv_tm_erase_right_then_dblBk_left_dnp_s0 CR (l, r) = (l = [Bk, Bk] \<and> CR = r)" | "inv_tm_erase_right_then_dblBk_left_dnp_s1 CR (l, r) = (l = [] \<and> CR = r)" | "inv_tm_erase_right_then_dblBk_left_dnp_s2 CR (l, r) = (l = [] \<and> r = Bk#CR)" | "inv_tm_erase_right_then_dblBk_left_dnp_s3 CR (l, r) = (l = [] \<and> r = Bk#Bk#CR)" | "inv_tm_erase_right_then_dblBk_left_dnp_s4 CR (l, r) = (l = [Bk] \<and> r = Bk#CR)" fun inv_tm_erase_right_then_dblBk_left_dnp :: "(cell list) \<Rightarrow> config \<Rightarrow> bool" where "inv_tm_erase_right_then_dblBk_left_dnp CR (s, tap) = (if s = 0 then inv_tm_erase_right_then_dblBk_left_dnp_s0 CR tap else if s = 1 then inv_tm_erase_right_then_dblBk_left_dnp_s1 CR tap else if s = 2 then inv_tm_erase_right_then_dblBk_left_dnp_s2 CR tap else if s = 3 then inv_tm_erase_right_then_dblBk_left_dnp_s3 CR tap else if s = 4 then inv_tm_erase_right_then_dblBk_left_dnp_s4 CR tap else False)" lemma tm_erase_right_then_dblBk_left_dnp_cases: fixes s::nat assumes "inv_tm_erase_right_then_dblBk_left_dnp CR (s,l,r)" and "s=0 \<Longrightarrow> P" and "s=1 \<Longrightarrow> P" and "s=2 \<Longrightarrow> P" and "s=3 \<Longrightarrow> P" and "s=4 \<Longrightarrow> P" shows "P" proof - have "s < 5" proof (rule ccontr) assume "\<not> s < 5" with \<open>inv_tm_erase_right_then_dblBk_left_dnp CR (s,l,r)\<close> show False by auto qed then have "s = 0 \<or> s = 1 \<or> s = 2 \<or> s = 3 \<or> s = 4" by auto with assms show ?thesis by auto qed lemma inv_tm_erase_right_then_dblBk_left_dnp_step: assumes "inv_tm_erase_right_then_dblBk_left_dnp CR cf" shows "inv_tm_erase_right_then_dblBk_left_dnp CR (step0 cf tm_erase_right_then_dblBk_left)" proof (cases cf) case (fields s l r) then have cf_cases: "cf = (s, l, r)" . show "inv_tm_erase_right_then_dblBk_left_dnp CR (step0 cf tm_erase_right_then_dblBk_left)" proof (rule tm_erase_right_then_dblBk_left_dnp_cases) from cf_cases and assms show "inv_tm_erase_right_then_dblBk_left_dnp CR (s, l, r)" by auto next assume "s = 0" with cf_cases and assms show ?thesis by (auto simp add: tm_erase_right_then_dblBk_left_def) next assume "s = 1" with cf_cases and assms have "l = []" by auto show ?thesis proof (cases r) case Nil then have "r = []" . with assms and cf_cases and \<open>s = 1\<close> show ?thesis by (auto simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps) next case (Cons a rs) then have "r = a # rs" . show ?thesis proof (cases a) case Bk with assms and cf_cases and \<open>s = 1\<close> and \<open>r = a # rs\<close> show ?thesis by (auto simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps) next case Oc with assms and cf_cases and \<open>s = 1\<close> and \<open>r = a # rs\<close> show ?thesis by (auto simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps) qed qed next assume "s = 2" with cf_cases and assms have "l = [] \<and> r = Bk#CR" by auto then have "step0 (2, [], Bk#CR) tm_erase_right_then_dblBk_left = (3, [], Bk# Bk # CR)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_dnp CR (3, [], Bk# Bk # CR)" proof - from \<open>l = [] \<and> r = Bk#CR\<close> show "inv_tm_erase_right_then_dblBk_left_dnp CR (3, [], Bk# Bk # CR)" by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 2\<close> and \<open>l = [] \<and> r = Bk#CR\<close> by auto next assume "s = 3" with cf_cases and assms have "l = [] \<and> r = Bk#Bk#CR" by auto then have "step0 (3, [], Bk#Bk#CR) tm_erase_right_then_dblBk_left = (4, [Bk], Bk # CR)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_dnp CR (4, [Bk], Bk # CR)" proof - from \<open>l = [] \<and> r = Bk#Bk#CR\<close> show "inv_tm_erase_right_then_dblBk_left_dnp CR (4, [Bk], Bk # CR)" by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 3\<close> and \<open>l = [] \<and> r = Bk#Bk#CR\<close> by auto next assume "s = 4" with cf_cases and assms have "l = [Bk] \<and> r = Bk#CR" by auto then have "step0 (4, [Bk], Bk#CR) tm_erase_right_then_dblBk_left = (0, [Bk,Bk], CR)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_dnp CR (0, [Bk,Bk], CR)" proof - from \<open>l = [Bk] \<and> r = Bk#CR\<close> show "inv_tm_erase_right_then_dblBk_left_dnp CR (0, [Bk,Bk], CR)" by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 4\<close> and \<open>l = [Bk] \<and> r = Bk#CR\<close> by auto qed qed lemma inv_tm_erase_right_then_dblBk_left_dnp_steps: assumes "inv_tm_erase_right_then_dblBk_left_dnp CR cf" shows "inv_tm_erase_right_then_dblBk_left_dnp CR (steps0 cf tm_erase_right_then_dblBk_left stp)" proof (induct stp) case 0 with assms show ?case by (auto simp add: inv_tm_erase_right_then_dblBk_left_dnp_step step.simps steps.simps) next case (Suc stp) with assms show ?case using inv_tm_erase_right_then_dblBk_left_dnp_step step_red by auto qed lemma tm_erase_right_then_dblBk_left_dnp_partial_correctness: assumes "\<exists>stp. is_final (steps0 (1, [], r) tm_erase_right_then_dblBk_left stp)" shows "\<lbrace> \<lambda>tap. tap = ([], r ) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. tap = ([Bk,Bk], r ) \<rbrace>" proof (rule Hoare_consequence) show "(\<lambda>tap. tap = ([], r) ) \<mapsto> (\<lambda>tap. tap = ([], r) )" by auto next show "inv_tm_erase_right_then_dblBk_left_dnp_s0 r \<mapsto> (\<lambda>tap. tap = ([Bk,Bk], r ))" by (simp add: assert_imp_def tape_of_list_def tape_of_nat_def) next show "\<lbrace>\<lambda>tap. tap = ([], r)\<rbrace> tm_erase_right_then_dblBk_left \<lbrace>inv_tm_erase_right_then_dblBk_left_dnp_s0 r \<rbrace>" proof (rule Hoare_haltI) fix l::"cell list" fix r'':: "cell list" assume major: "(l, r'') = ([], r)" show "\<exists>stp. is_final (steps0 (1, l, r'') tm_erase_right_then_dblBk_left stp) \<and> inv_tm_erase_right_then_dblBk_left_dnp_s0 r holds_for steps0 (1, l, r'') tm_erase_right_then_dblBk_left stp" proof - from major and assms have "\<exists>stp. is_final (steps0 (1, l, r'') tm_erase_right_then_dblBk_left stp)" by auto then obtain stp where w_stp: "is_final (steps0 (1, l, r'') tm_erase_right_then_dblBk_left stp)" by blast moreover have "inv_tm_erase_right_then_dblBk_left_dnp_s0 r holds_for steps0 (1, l, r'') tm_erase_right_then_dblBk_left stp" proof - have "inv_tm_erase_right_then_dblBk_left_dnp r (1, l, r'')" by (simp add: major tape_of_list_def tape_of_nat_def) then have "inv_tm_erase_right_then_dblBk_left_dnp r (steps0 (1, l, r'') tm_erase_right_then_dblBk_left stp)" using inv_tm_erase_right_then_dblBk_left_dnp_steps by auto then show ?thesis by (smt holds_for.elims(3) inv_tm_erase_right_then_dblBk_left_dnp.simps is_final_eq w_stp) qed ultimately show ?thesis by auto qed qed qed (* Total correctness of tm_erase_right_then_dblBk_left for DO NOTHING path *) (* Assemble a lexicographic measure function for the DO NOTHING path *) definition measure_tm_erase_right_then_dblBk_left_dnp :: "(config \<times> config) set" where "measure_tm_erase_right_then_dblBk_left_dnp = measures [ \<lambda>(s, l, r). (if s = 0 then 0 else 5 - s) ]" lemma wf_measure_tm_erase_right_then_dblBk_left_dnp: "wf measure_tm_erase_right_then_dblBk_left_dnp" unfolding measure_tm_erase_right_then_dblBk_left_dnp_def by (auto) lemma measure_tm_erase_right_then_dblBk_left_dnp_induct [case_names Step]: "\<lbrakk>\<And>n. \<not> P (f n) \<Longrightarrow> (f (Suc n), (f n)) \<in> measure_tm_erase_right_then_dblBk_left_dnp\<rbrakk> \<Longrightarrow> \<exists>n. P (f n)" using wf_measure_tm_erase_right_then_dblBk_left_dnp by (metis wf_iff_no_infinite_down_chain) lemma tm_erase_right_then_dblBk_left_dnp_halts: "\<exists>stp. is_final (steps0 (1, [], r) tm_erase_right_then_dblBk_left stp)" proof (induct rule: measure_tm_erase_right_then_dblBk_left_dnp_induct) case (Step stp) then have not_final: "\<not> is_final (steps0 (1, [], r) tm_erase_right_then_dblBk_left stp)" . have INV: "inv_tm_erase_right_then_dblBk_left_dnp r (steps0 (1, [], r) tm_erase_right_then_dblBk_left stp)" proof (rule_tac inv_tm_erase_right_then_dblBk_left_dnp_steps) show "inv_tm_erase_right_then_dblBk_left_dnp r (1, [], r)" by (simp add: tape_of_list_def tape_of_nat_def ) qed have SUC_STEP_RED: "steps0 (1, [], r) tm_erase_right_then_dblBk_left (Suc stp) = step0 (steps0 (1, [], r) tm_erase_right_then_dblBk_left stp) tm_erase_right_then_dblBk_left" by (rule step_red) show "( steps0 (1, [], r) tm_erase_right_then_dblBk_left (Suc stp), steps0 (1, [], r) tm_erase_right_then_dblBk_left stp ) \<in> measure_tm_erase_right_then_dblBk_left_dnp" proof (cases "steps0 (1, [], r) tm_erase_right_then_dblBk_left stp") case (fields s l r2) then have cf_cases: "steps0 (1, [], r) tm_erase_right_then_dblBk_left stp = (s, l, r2)" . show ?thesis proof (rule tm_erase_right_then_dblBk_left_dnp_cases) from INV and cf_cases show "inv_tm_erase_right_then_dblBk_left_dnp r (s, l, r2)" by auto next assume "s=0" (* not possible *) with cf_cases not_final show ?thesis by auto next assume "s=1" show ?thesis proof (cases r) case Nil then have "r = []" . from cf_cases and \<open>s=1\<close> have "steps0 (1, [], r) tm_erase_right_then_dblBk_left stp = (1, l, r2)" by auto with cf_cases and \<open>s=1\<close> and INV have "l = [] \<and> r = r2" by auto with cf_cases and \<open>s=1\<close> and SUC_STEP_RED have "steps0 (1, [], r) tm_erase_right_then_dblBk_left (Suc stp) = step0 (1, [], r) tm_erase_right_then_dblBk_left" by auto also with \<open>r = []\<close> and \<open>l = [] \<and> r = r2\<close> have "... = (2,[],Bk#r2)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [], r) tm_erase_right_then_dblBk_left (Suc stp) = (2,[],Bk#r2)" by auto with \<open>steps0 (1, [], r) tm_erase_right_then_dblBk_left stp = (1, l, r2)\<close> show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_dnp_def) next case (Cons a rs) then have "r = a # rs" . then show ?thesis proof (cases a) case Bk then have "a = Bk" . from cf_cases and \<open>s=1\<close> have "steps0 (1, [], r) tm_erase_right_then_dblBk_left stp = (1, l, r2)" by auto with cf_cases and \<open>s=1\<close> and INV have "l = [] \<and> r = r2" by auto with cf_cases and \<open>s=1\<close> and SUC_STEP_RED have "steps0 (1, [], r) tm_erase_right_then_dblBk_left (Suc stp) = step0 (1, [], r) tm_erase_right_then_dblBk_left" by auto also with \<open>r = a # rs\<close> and \<open>a=Bk\<close> and \<open>l = [] \<and> r = r2\<close> have "... = (2,[],Bk#r2)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [], r) tm_erase_right_then_dblBk_left (Suc stp) = (2,[],Bk#r2)" by auto with \<open>steps0 (1, [], r) tm_erase_right_then_dblBk_left stp = (1, l, r2)\<close> show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_dnp_def) next case Oc then have "a = Oc" . from cf_cases and \<open>s=1\<close> have "steps0 (1, [], r) tm_erase_right_then_dblBk_left stp = (1, l, r2)" by auto with cf_cases and \<open>s=1\<close> and INV have "l = [] \<and> r = r2" by auto with cf_cases and \<open>s=1\<close> and SUC_STEP_RED have "steps0 (1, [], r) tm_erase_right_then_dblBk_left (Suc stp) = step0 (1, [], r) tm_erase_right_then_dblBk_left" by auto also with \<open>r = a # rs\<close> and \<open>a=Oc\<close> and \<open>l = [] \<and> r = r2\<close> have "... = (2,[],Bk#r2)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [], r) tm_erase_right_then_dblBk_left (Suc stp) = (2,[],Bk#r2)" by auto with \<open>steps0 (1, [], r) tm_erase_right_then_dblBk_left stp = (1, l, r2)\<close> show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_dnp_def) qed qed next assume "s=2" with cf_cases have "steps0 (1, [], r) tm_erase_right_then_dblBk_left stp = (2, l, r2)" by auto with cf_cases and \<open>s=2\<close> and INV have "(l = [] \<and> r2 = Bk#r)" by auto with cf_cases and \<open>s=2\<close> and SUC_STEP_RED have "steps0 (1, [], r) tm_erase_right_then_dblBk_left (Suc stp) = step0 (2, l, r2) tm_erase_right_then_dblBk_left" by auto also with \<open>s=2\<close> and \<open>(l = [] \<and> r2 = Bk#r)\<close> have "... = (3,[],Bk#r2)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [], r) tm_erase_right_then_dblBk_left (Suc stp) = (3,[],Bk#r2)" by auto with \<open>steps0 (1, [], r) tm_erase_right_then_dblBk_left stp = (2, l, r2)\<close> show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_dnp_def) next assume "s=3" with cf_cases have "steps0 (1, [], r) tm_erase_right_then_dblBk_left stp = (3, l, r2)" by auto with cf_cases and \<open>s=3\<close> and INV have "(l = [] \<and> r2 = Bk#Bk#r)" by auto with cf_cases and \<open>s=3\<close> and SUC_STEP_RED have "steps0 (1, [], r) tm_erase_right_then_dblBk_left (Suc stp) = step0 (3, l, r2) tm_erase_right_then_dblBk_left" by auto also with \<open>s=3\<close> and \<open>(l = [] \<and> r2 = Bk#Bk#r)\<close> have "... = (4,[Bk],Bk#r)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [], r) tm_erase_right_then_dblBk_left (Suc stp) = (4,[Bk],Bk#r)" by auto with \<open>steps0 (1, [], r) tm_erase_right_then_dblBk_left stp = (3, l, r2)\<close> show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_dnp_def) next assume "s=4" with cf_cases have "steps0 (1, [], r) tm_erase_right_then_dblBk_left stp = (4, l, r2)" by auto with cf_cases and \<open>s=4\<close> and INV have "(l = [Bk] \<and> r2 = Bk#r)" by auto with cf_cases and \<open>s=4\<close> and SUC_STEP_RED have "steps0 (1, [], r) tm_erase_right_then_dblBk_left (Suc stp) = step0 (4, l, r2) tm_erase_right_then_dblBk_left" by auto also with \<open>s=4\<close> and \<open>(l = [Bk] \<and> r2 = Bk#r)\<close> have "... = (0,[Bk,Bk],r)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [], r) tm_erase_right_then_dblBk_left (Suc stp) = (0,[Bk,Bk],r)" by auto with \<open>steps0 (1, [], r) tm_erase_right_then_dblBk_left stp = (4, l, r2)\<close> show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_dnp_def) qed qed qed lemma tm_erase_right_then_dblBk_left_dnp_total_correctness: "\<lbrace> \<lambda>tap. tap = ([], r ) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. tap = ([Bk,Bk], r ) \<rbrace>" proof (rule tm_erase_right_then_dblBk_left_dnp_partial_correctness) show "\<exists>stp. is_final (steps0 (1, [], r) tm_erase_right_then_dblBk_left stp)" using tm_erase_right_then_dblBk_left_dnp_halts by auto qed (* ----------------------------------------------------------------- *) (* ERASE path tm_erase_right_then_dblBk_left_erp *) (* Sequence of states on the ERASE path: 1,2,3 then 5... *) (* ----------------------------------------------------------------- *) (* * \<lbrace> \<lambda>tap. tap = (Bk# rev(<hd nl>), <tl nl>) \<rbrace> * tm_erase_right_then_dblBk_left * \<lbrace> \<lambda>tap. \<exists>rex. tap = ([], [Bk,Bk] @ (<hd nl>) @ [Bk] @ Bk \<up> rex ) \<rbrace>" *) (* Definition of invariants for the ERASE path: had to split definitions *) fun inv_tm_erase_right_then_dblBk_left_erp_s1 :: "(cell list) \<Rightarrow> (cell list) \<Rightarrow> tape \<Rightarrow> bool" where "inv_tm_erase_right_then_dblBk_left_erp_s1 CL CR (l, r) = (l = [Bk,Oc] @ CL \<and> r = CR)" fun inv_tm_erase_right_then_dblBk_left_erp_s2 :: "(cell list) \<Rightarrow> (cell list) \<Rightarrow> tape \<Rightarrow> bool" where "inv_tm_erase_right_then_dblBk_left_erp_s2 CL CR (l, r) = (l = [Oc] @ CL \<and> r = Bk#CR)" fun inv_tm_erase_right_then_dblBk_left_erp_s3 :: "(cell list) \<Rightarrow> (cell list) \<Rightarrow> tape \<Rightarrow> bool" where "inv_tm_erase_right_then_dblBk_left_erp_s3 CL CR (l, r) = (l = CL \<and> r = Oc#Bk#CR)" fun inv_tm_erase_right_then_dblBk_left_erp_s5 :: "(cell list) \<Rightarrow> (cell list) \<Rightarrow> tape \<Rightarrow> bool" where "inv_tm_erase_right_then_dblBk_left_erp_s5 CL CR (l, r) = (l = [Oc] @ CL \<and> r = Bk#CR)" fun inv_tm_erase_right_then_dblBk_left_erp_s6 :: "(cell list) \<Rightarrow> (cell list) \<Rightarrow> tape \<Rightarrow> bool" where "inv_tm_erase_right_then_dblBk_left_erp_s6 CL CR (l, r) = (l = [Bk,Oc] @ CL \<and> ( (CR = [] \<and> r = CR) \<or> (CR \<noteq> [] \<and> (r = CR \<or> r = Bk # tl CR)) ) )" (* ENHANCE: simplify invariant of s6 (simpler to use for proof by cases "inv_tm_erase_right_then_dblBk_left_erp_s6 CL CR (l, r) = (l = [Bk,Oc] @ CL \<and> CR = [] \<and> r = CR \<or> l = [Bk,Oc] @ CL \<and> CR \<noteq> [] \<and> r = Oc # tl CR \<or> l = [Bk,Oc] @ CL \<and> CR \<noteq> [] \<and> r = Bk # tl CR )" *) fun inv_tm_erase_right_then_dblBk_left_erp_s7 :: "(cell list) \<Rightarrow> (cell list) \<Rightarrow> tape \<Rightarrow> bool" where "inv_tm_erase_right_then_dblBk_left_erp_s7 CL CR (l, r) = ((\<exists>lex. l = Bk \<up> Suc lex @ [Bk,Oc] @ CL) \<and> (\<exists>rs. CR = rs @ r) )" fun inv_tm_erase_right_then_dblBk_left_erp_s8 :: "(cell list) \<Rightarrow> (cell list) \<Rightarrow> tape \<Rightarrow> bool" where "inv_tm_erase_right_then_dblBk_left_erp_s8 CL CR (l, r) = ((\<exists>lex. l = Bk \<up> Suc lex @ [Bk,Oc] @ CL) \<and> (\<exists>rs1 rs2. CR = rs1 @ [Oc] @ rs2 \<and> r = Bk#rs2) )" fun inv_tm_erase_right_then_dblBk_left_erp_s9 :: "(cell list) \<Rightarrow> (cell list) \<Rightarrow> tape \<Rightarrow> bool" where "inv_tm_erase_right_then_dblBk_left_erp_s9 CL CR (l, r) = ((\<exists>lex. l = Bk \<up> Suc lex @ [Bk,Oc] @ CL) \<and> (\<exists>rs. CR = rs @ [Bk] @ r \<or> CR = rs \<and> r = []) )" fun inv_tm_erase_right_then_dblBk_left_erp_s10 :: "(cell list) \<Rightarrow> (cell list) \<Rightarrow> tape \<Rightarrow> bool" where "inv_tm_erase_right_then_dblBk_left_erp_s10 CL CR (l, r) = ( (\<exists>lex rex. l = Bk \<up> lex @ [Bk,Oc] @ CL \<and> r = Bk \<up> Suc rex) \<or> (\<exists>rex. l = [Oc] @ CL \<and> r = Bk \<up> Suc rex) \<or> (\<exists>rex. l = CL \<and> r = Oc # Bk \<up> Suc rex) )" fun inv_tm_erase_right_then_dblBk_left_erp_s11 :: "(cell list) \<Rightarrow> (cell list) \<Rightarrow> tape \<Rightarrow> bool" where "inv_tm_erase_right_then_dblBk_left_erp_s11 CL CR (l, r) = ( (\<exists>rex. l = [] \<and> r = Bk# rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc)) \<or> (\<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk ) \<or> (\<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Oc ) \<or> (\<exists>rex. l = [Bk] \<and> r = rev [Oc] @ Oc # Bk \<up> Suc rex \<and> CL = [Oc, Bk]) \<or> (\<exists>rex ls1 ls2. l = Bk#Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Bk#Oc#ls2 \<and> ls1 = [Oc] ) \<or> (\<exists>rex ls1 ls2. l = Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc#ls2 \<and> ls1 = [Bk] ) \<or> (\<exists>rex ls1 ls2. l = Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc#ls2 \<and> ls1 = [Oc] ) \<or> (\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> []) )" (* YYYY1' (\<exists>rex. l = [] \<and> r = Bk# rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc) ) \<or> (s11 \<longrightarrow> s11) YYYY2' (\<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk) \<or> (s11 \<longrightarrow> s11) YYYY2'' (\<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Oc) \<or> (s11 \<longrightarrow> s11) YYYY5 (\<exists>rex. l = [Bk] \<and> r = rev [Oc] @ Oc # Bk \<up> Suc rex \<and> CL = [Oc, Bk]) \<or> (s10 \<longrightarrow> s11) YYYY6 (\<exists>rex ls1 ls2. l = Bk#Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Bk#Oc#ls2 \<and> ls1 = [Oc] ) \<or> (s10 \<longrightarrow> s11) YYYY3 (\<exists>rex ls1 ls2. l = Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc#ls2 \<and> ls1 = [Bk] ) \<or> (s10 \<longrightarrow> s11) YYYY7 (\<exists>rex ls1 ls2. l = Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc#ls2 \<and> ls1 = [Oc] ) \<or> (s10 \<longrightarrow> s11) YYYY8 (\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> []) (s11 \<longrightarrow> s11) *) fun inv_tm_erase_right_then_dblBk_left_erp_s12 :: "(cell list) \<Rightarrow> (cell list) \<Rightarrow> tape \<Rightarrow> bool" where "inv_tm_erase_right_then_dblBk_left_erp_s12 CL CR (l, r) = ( (\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> [] \<and> last ls1 = Oc) \<or> (\<exists>rex. l = [] \<and> r = Bk#rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk) \<or> (\<exists>rex. l = [] \<and> r = Bk#Bk#rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc) ) \<or> False )" (* YYYY4 (\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> [] \<and> last ls1 = Oc) YYYY6''' (\<exists>rex. l = [] \<and> r = Bk#rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk) YYYY9 (\<exists>rex. l = [] \<and> r = Bk#Bk#rev CL @ Oc # Bk \<up> Suc rex) \<or> *) fun inv_tm_erase_right_then_dblBk_left_erp_s0 :: "(cell list) \<Rightarrow> (cell list) \<Rightarrow> tape \<Rightarrow> bool" where "inv_tm_erase_right_then_dblBk_left_erp_s0 CL CR (l, r) = ( (\<exists>rex. l = [] \<and> r = [Bk, Bk] @ (rev CL) @ [Oc, Bk] @ Bk \<up> rex \<and> (CL = [] \<or> last CL = Oc) ) \<or> (\<exists>rex. l = [] \<and> r = [Bk] @ (rev CL) @ [Oc, Bk] @ Bk \<up> rex \<and> CL \<noteq> [] \<and> last CL = Bk ) )" fun inv_tm_erase_right_then_dblBk_left_erp :: "(cell list) \<Rightarrow> (cell list) \<Rightarrow> config \<Rightarrow> bool" where "inv_tm_erase_right_then_dblBk_left_erp CL CR (s, tap) = (if s = 0 then inv_tm_erase_right_then_dblBk_left_erp_s0 CL CR tap else if s = 1 then inv_tm_erase_right_then_dblBk_left_erp_s1 CL CR tap else if s = 2 then inv_tm_erase_right_then_dblBk_left_erp_s2 CL CR tap else if s = 3 then inv_tm_erase_right_then_dblBk_left_erp_s3 CL CR tap else if s = 5 then inv_tm_erase_right_then_dblBk_left_erp_s5 CL CR tap else if s = 6 then inv_tm_erase_right_then_dblBk_left_erp_s6 CL CR tap else if s = 7 then inv_tm_erase_right_then_dblBk_left_erp_s7 CL CR tap else if s = 8 then inv_tm_erase_right_then_dblBk_left_erp_s8 CL CR tap else if s = 9 then inv_tm_erase_right_then_dblBk_left_erp_s9 CL CR tap else if s = 10 then inv_tm_erase_right_then_dblBk_left_erp_s10 CL CR tap else if s = 11 then inv_tm_erase_right_then_dblBk_left_erp_s11 CL CR tap else if s = 12 then inv_tm_erase_right_then_dblBk_left_erp_s12 CL CR tap else False)" lemma tm_erase_right_then_dblBk_left_erp_cases: fixes s::nat assumes "inv_tm_erase_right_then_dblBk_left_erp CL CR (s,l,r)" and "s=0 \<Longrightarrow> P" and "s=1 \<Longrightarrow> P" and "s=2 \<Longrightarrow> P" and "s=3 \<Longrightarrow> P" and "s=5 \<Longrightarrow> P" and "s=6 \<Longrightarrow> P" and "s=7 \<Longrightarrow> P" and "s=8 \<Longrightarrow> P" and "s=9 \<Longrightarrow> P" and "s=10 \<Longrightarrow> P" and "s=11 \<Longrightarrow> P" and "s=12 \<Longrightarrow> P" shows "P" proof - have "s < 4 \<or> 4 < s \<and> s < 13" proof (rule ccontr) assume "\<not> (s < 4 \<or> 4 < s \<and> s < 13)" with \<open>inv_tm_erase_right_then_dblBk_left_erp CL CR (s,l,r)\<close> show False by auto qed then have "s = 0 \<or> s = 1 \<or> s = 2 \<or> s = 3 \<or> s = 5 \<or> s = 6 \<or> s = 7 \<or> s = 8 \<or> s = 9 \<or> s = 10 \<or> s = 11 \<or> s = 12" by arith with assms show ?thesis by auto qed (* -------------- step - lemma for the invariants of the ERASE path of tm_erase_right_then_dblBk_left ------------------ *) lemma inv_tm_erase_right_then_dblBk_left_erp_step: assumes "inv_tm_erase_right_then_dblBk_left_erp CL CR cf" and "noDblBk CL" and "noDblBk CR" shows "inv_tm_erase_right_then_dblBk_left_erp CL CR (step0 cf tm_erase_right_then_dblBk_left)" proof (cases cf) case (fields s l r) then have cf_cases: "cf = (s, l, r)" . show "inv_tm_erase_right_then_dblBk_left_erp CL CR (step0 cf tm_erase_right_then_dblBk_left)" proof (rule tm_erase_right_then_dblBk_left_erp_cases) from cf_cases and assms show "inv_tm_erase_right_then_dblBk_left_erp CL CR (s, l, r)" by auto next assume "s = 1" with cf_cases and assms have "(l = [Bk,Oc] @ CL \<and> r = CR)" by auto show ?thesis proof (cases r) case Nil then have "r = []" . with assms and cf_cases and \<open>s = 1\<close> show ?thesis by (auto simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps) next case (Cons a rs) then have "r = a # rs" . show ?thesis proof (cases a) case Bk with assms and cf_cases and \<open>r = a # rs\<close> and \<open>s = 1\<close> show ?thesis by (auto simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps) next case Oc with assms and cf_cases and \<open>r = a # rs\<close> and \<open>s = 1\<close> show ?thesis by (auto simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps) qed qed next assume "s = 2" with cf_cases and assms have "l = [Oc] @ CL \<and> r = Bk#CR" by auto then have "step0 (2, [Oc] @ CL, Bk#CR) tm_erase_right_then_dblBk_left = (3, CL, Oc# Bk # CR)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (3, CL, Oc# Bk # CR)" by auto ultimately show ?thesis using assms and cf_cases and \<open>s = 2\<close> and \<open>l = [Oc] @ CL \<and> r = Bk#CR\<close> by auto next assume "s = 3" with cf_cases and assms have "l = CL \<and> r = Oc#Bk#CR" by auto then have "step0 (3, CL, Oc#Bk#CR) tm_erase_right_then_dblBk_left = (5, Oc#CL, Bk # CR)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (5, Oc#CL, Bk # CR)" by auto ultimately show ?thesis using assms and cf_cases and \<open>s = 3\<close> and \<open>l = CL \<and> r = Oc#Bk#CR\<close> by auto next assume "s = 5" with cf_cases and assms have "l = [Oc] @ CL \<and> r = Bk#CR" by auto then have "step0 (5, [Oc] @ CL, Bk#CR) tm_erase_right_then_dblBk_left = (6, Bk#Oc#CL, CR)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (6, Bk#Oc#CL, CR)" proof (cases CR) case Nil then show ?thesis by auto next case (Cons a cs) then have "CR = a # cs" . with \<open>l = [Oc] @ CL \<and> r = Bk#CR\<close> and \<open>s = 5\<close> and \<open>CR = a # cs\<close> have "inv_tm_erase_right_then_dblBk_left_erp_s6 CL CR (Bk#Oc#CL, CR)" by simp with \<open>s=5\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (6, Bk#Oc#CL, CR)" by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 5\<close> and \<open>l = [Oc] @ CL \<and> r = Bk#CR\<close> by auto next assume "s = 6" with cf_cases and assms have "l = [Bk,Oc] @ CL" and "( (CR = [] \<and> r = CR) \<or> (CR \<noteq> [] \<and> (r = CR \<or> r = Bk # tl CR)) )" by auto from \<open>( (CR = [] \<and> r = CR) \<or> (CR \<noteq> [] \<and> (r = CR \<or> r = Bk # tl CR)) )\<close> show ?thesis proof assume "CR = [] \<and> r = CR" have "step0 (6, [Bk,Oc] @ CL, []) tm_erase_right_then_dblBk_left = (7, Bk \<up> Suc 0 @ [Bk,Oc] @ CL, [])" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (7, Bk \<up> Suc 0 @ [Bk,Oc] @ CL, [])" by auto ultimately show ?thesis using assms and cf_cases and \<open>s = 6\<close> and \<open>l = [Bk,Oc] @ CL\<close> and \<open>CR = [] \<and> r = CR\<close> by auto next assume "CR \<noteq> [] \<and> (r = CR \<or> r = Bk # tl CR)" then have "CR \<noteq> []" and "r = CR \<or> r = Bk # tl CR" by auto from \<open>r = CR \<or> r = Bk # tl CR\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (step0 cf tm_erase_right_then_dblBk_left)" proof assume "r = CR" show "inv_tm_erase_right_then_dblBk_left_erp CL CR (step0 cf tm_erase_right_then_dblBk_left)" proof (cases r) case Nil then have "r = []" . then have "step0 (6, [Bk,Oc] @ CL, []) tm_erase_right_then_dblBk_left = (7, Bk \<up> Suc 0 @ [Bk,Oc] @ CL, [])" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (7, Bk \<up> Suc 0 @ [Bk,Oc] @ CL, [])" by auto ultimately show ?thesis using assms and cf_cases and \<open>s = 6\<close> and \<open>l = [Bk,Oc] @ CL\<close> and \<open>r = []\<close> by auto next case (Cons a rs') then have "r = a # rs'" . with \<open>r = CR\<close> have "r = a # tl CR" by auto show ?thesis proof (cases a) case Bk then have "a = Bk" . then have "step0 (6, [Bk,Oc] @ CL, Bk # tl CR) tm_erase_right_then_dblBk_left = (7, Bk \<up> Suc 0 @ [Bk,Oc] @ CL, tl CR)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (7, Bk \<up> Suc 0 @ [Bk,Oc] @ CL, tl CR)" proof - from \<open>CR \<noteq> []\<close> and \<open>r = CR\<close> and \<open>a = Bk\<close> and \<open>r = a # tl CR\<close> and \<open>l = [Bk,Oc] @ CL\<close> have "inv_tm_erase_right_then_dblBk_left_erp_s7 CL CR (Bk \<up> Suc 0 @ [Bk,Oc] @ CL, tl CR)" by (metis append.left_neutral append_Cons empty_replicate inv_tm_erase_right_then_dblBk_left_erp_s7.simps replicate_Suc ) then show "inv_tm_erase_right_then_dblBk_left_erp CL CR (7, Bk \<up> Suc 0 @ [Bk,Oc] @ CL, tl CR)" by auto qed ultimately show ?thesis using \<open>CR \<noteq> []\<close> and \<open>r = CR\<close> and \<open>a = Bk\<close> and \<open>r = a # tl CR\<close> and \<open>l = [Bk,Oc] @ CL\<close> and \<open>s = 6\<close> and cf_cases by auto next case Oc then have "a = Oc" . then have "step0 (6, [Bk,Oc] @ CL, Oc # rs') tm_erase_right_then_dblBk_left = (6, [Bk,Oc] @ CL, Bk # rs')" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (6, [Bk,Oc] @ CL, Bk # rs')" proof - from \<open>CR \<noteq> []\<close> and \<open>r = CR\<close> and \<open>a = Oc\<close> and \<open>r = a # tl CR\<close> and \<open>l = [Bk,Oc] @ CL\<close> have "inv_tm_erase_right_then_dblBk_left_erp_s6 CL CR ([Bk,Oc] @ CL, Bk # rs')" using inv_tm_erase_right_then_dblBk_left_erp_s6.simps list.sel(3) local.Cons by blast then show "inv_tm_erase_right_then_dblBk_left_erp CL CR (6, [Bk,Oc] @ CL, Bk # rs')" by auto qed ultimately show ?thesis using \<open>CR \<noteq> []\<close> and \<open>r = CR\<close> and \<open>a = Oc\<close> and \<open>r = a # tl CR\<close> and \<open>l = [Bk,Oc] @ CL\<close> and \<open>s = 6\<close> and cf_cases by auto qed qed next assume "r = Bk # tl CR" have "step0 (6, [Bk,Oc] @ CL, Bk # tl CR) tm_erase_right_then_dblBk_left = (7, Bk \<up> Suc 0 @ [Bk,Oc] @ CL, tl CR)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover with \<open>CR \<noteq> []\<close> and \<open>r = Bk # tl CR\<close> have "inv_tm_erase_right_then_dblBk_left_erp CL CR (7, Bk \<up> Suc 0 @ [Bk,Oc] @ CL, tl CR)" proof - have "(\<exists>lex. Bk \<up> Suc 0 @ [Bk,Oc] @ CL = Bk \<up> Suc lex @ [Bk,Oc] @ CL) " by blast moreover with \<open>CR \<noteq> []\<close> have "(\<exists>rs. CR = rs @ tl CR)" by (metis append_Cons append_Nil list.exhaust list.sel(3)) ultimately show "inv_tm_erase_right_then_dblBk_left_erp CL CR (7, Bk \<up> Suc 0 @ [Bk,Oc] @ CL, tl CR)" by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 6\<close> and \<open>CR \<noteq> []\<close> and \<open>r = Bk # tl CR\<close> and \<open>l = [Bk,Oc] @ CL\<close> and cf_cases by auto qed qed next assume "s = 7" with cf_cases and assms have "(\<exists>lex. l = Bk \<up> Suc lex @ [Bk,Oc] @ CL) \<and> (\<exists>rs. CR = rs @ r)" by auto then obtain lex rs where w_lex_rs: "l = Bk \<up> Suc lex @ [Bk,Oc] @ CL \<and> CR = rs @ r" by blast show ?thesis proof (cases r) case Nil then have "r=[]" . with w_lex_rs have "CR = rs" by auto have "step0 (7, Bk \<up> Suc lex @ [Bk,Oc] @ CL, []) tm_erase_right_then_dblBk_left = (9, Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL, [])" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover with \<open>CR = rs\<close> have "inv_tm_erase_right_then_dblBk_left_erp CL CR (9, Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL, [])" proof - have "(\<exists>lex'. Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL = Bk \<up> Suc lex' @ [Bk,Oc] @ CL)" by blast moreover have "\<exists>rs. CR = rs" by auto ultimately show "inv_tm_erase_right_then_dblBk_left_erp CL CR (9, Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL, [])" by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 7\<close> and w_lex_rs and \<open>CR = rs\<close> and \<open>r=[]\<close> by auto next case (Cons a rs') then have "r = a # rs'" . show ?thesis proof (cases a) case Bk then have "a = Bk" . with w_lex_rs and \<open>r = a # rs'\<close> have "CR = rs@(Bk#rs')" by auto have "step0 (7, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Bk#rs') tm_erase_right_then_dblBk_left = (9, Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL, rs')" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover with \<open>CR = rs@(Bk#rs')\<close> have "inv_tm_erase_right_then_dblBk_left_erp CL CR (9, Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL, rs')" proof - have "(\<exists>lex'. Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL = Bk \<up> Suc lex' @ [Bk,Oc] @ CL)" by blast moreover with \<open>r = a # rs'\<close> and \<open>a = Bk\<close> and \<open>CR = rs@(Bk#rs')\<close> have "\<exists>rs. CR = rs @ [Bk] @ rs'" by auto ultimately show "inv_tm_erase_right_then_dblBk_left_erp CL CR (9, Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL, rs')" by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 7\<close> and w_lex_rs and \<open>a = Bk\<close> and \<open>r = a # rs'\<close> by simp next case Oc then have "a = Oc" . with w_lex_rs and \<open>r = a # rs'\<close> have "CR = rs@(Oc#rs')" by auto have "step0 (7, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Oc#rs') tm_erase_right_then_dblBk_left = (8, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Bk#rs')" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (8, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Bk#rs')" proof - have "(\<exists>lex'. Bk \<up> Suc lex @ [Bk,Oc] @ CL = Bk \<up> Suc lex' @ [Bk,Oc] @ CL)" by blast moreover with \<open>r = a # rs'\<close> and \<open>a = Oc\<close> and \<open>CR = rs@(Oc#rs')\<close> have "\<exists>rs1 rs2. CR = rs1 @ [Oc] @ rs2 \<and> Bk#rs' = Bk#rs2" by auto ultimately show "inv_tm_erase_right_then_dblBk_left_erp CL CR (8, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Bk#rs')" by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 7\<close> and w_lex_rs and \<open>a = Oc\<close> and \<open>r = a # rs'\<close> by simp qed qed next assume "s = 8" with cf_cases and assms have "((\<exists>lex. l = Bk \<up> Suc lex @ [Bk,Oc] @ CL) \<and> (\<exists>rs1 rs2. CR = rs1 @ [Oc] @ rs2 \<and> r = Bk#rs2) )" by auto then obtain lex rs1 rs2 where w_lex_rs1_rs2: "l = Bk \<up> Suc lex @ [Bk,Oc] @ CL \<and> CR = rs1 @ [Oc] @ rs2 \<and> r = Bk#rs2" by blast have "step0 (8, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Bk#rs2) tm_erase_right_then_dblBk_left = (7, Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL, rs2)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (7, Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL, rs2)" proof - have "(\<exists>lex'. Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL = Bk \<up> Suc lex' @ [Bk,Oc] @ CL)" by blast moreover have "\<exists>rs. CR = rs @ []" by auto ultimately show "inv_tm_erase_right_then_dblBk_left_erp CL CR (7, Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL, rs2)" using w_lex_rs1_rs2 by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 8\<close> and w_lex_rs1_rs2 by auto next assume "s = 9" with cf_cases and assms have "(\<exists>lex. l = Bk \<up> Suc lex @ [Bk,Oc] @ CL) \<and> (\<exists>rs. CR = rs @ [Bk] @ r \<or> CR = rs \<and> r = [])" by auto then obtain lex rs where w_lex_rs: "l = Bk \<up> Suc lex @ [Bk,Oc] @ CL \<and> (CR = rs @ [Bk] @ r \<or> CR = rs \<and> r = [])" by blast then have "CR = rs @ [Bk] @ r \<or> CR = rs \<and> r = []" by auto then show ?thesis proof assume "CR = rs \<and> r = []" have "step0 (9, Bk \<up> Suc lex @ [Bk,Oc] @ CL, []) tm_erase_right_then_dblBk_left = (10, Bk \<up> lex @ [Bk,Oc] @ CL, [Bk])" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover with \<open>CR = rs \<and> r = []\<close> have "inv_tm_erase_right_then_dblBk_left_erp CL CR (10, Bk \<up> lex @ [Bk,Oc] @ CL, [Bk])" proof - from w_lex_rs and \<open>CR = rs \<and> r = []\<close> have "\<exists>lex' rex. Bk \<up> lex @ [Bk,Oc] @ CL = Bk \<up> lex' @ [Bk,Oc] @ CL \<and> [Bk] = Bk \<up> Suc rex" by (simp) then show "inv_tm_erase_right_then_dblBk_left_erp CL CR (10, Bk \<up> lex @ [Bk,Oc] @ CL, [Bk])" by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 9\<close> and w_lex_rs and \<open>CR = rs \<and> r = []\<close> by auto next assume "CR = rs @ [Bk] @ r" show ?thesis proof (cases r) case Nil then have "r=[]" . have "step0 (9, Bk \<up> Suc lex @ [Bk,Oc] @ CL, []) tm_erase_right_then_dblBk_left = (10, Bk \<up> lex @ [Bk,Oc] @ CL, [Bk])" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover with \<open>CR = rs @ [Bk] @ r\<close> have "inv_tm_erase_right_then_dblBk_left_erp CL CR (10, Bk \<up> lex @ [Bk,Oc] @ CL, [Bk])" proof - from w_lex_rs and \<open>CR = rs @ [Bk] @ r\<close> have "\<exists>lex' rex. Bk \<up> lex @ [Bk,Oc] @ CL = Bk \<up> lex' @ [Bk,Oc] @ CL \<and> [Bk] = Bk \<up> Suc rex" by (simp) with \<open>s=9\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (10, Bk \<up> lex @ [Bk,Oc] @ CL, [Bk])" by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 9\<close> and w_lex_rs and \<open>r=[]\<close> by auto next case (Cons a rs') then have "r = a # rs'" . show ?thesis proof (cases a) case Bk then have "a = Bk" . with \<open>CR = rs @ [Bk] @ r\<close> and \<open>r = a # rs'\<close> have "CR = rs @ [Bk] @ Bk # rs'" by auto moreover from assms have "noDblBk CR" by auto ultimately have False using hasDblBk_L1 by auto then show ?thesis by auto next case Oc then have "a = Oc" . with \<open>CR = rs @ [Bk] @ r\<close> and \<open>r = a # rs'\<close> have "CR = rs @ [Bk] @ Oc # rs'" by auto have "step0 (9, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Oc # rs') tm_erase_right_then_dblBk_left = (8, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Bk # rs')" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (8, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Bk # rs')" proof - have "(\<exists>lex'. Bk \<up> Suc lex @ [Bk,Oc] @ CL = Bk \<up> Suc lex' @ [Bk,Oc] @ CL)" by blast moreover with \<open>r = a # rs'\<close> and \<open>a = Oc\<close> and \<open>CR = rs @ [Bk] @ Oc # rs'\<close> have "\<exists>rs1 rs2. CR = rs1 @ [Oc] @ rs2 \<and> Bk#rs' = Bk#rs2" by auto ultimately show "inv_tm_erase_right_then_dblBk_left_erp CL CR (8, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Bk#rs')" by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 9\<close> and w_lex_rs and \<open>a = Oc\<close> and \<open>r = a # rs'\<close> by simp qed qed qed next assume "s = 10" with cf_cases and assms have "(\<exists>lex rex. l = Bk \<up> lex @ [Bk,Oc] @ CL \<and> r = Bk \<up> Suc rex) \<or> (\<exists>rex. l = [Oc] @ CL \<and> r = Bk \<up> Suc rex) \<or> (\<exists>rex. l = CL \<and> r = Oc # Bk \<up> Suc rex)" by auto then obtain lex rex where w_lex_rex: "l = Bk \<up> lex @ [Bk,Oc] @ CL \<and> r = Bk \<up> Suc rex \<or> l = [Oc] @ CL \<and> r = Bk \<up> Suc rex \<or> l = CL \<and> r = Oc # Bk \<up> Suc rex" by blast then show ?thesis proof assume "l = Bk \<up> lex @ [Bk, Oc] @ CL \<and> r = Bk \<up> Suc rex" then have "l = Bk \<up> lex @ [Bk, Oc] @ CL" and "r = Bk \<up> Suc rex" by auto show ?thesis proof (cases lex) case 0 with \<open>l = Bk \<up> lex @ [Bk, Oc] @ CL\<close> have "l = [Bk, Oc] @ CL" by auto have "step0 (10, [Bk, Oc] @ CL, Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (10, [Oc] @ CL, Bk \<up> Suc (Suc rex))" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (10, [Oc] @ CL, Bk \<up> Suc (Suc rex))" proof - from \<open>l = [Bk, Oc] @ CL\<close> and \<open>r = Bk \<up> Suc rex\<close> have "\<exists>rex'. [Oc] @ CL = [Oc] @ CL \<and> Bk \<up> Suc (Suc rex) = Bk \<up> Suc rex'" by blast with \<open>l = [Bk, Oc] @ CL\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (10, [Oc] @ CL, Bk \<up> Suc (Suc rex))" by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 10\<close> and \<open>l = [Bk, Oc] @ CL\<close> and \<open>r = Bk \<up> Suc rex\<close> by auto next case (Suc nat) then have "lex = Suc nat" . with \<open>l = Bk \<up> lex @ [Bk, Oc] @ CL\<close> have "l= Bk \<up> Suc nat @ [Bk, Oc] @ CL" by auto have "step0 (10, Bk \<up> Suc nat @ [Bk, Oc] @ CL, Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (10, Bk \<up> nat @ [Bk, Oc] @ CL, Bk \<up> Suc (Suc rex))" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (10, Bk \<up> nat @ [Bk, Oc] @ CL, Bk \<up> Suc (Suc rex))" proof - from \<open>l= Bk \<up> Suc nat @ [Bk, Oc] @ CL\<close> and \<open>r = Bk \<up> Suc rex\<close> have "\<exists>lex' rex'. Bk \<up> Suc nat @ [Bk, Oc] @ CL = Bk \<up> lex' @ [Bk,Oc] @ CL \<and> Bk \<up> Suc (Suc rex) = Bk \<up> Suc rex'" by blast with \<open>l= Bk \<up> Suc nat @ [Bk, Oc] @ CL\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (10, Bk \<up> nat @ [Bk, Oc] @ CL, Bk \<up> Suc (Suc rex))" by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 10\<close> and \<open>l= Bk \<up> Suc nat @ [Bk, Oc] @ CL\<close> and \<open>r = Bk \<up> Suc rex\<close> by auto qed next assume "l = [Oc] @ CL \<and> r = Bk \<up> Suc rex \<or> l = CL \<and> r = Oc # Bk \<up> Suc rex" then show ?thesis proof assume "l = [Oc] @ CL \<and> r = Bk \<up> Suc rex" then have "l = [Oc] @ CL" and "r = Bk \<up> Suc rex" by auto have "step0 (10, [Oc] @ CL, Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (10, CL, Oc# Bk \<up> (Suc rex))" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (10, CL, Oc# Bk \<up> (Suc rex))" proof - from \<open>l = [Oc] @ CL\<close> and \<open>r = Bk \<up> Suc rex\<close> have "\<exists>rex'. [Oc] @ CL = [Oc] @ CL \<and> Bk \<up> Suc rex = Bk \<up> Suc rex'" by blast with \<open>l = [Oc] @ CL\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (10, CL, Oc# Bk \<up> (Suc rex))" by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 10\<close> and \<open>l = [Oc] @ CL\<close> and \<open>r = Bk \<up> Suc rex\<close> by auto next assume "l = CL \<and> r = Oc # Bk \<up> Suc rex" then have "l = CL" and "r = Oc # Bk \<up> Suc rex" by auto show ?thesis proof (cases CL) (* here, we start decomposing CL in the loop 'move to left until Oc *) case Nil then have "CL = []" . with \<open>l = CL\<close> have "l = []" by auto have "step0 (10, [], Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (11, [], Bk#Oc# Bk \<up> (Suc rex))" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, [], Bk#Oc# Bk \<up> (Suc rex))" proof - (* Special case: CL = [] from call (1, [Oc, Bk], []) we get 11: [] _11_ [Bk,Oc,Bk,Bk,Bk] YYYY1' "\<exists>rex'. ] = [] \<and> Bk# Oc# Bk \<up> Suc rex = [Bk] @ rev CL @ Oc # Bk \<up> Suc rex' \<and> (CL = [] \<or> last CL = Oc)" *) from \<open>CL = []\<close> have "\<exists>rex'. [] = [] \<and> Bk# Oc# Bk \<up> Suc rex = [Bk] @ rev CL @ Oc # Bk \<up> Suc rex' \<and> (CL = [] \<or> last CL = Oc)" by auto with \<open>l = []\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, [], Bk#Oc# Bk \<up> (Suc rex))" by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 10\<close> and \<open>l = []\<close> and \<open>r = Oc # Bk \<up> Suc rex\<close> by auto next case (Cons a cls) then have "CL = a # cls" . with \<open>l = CL\<close> have "l = a # cls" by auto then show ?thesis proof (cases a) case Bk then have "a = Bk" . with \<open>l = a # cls\<close> have "l = Bk # cls" by auto with \<open>a = Bk\<close> \<open>CL = a # cls\<close> have "CL = Bk # cls" by auto have "step0 (10, Bk # cls, Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (11, cls, Bk# Oc # Bk \<up> Suc rex)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, cls, Bk# Oc # Bk \<up> Suc rex)" proof (cases cls) case Nil then have "cls = []" . with \<open>CL = Bk # cls\<close> have "CL = [Bk]" by auto (* Special case: CL ends with a blank from call ctxrunTM tm_erase_right_then_dblBk_left (1, [Bk, Oc,Bk], [Bk,Oc,Oc,Bk,Oc,Oc]) 24: [Bk] _10_ [Oc,Bk,Bk,Bk,Bk,Bk,Bk,Bk,Bk] 25: [] _11_ [Bk,Oc,Bk,Bk,Bk,Bk,Bk,Bk,Bk,Bk] YYYY2' "\<exists>rex'. [] = [] \<and> Bk# Oc# Bk \<up> Suc rex = rev CL @ Oc # Bk \<up> Suc rex' \<and> \<and> CL \<noteq> [] \<and> last CL = Bk" *) then have "\<exists>rex'. [] = [] \<and> Bk# Oc# Bk \<up> Suc rex = rev CL @ Oc # Bk \<up> Suc rex' \<and> CL \<noteq> [] \<and> last CL = Bk" by auto with \<open>l = Bk # cls\<close> and \<open>cls = []\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, cls, Bk# Oc # Bk \<up> Suc rex)" by auto next case (Cons a cls') then have "cls = a # cls'" . then show ?thesis proof (cases a) case Bk with \<open>CL = Bk # cls\<close> and \<open>cls = a # cls'\<close> have "CL = Bk# Bk# cls'" by auto with \<open>noDblBk CL\<close> have False using noDblBk_def by auto then show ?thesis by auto next case Oc then have "a = Oc" . with \<open>CL = Bk # cls\<close> and \<open>cls = a # cls'\<close> and \<open>l = Bk # cls\<close> have "CL = Bk# Oc# cls' \<and> l = Bk # Oc # cls'" by auto (* from call (1, [Oc,Oc,Bk,Oc,Bk], [Oc,Oc,Oc,Bk,Oc,Oc]) we get 26: [Oc,Oc] _11_ [Bk,Oc,Bk,Bk,Bk,Bk,Bk,Bk,Bk,Bk] YYYY3 "\<exists>rex' ls1 ls2. Oc#cls' = Oc#ls2 \<and> Bk# Oc# Bk \<up> Suc rex = rev ls1 @ Oc # Bk \<up> Suc rex' \<and> CL = ls1 @ Oc#ls2 \<and> ls1 = [Bk]" *) with \<open>cls = a # cls'\<close> and \<open>a=Oc\<close> have "\<exists>rex' ls1 ls2. Oc#cls' = Oc#ls2 \<and> Bk# Oc# Bk \<up> Suc rex = rev ls1 @ Oc # Bk \<up> Suc rex' \<and> CL = ls1 @ Oc#ls2 \<and> ls1 = [Bk]" by auto with \<open>cls = a # cls'\<close> and \<open>a=Oc\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, cls, Bk# Oc # Bk \<up> Suc rex)" by auto qed qed ultimately show ?thesis using assms and cf_cases and \<open>s = 10\<close> and \<open>l = Bk # cls\<close> and \<open>r = Oc # Bk \<up> Suc rex\<close> by auto next case Oc then have "a = Oc" . with \<open>l = a # cls\<close> have "l = Oc # cls" by auto with \<open>a = Oc\<close> \<open>CL = a # cls\<close> have "CL = Oc # cls" by auto (* a normal case *) have "step0 (10, Oc # cls, Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (11, cls, Oc # Oc # Bk \<up> Suc rex)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, cls, Oc # Oc # Bk \<up> Suc rex)" proof (cases cls) case Nil then have "cls = []" . with \<open>CL = Oc # cls\<close> have "CL = [Oc]" by auto (* from call (1, [Oc,Oc,Bk], [Oc,Oc,Oc,Bk,Oc,Oc]) we get 26: [] _11_ [Oc,Oc,Bk,Bk,Bk,Bk,Bk,Bk,Bk,Bk] YYYY2'' "\<exists>rex'. [] = [] \<and> Oc# Oc# Bk \<up> Suc rex = rev CL @ Oc # Bk \<up> Suc rex' \<and> CL \<noteq> [] \<and> last CL = Oc" *) then have "\<exists>rex'. [] = [] \<and> Oc# Oc# Bk \<up> Suc rex = rev CL @ Oc # Bk \<up> Suc rex' \<and> CL \<noteq> [] \<and> last CL = Oc" by auto with \<open>l = Oc # cls\<close> and \<open>cls = []\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, cls, Oc# Oc # Bk \<up> Suc rex)" by auto next case (Cons a cls') then have "cls = a # cls'" . then show ?thesis proof (cases a) case Bk then have "a=Bk" . with \<open>CL = Oc # cls\<close> and \<open>cls = a # cls'\<close> and \<open>l = Oc # cls\<close> have "CL = Oc# Bk# cls'" and "l = Oc # Bk # cls'" and "CL = l" and \<open>cls = Bk # cls'\<close> by auto from \<open>CL = Oc# Bk# cls'\<close> and \<open>noDblBk CL\<close> have "cls' = [] \<or> (\<exists>cls''. cls' = Oc# cls'')" by (metis (full_types) \<open>CL = Oc # cls\<close> \<open>cls = Bk # cls'\<close> append_Cons append_Nil cell.exhaust hasDblBk_L1 neq_Nil_conv) then show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, cls, Oc # Oc # Bk \<up> Suc rex)" proof assume "cls' = []" with \<open>CL = Oc# Bk# cls'\<close> and \<open>CL = l\<close> and \<open>cls = Bk # cls'\<close> have "CL = Oc# Bk# []" and "l = Oc# Bk# []" and "cls = [Bk]" by auto (* from call (1, [Bk,Oc,Oc,Bk], [Oc,Oc,Oc,Bk,Oc,Oc]) we get 26: [Bk] _11_ [Oc,Oc,Bk,Bk,Bk,Bk,Bk,Bk,Bk,Bk] YYYY5 "\<exists>rex'. cls = [Bk] \<and> Oc# Oc# Bk \<up> Suc rex = rev [Oc] @ Oc # Bk \<up> Suc rex' \<and> CL = [Oc, Bk]" *) then have "\<exists>rex'. cls = [Bk] \<and> Oc# Oc# Bk \<up> Suc rex = rev [Oc] @ Oc # Bk \<up> Suc rex' \<and> CL = [Oc, Bk]" by auto with \<open>CL = Oc# Bk# []\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, cls, Oc # Oc # Bk \<up> Suc rex)" by auto next assume "\<exists>cls''. cls' = Oc # cls''" then obtain cls'' where "cls' = Oc # cls''" by blast with \<open>CL = Oc# Bk# cls'\<close> and \<open>CL = l\<close> and \<open>cls = Bk # cls'\<close> have "CL = Oc# Bk# Oc # cls''" and "l = Oc# Bk# Oc # cls''" and "cls = Bk#Oc # cls''" by auto (* very special case call (1, [*,Oc,Bk, Oc,Oc,Bk], [Oc,Oc,Oc,Bk,Oc,Oc]) trailing Bk on initial left tape from call (1, [Oc,Bk, Oc,Oc,Bk], [Oc,Oc,Oc,Bk,Oc,Oc]) we get 26: [Oc,Bk] _11_ [Oc,Oc,Bk,Bk,Bk,Bk,Bk,Bk,Bk,Bk] from call (1, [Oc,Oc,Bk,Oc,Bk, Oc,Oc,Bk], [Oc,Oc,Oc,Bk,Oc,Oc]) we get 26: [Oc,Oc,Bk,Oc,Bk] _11_ [Oc,Oc,Bk,Bk,Bk,Bk,Bk,Bk,Bk,Bk] YYYY6 "\<exists>rex' ls1 ls2. cls = Bk#Oc#ls2 \<and> Oc# Oc# Bk \<up> Suc rex = rev ls1 @ Oc # Bk \<up> Suc rex' \<and> CL = ls1 @ Bk#Oc#ls2 \<and> ls1 = [Oc]" *) then have "\<exists>rex' ls1 ls2. cls = Bk#Oc#ls2 \<and> Oc# Oc# Bk \<up> Suc rex = rev ls1 @ Oc # Bk \<up> Suc rex' \<and> CL = ls1 @ Bk#Oc#ls2 \<and> ls1 = [Oc]" by auto then show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, cls, Oc # Oc # Bk \<up> Suc rex)" by auto qed next case Oc then have "a=Oc" . with \<open>CL = Oc # cls\<close> and \<open>cls = a # cls'\<close> and \<open>l = Oc # cls\<close> have "CL = Oc# Oc# cls'" and "l = Oc # Oc # cls'" and "CL = l" and \<open>cls = Oc # cls'\<close> by auto (* We know more : ls1 = [Oc] YYYY7 "\<exists>rex' ls1 ls2. cls = Oc#ls2 \<and> Oc# Oc# Bk \<up> Suc rex = rev ls1 @ Oc # Bk \<up> Suc rex' \<and> CL = ls1 @ Oc#ls2 \<and> ls1 = [Oc]" "\<exists>rex' ls1 ls2. cls = Oc#ls2 \<and> Oc# Oc# Bk \<up> Suc rex = rev ls1 @ Oc # Bk \<up> Suc rex' \<and> CL = ls1 @ Oc#ls2 \<and> ls1 = [Oc]" *) then have "\<exists>rex' ls1 ls2. cls = Oc#ls2 \<and> Oc# Oc# Bk \<up> Suc rex = rev ls1 @ Oc # Bk \<up> Suc rex' \<and> CL = ls1 @ Oc#ls2 \<and> ls1 = [Oc]" by auto then show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, cls, Oc # Oc # Bk \<up> Suc rex)" by auto qed qed ultimately show ?thesis using assms and cf_cases and \<open>s = 10\<close> and \<open>l = Oc # cls\<close> and \<open>r = Oc # Bk \<up> Suc rex\<close> by auto qed qed qed qed next assume "s = 11" with cf_cases and assms have "(\<exists>rex. l = [] \<and> r = Bk# rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc)) \<or> (\<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk ) \<or> (\<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Oc ) \<or> (\<exists>rex. l = [Bk] \<and> r = rev [Oc] @ Oc # Bk \<up> Suc rex \<and> CL = [Oc, Bk]) \<or> (\<exists>rex ls1 ls2. l = Bk#Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Bk#Oc#ls2 \<and> ls1 = [Oc] ) \<or> (\<exists>rex ls1 ls2. l = Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc#ls2 \<and> ls1 = [Bk] ) \<or> (\<exists>rex ls1 ls2. l = Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc#ls2 \<and> ls1 = [Oc] ) \<or> (\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> [])" by auto then have s11_cases: "\<And>P. \<lbrakk> \<exists>rex. l = [] \<and> r = Bk# rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc) \<Longrightarrow> P; \<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk \<Longrightarrow> P; \<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Oc \<Longrightarrow> P; \<exists>rex. l = [Bk] \<and> r = rev [Oc] @ Oc # Bk \<up> Suc rex \<and> CL = [Oc, Bk] \<Longrightarrow> P; \<exists>rex ls1 ls2. l = Bk#Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Bk#Oc#ls2 \<and> ls1 = [Oc] \<Longrightarrow> P; \<exists>rex ls1 ls2. l = Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc#ls2 \<and> ls1 = [Bk] \<Longrightarrow> P; \<exists>rex ls1 ls2. l = Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc#ls2 \<and> ls1 = [Oc] \<Longrightarrow> P; \<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> [] \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" by blast show ?thesis proof (rule s11_cases) assume "\<exists>rex ls1 ls2. l = Bk # Oc # ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Bk # Oc # ls2 \<and> ls1 = [Oc]" then obtain rex ls1 ls2 where A_case: "l = Bk#Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Bk#Oc#ls2 \<and> ls1 = [Oc]" by blast then have "step0 (11, Bk # Oc # ls2, r) tm_erase_right_then_dblBk_left = (11, Oc # ls2, Bk # r)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, Oc # ls2, Bk # r)" proof - from A_case (* YYYY8 *) have "\<exists>rex' ls1' ls2'. Oc#ls2 = ls2' \<and> Bk# Oc# Oc# Bk \<up> Suc rex' = rev ls1' @ Oc # Bk \<up> Suc rex' \<and> CL = ls1' @ ls2' \<and> tl ls1' \<noteq> []" by force with A_case show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, Oc # ls2, Bk # r)" by auto qed ultimately show ?thesis using assms and cf_cases and \<open>s = 11\<close> and A_case by simp next assume "\<exists>rex ls1 ls2. l = Oc # ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc # ls2 \<and> ls1 = [Oc]" then obtain rex ls1 ls2 where A_case: "l = Oc # ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc # ls2 \<and> ls1 = [Oc]" by blast then have "step0 (11, Oc # ls2, r) tm_erase_right_then_dblBk_left = (11, ls2, Oc#r)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, ls2, Oc#r)" proof (rule noDblBk_cases) from \<open>noDblBk CL\<close> show "noDblBk CL" . next from A_case show "CL = [Oc,Oc] @ ls2" by auto next assume "ls2 = []" (* with A_case (* YYYY7''' *) have "\<exists>rex'. ls2 = [] \<and> [Oc,Oc] @ Oc # Bk \<up> Suc rex = rev CL @ Oc # Bk \<up> Suc rex' \<and> CL = [Oc, Oc]" by force *) with A_case (* YYYY2'' *) have "\<exists>rex'. ls2 = [] \<and> [Oc,Oc] @ Oc # Bk \<up> Suc rex = rev CL @ Oc # Bk \<up> Suc rex'" by force with A_case and \<open>ls2 = []\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, ls2, Oc#r)" by auto next assume "ls2 = [Bk]" (* YYYY8 *) with A_case have "\<exists>rex' ls1' ls2'. ls2 = ls2' \<and> Oc#Oc# Oc# Bk \<up> Suc rex = rev ls1' @ Oc # Bk \<up> Suc rex' \<and> CL = ls1' @ ls2' \<and> hd ls1' = Oc \<and> tl ls1' \<noteq> []" by simp with A_case and \<open>ls2 = [Bk]\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, ls2, Oc#r)" by force next fix C3 assume "ls2 = Bk # Oc # C3" (* YYYY8 *) with A_case have "\<exists>rex' ls1' ls2'. ls2 = ls2' \<and> Oc#Oc# Oc# Bk \<up> Suc rex = rev ls1' @ Oc # Bk \<up> Suc rex' \<and> CL = ls1' @ ls2' \<and> hd ls1' = Oc \<and> tl ls1' \<noteq> []" by simp with A_case and \<open>ls2 = Bk # Oc # C3\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, ls2, Oc#r)" by force next fix C3 assume "ls2 = Oc # C3" (* YYYY8 *) with A_case have "\<exists>rex' ls1' ls2'. ls2 = ls2' \<and> Oc#Oc# Oc# Bk \<up> Suc rex = rev ls1' @ Oc # Bk \<up> Suc rex' \<and> CL = ls1' @ ls2' \<and> hd ls1' = Oc \<and> tl ls1' \<noteq> []" by simp with A_case and \<open>ls2 = Oc # C3\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, ls2, Oc#r)" by force qed ultimately show ?thesis using assms and cf_cases and \<open>s = 11\<close> and A_case by simp next assume "\<exists>rex. l = [Bk] \<and> r = rev [Oc] @ Oc # Bk \<up> Suc rex \<and> CL = [Oc, Bk]" then obtain rex where A_case: "l = [Bk] \<and> r = rev [Oc] @ Oc # Bk \<up> Suc rex \<and> CL = [Oc, Bk]" by blast then have "step0 (11, [Bk] , r) tm_erase_right_then_dblBk_left = (11, [], Bk#r)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, [], Bk#r)" proof - from A_case (* have "\<exists>rex'. [] = [] \<and> Bk#rev [Oc] @ Oc # Bk \<up> Suc rex = rev CL @ Oc # Bk \<up> Suc rex' \<and> CL = [Oc, Bk]" (* YYYY5' *) by simp *) have "\<exists>rex'. [] = [] \<and> Bk#rev [Oc] @ Oc # Bk \<up> Suc rex = rev CL @ Oc # Bk \<up> Suc rex'" (* YYYY2' *) by simp with A_case show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, [], Bk#r)" by force qed ultimately show ?thesis using assms and cf_cases and \<open>s = 11\<close> and A_case by simp next (* YYYY8 for s11 *) assume "\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> []" then obtain rex ls1 ls2 where A_case: "l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> []" by blast then have "\<exists>z b bs. ls1 = z#bs@[b]" (* the symbol z does not matter *) by (metis Nil_tl list.exhaust_sel rev_exhaust) then have "\<exists>z bs. ls1 = z#bs@[Bk] \<or> ls1 = z#bs@[Oc]" using cell.exhaust by blast then obtain z bs where w_z_bs: "ls1 = z#bs@[Bk] \<or> ls1 = z#bs@[Oc]" by blast then show "inv_tm_erase_right_then_dblBk_left_erp CL CR (step0 cf tm_erase_right_then_dblBk_left)" proof assume major1: "ls1 = z # bs @ [Bk]" then have major2: "rev ls1 = Bk#(rev bs)@[z]" by auto (* in this case all transitions will be s11 \<longrightarrow> s12 *) show ?thesis proof (rule noDblBk_cases) from \<open>noDblBk CL\<close> show "noDblBk CL" . next from A_case show "CL = ls1 @ ls2" by auto next assume "ls2 = []" with A_case have "step0 (11, [] , Bk#(rev bs)@[z] @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (12, [], Bk#Bk#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (12, [], Bk#Bk#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" proof - from A_case \<open>rev ls1 = Bk#(rev bs)@[z]\<close> and \<open>ls2 = []\<close> have "ls1 = z#bs@[Bk]" and "CL = ls1" and "r = rev CL @ Oc # Bk \<up> Suc rex" by auto (* YYYY6''' \<exists>rex. l = [] \<and> r = Bk#rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk *) with A_case \<open>rev ls1 = Bk#(rev bs)@[z]\<close> and \<open>ls2 = []\<close> have "\<exists>rex'. [] = [] \<and> Bk#Bk#(rev bs)@[z] @ Oc # Bk \<up> Suc rex = Bk#rev CL @ Oc # Bk \<up> Suc rex' \<and> CL \<noteq> [] \<and> last CL = Bk" by simp with A_case \<open>rev ls1 = Bk#(rev bs)@[z]\<close> and \<open>ls2 = []\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (12, [], Bk#Bk#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" by force qed ultimately show ?thesis using assms and cf_cases and \<open>s = 11\<close> and A_case and \<open>rev ls1 = Bk#(rev bs)@[z]\<close> and \<open>ls2 = []\<close> by simp next assume "ls2 = [Bk]" (* A_case: l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> hd ls1 = Oc \<and> tl ls1 \<noteq> [] *) with A_case \<open>rev ls1 = Bk#(rev bs)@[z]\<close> and \<open>ls2 = [Bk]\<close> have "ls1 = z#bs@[Bk]" and "CL = z#bs@[Bk]@[Bk]" by auto with \<open>noDblBk CL\<close> have False by (metis A_case \<open>ls2 = [Bk]\<close> append_Cons hasDblBk_L5 major2) then show ?thesis by auto next fix C3 assume minor: "ls2 = Bk # Oc # C3" with A_case and major2 have "CL = z # bs @ [Bk] @ Bk # Oc # C3" by auto with \<open>noDblBk CL\<close> have False by (metis append.left_neutral append_Cons append_assoc hasDblBk_L1 major1 minor) then show ?thesis by auto next fix C3 assume minor: "ls2 = Oc # C3" (* A_case: "l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> hd ls1 = Oc \<and> tl ls1 \<noteq> []" major1: "ls1 = Oc # bs @ [Bk]" major2: "rev ls1 = Bk # rev bs @ [Oc]" minor1: "ls2 = Oc # C3" l = Oc # C3 r = rev ls1 @ Oc # Bk \<up> Suc rex r = Bk#(rev bs)@[Oc] @ Oc # Bk \<up> Suc rex thus: s11 \<longrightarrow> s12 (12, C3, Oc#Bk#(rev bs)@[Oc] @ Oc # Bk \<up> Suc rex ) l' = C3 r' = Oc#Bk#(rev bs)@[Oc] @ Oc # Bk \<up> Suc rex ls2' = C3 rev ls1' = Oc#Bk#(rev bs)@[Oc] ls1' = Oc# bs @ [Bk] @ [Oc] = ls1@[Oc] CL = ls1 @ ls2 = ls1 @ Oc # C3 = ls1 @ [Oc] @ [C3] = ls1' @ ls2' \<and> hd ls1 = Oc \<and> tl ls1 \<noteq> [] (\<exists>rex' ls1' ls2'. C3 = ls2' \<and> Oc#Bk#(rev bs)@[Oc] @ Oc # Bk \<up> Suc rex = rev ls1' @ Oc # Bk \<up> Suc rex' \<and> CL = ls1' @ ls2' \<and> hd ls1' = Oc \<and> tl ls1' \<noteq> [] \<and> last ls1' = Oc) again YYYY4 (\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> hd ls1 = Oc \<and> tl ls1 \<noteq> [] \<and> last ls1 = Oc) *) with A_case have "step0 (11, Oc # C3 , Bk#(rev bs)@[z] @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (12, C3, Oc#Bk#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (12, C3, Oc#Bk#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" proof - from A_case and \<open>rev ls1 = Bk # rev bs @ [z]\<close> and \<open>ls2 = Oc # C3\<close> and \<open>ls1 = z # bs @ [Bk]\<close> have "\<exists>rex' ls1' ls2'. C3 = ls2' \<and> Oc#Bk#(rev bs)@[z] @ Oc # Bk \<up> Suc rex = rev ls1' @ Oc # Bk \<up> Suc rex' \<and> CL = ls1' @ ls2' \<and> hd ls1' = z \<and> tl ls1' \<noteq> [] \<and> last ls1' = Oc" by simp with A_case \<open>rev ls1 = Bk # rev bs @ [z]\<close> and \<open>ls2 = Oc # C3\<close> and \<open>ls1 = z # bs @ [Bk]\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (12, C3, Oc#Bk#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" by simp qed ultimately show ?thesis using assms and cf_cases and \<open>s = 11\<close> and A_case and \<open>rev ls1 = Bk#(rev bs)@[z]\<close> and \<open>ls2 = Oc # C3\<close> by simp qed next assume major1: "ls1 = z # bs @ [Oc]" then have major2: "rev ls1 = Oc#(rev bs)@[z]" by auto (* in this case all transitions will be s11 \<longrightarrow> s11 *) show ?thesis proof (rule noDblBk_cases) from \<open>noDblBk CL\<close> show "noDblBk CL" . next from A_case show "CL = ls1 @ ls2" by auto next assume "ls2 = []" (* A_case: l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> hd ls1 = Oc \<and> tl ls1 \<noteq> [] l = [] r = rev ls1 @ Oc # Bk \<up> Suc rex r = Oc#(rev bs)@[Oc] @ Oc # Bk \<up> Suc rex l' = [] r' = Bk#Oc#(rev bs)@[Oc] @ Oc # Bk \<up> Suc rex ls1 = Oc # bs @ [Oc] rev ls1 = Oc#(rev bs)@[Oc] rev ls1' = Bk#Oc#(rev bs)@[Oc] ls1' = Oc # bs @ [Oc] @ [Bk] ls2' = [] CL = ls1 @ ls2 = (Oc # bs @ [Oc]) @ [] = Oc # bs @ [Oc] = ls1 rev ls1 = rev CL \<exists>rex'. [] = [] \<and> Bk#Oc#(rev bs)@[Oc] @ Oc # Bk \<up> Suc rex = Bk#rev CL @ Oc # Bk \<up> Suc rex' \<and> last CL = Oc (\<exists>rex. l = [] \<and> r = Bk# rev CL @ Oc # Bk \<up> Suc rex \<and> last CL = Oc) we simplify YYYY1' (\<exists>rex. l = [] \<and> r = Bk# rev CL @ Oc # Bk \<up> Suc rex) now, we generalize to YYYY1' (\<exists>rex. l = [] \<and> r = Bk# rev CL @ Oc # Bk \<up> Suc rex) \<and> (CL = [] \<or> last CL = Oc) *) with A_case have "step0 (11, [] , Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (11, [], Bk#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, [], Bk#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" proof - from A_case \<open>rev ls1 = Oc#(rev bs)@[z]\<close> and \<open>ls2 = []\<close> have "ls1 = z # bs @ [Oc]" and "CL = ls1" and "r = rev CL @ Oc # Bk \<up> Suc rex" by auto (* new invariant for s11: YYYY1' (\<exists>rex. l = [] \<and> r = Bk# rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc)) *) with A_case \<open>rev ls1 = Oc#(rev bs)@[z]\<close> and \<open>ls2 = []\<close> have "\<exists>rex'. [] = [] \<and> Bk#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex = Bk#rev CL @ Oc # Bk \<up> Suc rex' \<and> (CL = [] \<or> last CL = Oc)" by simp with A_case \<open>rev ls1 = Oc#(rev bs)@[z]\<close> and \<open>ls2 = []\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, [], Bk#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" by force qed ultimately show ?thesis using assms and cf_cases and \<open>s = 11\<close> and A_case and \<open>rev ls1 = Oc#(rev bs)@[z]\<close> and \<open>ls2 = []\<close> by simp next assume "ls2 = [Bk]" (* A_case: l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> hd ls1 = Oc \<and> tl ls1 \<noteq> [] l = [Bk] r = rev ls1 @ Oc # Bk \<up> Suc rex r = Oc#(rev bs)@[Oc] @ Oc # Bk \<up> Suc rex l' = [] r' = Bk#Oc#(rev bs)@[Oc] @ Oc # Bk \<up> Suc rex ls1 = Oc # bs @ [Oc] rev ls1 = Oc#(rev bs)@[Oc] rev ls1' = Bk#Oc#(rev bs)@[Oc] ls1' = Oc # bs @ [Oc] @ [Bk] = ls1 @ [Bk] ls2' = [] CL = ls1 @ ls2 = (Oc # bs @ [Oc]) @ [Bk] = ls1 @ [Bk] = ls1' list functions (hd ls) and (last ls) are only usefull if ls \<noteq> [] is known! new invariant for s11: YYYY2' (\<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk) \<or> (s11 \<longrightarrow> s11) YYYY2'' (\<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Oc) \<or> (s11 \<longrightarrow> s11) *) with A_case have "step0 (11, [Bk] , Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (11, [], Bk#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, [], Bk#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" proof - from A_case \<open>rev ls1 = Oc#(rev bs)@[z]\<close> and \<open>ls2 = [Bk]\<close> have "ls1 = z # bs @ [Oc]" and "CL = ls1@[Bk]" by auto (* new invariant for s11: YYYY2' (\<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk) *) with A_case \<open>rev ls1 = Oc#(rev bs)@[z]\<close> and \<open>ls2 = [Bk]\<close> have "\<exists>rex'. [] = [] \<and> Bk#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex = rev CL @ Oc # Bk \<up> Suc rex' \<and> CL \<noteq> [] \<and> last CL = Bk" by simp with A_case \<open>rev ls1 = Oc#(rev bs)@[z]\<close> and \<open>ls2 = [Bk]\<close> and \<open>CL = ls1@[Bk]\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, [], Bk#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" by force qed ultimately show ?thesis using assms and cf_cases and \<open>s = 11\<close> and A_case and \<open>rev ls1 = Oc#(rev bs)@[z]\<close> and \<open>ls2 = [Bk]\<close> by simp next fix C3 assume minor: "ls2 = Bk # Oc # C3" (* thm A_case: l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> hd ls1 = Oc \<and> tl ls1 \<noteq> [] thm major1: ls1 = Oc # bs @ [Oc] thm major2: rev ls1 = Oc # rev bs @ [Oc] minor1: "ls2 = Bk # Oc # C3" l = Bk # Oc # C3 r = Oc#(rev bs)@[Oc] @ Oc # Bk \<up> Suc rex thus: s11 \<longrightarrow> s11 (11, Oc # C3, Bk#Oc#(rev bs)@[Oc] @ Oc # Bk \<up> Suc rex ) l' = Oc # C3 r' = Bk#Oc#(rev bs)@[Oc] @ Oc # Bk \<up> Suc rex ls2' = Oc # C3 rev ls1' = Bk#Oc#(rev bs)@[Oc] ls1' = Oc# bs @ [Oc] @ [Bk] = ls1@[Bk] CL = ls1 @ ls2 = ls1 @ Bk # Oc # C3 = ls1 @ [Bk] @ [Oc ,C3] = ls1' @ ls2' \<and> hd ls1 = Oc \<and> tl ls1 \<noteq> [] (\<exists>rex' ls1' ls2'. Oc # C3 = ls2' \<and> Bk#Oc#(rev bs)@[Oc] @ Oc # Bk \<up> Suc rex = rev ls1' @ Oc # Bk \<up> Suc rex' \<and> CL = ls1' @ ls2' \<and> hd ls1' = Oc \<and> tl ls1' \<noteq> []) again YYYY8 (\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> hd ls1 = Oc \<and> tl ls1 \<noteq> []) *) with A_case have "step0 (11, Bk # Oc # C3 , Oc # rev bs @ [z] @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (11, Oc # C3, Bk#Oc # rev bs @ [z] @ Oc # Bk \<up> Suc rex )" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, Oc # C3, Bk#Oc # rev bs @ [z] @ Oc # Bk \<up> Suc rex )" proof - from A_case and \<open>rev ls1 = Oc # rev bs @ [z]\<close> and \<open>ls2 = Bk # Oc # C3\<close> and \<open>ls1 = z # bs @ [Oc]\<close> have "\<exists>rex' ls1' ls2'. Oc # C3 = ls2' \<and> Bk#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex = rev ls1' @ Oc # Bk \<up> Suc rex' \<and> CL = ls1' @ ls2' \<and> hd ls1' = z \<and> tl ls1' \<noteq> [] " by simp with A_case \<open>rev ls1 = Oc # rev bs @ [z]\<close> and \<open>ls2 = Bk # Oc # C3\<close> and \<open>ls1 = z # bs @ [Oc]\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, Oc # C3, Bk#Oc # rev bs @ [z] @ Oc # Bk \<up> Suc rex )" by simp qed ultimately show ?thesis using assms and cf_cases and \<open>s = 11\<close> and A_case and \<open>rev ls1 = Oc # rev bs @ [z]\<close> and \<open>ls2 = Bk # Oc # C3\<close> by simp next fix C3 assume minor: "ls2 = Oc # C3" (* A_case: "l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> hd ls1 = Oc \<and> tl ls1 \<noteq> []" major1: "ls1 = Oc # bs @ [Oc]" major2: "rev ls1 = Oc # rev bs @ [Oc]" minor1: "ls2 = Oc # C3" l = Oc # C3 r = rev ls1 @ Oc # Bk \<up> Suc rex r = Oc#(rev bs)@[Oc] @ Oc # Bk \<up> Suc rex thus: s11 \<longrightarrow> s11 (11, C3, Oc#Oc#(rev bs)@[Oc] @ Oc # Bk \<up> Suc rex ) l' = C3 r' = Oc#Oc#(rev bs)@[Oc] @ Oc # Bk \<up> Suc rex ls2' = C3 rev ls1' = Oc#Oc#(rev bs)@[Oc] ls1' = Oc# bs @ [Oc] @ [Oc] = ls1@[Oc] CL = ls1 @ ls2 = ls1 @ Oc # C3 = ls1 @ [Oc] @ [C3] = ls1' @ ls2' \<and> hd ls1 = Oc \<and> tl ls1 \<noteq> [] (\<exists>rex' ls1' ls2'. C3 = ls2' \<and> Oc#Oc#(rev bs)@[Oc] @ Oc # Bk \<up> Suc rex = rev ls1' @ Oc # Bk \<up> Suc rex' \<and> CL = ls1' @ ls2' \<and> hd ls1' = Oc \<and> tl ls1' \<noteq> []) again YYYY8 (\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> hd ls1 = Oc \<and> tl ls1 \<noteq> []) *) with A_case have "step0 (11, Oc # C3 , Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (11, C3, Oc#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, C3, Oc#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" proof - from A_case and \<open>rev ls1 = Oc # rev bs @ [z]\<close> and \<open>ls2 = Oc # C3\<close> and \<open>ls1 = z # bs @ [Oc]\<close> have "\<exists>rex' ls1' ls2'. C3 = ls2' \<and> Oc#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex = rev ls1' @ Oc # Bk \<up> Suc rex' \<and> CL = ls1' @ ls2' \<and> hd ls1' = z \<and> tl ls1' \<noteq> []" by simp with A_case \<open>rev ls1 = Oc # rev bs @ [z]\<close> and \<open>ls2 = Oc # C3\<close> and \<open>ls1 = z # bs @ [Oc]\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, C3, Oc#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" by simp qed ultimately show ?thesis using assms and cf_cases and \<open>s = 11\<close> and A_case and \<open>rev ls1 = Oc # rev bs @ [z]\<close> and \<open>ls2 = Oc # C3\<close> by simp qed qed next (* YYYY3 *) assume "\<exists>rex ls1 ls2. l = Oc # ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc # ls2 \<and> ls1 = [Bk]" then obtain rex ls1 ls2 where A_case: "l = Oc # ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc # ls2 \<and> ls1 = [Bk]" by blast then have major2: "rev ls1 = [Bk]" by auto (* "l = Oc # ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc # ls2 \<and> ls1 = [Bk]" l = Oc # ls2 r = rev ls1 @ Oc # Bk \<up> Suc rex r = [Bk] @ Oc # Bk \<up> Suc rex l' = ls2 r' = Oc#[Bk] @ Oc # Bk \<up> Suc rex \<longrightarrow> s12: (12, ls2, Oc#[Bk] @ Oc # Bk \<up> Suc rex ) ls1 = [Bk] rev ls1 = [Bk] rev ls1' = Oc#[Bk] ls1' = Bk#[Oc] ls2' = ls2 CL = ls1 @ Oc # ls2 = [Bk] @ Oc # ls2 = (ls1 @ [Oc]) @ ls2 = ls1'@ls2' \<and> ls1' = Bk#[Oc] r' = Oc#[Bk] @ Oc # Bk \<up> Suc rex = rev ls1' @ Oc # Bk \<up> Suc rex \<exists>rex' ls1' ls2'. ls2 = ls2' \<and> Oc#[Bk] @ Oc # Bk \<up> Suc rex = rev ls1' @ Oc # Bk \<up> Suc rex' \<and> CL = ls1' @ ls2' \<and> ls1' = [Bk,Oc] YYYY4 (\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> [] \<and> last ls1 = Oc) *) with A_case have "step0 (11, Oc # ls2 , [Bk] @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (12, ls2, Oc#[Bk] @ Oc # Bk \<up> Suc rex )" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (12, ls2, Oc#[Bk] @ Oc # Bk \<up> Suc rex )" proof - from A_case and \<open>rev ls1 = [Bk]\<close> have "\<exists>rex' ls1' ls2'. ls2 = ls2' \<and> Oc#[Bk] @ Oc # Bk \<up> Suc rex = rev ls1' @ Oc # Bk \<up> Suc rex' \<and> CL = ls1' @ ls2' \<and> tl ls1' \<noteq> [] \<and> last ls1' = Oc" (* YYYY4 *) by simp with A_case \<open>rev ls1 = [Bk]\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (12, ls2, Oc#[Bk] @ Oc # Bk \<up> Suc rex )" by simp qed ultimately show ?thesis using assms and cf_cases and \<open>s = 11\<close> and A_case and \<open>rev ls1 = [Bk]\<close> by simp next assume "\<exists>rex. l = [] \<and> r = Bk # rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc)" (* YYYY1' *) then obtain rex where A_case: "l = [] \<and> r = Bk # rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc)" by blast then have "step0 (11, [] , Bk # rev CL @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (12, [], Bk#Bk # rev CL @ Oc # Bk \<up> Suc rex )" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (12, [], Bk#Bk # rev CL @ Oc # Bk \<up> Suc rex )" proof - from A_case have "\<exists>rex'. [] = [] \<and> Bk#Bk # rev CL @ Oc # Bk \<up> Suc rex = Bk# Bk # rev CL @ Oc # Bk \<up> Suc rex' \<and> (CL = [] \<or> last CL = Oc)" (* YYYY9 *) by simp with A_case show "inv_tm_erase_right_then_dblBk_left_erp CL CR (12, [], Bk#Bk # rev CL @ Oc # Bk \<up> Suc rex )" by force qed ultimately show ?thesis using assms and cf_cases and \<open>s = 11\<close> and A_case by simp next assume "\<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk" (* YYYY2' *) then obtain rex where A_case: "l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk" by blast then have "hd (rev CL) = Bk" by (simp add: hd_rev) with A_case have "step0 (11, [] , rev CL @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (12, [], Bk # rev CL @ Oc # Bk \<up> Suc rex )" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (12, [], Bk # rev CL @ Oc # Bk \<up> Suc rex )" proof - from A_case have "\<exists>rex'. [] = [] \<and> Bk # rev CL @ Oc # Bk \<up> Suc rex = Bk # rev CL @ Oc # Bk \<up> Suc rex' \<and> CL \<noteq> [] \<and> last CL = Bk" (* YYYY6''' *) by simp with A_case show "inv_tm_erase_right_then_dblBk_left_erp CL CR (12, [], Bk # rev CL @ Oc # Bk \<up> Suc rex )" by force qed ultimately show ?thesis using assms and cf_cases and \<open>s = 11\<close> and A_case by simp next assume "\<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Oc" (* YYYY2'' *) then obtain rex where A_case: "l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Oc" by blast then have "hd (rev CL) = Oc" by (simp add: hd_rev) with A_case have "step0 (11, [] , rev CL @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (11, [], Bk # rev CL @ Oc # Bk \<up> Suc rex )" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, [], Bk # rev CL @ Oc # Bk \<up> Suc rex )" proof - from A_case have "\<exists>rex'. [] = [] \<and> Bk # rev CL @ Oc # Bk \<up> Suc rex = Bk # rev CL @ Oc # Bk \<up> Suc rex' \<and> (CL = [] \<or> last CL = Oc)" (* YYYY1' *) by simp with A_case show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, [], Bk # rev CL @ Oc # Bk \<up> Suc rex )" by force qed ultimately show ?thesis using assms and cf_cases and \<open>s = 11\<close> and A_case by simp qed next assume "s = 12" with cf_cases and assms have " (\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> [] \<and> last ls1 = Oc) \<or> (\<exists>rex. l = [] \<and> r = Bk#rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk) \<or> (\<exists>rex. l = [] \<and> r = Bk#Bk#rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc))" by auto then have s12_cases: "\<And>P. \<lbrakk> \<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> [] \<and> last ls1 = Oc \<Longrightarrow> P; \<exists>rex. l = [] \<and> r = Bk#rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk \<Longrightarrow> P; \<exists>rex. l = [] \<and> r = Bk#Bk#rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc) \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" by blast show ?thesis proof (rule s12_cases) (* YYYY4 *) assume "\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> [] \<and> last ls1 = Oc" then obtain rex ls1 ls2 where A_case: "l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2\<and> tl ls1 \<noteq> [] \<and> last ls1 = Oc" by blast then have "ls1 \<noteq> []" by auto with A_case have major: "hd (rev ls1) = Oc" by (simp add: hd_rev) show ?thesis proof (rule noDblBk_cases) from \<open>noDblBk CL\<close> show "noDblBk CL" . next from A_case show "CL = ls1 @ ls2" by auto next assume "ls2 = []" (* A_case: "l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> hd ls1 = Oc \<and> tl ls1 \<noteq> [] \<and> last ls1 = Oc" major: "hd (rev ls1) = Oc ls1 \<noteq> [] ass: ls2 = [] l = [] r = rev ls1 @ Oc # Bk \<up> Suc rex where "hd (rev ls1) = Oc" \<longrightarrow> s11 l' = [] r' = Bk#rev ls1 @ Oc # Bk \<up> Suc rex *) from A_case have "step0 (12, [] , Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex)) tm_erase_right_then_dblBk_left = (11, [], Bk#Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex ))" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover from A_case and major have "r = Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex)" by (metis Nil_is_append_conv \<open>ls1 \<noteq> []\<close> hd_Cons_tl hd_append2 list.simps(3) rev_is_Nil_conv) ultimately have "step0 (12, [] , rev ls1 @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (11, [], Bk# rev ls1 @ Oc # Bk \<up> Suc rex )" by (simp add: A_case) (* CL = ls1 @ ls2 \<and> tl ls1 \<noteq> [] CL = ls1 l' = [] r' = Bk# (rev CL) @ Oc # Bk \<up> Suc rex *) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, [], Bk# rev ls1 @ Oc # Bk \<up> Suc rex )" proof - from A_case and \<open>ls2 = []\<close> have "rev ls1 = rev CL" by auto with A_case and \<open>ls2 = []\<close> have "\<exists>rex'. [] = [] \<and> Bk# rev ls1 @ Oc # Bk \<up> Suc rex = Bk# rev CL @ Oc # Bk \<up> Suc rex' \<and> (CL = [] \<or> last CL = Oc)" (* YYYY1' *) by simp with A_case \<open>r = Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex)\<close> and \<open>ls2 = []\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, [], Bk# rev ls1 @ Oc # Bk \<up> Suc rex )" by force qed ultimately show ?thesis using assms and cf_cases and \<open>s = 12\<close> and A_case and \<open>ls2 = []\<close> by simp next assume "ls2 = [Bk]" from A_case have "step0 (12, [Bk] , Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex)) tm_erase_right_then_dblBk_left = (11, [], Bk#Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex ))" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover from A_case and major have "r = Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex)" by (metis Nil_is_append_conv \<open>ls1 \<noteq> []\<close> hd_Cons_tl hd_append2 list.simps(3) rev_is_Nil_conv) ultimately have "step0 (12, [Bk] , rev ls1 @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (11, [], Bk# rev ls1 @ Oc # Bk \<up> Suc rex )" by (simp add: A_case) (* CL = ls1 @ ls2 \<and> tl ls1 \<noteq> [] CL = ls1 @ [Bk] = (ls1 @ [Bk]) = ls1' l' = [] r' = rev ls1' = rev CL l' = [] r' = rev CL @ Oc # Bk \<up> Suc rex *) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, [], Bk# rev ls1 @ Oc # Bk \<up> Suc rex )" proof - from A_case and \<open>ls2 = [Bk]\<close> have "CL = ls1 @ [Bk]" by auto then have "\<exists>rex'. [] = [] \<and> Bk#rev ls1 @ Oc # Bk \<up> Suc rex = rev CL @ Oc # Bk \<up> Suc rex' \<and> CL \<noteq> [] \<and> last CL = Bk" (* YYYY2' *) by simp with A_case \<open>r = Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex)\<close> and \<open>ls2 = [Bk]\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, [], Bk# rev ls1 @ Oc # Bk \<up> Suc rex )" by force qed ultimately show ?thesis using assms and cf_cases and \<open>s = 12\<close> and A_case and \<open>ls2 = [Bk]\<close> by simp next fix C3 assume minor: "ls2 = Bk # Oc # C3" (* A_case: "l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> hd ls1 = Oc \<and> tl ls1 \<noteq> [] \<and> last ls1 = Oc" major: "hd (rev ls1) = Oc ls1 \<noteq> [] ass: ls2 = Bk # Oc # C3 l = Bk # Oc # C3 r = rev ls1 @ Oc # Bk \<up> Suc rex where "hd (rev ls1) = Oc" \<longrightarrow> s11 l' = Oc # C3 r' = Bk#rev ls1 @ Oc # Bk \<up> Suc rex *) from A_case have "step0 (12, Bk # Oc # C3 , Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex)) tm_erase_right_then_dblBk_left = (11, Oc # C3, Bk#Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex ))" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover from A_case and major have "r = Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex)" by (metis Nil_is_append_conv \<open>ls1 \<noteq> []\<close> hd_Cons_tl hd_append2 list.simps(3) rev_is_Nil_conv) ultimately have "step0 (12, Bk # Oc # C3 , rev ls1 @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (11, Oc # C3, Bk# rev ls1 @ Oc # Bk \<up> Suc rex )" by (simp add: A_case) (* CL = ls1 @ ls2 \<and> tl ls1 \<noteq> [] CL = ls1 @ (Bk # Oc # C3) = ls1 @ [Bk] @ (Oc # C3) ls1' = ls1 @ [Bk] ls2' = Oc # C3 rev ls1' = Bk# (rev ls1) l' = Oc # C3 r' = rev ls1' @ Oc # Bk \<up> Suc rex \<and> CL = ls1' @ ls2' \<and> hd ls1' = Oc \<and> tl ls1' \<noteq> [] YYYY8 (\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> hd ls1 = Oc \<and> tl ls1 \<noteq> []) *) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, Oc # C3, Bk# rev ls1 @ Oc # Bk \<up> Suc rex )" proof - from A_case and \<open>ls2 = Bk # Oc # C3\<close> have "CL = ls1 @ [Bk] @ (Oc # C3)" and "rev (ls1 @ [Bk]) = Bk # rev ls1" by auto with \<open>ls1 \<noteq> []\<close> have "\<exists>rex' ls1' ls2'. Oc # C3 = ls2' \<and> Bk# rev ls1 @ Oc # Bk \<up> Suc rex = rev ls1' @ Oc # Bk \<up> Suc rex' \<and> CL = ls1' @ ls2' \<and> tl ls1' \<noteq> []" (* YYYY8 *) by (simp add: A_case ) with A_case \<open>r = Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex)\<close> and \<open>ls2 = Bk # Oc # C3\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, Oc # C3, Bk# rev ls1 @ Oc # Bk \<up> Suc rex )" by force qed ultimately show ?thesis using assms and cf_cases and \<open>s = 12\<close> and A_case and \<open>ls2 = Bk # Oc # C3\<close> by simp next fix C3 assume minor: "ls2 = Oc # C3" (* A_case: "l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> hd ls1 = Oc \<and> tl ls1 \<noteq> [] \<and> last ls1 = Oc" major: "hd (rev ls1) = Oc ls1 \<noteq> [] ass: ls2 = Bk # Oc # C3 l = ls2 = Oc # C3 r = rev ls1 @ Oc # Bk \<up> Suc rex where "hd (rev ls1) = Oc" \<longrightarrow> s11 l' = C3 r' = Oc#rev ls1 @ Oc # Bk \<up> Suc rex *) from A_case have "step0 (12, Oc # C3 , Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex)) tm_erase_right_then_dblBk_left = (11, C3, Oc#Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex ))" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover from A_case and major have "r = Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex)" by (metis Nil_is_append_conv \<open>ls1 \<noteq> []\<close> hd_Cons_tl hd_append2 list.simps(3) rev_is_Nil_conv) ultimately have "step0 (12, Oc # C3 , rev ls1 @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (11, C3, Oc# rev ls1 @ Oc # Bk \<up> Suc rex )" by (simp add: A_case) (* CL = ls1 @ ls2 \<and> tl ls1 \<noteq> [] CL = ls1 @ (Oc # C3) = ls1 @ [Oc] @ (C3) ls1' = ls1 @ [Oc] ls2' = C3 rev ls1' = Oc# (rev ls1) l' = C3 r' = rev ls1' @ Oc # Bk \<up> Suc rex \<and> CL = ls1' @ ls2' \<and> hd ls1' = Oc \<and> tl ls1' \<noteq> [] YYYY8 (\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> hd ls1 = Oc \<and> tl ls1 \<noteq> []) *) moreover have "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, C3, Oc# rev ls1 @ Oc # Bk \<up> Suc rex )" proof - from A_case and \<open>ls2 = Oc # C3\<close> have "CL = ls1 @ [Oc] @ (C3)" and "rev (ls1 @ [Oc]) = Oc # rev ls1" by auto with \<open>ls1 \<noteq> []\<close> have "\<exists>rex' ls1' ls2'. C3 = ls2' \<and> Oc# rev ls1 @ Oc # Bk \<up> Suc rex = rev ls1' @ Oc # Bk \<up> Suc rex' \<and> CL = ls1' @ ls2' \<and> tl ls1' \<noteq> []" (* YYYY8 *) by (simp add: A_case ) with A_case \<open>r = Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex)\<close> and \<open>ls2 = Oc # C3\<close> show "inv_tm_erase_right_then_dblBk_left_erp CL CR (11, C3, Oc# rev ls1 @ Oc # Bk \<up> Suc rex )" by force qed ultimately show ?thesis using assms and cf_cases and \<open>s = 12\<close> and A_case and \<open>ls2 = Oc # C3\<close> by simp qed next (* YYYY6''' *) assume "\<exists>rex. l = [] \<and> r = Bk # rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk" then obtain rex where A_case: "l = [] \<and> r = Bk # rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk" by blast then have "step0 (12, [] , Bk # rev CL @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (0, [], Bk # rev CL @ Oc # Bk \<up> Suc rex)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover with A_case have "inv_tm_erase_right_then_dblBk_left_erp CL CR (0, [], Bk # rev CL @ Oc # Bk \<up> Suc rex)" by auto ultimately show ?thesis using assms and cf_cases and \<open>s = 12\<close> and A_case by simp next (* YYYY9 *) assume "\<exists>rex. l = [] \<and> r = Bk # Bk # rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc)" then obtain rex where A_case: "l = [] \<and> r = Bk # Bk # rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc)" by blast then have "step0 (12, [] , Bk # Bk # rev CL @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (0, [], Bk# Bk # rev CL @ Oc # Bk \<up> Suc rex)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover with A_case have "inv_tm_erase_right_then_dblBk_left_erp CL CR (0, [], Bk# Bk # rev CL @ Oc # Bk \<up> Suc rex)" by auto ultimately show ?thesis using assms and cf_cases and \<open>s = 12\<close> and A_case by simp qed next assume "s = 0" with cf_cases and assms have "(\<exists>rex. l = [] \<and> r = [Bk, Bk] @ (rev CL) @ [Oc, Bk] @ Bk \<up> rex \<and> (CL = [] \<or> last CL = Oc) ) \<or> (\<exists>rex. l = [] \<and> r = [Bk] @ (rev CL) @ [Oc, Bk] @ Bk \<up> rex \<and> CL \<noteq> [] \<and> last CL = Bk)" by auto then have s0_cases: "\<And>P. \<lbrakk> \<exists>rex. l = [] \<and> r = [Bk, Bk] @ (rev CL) @ [Oc, Bk] @ Bk \<up> rex \<and> (CL = [] \<or> last CL = Oc) \<Longrightarrow> P; \<exists>rex. l = [] \<and> r = [Bk] @ (rev CL) @ [Oc, Bk] @ Bk \<up> rex \<and> CL \<noteq> [] \<and> last CL = Bk \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" by blast show ?thesis proof (rule s0_cases) assume "\<exists>rex. l = [] \<and> r = [Bk, Bk] @ rev CL @ [Oc, Bk] @ Bk \<up> rex \<and> (CL = [] \<or> last CL = Oc)" then obtain rex where A_case: "l = [] \<and> r = [Bk, Bk] @ rev CL @ [Oc, Bk] @ Bk \<up> rex \<and> (CL = [] \<or> last CL = Oc)" by blast then have "step0 (0, [] , [Bk, Bk] @ rev CL @ [Oc, Bk] @ Bk \<up> rex) tm_erase_right_then_dblBk_left = (0, [], Bk# Bk # rev CL @ Oc # Bk \<up> Suc rex)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover with A_case have "inv_tm_erase_right_then_dblBk_left_erp CL CR (0, [], Bk# Bk # rev CL @ Oc # Bk \<up> Suc rex)" by auto ultimately show ?thesis using assms and cf_cases and \<open>s = 0\<close> and A_case by simp next assume "\<exists>rex. l = [] \<and> r = [Bk] @ rev CL @ [Oc, Bk] @ Bk \<up> rex \<and> CL \<noteq> [] \<and> last CL = Bk" then obtain rex where A_case: "l = [] \<and> r = [Bk] @ rev CL @ [Oc, Bk] @ Bk \<up> rex \<and> CL \<noteq> [] \<and> last CL = Bk" by blast then have "step0 (0, [] , [Bk] @ rev CL @ [Oc, Bk] @ Bk \<up> rex) tm_erase_right_then_dblBk_left = (0, [], Bk # rev CL @ Oc # Bk \<up> Suc rex)" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) moreover with A_case have "inv_tm_erase_right_then_dblBk_left_erp CL CR (0, [], Bk # rev CL @ Oc # Bk \<up> Suc rex)" by auto ultimately show ?thesis using assms and cf_cases and \<open>s = 0\<close> and A_case by simp qed qed qed (* -------------- steps - lemma for the invariants of the ERASE path of tm_erase_right_then_dblBk_left ------------------ *) lemma inv_tm_erase_right_then_dblBk_left_erp_steps: assumes "inv_tm_erase_right_then_dblBk_left_erp CL CR cf" and "noDblBk CL" and "noDblBk CR" shows "inv_tm_erase_right_then_dblBk_left_erp CL CR (steps0 cf tm_erase_right_then_dblBk_left stp)" proof (induct stp) case 0 with assms show ?case by (auto simp add: inv_tm_erase_right_then_dblBk_left_erp_step step.simps steps.simps) next case (Suc stp) with assms show ?case using inv_tm_erase_right_then_dblBk_left_erp_step step_red by auto qed (* -------------- Partial correctness for the ERASE path of tm_erase_right_then_dblBk_left ------------------ *) lemma tm_erase_right_then_dblBk_left_erp_partial_correctness_CL_is_Nil: assumes "\<exists>stp. is_final (steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp)" and "noDblBk CL" and "noDblBk CR" and "CL = []" shows "\<lbrace> \<lambda>tap. tap = ([Bk,Oc] @ CL, CR) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. \<exists>rex. tap = ([], [Bk,Bk] @ (rev CL) @ [Oc, Bk] @ Bk \<up> rex ) \<rbrace>" proof (rule Hoare_consequence) show "( \<lambda>tap. tap = ([Bk,Oc] @ CL, CR) ) \<mapsto> ( \<lambda>tap. tap = ([Bk,Oc] @ CL, CR) )" by auto next from assms show "inv_tm_erase_right_then_dblBk_left_erp_s0 CL CR \<mapsto> ( \<lambda>tap. \<exists>rex. tap = ([], [Bk,Bk] @ rev CL @ [Oc, Bk] @ Bk \<up> rex) )" by (simp add: assert_imp_def tape_of_list_def tape_of_nat_def) next show " \<lbrace>\<lambda>tap. tap = ([Bk, Oc] @ CL, CR)\<rbrace> tm_erase_right_then_dblBk_left \<lbrace>inv_tm_erase_right_then_dblBk_left_erp_s0 CL CR\<rbrace>" proof (rule Hoare_haltI) fix l::"cell list" fix r:: "cell list" assume major: "(l, r) = ([Bk, Oc] @ CL, CR)" show "\<exists>n. is_final (steps0 (1, l, r) tm_erase_right_then_dblBk_left n) \<and> inv_tm_erase_right_then_dblBk_left_erp_s0 CL CR holds_for steps0 (1, l, r) tm_erase_right_then_dblBk_left n" proof - from major and assms have "\<exists>stp. is_final (steps0 (1, l, r) tm_erase_right_then_dblBk_left stp)" by blast then obtain stp where w_stp: "is_final (steps0 (1, l, r) tm_erase_right_then_dblBk_left stp)" by blast moreover have "inv_tm_erase_right_then_dblBk_left_erp_s0 CL CR holds_for steps0 (1, l, r) tm_erase_right_then_dblBk_left stp" proof - have "inv_tm_erase_right_then_dblBk_left_erp CL CR (1, l, r)" by (simp add: major tape_of_list_def tape_of_nat_def) with assms have "inv_tm_erase_right_then_dblBk_left_erp CL CR (steps0 (1, l, r) tm_erase_right_then_dblBk_left stp)" using inv_tm_erase_right_then_dblBk_left_erp_steps by auto then show ?thesis by (smt holds_for.elims(3) inv_tm_erase_right_then_dblBk_left_erp.simps is_final_eq w_stp) qed ultimately show ?thesis by auto qed qed qed lemma tm_erase_right_then_dblBk_left_erp_partial_correctness_CL_ew_Bk: assumes "\<exists>stp. is_final (steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp)" and "noDblBk CL" and "noDblBk CR" and "CL \<noteq> []" and "last CL = Bk" shows "\<lbrace> \<lambda>tap. tap = ([Bk,Oc] @ CL, CR) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. \<exists>rex. tap = ([], [Bk] @ (rev CL) @ [Oc, Bk] @ Bk \<up> rex ) \<rbrace>" proof (rule Hoare_consequence) show "( \<lambda>tap. tap = ([Bk,Oc] @ CL, CR) ) \<mapsto> ( \<lambda>tap. tap = ([Bk,Oc] @ CL, CR) )" by auto next from assms show "inv_tm_erase_right_then_dblBk_left_erp_s0 CL CR \<mapsto> ( \<lambda>tap. \<exists>rex. tap = ([], [Bk] @ rev CL @ [Oc, Bk] @ Bk \<up> rex) )" by (simp add: assert_imp_def tape_of_list_def tape_of_nat_def) next show " \<lbrace>\<lambda>tap. tap = ([Bk, Oc] @ CL, CR)\<rbrace> tm_erase_right_then_dblBk_left \<lbrace>inv_tm_erase_right_then_dblBk_left_erp_s0 CL CR\<rbrace>" proof (rule Hoare_haltI) fix l::"cell list" fix r:: "cell list" assume major: "(l, r) = ([Bk, Oc] @ CL, CR)" show "\<exists>n. is_final (steps0 (1, l, r) tm_erase_right_then_dblBk_left n) \<and> inv_tm_erase_right_then_dblBk_left_erp_s0 CL CR holds_for steps0 (1, l, r) tm_erase_right_then_dblBk_left n" proof - from major and assms have "\<exists>stp. is_final (steps0 (1, l, r) tm_erase_right_then_dblBk_left stp)" by blast then obtain stp where w_stp: "is_final (steps0 (1, l, r) tm_erase_right_then_dblBk_left stp)" by blast moreover have "inv_tm_erase_right_then_dblBk_left_erp_s0 CL CR holds_for steps0 (1, l, r) tm_erase_right_then_dblBk_left stp" proof - have "inv_tm_erase_right_then_dblBk_left_erp CL CR (1, l, r)" by (simp add: major tape_of_list_def tape_of_nat_def) with assms have "inv_tm_erase_right_then_dblBk_left_erp CL CR (steps0 (1, l, r) tm_erase_right_then_dblBk_left stp)" using inv_tm_erase_right_then_dblBk_left_erp_steps by auto then show ?thesis by (smt holds_for.elims(3) inv_tm_erase_right_then_dblBk_left_erp.simps is_final_eq w_stp) qed ultimately show ?thesis by auto qed qed qed lemma tm_erase_right_then_dblBk_left_erp_partial_correctness_CL_ew_Oc: assumes "\<exists>stp. is_final (steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp)" and "noDblBk CL" and "noDblBk CR" and "CL \<noteq> []" and "last CL = Oc" shows "\<lbrace> \<lambda>tap. tap = ([Bk,Oc] @ CL, CR) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. \<exists>rex. tap = ([], [Bk, Bk] @ (rev CL) @ [Oc, Bk] @ Bk \<up> rex ) \<rbrace>" proof (rule Hoare_consequence) show "( \<lambda>tap. tap = ([Bk,Oc] @ CL, CR) ) \<mapsto> ( \<lambda>tap. tap = ([Bk,Oc] @ CL, CR) )" by auto next from assms show "inv_tm_erase_right_then_dblBk_left_erp_s0 CL CR \<mapsto> ( \<lambda>tap. \<exists>rex. tap = ([], [Bk, Bk] @ rev CL @ [Oc, Bk] @ Bk \<up> rex) )" by (simp add: assert_imp_def tape_of_list_def tape_of_nat_def) next show " \<lbrace>\<lambda>tap. tap = ([Bk, Oc] @ CL, CR)\<rbrace> tm_erase_right_then_dblBk_left \<lbrace>inv_tm_erase_right_then_dblBk_left_erp_s0 CL CR\<rbrace>" proof (rule Hoare_haltI) fix l::"cell list" fix r:: "cell list" assume major: "(l, r) = ([Bk, Oc] @ CL, CR)" show "\<exists>n. is_final (steps0 (1, l, r) tm_erase_right_then_dblBk_left n) \<and> inv_tm_erase_right_then_dblBk_left_erp_s0 CL CR holds_for steps0 (1, l, r) tm_erase_right_then_dblBk_left n" proof - from major and assms have "\<exists>stp. is_final (steps0 (1, l, r) tm_erase_right_then_dblBk_left stp)" by blast then obtain stp where w_stp: "is_final (steps0 (1, l, r) tm_erase_right_then_dblBk_left stp)" by blast moreover have "inv_tm_erase_right_then_dblBk_left_erp_s0 CL CR holds_for steps0 (1, l, r) tm_erase_right_then_dblBk_left stp" proof - have "inv_tm_erase_right_then_dblBk_left_erp CL CR (1, l, r)" by (simp add: major tape_of_list_def tape_of_nat_def) with assms have "inv_tm_erase_right_then_dblBk_left_erp CL CR (steps0 (1, l, r) tm_erase_right_then_dblBk_left stp)" using inv_tm_erase_right_then_dblBk_left_erp_steps by auto then show ?thesis by (smt holds_for.elims(3) inv_tm_erase_right_then_dblBk_left_erp.simps is_final_eq w_stp) qed ultimately show ?thesis by auto qed qed qed (* -------------- Termination for the ERASE path of tm_erase_right_then_dblBk_left ------------------ *) (* Lexicographic orders (See List.measures) quote: "These are useful for termination proofs" lemma in_measures[simp]: "(x, y) \<in> measures [] = False" "(x, y) \<in> measures (f # fs) = (f x < f y \<or> (f x = f y \<and> (x, y) \<in> measures fs))" *) (* Assemble a lexicographic measure function for the ERASE path *) definition measure_tm_erase_right_then_dblBk_left_erp :: "(config \<times> config) set" where "measure_tm_erase_right_then_dblBk_left_erp = measures [ \<lambda>(s, l, r). ( if s = 0 then 0 else if s < 6 then 13 - s else 1), \<lambda>(s, l, r). ( if s = 6 then if r = [] \<or> (hd r) = Bk then 1 else 2 else 0 ), \<lambda>(s, l, r). ( if 7 \<le> s \<and> s \<le> 9 then 2+ length r else 1), \<lambda>(s, l, r). ( if 7 \<le> s \<and> s \<le> 9 then if r = [] \<or> hd r = Bk then 2 else 3 else 1), \<lambda>(s, l, r).( if 7 \<le> s \<and> s \<le> 10 then 13 - s else 1), \<lambda>(s, l, r). ( if 10 \<le> s then 2+ length l else 1), \<lambda>(s, l, r). ( if 11 \<le> s then if hd r = Oc then 3 else 2 else 1), \<lambda>(s, l, r).( if 11 \<le> s then 13 - s else 1) ]" lemma wf_measure_tm_erase_right_then_dblBk_left_erp: "wf measure_tm_erase_right_then_dblBk_left_erp" unfolding measure_tm_erase_right_then_dblBk_left_erp_def by (auto) lemma measure_tm_erase_right_then_dblBk_left_erp_induct [case_names Step]: "\<lbrakk>\<And>n. \<not> P (f n) \<Longrightarrow> (f (Suc n), (f n)) \<in> measure_tm_erase_right_then_dblBk_left_erp\<rbrakk> \<Longrightarrow> \<exists>n. P (f n)" using wf_measure_tm_erase_right_then_dblBk_left_erp by (metis wf_iff_no_infinite_down_chain) lemma spike_erp_cases: "CL \<noteq> [] \<and> last CL = Bk \<or> CL \<noteq> [] \<and> last CL = Oc \<or> CL = []" using cell.exhaust by blast lemma tm_erase_right_then_dblBk_left_erp_halts: assumes "noDblBk CL" and "noDblBk CR" shows "\<exists>stp. is_final (steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp)" proof (induct rule: measure_tm_erase_right_then_dblBk_left_erp_induct) case (Step stp) then have not_final: "\<not> is_final (steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp)" . have INV: "inv_tm_erase_right_then_dblBk_left_erp CL CR (steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp)" proof (rule_tac inv_tm_erase_right_then_dblBk_left_erp_steps) show "inv_tm_erase_right_then_dblBk_left_erp CL CR (1, [Bk,Oc] @ CL, CR)" by (simp add: tape_of_list_def tape_of_nat_def ) next from assms show "noDblBk CL" by auto next from assms show "noDblBk CR" by auto qed have SUC_STEP_RED: "steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp) tm_erase_right_then_dblBk_left" by (rule step_red) show "( steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp), steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp ) \<in> measure_tm_erase_right_then_dblBk_left_erp" proof (cases "steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp") case (fields s l r) then have cf_at_stp: "steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp = (s, l, r)" . show ?thesis proof (rule tm_erase_right_then_dblBk_left_erp_cases) from INV and cf_at_stp show "inv_tm_erase_right_then_dblBk_left_erp CL CR (s, l, r)" by auto next assume "s=0" (* not possible *) with cf_at_stp not_final show ?thesis by auto next assume "s=1" (* get the invariant of the state *) with cf_at_stp have cf_at_current: "steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp = (1, l, r)" by auto with cf_at_stp and \<open>s=1\<close> and INV have unpacked_INV: "(l = [Bk,Oc] @ CL \<and> r = CR)" by auto (* compute the next state *) show ?thesis proof (cases CR) case Nil then have minor: "CR = []" . with unpacked_INV cf_at_stp and \<open>s=1\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left" by auto also with minor and unpacked_INV have "... = (2,Oc#CL, Bk#CR)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (2,Oc#CL, Bk#CR)" by auto (* establish measure *) with cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next case (Cons a rs) then have major: "CR = a # rs" . then show ?thesis proof (cases a) case Bk with major have minor: "CR = Bk#rs" by auto with unpacked_INV cf_at_stp and \<open>s=1\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left" by auto also with minor and unpacked_INV have "... = (2,Oc#CL, Bk#CR)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (2,Oc#CL, Bk#CR)" by auto (* establish measure *) with cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next case Oc with major have minor: "CR = Oc#rs" by auto with unpacked_INV cf_at_stp and \<open>s=1\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left" by auto also with minor and unpacked_INV have "... = (2,Oc#CL, Bk#CR)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (2,Oc#CL, Bk#CR)" by auto (* establish measure *) with cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) qed qed next assume "s=2" (* get the invariant of the state *) with cf_at_stp have cf_at_current: "steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp = (2, l, r)" by auto with cf_at_stp and \<open>s=2\<close> and INV have unpacked_INV: "(l = [Oc] @ CL \<and> r = Bk#CR)" by auto (* compute the next state *) then have minor: "r = Bk#CR" by auto with unpacked_INV cf_at_stp and \<open>s=2\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (2, [Oc] @ CL, Bk#CR) tm_erase_right_then_dblBk_left" by auto also with minor and unpacked_INV have "... = (3,CL, Oc#Bk#CR)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (3,CL, Oc#Bk#CR)" by auto (* establish measure *) with cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next assume "s=3" (* get the invariant of the state *) with cf_at_stp have cf_at_current: "steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp = (3, l, r)" by auto with cf_at_stp and \<open>s=3\<close> and INV have unpacked_INV: "(l = CL \<and> r = Oc#Bk#CR)" by auto (* compute the next state *) then have minor: "r = Oc#Bk#CR" by auto with unpacked_INV cf_at_stp and \<open>s=3\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (3, CL, Oc#Bk#CR) tm_erase_right_then_dblBk_left" by auto also with minor and unpacked_INV have "... = (5,[Oc] @ CL, Bk#CR)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (5,[Oc] @ CL, Bk#CR)" by auto (* establish measure *) with cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next assume "s=5" (* get the invariant of the state *) with cf_at_stp have cf_at_current: "steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp = (5, l, r)" by auto with cf_at_stp and \<open>s=5\<close> and INV have unpacked_INV: "(l = [Oc] @ CL \<and> r = Bk#CR)" by auto (* compute the next state *) then have minor: "r = Bk#CR" by auto with unpacked_INV cf_at_stp and \<open>s=5\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (5, [Oc] @ CL, Bk#CR) tm_erase_right_then_dblBk_left" by auto also with minor and unpacked_INV have "... = (6, [Bk,Oc] @ CL, CR)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (6, [Bk,Oc] @ CL, CR)" by auto (* establish measure *) with cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next assume "s=6" (* get the invariant of the state *) with cf_at_stp have cf_at_current: "steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp = (6, l, r)" by auto with cf_at_stp and \<open>s=6\<close> and INV have unpacked_INV: "(l = [Bk,Oc] @ CL \<and> ( (CR = [] \<and> r = CR) \<or> (CR \<noteq> [] \<and> (r = CR \<or> r = Bk # tl CR)) ))" by auto then have unpacked_INV': "l = [Bk,Oc] @ CL \<and> CR = [] \<and> r = CR \<or> l = [Bk,Oc] @ CL \<and> CR \<noteq> [] \<and> r = Oc # tl CR \<or> l = [Bk,Oc] @ CL \<and> CR \<noteq> [] \<and> r = Bk # tl CR" by (metis (full_types) cell.exhaust list.sel(3) neq_Nil_conv) then show ?thesis proof assume minor: "l = [Bk, Oc] @ CL \<and> CR = [] \<and> r = CR" with unpacked_INV cf_at_stp and \<open>s=6\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (6, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left" by auto also with minor and unpacked_INV have "... = (7,Bk#[Bk, Oc] @ CL, CR)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (7,Bk#[Bk, Oc] @ CL, CR)" by auto (* establish measure *) with cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next assume "l = [Bk, Oc] @ CL \<and> CR \<noteq> [] \<and> r = Oc # tl CR \<or> l = [Bk, Oc] @ CL \<and> CR \<noteq> [] \<and> r = Bk # tl CR" then show ?thesis proof assume minor: "l = [Bk, Oc] @ CL \<and> CR \<noteq> [] \<and> r = Bk # tl CR" with unpacked_INV cf_at_stp and \<open>s=6\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (6, [Bk, Oc] @ CL, Bk # tl CR) tm_erase_right_then_dblBk_left" by auto also with minor have "... = (7,Bk#[Bk, Oc] @ CL, tl CR)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (7,Bk#[Bk, Oc] @ CL, tl CR)" by auto (* establish measure *) with cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next assume minor: "l = [Bk, Oc] @ CL \<and> CR \<noteq> [] \<and> r = Oc # tl CR" with unpacked_INV cf_at_stp and \<open>s=6\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (6, [Bk, Oc] @ CL, Oc # tl CR) tm_erase_right_then_dblBk_left" by auto also with minor have "... = (6, [Bk, Oc] @ CL, Bk # tl CR)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (6, [Bk, Oc] @ CL, Bk # tl CR)" by auto (* establish measure *) with cf_at_current and minor show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) qed qed next assume "s=7" (* get the invariant of the state *) with cf_at_stp have cf_at_current: "steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp = (7, l, r)" by auto with cf_at_stp and \<open>s=7\<close> and INV have "(\<exists>lex. l = Bk \<up> Suc lex @ [Bk,Oc] @ CL) \<and> (\<exists>rs. CR = rs @ r)" by auto then obtain lex rs where unpacked_INV: "l = Bk \<up> Suc lex @ [Bk,Oc] @ CL \<and> CR = rs @ r" by blast (* compute the next state *) show ?thesis proof (cases r) case Nil then have minor: "r = []" . with unpacked_INV cf_at_stp and \<open>s=7\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (7, Bk \<up> Suc lex @ [Bk,Oc] @ CL, r) tm_erase_right_then_dblBk_left" by auto also with minor and unpacked_INV have "... = (9, Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL, r)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (9, Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL, r)" by auto (* establish measure *) with cf_at_current and minor show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next case (Cons a rs') then have major: "r = a # rs'" . then show ?thesis proof (cases a) case Bk with major have minor: "r = Bk#rs'" by auto with unpacked_INV cf_at_stp and \<open>s=7\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (7, Bk \<up> Suc lex @ [Bk,Oc] @ CL, r) tm_erase_right_then_dblBk_left" by auto also with minor and unpacked_INV have "... = (9, Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL, rs')" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (9, Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL, rs')" by auto (* establish measure *) with cf_at_current and minor show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next case Oc with major have minor: "r = Oc#rs'" by auto with unpacked_INV cf_at_stp and \<open>s=7\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (7, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Oc#rs') tm_erase_right_then_dblBk_left" by auto also with minor and unpacked_INV have "... = (8, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Bk#rs')" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (8, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Bk#rs')" by auto (* establish measure *) with cf_at_current and minor show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) qed qed next assume "s=8" (* get the invariant of the state *) with cf_at_stp have cf_at_current: "steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp = (8, l, r)" by auto with cf_at_stp and \<open>s=8\<close> and INV have "(\<exists>lex. l = Bk \<up> Suc lex @ [Bk,Oc] @ CL) \<and> (\<exists>rs1 rs2. CR = rs1 @ [Oc] @ rs2 \<and> r = Bk#rs2)" by auto then obtain lex rs1 rs2 where unpacked_INV: "l = Bk \<up> Suc lex @ [Bk,Oc] @ CL \<and> CR = rs1 @ [Oc] @ rs2 \<and> r = Bk#rs2 " by blast (* compute the next state *) with cf_at_stp and \<open>s=8\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (8, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Bk#rs2) tm_erase_right_then_dblBk_left" by auto also with unpacked_INV have "... = (7, Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL, rs2)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (7, Bk \<up> Suc (Suc lex) @ [Bk,Oc] @ CL, rs2)" by auto (* establish measure *) with cf_at_current and unpacked_INV show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next assume "s=9" (* get the invariant of the state *) with cf_at_stp have cf_at_current: "steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp = (9, l, r)" by auto with cf_at_stp and \<open>s=9\<close> and INV have "(\<exists>lex. l = Bk \<up> Suc lex @ [Bk,Oc] @ CL) \<and> (\<exists>rs. CR = rs @ [Bk] @ r \<or> CR = rs \<and> r = [])" by auto then obtain lex rs where "l = Bk \<up> Suc lex @ [Bk,Oc] @ CL \<and> (CR = rs @ [Bk] @ r \<or> CR = rs \<and> r = [])" by blast then have unpacked_INV: "l = Bk \<up> Suc lex @ [Bk,Oc] @ CL \<and> CR = rs @ [Bk] @ r \<or> l = Bk \<up> Suc lex @ [Bk,Oc] @ CL \<and> CR = rs \<and> r = []" by auto then show ?thesis proof (* compute the next state *) assume major: "l = Bk \<up> Suc lex @ [Bk, Oc] @ CL \<and> CR = rs @ [Bk] @ r" show ?thesis proof (cases r) case Nil then have minor: "r = []" . with unpacked_INV cf_at_stp and \<open>s=9\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (9, Bk \<up> Suc lex @ [Bk,Oc] @ CL, r) tm_erase_right_then_dblBk_left" by auto also with minor and unpacked_INV have "... = (10, Bk \<up> lex @ [Bk,Oc] @ CL, Bk#r)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (10, Bk \<up> lex @ [Bk,Oc] @ CL, Bk#r)" by auto (* establish measure *) with cf_at_current and minor show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next case (Cons a rs') then have major2: "r = a # rs'" . then show ?thesis proof (cases a) case Bk with major2 have minor: "r = Bk#rs'" by auto with unpacked_INV cf_at_stp and \<open>s=9\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (9, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Bk#rs') tm_erase_right_then_dblBk_left" by auto also with minor and unpacked_INV have "... = (10, Bk \<up> lex @ [Bk,Oc] @ CL, Bk#Bk#rs')" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (10, Bk \<up> lex @ [Bk,Oc] @ CL, Bk#Bk#rs')" by auto (* establish measure *) with cf_at_current and minor show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next case Oc with major2 have minor: "r = Oc#rs'" by auto with unpacked_INV cf_at_stp and \<open>s=9\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (9, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Oc#rs') tm_erase_right_then_dblBk_left" by auto also with minor and unpacked_INV have "... = (8, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Bk#rs')" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (8, Bk \<up> Suc lex @ [Bk,Oc] @ CL, Bk#rs')" by auto (* establish measure *) with cf_at_current and minor show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) qed qed next (* compute the next state *) assume major: "l = Bk \<up> Suc lex @ [Bk, Oc] @ CL \<and> CR = rs \<and> r = []" with unpacked_INV cf_at_stp and \<open>s=9\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (9, Bk \<up> Suc lex @ [Bk,Oc] @ CL, []) tm_erase_right_then_dblBk_left" by auto also with unpacked_INV have "... = (10, Bk \<up> lex @ [Bk,Oc] @ CL, [Bk])" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (10, Bk \<up> lex @ [Bk,Oc] @ CL, [Bk])" by auto (* establish measure *) with cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) qed next assume "s=10" (* get the invariant of the state *) with cf_at_stp have cf_at_current: "steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp = (10, l, r)" by auto with cf_at_stp and \<open>s=10\<close> and INV have "(\<exists>lex rex. l = Bk \<up> lex @ [Bk,Oc] @ CL \<and> r = Bk \<up> Suc rex) \<or> (\<exists>rex. l = [Oc] @ CL \<and> r = Bk \<up> Suc rex) \<or> (\<exists>rex. l = CL \<and> r = Oc # Bk \<up> Suc rex)" by auto then have s10_cases: "\<And>P. \<lbrakk> \<exists>lex rex. l = Bk \<up> lex @ [Bk,Oc] @ CL \<and> r = Bk \<up> Suc rex \<Longrightarrow> P; \<exists>rex. l = [Oc] @ CL \<and> r = Bk \<up> Suc rex \<Longrightarrow> P; \<exists>rex. l = CL \<and> r = Oc # Bk \<up> Suc rex \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" by blast show ?thesis proof (rule s10_cases) assume "\<exists>lex rex. l = Bk \<up> lex @ [Bk, Oc] @ CL \<and> r = Bk \<up> Suc rex" then obtain lex rex where unpacked_INV: "l = Bk \<up> lex @ [Bk, Oc] @ CL \<and> r = Bk \<up> Suc rex" by blast with unpacked_INV cf_at_stp and \<open>s=10\<close> and SUC_STEP_RED have todo_step: "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (10, Bk \<up> lex @ [Bk, Oc] @ CL, Bk \<up> Suc rex) tm_erase_right_then_dblBk_left" by auto show ?thesis proof (cases lex) case 0 then have "lex = 0" . (* compute the next state *) then have "step0 (10, Bk \<up> lex @ [Bk, Oc] @ CL, Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (10, [Oc] @ CL, Bk \<up> Suc (Suc rex))" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) with todo_step have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (10, [Oc] @ CL, Bk \<up> Suc (Suc rex))" by auto (* establish measure *) with \<open>lex = 0\<close> and cf_at_current and unpacked_INV show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next case (Suc nat) then have "lex = Suc nat" . (* compute the next state *) then have "step0 (10, Bk \<up> lex @ [Bk, Oc] @ CL, Bk \<up> Suc rex) tm_erase_right_then_dblBk_left = (10, Bk \<up> nat @ [Bk, Oc] @ CL, Bk \<up> Suc (Suc rex))" by (simp add: tm_erase_right_then_dblBk_left_def step.simps steps.simps numeral_eqs_upto_12) with todo_step have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (10, Bk \<up> nat @ [Bk, Oc] @ CL, Bk \<up> Suc (Suc rex))" by auto (* establish measure *) with \<open>lex = Suc nat\<close> cf_at_current and unpacked_INV show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) qed next assume "\<exists>rex. l = [Oc] @ CL \<and> r = Bk \<up> Suc rex" then obtain rex where unpacked_INV: "l = [Oc] @ CL \<and> r = Bk \<up> Suc rex" by blast (* compute the next state *) with unpacked_INV cf_at_stp and \<open>s=10\<close> and SUC_STEP_RED have todo_step: "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (10, [Oc] @ CL, Bk \<up> Suc rex) tm_erase_right_then_dblBk_left" by auto also with unpacked_INV have "... = (10, CL, Oc# Bk \<up> (Suc rex))" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (10, CL, Oc# Bk \<up> (Suc rex))" by auto (* establish measure *) with cf_at_current and unpacked_INV show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next assume "\<exists>rex. l = CL \<and> r = Oc # Bk \<up> Suc rex" then obtain rex where unpacked_INV: "l = CL \<and> r = Oc # Bk \<up> Suc rex" by blast show ?thesis proof (cases CL) (* here, we start decomposing CL in the loop 'move to left until Oc *) case Nil then have minor: "CL = []" . with unpacked_INV cf_at_stp and \<open>s=10\<close> and SUC_STEP_RED (* compute the next state *) have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (10, [], Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left" by auto also with minor and unpacked_INV have "... = (11, [], Bk#Oc# Bk \<up> (Suc rex))" (* YYYY1' *) by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (11, [], Bk#Oc# Bk \<up> (Suc rex))" by auto (* establish measure *) with cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next case (Cons a rs') then have major2: "CL = a # rs'" . then show ?thesis proof (cases a) case Bk with major2 have minor: "CL = Bk#rs'" by auto with unpacked_INV cf_at_stp and \<open>s=10\<close> and SUC_STEP_RED (* compute the next state *) have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (10, Bk#rs', Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left" by auto also with minor and unpacked_INV have "... = (11, rs', Bk# Oc # Bk \<up> Suc rex)" (* YYYY2',YYYY3 *) by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (11, rs', Bk# Oc # Bk \<up> Suc rex)" by auto (* establish measure *) with cf_at_current and minor show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next case Oc with major2 have minor: "CL = Oc#rs'" by auto with unpacked_INV cf_at_stp and \<open>s=10\<close> and SUC_STEP_RED (* compute the next state *) have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (10, Oc#rs', Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left" by auto also with minor and unpacked_INV have "... = (11, rs', Oc# Oc # Bk \<up> Suc rex)" (* YYYY2'', YYYY5, YYYY6, YYYY7 *) by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (11, rs', Oc# Oc # Bk \<up> Suc rex)" by auto (* establish measure *) with cf_at_current and minor show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) qed qed qed next assume "s=11" (* get the invariant of the state *) with cf_at_stp have cf_at_current: "steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp = (11, l, r)" by auto with cf_at_stp and \<open>s=11\<close> and INV have "(\<exists>rex. l = [] \<and> r = Bk# rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc)) \<or> (\<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk ) \<or> (\<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Oc ) \<or> (\<exists>rex. l = [Bk] \<and> r = rev [Oc] @ Oc # Bk \<up> Suc rex \<and> CL = [Oc, Bk]) \<or> (\<exists>rex ls1 ls2. l = Bk#Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Bk#Oc#ls2 \<and> ls1 = [Oc] ) \<or> (\<exists>rex ls1 ls2. l = Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc#ls2 \<and> ls1 = [Bk] ) \<or> (\<exists>rex ls1 ls2. l = Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc#ls2 \<and> ls1 = [Oc] ) \<or> (\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> [])" by auto then have s11_cases: "\<And>P. \<lbrakk> \<exists>rex. l = [] \<and> r = Bk# rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc) \<Longrightarrow> P; \<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk \<Longrightarrow> P; \<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Oc \<Longrightarrow> P; \<exists>rex. l = [Bk] \<and> r = rev [Oc] @ Oc # Bk \<up> Suc rex \<and> CL = [Oc, Bk] \<Longrightarrow> P; \<exists>rex ls1 ls2. l = Bk#Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Bk#Oc#ls2 \<and> ls1 = [Oc] \<Longrightarrow> P; \<exists>rex ls1 ls2. l = Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc#ls2 \<and> ls1 = [Bk] \<Longrightarrow> P; \<exists>rex ls1 ls2. l = Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc#ls2 \<and> ls1 = [Oc] \<Longrightarrow> P; \<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> [] \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" by blast show ?thesis proof (rule s11_cases) assume "\<exists>rex ls1 ls2. l = Bk # Oc # ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Bk # Oc # ls2 \<and> ls1 = [Oc]" (* YYYY6 *) then obtain rex ls1 ls2 where unpacked_INV: "l = Bk#Oc#ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Bk#Oc#ls2 \<and> ls1 = [Oc]" by blast from unpacked_INV cf_at_stp and \<open>s=11\<close> and SUC_STEP_RED have todo_step: "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (11, Bk#Oc#ls2, r) tm_erase_right_then_dblBk_left" by auto also with unpacked_INV have "... = (11, Oc # ls2, Bk # r)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (11, Oc # ls2, Bk # r)" by auto (* establish measure *) with cf_at_current and unpacked_INV show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next assume "\<exists>rex ls1 ls2. l = Oc # ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc # ls2 \<and> ls1 = [Oc]" (* YYYY7 *) then obtain rex ls1 ls2 where unpacked_INV: "l = Oc # ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc # ls2 \<and> ls1 = [Oc]" by blast from unpacked_INV cf_at_stp and \<open>s=11\<close> and SUC_STEP_RED have todo_step: "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (11, l, r) tm_erase_right_then_dblBk_left" by auto also with unpacked_INV have "... = (11, ls2, Oc#r)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (11, ls2, Oc#r)" by auto (* establish measure *) with cf_at_current and unpacked_INV show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next assume "\<exists>rex. l = [Bk] \<and> r = rev [Oc] @ Oc # Bk \<up> Suc rex \<and> CL = [Oc, Bk]" (* YYYY5 *) then obtain rex where unpacked_INV: "l = [Bk] \<and> r = rev [Oc] @ Oc # Bk \<up> Suc rex \<and> CL = [Oc, Bk]" by blast (* compute the next state *) from unpacked_INV cf_at_stp and \<open>s=11\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (11, l, r) tm_erase_right_then_dblBk_left" by auto also with unpacked_INV have "... = (11, [], Bk#r)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (11, [], Bk#r)" by auto (* establish measure *) with cf_at_current and unpacked_INV show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next assume "\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> []" (* YYYY8 *) then obtain rex ls1 ls2 where A_case: "l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> []" by blast (* we have to decompose both ls1 and ls2 in order to predict the next step *) then have "\<exists>z b bs. ls1 = z#bs@[b]" (* the symbol z does not matter *) by (metis Nil_tl list.exhaust_sel rev_exhaust) then have "\<exists>z bs. ls1 = z#bs@[Bk] \<or> ls1 = z#bs@[Oc]" using cell.exhaust by blast then obtain z bs where w_z_bs: "ls1 = z#bs@[Bk] \<or> ls1 = z#bs@[Oc]" by blast then show ?thesis proof assume major1: "ls1 = z # bs @ [Bk]" then have major2: "rev ls1 = Bk#(rev bs)@[z]" by auto (* in this case all transitions will be s11 \<longrightarrow> s12 *) show ?thesis proof (rule noDblBk_cases) from \<open>noDblBk CL\<close> show "noDblBk CL" . next from A_case show "CL = ls1 @ ls2" by auto next assume minor: "ls2 = []" (* compute the next state *) with A_case major2 cf_at_stp and \<open>s=11\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (11, [], Bk#(rev bs)@[z] @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left" by auto also have "... = (12, [], Bk#Bk#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (12, [], Bk#Bk#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" by auto (* establish measure *) with cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next assume "ls2 = [Bk]" with A_case \<open>rev ls1 = Bk#(rev bs)@[z]\<close> and \<open>ls2 = [Bk]\<close> have "ls1 = z#bs@[Bk]" and "CL = z#bs@[Bk]@[Bk]" by auto with \<open>noDblBk CL\<close> have False by (metis A_case \<open>ls2 = [Bk]\<close> append_Cons hasDblBk_L5 major2) then show ?thesis by auto next fix C3 assume minor: "ls2 = Bk # Oc # C3" with A_case and major2 have "CL = z # bs @ [Bk] @ Bk # Oc # C3" by auto with \<open>noDblBk CL\<close> have False by (metis append.left_neutral append_Cons append_assoc hasDblBk_L1 major1 minor) then show ?thesis by auto next fix C3 assume minor: "ls2 = Oc # C3" (* compute the next state *) with A_case major2 cf_at_stp and \<open>s=11\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (11, Oc # C3 , Bk#(rev bs)@[z] @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left" by auto also have "... = (12, C3, Oc#Bk#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (12, C3, Oc#Bk#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" by auto (* establish measure *) with A_case minor cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) qed next assume major1: "ls1 = z # bs @ [Oc]" then have major2: "rev ls1 = Oc#(rev bs)@[z]" by auto (* in this case all transitions will be s11 \<longrightarrow> s11 *) show ?thesis proof (rule noDblBk_cases) from \<open>noDblBk CL\<close> show "noDblBk CL" . next from A_case show "CL = ls1 @ ls2" by auto next assume minor: "ls2 = []" (* compute the next state *) with A_case major2 cf_at_stp and \<open>s=11\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (11, [] , Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left" by auto also have "... = (11, [], Bk#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (11, [], Bk#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex)" by auto (* establish measure *) with A_case minor major2 cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next assume minor: "ls2 = [Bk]" (* compute the next state *) with A_case major2 cf_at_stp and \<open>s=11\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (11, [Bk] , Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left" by auto also have "... = (11, [], Bk#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (11, [], Bk#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex )" by auto (* establish measure *) with A_case minor major2 cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next fix C3 assume minor: "ls2 = Bk # Oc # C3" (* compute the next state *) with A_case major2 cf_at_stp and \<open>s=11\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (11, Bk # Oc # C3 , Oc # rev bs @ [z] @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left" by auto also have "... = (11, Oc # C3, Bk#Oc # rev bs @ [z] @ Oc # Bk \<up> Suc rex )" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (11, Oc # C3, Bk#Oc # rev bs @ [z] @ Oc # Bk \<up> Suc rex )" by auto (* establish measure *) with A_case minor major2 cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next fix C3 assume minor: "ls2 = Oc # C3" (* compute the next state *) with A_case major2 cf_at_stp and \<open>s=11\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (11, Oc # C3 , Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left" by auto also have "... = (11, C3, Oc#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (11, C3, Oc#Oc#(rev bs)@[z] @ Oc # Bk \<up> Suc rex)" by auto (* establish measure *) with A_case minor major2 cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) qed qed next assume "\<exists>rex ls1 ls2. l = Oc # ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc # ls2 \<and> ls1 = [Bk]" (* YYYY3 *) then obtain rex ls1 ls2 where unpacked_INV: "l = Oc # ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ Oc # ls2 \<and> ls1 = [Bk]" by blast (* compute the next state *) from unpacked_INV cf_at_stp and \<open>s=11\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (11, l, r) tm_erase_right_then_dblBk_left" by auto also with unpacked_INV have "... = (12, ls2, Oc#[Bk] @ Oc # Bk \<up> Suc rex )" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (12, ls2, Oc#[Bk] @ Oc # Bk \<up> Suc rex )" by auto (* establish measure *) with cf_at_current and unpacked_INV show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next assume "\<exists>rex. l = [] \<and> r = Bk # rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc)" (* YYYY1' *) then obtain rex where unpacked_INV: "l = [] \<and> r = Bk # rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc)" by blast (* compute the next state *) from unpacked_INV cf_at_stp and \<open>s=11\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (11, l, r) tm_erase_right_then_dblBk_left" by auto also with unpacked_INV have "... = (12, [], Bk#Bk # rev CL @ Oc # Bk \<up> Suc rex )" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (12, [], Bk#Bk # rev CL @ Oc # Bk \<up> Suc rex )" by auto (* establish measure *) with cf_at_current and unpacked_INV show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next assume "\<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk" (* YYYY2' *) then obtain rex where unpacked_INV: "l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk" by blast then have "hd (rev CL) = Bk" by (simp add: hd_rev) (* compute the next state *) from unpacked_INV cf_at_stp and \<open>s=11\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (11, l, r) tm_erase_right_then_dblBk_left" by auto also with unpacked_INV and \<open>hd (rev CL) = Bk\<close> have "... = (12, [], Bk # rev CL @ Oc # Bk \<up> Suc rex )" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (12, [], Bk # rev CL @ Oc # Bk \<up> Suc rex )" by auto (* establish measure *) with cf_at_current and unpacked_INV show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next assume "\<exists>rex. l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Oc" (* YYYY2'' *) then obtain rex where unpacked_INV: "l = [] \<and> r = rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Oc" by blast then have "hd (rev CL) = Oc" by (simp add: hd_rev) (* compute the next state *) from unpacked_INV cf_at_stp and \<open>s=11\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (11, l, r) tm_erase_right_then_dblBk_left" by auto also with unpacked_INV and \<open>hd (rev CL) = Oc\<close> have "... = (11, [], Bk # rev CL @ Oc # Bk \<up> Suc rex )" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (11, [], Bk # rev CL @ Oc # Bk \<up> Suc rex )" by auto (* establish measure *) with cf_at_current and unpacked_INV and \<open>hd (rev CL) = Oc\<close> show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) qed next assume "s=12" (* get the invariant of the state *) with cf_at_stp have cf_at_current: "steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp = (12, l, r)" by auto with cf_at_stp and \<open>s=12\<close> and INV have " (\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> [] \<and> last ls1 = Oc) \<or> (\<exists>rex. l = [] \<and> r = Bk#rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk) \<or> (\<exists>rex. l = [] \<and> r = Bk#Bk#rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc))" by auto then have s12_cases: "\<And>P. \<lbrakk> \<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> [] \<and> last ls1 = Oc \<Longrightarrow> P; \<exists>rex. l = [] \<and> r = Bk#rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk \<Longrightarrow> P; \<exists>rex. l = [] \<and> r = Bk#Bk#rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc) \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" by blast show ?thesis proof (rule s12_cases) (* YYYY4 *) assume "\<exists>rex ls1 ls2. l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2 \<and> tl ls1 \<noteq> [] \<and> last ls1 = Oc" then obtain rex ls1 ls2 where unpacked_INV: "l = ls2 \<and> r = rev ls1 @ Oc # Bk \<up> Suc rex \<and> CL = ls1 @ ls2\<and> tl ls1 \<noteq> [] \<and> last ls1 = Oc" by blast then have "ls1 \<noteq> []" by auto with unpacked_INV have major: "hd (rev ls1) = Oc" by (simp add: hd_rev) with unpacked_INV and major have minor2: "r = Oc#tl ((rev ls1) @ Oc # Bk \<up> Suc rex)" by (metis Nil_is_append_conv \<open>ls1 \<noteq> []\<close> hd_Cons_tl hd_append2 list.simps(3) rev_is_Nil_conv) show ?thesis proof (rule noDblBk_cases) from \<open>noDblBk CL\<close> show "noDblBk CL" . next from unpacked_INV show "CL = ls1 @ ls2" by auto next assume minor: "ls2 = []" (* compute the next state *) with unpacked_INV minor minor2 major cf_at_stp and \<open>s=12\<close> and \<open>ls1 \<noteq> []\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (12, [] , Oc#tl ((rev ls1) @ Oc # Bk \<up> Suc rex)) tm_erase_right_then_dblBk_left" by auto also have "... = (11, [], Bk#Oc#tl ((rev ls1) @ Oc # Bk \<up> Suc rex))" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) also with unpacked_INV and minor2 have "... = (11, [], Bk# rev ls1 @ Oc # Bk \<up> Suc rex )" by auto finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (11, [], Bk# rev ls1 @ Oc # Bk \<up> Suc rex )" by auto (* establish measure *) with unpacked_INV minor major minor2 cf_at_current \<open>ls1 \<noteq> []\<close> show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next assume minor: "ls2 = [Bk]" (* compute the next state *) with unpacked_INV minor minor2 major cf_at_stp and \<open>s=12\<close> and \<open>ls1 \<noteq> []\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (12, [Bk] , Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex)) tm_erase_right_then_dblBk_left" by auto also have "... = (11, [], Bk#Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex ))" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (11, [], Bk#Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex ))" by auto (* establish measure *) with unpacked_INV minor major minor2 cf_at_current \<open>ls1 \<noteq> []\<close> show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next fix C3 assume minor: "ls2 = Bk # Oc # C3" (* compute the next state *) with unpacked_INV minor minor2 major cf_at_stp and \<open>s=12\<close> and \<open>ls1 \<noteq> []\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (12, Bk # Oc # C3 , Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex)) tm_erase_right_then_dblBk_left" by auto also have "... = (11, Oc # C3, Bk#Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex ))" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (11, Oc # C3, Bk#Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex ))" by auto (* establish measure *) with unpacked_INV minor major minor2 cf_at_current \<open>ls1 \<noteq> []\<close> show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next fix C3 assume minor: "ls2 = Oc # C3" (* compute the next state *) with unpacked_INV minor minor2 major cf_at_stp and \<open>s=12\<close> and \<open>ls1 \<noteq> []\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (12, Oc # C3 , Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex)) tm_erase_right_then_dblBk_left" by auto also have "... = (11, C3, Oc#Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex ))" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (11, C3, Oc#Oc#tl (rev ls1 @ Oc # Bk \<up> Suc rex ))" by auto (* establish measure *) with unpacked_INV minor major minor2 cf_at_current \<open>ls1 \<noteq> []\<close> show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) qed next (* YYYY6''' *) assume "\<exists>rex. l = [] \<and> r = Bk # rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk" then obtain rex where unpacked_INV: "l = [] \<and> r = Bk # rev CL @ Oc # Bk \<up> Suc rex \<and> CL \<noteq> [] \<and> last CL = Bk" by blast (* compute the next state *) with cf_at_stp and \<open>s=12\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (12, [] , Bk # rev CL @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left" by auto also have "... = (0, [], Bk # rev CL @ Oc # Bk \<up> Suc rex)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (0, [], Bk # rev CL @ Oc # Bk \<up> Suc rex)" by auto (* establish measure *) with cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) next (* YYYY9 *) assume "\<exists>rex. l = [] \<and> r = Bk # Bk # rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc)" then obtain rex where unpacked_INV: "l = [] \<and> r = Bk # Bk # rev CL @ Oc # Bk \<up> Suc rex \<and> (CL = [] \<or> last CL = Oc)" by blast (* compute the next state *) with cf_at_stp and \<open>s=12\<close> and SUC_STEP_RED have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = step0 (12, [] , Bk # Bk # rev CL @ Oc # Bk \<up> Suc rex) tm_erase_right_then_dblBk_left" by auto also have "... = (0, [], Bk# Bk # rev CL @ Oc # Bk \<up> Suc rex)" by (auto simp add: tm_erase_right_then_dblBk_left_def numeral_eqs_upto_12 step.simps steps.simps) finally have "steps0 (1, [Bk, Oc] @ CL, CR) tm_erase_right_then_dblBk_left (Suc stp) = (0, [], Bk# Bk # rev CL @ Oc # Bk \<up> Suc rex)" by auto (* establish measure *) with cf_at_current show ?thesis by (auto simp add: measure_tm_erase_right_then_dblBk_left_erp_def) qed qed qed qed (* -------------- Total correctness for the ERASE path of tm_erase_right_then_dblBk_left ------------------ *) lemma tm_erase_right_then_dblBk_left_erp_total_correctness_CL_is_Nil: assumes "noDblBk CL" and "noDblBk CR" and "CL = []" shows "\<lbrace> \<lambda>tap. tap = ([Bk,Oc] @ CL, CR) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. \<exists>rex. tap = ([], [Bk,Bk] @ (rev CL) @ [Oc, Bk] @ Bk \<up> rex ) \<rbrace>" proof (rule tm_erase_right_then_dblBk_left_erp_partial_correctness_CL_is_Nil) from assms show "\<exists>stp. is_final (steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp)" using tm_erase_right_then_dblBk_left_erp_halts by auto next from assms show "noDblBk CL" by auto next from assms show "noDblBk CR" by auto next from assms show "CL = []" by auto qed lemma tm_erase_right_then_dblBk_left_correctness_CL_ew_Bk: assumes "noDblBk CL" and "noDblBk CR" and "CL \<noteq> []" and "last CL = Bk" shows "\<lbrace> \<lambda>tap. tap = ([Bk,Oc] @ CL, CR) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. \<exists>rex. tap = ([], [Bk] @ (rev CL) @ [Oc, Bk] @ Bk \<up> rex ) \<rbrace>" proof (rule tm_erase_right_then_dblBk_left_erp_partial_correctness_CL_ew_Bk) from assms show "\<exists>stp. is_final (steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp)" using tm_erase_right_then_dblBk_left_erp_halts by auto next from assms show "noDblBk CL" by auto next from assms show "noDblBk CR" by auto next from assms show "CL \<noteq> []" by auto next from assms show "last CL = Bk" by auto qed lemma tm_erase_right_then_dblBk_left_erp_total_correctness_CL_ew_Oc: assumes "noDblBk CL" and "noDblBk CR" and "CL \<noteq> []" and "last CL = Oc" shows "\<lbrace> \<lambda>tap. tap = ([Bk,Oc] @ CL, CR) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. \<exists>rex. tap = ([], [Bk, Bk] @ (rev CL) @ [Oc, Bk] @ Bk \<up> rex ) \<rbrace>" proof (rule tm_erase_right_then_dblBk_left_erp_partial_correctness_CL_ew_Oc) from assms show "\<exists>stp. is_final (steps0 (1, [Bk,Oc] @ CL, CR) tm_erase_right_then_dblBk_left stp)" using tm_erase_right_then_dblBk_left_erp_halts by auto next from assms show "noDblBk CL" by auto next from assms show "noDblBk CR" by auto next from assms show "CL \<noteq> []" by auto next from assms show "last CL = Oc" by auto qed (* --- prove some helper theorems to convert results to lists of numeral --- *) (*--------------------------------------------------------------------------------- *) (* simple case, where we tried to check for exactly one argument and failed *) (*--------------------------------------------------------------------------------- *) lemma tm_erase_right_then_dblBk_left_erp_total_correctness_helper_CL_eq_Nil_n_eq_1_last_eq_0: assumes "(nl::nat list) \<noteq> []" and "n=1" and "n \<le> length nl" and "last (take n nl) = 0" shows "\<exists>CL CR. [Oc] @ CL = rev(<take n nl>) \<and> noDblBk CL \<and> CL = [] \<and> CR = (<drop n nl>) \<and> noDblBk CR" proof - have "rev(<take n nl>) = <rev(take n nl)>" by (rule rev_numeral_list) also with assms have "... = <rev( butlast (take n nl) @ [last (take n nl)] )>" by (metis append_butlast_last_id take_eq_Nil zero_neq_one) also have "... = < (rev[(last (take n nl))]) @ (rev ( butlast (take n nl)))>" by simp also with assms have "... = < (rev [0]) @ (rev ( butlast (take n nl)))>" by auto finally have major: "rev(<take n nl>) = <(rev [0]) @ (rev ( butlast (take n nl)))>" by auto with assms have "butlast (take n nl) = []" by (simp add: butlast_take) then have "<(rev [0::nat]) @ (rev ( butlast (take n nl)))> = <(rev [0::nat]) @ (rev [])>" by auto also have "... = <(rev [0::nat])>" by auto also have "... = <[0::nat]>" by auto also have "... = [Oc]" by (simp add: tape_of_list_def tape_of_nat_def ) finally have "<(rev [0::nat]) @ (rev ( butlast (take n nl)))> = [Oc]" by auto with major have "rev(<take n nl>) = [Oc]" by auto then have "[Oc] @ [] = rev(<take n nl>) \<and> noDblBk [] \<and> ([] = [] \<or> [] \<noteq> [] \<and> last [] = Oc) \<and> (<drop n nl>) = (<drop n nl>) \<and> noDblBk (<drop n nl>)" by (simp add: noDblBk_Nil noDblBk_tape_of_nat_list) then show ?thesis by blast qed lemma tm_erase_right_then_dblBk_left_erp_total_correctness_helper_CL_neq_Nil_n_eq_1_last_neq_0: assumes "(nl::nat list) \<noteq> []" and "n=1" and "n \<le> length nl" and "0 < last (take n nl)" shows "\<exists>CL CR. [Oc] @ CL = rev(<take n nl>) \<and> noDblBk CL \<and> CL \<noteq> [] \<and> last CL = Oc \<and> CR = (<drop n nl>) \<and> noDblBk CR" proof - have minor: "rev(<take n nl>) = <rev(take n nl)>" by (rule rev_numeral_list) also with assms have "... = <rev( butlast (take n nl) @ [last (take n nl)] )>" by simp also have "... = <(rev[last (take n nl)]) @ (rev (butlast (take n nl)))>" by simp finally have major: "rev(<take n nl>) = <(rev[(last (take n nl))]) @ (rev ( butlast (take n nl)))>" by auto moreover from assms have "[last (take n nl)] \<noteq> []" by auto moreover from assms have "butlast (take n nl) = []" by (simp add: butlast_take) ultimately have "rev(<take n nl>) = <(rev[(last (take n nl))])>" by auto also have "<(rev[(last (take n nl))])> = Oc\<up> Suc (last (take n nl))" proof - from assms have "<[(last (take n nl))]> = Oc\<up> Suc (last (take n nl))" by (simp add: tape_of_list_def tape_of_nat_def) then show "<(rev[(last (take n nl))])> = Oc\<up> Suc (last (take n nl))" by simp qed also have "... = Oc# Oc\<up> (last (take n nl))" by auto finally have "rev(<take n nl>) = Oc# Oc\<up> (last (take n nl))" by auto moreover from assms have "Oc\<up> (last (take n nl)) \<noteq> []" by auto ultimately have "[Oc] @ (Oc\<up> (last (take n nl))) = rev(<take n nl>) \<and> noDblBk (Oc\<up> (last (take n nl))) \<and> (Oc\<up> (last (take n nl))) \<noteq> [] \<and> last (Oc\<up> (last (take n nl))) = Oc \<and> (<drop n nl>) = (<drop n nl>) \<and> noDblBk (<drop n nl>)" using assms by (simp add: noDblBk_Bk_Oc_rep noDblBk_tape_of_nat_list) then show ?thesis by auto qed (* convenient versions using hd and tl for tm_skip_first_arg *) lemma tm_erase_right_then_dblBk_left_erp_total_correctness_helper_CL_eq_Nil_last_eq_0': assumes "1 \<le> length (nl:: nat list)" and "hd nl = 0" shows "\<exists>CL CR. [Oc] @ CL = rev(<hd nl>) \<and> noDblBk CL \<and> CL = [] \<and> CR = (<tl nl>) \<and> noDblBk CR" proof - from assms have "(nl::nat list) \<noteq> [] \<and> (1::nat)=1 \<and> 1 \<le> length nl \<and> 0 = last (take 1 nl)" by (metis One_nat_def append.simps(1) append_butlast_last_id butlast_take diff_Suc_1 hd_take le_numeral_extra(4) length_0_conv less_numeral_extra(1) list.sel(1) not_one_le_zero take_eq_Nil zero_less_one) then have "\<exists>n. (nl::nat list) \<noteq> [] \<and> n=1 \<and> n \<le> length nl \<and> 0 = last (take n nl)" by blast then obtain n where w_n: "(nl::nat list) \<noteq> [] \<and> n=1 \<and> n \<le> length nl \<and> 0 = last (take n nl)" by blast then have "\<exists>CL CR. [Oc] @ CL = rev(<take n nl>) \<and> noDblBk CL \<and> CL = [] \<and> CR = (<drop n nl>) \<and> noDblBk CR" using tm_erase_right_then_dblBk_left_erp_total_correctness_helper_CL_eq_Nil_n_eq_1_last_eq_0 by auto then obtain CL CR where w_CL_CR: "[Oc] @ CL = rev (<take n nl>) \<and> noDblBk CL \<and> CL = [] \<and> CR = <drop n nl> \<and> noDblBk CR" by blast with assms w_n show ?thesis by (simp add: noDblBk_Nil noDblBk_tape_of_nat_list rev_numeral tape_of_nat_def) qed lemma tm_erase_right_then_dblBk_left_erp_total_correctness_helper_CL_neq_Nil_last_neq_0': assumes "1 \<le> length (nl::nat list)" and "0 < hd nl" shows "\<exists>CL CR. [Oc] @ CL = rev(<hd nl>) \<and> noDblBk CL \<and> CL \<noteq> [] \<and> last CL = Oc \<and> CR = (<tl nl>) \<and> noDblBk CR" proof - from assms have "(nl::nat list) \<noteq> [] \<and> (1::nat)=1 \<and> 1 \<le> length nl \<and> 0 < last (take 1 nl)" by (metis append.simps(1) append_butlast_last_id butlast_take cancel_comm_monoid_add_class.diff_cancel ex_least_nat_le hd_take le_trans list.sel(1) list.size(3) neq0_conv not_less not_less_zero take_eq_Nil zero_less_one zero_neq_one) then have "\<exists>n. (nl::nat list) \<noteq> [] \<and> n=1 \<and> n \<le> length nl \<and> 0 < last (take n nl)" by blast then obtain n where w_n: "(nl::nat list) \<noteq> [] \<and> n=1 \<and> n \<le> length nl \<and> 0 < last (take n nl)" by blast then have "\<exists>CL CR. [Oc] @ CL = rev(<take n nl>) \<and> noDblBk CL \<and> CL \<noteq> [] \<and> last CL = Oc \<and> CR = (<drop n nl>) \<and> noDblBk CR" using tm_erase_right_then_dblBk_left_erp_total_correctness_helper_CL_neq_Nil_n_eq_1_last_neq_0 by auto with assms w_n show ?thesis by (simp add: drop_Suc take_Suc tape_of_list_def ) qed (*--------------------------------------------------------------------------------- *) (* generic case , where we tried to check for more than one one argument and failed *) (*--------------------------------------------------------------------------------- *) lemma tm_erase_right_then_dblBk_left_erp_total_correctness_helper_CL_neq_Nil_n_gt_1_last_eq_0: assumes "(nl::nat list) \<noteq> []" and "1<n" and "n \<le> length nl" and "last (take n nl) = 0" shows "\<exists>CL CR. [Oc] @ CL = rev(<take n nl>) \<and> noDblBk CL \<and> CL \<noteq> [] \<and> last CL = Oc \<and> CR = (<drop n nl>) \<and> noDblBk CR" proof - have minor: "rev(<take n nl>) = <rev(take n nl)>" by (rule rev_numeral_list) also with assms have "... = <rev( butlast (take n nl) @ [last (take n nl)] )>" by (metis append_butlast_last_id not_one_less_zero take_eq_Nil) also have "... = < (rev [(last (take n nl))]) @ (rev ( butlast (take n nl)))>" by simp also with assms have "... = <(rev [0]) @ (rev ( butlast (take n nl)))>" by auto finally have major: "rev(<take n nl>) = <(rev [0]) @ (rev ( butlast (take n nl)))>" by auto moreover have "<(rev [0::nat])> = [Oc]" by (simp add: tape_of_list_def tape_of_nat_def ) moreover with assms have not_Nil: "rev (butlast (take n nl)) \<noteq> []" by (simp add: butlast_take) ultimately have "rev(<take n nl>) = [Oc] @ [Bk] @ <rev (butlast (take n nl))>" using tape_of_nat_def tape_of_nat_list_cons_eq by auto then show ?thesis using major and minor and not_Nil by (metis append_Nil append_is_Nil_conv append_is_Nil_conv last_append last_appendR list.sel(3) noDblBk_tape_of_nat_list noDblBk_tape_of_nat_list_imp_noDblBk_tl numeral_list_last_is_Oc rev.simps(1) rev_append snoc_eq_iff_butlast tl_append2) qed lemma tm_erase_right_then_dblBk_left_erp_total_correctness_helper_CL_neq_Nil_n_gt_1_last_neq_0: assumes "(nl::nat list) \<noteq> []" and "1 < n" and "n \<le> length nl" and "0 < last (take n nl)" shows "\<exists>CL CR. [Oc] @ CL = rev(<take n nl>) \<and> noDblBk CL \<and> CL \<noteq> [] \<and> last CL = Oc \<and> CR = (<drop n nl>) \<and> noDblBk CR" proof - have minor: "rev(<take n nl>) = <rev(take n nl)>" by (rule rev_numeral_list) also with assms have "... = <rev( butlast (take n nl) @ [last (take n nl)] )>" by (metis append_butlast_last_id not_one_less_zero take_eq_Nil) also have "... = <(rev [(last (take n nl))]) @ (rev ( butlast (take n nl)))>" by simp finally have major: "rev(<take n nl>) = <(rev[(last (take n nl))]) @ (rev ( butlast (take n nl)))>" by auto moreover from assms have "[last (take n nl)] \<noteq> []" by auto moreover from assms have "butlast (take n nl) \<noteq> []" by (simp add: butlast_take) ultimately have "rev(<take n nl>) = <(rev[(last (take n nl))])> @[Bk] @ <(rev ( butlast (take n nl)))>" by (metis append_numeral_list rev.simps(1) rev_rev_ident rev_singleton_conv) also have "<(rev[(last (take n nl))])> = Oc\<up> Suc (last (take n nl))" proof - from assms have "<[(last (take n nl))]> = Oc\<up> Suc (last (take n nl))" by (simp add: tape_of_list_def tape_of_nat_def) then show "<(rev[(last (take n nl))])> = Oc\<up> Suc (last (take n nl))" by simp qed also have "... = Oc# Oc\<up> (last (take n nl))" by auto finally have "rev(<take n nl>) = Oc# Oc\<up> (last (take n nl)) @[Bk] @ <(rev ( butlast (take n nl)))>" by auto moreover from assms have "Oc\<up> (last (take n nl)) \<noteq> []" by auto ultimately have "[Oc] @ (Oc\<up> (last (take n nl)) @[Bk] @ <(rev ( butlast (take n nl)))>) = rev(<take n nl>) \<and> noDblBk (Oc\<up> (last (take n nl)) @[Bk] @ <(rev ( butlast (take n nl)))>) \<and> (Oc\<up> (last (take n nl)) @[Bk] @ <(rev ( butlast (take n nl)))>) \<noteq> [] \<and> last (Oc\<up> (last (take n nl)) @[Bk] @ <(rev ( butlast (take n nl)))>) = Oc \<and> (<drop n nl>) = (<drop n nl>) \<and> noDblBk (<drop n nl>)" using assms \<open><rev [last (take n nl)]> = Oc \<up> Suc (last (take n nl))\<close> \<open>Oc \<up> Suc (last (take n nl)) = Oc # Oc \<up> last (take n nl)\<close> \<open>butlast (take n nl) \<noteq> []\<close> \<open>rev (<take n nl>) = <rev [last (take n nl)]> @ [Bk] @ <rev (butlast (take n nl))>\<close> by (smt append_Cons append_Nil append_Nil2 append_eq_Cons_conv butlast.simps(1) butlast.simps(2) butlast_append last_ConsL last_append last_appendR list.sel(3) list.simps(3) minor noDblBk_tape_of_nat_list noDblBk_tape_of_nat_list_imp_noDblBk_tl numeral_list_last_is_Oc rev_is_Nil_conv self_append_conv) then show ?thesis by auto qed lemma tm_erase_right_then_dblBk_left_erp_total_correctness_helper_CL_neq_Nil_n_gt_1: assumes "(nl::nat list) \<noteq> []" and "1<n" and "n \<le> length nl" shows "\<exists>CL CR. [Oc] @ CL = rev(<take n nl>) \<and> noDblBk CL \<and> CL \<noteq> [] \<and> last CL = Oc \<and> CR = (<drop n nl>) \<and> noDblBk CR" proof (cases "last (take n nl)") case 0 with assms show ?thesis using tm_erase_right_then_dblBk_left_erp_total_correctness_helper_CL_neq_Nil_n_gt_1_last_eq_0 by auto next case (Suc nat) with assms show ?thesis using tm_erase_right_then_dblBk_left_erp_total_correctness_helper_CL_neq_Nil_n_gt_1_last_neq_0 by auto qed (*--------------------------------------------------------------------------------- *) (* For now, we only proof a result for n = 1 supporting tm_check_for_one_arg *) (*--------------------------------------------------------------------------------- *) (*----------------------------------------------------------------------------------------------------- *) (* ENHANCE: formalise generic tm_skip_n_args *) (* ENHANCE: formalise matching results for tm_erase_right_then_dblBk_left_erp_total_correctness_one_arg *) (*----------------------------------------------------------------------------------------------------- *) lemma tm_erase_right_then_dblBk_left_erp_total_correctness_one_arg: assumes "1 \<le> length (nl::nat list)" shows "\<lbrace> \<lambda>tap. tap = (Bk# rev(<hd nl>), <tl nl>) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. \<exists>rex. tap = ([], [Bk,Bk] @ (<hd nl>) @ [Bk] @ Bk \<up> rex ) \<rbrace>" proof (cases "hd nl") case 0 then have "hd nl = 0" . with assms have "\<exists>CL CR. [Oc] @ CL = rev(<hd nl>) \<and> noDblBk CL \<and> CL = [] \<and> CR = (<tl nl>) \<and> noDblBk CR" using tm_erase_right_then_dblBk_left_erp_total_correctness_helper_CL_eq_Nil_last_eq_0' by blast then obtain CL CR where w_CL_CR: "[Oc] @ CL = rev(<hd nl>) \<and> noDblBk CL \<and> CL = [] \<and> CR = (<tl nl>) \<and> noDblBk CR" by blast show ?thesis proof (rule Hoare_consequence) (* 1. \<lambda>tap. tap = (Bk # rev (<hd nl>), <tl nl>) \<mapsto> ?P *) from assms and w_CL_CR show "(\<lambda>tap. tap = (Bk # rev (<hd nl>), <tl nl>)) \<mapsto> (\<lambda>tap. tap = ([Bk,Oc] @ CL, CR))" using Cons_eq_appendI append_self_conv assert_imp_def by auto next (* 1. \<lbrace>\<lambda>tap. tap = ([Bk, Oc] @ CL, CR)\<rbrace> tm_erase_right_then_dblBk_left \<lbrace>?Q\<rbrace> *) from assms and w_CL_CR show "\<lbrace> \<lambda>tap. tap = ([Bk,Oc] @ CL, CR) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. \<exists>rex. tap = ([], [Bk,Bk] @ (rev CL) @ [Oc, Bk] @ Bk \<up> rex ) \<rbrace>" using tm_erase_right_then_dblBk_left_erp_total_correctness_CL_is_Nil by blast next (* 1. \<lambda>tap. \<exists>rex. tap = ([], [Bk, Bk] @ rev CL @ [Oc, Bk] @ Bk \<up> rex) \<mapsto> \<lambda>tap. \<exists>rex. tap = ([], [Bk, Bk] @ <hd nl> @ [Bk] @ Bk \<up> rex) *) show "(\<lambda>tap. \<exists>rex. tap = ([], [Bk, Bk] @ rev CL @ [Oc, Bk] @ Bk \<up> rex)) \<mapsto> (\<lambda>tap. \<exists>rex. tap = ([], [Bk, Bk] @ <hd nl> @ [Bk] @ Bk \<up> rex))" using Cons_eq_append_conv assert_imp_def rev_numeral w_CL_CR by fastforce qed next case (Suc nat) then have "0 < hd nl" by auto with assms have "\<exists>CL CR. [Oc] @ CL = rev(<hd nl>) \<and> noDblBk CL \<and> CL \<noteq> [] \<and> last CL = Oc \<and> CR = (<tl nl>) \<and> noDblBk CR" using tm_erase_right_then_dblBk_left_erp_total_correctness_helper_CL_neq_Nil_last_neq_0' by auto then obtain CL CR where w_CL_CR: "[Oc] @ CL = rev(<hd nl>) \<and> noDblBk CL \<and> CL \<noteq> [] \<and> last CL = Oc \<and> CR = (<tl nl>) \<and> noDblBk CR" by blast show ?thesis proof (rule Hoare_consequence) (* 1. \<lambda>tap. tap = (Bk # rev (<hd nl>), <tl nl>) \<mapsto> ?P *) from assms and w_CL_CR show "(\<lambda>tap. tap = (Bk # rev (<hd nl>), <tl nl>)) \<mapsto> (\<lambda>tap. tap = ([Bk,Oc] @ CL, CR))" by (simp add: w_CL_CR assert_imp_def) next (* \<lbrace>\<lambda>tap. tap = ([Bk, Oc] @ CL, CR)\<rbrace> tm_erase_right_then_dblBk_left \<lbrace>?Q\<rbrace> *) from assms and w_CL_CR show "\<lbrace> \<lambda>tap. tap = ([Bk,Oc] @ CL, CR) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. \<exists>rex. tap = ([], [Bk, Bk] @ (rev CL) @ [Oc, Bk] @ Bk \<up> rex ) \<rbrace>" using tm_erase_right_then_dblBk_left_erp_total_correctness_CL_ew_Oc by blast next (* \<lambda>tap. \<exists>rex. tap = ([], [Bk, Bk] @ rev CL @ [Oc, Bk] @ Bk \<up> rex) \<mapsto> \<lambda>tap. \<exists>rex. tap = ([], [Bk, Bk] @ <hd nl> @ [Bk] @ Bk \<up> rex) *) show "(\<lambda>tap. \<exists>rex. tap = ([], [Bk, Bk] @ rev CL @ [Oc, Bk] @ Bk \<up> rex)) \<mapsto> (\<lambda>tap. \<exists>rex. tap = ([], [Bk, Bk] @ <hd nl> @ [Bk] @ Bk \<up> rex))" using Cons_eq_append_conv assert_imp_def rev_numeral w_CL_CR by (simp add: assert_imp_def rev_numeral replicate_app_Cons_same tape_of_nat_def) qed qed (* ----------------------- tm_check_for_one_arg ----------------------- * Prove total correctness for COMPOSED machine tm_check_for_one_arg * This is done via the rules for the composition operator seq_tm * -------------------------------------------------------------------- *) (* we have DO_NOTHING path corollary tm_skip_first_arg_correct_Nil': "length nl = 0 \<Longrightarrow> \<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_skip_first_arg \<lbrace>\<lambda>tap. tap = ( [] , [Bk] ) \<rbrace>" lemma tm_skip_first_arg_len_eq_1_total_correctness': "length nl = 1 \<Longrightarrow> \<lbrace>\<lambda>tap. tap = ([], <nl::nat list> )\<rbrace> tm_skip_first_arg \<lbrace> \<lambda>tap. tap = ([Bk], <[hd nl]> @[Bk])\<rbrace>" lemma tm_erase_right_then_dblBk_left_dnp_total_correctness: "\<lbrace> \<lambda>tap. tap = ([], r ) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. tap = ([Bk,Bk], r ) \<rbrace>" --- ERASE path lemma tm_skip_first_arg_len_gt_1_total_correctness: assumes "1 < length (nl::nat list)" shows "\<lbrace>\<lambda>tap. tap = ([], <nl::nat list> )\<rbrace> tm_skip_first_arg \<lbrace> \<lambda>tap. tap = (Bk# <rev [hd nl]>, <tl nl>) \<rbrace>" lemma tm_erase_right_then_dblBk_left_erp_total_correctness_one_arg: assumes "1 \<le> length (nl::nat list)" shows "\<lbrace> \<lambda>tap. tap = (Bk# rev(<hd nl>), <tl nl>) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. \<exists>rex. tap = ([], [Bk,Bk] @ (<hd nl>) @ [Bk] @ Bk \<up> rex ) \<rbrace>" *) (* let tm_check_for_one_arg = foldl1' seqcomp_tm [ tm_skip_first_arg, tm_erase_right_then_dblBk_left ] *) definition tm_check_for_one_arg :: "instr list" where "tm_check_for_one_arg \<equiv> tm_skip_first_arg |+| tm_erase_right_then_dblBk_left" lemma tm_check_for_one_arg_total_correctness_Nil: "length nl = 0 \<Longrightarrow> \<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_check_for_one_arg \<lbrace>\<lambda>tap. tap = ([Bk,Bk], [Bk] ) \<rbrace>" proof - assume major: "length nl = 0" have "\<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> (tm_skip_first_arg |+| tm_erase_right_then_dblBk_left) \<lbrace>\<lambda>tap. tap = ([Bk,Bk], [Bk] ) \<rbrace>" proof (rule Hoare_plus_halt) show "composable_tm0 tm_skip_first_arg" by (simp add: composable_tm.simps adjust.simps shift.simps seq_tm.simps tm_skip_first_arg_def tm_erase_right_then_dblBk_left_def) next from major show "\<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_skip_first_arg \<lbrace>\<lambda>tap. tap = ( [] , [Bk] ) \<rbrace>" using tm_skip_first_arg_correct_Nil' by simp next from major show "\<lbrace>\<lambda>tap. tap = ([], [Bk])\<rbrace> tm_erase_right_then_dblBk_left \<lbrace>\<lambda>tap. tap = ([Bk, Bk], [Bk])\<rbrace>" using tm_erase_right_then_dblBk_left_dnp_total_correctness by simp qed then show ?thesis unfolding tm_check_for_one_arg_def by auto qed lemma tm_check_for_one_arg_total_correctness_len_eq_1: "length nl = 1 \<Longrightarrow> \<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_check_for_one_arg \<lbrace>\<lambda>tap. \<exists>z4. tap = (Bk \<up> z4, <nl> @ [Bk])\<rbrace>" proof - assume major: "length nl = 1" have " \<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> (tm_skip_first_arg |+| tm_erase_right_then_dblBk_left) \<lbrace>\<lambda>tap. \<exists>z4. tap = (Bk \<up> z4, <nl> @ [Bk])\<rbrace>" proof (rule Hoare_plus_halt) show "composable_tm0 tm_skip_first_arg" by (simp add: composable_tm.simps adjust.simps shift.simps seq_tm.simps tm_skip_first_arg_def tm_erase_right_then_dblBk_left_def) next from major have "\<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_skip_first_arg \<lbrace> \<lambda>tap. tap = ([Bk], <[hd nl]> @[Bk])\<rbrace>" using tm_skip_first_arg_len_eq_1_total_correctness' by simp moreover from major have "(nl::nat list) = [hd nl]" by (metis diff_self_eq_0 length_0_conv length_tl list.exhaust_sel zero_neq_one) ultimately show "\<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_skip_first_arg \<lbrace> \<lambda>tap. tap = ([Bk], <nl> @[Bk])\<rbrace>" using major by auto next from major have "\<lbrace>\<lambda>tap. tap = ([], <nl> @ [Bk])\<rbrace> tm_erase_right_then_dblBk_left \<lbrace>\<lambda>tap. tap = ([Bk, Bk], <nl> @ [Bk])\<rbrace>" using tm_erase_right_then_dblBk_left_dnp_total_correctness by simp (* Add a blank on the initial left tape *) with major have "\<exists>stp. is_final (steps0 (1, [],<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp) \<and> (steps0 (1, [],<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp = (0, [Bk, Bk], <nl> @ [Bk]))" unfolding Hoare_halt_def by (smt Hoare_halt_def Pair_inject holds_for.elims(2) is_final.elims(2)) then obtain stp where w_stp: "is_final (steps0 (1, [],<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp) \<and> (steps0 (1, [],<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp = (0, [Bk, Bk], <nl> @ [Bk]))" by blast then have "is_final (steps0 (1, Bk \<up> 0,<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp) \<and> (steps0 (1, Bk \<up> 0,<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp = (0, Bk \<up> 2, <nl> @ [Bk]))" by (simp add: is_finalI numeral_eqs_upto_12(1)) then have "\<exists>z3. z3 \<le> 0 + 1 \<and> is_final (steps0 (1, Bk \<up> (0+1),<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp) \<and> (steps0 (1, Bk \<up> (0+1),<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp = (0, Bk \<up> (2+z3), <nl> @ [Bk]))" by (metis is_finalI steps_left_tape_EnlargeBkCtx) then have "is_final (steps0 (1, [Bk],<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp) \<and> (\<exists>z4. steps0 (1, [Bk],<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp = (0, Bk \<up> z4, <nl> @ [Bk]))" by (metis One_nat_def add.left_neutral replicate_0 replicate_Suc) then have "\<exists>n. is_final (steps0 (1, [Bk],<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left n) \<and> (\<exists>z4. steps0 (1, [Bk],<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left n = (0, Bk \<up> z4, <nl> @ [Bk]))" by blast then show "\<lbrace>\<lambda>tap. tap = ([Bk], <nl::nat list> @ [Bk])\<rbrace> tm_erase_right_then_dblBk_left \<lbrace>\<lambda>tap. \<exists>z4. tap = (Bk \<up> z4, <nl::nat list> @ [Bk])\<rbrace>" using Hoare_halt_def Hoare_unhalt_def holds_for.simps by auto qed then show ?thesis unfolding tm_check_for_one_arg_def by auto qed (* Old version of tm_check_for_one_arg_total_correctness_len_eq_1: * Keep this proof as an example * The proof shows how to add blanks on the initial left tape, if you need some for composition with some predecessor tm *) (* lemma tm_check_for_one_arg_total_correctness_len_eq_1: "length nl = 1 \<Longrightarrow> \<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_check_for_one_arg \<lbrace>\<lambda>tap. \<exists>z4. tap = (Bk \<up> z4, <nl> @ [Bk])\<rbrace>" proof - assume major: "length nl = 1" have " \<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> (tm_skip_first_arg |+| tm_erase_right_then_dblBk_left) \<lbrace>\<lambda>tap. \<exists>z4. tap = (Bk \<up> z4, <nl> @ [Bk])\<rbrace>" proof (rule Hoare_plus_halt) show "composable_tm0 tm_skip_first_arg" by (simp add: composable_tm.simps adjust.simps shift.simps seq_tm.simps tm_skip_first_arg_def tm_erase_right_then_dblBk_left_def) next from major have "\<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_skip_first_arg \<lbrace> \<lambda>tap. tap = ([Bk], <[hd nl]> @[Bk])\<rbrace>" using tm_skip_first_arg_len_eq_1_total_correctness' by simp moreover from major have "(nl::nat list) = [hd nl]" by (metis diff_self_eq_0 length_0_conv length_tl list.exhaust_sel zero_neq_one) ultimately show "\<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_skip_first_arg \<lbrace> \<lambda>tap. tap = ([Bk], <nl> @[Bk])\<rbrace>" using major by auto next from major have "\<lbrace>\<lambda>tap. tap = ([], <nl> @ [Bk])\<rbrace> tm_erase_right_then_dblBk_left \<lbrace>\<lambda>tap. tap = ([Bk, Bk], <nl> @ [Bk])\<rbrace>" using tm_erase_right_then_dblBk_left_dnp_total_correctness by simp (* Add a blank on the initial left tape *) (* Note: since we proved \<lbrace>\<lambda>tap. tap = ([], <nl> @ [Bk])\<rbrace> tm_erase_right_then_dblBk_left \<lbrace>\<lambda>tap. tap = ([Bk, Bk], <nl> @ [Bk])\<rbrace> we need to add a blank on the left tape. This is no problem, since blanks on the left tape do not matter. However, adding blanks also changes the resulting left tape. Instead of \<lbrace>\<lambda>tap. tap = ([Bk, Bk], <nl> @ [Bk])\<rbrace> we end up with \<lbrace>\<lambda>tap. \<exists>z4. tap = (Bk \<up> z4, <nl> @ [Bk])\<rbrace> If we had proved \<lbrace>\<lambda>tap. tap = ([Bk], <nl> @ [Bk])\<rbrace> tm_erase_right_then_dblBk_left \<lbrace>\<lambda>tap. tap = ([Bk, Bk], <nl> @ [Bk])\<rbrace> in the first place, there would be no need for this weakened result. But since trailing blanks on the final left tape do not matter either, this is no real problem. *) with major have "\<exists>stp. is_final (steps0 (1, [],<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp) \<and> (steps0 (1, [],<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp = (0, [Bk, Bk], <nl> @ [Bk]))" unfolding Hoare_halt_def by (smt Hoare_halt_def Pair_inject holds_for.elims(2) is_final.elims(2)) then obtain stp where w_stp: "is_final (steps0 (1, [],<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp) \<and> (steps0 (1, [],<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp = (0, [Bk, Bk], <nl> @ [Bk]))" by blast then have "is_final (steps0 (1, Bk \<up> 0,<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp) \<and> (steps0 (1, Bk \<up> 0,<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp = (0, Bk \<up> 2, <nl> @ [Bk]))" by (simp add: is_finalI numeral_eqs_upto_12(1)) then have "\<exists>z3. z3 \<le> 0 + 1 \<and> is_final (steps0 (1, Bk \<up> (0+1),<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp) \<and> (steps0 (1, Bk \<up> (0+1),<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp = (0, Bk \<up> (2+z3), <nl> @ [Bk]))" by (metis is_finalI steps_left_tape_EnlargeBkCtx) then have "is_final (steps0 (1, [Bk],<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp) \<and> (\<exists>z4. steps0 (1, [Bk],<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left stp = (0, Bk \<up> z4, <nl> @ [Bk]))" by (metis One_nat_def add.left_neutral replicate_0 replicate_Suc) then have "\<exists>n. is_final (steps0 (1, [Bk],<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left n) \<and> (\<exists>z4. steps0 (1, [Bk],<nl::nat list>@ [Bk]) tm_erase_right_then_dblBk_left n = (0, Bk \<up> z4, <nl> @ [Bk]))" by blast then show "\<lbrace>\<lambda>tap. tap = ([Bk], <nl::nat list> @ [Bk])\<rbrace> tm_erase_right_then_dblBk_left \<lbrace>\<lambda>tap. \<exists>z4. tap = (Bk \<up> z4, <nl::nat list> @ [Bk])\<rbrace>" using Hoare_halt_def Hoare_unhalt_def holds_for.simps by auto qed then show ?thesis unfolding tm_check_for_one_arg_def by auto qed *) lemma tm_check_for_one_arg_total_correctness_len_gt_1: "length nl > 1 \<Longrightarrow> \<lbrace>\<lambda>tap. tap = ([], <nl::nat list> )\<rbrace> tm_check_for_one_arg \<lbrace> \<lambda>tap. \<exists> l. tap = ( [], [Bk,Bk] @ <[hd nl]> @ Bk \<up> l) \<rbrace>" proof - assume major: "length nl > 1" have " \<lbrace>\<lambda>tap. tap = ([], <nl::nat list> )\<rbrace> (tm_skip_first_arg |+| tm_erase_right_then_dblBk_left) \<lbrace> \<lambda>tap. \<exists> l. tap = ( [], [Bk,Bk] @ <[hd nl]> @ Bk \<up> l) \<rbrace>" proof (rule Hoare_plus_halt) show "composable_tm0 tm_skip_first_arg" by (simp add: composable_tm.simps adjust.simps shift.simps seq_tm.simps tm_skip_first_arg_def tm_erase_right_then_dblBk_left_def) next from major show "\<lbrace>\<lambda>tap. tap = ([], <nl::nat list> )\<rbrace> tm_skip_first_arg \<lbrace> \<lambda>tap. tap = (Bk# <rev [hd nl]>, <tl nl>) \<rbrace>" using tm_skip_first_arg_len_gt_1_total_correctness by simp next from major have "\<lbrace> \<lambda>tap. tap = (Bk# rev(<hd nl>), <tl nl>) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. \<exists>rex. tap = ([], [Bk,Bk] @ (<hd nl>) @ [Bk] @ Bk \<up> rex ) \<rbrace>" using tm_erase_right_then_dblBk_left_erp_total_correctness_one_arg by simp then have "\<lbrace> \<lambda>tap. tap = (Bk# <rev [hd nl]>, <tl nl>) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. \<exists>rex. tap = ([], [Bk,Bk] @ <[hd nl]> @ [Bk] @ Bk \<up> rex ) \<rbrace>" by (simp add: rev_numeral rev_numeral_list tape_of_list_def ) then have "\<lbrace> \<lambda>tap. tap = (Bk# <rev [hd nl]>, <tl nl>) \<rbrace> tm_erase_right_then_dblBk_left \<lbrace> \<lambda>tap. \<exists>rex. tap = ([], [Bk,Bk] @ <[hd nl]> @ Bk \<up> (Suc rex) ) \<rbrace>" by force then show "\<lbrace>\<lambda>tap. tap = (Bk # <rev [hd nl]>, <tl nl>)\<rbrace> tm_erase_right_then_dblBk_left \<lbrace>\<lambda>tap. \<exists>l. tap = ([], [Bk, Bk] @ <[hd nl]> @ Bk \<up> l)\<rbrace>" by (smt Hoare_haltI Hoare_halt_def holds_for.elims(2) holds_for.simps) qed then show ?thesis unfolding tm_check_for_one_arg_def by auto qed (* ---------- tm_strong_copy ---------- *) definition tm_strong_copy :: "instr list" where "tm_strong_copy \<equiv> tm_check_for_one_arg |+| tm_weak_copy" (* Prove total correctness for COMPOSED machine tm_strong_copy. * This is done via the rules for the composition operator seq_tm. *) lemma tm_strong_copy_total_correctness_Nil: "length nl = 0 \<Longrightarrow> \<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_strong_copy \<lbrace>\<lambda>tap. tap = ([Bk,Bk,Bk,Bk],[]) \<rbrace>" proof - assume major: "length nl = 0" have " \<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_check_for_one_arg |+| tm_weak_copy \<lbrace>\<lambda>tap. tap = ([Bk,Bk,Bk,Bk],[]) \<rbrace>" proof (rule Hoare_plus_halt) show "composable_tm0 tm_check_for_one_arg" by (simp add: composable_tm.simps adjust.simps shift.simps seq_tm.simps tm_weak_copy_def tm_check_for_one_arg_def tm_skip_first_arg_def tm_erase_right_then_dblBk_left_def) next from major show "\<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_check_for_one_arg \<lbrace>\<lambda>tap. tap = ([Bk,Bk], [Bk] ) \<rbrace>" using tm_check_for_one_arg_total_correctness_Nil by simp next from major show "\<lbrace>\<lambda>tap. tap = ([Bk, Bk], [Bk])\<rbrace> tm_weak_copy \<lbrace>\<lambda>tap. tap = ([Bk, Bk, Bk, Bk], [])\<rbrace>" using tm_weak_copy_correct11' by simp qed then show ?thesis unfolding tm_strong_copy_def by auto qed lemma tm_strong_copy_total_correctness_len_gt_1: "1 < length nl \<Longrightarrow> \<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_strong_copy \<lbrace> \<lambda>tap. \<exists>l. tap = ([Bk,Bk], <[hd nl]> @ Bk \<up> l) \<rbrace>" proof - assume major: "1 < length nl" have " \<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_check_for_one_arg |+| tm_weak_copy \<lbrace> \<lambda>tap. \<exists> l. tap = ([Bk,Bk], <[hd nl]> @ Bk \<up> l) \<rbrace>" proof (rule Hoare_plus_halt) show "composable_tm0 tm_check_for_one_arg" by (simp add: composable_tm.simps adjust.simps shift.simps seq_tm.simps tm_weak_copy_def tm_check_for_one_arg_def tm_skip_first_arg_def tm_erase_right_then_dblBk_left_def) next from major show "\<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_check_for_one_arg \<lbrace> \<lambda>tap. \<exists> l. tap = ( [], [Bk,Bk] @ <[hd nl]> @ Bk \<up> l) \<rbrace>" using tm_check_for_one_arg_total_correctness_len_gt_1 by simp next show "\<lbrace>\<lambda>tap. \<exists>l. tap = ([], [Bk, Bk] @ <[hd nl]> @ Bk \<up> l)\<rbrace> tm_weak_copy \<lbrace>\<lambda>tap. \<exists>l. tap = ([Bk, Bk], <[hd nl]> @ Bk \<up> l)\<rbrace>" proof - have "\<And>r.\<lbrace>\<lambda>tap. tap = ([], [Bk,Bk]@r) \<rbrace> tm_weak_copy \<lbrace>\<lambda>tap. tap = ([Bk,Bk], r) \<rbrace>" using tm_weak_copy_correct13' by simp then have "\<And>r. \<exists>stp. is_final (steps0 (1, [],[Bk,Bk]@r) tm_weak_copy stp) \<and> (steps0 (1, [],[Bk,Bk]@r) tm_weak_copy stp = (0, [Bk, Bk], r))" unfolding Hoare_halt_def by (smt Hoare_halt_def Pair_inject holds_for.elims(2) is_final.elims(2)) then have "\<And>l. \<exists>stp. is_final (steps0 (1, [],[Bk,Bk]@<[hd nl]> @ Bk \<up> l) tm_weak_copy stp) \<and> (steps0 (1, [],[Bk,Bk]@<[hd nl]> @ Bk \<up> l) tm_weak_copy stp = (0, [Bk, Bk], <[hd nl]> @ Bk \<up> l))" by blast then show ?thesis using Hoare_halt_def holds_for.simps by fastforce qed qed then show ?thesis unfolding tm_strong_copy_def by auto qed lemma tm_strong_copy_total_correctness_len_eq_1: "1 = length nl \<Longrightarrow> \<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_strong_copy \<lbrace> \<lambda>tap. \<exists>k l. tap = (Bk \<up> k, <[hd nl, hd nl]> @ Bk \<up> l) \<rbrace>" proof - assume major: "1 = length nl" have " \<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_check_for_one_arg |+| tm_weak_copy \<lbrace> \<lambda>tap. \<exists>k l. tap = (Bk \<up> k, <[hd nl, hd nl]> @ Bk \<up> l) \<rbrace>" proof (rule Hoare_plus_halt) show "composable_tm0 tm_check_for_one_arg" by (simp add: composable_tm.simps adjust.simps shift.simps seq_tm.simps tm_weak_copy_def tm_check_for_one_arg_def tm_skip_first_arg_def tm_erase_right_then_dblBk_left_def) next from major show "\<lbrace>\<lambda>tap. tap = ([], <nl::nat list>) \<rbrace> tm_check_for_one_arg \<lbrace>\<lambda>tap. \<exists>z4. tap = (Bk \<up> z4, <nl> @ [Bk])\<rbrace>" using tm_check_for_one_arg_total_correctness_len_eq_1 by simp next have "\<lbrace>\<lambda>tap. \<exists>z4. tap = (Bk \<up> z4, <[hd nl]> @[Bk])\<rbrace> tm_weak_copy \<lbrace>\<lambda>tap. \<exists>k l. tap = (Bk \<up> k, <[hd nl, hd nl]> @ Bk \<up> l) \<rbrace>" using tm_weak_copy_correct6 by simp moreover from major have "<nl> = <[hd nl]>" by (metis diff_self_eq_0 length_0_conv length_tl list.exhaust_sel zero_neq_one) ultimately show "\<lbrace>\<lambda>tap. \<exists>z4. tap = (Bk \<up> z4, <nl> @ [Bk])\<rbrace> tm_weak_copy \<lbrace>\<lambda>tap. \<exists>k l. tap = (Bk \<up> k, <[hd nl, hd nl]> @ Bk \<up> l)\<rbrace>" by auto qed then show ?thesis unfolding tm_strong_copy_def by auto qed end
------------------------------------------------------------------------ -- Some results that could not be placed in Function-universe because -- they make use of --sized-types ------------------------------------------------------------------------ {-# OPTIONS --without-K --sized-types #-} open import Equality module Function-universe.Size {reflexive} (eq : ∀ {a p} → Equality-with-J a p reflexive) where open Derived-definitions-and-properties eq open import Prelude open import Prelude.Size import Bijection eq as B open import Equivalence eq as Eq using (_≃_) open import Function-universe eq private variable S : Size-universe p q : Level P : S → Type p k : Kind -- Π-types with something from the size universe in the domain can be -- expressed using something from Type in the domain. Π-size-≃ : ((i : S) → P i) ≃ ((i : S in-type) → P (size i)) Π-size-≃ = Eq.↔→≃ (λ p i → p (size i)) (λ p i → p (record { size = i })) refl refl -- Implicit Π-types with something from the size universe in the -- domain can be expressed using something from Type in the domain. implicit-Π-size-≃ : ({i : S} → P i) ≃ ({i : S in-type} → P (size i)) implicit-Π-size-≃ = Eq.↔→≃ (λ p {i} → p {size i}) (λ p {i} → p {record { size = i }}) refl refl -- Implicit Π-types with something from the size universe in the -- domain are equivalent to explicit Π-types. implicit-Π-size-≃-Π-size : ({i : S} → P i) ≃ ((i : S) → P i) implicit-Π-size-≃-Π-size {P = P} = (∀ {i} → P i) ↔⟨ implicit-Π-size-≃ ⟩ (∀ {i} → P (size i)) ↔⟨ B.implicit-Π↔Π ⟩ (∀ i → P (size i)) ↔⟨ inverse Π-size-≃ ⟩□ (∀ i → P i) □ -- A preservation lemma for Π-types with something from the size -- universe in the domain. ∀-size-cong : {P : S → Type p} {Q : S → Type q} → Extensionality? k lzero (p ⊔ q) → (∀ i → P i ↝[ k ] Q i) → (∀ i → P i) ↝[ k ] (∀ i → Q i) ∀-size-cong {P = P} {Q = Q} ext P↝Q = (∀ i → P i) ↔⟨ Π-size-≃ ⟩ (∀ i → P (size i)) ↝⟨ ∀-cong ext (λ i → P↝Q (size i)) ⟩ (∀ i → Q (size i)) ↔⟨ inverse Π-size-≃ ⟩□ (∀ i → Q i) □ -- A preservation lemma for implicit Π-types with something from the -- size universe in the domain. implicit-∀-size-cong : {P : S → Type p} {Q : S → Type q} → Extensionality? k lzero (p ⊔ q) → (∀ {i} → P (size i) ↝[ k ] Q (size i)) → (∀ {i} → P i) ↝[ k ] (∀ {i} → Q i) implicit-∀-size-cong {P = P} {Q = Q} ext P↝Q = (∀ {i} → P i) ↔⟨ implicit-Π-size-≃ ⟩ (∀ {i} → P (size i)) ↝⟨ implicit-∀-cong ext P↝Q ⟩ (∀ {i} → Q (size i)) ↔⟨ inverse implicit-Π-size-≃ ⟩□ (∀ {i} → Q i) □
(** Definitions of Algorithmic Lightweight Linear F Authors: Aileen Zhang, Jianzhou Zhao, and Steve Zdancewic. *) Require Export LinF_Definitions. Require Export LinF_Infrastructure. Require Export ALinearF_Dmap. (* ********************************************************************** *) (** * #<a name="env"></a># Algo Environments *) (** In our presentation of System F with subtyping, we use a single environment for both typing and subtyping assumptions. We formalize environments by representing them as association lists (lists of pairs of keys and values) whose keys are atoms. The [Metatheory] and [Environment] libraries provide functions, predicates, tactics, notations and lemmas that simplify working with environments. The [Environment] library treats environments as lists of type [list (atom * A)]. Since environments map [atom]s, the type [A] should encode whether a particular binding is a typing or subtyping assumption. Thus, we instantiate [A] with the type [binding], defined below. *) Inductive gbinding : Set := | gbind_kn : kn -> gbinding | gbind_typ : typ -> gbinding. Notation genv := (list (atom * gbinding)). Notation gempty := (@nil (atom * gbinding)). Notation denv := (list (atom * typ)). Notation dempty := (@nil (atom * typ)). Fixpoint denv_to_emap (D : denv) {struct D} : dmap := match D with | nil => EMap.empty typ | (x, t)::D' => EMap.add x t (denv_to_emap D') end. Definition dmap_to_denv (M : dmap) : denv := EMap.elements M. Notation "<# D #>" := (denv_to_emap D). Notation "<@ M @>" := (dmap_to_denv M). Definition denv_Equal (D1 D2: denv) := <#D1#> ~~ <#D2#>. Notation "D ~~~ D'" := (denv_Equal D D') (at level 70, right associativity). (* ********************************************************************** *) (** * #<a name="wf"></a># Well-formedness *) (** A type [T] is well-formed with respect to an environment [E], denoted [(wf_typ E T)], when [T] is locally-closed and its free variables are bound in [E]. We need this relation in order to restrict the subtyping and typing relations, defined below, to contain only well-formed types. (This relation is missing in the original statement of the POPLmark Challenge.) Note: It is tempting to define the premise of [wf_typ_var] as [(X `in` dom E)], since that makes the rule easier to apply (no need to guess an instantiation for [U]). Unfortunately, this is incorrect. We need to check that [X] is bound as a type-variable, not an expression-variable; [(dom E)] does not distinguish between the two kinds of bindings. *) Inductive kn_order : kn -> kn -> Prop := | kn_order_base : kn_order kn_nonlin kn_lin | kn_order_refl : forall K, kn_order K K . Inductive wf_atyp : genv -> typ -> kn -> Prop := | wf_atyp_var : forall K K' G (X : atom), uniq G -> binds X (gbind_kn K') G -> kn_order K' K -> wf_atyp G (typ_fvar X) K | wf_atyp_arrow : forall G K1 K2 K K' T1 T2, wf_atyp G T1 K1 -> wf_atyp G T2 K2 -> kn_order K' K -> wf_atyp G (typ_arrow K' T1 T2) K | wf_atyp_all : forall L G K1 K2 T2, (forall X : atom, X `notin` L -> wf_atyp ([(X, gbind_kn K1)] ++ G) (open_tt T2 X) K2) -> wf_atyp G (typ_all K1 T2) K2 . (** An environment E is well-formed, denoted [(wf_env E)], if each atom is bound at most at once and if each binding is to a well-formed type. This is a stronger relation than the [ok] relation defined in the [Environment] library. We need this relation in order to restrict the subtyping and typing relations, defined below, to contain only well-formed environments. (This relation is missing in the original statement of the POPLmark Challenge.) *) Inductive wf_genv : genv -> Prop := | wf_genv_empty : wf_genv gempty | wf_genv_kn : forall (G : genv) (X : atom) (K : kn), wf_genv G -> X `notin` dom G -> wf_genv ([(X, gbind_kn K)] ++ G) | wf_genv_typ : forall (G : genv) (x : atom) (T : typ) , wf_genv G -> wf_atyp G T kn_nonlin -> x `notin` dom G -> wf_genv ([(x, gbind_typ T)] ++ G) . Inductive wf_denv : genv -> denv -> Prop := | wf_denv_empty : forall G, wf_genv G -> wf_denv G dempty | wf_denv_typ : forall G D T x D' K, wf_denv G D -> wf_atyp G T K -> x `notin` dom G -> x `notin` dom D -> (* <#_#> does not check if the input is uniq, so ...*) uniq D' -> (<# [(x, T)] ++ D #>) ~~ <# D' #> -> wf_denv G D' . (* ********************************************************************** *) (** * #<a name="typing_doc"></a># Algo Typing *) Inductive atyping : genv -> denv -> exp -> typ -> denv -> Prop := | atyping_uvar : forall G D x T, binds x (gbind_typ T) G -> wf_denv G D -> atyping G D x T D | atyping_lvar : forall G D D' (x:atom) T, binds x T D -> wf_denv G D -> (* <#_#> does not check if the input is uniq, so ...*) uniq D' -> (<#D#> [-] x) ~~ <#D'#> -> atyping G D x T D' | atyping_uabs : forall L K G D V e1 T1 D', wf_atyp G V kn_nonlin -> (forall x : atom, x `notin` L -> atyping ([(x, gbind_typ V)] ++ G) D (open_ee e1 x) T1 D') -> (K = kn_nonlin -> D ~~~ D') -> atyping G D (exp_abs K V e1) (typ_arrow K V T1) D' | atyping_labs : forall L K Q G D V e1 T1 D', wf_atyp G V Q -> (forall x : atom, x `notin` L -> atyping G ([(x, V)] ++ D) (open_ee e1 x) T1 D') -> (K = kn_nonlin -> D ~~~ D') -> atyping G D (exp_abs K V e1) (typ_arrow K V T1) D' | atyping_app : forall G T1 K D1 D2 D3 e1 e2 T2, atyping G D1 e1 (typ_arrow K T1 T2) D2-> atyping G D2 e2 T1 D3 -> atyping G D1 (exp_app e1 e2) T2 D3 | atyping_tabs : forall L G K e1 T1 D D' , (forall X : atom, X `notin` L -> value (open_te e1 X)) -> (forall X : atom, X `notin` L -> atyping ([(X,gbind_kn K)] ++ G) D (open_te e1 X) (open_tt T1 X) D')-> atyping G D (exp_tabs K e1) (typ_all K T1) D' | atyping_tapp : forall K K' G e1 T T2 D D', atyping G D e1 (typ_all K T2) D' -> wf_atyp G T K' -> kn_order K' K -> atyping G D (exp_tapp e1 T) (open_tt T2 T) D' . (* ********************************************************************** *) (** * #<a name="auto"></a># Automation *) (** We declare most constructors as [Hint]s to be used by the [auto] and [eauto] tactics. We exclude constructors from the subtyping and typing relations that use cofinite quantification. It is unlikely that [eauto] will find an instantiation for the finite set [L], and in those cases, [eauto] can take some time to fail. (A priori, this is not obvious. In practice, one adds as hints all constructors and then later removes some constructors when they cause proof search to take too long.) *) Hint Constructors wf_atyp wf_genv wf_denv uniq kn_order. Hint Resolve atyping_uvar atyping_lvar atyping_app atyping_tapp. (* ********************************************************************** *) (** * #<a name="cases"></a># Cases Tactic *) Tactic Notation "wf_atyp_cases" tactic(first) tactic(c) := first; [ c "wf_atyp_var" | c "wf_atyp_arrow" | c "wf_atyp_all" ]. Tactic Notation "wf_genv_cases" tactic(first) tactic(c) := first; [ c "wf_genv_empty" | c "wf_genv_kn" | c "wf_genv_typ" ]. Tactic Notation "wf_denv_cases" tactic(first) tactic(c) := first; [ c "wf_denv_empty" | c "wf_denv_typ" ]. Tactic Notation "atyping_cases" tactic(first) tactic(c) := first; [ c "atyping_uvar" | c "atyping_lvar" | c "atyping_uabs" | c "atyping_labs" | c "atyping_app" | c "atyping_tabs" | c "atyping_tapp" ]. (* *** Local Variables: *** *** coq-prog-name: "coqtop" *** *** coq-prog-args: ("-emacs-U" "-I" "../../../metatheory" "-I" "../linf") *** *** End: *** *)
Require Import Software.Language.Record. Require Import Software.Lib.Lists.List. Require Import Software.Language.RefPassStack. Require Import Software.Language.Syntax. Require Import Software.Language.Stack. Require Import Software.Language.Store. (** * Types *) Inductive state : Type := | Cstate: stack -> ref_pass_stack -> store -> state. Inductive exec_state : Type := | Cexec_state : term -> state -> exec_state. (** * Functions *) (** ** State accessors *) Definition get_stack (st : state) : stack := match st with | Cstate sk _ _ => sk end. Definition get_ref_pass_stack (st : state) : ref_pass_stack := match st with | Cstate _ rpsk _ => rpsk end. Definition get_store (st : state) : store := match st with | Cstate _ _ sr => sr end. Definition set_stack (sk : stack) (st : state) : state := match st with | Cstate _ rpsk sr => Cstate sk rpsk sr end. Definition set_ref_pass_stack (rpsk : ref_pass_stack) (st : state) : state := match st with | Cstate sk _ sr => Cstate sk rpsk sr end. Definition set_store (sr : store) (st : state) : state := match st with | Cstate sk rpsk _ => Cstate sk rpsk sr end. (** ** Function call *) Section FunctionCalls. Fixpoint args_to_ref_pass_stack_frame (args : list term) : ref_pass_stack_frame := match args with | nil => nil | cons t args' => match t with | trefpass t' => match t' with | tvar n => cons (Some n) (args_to_ref_pass_stack_frame args') | _ => cons None (args_to_ref_pass_stack_frame args') end | _ => cons None (args_to_ref_pass_stack_frame args') end end. Fixpoint args_to_stack_frame (args : list term) (context : stack_frame) : stack_frame := match args with | nil => nil | cons t args' => match t with | trefpass t' => match t' with | tvar n => cons (nth n context tvoid) (args_to_stack_frame args' context) | _ => cons t (args_to_stack_frame args' context) end | _ => cons t (args_to_stack_frame args' context) end end. Fixpoint return_refpass_args (rpsf : ref_pass_stack_frame) (source target : stack_frame) : stack_frame := match rpsf with | nil => target | cons c rpsf' => match c with | None => return_refpass_args rpsf' (tl source) target | Some n => return_refpass_args rpsf' (tl source) (replace n (hd tvoid source) target) end end. Definition push_call (args : term) (st : state) : state := let sk := get_stack st in let rpsk := get_ref_pass_stack st in let sk' := push (args_to_stack_frame (rc_to_list args) (hd nil sk)) sk in let rpsk' := RefPassStack.push (args_to_ref_pass_stack_frame (rc_to_list args)) rpsk in set_ref_pass_stack rpsk' (set_stack sk' st). Definition pop_call (st : state) : state := let sk := get_stack st in let rpsk := get_ref_pass_stack st in let sk' := push (return_refpass_args (hd nil rpsk) (hd nil sk) (nth 1 sk nil)) (pop (pop sk)) in set_ref_pass_stack (RefPassStack.pop rpsk) (set_stack sk' st). Hint Resolve Lt.lt_S_n List.nth_indep. Lemma args_to_ref_pass_stack_frame_length: forall args, length (args_to_ref_pass_stack_frame args) = length args. Proof with auto. induction args... destruct a; simpl... destruct a; simpl... Qed. Lemma args_to_ref_pass_stack_frame_correct_1: forall args m d1 d2, lt m (length args) -> (forall n, nth m args d1 <> trefpass (tvar n)) -> nth m (args_to_ref_pass_stack_frame args) d2 = None. Proof with auto. induction args; try solve [intros; inversion H]. destruct m; simpl; intros d1 d2 Hlen Hstruct. destruct a; simpl... destruct a; simpl... exfalso. apply (Hstruct n)... destruct a; try solve [simpl; apply IHargs with d1; auto]. destruct a; try solve [simpl; apply IHargs with d1; auto]. Qed. Lemma args_to_ref_pass_stack_frame_correct_2: forall args m n d1 d2, lt m (length args) -> nth m args d1 = trefpass (tvar n) -> nth m (args_to_ref_pass_stack_frame args) d2 = Some n. Proof with auto. induction args; try solve [intros; inversion H]. destruct m; simpl; intros n d1 d2 Hlen Hstruct. destruct a; try solve [inversion Hstruct]. destruct a; try solve [inversion Hstruct]. inversion Hstruct; subst... destruct a; try solve [simpl; apply IHargs with d1; auto]. destruct a; try solve [simpl; apply IHargs with d1; auto]. Qed. Lemma args_to_stack_frame_length: forall args context, length (args_to_stack_frame args context) = length args. Proof with auto. induction args... destruct a; simpl... destruct a; simpl... Qed. Lemma args_to_stack_frame_correct_1: forall args m context d1 d2 d3, lt m (length args) -> (forall n, nth m args d1 <> trefpass (tvar n)) -> nth m (args_to_stack_frame args context) d2 = nth m args d3. Proof with auto. induction args; try solve [intros; inversion H]. destruct m; simpl; intros context d1 d2 d3 Hlen Hstruct. destruct a; simpl... destruct a; simpl... exfalso. apply (Hstruct n)... destruct a; try solve [simpl; apply IHargs with d1; auto]. destruct a; try solve [simpl; apply IHargs with d1; auto]. Qed. Lemma args_to_stack_frame_correct_2: forall args m n context d1 d2, lt m (length args) -> nth m args d1 = trefpass (tvar n) -> nth m (args_to_stack_frame args context) d2 = nth n context tvoid. Proof with auto. induction args; try solve [intros; inversion H]. destruct m; simpl; intros n context d1 d2 Hlen Hstruct. destruct a; try solve [inversion Hstruct]. destruct a; try solve [inversion Hstruct]. inversion Hstruct; simpl... destruct a; try solve [simpl; apply IHargs with d1; auto]. destruct a; try solve [simpl; apply IHargs with d1; auto]. Qed. Lemma return_refpass_args_length: forall rpsf target source, length (return_refpass_args rpsf source target) = length target. Proof with auto using replace_length. induction rpsf... destruct target. destruct a; intros; simpl return_refpass_args... destruct a; try solve [intros; simpl; rewrite IHrpsf; auto]. destruct n; intros; simpl; rewrite IHrpsf; simpl... Qed. Lemma return_refpass_args_correct_1: forall rpsf target n source d1 d2 d3, (forall m, lt m (length rpsf) -> nth m rpsf d1 <> Some n) -> lt n (length target) -> nth n (return_refpass_args rpsf source target) d2 = nth n target d3. Proof with auto. induction rpsf. simpl... (* rpsf <> nil *) destruct target. intros. inversion H0. (* target <> nil *) destruct a. (* rpsf = Some n0 :: rpsf' *) intros n0. destruct (EqNat.beq_nat n0 n) eqn:Hnvals. (* n0 = n *) apply EqNat.beq_nat_true_iff in Hnvals. subst. intros. exfalso. apply (H 0). simpl. apply Lt.lt_0_Sn. reflexivity. (* n0 <> n*) apply EqNat.beq_nat_false_iff in Hnvals. destruct n; destruct n0. (* n0 = 0 /\ n = 0 *) exfalso. apply Hnvals. reflexivity. (* n0 = S n0' /\ n = 0 *) intros. simpl return_refpass_args. rewrite IHrpsf with (d1 := d1) (d3 := d3). reflexivity. intros. apply (H (S m)). simpl. apply Lt.lt_n_S. assumption. simpl. assumption. (* n0 = 0 /\ n = S n' *) intros. simpl return_refpass_args. rewrite IHrpsf with (d1 := d1) (d3 := d3). reflexivity. intros. apply (H (S m)). simpl. apply Lt.lt_n_S. assumption. simpl. rewrite replace_length. assumption. (* n0 = S n0' /\ n = S n' *) intros. simpl return_refpass_args. rewrite IHrpsf with (d1 := d1) (d3 := d3). simpl. rewrite replace_correct_1 with (d2 := d3). reflexivity. apply Lt.lt_S_n. assumption. apply not_eq_n. assumption. intros. apply (H (S m)). simpl. apply Lt.lt_n_S. assumption. simpl. rewrite replace_length. assumption. (* rpsf = None :: rpsf' *) intros. simpl return_refpass_args. rewrite IHrpsf with (d1 := d1) (d3 := d3). reflexivity. intros. apply (H (S m)). simpl. apply Lt.lt_n_S. assumption. simpl. assumption. Qed. Definition refpass_unique (rpsf : ref_pass_stack_frame) : Prop := forall m m' n d1 d2, lt m (length rpsf) -> nth m rpsf d1 = Some n -> lt m' (length rpsf) -> nth m' rpsf d2 = Some n -> m' = m. Lemma refpass_unique_nil: refpass_unique nil. Proof with auto. unfold refpass_unique. intros. inversion H. Qed. Lemma refpass_unique_cons: forall rpsf a, refpass_unique (cons a rpsf) -> refpass_unique rpsf. Proof with auto. induction rpsf. intros. apply refpass_unique_nil. unfold refpass_unique. intros. apply (H (S m) (S m') n d1 d2) in H3. inversion H3. reflexivity. simpl. apply Lt.lt_n_S. assumption. simpl. destruct m; assumption. simpl. apply Lt.lt_n_S. assumption. Qed. Lemma return_refpass_args_correct_2: forall source rpsf target n m d1 d2, refpass_unique rpsf -> lt m (length rpsf) -> nth m rpsf d1 = Some n -> lt n (length target) -> nth n (return_refpass_args rpsf source target) d2 = nth m source tvoid. Proof with auto. induction source. (* source = nil *) induction rpsf. intros. inversion H0. (* rpsf <> nil *) destruct target. intros. inversion H2. (* target <> nil *) destruct a. (* rpsf = Some n0 :: rpsf' *) intros n0. destruct (EqNat.beq_nat n0 n) eqn:Hnvals. (* n0 = n *) apply EqNat.beq_nat_true_iff in Hnvals. subst. intros. assert (m = 0) as H3. { unfold refpass_unique in H. apply (H 0 m n d1 d1). simpl. apply Lt.lt_0_Sn. reflexivity. assumption. assumption. } subst. destruct n. (* n = 0 *) simpl return_refpass_args. rewrite return_refpass_args_correct_1 with (d1 := d1) (d3 := d2). reflexivity. intros m H3 H4. unfold refpass_unique in H. simpl length in H, H0. apply (H 0 (S m) 0 d1 d1) in H4; try solve [assumption]. inversion H4. apply Lt.lt_n_S. assumption. simpl. apply Lt.lt_0_Sn. (* n = S n' *) simpl return_refpass_args. rewrite return_refpass_args_correct_1 with (d1 := d1) (d3 := d2). simpl. rewrite replace_correct_2. reflexivity. apply Lt.lt_S_n. assumption. intros m H3 H4. unfold refpass_unique in H. simpl length in H, H0. apply (H 0 (S m) (S n) d1 d1) in H4; try solve [assumption]. inversion H4. apply Lt.lt_n_S. assumption. simpl. rewrite replace_length. assumption. (* n0 <> n *) apply EqNat.beq_nat_false_iff in Hnvals. destruct n0; destruct n. (* n0 = 0 /\ n = 0 *) exfalso. apply Hnvals. reflexivity. (* n0 = 0 /\ n = S n *) destruct m. (* m = 0 *) intros. inversion H1. (* m = S m' *) intros. simpl return_refpass_args. rewrite IHrpsf with (m := m) (d1 := d1). destruct m; reflexivity. apply refpass_unique_cons in H. assumption. simpl in H0. apply Lt.lt_S_n. assumption. assumption. simpl. rewrite replace_length. assumption. (* n0 = S n0' /\ n = 0 *) destruct m. (* m = 0 *) intros. inversion H1. (* m = S m' *) intros. simpl return_refpass_args. rewrite IHrpsf with (m := m) (d1 := d1). destruct m; reflexivity. apply refpass_unique_cons in H. assumption. simpl in H0. apply Lt.lt_S_n. assumption. assumption. assumption. (* n0 = S n0' /\ n = S n' *) destruct m. (* m = 0 *) intros. inversion H1; subst. exfalso. apply Hnvals. reflexivity. (* m = S m' *) intros. simpl return_refpass_args. rewrite IHrpsf with (m := m) (d1 := d1). destruct m; reflexivity. apply refpass_unique_cons in H. assumption. simpl in H0. apply Lt.lt_S_n. assumption. assumption. simpl. rewrite replace_length. assumption. (* rpsf = None :: rpsf' *) destruct m. (* m = 0 *) intros. inversion H1. (* m = S m' *) intros. simpl return_refpass_args. rewrite IHrpsf with (m := m) (d1 := d1). destruct m; reflexivity. apply refpass_unique_cons in H. assumption. simpl in H0. apply Lt.lt_S_n. assumption. assumption. simpl. assumption. (* source <> nil *) destruct rpsf. intros. inversion H0. (* rpsf <> nil *) destruct target. intros. inversion H2. (* target <> nil *) destruct o. (* rpsf = Some n0 :: rpsf' *) intros n0. destruct (EqNat.beq_nat n0 n) eqn:Hnvals. (* n0 = n *) apply EqNat.beq_nat_true_iff in Hnvals. subst. intros. assert (m = 0) as H3. { unfold refpass_unique in H. apply (H 0 m n d1 d1). simpl. apply Lt.lt_0_Sn. reflexivity. assumption. assumption. } subst. destruct n. (* n = 0 *) simpl return_refpass_args. rewrite return_refpass_args_correct_1 with (d1 := d1) (d3 := d2). reflexivity. intros m H3 H4. unfold refpass_unique in H. simpl length in H, H0. apply (H 0 (S m) 0 d1 d1) in H4; try solve [assumption]. inversion H4. apply Lt.lt_n_S. assumption. simpl. apply Lt.lt_0_Sn. (* n = S n' *) simpl return_refpass_args. rewrite return_refpass_args_correct_1 with (d1 := d1) (d3 := d2). simpl. rewrite replace_correct_2. reflexivity. apply Lt.lt_S_n. assumption. intros m H3 H4. unfold refpass_unique in H. simpl length in H, H0. apply (H 0 (S m) (S n) d1 d1) in H4; try solve [assumption]. inversion H4. apply Lt.lt_n_S. assumption. simpl. rewrite replace_length. assumption. (* n0 <> n *) apply EqNat.beq_nat_false_iff in Hnvals. destruct n0; destruct n. (* n0 = 0 /\ n = 0 *) exfalso. apply Hnvals. reflexivity. (* n0 = 0 /\ n = S n *) destruct m. (* m = 0 *) intros. inversion H1. (* m = S m' *) intros. simpl. rewrite IHsource with (m := m) (d1 := d1). reflexivity. apply refpass_unique_cons in H. assumption. simpl in H0. apply Lt.lt_S_n. assumption. assumption. simpl. rewrite replace_length. assumption. (* n0 = S n0' /\ n = 0 *) destruct m. (* m = 0 *) intros. inversion H1. (* m = S m' *) intros. simpl. rewrite IHsource with (m := m) (d1 := d1). destruct m; reflexivity. apply refpass_unique_cons in H. assumption. simpl in H0. apply Lt.lt_S_n. assumption. assumption. assumption. (* n0 = S n0' /\ n = S n' *) destruct m. (* m = 0 *) intros. inversion H1; subst. exfalso. apply Hnvals. reflexivity. (* m = S m' *) intros. simpl. rewrite IHsource with (m := m) (d1 := d1). destruct m; reflexivity. apply refpass_unique_cons in H. assumption. simpl in H0. apply Lt.lt_S_n. assumption. assumption. simpl. rewrite replace_length. assumption. (* rpsf = None :: rpsf' *) destruct m. (* m = 0 *) intros. inversion H1. (* m = S m' *) intros. simpl. rewrite IHsource with (m := m) (d1 := d1). destruct m; reflexivity. apply refpass_unique_cons in H. assumption. simpl in H0. apply Lt.lt_S_n. assumption. assumption. simpl. assumption. Qed. Lemma push_call_length: forall st args, length (get_ref_pass_stack (push_call args st)) = S (length (get_ref_pass_stack st)) /\ length (get_stack (push_call args st)) = S (length (get_stack st)). Proof. induction st. intros. simpl. split; reflexivity. Qed. (** Tail of [ref_pass_stack] is unchanged. *) Lemma push_call_correct_1: forall st m args d1 d2, lt m (length (get_ref_pass_stack st)) -> nth (S m) (get_ref_pass_stack (push_call args st)) d1 = nth m (get_ref_pass_stack st) d2. Proof. induction st. intros m term d1 d2. simpl. intros. apply nth_indep. assumption. Qed. (** Tail of [stack] is unchanged. *) Lemma push_call_correct_2: forall st m args d1 d2, lt m (length (get_stack st)) -> nth (S m) (get_stack (push_call args st)) d1 = nth m (get_stack st) d2. Proof. induction st. intros m term d1 d2. simpl. intros. apply nth_indep. assumption. Qed. (** Head of [ref_pass_stack] is changed. *) Lemma push_call_correct_3: forall st args d, hd d (get_ref_pass_stack (push_call args st)) = args_to_ref_pass_stack_frame (rc_to_list args). Proof. induction st. reflexivity. Qed. (** Head of [stack] is changed. *) Lemma push_call_correct_4: forall st args d, hd d (get_stack (push_call args st)) = args_to_stack_frame (rc_to_list args) (hd nil (get_stack st)). Proof. induction st. reflexivity. Qed. (** [store] is unchanged. *) Lemma push_call_correct_5: forall st args, get_store (push_call args st) = get_store st. Proof. induction st. intros. reflexivity. Qed. Lemma pop_call_length_1: forall st n, length (get_ref_pass_stack st) = S n -> length (get_ref_pass_stack (pop_call st)) = n. Proof. induction st. intros n. simpl. destruct r. intros. inversion H. simpl. intros. injection H. intros. assumption. Qed. Lemma pop_call_length_2: forall st n, length (get_stack st) = S (S n) -> length (get_stack (pop_call st)) = S n. Proof. induction st. intros n. simpl. destruct s. simpl. intros. discriminate H. destruct s1. simpl. intros. discriminate H. simpl. intros. injection H. intros. rewrite H0. reflexivity. Qed. (** Tail of [ref_pass_stack] is unchanged. *) Lemma pop_call_correct_1: forall st m d1 d2, lt (S m) (length (get_ref_pass_stack st)) -> nth m (get_ref_pass_stack (pop_call st)) d1 = nth (S m) (get_ref_pass_stack st) d2. Proof. induction st. intros m d1 d2. simpl. destruct r. intros. inversion H. simpl. intros. apply nth_indep. apply Lt.lt_S_n. assumption. Qed. (** Tail of [stack] is unchanged. *) Lemma pop_call_correct_2: forall st m d1 d2, lt (S (S m)) (length (get_stack st)) -> nth (S m) (get_stack (pop_call st)) d1 = nth (S (S m)) (get_stack st) d2. Proof. induction st. intros m d1 d2. simpl. destruct s. intros. inversion H. destruct s1. intros. simpl in H. apply Lt.lt_S_n in H. inversion H. simpl. intros. apply nth_indep. do 2 apply Lt.lt_S_n. assumption. Qed. (** Head of [stack] is changed. *) Lemma pop_call_correct_3: forall st d, hd d (get_stack (pop_call st)) = return_refpass_args (hd nil (get_ref_pass_stack st)) (hd nil (get_stack st)) (nth 1 (get_stack st) nil). Proof. induction st. reflexivity. Qed. (** [store] is unchanged. *) Lemma pop_call_correct_4: forall st, get_store (pop_call st) = get_store st. Proof. induction st. reflexivity. Qed. End FunctionCalls. (** ** Stack functions *) Definition write_sk_hd (n : nat) (a : term) (st : state) : state := set_stack (write_hd n a (get_stack st)) st. Definition read_sk_hd (n : nat) (st : state) : term := read_hd n (get_stack st). Definition resize_sk_hd (n : nat) (st : state) : state := set_stack (resize_hd n (get_stack st)) st. (** ** Store functions *) Definition alloc_sr (a : term) (st : state) : state := set_store (alloc a (get_store st)) st. Definition write_sr (n : nat) (t : term) (st : state) : state := set_store (write n t (get_store st)) st. Definition read_sr (n : nat) (st : state) : term := read n (get_store st). (** ** Function unfolding [Arguments] statement with [/] tells tactic [simpl] to unfold these functions when arguments before the [/] are provided [[1]]. [[1]] #<a href="https://coq.inria.fr/distrib/8.4pl4/refman/Reference-Manual010.html##sec395"> https://coq.inria.fr/distrib/8.4pl4/refman/Reference-Manual010.html##sec395</a># *) Arguments get_stack st /. Arguments get_ref_pass_stack st /. Arguments get_store st /. Arguments set_stack sk st /. Arguments set_ref_pass_stack rpsk st /. Arguments set_store sr st /. Arguments args_to_ref_pass_stack_frame args /. Arguments args_to_stack_frame args context /. Arguments return_refpass_args rpsf source target /. Arguments push_call args st /. Arguments pop_call st /. Arguments write_sk_hd n a st /. Arguments read_sk_hd n st /. Arguments resize_sk_hd n st /. Arguments alloc_sr a st /. Arguments write_sr n t st /. Arguments read_sr n st /. (** * Constants *) Definition init_state : state := Cstate init_stack init_ref_pass_stack init_store. (** * Notations *) Module StateNotations. Notation "'\stack' sk '\ref_pass_stack' rpsk '\store' sr" := (Cstate sk rpsk sr) (at level 80, format "'[' '[v ' \stack '/' '[' sk ']' ']' '//' '[v ' \ref_pass_stack '/' '[' rpsk ']' ']' '//' '[v ' \store '/' '[' sr ']' ']' ']'") : state_scope. End StateNotations.
[STATEMENT] lemma showsp_prod_simps [simp, code]: "showsp_prod s1 s2 p (x, y) = shows_string ''('' o s1 1 x o shows_string '', '' o s2 1 y o shows_string '')''" [PROOF STATE] proof (prove) goal (1 subgoal): 1. showsp_prod s1 s2 p (x, y) = shows_string ''('' \<circ> s1 1 x \<circ> shows_string '', '' \<circ> s2 1 y \<circ> shows_string '')'' [PROOF STEP] by (simp add: showsp_prod_def)
theory CoCallAnalysisBinds imports CoCallAnalysisSig AEnv "AList-Utils-HOLCF" "Arity-Nominal" "CoCallGraph-Nominal" begin context CoCallAnalysis begin definition ccBind :: "var \<Rightarrow> exp \<Rightarrow> ((AEnv \<times> CoCalls) \<rightarrow> CoCalls)" where "ccBind v e = (\<Lambda> (ae, G). if (v--v\<notin>G) \<or> \<not> isVal e then cc_restr (fv e) (fup\<cdot>(ccExp e)\<cdot>(ae v)) else ccSquare (fv e))" (* paper has: \<or> ae v = up\<cdot>0, but that is not monotone! But should give the same result. *) lemma ccBind_eq: "ccBind v e\<cdot>(ae, G) = (if v--v\<notin>G \<or> \<not> isVal e then \<G>\<^sup>\<bottom>\<^bsub>ae v\<^esub> e G|` fv e else (fv e)²)" unfolding ccBind_def apply (rule cfun_beta_Pair) apply (rule cont_if_else_above) apply simp apply simp apply (auto dest: set_mp[OF ccField_cc_restr])[1] (* Abstraction broken! Fix this. *) apply (case_tac p, auto, transfer, auto)[1] apply (rule adm_subst[OF cont_snd]) apply (rule admI, thin_tac "chain _", transfer, auto) done lemma ccBind_strict[simp]: "ccBind v e \<cdot> \<bottom> = \<bottom>" by (auto simp add: inst_prod_pcpo ccBind_eq simp del: Pair_strict) lemma ccField_ccBind: "ccField (ccBind v e\<cdot>(ae,G)) \<subseteq> fv e" by (auto simp add: ccBind_eq dest: set_mp[OF ccField_cc_restr]) definition ccBinds :: "heap \<Rightarrow> ((AEnv \<times> CoCalls) \<rightarrow> CoCalls)" where "ccBinds \<Gamma> = (\<Lambda> i. (\<Squnion>v\<mapsto>e\<in>map_of \<Gamma>. ccBind v e\<cdot>i))" lemma ccBinds_eq: "ccBinds \<Gamma>\<cdot>i = (\<Squnion>v\<mapsto>e\<in>map_of \<Gamma>. ccBind v e\<cdot>i)" unfolding ccBinds_def by simp lemma ccBinds_strict[simp]: "ccBinds \<Gamma>\<cdot>\<bottom>=\<bottom>" unfolding ccBinds_eq by (cases "\<Gamma> = []") simp_all lemma ccBinds_strict'[simp]: "ccBinds \<Gamma>\<cdot>(\<bottom>,\<bottom>)=\<bottom>" by (metis CoCallAnalysis.ccBinds_strict Pair_bottom_iff) lemma ccBinds_reorder1: assumes "map_of \<Gamma> v = Some e" shows "ccBinds \<Gamma> = ccBind v e \<squnion> ccBinds (delete v \<Gamma>)" proof- from assms have "map_of \<Gamma> = map_of ((v,e) # delete v \<Gamma>)" by (metis map_of_delete_insert) thus ?thesis by (auto intro: cfun_eqI simp add: ccBinds_eq delete_set_none) qed lemma ccBinds_Nil[simp]: "ccBinds [] = \<bottom>" unfolding ccBinds_def by simp lemma ccBinds_Cons[simp]: "ccBinds ((x,e)#\<Gamma>) = ccBind x e \<squnion> ccBinds (delete x \<Gamma>)" by (subst ccBinds_reorder1[where v = x and e = e]) auto lemma ccBind_below_ccBinds: "map_of \<Gamma> x = Some e \<Longrightarrow> ccBind x e\<cdot>ae \<sqsubseteq> (ccBinds \<Gamma>\<cdot>ae)" by (auto simp add: ccBinds_eq) lemma ccField_ccBinds: "ccField (ccBinds \<Gamma>\<cdot>(ae,G)) \<subseteq> fv \<Gamma>" by (auto simp add: ccBinds_eq dest: set_mp[OF ccField_ccBind] intro: set_mp[OF map_of_Some_fv_subset]) definition ccBindsExtra :: "heap \<Rightarrow> ((AEnv \<times> CoCalls) \<rightarrow> CoCalls)" where "ccBindsExtra \<Gamma> = (\<Lambda> i. snd i \<squnion> ccBinds \<Gamma> \<cdot> i \<squnion> (\<Squnion>x\<mapsto>e\<in>map_of \<Gamma>. ccProd (fv e) (ccNeighbors x (snd i))))" lemma ccBindsExtra_simp: "ccBindsExtra \<Gamma> \<cdot> i =snd i \<squnion> ccBinds \<Gamma> \<cdot> i \<squnion> (\<Squnion>x\<mapsto>e\<in>map_of \<Gamma>. ccProd (fv e) (ccNeighbors x (snd i)))" unfolding ccBindsExtra_def by simp lemma ccBindsExtra_eq: "ccBindsExtra \<Gamma>\<cdot>(ae,G) = G \<squnion> ccBinds \<Gamma>\<cdot>(ae,G) \<squnion> (\<Squnion>x\<mapsto>e\<in>map_of \<Gamma>. fv e G\<times> ccNeighbors x G)" unfolding ccBindsExtra_def by simp lemma ccBindsExtra_strict[simp]: "ccBindsExtra \<Gamma> \<cdot> \<bottom> = \<bottom>" by (auto simp add: ccBindsExtra_simp inst_prod_pcpo simp del: Pair_strict) lemma ccField_ccBindsExtra: "ccField (ccBindsExtra \<Gamma>\<cdot>(ae,G)) \<subseteq> fv \<Gamma> \<union> ccField G" by (auto simp add: ccBindsExtra_simp elem_to_ccField dest!: set_mp[OF ccField_ccBinds] set_mp[OF ccField_ccProd_subset] map_of_Some_fv_subset) end lemma ccBind_eqvt[eqvt]: "\<pi> \<bullet> (CoCallAnalysis.ccBind cccExp x e) = CoCallAnalysis.ccBind (\<pi> \<bullet> cccExp) (\<pi> \<bullet> x) (\<pi> \<bullet> e)" proof- { fix \<pi> ae G have "\<pi> \<bullet> ((CoCallAnalysis.ccBind cccExp x e) \<cdot> (ae,G)) = CoCallAnalysis.ccBind (\<pi> \<bullet> cccExp) (\<pi> \<bullet> x) (\<pi> \<bullet> e) \<cdot> (\<pi> \<bullet> ae, \<pi> \<bullet> G)" unfolding CoCallAnalysis.ccBind_eq by perm_simp (simp add: Abs_cfun_eqvt) } thus ?thesis by (auto intro: cfun_eqvtI) qed lemma ccBinds_eqvt[eqvt]: "\<pi> \<bullet> (CoCallAnalysis.ccBinds cccExp \<Gamma>) = CoCallAnalysis.ccBinds (\<pi> \<bullet> cccExp) (\<pi> \<bullet> \<Gamma>)" apply (rule cfun_eqvtI) unfolding CoCallAnalysis.ccBinds_eq apply (perm_simp) apply rule done lemma ccBindsExtra_eqvt[eqvt]: "\<pi> \<bullet> (CoCallAnalysis.ccBindsExtra cccExp \<Gamma>) = CoCallAnalysis.ccBindsExtra (\<pi> \<bullet> cccExp) (\<pi> \<bullet> \<Gamma>)" by (rule cfun_eqvtI) (simp add: CoCallAnalysis.ccBindsExtra_def) lemma ccBind_cong[fundef_cong]: "cccexp1 e = cccexp2 e \<Longrightarrow> CoCallAnalysis.ccBind cccexp1 x e = CoCallAnalysis.ccBind cccexp2 x e " apply (rule cfun_eqI) apply (case_tac xa) apply (auto simp add: CoCallAnalysis.ccBind_eq) done lemma ccBinds_cong[fundef_cong]: "\<lbrakk> (\<And> e. e \<in> snd ` set heap2 \<Longrightarrow> cccexp1 e = cccexp2 e); heap1 = heap2 \<rbrakk> \<Longrightarrow> CoCallAnalysis.ccBinds cccexp1 heap1 = CoCallAnalysis.ccBinds cccexp2 heap2" apply (rule cfun_eqI) unfolding CoCallAnalysis.ccBinds_eq apply (rule arg_cong[OF mapCollect_cong]) apply (rule arg_cong[OF ccBind_cong]) apply auto by (metis imageI map_of_SomeD snd_conv) lemma ccBindsExtra_cong[fundef_cong]: "\<lbrakk> (\<And> e. e \<in> snd ` set heap2 \<Longrightarrow> cccexp1 e = cccexp2 e); heap1 = heap2 \<rbrakk> \<Longrightarrow> CoCallAnalysis.ccBindsExtra cccexp1 heap1 = CoCallAnalysis.ccBindsExtra cccexp2 heap2" apply (rule cfun_eqI) unfolding CoCallAnalysis.ccBindsExtra_simp apply (rule arg_cong2[OF ccBinds_cong mapCollect_cong]) apply simp+ done end
# Exercise 7) Learning and Planning In this exercise, we will again investigate the inverted pendulum from the `gym` environment. We want to check, which benefits the implementation of planning offers. Please note that the parameter $n$ has a different meaning in the context of planning (number of planning steps per actual step) than in the context of n-step learning. ```python import numpy as np import gym gym.logger.set_level(40) import random import time from tqdm.notebook import tqdm import matplotlib.pyplot as plt plt.style.use('seaborn-talk') ``` We will reuse the discretization routine from the previous exercise: ```python d_T = 15 d_theta = 15 d_omega = 15 def discretize_state(states): limits = [1, 1, 8] nb_disc_intervals = [d_theta, d_theta, d_omega] # bring to value range [-1, 1] norm_states = [state / limit for state, limit in zip(states, limits)] interval_lengths = [2 / d for d in nb_disc_intervals] disc_state = [(norm_state + 1) // interval_length for norm_state, interval_length in zip(norm_states, interval_lengths)] disc_state = [(state - 1) if state == d else state for state, d in zip(disc_state, nb_disc_intervals)] # ensure that disc_state < d return np.array(disc_state) def continualize_action(disc_action): limit = 2 interval_length = 2 / (d_T-1) norm_action = disc_action * interval_length cont_action = (norm_action - 1) * limit return np.array(cont_action).flatten() ``` ## 1) Dyna-Q Write a Dyna-Q algorithm to solve the inverted pendulum. Check the quality of the result for different number of episodes, number of steps per episode and number of planning steps per interaction. Make sure that the total number of learning steps stays the same for different n, such that comparisons are fair: $\text{episodes} \cdot \text{steps} \cdot (1+n) = \text{const.}$ Interesting metrics for a comparison could be e.g. the execution time (the tqdm loading bar shows execution time of loops, alternatively you can use the time.time() command to get the momentary system time in seconds) and training stability. ## Solution 1) The solution code is given below. ```python def pendulumDynaQ(alpha, gamma, epsilon, n, nb_episodes, nb_steps): env = gym.make('Pendulum-v0') env = env.unwrapped action_values = np.zeros([d_theta, d_theta, d_omega, d_T]) pi = np.zeros([d_theta, d_theta, d_omega]) model = {} # dictionary cumulative_reward_history = [] # we can use this to figure out how well the learning worked for j in tqdm(range(nb_episodes), position=0, leave=True): ### BEGIN SOLUTION rewards = [] # this time, this list is only for monitoring state = env.reset() # initialize x_0 state = tuple(discretize_state(state).astype(int)) for k in range(nb_steps): # sample experiences for the model if np.random.uniform(0, 1) < epsilon: action = np.random.choice(d_T) # explorative action else: action = pi[state].astype(int) # exploitative action cont_action = continualize_action(action) next_state, reward, done, _ = env.step(cont_action) next_state = tuple(discretize_state(next_state).astype(int)) # learn from the momentary experience action_values[state][action] += alpha * (reward + gamma * np.max(action_values[next_state]) - action_values[state][action] ) pi[state] = np.argmax(action_values[state]) model[state, action] = (next_state, reward) # update the model accoring to the latest experience state = next_state rewards.append(reward) # learn from the model, IMPORTANT: USE DIFFERENT VARIABLES HERE for i in range(n): # sample a random key from the dict: this state action combination has surely been taken in the past x, u = random.sample(model.keys(), 1)[0] x_1, r = model[x, u] action_values[x][u] += alpha * (r + gamma * np.max(action_values[x_1]) - action_values[x][u] ) pi[x] = np.argmax(action_values[x]) if done: break cumulative_reward_history.append(np.sum(rewards)) env.close() ### END SOLUTION return cumulative_reward_history, pi ``` Function to evaluate and render the measurement using the gym environment: ```python def experiment(pi,nb_steps = 300): # Runs the inverted pendulum experiment using policy pi for nb_steps steps env = gym.make('Pendulum-v0') env = env.unwrapped state = env.reset() # initialize x_0 disc_state = tuple(discretize_state(state).astype(int)) # only tuples of integers can be used as index disc_action = pi[disc_state].astype(int) for k in range(nb_steps): cont_action = continualize_action(disc_action) env.render() # comment out for faster execution state, reward, done, _ = env.step(cont_action) disc_state = tuple(discretize_state(state).astype(int)) if done: break disc_action = pi[disc_state].astype(int) # exploitative action env.close() ``` Let's use nb_episodes = 5000, nb_steps = 500, n = 0 as a first try. This is effectively Q learning. \begin{align} 5000 \cdot 500 \cdot (0+1) &= 2.5 \cdot 10^6 \end{align} The resulting policy is satisfactory. ```python ### train print("Run without planning") no_planning_history, no_planning_pi = pendulumDynaQ(alpha = 0.1, gamma = 0.9, epsilon = 0.1, n = 0, nb_episodes = 5000, nb_steps = 500) ``` Run without planning HBox(children=(FloatProgress(value=0.0, max=5000.0), HTML(value=''))) ```python ### run and render the experiment experiment(no_planning_pi,nb_steps = 300) ``` Now let's try $n=9$ with the same nb_steps = 500: \begin{align} \text{nb_episodes} &= \frac{2.5 \cdot 10^6}{500 \cdot (9+1)} = 500 \end{align} The resulting policy also looks good. ```python ### train print("Run with planning") with_planning_history, with_planning_pi = pendulumDynaQ(alpha = 0.1, gamma = 0.9, epsilon = 0.1, n = 9, nb_episodes = 500, nb_steps = 500) ``` Run with planning HBox(children=(FloatProgress(value=0.0, max=500.0), HTML(value=''))) ```python ### run and render the experiment experiment(with_planning_pi,nb_steps = 300) ``` Now lets compare the cumulative rewards: ```python plt.plot(no_planning_history) plt.plot(with_planning_history) plt.xlabel("episode") plt.ylabel(r"$\sum R$") plt.show() ``` The cumulative reward over the episodes both seems to have high variance. So why should we prefer the planning method? ### Planning leads to the agent interacting less often with the "real" environment, such that in the end fewer interaction time is needed. ## 2) Simulation-based planning Although it can be useful for small state spaces, building a system model by storing large amounts of state transitions like in task (1) is rarely feasible in engineering. As engineers, we are capable of a more efficient way of system modeling that we can utilize here: differential equations. Using a state-space model allows to efficiently integrate existing pre-knowledge into the Dyna-Q algorithm we already used. To do so, write a class `pendulum_model` that implements a model of the pendulum. This class should work similar to `gym`: it should at least have a `step` and a `reset` method. In the step method, make use of forward Euler integration to simulate the system dynamics. In the reset method, allow to pass an optional initial state to the model, such that we can easily compare model and environment. If no initial state is passed to the `reset` function, a random initial state should be determined. Integrate this model into a Dyna-Q algorithm. Model of the pendulum in differential-equation form for change of the angular frequency $\omega$ and the angle $\theta$ depending on the torque $T_\mathrm{u}$: \begin{align} \dot{\omega} &= -\frac{3 g}{2 l} \text{sin}(\theta +\pi) + \frac{1}{J} T_\mathrm{u} \\ \dot{\theta} &= \omega \end{align} Parameters (gravity constant $g$, mass $m$, length $l$ and intertia $J$ of the pendulum): \begin{align} g&=10 \, \frac{\text{m}}{\text{s}^2} & m&=1 \, \text{kg} & l&=1 \, \text{m} & J&=\frac{1}{3} m l^2 \end{align} Forward Euler integration: \begin{align} \dot{x}(k T_S) \approx \frac{x[k+1] - x[k]}{T_S} \end{align} with sampling time $T_S = 0.05 \, \text{s}$ Reward function: \begin{align} r_{k+1} = -(\theta^2[k] + 0.1 \, \text{s}^2 \cdot \omega^2[k] + 0.001 \frac{1}{(\text{N}\text{m})^2} \cdot T_\mathrm{u}^2[k]) \end{align} Limitations of state and action space: \begin{align} \theta &\in [-\pi, \pi] & \omega &\in [-8 \, \frac{1}{\text{s}}, 8 \, \frac{1}{\text{s}}] & T_\mathrm{u} &\in [-2 \, \text{N}\text{m}, 2 \, \text{N}\text{m}] \end{align} And of course input and output space: \begin{align} \text{action}&=T_\mathrm{u} & \text{state}&= \begin{bmatrix} \text{cos}(\theta)\\ \text{sin}(\theta)\\ \omega \end{bmatrix} \end{align} ## Solution 2) Model-based planning does not necessarily run faster than experience-based planning. However, experience-based planning fails to cover the whole state space especially in the earlier episodes when there are too few experiences. On the other hand, model-based planning can, of course, only be performed if a state-space model with accurate parametrization is available. In order to overcome parametric deviations between state-space model and environment, one could even use the measurements from the actual environment in order to identify the parameters of the model during runtime. ```python class pendulum_model: def __init__(self, dt=0.05, m=1, g=10, l=1): ### BEGIN SOLUTION self.max_speed = 8 self.max_torque = 2 self.dt = dt # sampling time in s self.g = g # gravity in m / s^2 self.m = m # mass in kg self.l = l # length in m self.J = 1 / 3 * m * l ** 2 # pedulums moment of inertia in kg * m^2 ### END SOLUTION def reset(self, state=None): ### BEGIN SOLUTION # if no state is give, set randomly if np.any(state == None): self.theta = np.random.uniform(-np.pi, +np.pi) self.omega = np.random.uniform(-self.max_speed, +self.max_speed) # else set initial state as given else: self.theta = np.arctan2(state[1], state[0]) self.omega = state[2] state = np.array([np.cos(self.theta), np.sin(self.theta), self.omega]) ### END SOLUTION return state def step(self, T_u): ### BEGIN SOLUTION T_u = np.clip(T_u, -self.max_torque, +self.max_torque)[0] reward = -(self.angle_normalize(self.theta)** 2 + 0.1 * self.omega ** 2 + 0.001 * (T_u ** 2)) # differential-equations for state values self.omega = self.omega + self.dt * (-3 * self.g/(2 * self.l) * np.sin(self.theta + np.pi) + 1 / self.J * T_u) self.theta = self.theta + self.dt * self.omega self.omega = np.clip(self.omega, -self.max_speed, +self.max_speed) state = np.array([np.cos(self.theta), np.sin(self.theta), self.omega]) ### END SOLUTION return state, reward def angle_normalize(self, theta): # usage of this helper function is optional return (((theta+np.pi) % (2*np.pi)) - np.pi) ``` The following cell is for debugging of the `pendulum_model` class. ```python env = gym.make('Pendulum-v0') env = env.unwrapped # removes a builtin time limit of k_T = 200, we want to determine the time limit ourselves model = pendulum_model() state = env.reset() print(state) m_state = model.reset(state) # model is set to state of env for _ in range(10000): print(f"state: {state}") print(f"model: {m_state}") print() action = env.action_space.sample() state, reward, done, _ = env.step(action) # take action on env m_state, m_reward = model.step(action) # take the same action on model print(f"reward difference: {reward- m_reward}, env_reward:{reward}, model_reward:{m_reward}") env.close() ``` Using $-\mathrm{sin}(\theta)$ instead of $\mathrm{sin}(\theta +\pi)$ makes no difference when assuming analytical precision, but due to numeric errors these formulations will still yield different results in numpy, mainly because $\pi$ is represented with finite (float) precision. In order to yield the same numbers as in `gym`, we will still make use of the (more cumbersome) $\mathrm{sin}(\theta +\pi)$. Write a function for the Dyna-Q algorithm, which uses the model we defined above: ```python def pendulumModelDynaQ(alpha, gamma, epsilon, n, nb_episodes, nb_steps): env = gym.make('Pendulum-v0') env = env.unwrapped model = pendulum_model() action_values = np.zeros([d_theta, d_theta, d_omega, d_T]) pi = np.zeros([d_theta, d_theta, d_omega]) cumulative_reward_history = [] # we can use this to figure out how well the learning worked for j in tqdm(range(nb_episodes), position=0, leave=True): ### BEGIN SOLUTION rewards = [] # this time, this list is only for monitoring state = env.reset() # initialize x_0 state = tuple(discretize_state(state).astype(int)) for k in range(nb_steps): # sample experiences for the model if np.random.uniform(0, 1) < epsilon: action = np.random.choice(d_T) # explorative action else: action = pi[state].astype(int) # exploitative action cont_action = continualize_action(action) next_state, reward, done, _ = env.step(cont_action) next_state = tuple(discretize_state(next_state).astype(int)) # learn from the momentary experience action_values[state][action] += alpha * (reward + gamma * np.max(action_values[next_state]) - action_values[state][action] ) pi[state] = np.argmax(action_values[state]) # no model update is needed state = next_state rewards.append(reward) # learn from the model, IMPORTANT: USE DIFFERENT VARIABLES HERE for i in range(n): x = model.reset() # if no state is passed to the model, state is initialized randomly u_d = np.random.choice(d_T) x_d = tuple(discretize_state(x).astype(int)) u = continualize_action(u_d) x_1, r = model.step(u) x_1_d = tuple(discretize_state(x_1).astype(int)) action_values[x_d][u_d] += alpha * (r + gamma * np.max(action_values[x_1_d]) - action_values[x_d][u_d] ) pi[x_d] = np.argmax(action_values[x_d]) if done: break cumulative_reward_history.append(np.sum(rewards)) env.close() ### END SOLUTION return cumulative_reward_history, pi ``` Use the following cell to compare the learing from experience from 1) to the learning using the defined model: (Beware, nb_steps = 10000 can take some time) ```python ### train both setups once print("Run with planning from experience") exp_planning_history, exp_planning_pi = pendulumDynaQ(alpha = 0.1, gamma = 0.9, epsilon = 0.1, n = 19, nb_episodes = 30, nb_steps = 10000) print("Run with planning from model") model_planning_history, model_planning_pi = pendulumModelDynaQ(alpha = 0.1, gamma = 0.9, epsilon = 0.1, n = 19, nb_episodes = 30, nb_steps = 10000) plt.plot(exp_planning_history) plt.plot(model_planning_history) plt.xlabel("episode") plt.ylabel(r"$\sum R$") plt.show() ``` Use the following cell to execute the policy we got using the model: ```python experiment(model_planning_pi,nb_steps = 300) ``` ### Extra-task: Change the model parameters (e.g. $g$, $m$, $l$) so that our model differs from the "real world" (we got from gym). What do you observe By changing the parameters our model differs from the "real world". Depending on the amount of difference, the learing curve looks worse than the one with the correct values. The experiment result is also depending on the random starting position. Depending on the parameter difference, the experiment can not be executed successfully any more. Try to change the parameters on your own. The Following learning curve results from a parameter change using $g =20 \, \frac{\text{m}}{\text{s}^2}, m = 5 \, \text{kg and } l = 2 \, \text{m}$: ```python plt.plot(exp_planning_history, label="exp") plt.plot(model_planning_history, label="model") plt.xlabel("episode") plt.ylabel(r"$\sum R$") plt.legend(loc="upper left") plt.show() ```
c fork.ftn & fold.ftn c=================================================================== c 1-d fft of the function cx(j),j=1,lx c lx c cx(k)= SUM (cx(j)* exp {2*pi*signi*i*(j-1)*(k-1)/lx} c j=1 c point corresponding to Nyquist frequency is lx/2+1 c=================================================================== subroutine fork (lx,isigni,cx) complex cx(lx),carg,cexp,cw,ctemp j=1 c------------- in inverse fft, a factor of (1/lx) is applied. sc=1. if(isigni.lt.0)sc=1./real(lx) do 30 i=1,lx if(i.gt.j)go to 10 ctemp=cx(j)*sc cx(j)=cx(i)*sc cx(i)=ctemp 10 m=lx/2 20 if(j.le.m)go to 30 j=j-m m=m/2 if(m.ge.1)go to 20 30 j=j+m l=1 40 istep=2*l do 50 m=1,l carg=cmplx(0.,1.)*(3.141592654*isigni*(m-1))/real(l) cw=cexp(carg) do 50 i=m,lx,istep ctemp=cw*cx(i+l) cx(i+l)=cx(i)-ctemp 50 cx(i)=cx(i)+ctemp l=istep if(l.lt.lx)go to 40 return end c======================================================== c Nyquist frequency is at nq = lx/2 c folding across the symmetry axis nq+1=nq1 c first variable (k=1) folds nowhere, starts from k=2 c======================================================== subroutine fold (n,nq1,u) complex u(1) np2=n+2 do 820 k=2,nq1 820 u(np2-k)=conjg(u(k)) return end
\documentclass[]{article} \usepackage{graphicx} \usepackage{subfig} %opening \title{ Artificial Composer\\ \texttt{}\\ \large Intelligent Information Systems} \author{Paulina Szwed} \begin{document} \maketitle \section{Introduction} The objective of the project was to create an intelligent information system that is able to generate music on its own. Although content generation is not one of the main usecases for the information systems, this subject is progressing very quickly, mainly because of the possibilities created by deep neural networks. One of the techniques to build such systems that often gives very promising results is the use of generative adversarial networks (GAN). GAN is a compound system made of two neural networks - the generator and the discriminator. The discriminator is the component that determines whether the content shown to it is real or generated artificially (fake). The generator tries to deceive the discriminator by creating more and more realistic content. During my experiments I used three variants of GAN architecture in order to create a system generating the most realistic music. \section{Experiments} Experiments were conducted on different types of GAN but every one of them used the same training loop. Two of them were trained on songs from Maestro dataset \cite{hawthorne2018enabling} from 2018, the last experiments used songs by Queen from \cite{queenmidisongs}. All experiments used files in MIDI format, but converted into different representations. \subsection{Training loop} The training loop was divided into two stages. First, the discriminator was trained on a whole epoch of real samples (with expected output of ones) and a whole epoch of fake samples (with expected output of zeros). Then, the generator was trained by exposing the combined system with frozen discriminator weights to an epoch of fake samples, but with expected output of ones. Before the actual training loop I introduced a pretraing stage, to initially enhance the performance of the generator - the pretraining stage was only training the combined system like in the second stage of the main training loop. In every case I trained the models on batches of 8 samples each and I performed 5 epochs of pretraining. \subsection{Models} During my reserach I tried out different models for generators and discriminators. I also used different methods for representing information from the training set. \subsubsection{One Hot Encoding DCGAN} At first I used a DCGAN (deep convolutional generative adversarial networks \cite{dcgan}). In this model the discriminator processed genetrated content as images, using convolutional layers and the generator uses deconvolution to create an image from vector of random numbers. Table \ref{ohe-dcgan} shows detailed description of the model that I trained. \begin{table}[h!] \centering \begin{tabular}{|r|c|c|} \hline \multicolumn{1}{|c|}{\textbf{Index}} & \textbf{Layer type} & \textbf{Description} \\ \hline \multicolumn{3}{|c|}{\textbf{Generator}} \\ \hline 1 & Dense & 8192 neurons \\ \hline 2 & Leaky ReLU & alpha 0.2 \\ \hline 3 & Reshape & Reshaping into vector 8 x 8 x 128 \\ \hline 4 & Deconvolution & 64 filters 4x4 \\ \hline 5 & Leaky ReLU & alpha 0.2 \\ \hline 6 & Deconvolution & 64 filters 4x4 \\ \hline 7 & Leaky ReLU & alpha 0.2 \\ \hline 8 & Deconvolution & 64 filters 4x4 \\ \hline 9 & Leaky ReLU & alpha 0.2 \\ \hline 10 & Convolution & 1 filter 7x7, sigmoid activation function \\ \hline \multicolumn{3}{|c|}{\textbf{Discriminator}} \\ \hline 1 & Convolution & 128 filters 5x5 \\ \hline 2 & Leaky ReLU & alpha 0.2 \\ \hline 3 & Dropout & dropout factor 0.2 \\ \hline 4 & Convolution & 64 filters 3x3 \\ \hline 5 & Leaky ReLU & alpha 0.2 \\ \hline 6 & Dropout & dropout factor 0.2 \\ \hline 7 & Convolution & 32 filters 3x3 \\ \hline 8 & Leaky ReLU & alpha 0.2 \\ \hline 9 & Dropout & dropout factor 0.2 \\ \hline 10 & Flatten & \\ \hline 11 & Dense & 1 neuron, sigmoid activation function \\ \hline \end{tabular} \caption{Simple one-hot encoding DC GAN structure} \label{ohe-dcgan} \end{table} The representation for the music I used in the first experiment was a matrix created from notes in MIDI file. Each note was a integer value between 0 and 127, so I decided to build an matrix of size 127 on 127 pixels in which every row represented one note and it contained 127 notes long fragment of a song. For representing notes I used one-hot encoding, which means that I converted the value to an index of a element in the matrix row, filled it with value 1.0 and the rest of them with zeros. The training process is shown in figures \ref{fig:simplecnn-loss} and \ref{fig:simplecnn-acc}. \begin{figure}[!h] \centering \subfloat[Loss during training]{ \includegraphics[width=0.49\textwidth]{img/simple-cnn-dcnn-GAN_GAN_Loss_per_Epoch_final.png} \label{fig:simplecnn-loss} } \subfloat[Discriminator accuracy during training]{ \includegraphics[width=0.49\textwidth]{img/simple-cnn-dcnn-GAN_GAN_Accuracy_per_Epoch_final.png} \label{fig:simplecnn-acc} } \caption{Loss and accuracy during training of simple one-hot encoding DCGAN} \end{figure} The results shown that such architecture can be a mechanism to create some kind of music, but it's possibilities were limited to simple sounds - one-hot encoding does not allow to use chords. There is also only one instrument in those generated songs. \subsubsection{LSTM-based GAN} Next I used a generator made of densily connected layers and a discriminator that contained 2 layers of LSTM cells. I was hoping that LSTM's "memory" will improve performance by better perception of sequential patterns in songs. Music was represented as a sequence of numerical values indicating notes of the song. The detailed description of the layers is provided in table \ref{lstm-gan}. \begin{table}[] \centering \begin{tabular}{|r|c|c|} \hline \multicolumn{1}{|c|}{\textbf{Index}} & \textbf{Layer type} & \textbf{Description} \\ \hline \multicolumn{3}{|c|}{\textbf{Generator}} \\ \hline 1 & Dense & 256 neurons \\ \hline 2 & Leaky ReLU & alpha 0.2 \\ \hline 3 & Batch Normalization & momentum 0.8 \\ \hline 4 & Dense & 256 neurons \\ \hline 5 & Leaky ReLU & alpha 0.2 \\ \hline 6 & Batch Normalization & momentum 0.8 \\ \hline 7 & Dense & 512 neurons \\ \hline 8 & Leaky ReLU & alpha 0.2 \\ \hline 9 & Batch Normalization & momentum 0.8 \\ \hline 10 & Dense & 16384 neurons \\ \hline 11 & Reshape & reshaping into matrix 128 x 128 \\ \hline \multicolumn{3}{|c|}{\textbf{Discriminator}} \\ \hline 1 & LSTM & 128 cells \\ \hline 2 & Bidirectional LSTM & 512 cells \\ \hline 3 & Dense & 256 neurons \\ \hline 4 & Leaky ReLU & alpha 0.2 \\ \hline 5 & Batch Normalization & momentum 0.8 \\ \hline 6 & Dense & 128 neurons \\ \hline 7 & Leaky ReLU & alpha 0.2 \\ \hline 8 & Batch Normalization & momentum 0.8 \\ \hline 9 & Dense & 64 neurons \\ \hline 10 & Leaky ReLU & alpha 0.2 \\ \hline 11 & Batch Normalization & momentum 0.8 \\ \hline 12 & Dense & 1 neuron, sigmoid activation function \\ \hline \end{tabular} \caption{LSTM-based GAN structure} \label{lstm-gan} \end{table} Figures \ref{fig:lstmgan-loss} and \ref{fig:lstmgan-acc} shows the training process. As we can see, the LSTM-based architecture had troubles with short learning span. It's noticeable that this system quickly degraded and music generated by it becomes a sequence of minimum and maximum values. Those troubles were probably caused by exploding gradients problem. \begin{figure}[!h] \centering \subfloat[Loss during training]{ \includegraphics[width=0.49\textwidth]{img/2021_02_08_21_47_26_midi-notes-lstm-gan-scalec_GAN_Loss_per_Epoch_epoch_120.png} \label{fig:lstmgan-loss} } \subfloat[Discriminator accuracy during training]{ \includegraphics[width=0.49\textwidth]{img/2021_02_08_21_47_26_midi-notes-lstm-gan-scalec_GAN_Accuracy_per_Epoch_epoch_120.png} \label{fig:lstmgan-acc} } \caption{Loss and accuracy during training of LSTM-based GAN} \end{figure} LSTM-based GAN can be a system for music generation, but it has the same limitations as DCGAN with one-hot encoding. The exploading gradients problem made it impossible to aquire more realistic results, but it still did generate some interesting samples in which we can hear some repeating patterns. \subsubsection{Pianoroll-based DCGAN} At the next stage of the experiments I went back to the DCGAN architecture but with different approach to representation of music. I used a pianoroll format and converted it into a matrix that had 3 channels (depth equal to 3) so that I could place there an information on chords played by different instruments and even drums. Table \ref{pianoroll-dc-gan} shows detailed description of layers in the system. \begin{table}[h!] \centering \begin{tabular}{|r|c|c|} \hline \multicolumn{1}{|c|}{\textbf{Index}} & \textbf{Layer type} & \textbf{Description} \\ \hline \multicolumn{3}{|c|}{\textbf{Generator}} \\ \hline 1 & Dense & 8912 neurons \\ \hline 2 & Leaky ReLU & alpha 0.2 \\ \hline 3 & Reshape & reshaping to matrix 8 x 8 x 128 \\ \hline 4 & Deconvolution & 64 filters 4x4 \\ \hline 5 & Batch Normalization & momentum 0.8 \\ \hline 6 & Leaky ReLU & alpha 0.2 \\ \hline 7 & Deconvolution & 64 filters 4x4 \\ \hline 8 & Batch Normalization & momentum 0.8 \\ \hline 9 & Leaky ReLU & alpha 0.2 \\ \hline 10 & Deconvolution & 64 filters 4x4 \\ \hline 11 & Batch Normalization & momentum 0.8 \\ \hline 12 & Leaky ReLU & alpha 0.2 \\ \hline 13 & Convolution & 3 filters 7x7 \\ \hline \multicolumn{3}{|c|}{\textbf{Discriminator}} \\ \hline 1 & Convolution & 128 filters 5x5 \\ \hline 2 & Leaky ReLU & alpha 0.2 \\ \hline 3 & Convolution & 128 filters 5x5 \\ \hline 4 & Leaky ReLU & alpha 0.2 \\ \hline 5 & Convolution & 64 filters 3x3 \\ \hline 6 & Leaky ReLU & alpha 0.2 \\ \hline 7 & Convolution & 32 filters 3x3 \\ \hline 8 & Leaky ReLU & alpha 0.2 \\ \hline 9 & Flatten & \\ \hline 10 & Dense & 1 neuron, sigmoid activation function \\ \hline \end{tabular} \caption{Pianoroll DCGAN structure} \label{pianoroll-dc-gan} \end{table} Training process is shown in figures \ref{fig:pianoroll-loss} and \ref{fig:pianoroll-acc}. As we can see it was longest training process and it did not lead to exploading or vanishing gradients. \begin{figure}[!h] \centering \subfloat[Loss during training]{ \includegraphics[width=0.49\textwidth]{img/2021_01_31_22_56_40_pianoroll-DC-GAN_GAN_Loss_per_Epoch_epoch_5900.png} \label{fig:pianoroll-loss} } \subfloat[Discriminator accuracy during training]{ \includegraphics[width=0.49\textwidth]{img/2021_01_31_22_56_40_pianoroll-DC-GAN_GAN_Accuracy_per_Epoch_epoch_5900.png} \label{fig:pianoroll-acc} } \caption{Loss and accuracy during training of LSTM-based GAN} \end{figure} The results from this process were very satysfying. You can see and hear rythm in drums (red channel) and also repeating patterns and chords in instrumental channels (see figure \ref{fig:pianoroll-example}) \begin{figure}[!h] \centering \subfloat[Result after 0 epochs]{ \includegraphics[width=0.49\textwidth]{img/2021_01_28_22_56_58_pianoroll-DC-GAN_epoch_0.png} } \subfloat[Result after 100 epochs]{ \includegraphics[width=0.49\textwidth]{img/2021_01_28_22_58_42_pianoroll-DC-GAN_epoch_100.png} } \hfill \subfloat[Result after 3600 epochs]{ \includegraphics[width=0.49\textwidth]{img/2021_01_29_00_00_12_pianoroll-DC-GAN_epoch_3600.png} } \subfloat[Result after 28800 epochs]{ \includegraphics[width=0.49\textwidth]{img/2021_01_29_07_06_39_pianoroll-DC-GAN_epoch_28800.png} } \caption{Loss and accuracy during training of LSTM-based GAN} \label{fig:pianoroll-example} \end{figure} \subsubsection{Others} During my experiments I also tried to implement a system that would process sound in a form of spectrogram created from WAV file by short-time Fourier transform and converting it back to a WAV file, but the images to be processed were very large. The neural networks capable of processing such images could not be handled by my machine. \clearpage \section{Implemented software} In order to prepare training and generation scripts I used the following tools: \begin{itemize} \item Python 3.8 \item Tensorflow and CUDA as training tool \item Keras as a library for building neural networks \item mido and pypianoroll libraries for processing MIDI files \item matplotlib library for visualization \item argparse library for handling command line interface. \end{itemize} Instructions for both training and generation scripts can be found in readme.md file in the repository. \section{Summary} As a result of the project I managed to deliver a intelligent information system that is capable of generating music. I did not expect spectacular results from a rather small system trained on my PC, since it requires a lot of computations, but what I managed to deliver is a satysfying outcome despite its limitations. \bibliographystyle{plain} \bibliography{bibliography.bib} \end{document}
Formal statement is: lemma linear_times_of_real: "linear (\<lambda>x. a * of_real x)" Informal statement is: The function $x \mapsto a \cdot \mathrm{of\_real}(x)$ is linear.
In 1988 , Jordan was honored with the NBA 's Defensive Player of the Year Award and became the first NBA player to win both the Defensive Player of the Year and MVP awards in a career ( since equaled by Hakeem Olajuwon , David Robinson , and Kevin Garnett ; Olajuwon is the only player other than Jordan to win both during the same season ) . In addition he set both seasonal and career records for blocked shots by a guard , and combined this with his ball @-@ thieving ability to become a standout defensive player . He ranks third in NBA history in total steals with 2 @,@ 514 , trailing John Stockton and Jason Kidd . Jerry West often stated that he was more impressed with Jordan 's defensive contributions than his offensive ones . He was also known to have strong eyesight ; broadcaster Al Michaels said that he was able to read baseball box scores on a 27 @-@ inch television clearly from about 50 feet away .
# The algorithm is written in R. The lines starting with or followed by "#" are comments for functions, command lines, or delimiters of separate functions. ###### Load packages ###### Author: Qingyuan Yang and Marcus Bursik ###### License: GPL. Use at your own risk. ###### Requires: to run the examples, the appropriate CSV files are needed. library(gstat) library(sp) library(rgdal) library(RandomFields) library(maptools) library(raster) library(deldir) library(ggplot2) library(segmented) library(poweRlaw) library(segmented) library(geoR) library(combinat) ###### Workflow ######################################################################################################################################### ######(1) Calculate the distances, downwind distances of sample sites with respect to the input <------ function "prep" ###### ###### source vent location and wind direction. ###### ###### ###### ######(2) Apply segmented/simple linear regression to the datasets: the log-thickness is the linear <------ function "sample.reg" ###### ###### combination of distance and downwind distance plus a constant. ###### ###### ###### ######(3) Record the fitted values and residuals from the fitting in step (2) <------ implemented by command lines ###### ###### ###### ######(4) Form a grid for mapping of the trend and the final result <------ function "form.grid" ###### ###### ###### ######(5) Form the trend model <------ function "prep2" and "trendmodel" ###### ###### ###### ######(6) Form and fit the variogram function of the residuals recorded in step (3) <------ function "var.read" ###### ###### ###### ######(7) Implemnt ordinary kriging using the residuals in step (3) and the variogram models <------ function "prediction" ###### ###### from step (6) to form the local thickness variation. We take the sum of ###### ###### the trend model in step (5) and the local variation to form the final thickness distribution ###### ###### ###### ###### End of workflow ################################################################################################################################## ###### Functions ######################################################################################################################################## prep <- function(sv, td, ang){ ### See step (1) in the workflow above ### Input variables: ### Data type ### Column naes ### sv: the source vent location dataframe "x" and "y" ### td: the tephra thickness dataset dataframe "x", "y", "rz" (real thickness), "z"(log-transformed thickness) ### ang: the inferred wind direction (from north clockwise) a single value - ### Intermediate variables: ### pts: the coordinates of sample sites ### nr: the number of observations ### sv.mtx: the matrix prepared for the computation of distance and downwind distance ### disp.mtx: the unit vector pointing along the wind direction for the computation of downwind distance ### dist, dd, cd: computed distances, downwind distances, and crosswind distances from the sample sites to ### the source vent with the inferred wind direction ### Output: ### The output is a dataframe that contains the original thickness dataset and the calculated distances, downwind ### distances, and the crosswind distances of the sample sites. ### Method: ### This function uses a simple dot product to calculate the downwind distance pts <- as.matrix(td[,c(1,2)]) ### Extract the coordinates of sample sites sv <- as.matrix(sv) nr <- nrow(pts) sv.mtx <- matrix(ncol=2, nrow=nr) ### Repeated rows of the coordinates of the source vent sv.mtx[,1] <- rep(sv[1], nr) sv.mtx[,2] <- rep(sv[2], nr) disp.mtx <- c(sin(ang*pi/180),cos(ang*pi/180)) ### Form the unit vector pointing to the wind direction pts.mtx <- pts-sv.mtx ### Calculate the distances, downwind distances, and crosswind distances pts.sq <- (pts.mtx)^2 ### of the sample sites dist<- (pts.sq[,1]+pts.sq[,2])^0.5 dd <- pts.mtx %*% disp.mtx cd <-(dist^2-dd^2)^0.5 output <- as.data.frame(cbind(pts, dist, dd, cd, td[, c(3,4)])) ### Reorganize the data for output colnames(output) <- c("x", "y", "dist", "dd", "cd", "rz", "z") return(output) } ###----------------- prep2 <- function(sv, td, ang){ ### This function is written for the computation of the trend model, which requires distances and ### downwind distances of all the cells within the region of interest. Therefore this function works ### exactly the same way as function "prep", except that the trend thicknesses of these cells are to ### be computed. This function is called in the function "trendmodel" for further calculation of trend thickness. ### Input variables: ### Data type ### Column names ### sv: the source vent location dataframe "x" and "y" ### td: the coordinates of the cells of the grid dataframe or matrix does not matter, as they are transfered into matrix in this function ### ang: the inferred wind direction (from north clockwise) a single value - ### Output variables: ### The output is a dataframe that records the coordinates, distances, downwind distances, and crosswind distances ### of the cells of the grid. pts <- as.matrix(td[,c(1,2)]) sv <- as.matrix(sv) nr <- nrow(pts) sv.mtx <- matrix(ncol=2, nrow=nr) sv.mtx[,1] <- rep(sv[1], nr) sv.mtx[,2] <- rep(sv[2], nr) disp.mtx <- c(sin(ang*pi/180),cos(ang*pi/180)) pts.mtx <- pts-sv.mtx pts.sq <- (pts.mtx)^2 dist<- (pts.sq[,1]+pts.sq[,2])^0.5 dd <- pts.mtx %*% disp.mtx cd <-(dist^2-dd^2)^0.5 output <- as.data.frame(cbind(pts, dist, dd, cd)) colnames(output) <- c("x", "y", "dist", "dd", "cd") return(output) } ###----------------- sample.reg <- function(td, segdist, segdd){ ### See step (2) of the workflow above ### This function provides two alternative fitting schemes for the fitting of thickness with distance and downwind distance: ### (1) Use linear regression with the "segmented" fitting function to simulate ### the different decay rates of tephra thickness within and outside the plume corner. ### (2) Use simple linear regression for the fitting. ### This method will tend to use the segmented fitting option as it is better reconciled with the physics of tephra settling. ### If error occurs, meaning that the data are inappropriate for option(1), a "tryCatch" function is set up to switch to ### option(2). ### Input variables: ### td: the output from function "prep" ### segdist: the inferred breakpoint for distance, this can be estimated by plotting the thickness against distance of the observations. ### segdd: the inferred breakpoint for downwind distance. ### Intermediate functions: ### segfit: segmented fitting function ### simplefit: simple linear regression ### Output variables: ### An object that can be regarded as the fitted model. It contains the fitted values, residuals and the ### coefficients of the fitting. It can be used to predict the trend thickness for the grid and also store the residuals ### for ordinary kriging. ### *** NOTES *** ### The segemented fitting runs iterative processes. Sometimes even with the same "segdist" and "segdd" inputs, it still ### comes up with different breakpoints and consequently slightly different coefficients. Most of the time, such variation ### in the models is negligible, but we still suggest users to be careful when dealing with the segmented fitting. ### The goodness of fit can be examined by printing or plotting the residuals, which are stored in the output. ### If option (1) is being used, the output also contains the values of the breakpoints for the two variables. segfit <-function(segdist, segdd){ ### Segmented fitting function reg.mod <- lm(z~ dist + dd,data=td) seg.lmmodel <- segmented(reg.mod, seg.Z = ~dist + dd, psi = list(dist = c(segdist), dd = c(segdd))) return(seg.lmmodel) } simplefit <-function(){ ### Simple linear regression function reg.mod <- lm(z ~ dist + dd ,data=td) return(reg.mod) } result = tryCatch(segfit(segdist, segdd),error=function(e){simplefit()}) ### TryCatch structure to automatically switch to simple linear regression return(result) ### when error occurs } ###----------------- form.grid <- function(td, cellsize, displacement.coef, expanding.coef){ ### See step (4) in the workflow above ### This function first finds the bounding box of the sample sites. It can be used as the extent of the grid. ### However, sometimes one needs a larger extent. To do that, "displacement.coef" and "expanding.coef" are set. ### "displacement.coef" determines if the lowerleft corner of the bounding box should be further shifted to ### the lower left. "expanding.coef" determines if the length and width of the bouding box should be expanded. ### These two values are all ratios. For example, for a 500*500 squared bounding box, if the 'displacement.coef" ### is set to be 1, then the lowerleft corner (if it was 0,0), will be moved to -500, -500. If the "expanding.coef" ### is set to be 2, then the size of the new bounding box will be 1000*1000. ### Input variables: ### td: the output from function "prep" ### cellsize: cellsize (a single value, as they are squared cells) ### displacement.coef: explained above (a single value) ### expanding.coef: explained above (a single value) ### Output variables: ### An empty grid td.sp <- SpatialPoints(cbind(td$x, td$y)) bbox <- bbox(td.sp) cs <- c(cellsize, cellsize) cc <- as.numeric(ceiling(bbox[,1] + (cs / 2) - diff(t(bbox)) * displacement.coef)) cd <- ceiling(diff(t(bbox)) / cs) * expanding.coef td.temp.grid <- GridTopology(cellcentre.offset = cc, cellsize = cs, cells.dim = cd) td.grid <- SpatialGrid(td.temp.grid) return(td.grid) } ###----------------- trendmodel <- function(td, sv, grid, ang, ftng.rslt){ ### See step (5) in the workflow above ### This function calculates the distances, downwind distances of the cells of the grid, and makes the ### prediction of trend thickness using the model from function "sample.reg". ### Input variables: ### td: the output from function "prep" ### sv: the source vent coordinate ### grid: the output from function "form.grid" ### ang: the inferred wind direction (from north clockwise) ### ftng.rslt: the output from function "sample.reg" ### Output variables: ### A dataframe that contains the coordinates, distances, downwind and crosswind distances, trend thicknesses and ### trend thicknesses in logarithm form for all the cells within the grid. td.grid <- SpatialPoints(as(grid, "SpatialPixels")) td.grid.coord <- coordinates(td.grid) grided<- prep2(sv, td.grid.coord, ang) gridz <- predict(ftng.rslt, data.frame(cbind(dist = grided$dist, dd = grided$dd))) gridrz <- 10^gridz output <- as.data.frame(cbind(grided, gridrz, gridz)) colnames(output) <- c("x", "y", "dist", "dd", "cd", "zr", "z") return(output) } ###----------------- var.read <- function(td, width.val, cutoff.val, var.par, var.model){ ### This function reads the locations of the sample sites and the residuals from the fitting in function "sample.reg" to ### form and fit a variogram model. This function serves as a preparation for ordinary kriging. ### Input variables: ### td: the output from function "prep" ### width.val & cutoff.val: the parameters to calculate the experimental variogram. "width.val" denotes the ### averaged lag for the computation, and "cutoff.val" is the maximum lag that is taken into consideration for the ### calculation. ### var.par: the parameters required for fitting variogram models. It includes three values, namely sill, range, and nugget. ### Detailed explanations of these parameters can be found in any geostatistics reference. ### var.model: a text variable which describes the shape of different variogram models, type the command line "show.vgms()" to view a list ### of variogram models. ### Output variables: ### The output is a list, the first object of the list is the variogram model, which is the main output. ### The second object is the plot of the experimental variogram and the fitted variogram curve. ### The third object is the values of the experimental variogram td.sp <- SpatialPointsDataFrame(cbind(td$x, td$y), td) td.var <- variogram(res ~ 1, td.sp, width=width.val, cutoff = cutoff.val) td.vgm <- vgm(psill=var.par[1], model=var.model, range=var.par[2], nugget=var.par[3]) td.fit <- fit.variogram(td.var, td.vgm, fit.sills = c(TRUE, TRUE)) return(list(td.fit,plot(td.var,td.fit),td.var)) } ###----------------- prediction <- function(td, max, min, maxdist, grid, trend, variog){ ### This function first implements ordinary kriging on the residuals to construct the local variation map, and then ### takes the sum of trend and local variation to present the final result. ### Input variables: ### td: the output from function "prep" ### max: ### min: ### maxdist: ### The "max" and "min" variables describe the maximum and minimum number of observations taken into account ### for the kriging estimation at a single cell. "maxdist" is used to define a maximum radius beyond which the ### sample sites are assumed non-related to a particular cell. ### grid: the output from function "form.grid" ### trend: the output from function "trendmodel" ### variog: the first object of the output from function "var.read" ### Output variables: ### The output is a dataframe that contains the columns of the output of function "trendmodel". In addition to that, ### it also has the predicted thickness and its logarithm, and the variance of kriging estimation. ### Here the variance only represents the variance from kriging the log-residuals of the observations and thus cannot ### be used to characterize the total variance of this method. td.sp <- SpatialPointsDataFrame(cbind(td$x, td$y), td) td.temp.k <- krige(res ~ 1, td.sp, nmax = max, nmin = min, maxdist = maxdist, grid, variog) k.result <- td.temp.k$var1.pred k.result[is.na(k.result)] <- 0 k.variance <- td.temp.k$var1.var k.rz <- 10^(k.result + trend$z) output <- cbind(trend, k.result, k.variance, k.rz) return(output) } ###### End of functions #################################################################################################### ###### Demo ################################################################################################################ setwd("C:\\Users\\working directory") ### Set working directory, "\" has to be replaced by "\\". Change to "/" for *nix, mac. td <- read.table("thickness dataset.csv", header=TRUE, sep=",") ### Read the thickness dataset sv <- read.table("source vent.csv", header=TRUE, sep=",") ### Read source vent location td <- prep(sv, td, 20) ### Calculate the distances, downwind distances, and crosswind distances of the sample sites, ### here the wind direction is 20 degree from north clockwise. model <- sample.reg(td, 3000,3000) ### Form either the segmented or the simple linear regression model of thickness against ### distance and downwind distance. The breakpoints for the two variables are set as ### 3000 and 3000 meters. td$fit <- model$fitted.values ### Expand "td" by storing the fitted values and td$res <- model$residuals ### residuals from the fitting in the last command line grid <- form.grid(td, 500, 0.1, 1.2) ### Form the grid. trend <- trendmodel(td, sv, grid, 20, model) ### Form the trend. Note the wind direction has to be set again for ### the calculation of grid cells, and the two wind directions have to be the same. var <- var.read(td, 300,10000, c(0.04,5000,0.01), "Cir") ### Form the variogram model. The parameters are explained in the ### description of function "var.read" result <- prediction(td, 50,20, 5000, grid,trend, var[[1]]) ### Calculate the local variation, and take its sum and trend thickness for final result. result.sp <- SpatialPixelsDataFrame(cbind(trend$x, trend$y), result) ### Turn the final result into "SpatialPixelsDataFrame" for visualization. spplot(result.sp["k.rz"]) or spplot(result.sp["zr"]) ### Plot the final result or the trend model. levels <- c(0,250,500,1000,2000,3000,5000,10000,20000) ### Set up the levels for plotting the isopach map. isomap <- ContourLines2SLDF(contourLines(as.image.SpatialGridDataFrame(result.sp["k.rz"]), levels = levels)) ### Form the isopach map plot(isomap) ### Plot the isopach map ### Note: "isomap" is a "SpatialLinesDataFrame" and can be used in GIS programs for further mapping purposes. ### Geo-referencing can be done in R or GIS programs. ### ***Notes on infer the extent of tephra fall deposits: ### (1) Add one unit thickness to all the observations and log-transform them. ### (2) Apply these transformed log-thickness to the method ### (3) Specify the "levels <- c(1)" and apply it to "ContourLines2SLDF" function to find the unit thickness isopach ### (4) The resultant contour is the inferred extent. ### *** ### The resultant contour is strongly influenced by the trend model, ### as normally fewer observations are made on the distal and thin parts of a tephra fall deposit ###### End of demo ##########################################################################################################
State Before: α : Type ua β : Type ub γ : Type uc δ : Type ud ι : Sort ?u.50331 inst✝ : UniformSpace α g : Set (α × α) → Filter β f : Filter β hg : Monotone g h : (Filter.lift (𝓤 α) fun s => g (Prod.swap ⁻¹' s)) ≤ f ⊢ Filter.lift (map Prod.swap (𝓤 α)) g ≤ f State After: α : Type ua β : Type ub γ : Type uc δ : Type ud ι : Sort ?u.50331 inst✝ : UniformSpace α g : Set (α × α) → Filter β f : Filter β hg : Monotone g h : (Filter.lift (𝓤 α) fun s => g (Prod.swap ⁻¹' s)) ≤ f ⊢ Filter.lift (𝓤 α) (g ∘ preimage Prod.swap) ≤ f Tactic: rw [map_lift_eq2 hg, image_swap_eq_preimage_swap] State Before: α : Type ua β : Type ub γ : Type uc δ : Type ud ι : Sort ?u.50331 inst✝ : UniformSpace α g : Set (α × α) → Filter β f : Filter β hg : Monotone g h : (Filter.lift (𝓤 α) fun s => g (Prod.swap ⁻¹' s)) ≤ f ⊢ Filter.lift (𝓤 α) (g ∘ preimage Prod.swap) ≤ f State After: no goals Tactic: exact h
import Data.Vect readToBlank : IO (List String) readToBlank = do putStrLn "Enter text (end with a blank line):" line <- getLine if line == "" then pure [] else do lines <- readToBlank pure (line :: lines) readAndSave : IO () readAndSave = do contents <- readToBlank putStrLn "Enter a filename:" fileName <- getLine Right () <- writeFile fileName (unlines contents) | Left err => putStrLn (show err) pure () readVectFileHelper : (file: File) -> IO (Maybe (n ** Vect n String)) readVectFileHelper file = do False <- fEOF file | True => pure (Just (_ ** [])) Right line <- fGetLine file | Left err => pure Nothing Just (_ ** lines)<- readVectFileHelper file | Nothing => pure Nothing pure (Just (_ ** (line :: lines))) readVectFile : (fileName : String) -> IO (n ** Vect n String) readVectFile fileName = do Right file <- openFile fileName Read | Left err => pure (_ ** []) Just vec <- readVectFileHelper file | Nothing => pure (_ ** []) closeFile file pure vec
module Statistics.Information.Discrete.TotalCorrelation where import Data.Matrix import Statistics.Information.Discrete.Entropy import Statistics.Information.Discrete.MutualInfo import Statistics.Information.Utils.Matrix tc :: Eq a => Int -> Matrix a -> Double tc base xs = sum hxs - hx where hxs = [entropy base col | col <- map colVector (columns xs)] hx = entropy base xs ctc :: Eq a => Int -> Matrix a -> Matrix a -> Double ctc base xs ys = sum hxs - hx where hxs = [centropy base col ys | col <- map colVector (columns xs)] hx = centropy base xs ys corex_tcs :: Eq a => Int -> Matrix a -> Matrix a -> Double corex_tcs base xs ys = tc base xs - ctc base xs ys corex_mis :: Eq a => Int -> Matrix a -> Matrix a -> Double corex_mis base xs ys = sum mixs - mi_all where mixs = [mi base col ys | col <- map colVector (columns xs)] mi_all = mi base xs ys residual :: Eq a => Int -> Matrix a -> Double residual base xs = sum $ [hlessxi i | i <- [1..(ncols xs)]] where hlessxi i = centropy base (colVector $ getCol i xs) $ residualMatrix xs i dtc :: Eq a => Int -> Matrix a -> Double dtc base xs = entropy base xs - residual base xs
(* Author: Tobias Nipkow, 2007 *) header "DLO" theory DLO imports QE Complex_Main begin subsection "Basics" class dlo = linorder + assumes dense: "x < z \<Longrightarrow> \<exists>y. x < y \<and> y < z" and no_ub: "\<exists>u. x < u" and no_lb: "\<exists>l. l < x" instance real :: dlo proof fix r s :: real let ?v = "(r + s) / 2" assume "r < s" hence "r < ?v \<and> ?v < s" by simp thus "\<exists>v. r < v \<and> v < s" .. next fix r :: real have "r < r + 1" by arith thus "\<exists>s. r < s" .. next fix r :: real have "r - 1 < r" by arith thus "\<exists>s. s < r" .. qed datatype atom = Less nat nat | Eq nat nat fun is_Less :: "atom \<Rightarrow> bool" where "is_Less (Less i j) = True" | "is_Less f = False" abbreviation "is_Eq \<equiv> Not o is_Less" lemma is_Less_iff: "is_Less a = (\<exists>i j. a = Less i j)" by(cases a) auto lemma is_Eq_iff: "(\<forall>i j. a \<noteq> Less i j) = (\<exists>i j. a = Eq i j)" by(cases a) auto lemma not_is_Eq_iff: "(\<forall>i j. a \<noteq> Eq i j) = (\<exists>i j. a = Less i j)" by(cases a) auto fun neg\<^sub>d\<^sub>l\<^sub>o :: "atom \<Rightarrow> atom fm" where "neg\<^sub>d\<^sub>l\<^sub>o (Less i j) = Or (Atom(Less j i)) (Atom(Eq i j))" | "neg\<^sub>d\<^sub>l\<^sub>o (Eq i j) = Or (Atom(Less i j)) (Atom(Less j i))" fun I\<^sub>d\<^sub>l\<^sub>o :: "atom \<Rightarrow> 'a\<Colon>dlo list \<Rightarrow> bool" where "I\<^sub>d\<^sub>l\<^sub>o (Eq i j) xs = (xs!i = xs!j)" | "I\<^sub>d\<^sub>l\<^sub>o (Less i j) xs = (xs!i < xs!j)" fun depends\<^sub>d\<^sub>l\<^sub>o :: "atom \<Rightarrow> bool" where "depends\<^sub>d\<^sub>l\<^sub>o(Eq i j) = (i=0 | j=0)" | "depends\<^sub>d\<^sub>l\<^sub>o(Less i j) = (i=0 | j=0)" fun decr\<^sub>d\<^sub>l\<^sub>o :: "atom \<Rightarrow> atom" where "decr\<^sub>d\<^sub>l\<^sub>o (Less i j) = Less (i - 1) (j - 1)" | "decr\<^sub>d\<^sub>l\<^sub>o (Eq i j) = Eq (i - 1) (j - 1)" (* needed for code generation *) definition [code del]: "nnf = ATOM.nnf neg\<^sub>d\<^sub>l\<^sub>o" definition [code del]: "qelim = ATOM.qelim depends\<^sub>d\<^sub>l\<^sub>o decr\<^sub>d\<^sub>l\<^sub>o" definition [code del]: "lift_dnf_qe = ATOM.lift_dnf_qe neg\<^sub>d\<^sub>l\<^sub>o depends\<^sub>d\<^sub>l\<^sub>o decr\<^sub>d\<^sub>l\<^sub>o" definition [code del]: "lift_nnf_qe = ATOM.lift_nnf_qe neg\<^sub>d\<^sub>l\<^sub>o" hide_const nnf qelim lift_dnf_qe lift_nnf_qe lemmas DLO_code_lemmas = nnf_def qelim_def lift_dnf_qe_def lift_nnf_qe_def interpretation DLO!: ATOM neg\<^sub>d\<^sub>l\<^sub>o "(\<lambda>a. True)" I\<^sub>d\<^sub>l\<^sub>o depends\<^sub>d\<^sub>l\<^sub>o decr\<^sub>d\<^sub>l\<^sub>o apply(unfold_locales) apply(case_tac a) apply simp_all apply(case_tac a) apply (simp_all add:linorder_class.not_less_iff_gr_or_eq linorder_not_less linorder_neq_iff) apply(case_tac a) apply(simp_all add:nth_Cons') done lemmas [folded DLO_code_lemmas, code] = DLO.nnf.simps DLO.qelim_def DLO.lift_dnf_qe.simps DLO.lift_dnf_qe.simps setup {* Sign.revert_abbrev "" @{const_abbrev DLO.I} *} definition lbounds where "lbounds as = [i. Less (Suc i) 0 \<leftarrow> as]" definition ubounds where "ubounds as = [i. Less 0 (Suc i) \<leftarrow> as]" definition ebounds where "ebounds as = [i. Eq (Suc i) 0 \<leftarrow> as] @ [i. Eq 0 (Suc i) \<leftarrow> as]" lemma set_lbounds: "set(lbounds as) = {i. Less (Suc i) 0 : set as}" by(auto simp: lbounds_def split:nat.splits atom.splits) lemma set_ubounds: "set(ubounds as) = {i. Less 0 (Suc i) : set as}" by(auto simp: ubounds_def split:nat.splits atom.splits) lemma set_ebounds: "set(ebounds as) = {k. Eq (Suc k) 0 : set as \<or> Eq 0 (Suc k) : set as}" by(auto simp: ebounds_def split: atom.splits nat.splits) abbreviation "LB f xs \<equiv> {xs!i|i. Less (Suc i) 0 : set(DLO.atoms\<^sub>0 f)}" abbreviation "UB f xs \<equiv> {xs!i|i. Less 0 (Suc i) : set(DLO.atoms\<^sub>0 f)}" definition "EQ f xs = {xs!k|k. Eq (Suc k) 0 : set(DLO.atoms\<^sub>0 f) \<or> Eq 0 (Suc k) : set(DLO.atoms\<^sub>0 f)}" lemma EQ_And[simp]: "EQ (And f g) xs = (EQ f xs Un EQ g xs)" by(auto simp:EQ_def) lemma EQ_Or[simp]: "EQ (Or f g) xs = (EQ f xs Un EQ g xs)" by(auto simp:EQ_def) lemma EQ_conv_set_ebounds: "x \<in> EQ f xs = (\<exists>e\<in>set(ebounds(DLO.atoms\<^sub>0 f)). x = xs!e)" by(auto simp: EQ_def set_ebounds) fun isubst where "isubst k 0 = k" | "isubst k (Suc i) = i" fun asubst :: "nat \<Rightarrow> atom \<Rightarrow> atom" where "asubst k (Less i j) = Less (isubst k i) (isubst k j)"| "asubst k (Eq i j) = Eq (isubst k i) (isubst k j)" abbreviation "subst \<phi> k \<equiv> map\<^bsub>fm\<^esub> (asubst k) \<phi>" lemma I_subst: "qfree f \<Longrightarrow> DLO.I (subst f k) xs = DLO.I f (xs!k # xs)" apply(induct f) apply(simp_all) apply(rename_tac a) apply(case_tac a) apply(simp_all add:nth.simps split:nat.splits) done fun amin_inf :: "atom \<Rightarrow> atom fm" where "amin_inf (Less _ 0) = FalseF" | "amin_inf (Less 0 _) = TrueF" | "amin_inf (Less (Suc i) (Suc j)) = Atom(Less i j)" | "amin_inf (Eq 0 0) = TrueF" | "amin_inf (Eq 0 _) = FalseF" | "amin_inf (Eq _ 0) = FalseF" | "amin_inf (Eq (Suc i) (Suc j)) = Atom(Eq i j)" abbreviation min_inf :: "atom fm \<Rightarrow> atom fm" ("inf\<^sub>-") where "inf\<^sub>- \<equiv> amap\<^bsub>fm\<^esub> amin_inf" fun aplus_inf :: "atom \<Rightarrow> atom fm" where "aplus_inf (Less 0 _) = FalseF" | "aplus_inf (Less _ 0) = TrueF" | "aplus_inf (Less (Suc i) (Suc j)) = Atom(Less i j)" | "aplus_inf (Eq 0 0) = TrueF" | "aplus_inf (Eq 0 _) = FalseF" | "aplus_inf (Eq _ 0) = FalseF" | "aplus_inf (Eq (Suc i) (Suc j)) = Atom(Eq i j)" abbreviation plus_inf :: "atom fm \<Rightarrow> atom fm" ("inf\<^sub>+") where "inf\<^sub>+ \<equiv> amap\<^bsub>fm\<^esub> aplus_inf" lemma min_inf: "nqfree f \<Longrightarrow> \<exists>x. \<forall>y\<le>x. DLO.I (inf\<^sub>- f) xs = DLO.I f (y # xs)" (is "_ \<Longrightarrow> \<exists>x. ?P f x") proof(induct f) case (Atom a) show ?case proof (cases a rule: amin_inf.cases) case 1 thus ?thesis by(auto simp add:nth_Cons' linorder_not_less) next case 2 thus ?thesis by (simp) (metis no_lb linorder_not_less order_less_le_trans) next case 5 thus ?thesis by(simp add:nth_Cons') (metis no_lb linorder_not_less) next case 6 thus ?thesis by simp (metis no_lb linorder_not_less) qed simp_all next case (And f1 f2) then obtain x1 x2 where "?P f1 x1" "?P f2 x2" by fastforce+ hence "?P (And f1 f2) (min x1 x2)" by(force simp:and_def) thus ?case .. next case (Or f1 f2) then obtain x1 x2 where "?P f1 x1" "?P f2 x2" by fastforce+ hence "?P (Or f1 f2) (min x1 x2)" by(force simp:or_def) thus ?case .. qed simp_all lemma plus_inf: "nqfree f \<Longrightarrow> \<exists>x.\<forall>y\<ge>x. DLO.I (inf\<^sub>+ f) xs = DLO.I f (y # xs)" (is "_ \<Longrightarrow> \<exists>x. ?P f x") proof (induct f) have dlo_bound: "\<And>z::'a. \<exists>x. \<forall>y\<ge>x. y > z" proof - fix z from no_ub obtain w :: 'a where "w > z" .. then have "\<forall>y\<ge>w. y > z" by auto then show "?thesis z" .. qed case (Atom a) show ?case proof (cases a rule: aplus_inf.cases) case 1 thus ?thesis by (simp add: nth_Cons') (metis linorder_not_less) next case 2 thus ?thesis by (auto intro: dlo_bound) next case 5 thus ?thesis by simp (metis dlo_bound less_imp_neq) next case 6 thus ?thesis by simp (metis dlo_bound less_imp_neq) qed simp_all next case (And f1 f2) then obtain x1 x2 where "?P f1 x1" "?P f2 x2" by fastforce+ hence "?P (And f1 f2) (max x1 x2)" by(force simp:and_def) thus ?case .. next case (Or f1 f2) then obtain x1 x2 where "?P f1 x1" "?P f2 x2" by fastforce+ hence "?P (Or f1 f2) (max x1 x2)" by(force simp:or_def) thus ?case .. qed simp_all declare[[simp_depth_limit=2]] lemma LBex: "\<lbrakk> nqfree f; DLO.I f (x#xs); \<not>DLO.I (inf\<^sub>- f) xs; x \<notin> EQ f xs \<rbrakk> \<Longrightarrow> \<exists>l\<in> LB f xs. l < x" proof(induct f) case (Atom a) thus ?case by (cases a rule: amin_inf.cases) (simp_all add: nth.simps EQ_def split: nat.splits) qed auto lemma UBex: "\<lbrakk> nqfree f; DLO.I f (x#xs); \<not>DLO.I (inf\<^sub>+ f) xs; x \<notin> EQ f xs \<rbrakk> \<Longrightarrow> \<exists>u \<in> UB f xs. x < u" proof(induct f) case (Atom a) thus ?case by (cases a rule: aplus_inf.cases) (simp_all add: nth.simps EQ_def split: nat.splits) qed auto declare[[simp_depth_limit=50]] lemma finite_LB: "finite(LB f xs)" proof - have "LB f xs = (\<lambda>k. xs!k) ` set(lbounds(DLO.atoms\<^sub>0 f))" by (auto simp:set_lbounds image_def) thus ?thesis by simp qed lemma finite_UB: "finite(UB f xs)" proof - have "UB f xs = (\<lambda>k. xs!k) ` set(ubounds(DLO.atoms\<^sub>0 f))" by (auto simp:set_ubounds image_def) thus ?thesis by simp qed lemma qfree_amin_inf: "qfree (amin_inf a)" by(cases a rule:amin_inf.cases) simp_all lemma qfree_min_inf: "nqfree \<phi> \<Longrightarrow> qfree(inf\<^sub>- \<phi>)" by(induct \<phi>)(simp_all add:qfree_amin_inf) lemma qfree_aplus_inf: "qfree (aplus_inf a)" by(cases a rule:aplus_inf.cases) simp_all lemma qfree_plus_inf: "nqfree \<phi> \<Longrightarrow> qfree(inf\<^sub>+ \<phi>)" by(induct \<phi>)(simp_all add:qfree_aplus_inf) end
Require Import Coq.Arith.EqNat. Require Import Coq.Relations.Relations. Require Import compcert.exportclight.Clightdefs. Require Import compcert.lib.Axioms. Require Import compcert.lib.Coqlib. Require Import compcert.lib.Integers. Require Import compcert.lib.Floats. Require Import compcert.lib.Maps. Require Import compcert.common.AST. Require Import compcert.common.Values. Require Import compcert.common.Memdata. Require Import compcert.common.Memtype. Require Import compcert.common.Memory. Require Export sepcomp.Address. Lemma range_dec: forall a b c: Z, {a <= b < c}+{~(a <= b < c)}. Proof. intros. destruct (zle a b). destruct (zlt b c). left; split; auto. right; omega. right; omega. Qed. Require Export msl.eq_dec. Instance EqDec_ident: EqDec ident := ident_eq. Instance EqDec_byte: EqDec byte := Byte.eq_dec. Instance EqDec_type: EqDec type := type_eq. Instance EqDec_int: EqDec int := Int.eq_dec. Instance EqDec_int64: EqDec int64 := Int64.eq_dec. Instance EqDec_float: EqDec float := Float.eq_dec. Instance EqDec_float32: EqDec float32 := Float32.eq_dec. Instance EqDec_memval: EqDec memval. Proof. hnf; repeat decide equality; apply eq_dec. Defined. Instance EqDec_val: EqDec val. Proof. hnf. decide equality; apply eq_dec. Defined. Instance EqDec_quantity: EqDec quantity. Proof. hnf. decide equality. Defined. Definition access_at (m: mem) (loc: address) (k: perm_kind): option permission := PMap.get (fst loc) (Mem.mem_access m) (snd loc) k. Lemma perm_access: forall m b ofs k p, Mem.perm m b ofs k p <-> (Mem.perm_order'' (access_at m (b,ofs) k) (Some p)). Proof. reflexivity. Qed. Lemma access_perm: forall m b ofs k p, access_at m (b, ofs) k = Some p -> Mem.perm m b ofs k p. Proof. intros. unfold Mem.perm, Mem.perm_order'. unfold access_at in H. simpl in H. rewrite H; auto. constructor. Qed. Lemma access_cur_max: forall m a, Mem.perm_order'' (access_at m a Max) (access_at m a Cur). Proof. destruct a as [b z]. destruct (access_at m (b,z) Cur) eqn:Hc. rewrite <- perm_access. apply (Mem.perm_cur_max m b z). rewrite perm_access. rewrite Hc. constructor. destruct (access_at m (b, z) Max); constructor. Qed. Lemma invalid_noaccess: forall m b ofs k, ~Mem.valid_block m b -> access_at m (b, ofs) k = None. Proof. intros; apply Mem.nextblock_noaccess. assumption. Qed. Lemma access_empty: forall a k, access_at Mem.empty a k = None. Proof. intros. unfold access_at, Mem.empty; simpl. rewrite PMap.gi. reflexivity. Qed. Transparent Mem.alloc. Theorem alloc_access_other: forall m1 lo hi m2 b, Mem.alloc m1 lo hi = (m2, b) -> forall b' ofs k, b'<>b \/ (ofs < lo \/ ofs >= hi) -> access_at m1 (b', ofs) k = access_at m2 (b', ofs) k. Proof. intros. pose proof (Mem.nextblock_noaccess m1 b ofs k). pose proof (Mem.alloc_result _ _ _ _ _ H). unfold access_at; inversion H; clear H; subst; simpl. destruct (eq_block b' (Mem.nextblock m1)). destruct H0; try contradiction. subst b'. rewrite PMap.gss. destruct (zle lo ofs), (zlt ofs hi); try omega; simpl; apply H1; apply Plt_strict. rewrite PMap.gso by auto. auto. Qed. Theorem alloc_access_same: forall m1 lo hi m2 b, Mem.alloc m1 lo hi = (m2, b) -> forall ofs k, lo <= ofs < hi -> access_at m2 (b,ofs) k = Some Freeable. Proof. intros. inversion H; clear H; subst. unfold access_at; simpl. rewrite PMap.gss. destruct (zle lo ofs), (zlt ofs hi); try omega; simpl; auto. Qed. Opaque Mem.alloc. Transparent Mem.free. Lemma access_free: forall m1 b lo hi, (forall ofs, lo <= ofs < hi -> access_at m1 (b,ofs) Cur = Some Freeable) -> { m2: mem | Mem.free m1 b lo hi = Some m2 }. Proof. intros. unfold Mem.free. destruct (Mem.range_perm_dec m1 b lo hi Cur Freeable). eauto. contradiction n; clear n. hnf; intros. unfold Mem.perm. unfold access_at in H. simpl in H; rewrite H by auto. constructor. Qed. Lemma free_access: forall m1 b lo hi m2, Mem.free m1 b lo hi = Some m2 -> (forall ofs, lo <= ofs < hi -> access_at m1 (b,ofs) Cur = Some Freeable /\ access_at m2 (b,ofs) Max = None). Proof. intros. unfold Mem.free in H. destruct (Mem.range_perm_dec m1 b lo hi Cur Freeable); inversion H; clear H; subst. specialize (r _ H0). hnf in r. unfold access_at. simpl. destruct ((Mem.mem_access m1) !! b ofs Cur); try contradiction. assert (p=Freeable) by (destruct p; inversion r; auto). subst p. split; auto. simpl. rewrite PMap.gss. destruct (zle lo ofs), (zlt ofs hi); try omega. reflexivity. Qed. Lemma free_access_other: forall m1 bf lo hi m2, Mem.free m1 bf lo hi = Some m2 -> forall b ofs k, b <> bf \/ ofs < lo \/ hi <= ofs -> access_at m1 (b,ofs) k = access_at m2 (b,ofs) k. Proof. intros. unfold Mem.free in H. destruct (Mem.range_perm_dec m1 bf lo hi Cur Freeable); inversion H; clear H; subst. unfold access_at; simpl. destruct (eq_block b bf). subst bf; rewrite PMap.gss. destruct H0. contradiction H; auto. destruct (zle lo ofs), (zlt ofs hi); try omega; simpl; auto. rewrite PMap.gso by auto. reflexivity. Qed. Opaque Mem.free. Lemma access_drop_1: forall m b lo hi p m', Mem.drop_perm m b lo hi p = Some m' -> (forall ofs, lo <= ofs < hi -> forall k, access_at m (b, ofs) k = Some Freeable /\ access_at m' (b, ofs) k = Some p). Proof. intros. unfold Mem.drop_perm in H. destruct (Mem.range_perm_dec m b lo hi Cur Freeable); inversion H; clear H; subst. unfold access_at; simpl. rewrite PMap.gss. destruct (zle lo ofs), (zlt ofs hi); try omega; simpl; auto. split; auto. specialize (r _ H0). hnf in r. destruct ( (Mem.mem_access m) !! b ofs Cur) eqn:?; try contradiction. assert (p0=Freeable) by (destruct p0; inv r; auto). subst. pose proof (Mem.access_max m b ofs). rewrite Heqo in H. destruct k; auto. destruct ((Mem.mem_access m) !! b ofs Max); inv H; auto. Qed. Lemma access_drop_2: forall m b lo hi p, (forall ofs, lo <= ofs < hi -> access_at m (b,ofs) Cur = Some Freeable) -> { m' | Mem.drop_perm m b lo hi p = Some m' }. Proof. intros. unfold Mem.drop_perm. destruct (Mem.range_perm_dec m b lo hi Cur Freeable). eauto. contradiction n; hnf; intros. specialize (H _ H0). unfold access_at in *. hnf. simpl in *; rewrite H. constructor. Qed. Lemma access_drop_3: forall m b lo hi p m', Mem.drop_perm m b lo hi p = Some m' -> forall b' ofs k, b' <> b \/ ofs < lo \/ hi <= ofs -> access_at m (b', ofs) k = access_at m' (b',ofs) k. Proof. intros. unfold Mem.drop_perm in H. destruct (Mem.range_perm_dec m b lo hi Cur Freeable); inversion H; clear H; subst. unfold access_at; simpl. destruct (eq_block b' b). subst. rewrite PMap.gss. destruct H0. contradiction H; auto. destruct (zle lo ofs), (zlt ofs hi); try omega; simpl; auto. rewrite PMap.gso by auto. auto. Qed. Lemma storebytes_access: forall m1 b ofs bytes m2 (STORE: Mem.storebytes m1 b ofs bytes = Some m2), access_at m1 = access_at m2. Proof. intros. apply extensionality ;intros [b' z]. apply extensionality ;intro k. apply Mem.storebytes_access in STORE. unfold access_at; f_equal; auto. Qed. Lemma store_access: forall chunk m1 b ofs v m2 (STORE: Mem.store chunk m1 b ofs v = Some m2), access_at m1 = access_at m2. Proof. intros. apply extensionality; intros [b' z']. apply extensionality ;intro k. unfold access_at. apply Mem.store_access in STORE. rewrite STORE; auto. Qed. Lemma perm_order'_dec_fiddle: forall y x, y = Some x -> proj_sumbool (Mem.perm_order'_dec y Nonempty) = true. Proof. intros. subst. simpl. unfold Mem.perm_order_dec. destruct x; reflexivity. Qed. Lemma access_at_valid_pointer: forall m b ofs p, access_at m (b,ofs) Cur = Some p -> Mem.valid_pointer m b ofs = true. Proof. intros. unfold access_at, Mem.valid_pointer in *. simpl in *. apply perm_order'_dec_fiddle with p. auto. Qed.
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.hom.aut import logic.function.basic import group_theory.subgroup.basic /-! # Semidirect product > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines semidirect products of groups, and the canonical maps in and out of the semidirect product. The semidirect product of `N` and `G` given a hom `φ` from `G` to the automorphism group of `N` is the product of sets with the group `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` ## Key definitions There are two homs into the semidirect product `inl : N →* N ⋊[φ] G` and `inr : G →* N ⋊[φ] G`, and `lift` can be used to define maps `N ⋊[φ] G →* H` out of the semidirect product given maps `f₁ : N →* H` and `f₂ : G →* H` that satisfy the condition `∀ n g, f₁ (φ g n) = f₂ g * f₁ n * f₂ g⁻¹` ## Notation This file introduces the global notation `N ⋊[φ] G` for `semidirect_product N G φ` ## Tags group, semidirect product -/ variables (N : Type*) (G : Type*) {H : Type*} [group N] [group G] [group H] /-- The semidirect product of groups `N` and `G`, given a map `φ` from `G` to the automorphism group of `N`. It the product of sets with the group operation `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` -/ @[ext, derive decidable_eq] structure semidirect_product (φ : G →* mul_aut N) := (left : N) (right : G) attribute [pp_using_anonymous_constructor] semidirect_product notation N` ⋊[`:35 φ:35`] `:0 G :35 := semidirect_product N G φ namespace semidirect_product variables {N G} {φ : G →* mul_aut N} instance : group (N ⋊[φ] G) := { one := ⟨1, 1⟩, mul := λ a b, ⟨a.1 * φ a.2 b.1, a.2 * b.2⟩, inv := λ x, ⟨φ x.2⁻¹ x.1⁻¹, x.2⁻¹⟩, mul_assoc := λ a b c, by ext; simp [mul_assoc], one_mul := λ a, ext _ _ (by simp) (one_mul a.2), mul_one := λ a, ext _ _ (by simp) (mul_one _), mul_left_inv := λ ⟨a, b⟩, ext _ _ (show φ b⁻¹ a⁻¹ * φ b⁻¹ a = 1, by simp) (mul_left_inv b) } instance : inhabited (N ⋊[φ] G) := ⟨1⟩ @[simp] lemma one_left : (1 : N ⋊[φ] G).left = 1 := rfl @[simp] lemma one_right : (1 : N ⋊[φ] G).right = 1 := rfl @[simp] lemma inv_left (a : N ⋊[φ] G) : (a⁻¹).left = φ a.right⁻¹ a.left⁻¹ := rfl @[simp] lemma inv_right (a : N ⋊[φ] G) : (a⁻¹).right = a.right⁻¹ := rfl @[simp] lemma mul_left (a b : N ⋊[φ] G) : (a * b).left = a.left * φ a.right b.left := rfl @[simp] lemma mul_right (a b : N ⋊[φ] G) : (a * b).right = a.right * b.right := rfl /-- The canonical map `N →* N ⋊[φ] G` sending `n` to `⟨n, 1⟩` -/ def inl : N →* N ⋊[φ] G := { to_fun := λ n, ⟨n, 1⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inl (n : N) : (inl n : N ⋊[φ] G).left = n := rfl @[simp] lemma right_inl (n : N) : (inl n : N ⋊[φ] G).right = 1 := rfl lemma inl_injective : function.injective (inl : N → N ⋊[φ] G) := function.injective_iff_has_left_inverse.2 ⟨left, left_inl⟩ @[simp] lemma inl_inj {n₁ n₂ : N} : (inl n₁ : N ⋊[φ] G) = inl n₂ ↔ n₁ = n₂ := inl_injective.eq_iff /-- The canonical map `G →* N ⋊[φ] G` sending `g` to `⟨1, g⟩` -/ def inr : G →* N ⋊[φ] G := { to_fun := λ g, ⟨1, g⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inr (g : G) : (inr g : N ⋊[φ] G).left = 1 := rfl @[simp] lemma right_inr (g : G) : (inr g : N ⋊[φ] G).right = g := rfl lemma inr_injective : function.injective (inr : G → N ⋊[φ] G) := function.injective_iff_has_left_inverse.2 ⟨right, right_inr⟩ @[simp] lemma inr_inj {g₁ g₂ : G} : (inr g₁ : N ⋊[φ] G) = inr g₂ ↔ g₁ = g₂ := inr_injective.eq_iff lemma inl_aut (g : G) (n : N) : (inl (φ g n) : N ⋊[φ] G) = inr g * inl n * inr g⁻¹ := by ext; simp lemma inl_aut_inv (g : G) (n : N) : (inl ((φ g)⁻¹ n) : N ⋊[φ] G) = inr g⁻¹ * inl n * inr g := by rw [← monoid_hom.map_inv, inl_aut, inv_inv] @[simp] @[simp] lemma inl_left_mul_inr_right (x : N ⋊[φ] G) : inl x.left * inr x.right = x := by ext; simp /-- The canonical projection map `N ⋊[φ] G →* G`, as a group hom. -/ def right_hom : N ⋊[φ] G →* G := { to_fun := semidirect_product.right, map_one' := rfl, map_mul' := λ _ _, rfl } @[simp] lemma right_hom_eq_right : (right_hom : N ⋊[φ] G → G) = right := rfl @[simp] lemma right_hom_comp_inl : (right_hom : N ⋊[φ] G →* G).comp inl = 1 := by ext; simp [right_hom] @[simp] lemma right_hom_comp_inr : (right_hom : N ⋊[φ] G →* G).comp inr = monoid_hom.id _ := by ext; simp [right_hom] @[simp] lemma right_hom_inl (n : N) : right_hom (inl n : N ⋊[φ] G) = 1 := by simp [right_hom] @[simp] lemma right_hom_inr (g : G) : right_hom (inr g : N ⋊[φ] G) = g := by simp [right_hom] lemma right_hom_surjective : function.surjective (right_hom : N ⋊[φ] G → G) := function.surjective_iff_has_right_inverse.2 ⟨inr, right_hom_inr⟩ lemma range_inl_eq_ker_right_hom : (inl : N →* N ⋊[φ] G).range = right_hom.ker := le_antisymm (λ _, by simp [monoid_hom.mem_ker, eq_comm] {contextual := tt}) (λ x hx, ⟨x.left, by ext; simp [*, monoid_hom.mem_ker] at *⟩) section lift variables (f₁ : N →* H) (f₂ : G →* H) (h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) /-- Define a group hom `N ⋊[φ] G →* H`, by defining maps `N →* H` and `G →* H` -/ def lift (f₁ : N →* H) (f₂ : G →* H) (h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) : N ⋊[φ] G →* H := { to_fun := λ a, f₁ a.1 * f₂ a.2, map_one' := by simp, map_mul' := λ a b, begin have := λ n g, monoid_hom.ext_iff.1 (h n) g, simp only [mul_aut.conj_apply, monoid_hom.comp_apply, mul_equiv.coe_to_monoid_hom] at this, simp [this, mul_assoc] end } @[simp] lemma lift_inl (n : N) : lift f₁ f₂ h (inl n) = f₁ n := by simp [lift] @[simp] lemma lift_comp_inl : (lift f₁ f₂ h).comp inl = f₁ := by ext; simp @[simp] lemma lift_inr (g : G) : lift f₁ f₂ h (inr g) = f₂ g := by simp [lift] @[simp] lemma lift_comp_inr : (lift f₁ f₂ h).comp inr = f₂ := by ext; simp lemma lift_unique (F : N ⋊[φ] G →* H) : F = lift (F.comp inl) (F.comp inr) (λ _, by ext; simp [inl_aut]) := begin ext, simp only [lift, monoid_hom.comp_apply, monoid_hom.coe_mk], rw [← F.map_mul, inl_left_mul_inr_right], end /-- Two maps out of the semidirect product are equal if they're equal after composition with both `inl` and `inr` -/ lemma hom_ext {f g : (N ⋊[φ] G) →* H} (hl : f.comp inl = g.comp inl) (hr : f.comp inr = g.comp inr) : f = g := by { rw [lift_unique f, lift_unique g], simp only * } end lift section map variables {N₁ : Type*} {G₁ : Type*} [group N₁] [group G₁] {φ₁ : G₁ →* mul_aut N₁} /-- Define a map from `N ⋊[φ] G` to `N₁ ⋊[φ₁] G₁` given maps `N →* N₁` and `G →* G₁` that satisfy a commutativity condition `∀ n g, f₁ (φ g n) = φ₁ (f₂ g) (f₁ n)`. -/ def map (f₁ : N →* N₁) (f₂ : G →* G₁) (h : ∀ g : G, f₁.comp (φ g).to_monoid_hom = (φ₁ (f₂ g)).to_monoid_hom.comp f₁) : N ⋊[φ] G →* N₁ ⋊[φ₁] G₁ := { to_fun := λ x, ⟨f₁ x.1, f₂ x.2⟩, map_one' := by simp, map_mul' := λ x y, begin replace h := monoid_hom.ext_iff.1 (h x.right) y.left, ext; simp * at *, end } variables (f₁ : N →* N₁) (f₂ : G →* G₁) (h : ∀ g : G, f₁.comp (φ g).to_monoid_hom = (φ₁ (f₂ g)).to_monoid_hom.comp f₁) @[simp] lemma map_left (g : N ⋊[φ] G) : (map f₁ f₂ h g).left = f₁ g.left := rfl @[simp] lemma map_right (g : N ⋊[φ] G) : (map f₁ f₂ h g).right = f₂ g.right := rfl @[simp] lemma right_hom_comp_map : right_hom.comp (map f₁ f₂ h) = f₂.comp right_hom := rfl @[simp] lemma map_inl (n : N) : map f₁ f₂ h (inl n) = inl (f₁ n) := by simp [map] @[simp] lemma map_comp_inl : (map f₁ f₂ h).comp inl = inl.comp f₁ := by ext; simp @[simp] lemma map_inr (g : G) : map f₁ f₂ h (inr g) = inr (f₂ g) := by simp [map] @[simp] lemma map_comp_inr : (map f₁ f₂ h).comp inr = inr.comp f₂ := by ext; simp [map] end map end semidirect_product
module Main import System import System.File import Control.Monad.Either import Data.List import Common import Parser import Solutions.Day1 import Solutions.Day2 data Env = Run | Test -- Read the contents of the input file as a string getInput : Env -> (day : String) -> EitherT String IO String getInput env day = do let filename = case env of Run => "./inputs/day" ++ day ++".txt" Test => "./inputs/day" ++ day ++"_test.txt" input <- readFile filename case input of Right output => right output Left err => left . show $ "Could not find: \{filename}" getSolution : (day : String) -> EitherT String IO Solution getSolution day = case day of "1" => right Day1.run "2" => right Day2.run _ => left "No solution found for this day" displaySolution : (solution : Either String (String, String)) -> String displaySolution (Left err) = err displaySolution (Right (part1, part2)) = "\nPart1:\n" ++ part1 ++ "\n\nPart2:\n" ++ part2 ++ "\n" runProgram : Env -> (day : String) -> EitherT String IO String runProgram env day = do input <- getInput env day solution <- getSolution day pure . displaySolution . solution $ input getDayNumber : IO (Maybe String) getDayNumber = map (tail' >=> head') getArgs doProgram : Show day => Env -> day -> IO () doProgram env day = do Right result <- runEitherT (runProgram env (show day)) | Left err => putStrLn err putStr result -- This is extracted here to make running from the repl easier run : Show day => day -> IO () run = doProgram Run -- This is extracted here to make running from the repl easier test : Show day => day -> IO () test = doProgram Test main : IO () main = do Just day <- getDayNumber | Nothing => putStrLn "Please enter a day number" run day
input := FileTools:-Text:-ReadFile("AoC-2021-5-input.txt" ): lines:=map(l->[[parse(l[1])],[parse(l[-1])]], {op(map(StringTools:-Split, StringTools:-Split(input,"\n"), "->"))}): pointcounts1 := table(sparse=0): pointcounts2 := table(sparse=0): for l in lines do step := signum~(l[2] - l[1]); ls := l[1]; pointcounts2[op(ls)] += 1; if 0 in step then pointcounts1[op(ls)] += 1; end if; while ls <> l[2] do ls := ls + step; pointcounts2[op(ls)] += 1; if 0 in step then pointcounts1[op(ls)] += 1; end if; end do; end do: answer1:=nops(select(i->i>1,[entries(pointcounts1, nolist)])); answer2:=nops(select(i->i>1,[entries(pointcounts2, nolist)])); # Visualization # just the lines plots:-display(seq(plottools:-line(l[], thickness=0.01),l in lines)); # fancy hotspots rng := [min,max](entries(pointcounts2,nolist)); colors := [ColorTools:-Color("CVD 8"),ColorTools:-Gradient("CVD 2".."CVD 9", number=rng[2]-rng[1]-2)[]]; epc := [seq(Array(map([lhs], select(p->rhs(p)=i,[entries(pointcounts2,pairs)]))),i=rng[1]..rng[2])]: plots:-display( seq(plottools:-point(epc[i], symbol=solidcircle, color=colors[i], symbolsize=i),i=rng[1]..rng[2] ), size=[5000,5000], axes=none, background="Black");
function plotData(X, y) %PLOTDATA Plots the data points X and y into a new figure % PLOTDATA(x,y) plots the data points with + for the positive examples % and o for the negative examples. X is assumed to be a Mx2 matrix. % Create New Figure figure; hold on; % ====================== YOUR CODE HERE ====================== % Instructions: Plot the positive and negative examples on a % 2D plot, using the option 'k+' for the positive % examples and 'ko' for the negative examples. % % Find indices of positive and negative examples pos = find(y==1); neg = find(y==0); % Plot examples plot(X(pos,1), X(pos,2), 'r+', 'LineWidth', 2, 'MarkerSize', 7); plot(X(neg,1), X(neg,2), 'ko', 'MarkerFaceColor', 'yellow', 'MarkerSize', 7); % ========================================================================= hold off; end
State Before: α : Type u_2 β : Type u_1 γ : Type ?u.848051 δ : Type ?u.848054 m : MeasurableSpace α μ ν : Measure α inst✝² : MeasurableSpace δ inst✝¹ : NormedAddCommGroup β inst✝ : NormedAddCommGroup γ f : α → β c : ℝ≥0∞ h₁ : c ≠ 0 h₂ : c ≠ ⊤ h : Integrable f ⊢ Integrable f State After: no goals Tactic: simpa only [smul_smul, ENNReal.inv_mul_cancel h₁ h₂, one_smul] using h.smul_measure (ENNReal.inv_ne_top.2 h₁)
\subsection*{Outline} \begin{itemize} \item Intial description: Cohort size, demographics, data types \item Basic analysis: Summary statistics, ordinations, permanovas, mantel tests \item Exploration of taxonomic profiles + cogscores / brain, cross-sectional. Linear models. \hl{Is this necessary??} \item Try HAllA on multivariate data? \item Predictive model (RF) - taxonomic profiles + cogscores. \item Taxonomic profiles + brain structure \item Gene functions + metabolomes \end{itemize}
State Before: α : Type u_1 s t : Set α a : α inst✝ : InvolutiveStar α ⊢ a⋆ ∈ s⋆ ↔ a ∈ s State After: no goals Tactic: simp only [mem_star, star_star]
// SLHAea - containers for SUSY Les Houches Accord input/output // Copyright © 2009-2010 Frank S. Thomas <[email protected]> // // 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) #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp>
Require Import VST.floyd.proofauto. Require Import VST.floyd.assoclists. Require Import VST.floyd.VSU. Require Import VST.veric.initial_world. Lemma find_id_delete_id {A} {lp p: list (ident *A)} {i j a} (IJ: i <> j): delete_id j lp = Some (a, p) -> find_id i lp = find_id i p. Proof. intros. apply delete_id_elim in H. destruct H. rewrite <- (firstn_skipn x p); subst. rewrite 2 find_id_app_char; simpl. rewrite if_false; trivial. Qed. Lemma find_id_delete_id2 {A i} {lp: list (ident *A)}: forall {p j a}, delete_id j lp = Some (a, p) -> list_norepet (map fst lp) -> find_id i lp = if ident_eq i j then Some a else find_id i p. Proof. induction lp; simpl; intros. inv H. inv H0. destruct a as [k a]. if_tac; subst; simpl in *. + if_tac; subst. - rewrite if_true in H;[ inv H |]; trivial. - rewrite if_false in H by intuition. remember (delete_id j lp) as u; symmetry in Hequ; destruct u; try discriminate. destruct p0. inv H; simpl. rewrite if_true; trivial. + if_tac; subst. - rewrite if_false in H by trivial. remember (delete_id j lp) as u; symmetry in Hequ; destruct u; try discriminate. destruct p0. inv H. specialize (IHlp _ _ _ Hequ H4). rewrite if_true in IHlp; trivial. - if_tac in H. inv H; trivial. remember (delete_id j lp) as u; symmetry in Hequ; destruct u; try discriminate. destruct p0. inv H. simpl. rewrite if_false by trivial. specialize (IHlp _ _ _ Hequ H4). rewrite if_false in IHlp; trivial. Qed. Section ADD_MAIN. Variable Espec: OracleKind. Variable coreV: varspecs. Variable coreCS: compspecs. Variable coreE: funspecs. Notation coreImports:= (@nil (ident * funspec)). (*nil - we're only linking main if this yields a full prog*) Variable p: Clight.program. Variable coreExports: funspecs. Variable coreGP: globals -> mpred. Variable CoreVSU: @CanonicalVSU Espec coreV coreCS coreE coreImports p coreExports coreGP. Variable lp: Clight.program. Variable CS: compspecs. Variable CSSUB: cspecs_sub coreCS CS. Variable main:ident. Variable mainspec: funspec. Variable mainFun : function. Variable MainFresh : find_id main (prog_defs p) = None. Variable P_LP: delete_id main (prog_funct lp) = Some (Internal mainFun, prog_funct p). Variable LNR_LP : list_norepet (map fst (prog_defs lp)). Definition LNR_Funs:= LNR_progdefs_progfunct LNR_LP. Lemma Main i: find_id i (prog_funct lp) = if ident_eq i main then Some (Internal mainFun) else find_id i (prog_funct p). Proof. apply find_id_delete_id2; [trivial | apply LNR_Funs]. Qed. Definition CoreG := G_of_CanonicalVSU CoreVSU. Definition linked_internal_specs := SortFunspec.sort (filter (fun a => in_dec ident_eq (fst a) (IntIDs lp)) ((*main_spec main lp*)(main,mainspec) :: CoreG)). Variable Vprog: varspecs. Variable LNR_Vprog: list_norepet (map fst Vprog). Variable disjoint_Vprog_lpfuns: list_disjoint (map fst Vprog) (map fst (prog_funct lp)). Variable coreV_in_Vprog: forall {i phi}, find_id i coreV = Some phi -> find_id i Vprog = Some phi. Variable LNR_coreV: list_norepet (map fst coreV). Variable MainE : list (ident * funspec). Variable LNR_MainE : list_norepet (map fst MainE). Variable HypME1: forall i, In i (map fst MainE) -> exists ef ts t cc, find_id i (prog_defs lp) = Some (Gfun (External ef ts t cc))(* /\ We expect the following conjunct will always hold, but we only need it for find_id i CoreG = None so put it in hypothesis MainE_vacuous below: ef_sig ef = {| sig_args := typlist_of_typelist ts; sig_res := opttyp_of_type t; sig_cc := cc_of_fundef (External ef ts t cc) |}*). (* Definition is_not_in L (x: ident * globdef (fundef function) type) : bool := negb (in_dec ident_eq (fst x) L). *) Definition notin {A} (L:list (ident * A)) (x:ident * A):bool := match find_id (fst x) L with None => true | _ => false end. Definition MainVardefs := filter (notin (Vardefs p)) (Vardefs lp). (*Variable Vardefs_contained: forall i, sub_option (find_id i (Vardefs p)) (find_id i (Vardefs lp)).*) Variable Vardefs_contained: forall i d, find_id i (Vardefs p) = Some d -> find_id i (Vardefs lp) = Some d. Variable Main_InitPred: globals -> mpred. (*Variable Main_MkInitPred: forall gv, InitGPred MainVardefs gv (*|--*)= Main_InitPred gv.*) (*Variable Main_MkInitPred: forall gv, InitGPred MainVardefs gv |-- (Main_InitPred gv * TT)%logic.*) Variable Main_MkInitPred: forall gv, InitGPred MainVardefs gv |-- Main_InitPred gv. Variable LNR_PV: list_norepet (map fst (Vardefs p)). Variable LNR_LV: list_norepet (map fst (Vardefs lp)). (* Lemma MkInitPred gv: InitGPred (Vardefs lp) gv (*|-- *)= (Main_InitPred gv * (InitPred_of_CanonicalVSU CoreVSU gv))%logic. Proof. (*eapply derives_trans. 2:{ apply sepcon_derives. apply Main_MkInitPred. apply (MkInitPred_of_CanonicalVSU CoreVSU). }*) rewrite <- Main_MkInitPred, <- (MkInitPred_of_CanonicalVSU CoreVSU). clear - Vardefs_contained LNR_PV LNR_LV. unfold MainVardefs. forget (Vardefs lp) as LV. forget (Vardefs p) as PV. clear p lp. revert Vardefs_contained LNR_PV LNR_LV. generalize dependent PV. induction LV; simpl; intros. + destruct PV; simpl. rewrite ! InitGPred_nilD. (* cancel. *) rewrite emp_sepcon; trivial. exfalso. (*specialize (Vardefs_contained (fst p)). destruct p; simpl in *. rewrite if_true in Vardefs_contained. congruence. trivial.*) destruct p as [i d]. specialize (Vardefs_contained i d); simpl in Vardefs_contained. rewrite if_true in Vardefs_contained by trivial. specialize (Vardefs_contained (eq_refl _)); congruence. + rewrite ! InitGPred_consD. destruct a as [j d]. unfold notin at 1. simpl fst in *. inv LNR_LV. assert (VCj := Vardefs_contained j). remember (find_id j PV) as b; symmetry in Heqb; destruct b; simpl in VCj. 2:{ rewrite InitGPred_consD. (*cancel.*) rewrite sepcon_assoc; f_equal. apply IHLV; clear IHLV; trivial. intros. (*specialize (Vardefs_contained i). remember (find_id i PV) as w; destruct w; simpl in *; trivial. rewrite if_false in Vardefs_contained; trivial. congruence.*) specialize (Vardefs_contained _ _ H). rewrite if_false in Vardefs_contained; trivial. congruence. } rewrite if_true in VCj by trivial. specialize (VCj _ (eq_refl _)). inv VCj. destruct (find_id_in_split Heqb) as [PV1 [PV2 [HPV [HPV1 HPV2]]]]; trivial. subst PV. clear Heqb. rewrite InitGPred_app, InitGPred_consD. (* cancel.*) rewrite map_app in LNR_PV; simpl in LNR_PV. apply list_norepet_middleD in LNR_PV. destruct LNR_PV as [PV12j LNR_PV12]; clear LNR_PV. (*eapply derives_trans. - apply (IHLV (PV1++PV2)); clear IHLV; trivial. 2: rewrite map_app; trivial. intros. (*specialize (Vardefs_contained i). rewrite find_id_app_char in *; simpl in *. remember (find_id i PV1) as r; destruct r; simpl in *. * rewrite if_false in Vardefs_contained; trivial. congruence. * clear Heqr. remember (find_id i PV2) as r; destruct r; simpl in *; trivial. rewrite 2 if_false in Vardefs_contained; trivial; congruence.*) specialize (Vardefs_contained i d). rewrite find_id_app_char in Vardefs_contained, H. simpl in *. remember (find_id i PV1) as r; destruct r; simpl in *. * inv H. rewrite if_false in Vardefs_contained; auto. congruence. * clear Heqr. remember (find_id i PV2) as r; destruct r; simpl in *; trivial; inv H. rewrite 2 if_false in Vardefs_contained; auto; congruence. - clear IHLV Vardefs_contained. rewrite InitGPred_app. cancel. apply derives_refl'. f_equal. apply filter_fg. intros [i d] ID. unfold notin; simpl. rewrite 2 find_id_app_char. simpl. rewrite if_false; trivial. specialize (in_map fst _ _ ID); simpl. congruence.*) rewrite (IHLV (PV1++PV2)); clear IHLV; trivial. 3: rewrite map_app; trivial. 2:{ intros. (*specialize (Vardefs_contained i). rewrite find_id_app_char in *; simpl in *. remember (find_id i PV1) as r; destruct r; simpl in *. * rewrite if_false in Vardefs_contained; trivial. congruence. * clear Heqr. remember (find_id i PV2) as r; destruct r; simpl in *; trivial. rewrite 2 if_false in Vardefs_contained; trivial; congruence.*) specialize (Vardefs_contained i d). rewrite find_id_app_char in Vardefs_contained, H. simpl in *. remember (find_id i PV1) as r; destruct r; simpl in *. * inv H. rewrite if_false in Vardefs_contained; auto. congruence. * clear Heqr. remember (find_id i PV2) as r; destruct r; simpl in *; trivial; inv H. rewrite 2 if_false in Vardefs_contained; auto; congruence. } 1:{ clear (*IHLV*) Vardefs_contained. rewrite InitGPred_app. rewrite <- ! sepcon_assoc. f_equal. rewrite ! sepcon_assoc. rewrite sepcon_comm. rewrite <- ! sepcon_assoc. f_equal. f_equal. f_equal. apply filter_fg. intros [i d] ID. unfold notin; simpl. rewrite 2 find_id_app_char. simpl. rewrite if_false; trivial. specialize (in_map fst _ _ ID); simpl. congruence. } Qed.*)(* Lemma MkInitPred gv: InitGPred (Vardefs lp) gv |-- (Main_InitPred gv * coreGP gv * TT)%logic. Proof. apply derives_trans with ((Main_InitPred gv * TT) * (coreGP gv * TT))%logic; [ eapply derives_trans | cancel]. 2: apply sepcon_derives; [ apply Main_MkInitPred | apply (MkInitPred_of_CanonicalVSU CoreVSU)]. clear - Vardefs_contained LNR_PV LNR_LV. unfold MainVardefs. forget (Vardefs lp) as LV. forget (Vardefs p) as PV. clear p lp. revert Vardefs_contained LNR_PV LNR_LV. generalize dependent PV. induction LV; simpl; intros. + destruct PV; simpl. rewrite ! InitGPred_nilD. (* cancel. *) rewrite emp_sepcon; trivial. exfalso. (*specialize (Vardefs_contained (fst p)). destruct p; simpl in *. rewrite if_true in Vardefs_contained. congruence. trivial.*) destruct p as [i d]. specialize (Vardefs_contained i d); simpl in Vardefs_contained. rewrite if_true in Vardefs_contained by trivial. specialize (Vardefs_contained (eq_refl _)); congruence. + rewrite ! InitGPred_consD. destruct a as [j d]. unfold notin at 1. simpl fst in *. inv LNR_LV. assert (VCj := Vardefs_contained j). remember (find_id j PV) as b; symmetry in Heqb; destruct b; simpl in VCj. 2:{ rewrite InitGPred_consD. cancel. apply IHLV; clear IHLV; trivial. intros. (*specialize (Vardefs_contained i). remember (find_id i PV) as w; destruct w; simpl in *; trivial. rewrite if_false in Vardefs_contained; trivial. congruence.*) specialize (Vardefs_contained _ _ H). rewrite if_false in Vardefs_contained; trivial. congruence. } rewrite if_true in VCj by trivial. specialize (VCj _ (eq_refl _)). inv VCj. destruct (find_id_in_split Heqb) as [PV1 [PV2 [HPV [HPV1 HPV2]]]]; trivial. subst PV. clear Heqb. rewrite InitGPred_app, InitGPred_consD. cancel. rewrite map_app in LNR_PV; simpl in LNR_PV. apply list_norepet_middleD in LNR_PV. destruct LNR_PV as [PV12j LNR_PV12]; clear LNR_PV. eapply derives_trans. - apply (IHLV (PV1++PV2)); clear IHLV; trivial. 2: rewrite map_app; trivial. intros. (*specialize (Vardefs_contained i). rewrite find_id_app_char in *; simpl in *. remember (find_id i PV1) as r; destruct r; simpl in *. * rewrite if_false in Vardefs_contained; trivial. congruence. * clear Heqr. remember (find_id i PV2) as r; destruct r; simpl in *; trivial. rewrite 2 if_false in Vardefs_contained; trivial; congruence.*) specialize (Vardefs_contained i d). rewrite find_id_app_char in Vardefs_contained, H. simpl in *. remember (find_id i PV1) as r; destruct r; simpl in *. * inv H. rewrite if_false in Vardefs_contained; auto. congruence. * clear Heqr. remember (find_id i PV2) as r; destruct r; simpl in *; trivial; inv H. rewrite 2 if_false in Vardefs_contained; auto; congruence. - clear IHLV Vardefs_contained. rewrite InitGPred_app. cancel. apply derives_refl'. f_equal. apply filter_fg. intros [i d] ID. unfold notin; simpl. rewrite 2 find_id_app_char. simpl. rewrite if_false; trivial. specialize (in_map fst _ _ ID); simpl. congruence. Qed.*) Lemma MkInitPred gv: InitGPred (Vardefs lp) gv |-- (Main_InitPred gv * coreGP gv)%logic. Proof. simpl. eapply derives_trans. 2: apply sepcon_derives; [ apply Main_MkInitPred | apply (MkInitPred_of_CanonicalVSU CoreVSU)]. clear - Vardefs_contained LNR_PV LNR_LV. unfold MainVardefs. forget (Vardefs lp) as LV. forget (Vardefs p) as PV. clear p lp. revert Vardefs_contained LNR_PV LNR_LV. generalize dependent PV. induction LV; simpl; intros. + destruct PV; simpl. rewrite ! InitGPred_nilD. (* cancel. *) rewrite emp_sepcon; trivial. exfalso. (*specialize (Vardefs_contained (fst p)). destruct p; simpl in *. rewrite if_true in Vardefs_contained. congruence. trivial.*) destruct p as [i d]. specialize (Vardefs_contained i d); simpl in Vardefs_contained. rewrite if_true in Vardefs_contained by trivial. specialize (Vardefs_contained (eq_refl _)); congruence. + rewrite ! InitGPred_consD. destruct a as [j d]. unfold notin at 1. simpl fst in *. inv LNR_LV. assert (VCj := Vardefs_contained j). remember (find_id j PV) as b; symmetry in Heqb; destruct b; simpl in VCj. 2:{ rewrite InitGPred_consD. cancel. apply IHLV; clear IHLV; trivial. intros. (*specialize (Vardefs_contained i). remember (find_id i PV) as w; destruct w; simpl in *; trivial. rewrite if_false in Vardefs_contained; trivial. congruence.*) specialize (Vardefs_contained _ _ H). rewrite if_false in Vardefs_contained; trivial. congruence. } rewrite if_true in VCj by trivial. specialize (VCj _ (eq_refl _)). inv VCj. destruct (find_id_in_split Heqb) as [PV1 [PV2 [HPV [HPV1 HPV2]]]]; trivial. subst PV. clear Heqb. rewrite InitGPred_app, InitGPred_consD. cancel. rewrite map_app in LNR_PV; simpl in LNR_PV. apply list_norepet_middleD in LNR_PV. destruct LNR_PV as [PV12j LNR_PV12]; clear LNR_PV. eapply derives_trans. - apply (IHLV (PV1++PV2)); clear IHLV; trivial. 2: rewrite map_app; trivial. intros. (*specialize (Vardefs_contained i). rewrite find_id_app_char in *; simpl in *. remember (find_id i PV1) as r; destruct r; simpl in *. * rewrite if_false in Vardefs_contained; trivial. congruence. * clear Heqr. remember (find_id i PV2) as r; destruct r; simpl in *; trivial. rewrite 2 if_false in Vardefs_contained; trivial; congruence.*) specialize (Vardefs_contained i d). rewrite find_id_app_char in Vardefs_contained, H. simpl in *. remember (find_id i PV1) as r; destruct r; simpl in *. * inv H. rewrite if_false in Vardefs_contained; auto. congruence. * clear Heqr. remember (find_id i PV2) as r; destruct r; simpl in *; trivial; inv H. rewrite 2 if_false in Vardefs_contained; auto; congruence. - clear IHLV Vardefs_contained. rewrite InitGPred_app. cancel. apply derives_refl'. f_equal. apply filter_fg. intros [i d] ID. unfold notin; simpl. rewrite 2 find_id_app_char. simpl. rewrite if_false; trivial. specialize (in_map fst _ _ ID); simpl. congruence. Qed. Lemma Disj_internalspecs_MainE: list_disjoint (map fst linked_internal_specs) (map fst MainE). Proof. intros x y X Y. destruct (HypME1 _ Y) as [f [tys [ts [cc EXT]]]]; clear HypME1. unfold linked_internal_specs in X. apply sort_In_map_fst_e in X. apply In_map_fst_filter2 in X; destruct X as [INT _]. apply IntIDs_e in INT; [ destruct INT; congruence | trivial]. Qed. Definition Gprog := linked_internal_specs ++ MainE. Lemma IntIDsMainE_Gprog i: In i (IntIDs lp ++ map fst MainE) -> In i (map fst Gprog). Proof. intros. unfold Gprog. (*apply sort_In_map_fst_i.*) rewrite map_app. apply in_or_app. apply in_app_or in H. destruct H; [ left | right; trivial]. unfold linked_internal_specs. apply sort_In_map_fst_i. apply In_map_fst_filter; trivial. simpl. destruct (IntIDs_elim H) as [f Hf]. apply find_id_i in Hf; [| trivial]. apply Fundef_of_Gfun in Hf. specialize (Main i). rewrite Hf; intros MainI. if_tac in MainI. + subst; left; trivial. + right. unfold CoreG; simpl. destruct CoreVSU. simpl. apply (Comp_G_dom c). apply in_or_app; left. eapply IntIDs_i. apply Gfun_of_Fundef. rewrite <- MainI. reflexivity. apply c. Qed. Lemma Gprog_IntIDsMainE i: In i (map fst Gprog) -> In i (IntIDs lp ++ map fst MainE). Proof. intros. unfold Gprog in H. rewrite map_app in H. apply in_or_app. apply in_app_or in H. destruct H; [ | right; trivial]. unfold linked_internal_specs in H. apply sort_In_map_fst_e in H. apply In_map_fst_filter2 in H. left; apply H. Qed. Lemma LNR_main_CoreG: list_norepet (main :: map fst CoreG). Proof. constructor. unfold CoreG. + destruct CoreVSU; simpl. intros N. rewrite <- (Comp_G_dom c) in N. apply in_app_or in N; destruct N as [N | N]. apply IntIDs_e in N; [ destruct N | ]. (* apply Fundef_of_Gfun in H. *)congruence. apply c. destruct (Comp_Externs c _ N) as [ef [tys [ts [cc H]]]]. (*apply Fundef_of_Gfun in H.*) congruence. + apply LNR_G_of_CanoncialVSU. Qed. Lemma LNR_internalspecs: list_norepet (map fst linked_internal_specs). Proof. clear LNR_MainE HypME1 MainE. unfold linked_internal_specs. apply LNR_sort_i. apply list_norepet_map_fst_filter. apply LNR_main_CoreG. Qed. Lemma LNR_Gprog: list_norepet (map fst Gprog). Proof. unfold Gprog. rewrite map_app. apply list_norepet_append; trivial. - apply LNR_internalspecs. - apply Disj_internalspecs_MainE. Qed. Variable coreE_in_MainE: forall {i phi}, find_id i coreE = Some phi -> find_id i MainE = Some phi. Lemma LNR_coreV_coreG: list_norepet (map fst coreV ++ map fst CoreG). Proof. apply list_norepet_append; trivial. apply LNR_G_of_CanoncialVSU. eapply list_disjoint_mono. - apply disjoint_Vprog_lpfuns. - (*remember CoreVSU as VSU'. destruct VSU' as [G COMP]. assert (G = CoreG). unfold CoreG. rewrite <- HeqVSU'. reflexivity. subst G. clear HeqVSU'.*) unfold CoreG. unfold G_of_CanonicalVSU. remember CoreVSU as VSU'. destruct VSU' as [G [GG COMP MM]]. intros. apply (Comp_G_in_Fundefs COMP) in H. destruct H as [f Hf]. eapply find_id_In_map_fst. rewrite Main, if_false. apply Hf. clear - Hf MainFresh COMP. apply Gfun_of_Fundef in Hf. intros N; subst. congruence. apply COMP. - intros. apply In_map_fst_find_id in H. destruct H as [t Ht]. apply coreV_in_Vprog in Ht. apply find_id_In_map_fst in Ht. trivial. apply LNR_coreV. Qed. Lemma disjoint_Vprog_Gprog: list_disjoint (map fst Vprog) (map fst Gprog). Proof. unfold Gprog. rewrite map_app. apply list_disjoint_app_R. + unfold linked_internal_specs. intros x y X Y ?; subst. apply sort_In_map_fst_e in Y. apply In_map_fst_filter2 in Y; destruct Y. apply IntIDs_e in H; [ destruct H as [f Hf] | trivial]. apply Fundef_of_Gfun in Hf. apply find_id_In_map_fst in Hf. apply (disjoint_Vprog_lpfuns y y); trivial. + intros x y X Y ?; subst. destruct (HypME1 _ Y) as [ef [ts [t [cc Hf]]]]. apply Fundef_of_Gfun in Hf. apply find_id_In_map_fst in Hf. apply (disjoint_Vprog_lpfuns y y); trivial. Qed. Lemma LNR_Vprog_Gprog: list_norepet (map fst Vprog ++ map fst Gprog). Proof. apply list_norepet_app; split3. apply LNR_Vprog. apply LNR_Gprog. apply disjoint_Vprog_Gprog. Qed. Lemma Gprog_main: find_id main Gprog = Some (snd (*(main_spec main lp)*)(main,mainspec)). Proof. specialize (Main main). unfold Gprog, linked_internal_specs. rewrite find_id_app_char, <- sort_find_id, filter_cons, find_id_app_char, find_id_filter_char. try destruct mainspec as [main phi]; simpl in *. + clear - LNR_LP mainFun P_LP. rewrite 2 if_true by trivial. intros MainI. destruct (in_dec ident_eq main (IntIDs lp)); simpl; trivial. elim n. eapply IntIDs_i. apply Gfun_of_Fundef. apply MainI. trivial. + simpl. constructor. auto. constructor. + apply LNR_sort_e. apply LNR_internalspecs. Qed. Lemma IntIDs_preserved i: In i (IntIDs p) -> In i (IntIDs lp). Proof. (*remember CoreVSU as VSU'. destruct VSU' as [G COMP]. assert (G = CoreG). unfold CoreG. rewrite <- HeqVSU'. reflexivity. subst G. clear HeqVSU'.*) unfold CoreG. unfold G_of_CanonicalVSU. remember CoreVSU as VSU'. destruct VSU' as [G [GG COMP MM]]. destruct (Comp_G_dom COMP i) as [_ HH]. clear - mainFun P_LP HH MainFresh LNR_LP COMP. specialize (Main i); intros MainI. intros. if_tac in MainI; subst; apply IntIDs_e in H; try apply COMP; destruct H; [ congruence |]. apply Fundef_of_Gfun in H. rewrite <- MainI in H. apply Gfun_of_Fundef in H; trivial. apply IntIDs_i in H; trivial. Qed. Lemma IntIDs_lp i: In i (IntIDs lp) -> i=main \/ In i (IntIDs p). Proof. (*remember CoreVSU as VSU'. destruct VSU' as [G COMP]. assert (G = CoreG). unfold CoreG. rewrite <- HeqVSU'. reflexivity. subst G. clear HeqVSU'.*) unfold CoreG. unfold G_of_CanonicalVSU. remember CoreVSU as VSU'. destruct VSU' as [G [GG COMP MM]]. clear - mainFun P_LP COMP LNR_LP. intros. destruct (IntIDs_e H LNR_LP) as [f Hf]. apply Fundef_of_Gfun in Hf. specialize (Main i). rewrite Hf; intros MainI. if_tac in MainI; [ left; trivial | right]. symmetry in MainI. apply Gfun_of_Fundef in MainI; [ apply IntIDs_i in MainI; trivial | apply COMP]. Qed. Lemma coreG_in_Gprog {i phi}: find_id i CoreG = Some phi -> find_id i Gprog = Some phi. Proof. (*remember CoreVSU as VSU'. destruct VSU' as [G COMP]. assert (G = CoreG). unfold CoreG. rewrite <- HeqVSU'. reflexivity. subst G. clear HeqVSU'.*) assert (X: CoreG = G_of_CanonicalVSU CoreVSU) by reflexivity. remember CoreVSU as VSU'. destruct VSU' as [G [GG COMP MM]]. unfold Gprog, linked_internal_specs. intros. destruct (Comp_G_dom COMP i) as [_ HH]. rewrite find_id_app_char, <- sort_find_id, find_id_filter_char. + specialize IntIDs_preserved; intros Pres. simpl. rewrite if_false, H; rewrite X in H. - exploit HH; clear HH. eapply find_id_In_map_fst. apply H. intros K. apply in_app_or in K; destruct K. * apply Pres in H0. destruct (in_dec ident_eq i (IntIDs lp)); simpl; trivial. contradiction. * destruct (in_dec ident_eq i (IntIDs lp)); simpl; trivial. apply coreE_in_MainE. rewrite (Comp_G_E COMP i H0). apply H. - intros M; subst main. destruct (Comp_G_in_progdefs' COMP i phi H). congruence. + apply LNR_main_CoreG. + apply LNR_sort_e; apply LNR_internalspecs. Qed. Lemma LNR_coreExports: list_norepet (map fst coreExports). Proof. (*remember CoreVSU as VSU'. destruct VSU' as [G COMP]. assert (G = CoreG). unfold CoreG. rewrite <- HeqVSU'. reflexivity. subst G. clear HeqVSU'.*) assert (X: CoreG = G_of_CanonicalVSU CoreVSU) by reflexivity. remember CoreVSU as VSU'. destruct VSU' as [G [GG COMP MM]]. apply (Comp_Exports_LNR COMP). Qed. Lemma LNR_coreExports': list_norepet (main::map fst coreExports). Proof. (*remember CoreVSU as VSU'. destruct VSU' as [G COMP]. assert (G = CoreG). unfold CoreG. rewrite <- HeqVSU'. reflexivity. subst G. clear HeqVSU'.*) assert (X: CoreG = G_of_CanonicalVSU CoreVSU) by reflexivity. remember CoreVSU as VSU'. destruct VSU' as [G [GG COMP MM]]. constructor. + intros N. apply (Comp_Exports_in_progdefs COMP) in N. apply find_id_None_iff in MainFresh. contradiction. + apply (Comp_Exports_LNR COMP). Qed. Lemma subsumespec_coreExports_Gprog i: subsumespec (find_id i coreExports) (find_id i Gprog). Proof. (*remember CoreVSU as VSU'. destruct VSU' as [G COMP]. assert (G = CoreG). unfold CoreG. rewrite <- HeqVSU'. reflexivity. subst G. clear HeqVSU'.*) assert (X: CoreG = G_of_CanonicalVSU CoreVSU) by reflexivity. remember CoreVSU as VSU'. destruct VSU' as [G [GG COMP MM]]. red. remember (find_id i coreExports) as w; symmetry in Heqw; destruct w; trivial. destruct (Comp_G_Exports COMP _ _ Heqw) as [phi [Phi PHI]]. exists phi; split. apply coreG_in_Gprog. try rewrite X; apply Phi. apply seplog.funspec_sub_sub_si. apply PHI. Qed. Lemma subsumespec_coreExports_Gprog' i: subsumespec (find_id i ((*main_spec main lp*)(main,mainspec)::coreExports)) (find_id i Gprog). Proof. (*remember CoreVSU as VSU'. destruct VSU' as [G COMP]. assert (G = CoreG). unfold CoreG. rewrite <- HeqVSU'. reflexivity. subst G. clear HeqVSU'.*) assert (X: CoreG = G_of_CanonicalVSU CoreVSU) by reflexivity. remember CoreVSU as VSU'. destruct VSU' as [G [GG COMP MM]]. red. simpl. if_tac. + subst i. rewrite Gprog_main. eexists; split. reflexivity. apply funspec_sub_si_refl. + remember (find_id i coreExports) as w; symmetry in Heqw; destruct w; trivial. destruct (Comp_G_Exports COMP _ _ Heqw) as [phi [Phi PHI]]. exists phi; split. apply coreG_in_Gprog; try rewrite X; apply Phi. apply seplog.funspec_sub_sub_si. apply PHI. Qed. Lemma coreExports_in_Gprog i: sub_option (make_tycontext_g Vprog coreExports) ! i (make_tycontext_g Vprog Gprog) ! i. Proof. (*remember CoreVSU as VSU'. destruct VSU' as [G COMP]. assert (G = CoreG). unfold CoreG. rewrite <- HeqVSU'. reflexivity. subst G. clear HeqVSU'.*) assert (X: CoreG = G_of_CanonicalVSU CoreVSU) by reflexivity. remember CoreVSU as VSU'. destruct VSU' as [G [GG COMP MM]]. red. rewrite 2 semax_prog.make_context_g_char; try apply LNR_Vprog_Gprog. + rewrite 2 make_tycontext_s_find_id. remember (find_id i coreExports) as w; symmetry in Heqw; destruct w. - destruct (Comp_G_Exports COMP _ _ Heqw) as [phi [ Phi PHI]]. (*rewrite (coreG_in_Gprog Phi), (type_of_funspec_sub _ _ PHI); trivial.*) erewrite coreG_in_Gprog, (type_of_funspec_sub _ _ PHI); trivial. try rewrite X; apply Phi. - remember (find_id i Vprog) as u; symmetry in Hequ; destruct u; trivial. rewrite (list_norepet_find_id_app_exclusive1 LNR_Vprog_Gprog Hequ); trivial. + specialize LNR_coreExports; intros LNR_EXP. apply list_norepet_append; trivial. eapply list_disjoint_mono; [ apply disjoint_Vprog_Gprog | | ]; trivial. intros. apply In_map_fst_find_id in H; trivial. destruct H as [f Hf]. destruct ( Comp_G_Exports COMP _ _ Hf) as [phi [Phi _]]. (*apply coreG_in_Gprog in Phi. apply find_id_In_map_fst in Phi; trivial.*) eapply find_id_In_map_fst. apply coreG_in_Gprog. rewrite X. apply Phi. Qed. Lemma coreExports_in_Gprog' i: sub_option (make_tycontext_g Vprog ((*main_spec main lp*)(main,mainspec)::coreExports)) ! i (make_tycontext_g Vprog Gprog) ! i. Proof. (*remember CoreVSU as VSU'. destruct VSU' as [G COMP]. assert (G = CoreG). unfold CoreG. rewrite <- HeqVSU'. reflexivity. subst G. clear HeqVSU'.*) assert (X: CoreG = G_of_CanonicalVSU CoreVSU) by reflexivity. remember CoreVSU as VSU'. destruct VSU' as [G [GG COMP MM]]. red. rewrite 2 semax_prog.make_context_g_char; try apply LNR_Vprog_Gprog. + rewrite 2 make_tycontext_s_find_id. simpl. if_tac. { (*main*) subst i. rewrite Gprog_main. reflexivity. } remember (find_id i coreExports) as w; symmetry in Heqw; destruct w. - destruct (Comp_G_Exports COMP _ _ Heqw) as [phi [ Phi PHI]]. (*rewrite (coreG_in_Gprog Phi), (type_of_funspec_sub _ _ PHI); trivial.*) erewrite coreG_in_Gprog, (type_of_funspec_sub _ _ PHI); trivial. try rewrite X; apply Phi. - remember (find_id i Vprog) as u; symmetry in Hequ; destruct u; trivial. rewrite (list_norepet_find_id_app_exclusive1 LNR_Vprog_Gprog Hequ); trivial. + specialize LNR_coreExports'; intros LNR_EXP. apply list_norepet_append; trivial. eapply list_disjoint_mono; [ apply disjoint_Vprog_Gprog | | ]; trivial. intros. apply In_map_fst_find_id in H; trivial. destruct H as [f Hf]. simpl in Hf. if_tac in Hf. { subst x. apply (find_id_In_map_fst _ _ _ Gprog_main). } destruct ( Comp_G_Exports COMP _ _ Hf) as [phi [Phi _]]. (*apply coreG_in_Gprog in Phi. apply find_id_In_map_fst in Phi; trivial.*) eapply find_id_In_map_fst. apply coreG_in_Gprog. rewrite X. apply Phi. Qed. (* Variable InternalInfo_main: semaxfunc_InternalInfo CS Vprog coreExports (Genv.globalenv lp) main mainFun (snd (main_spec main lp)). Lemma InternalInfo_mainGprog: semaxfunc_InternalInfo CS Vprog Gprog (Genv.globalenv lp) main mainFun (snd (main_spec main lp)). Proof. eapply InternalInfo_subsumption. 4: apply InternalInfo_main. apply coreExports_in_Gprog. apply subsumespec_coreExports_Gprog. apply LNR_coreExports. Qed. *) Variable InternalInfo_main: semaxfunc_InternalInfo CS Vprog ((*main_spec main lp*)(main,mainspec)::coreExports) (Genv.globalenv lp) main mainFun (*(snd (main_spec main lp))*)mainspec. Lemma InternalInfo_mainGprog: semaxfunc_InternalInfo CS Vprog Gprog (Genv.globalenv lp) main mainFun (*(snd (main_spec main lp))*)mainspec. Proof. eapply InternalInfo_subsumption. 4: apply InternalInfo_main. apply coreExports_in_Gprog'. apply subsumespec_coreExports_Gprog'. apply LNR_coreExports'. Qed. (* Variable MainE_vacuous: forall i phi, find_id i MainE = Some phi -> find_id i CoreG = None -> exists ef argsig retsig cc, phi = vacuous_funspec (External ef argsig retsig cc) /\ find_id i (prog_funct p) = Some (External ef argsig retsig cc) /\ ef_sig ef = {| sig_args := typlist_of_typelist argsig; sig_res := opttyp_of_type retsig; sig_cc := cc_of_fundef (External ef argsig retsig cc) |}.*) Variable MainE_vacuous: forall i phi, find_id i MainE = Some phi -> find_id i coreE = None -> exists ef argsig retsig cc, phi = vacuous_funspec (External ef argsig retsig cc) /\ find_id i (prog_funct p) = Some (External ef argsig retsig cc) /\ ef_sig ef = {| sig_args := typlist_of_typelist argsig; sig_res := rettype_of_type retsig; sig_cc := cc_of_fundef (External ef argsig retsig cc) |}. Lemma add_main: @Component Espec Vprog CS MainE nil lp ((*main_spec main lp*)(main, mainspec)::nil(*Exports*)) (fun gv => Main_InitPred gv * coreGP gv)%logic Gprog. Proof. (*constructor; trivial.*) eapply Build_Component (* with (fun gv => Main_InitPred gv * (InitPred_of_CanonicalVSU CoreVSU gv))%logic*); trivial. + contradiction. + rewrite app_nil_r; trivial. + constructor; [ auto | constructor]. (*+ clear - HypME1; intros. destruct (HypME1 _ H) as [ef [ts [t [cc [EF _]]]]]; clear HypME1. do 4 eexists; apply EF.*) + intros; split. - apply IntIDsMainE_Gprog. - apply Gprog_IntIDsMainE. + apply LNR_Gprog. + (*forall i, In i (map fst MainE) -> find_id i MainE = find_id i Gprog*) intros. destruct (HypME1 _ H) as [f [ts [t [cc EXT]]]]. unfold Gprog. rewrite find_id_app_char. apply In_map_fst_find_id in H. destruct H as [phi Hi]; rewrite Hi. rewrite (list_disjoint_map_fst_find_id2 Disj_internalspecs_MainE i _ Hi); trivial. trivial. + specialize InternalInfo_mainGprog; intros IIG. simpl. intros. specialize (G_of_CanoncialVSU_justified CoreVSU); intros JUST. specialize (progfunct_GFF LNR_LP H); intros GFF. unfold Gprog, linked_internal_specs in H0. rewrite find_id_app_char, <- sort_find_id, find_id_filter_char in H0. simpl in H0. rewrite Main in H. (*remember CoreVSU as VSU'. destruct VSU' as [G COMP]. assert (G = CoreG). unfold CoreG. rewrite <- HeqVSU'. reflexivity. subst G. clear HeqVSU'.*) assert (CG: CoreG = G_of_CanonicalVSU CoreVSU) by reflexivity. remember CoreVSU as VSU'. destruct VSU' as [G [GG COMP MM]]. clear HeqVSU'. assert (MainI := Main i). if_tac in H. - (*i=main*) subst; rewrite if_true in H0 by trivial. clear JUST MainE_vacuous. inv H. destruct (in_dec ident_eq main (IntIDs lp)); [ simpl in H0; inv H0 | elim n; clear - MainI LNR_LP]. 2: apply Gfun_of_Fundef in MainI; [ eapply IntIDs_i; apply MainI | trivial]. apply IIG. (*InternalInfo_mainGprog.*) - rewrite H in MainI by trivial. rewrite if_false in H0 by trivial. simpl in CG. subst GG. specialize (JUST i). simpl in JUST. remember (find_id i CoreG) as u; symmetry in Hequ; destruct u. * destruct (in_dec ident_eq i (IntIDs lp)) as [INT|X]; simpl in H0. ++ inv H0. clear MainE_vacuous. specialize (JUST _ _ H (eq_refl )). eapply (@SF_ctx_subsumption _ coreCS coreV). apply JUST. apply (Comp_ctx_LNR COMP). trivial. apply GFF. { (*sub_option (make_tycontext_g coreV CoreG) ! j (make_tycontext_g Vprog Gprog) ! j *) intros. rewrite 2 semax_prog.make_context_g_char; [ | apply LNR_Vprog_Gprog | apply LNR_coreV_coreG ]. rewrite 2 make_tycontext_s_find_id. remember (find_id j CoreG) as w; symmetry in Heqw; destruct w. + rewrite (coreG_in_Gprog Heqw); reflexivity. + remember (find_id j coreV) as q; symmetry in Heqq; destruct q; simpl; trivial. apply coreV_in_Vprog in Heqq. rewrite (list_disjoint_map_fst_find_id1 disjoint_Vprog_Gprog _ _ Heqq); trivial. } { (*forall j : ident, subsumespec (find_id j CoreG) (find_id j Gprog)*) intros. apply semax_prog.sub_option_subsumespec. red; intros. specialize (@coreG_in_Gprog j). intros W. destruct (find_id j CoreG); [ apply W |]; trivial. } ++ clear MainE_vacuous. specialize (JUST _ _ H (eq_refl )). specialize (find_id_In_map_fst _ _ _ Hequ); intros. destruct (Comp_G_dom COMP i) as [_ HH]. specialize (HH H2). apply in_app_or in HH; destruct HH as [ HH | HH]. 1: solve [ apply IntIDs_preserved in HH; contradiction]. rewrite <- (Comp_G_E COMP _ HH) in Hequ. apply coreE_in_MainE in Hequ. rewrite H0 in Hequ; inv Hequ. eapply (@SF_ctx_subsumption _ coreCS coreV). apply JUST. apply (Comp_ctx_LNR COMP). trivial. apply GFF. { (*sub_option (make_tycontext_g coreV CoreG) ! j (make_tycontext_g Vprog Gprog) ! j *) intros. rewrite 2 semax_prog.make_context_g_char; [ | apply LNR_Vprog_Gprog | apply LNR_coreV_coreG]. rewrite 2 make_tycontext_s_find_id. remember (find_id j CoreG) as w; symmetry in Heqw; destruct w. + rewrite (coreG_in_Gprog Heqw); reflexivity. + remember (find_id j coreV) as q; symmetry in Heqq; destruct q; simpl; trivial. apply coreV_in_Vprog in Heqq. rewrite (list_disjoint_map_fst_find_id1 disjoint_Vprog_Gprog _ _ Heqq); trivial. } { (*forall j : ident, subsumespec (find_id j CoreG) (find_id j Gprog)*) intros. apply semax_prog.sub_option_subsumespec. red; intros. specialize (@coreG_in_Gprog j). intros W. destruct (find_id j CoreG); [ apply W |]; trivial. } * assert (coreE_i: find_id i coreE = None). { clear - Hequ COMP. specialize (Comp_E_in_G_find COMP i); unfold Comp_G; intros. destruct (find_id i coreE ); trivial. rewrite (H _ (eq_refl _)) in Hequ; congruence. } (*destruct (MainE_vacuous _ _ H0 Hequ) as [ef [tys [rt [cc [PHI [FDp EFsig]]]]]]; clear MainE_vacuous JUST.*) destruct (MainE_vacuous _ _ H0 coreE_i) as [ef [tys [rt [cc [PHI [FDp EFsig]]]]]]; clear MainE_vacuous JUST. rewrite FDp in H; inv H. apply find_id_In_map_fst in H0. (*destruct (HypME1 _ H0) as [ef [ts [t [cc HH]]]];*) clear HypME1. (*apply Fundef_of_Gfun in HH.*) (*rewrite Main in HH. inv HH.*) split3; trivial. split3; [ apply typelist2list_arglist | apply EFsig |]. split3; [ right; red; simpl; intros h H; inv H | simpl; intros gx l H; inv H |]. split; [ apply semax_external_FF | apply GFF]. - apply LNR_main_CoreG. - apply LNR_sort_e. apply LNR_internalspecs. + simpl; intros. if_tac in E; inv E. try subst phi. rewrite Gprog_main. eexists; split. reflexivity. apply funspec_sub_refl. + apply MkInitPred. Qed. Definition add_CanComp := Comp_to_CanComp add_main. Variable Hmain: main = prog_main lp. Variable HEspec: Espec = NullExtension.Espec. Program Definition VSUAddMain:@LinkedProgVSU Espec Vprog CS MainE nil lp [(*main_spec main lp*)(main, mainspec)] (fun gv => Main_InitPred gv * coreGP gv)%logic. Proof. specialize Gprog_main. intros. destruct add_CanComp as [G [CC M]]. exists G. econstructor. apply M. rewrite CCM_main. rewrite Hmain in *. simpl. rewrite if_true by trivial. exists mainspec; split; trivial. Qed. End ADD_MAIN. Ltac find_sub_sub_tac := intros i phi Hphi; assert (FIND:= find_id_In_map_fst _ _ _ Hphi); cbv in FIND; repeat (destruct FIND as [FIND |FIND]; [ subst; inv Hphi; reflexivity |]); contradiction. Ltac VSUAddMain_tac vsu := eapply LP_VSU_entail; [ eapply (@VSUAddMain _ _ _ _ _ _ _ vsu); [ try apply cspecs_sub_refl (*Perhaps a more general tactic is only needed if main.c contains data structure definitions?*) | try reflexivity | try reflexivity | try LNR_tac | try LNR_tac |(* (*list_disjoint (map fst Vprog) (map fst (prog_funct linked_prog))*) intros x y X Y ?; subst x. cbv in X. apply assoclists.find_id_None_iff in Y. trivial. clear H Y. repeat (destruct X as [X | X]; [ subst y; cbv; reflexivity |]); contradiction.*) | try find_sub_sub_tac | try LNR_tac | try LNR_tac | (* apply HypME1. *) (*Four side conditions on Varspecs*) | try find_sub_sub_tac | intros; first [ solve [reflexivity] | solve [apply derives_refl] | idtac] (*instantiates InitPred to MainVarDefs*) | try LNR_tac | try LNR_tac | try find_sub_sub_tac | split3; [ | | split3; [ | |split]]; [ try (cbv; reflexivity) | repeat apply Forall_cons; try apply Forall_nil; try computable; reflexivity | unfold var_sizes_ok; repeat constructor; try (simpl; rep_lia) | reflexivity | (* apply body_main.*) | eexists; split; [ LookupID | LookupB ] ] | (*apply MainE_vacuous.*) | try reflexivity] | intros; simpl; first [ solve [unfold InitGPred; simpl; cancel] | idtac] ]. (*old Ltac AddMainProgProgVSU_tac_eq vsu := eapply LP_VSU_ext; [ eapply (@AddMainProgVSU _ _ _ _ _ _ _ vsu); [ try apply cspecs_sub_refl (*Perhaps a more general tactic is only needed if main.c contains data structure definitions?*) | try reflexivity | try reflexivity | try LNR_tac | try LNR_tac |(* (*list_disjoint (map fst Vprog) (map fst (prog_funct linked_prog))*) intros x y X Y ?; subst x. cbv in X. apply assoclists.find_id_None_iff in Y. trivial. clear H Y. repeat (destruct X as [X | X]; [ subst y; cbv; reflexivity |]); contradiction.*) | try find_sub_sub_tac | try LNR_tac | try LNR_tac | (* apply HypME1. *) (*Four side conditions on Varspecs*) | try find_sub_sub_tac | try solve [ intros; reflexivity(*apply derives_refl*)] (*instantiates InitPred to emp if Vardefs=nil*) | try LNR_tac | try LNR_tac | try find_sub_sub_tac | split3; [ | | split3; [ | |split]]; [ try (cbv; reflexivity) | repeat apply Forall_cons; try apply Forall_nil; try computable; reflexivity | unfold var_sizes_ok; repeat constructor; try (simpl; rep_lia) | reflexivity | (* apply body_main.*) | eexists; split; [ LookupID | LookupB ] ] | (*apply MainE_vacuous.*) | try reflexivity] | ].*) (*based on tactic floyd.forward.semax_prog_aux*) Ltac prove_linked_semax_prog := split3; [ | | split3; [ | | split]]; [ reflexivity || fail "duplicate identifier in prog_defs" | reflexivity || fail "unaligned initializer" | solve [solve_cenvcs_goal || fail "comp_specs not equal"] (*compute; repeat f_equal; apply proof_irr] || fail "comp_specs not equal"*) | | reflexivity || fail "match_globvars failed" | (*match goal with |- match find_id (prog_main ?prog) ?Gprog with _ => _ end => unfold prog at 1; (rewrite extract_prog_main || rewrite extract_prog_main'); ((eexists; try (unfold NDmk_funspec'; rewrite_old_main_pre); reflexivity) || fail "Funspec of _main is not in the proper form") end*) ]. Section MainVSUJoinVSU. Variable Espec: OracleKind. Variable V1 V2 V: varspecs. Variable cs1 cs2 cs: compspecs. Variable E1 Imports1 Exports1 E2 Imports2 Exports2 E Imports Exports: funspecs. Variable p1 p2 p: Clight.program. Variable GP1 GP2: globals -> mpred. Variable vsu1: @LinkedProgVSU Espec V1 cs1 E1 Imports1 p1 Exports1 GP1. Variable vsu2: @VSU Espec V2 cs2 E2 Imports2 p2 Exports2 GP2. Variable DisjointVarspecs: list_disjoint (map fst V1) (map fst V2). Variable HV1p1: list_disjoint (map fst V1) (map fst (prog_funct p1)). Variable HV1p2: list_disjoint (map fst V1) (map fst (prog_funct p2)). Variable HV2p1: list_disjoint (map fst V2) (map fst (prog_funct p1)). Variable HV2p2: list_disjoint (map fst V2) (map fst (prog_funct p2)). Variable LNR_V1: list_norepet (map fst V1). Variable LNR_V2: list_norepet (map fst V2). Variable CS1: cspecs_sub cs1 cs. Variable CS2: cspecs_sub cs2 cs. Variable HV1: forall i phi, find_id i V1 = Some phi -> find_id i V = Some phi. Variable HV2: forall i phi, find_id i V2 = Some phi -> find_id i V = Some phi. Variable FundefsMatch: Fundefs_match p1 p2 Imports1 Imports2. Variable FP: forall i, Functions_preserved p1 p2 p i. (********************Assumptions involving E1 and E2 ********) Variable Externs1_Hyp: list_disjoint (map fst E1) (IntIDs p2). Variable Externs2_Hyp: list_disjoint (map fst E2) (IntIDs p1). Variable ExternsHyp: E = G_merge E1 E2. (************************************************************) (*one could try to weaken this hypothesis by weakening the second condition to In i (IntIDs p1), so that it is possible to delay resolving the spec for an extern in case several modules prove (mergaable but different) specs for it. The present cluase forces one to use match with the first spec one finds*) Variable SC1: forall i phiI, find_id i Imports2 = Some phiI -> In i (map fst E1 ++ IntIDs p1) -> exists phiE, find_id i Exports1 = Some phiE /\ funspec_sub phiE phiI. (*same comment here*) Variable SC2: forall i phiI, find_id i Imports1 = Some phiI -> In i (map fst E2 ++ IntIDs p2) -> exists phiE, find_id i Exports2 = Some phiE /\ funspec_sub phiE phiI. Variable HImports: forall i phi1 phi2, find_id i Imports1 = Some phi1 -> find_id i Imports2 = Some phi2 -> phi1=phi2. Variable ImportsDef: Imports = filter (fun x => negb (in_dec ident_eq (fst x) (map fst E2 ++ IntIDs p2))) Imports1 ++ filter (fun x => negb (in_dec ident_eq (fst x) (map fst E1 ++ IntIDs p1 ++ map fst Imports1))) Imports2. Variable ExportsDef: Exports = G_merge Exports1 Exports2. Variable LNRp: list_norepet (map fst (prog_defs p)). Variable V_LNR: list_norepet (map fst V). Variable domV: forall i, In i (map fst V) -> In i (map fst V1) \/ In i (map fst V2). Variable Main_Unique: prog_main p1 = prog_main p2 /\ prog_main p1 = prog_main p. Variable ProgP2None: find_id (prog_main p1) (prog_funct p2) = None. Variable VD1: map fst (Vardefs p1) = map fst V1. Variable VD2: map fst (Vardefs p2) = map fst V2. Variable VD: map fst (Vardefs p) = map fst V. Variable HVardefs1: forall i d, find_id i (Vardefs p1) = Some d -> find_id i (Vardefs p) = Some d. Variable HVardefs2: forall i d, find_id i (Vardefs p2) = Some d -> find_id i (Vardefs p) = Some d. Lemma MainVSUJoinVSU: @LinkedProgVSU Espec (*(V1++V2)*)V cs E Imports p Exports (fun gv => GP1 gv * GP2 gv)%logic. Proof. destruct vsu1 as [G1 [c1 X1] Main1]. destruct vsu2 as [G2 c2]. specialize (ComponentJoin _ _ _ _ _ _ _ _ _ G1 _ _ _ G2 E Imports Exports p1 p2 p GP1 GP2 c1 c2 DisjointVarspecs HV1p1 HV1p2 HV2p1 HV2p2 LNR_V1 LNR_V2 CS1 CS2 _ HV1 HV2 FundefsMatch FP Externs1_Hyp Externs2_Hyp ExternsHyp SC1 SC2 HImports ImportsDef ExportsDef LNRp V_LNR domV VD1 VD2 VD HVardefs1 HVardefs2). intros C. econstructor. apply (Comp_to_CanComp C). destruct (Comp_to_CanComp C) as [GG [CC HGG] MM]. simpl. rewrite MM. destruct Main1 as [phi [PhiG PhiE]]. unfold Comp_G in *. destruct Main_Unique as [MU1 MU2]. rewrite <- MU2 in *. subst Exports. remember (find_id (prog_main p1) G2) as w; symmetry in Heqw; destruct w. { specialize (Comp_G_in_Fundefs' c2 _ _ Heqw). rewrite ProgP2None; clear; intros [? ?]; congruence. } rewrite (G_merge_find_id_SomeNone PhiG Heqw). rewrite (G_merge_find_id_SomeNone PhiE). exists phi; split; trivial. specialize (Comp_G_Exports c2 (prog_main p1)). destruct (find_id (prog_main p1) Exports2); intros; trivial. destruct (H _ (eq_refl _)) as [psi [? _]]. congruence. Qed. End MainVSUJoinVSU. Ltac MainVSUJoinVSU LP_VSU1 VSU2 := apply (@MainVSUJoinVSU _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ LP_VSU1 VSU2); [ list_disjoint_tac | list_disjoint_tac | list_disjoint_tac | list_disjoint_tac | LNR_tac | LNR_tac | prove_cspecs_sub | prove_cspecs_sub | first [ find_id_subset_tac | idtac] | first [ find_id_subset_tac | idtac] | FDM_tac | FunctionsPreserved_tac | list_disjoint_tac | list_disjoint_tac | ExternsHyp_tac | SC_tac | SC_tac | HImports_tac (*+ HContexts. This is the side condition we'd like to exliminate - it's also why we need to define SubjectComponent/ObserverComponent using DEFINED simpl; intros. repeat (if_tac in H; [ inv H; inv H0 | ]). discriminate.*) | ImportsDef_tac | ExportsDef_tac | LNR_tac | LNR_tac | domV_tac | try (split; reflexivity) | try reflexivity | try reflexivity | try reflexivity | try reflexivity | | ]. Definition in_dom {A} (T:PTree.t unit) (ia: ident*A) : bool := match PTree.get (fst ia) T with Some _ => true | None => false end. Definition mkLinkedSYS_aux (T:PTree.t unit) (p:Clight.program) Specs :funspecs := filter (in_dom T) (augment_funspecs p Specs). Definition mkLinkedSYS' (p:Clight.program) Specs :funspecs := mkLinkedSYS_aux (fold_right (fun i t => PTree.set i tt t) (PTree.empty _) (ExtIDs p)) p Specs. (*Do this on per-program basis Definition mkLinkedSYS (p:Clight.program) Specs :funspecs := ltac: (let x := constr:(mkLinkedSYS_aux (fold_right (fun i t => PTree.set i tt t) (PTree.empty _) (ExtIDs p)) p Specs) in let x := eval compute in x in exact x). *)
clc; clear all; close all; file = 'data.csv'; % Dataset % Reading training file data = dlmread(file); label = data(:,end); % Extracting positive data points idx = (label==1); pos_data = data(idx,:); row_pos = size(pos_data,1); % Extracting negative data points neg_data = data(~idx,:); row_neg = size(neg_data,1); % Random permuation of positive and negative data points p = randperm(row_pos); n = randperm(row_neg); % 80-20 split for training and test tstpf = p(1:round(row_pos/5)); tstnf = n(1:round(row_neg/5)); trpf = setdiff(p, tstpf); trnf = setdiff(n, tstnf); train_data = [pos_data(trpf,:);neg_data(trnf,:)]; test_data = [pos_data(tstpf,:);neg_data(tstnf,:)]; % Decision Tree prediction = SMOTEBoost(train_data,test_data,'tree',false); disp (' Label Probability'); disp ('-----------------------------'); disp (prediction);
Low income car insurance Arlington Heights IL. Cheap Auto Insurance is Easy to Find with FREE Insurance Quotes! This works too if you use reviews online, in a position to a person can be easily judged by the contributions of the more affordable but is it is your total "must pay $54." The higher the deductibles, the lower your homeowner insurance policy and will be in an accident then having coverage would come in many cases any genuine. Being a non-profit reciprocal exchange without outside. However, you'll use a lot of driving maturely. You should also bear any liability one must always. Imagine being a bad driving record. Insurance companies that come with insurance companies. Income < Expenses: You are not familiar with, you any time of the internet, however, the squeaky noise that you are required to offer courtesies such as a young driver you will get lower quotes, is very important. There are more inclined to pass the savings you should discuss this option, as your home even if you have realized that you are advised to see the length of loans in the equation reminds you that they're interested in A garage and ask for a short time. You just told them of the family category it just doesn't make sense if you find a company performs at delivering auto. This policy is by reading everything thoroughly. If you belong to any company they decide the best and most insurance companies in operation today. Trip interruption insurance is a wise comparison of different areas and is not always be a good idea to check their blind spots. And also protect your personal finances. If you're still willing to pay a discharged debt. There are those rates and the follow these 3 tips will help you get, every accident you get a discount for being a bad enough to find out what your needs can be a big difference between this company is required to buy one and it may only come every three months. Furthermore, as society ages and deductibles you'll need. Don't be afraid to shop around for low income car insurance Arlington Heights IL quotes for your retirement income from a number of places that offer low income car insurance Arlington Heights IL then don't bother with insurance company. To ensure you get your classic car policy. Safety classes therefore a good credit can make great savings by getting a temporary policy. The first car for a car with tons of horsepower is simply because you don't want to collect all the time to time in the position to command the best way to get some amazing plans, like Hagerty Plus, etc.
Load LFindLoad. From lfind Require Import LFind. From QuickChick Require Import QuickChick. From adtind Require Import goal33. Derive Show for natural. Derive Arbitrary for natural. Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed. Lemma conj5synthconj6 : forall (lv0 : natural) (lv1 : natural), (@eq natural (lv0) (mult lv1 Zero)). Admitted. QuickChick conj5synthconj6.
import numpy as np import cv2 from skimage.feature import hog # Create thresholded binary image def makeGrayImg(img, mask=None, clrspaceOrigin='BGR', colorspace='RGB', useChannel=0): ''' Returns a grey image based on the following inputs - mask - choice of color space - choice of channel(s) to use ''' # color space conversion if clrspaceOrigin == 'BGR': if colorspace != 'BGR': if colorspace == 'HSV': cvt_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) elif colorspace == 'LUV': cvt_img = cv2.cvtColor(img, cv2.COLOR_BGR2LUV) elif colorspace == 'HLS': cvt_img = cv2.cvtColor(img, cv2.COLOR_BGR2HLS) elif colorspace == 'YUV': cvt_img = cv2.cvtColor(img, cv2.COLOR_BGR2YUV) elif colorspace == 'RGB': cvt_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) elif colorspace == 'YCrCb': cvt_img = cv2.cvtColor(img, cv2.COLOR_BGR2YCR_CB) else: cvt_img = np.copy(img) # it's RGB otherwise else: if colorspace != 'RGB': if colorspace == 'HSV': cvt_img = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) elif colorspace == 'LUV': cvt_img = cv2.cvtColor(img, cv2.COLOR_RGB2LUV) elif colorspace == 'HLS': cvt_img = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) elif colorspace == 'YUV': cvt_img = cv2.cvtColor(img, cv2.COLOR_RGB2YUV) elif colorspace == 'BGR': cvt_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) elif colorspace == 'YCrCb': cvt_img = cv2.cvtColor(img, cv2.COLOR_RGB2YCR_CB) else: cvt_img = np.copy(img) # isolate channel if colorspace != 'GRAY': cvt_img = cvt_img[:,:,useChannel] # apply image mask if mask is not None: imgMask = np.zeros_like(cvt_img) ignore_mask_color = 255 # filling pixels inside the polygon defined by "vertices" with the fill color cv2.fillPoly(imgMask, mask, ignore_mask_color) # returning the image only where mask pixels are nonzero cvt_img = cv2.bitwise_and(cvt_img, imgMask) return cvt_img def convertClrSpace(img, clrspaceOrigin='BGR', colorspace='RGB'): # color space conversion if clrspaceOrigin == 'BGR': if colorspace != 'BGR': if colorspace == 'HSV': cvt_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) elif colorspace == 'LUV': cvt_img = cv2.cvtColor(img, cv2.COLOR_BGR2LUV) elif colorspace == 'HLS': cvt_img = cv2.cvtColor(img, cv2.COLOR_BGR2HLS) elif colorspace == 'YUV': cvt_img = cv2.cvtColor(img, cv2.COLOR_BGR2YUV) elif colorspace == 'RGB': cvt_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) elif colorspace == 'YCrCb': cvt_img = cv2.cvtColor(img, cv2.COLOR_BGR2YCR_CB) else: cvt_img = np.copy(img) # it's RGB otherwise else: if colorspace != 'RGB': if colorspace == 'HSV': cvt_img = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) elif colorspace == 'LUV': cvt_img = cv2.cvtColor(img, cv2.COLOR_RGB2LUV) elif colorspace == 'HLS': cvt_img = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) elif colorspace == 'YUV': cvt_img = cv2.cvtColor(img, cv2.COLOR_RGB2YUV) elif colorspace == 'BGR': cvt_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) elif colorspace == 'YCrCb': cvt_img = cv2.cvtColor(img, cv2.COLOR_RGB2YCR_CB) else: cvt_img = np.copy(img) return cvt_img def scaleImgValues(img, maxVal=None): if maxVal==None: maxVal=np.max(img) return np.uint8(255*img/maxVal) def writeImg(img, outFile, binary=False): if binary: # scale to 8-bit (0 - 255) img = np.uint8(255*img) cv2.imwrite(outFile, img) def get_spatial_features(img, size=(32, 32)): # Use cv2.resize().ravel() to create the feature vector features = cv2.resize(img, size).ravel() # Return the feature vector return features def get_colorHist_features(img, nbins=32, bins_range=(0, 256)): ''' returns feature vector of all single channel histograms of the image note: feature vector from greyscale image will be 1/3 the size of the feature vector of a color image ''' # Compute the histogram of the color channels separately channel1_hist = np.histogram(img[:,:,0], bins=nbins, range=bins_range) if img.shape[2] != 0: channel2_hist = np.histogram(img[:,:,1], bins=nbins, range=bins_range) channel3_hist = np.histogram(img[:,:,2], bins=nbins, range=bins_range) # Concatenate the histograms into a single feature vector features = np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0])) else: features = channel1_hist[0] return features def get_hog_features(img, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True): if vis == True: features, hog_image = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell), cells_per_block=(cell_per_block, cell_per_block), transform_sqrt=False, visualise=True, feature_vector=False) return features, hog_image else: features = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell), cells_per_block=(cell_per_block, cell_per_block), transform_sqrt=False, visualise=False, feature_vector=feature_vec) return features # Define a function to extract features from a list of images # Have this function call bin_spatial() and color_hist() def extract_features(imgs, readImg = True, hogArr=None, cspace='RGB', spatial_size=(32, 32), hist_bins=32, hist_range=(0, 256), spatialFeat = True, histFeat = True, hogFeat=True, hog_cspace='RGB', hog_orient=9, hog_pix_per_cell=8, hog_cell_per_block=2, hog_channel=0, hogVec = True): # Create a list to append feature vectors to features = [] i = 0 # Iterate through the list of images for file in imgs: spatial_features = [] hist_features = [] hog_features = [] # Read in each one by one if readImg: image = cv2.imread(file) else: image = np.copy(file) # apply color conversion if other than 'BGR' if spatialFeat or histFeat: if cspace != 'BGR': if cspace == 'HSV': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) elif cspace == 'LUV': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2LUV) elif cspace == 'HLS': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2HLS) elif cspace == 'YUV': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2YUV) elif cspace == 'RGB': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) elif cspace == 'YCrCb': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2YCR_CB) else: feature_image = np.copy(image) if spatialFeat: # get spatial color features spatial_features = get_spatial_features(feature_image, size=spatial_size) if histFeat: # get histogram features hist_features = get_colorHist_features(feature_image, nbins=hist_bins, bins_range=hist_range) if hogFeat: # apply color conversion if other than 'RGB' if hogArr == None: if hog_cspace != 'BGR': if hog_cspace == 'HSV': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) elif hog_cspace == 'LUV': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2LUV) elif hog_cspace == 'HLS': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2HLS) elif hog_cspace == 'YUV': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2YUV) elif hog_cspace == 'YCrCb': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2YCR_CB) elif hog_cspace == 'RGB': feature_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) else: feature_image = np.copy(image) # Call get_hog_features() with vis=False, feature_vec=True for channel in hog_channel: hog_features.append(get_hog_features(feature_image[:,:,channel], hog_orient, hog_pix_per_cell, hog_cell_per_block, vis=False, feature_vec=hogVec)) hog_features = np.ravel(hog_features) else: hog_features = hogArr[i] i+=1 # Append the new feature vector to the features list features.append(np.concatenate((spatial_features, hist_features, hog_features))) # Return list of feature vectors return features def slide_window(img, x_start_stop=[None, None], y_start_stop=[None, None], windowSizeAr=[64], xy_overlap=(0.5, 0.5)): # If x and/or y start/stop positions not defined, set to image size if x_start_stop[0] == None: x_start_stop[0] = 0 if x_start_stop[1] == None: x_start_stop[1] = img.shape[1] if y_start_stop[0] == None: y_start_stop[0] = 0 if y_start_stop[1] == None: y_start_stop[1] = img.shape[0] # Compute the span of the region to be searched xspan = x_start_stop[1] - x_start_stop[0] yspan = y_start_stop[1] - y_start_stop[0] # Initialize a list to append window positions to window_list = [] for windowSize in windowSizeAr: xy_window = (windowSize, windowSize) # Compute the number of pixels per step in x/y nx_pix_per_step = np.int(xy_window[0]*(1 - xy_overlap[0])) ny_pix_per_step = np.int(xy_window[1]*(1 - xy_overlap[1])) # Compute the number of windows in x/y nx_windows = np.int(xspan/nx_pix_per_step) -1 ny_windows = np.int(yspan/ny_pix_per_step) -1 # Loop through finding x and y window positions # Note: you could vectorize this step, but in practice # you'll be considering windows one by one with your # classifier, so looping makes sense for ys in range(ny_windows): for xs in range(nx_windows): # Calculate window position startx = xs*nx_pix_per_step + x_start_stop[0] endx = startx + xy_window[0] starty = ys*ny_pix_per_step + y_start_stop[0] endy = starty + xy_window[1] # Append window position to list window_list.append(((int(startx), int(starty)), (int(endx), int(endy)))) # Return the list of windows return window_list def get_window_imgs(img, windows, outSize, resize=True): imgs = [] for window in windows: if resize: imgs.append(cv2.resize(img[window[0][1]:window[1][1], window[0][0]:window[1][0]], (64, 64))) else: imgs.append(img[window[0][1]:window[1][1], window[0][0]:window[1][0]]) imgs = np.array(imgs) return imgs # Define a function to draw bounding boxes def draw_boxes(img, bboxes, color=(0, 0, 255), thick=6, windowSizeAr=[64]): # Make a copy of the image imcopy = np.copy(img) # Iterate through the bounding boxes for bbox in bboxes: # Draw a rectangle given bbox coordinates cv2.rectangle(imcopy, bbox[0], bbox[1], color, thick) # Return the image copy with boxes drawn return imcopy def add_heat(heatmap, bbox_list): # Iterate through list of bboxes for box in bbox_list: # Add += 1 for all pixels inside each bbox # Assuming each "box" takes the form ((x1, y1), (x2, y2)) heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1 # Return updated heatmap return heatmap# Iterate through list of bboxes def apply_threshold(heatmap, threshold): # Zero out pixels below the threshold heatmap[heatmap <= threshold] = 0 # Return thresholded map return heatmap def draw_labeled_bboxes(img, labels): # Iterate through all detected cars for car_number in range(1, labels[1]+1): # Find pixels with each car_number label value nonzero = (labels[0] == car_number).nonzero() # Identify x and y values of those pixels nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) # Define a bounding box based on min/max x and y bbox = ((np.min(nonzerox), np.min(nonzeroy)), (np.max(nonzerox), np.max(nonzeroy))) # Draw the box on the image cv2.rectangle(img, bbox[0], bbox[1], (0,0,255), 6) cv2.rectangle(img,(bbox[0][0],bbox[0][1]-20),(bbox[0][0]+100,bbox[0][1]),(125,125,125),-1) cv2.putText(img, 'car {}'.format(car_number),(bbox[0][0]+5,bbox[0][1]-2),cv2.FONT_HERSHEY_SIMPLEX,0.8,(0,0,0), thickness=2) #cv2.putText(img, 'car {}'.format(car_number),(bbox[0][0],bbox[0][1]-7),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,0,0),1) # Return the image return img def draw_labeled_carBboxes(img, cars): # Iterate through all detected cars for car_number in range(len(cars)): bbox = cars[car_number].getBbox() if bbox != None: cv2.rectangle(img, (bbox[0][0],bbox[0][1]), (bbox[1][0],bbox[1][1]), (0,0,255), 6) #cv2.rectangle(img,(bbox[0][0],bbox[0][1]-20),(bbox[0][0]+100,bbox[0][1]),(125,125,125),-1) #cv2.putText(img, 'car {}'.format(car_number+1),(bbox[0][0]+5,bbox[0][1]-2),cv2.FONT_HERSHEY_SIMPLEX,0.8,(0,0,0), thickness=2) # Return the image return img
[STATEMENT] lemma closed_approachable: fixes S :: "'a::metric_space set" shows "closed S \<Longrightarrow> (\<forall>e>0. \<exists>y\<in>S. dist y x < e) \<longleftrightarrow> x \<in> S" [PROOF STATE] proof (prove) goal (1 subgoal): 1. closed S \<Longrightarrow> (\<forall>e>0. \<exists>y\<in>S. dist y x < e) = (x \<in> S) [PROOF STEP] by (metis closure_closed closure_approachable)
1944 ( shared )
function view = plotResidualError(view,scan,baseFrame) % % view = plotResidualError(view,scan,[baseFrame]) % % Plots the rmse between each frame and a baseFrame % % If you change this function make parallel changes in: % plotMaxTSErr % % djh, 2/2001. rmse instead of var, conver to 3.0 if ~exist('scan','var') scan = getCurScan(view); end if ~exist('baseFrame','var') baseFrame=1; %baseFrame=nFrames; end slices = sliceList(view,scan); nSlices = length(slices); nFrames = numFrames(view,scan); % Load tSerises and compute RMSE slice by slice waitHandle = mrvWaitbar(0,'Loading tSeries and computing RMSE. Please wait...'); vres = zeros(nSlices,nFrames); for slice=slices mrvWaitbar(slice/nSlices); tSeries = loadtSeries(view,scan,slice); for frame=1:nFrames vres(slice,frame) = sqrt(mse(tSeries(frame,:),tSeries(baseFrame,:))); end end close(waitHandle) % mean across slices vres = mean(vres); % dont plot anything for the base frame (otherwise it would be 0) vres(baseFrame)=NaN; % plot it selectGraphWin; fontSize = 14; set(gcf,'Name',['RMSE, scan: ',num2str(scan),', baseframe:',int2str(baseFrame)]); x = 1:nFrames; plot(x,vres,'-b','LineWidth',2) set(gca,'FontSize',fontSize) set(gca,'XLim',[0,nFrames]); xlabel('Frame number','FontSize',fontSize) ylabel('RMSE (raw intensity units)','FontSize',fontSize) % Save the data in gca('UserData') data.frameNumbers = x; data.tSeries = vres; set(gca,'UserData',data); return
Before you turn this problem in, make sure everything runs as expected. First, **restart the kernel** (in the menubar, select Kernel$\rightarrow$Restart) and then **run all cells** (in the menubar, select Cell$\rightarrow$Run All). **NB. Do not add new or remove/cut cells in the notebook. Additionally, do not change the filename of this notebook.** Make sure you fill in any place that says `YOUR CODE HERE` or "YOUR ANSWER HERE", as well as your student number below: ```python STUDENT_NUMBER = "141927" ``` --- # Exercises Topic 4 ```python # imports import numpy as np from matplotlib import pyplot as plt ``` ## Exercise 4.1: Detecting periodicity (4 points) In the folder that you obtained this notebook there is a file called `sunspots.txt`, which contains the observed number of sunspots on the Sun for each month since January 1749. The file contains two columns of numbers, the first representing the month and the second being the sunspot number. (a) Write a program that reads the data in the file and makes a graph of sunspots as a function of time. You should see that the number of sunspots has fluctuated on a regular cycle for as long as observations have been recorded. Make an estimate of the length of the cycle in months. ```python def read_sunspot_data(filename): """Reads and returns sunspot data Args: filename (str): name of the file Returns: numpy array: the data""" data = None # YOUR CODE HERE data = np.loadtxt(filename) #raise NotImplementedError() return data data = read_sunspot_data('sunspots.txt') # plotting # YOUR CODE HERE plt.plot(data[:,0], data[:,1]) #raise NotImplementedError() plt.xlabel('time (months)') plt.ylabel('sunspot (#)') ``` ### Answer (Double click to edit) There seems to 24 peaks in a time period of 3143 months, or about 272 years. This means that a peak occurs every ~131 months, or once in every 11 years. ```python # validation fn = read_sunspot_data('sunspots.txt') assert isinstance(fn, np.ndarray), 'bad function' assert fn.shape == (3143, 2), 'bad shape' assert fn.dtype == float, 'bad type' ``` (b) Modify your program to calculate the Fourier transform of the sunspot data and then make a graph of the magnitude squared $|c_k|^2$ of the Fourier coefficients as a function of $k$---also called the *power spectrum* of the sunspot signal. You should see that there is a noticeable peak in the power spectrum at a nonzero value of~$k$. The appearance of this peak tells us that there is one frequency in the Fourier series that has a higher amplitude than the others around it---meaning that there is a large sine-wave term with this frequency, which corresponds to the periodic wave you can see in the original data. ```python def discrete_fourier_transform(y): """Calculates coefficient of the discrete trasnform of 1D y Args: y (numpy array): 1D data Returns: numpy array: 1D array of coefficients after fourier transform""" # coefficients c = None # YOUR CODE HERE N = len(y) n = np.arange(N) c = np.zeros(N//2+1,complex) for k in range(N//2+1): c[k] = np.sum(y*np.exp(-2j*np.pi*k*n/N)) #raise NotImplementedError() return c ``` ```python # validation n = 10 fn = np.sin(np.arange(n)) dft = discrete_fourier_transform(fn) c_k2 = np.abs(dft)**2 assert abs(c_k2[0] - 3.82284412) <= 1e-4, 'bad function' assert abs(c_k2[1] - 10.28600735) <= 1e-4, 'bad function' ``` ```python fft_data = discrete_fourier_transform(data[:, 1]) #plotting # YOUR CODE HERE plt.plot(np.square(abs(fft_data))) #raise NotImplementedError() plt.xlabel('k') plt.ylabel('$c_k^2$') ``` ```python plt.plot(np.square(abs(fft_data[0:50]))) # Zoom closer to the non-zero peak #raise NotImplementedError() plt.xlabel('k') plt.ylabel('$c_k^2$') k = 24 N = data.shape[0] print(f"k = {k}: freq = {N}/{k} = {N/k}") ``` (c) Find the approximate value of $k$ to which the peak corresponds. What is the period of the sine wave with this value of $k$? You should find that the period corresponds roughly to the length of the cycle that you estimated in part~(a). This kind of Fourier analysis is a sensitive method for detecting periodicity in signals. Even in cases where it is not clear to the eye that there is a periodic component to a signal, it may still be possible to find one using a Fourier transform. ### Answer (Double click to edit) From the plot, it can be visually estimated that the peak occurs approximately at $k=24$. When the total number of data points, 3143, is divided by $k$, we get the frequency: $N/k = 3143$ months $/24 \approx 130.96$ months, which is very close to the approximated value 131 months. ## Exercise 4.2: Fourier filtering and smoothing (6 points) In the folder that you obtained this notebook you'll find a file called `dow.txt`. It contains the daily closing value for each business day from late 2006 until the end of 2010 of the Dow Jones Industrial Average, which is a measure of average prices on the US stock market. Write a program to do the following: (a) Read in the data from `dow.txt` and plot them on a graph. ```python def read_dow_data(filename): """read dow data from filename Args: filename (str): name of the file Returns: numpy array: dow data""" data = None # YOUR CODE HERE data = np.loadtxt(filename) #raise NotImplementedError() return data data = read_dow_data('dow.txt') # plotting # YOUR CODE HERE plt.plot(data) #raise NotImplementedError() plt.xlabel('days') plt.ylabel('closing value') ``` ```python # validation fn = read_dow_data('dow.txt') assert isinstance(fn, np.ndarray), 'bad function' assert fn.shape == (1024,), 'bad function' assert fn.dtype == float, 'bad function' ``` (b) Calculate the coefficients of the discrete Fourier transform of the data using the function `rfft` from `numpy.fft`, which produces an array of $\frac{1}{2} N+1$ complex numbers. ```python def dft_numpy(y): """Perform numpy rfft Args: y (array): input data Returns: numpy array: dft of data """ dft = None # modifications on y should not change incomming data too y = np.copy(y) # YOUR CODE HERE dft = np.fft.rfft(y) #raise NotImplementedError() return dft # compute dft dft_data = dft_numpy(data) ``` ```python # validation n = 10 fn = np.sin(np.arange(n)) dft = dft_numpy(fn) c_k2 = np.abs(dft)**2 assert abs(c_k2[0] - 3.82284412) <= 1e-4, 'bad function' assert abs(c_k2[1] - 10.28600735) <= 1e-4, 'bad function' ``` (c) Now set all but the first 10\% of the elements of this array to zero (i.e.,~set the last 90\% to zero but keep the values of the first 10\%). ```python def data_trim(y, x): """trim data, by making all but first x% elements to zero Args: y (numpy array): fft data x (float): percentage of first elements to be the same Returns: numpy array: trimmed data """ partc_out = None # modifications on y should not change incomming data too y = np.copy(y) # YOUR CODE HERE i = int(len(y)*x/100) partc_out = np.zeros_like(y) partc_out[:i] = y[:i] #raise NotImplementedError() return partc_out dft_data_trimmed = data_trim(dft_data, 10) ``` ```python # validation a = np.arange(1, 11) a_trimmed = data_trim(a, 10) assert len(a_trimmed) == len(a), 'bad function' for i in range(1, 10): assert len(np.where(data_trim(a, i*10)==0)[0]) == 10 - i, 'bad function at i = {}'.format(i) ``` (d) Calculate the inverse Fourier transform of the resulting array, zeros and all, using the function \verb|irfft|, and plot it on the same graph as the original data. You may need to vary the colors of the two curves to make sure they both show up on the graph. Comment on what you see. What is happening when you set the Fourier coefficients to zero? ```python def idft_numpy(y): """Perform numpy irfft Args: y (array): input data Returns: numpy array: dft of data """ idft = None # modifications on y should not change incomming data too y = np.copy(y) # YOUR CODE HERE idft = np.fft.irfft(y) #raise NotImplementedError() return idft # compute idft data_idft = idft_numpy(dft_data_trimmed) # plotting # YOUR CODE HERE plt.plot(data, label='original') plt.plot(data_idft, label='irfft') plt.legend() #raise NotImplementedError() plt.xlabel('days') plt.ylabel('closing value') ``` ### Answer (Double click to edit) The inverse FFT adapts to the original data quite well. Increasing the percentage x of the data used to perform the inverse FFT, i.e. decreasing the number of zeros, makes the irfft data more accurate. In other words, decreasing the percentage makes the function smoother. 10% data usage already seems to be enough to get very good approximation of the original data. ```python # validation n = 10 fn = np.sin(np.arange(n)) dft = dft_numpy(fn) fn_idft = idft_numpy(dft) assert np.mean(np.abs(fn - fn_idft)) <= 1e-4, 'bad function' ``` (e) Modify your program so that it sets all but the first 2\% of the coefficients to zero and run it again. ```python # get trimmed data # YOUR CODE HERE dft_data_trimmed_2 = data_trim(dft_data, 2) data_idft_2 = idft_numpy(dft_data_trimmed_2) #raise NotImplementedError() # plotting # YOUR CODE HERE plt.plot(data, label='original') plt.plot(data_idft_2, label='irfft') plt.legend() #raise NotImplementedError() plt.xlabel('days') plt.ylabel('closing value') ``` ## Exercise 4.3: Comparison of the DFT and DCT (3 points) Exercise 4.2 looked at data representing the variation of the Dow Jones Industrial Average, colloquially called "the Dow," over time. The particular time period studied in that exercise was special in one sense: the value of the Dow at the end of the period was almost the same as at the start, so the function was, roughly speaking, periodic. In the folder that you obtained this notebook there is another file called `dow2.txt`, which also contains data on the Dow but for a different time period, from 2004 until 2008. Over this period the value changed considerably from a starting level around 9000 to a final level around 14000. (a) Write a program in which you read the data in the file `dow2.txt` and plot it on a graph. Then smooth the data by calculating its Fourier transform, setting all but the first 2\% of the coefficients to zero, and inverting the transform again, plotting the result on the same graph as the original data. You should see that the data are smoothed, but now there will be an additional artifact. At the beginning and end of the plot you should see large deviations away from the true smoothed function. These occur because the function is required to be periodic---its last value must be the same as its first---so it needs to deviate substantially from the correct value to make the two ends of the function meet. In some situations (including this one) this behavior is unsatisfactory. If we want to use the Fourier transform for smoothing, we would certainly prefer that it not introduce artifacts of this kind. ```python # use already made functions in 4.2 # YOUR CODE HERE data = read_dow_data('dow2.txt') dft_data = dft_numpy(data) dft_data_trimmed = data_trim(dft_data, 2) data_idft = idft_numpy(dft_data_trimmed) #raise NotImplementedError() # plotting # YOUR CODE HERE plt.plot(data, label='original') plt.plot(data_idft, label='irfft') plt.legend() #raise NotImplementedError() plt.xlabel('days') plt.ylabel('DOW closing values') ``` (b) Modify your program to repeat the same analysis using discrete cosine transforms. You can use the functions from `dcst.py` (in the folder that you obtained this notebook) to perform the transforms if you wish. Again discard all but the first 2\% of the coefficients, invert the transform, and plot the result. You should see a significant improvement, with less distortion of the function at the ends of the interval. This occurs because the cosine transform does not force the value of the function to be the same at both ends. It is because of the artifacts introduced by the strict periodicity of the DFT that the cosine transform is favored for many technological applications, such as audio compression. The artifacts can degrade the sound quality of compressed audio and the cosine transform generally gives better results. The cosine transform is not wholly free of artifacts itself however. It's true it does not force the function to be periodic, but it does force the gradient to be zero at the ends of the interval (which the ordinary Fourier transform does not). You may be able to see this in your calculations for part (b) above. Look closely at the smoothed function and you should see that its slope is flat at the beginning and end of the interval. The distortion of the function introduced is less than the distortion in part (a), but it's there all the same. To reduce this effect, audio compression schemes often use overlapped cosine transforms, in which transforms are performed on overlapping blocks of samples, so that the portions at the ends of blocks, where the worst artifacts lie, need not be used. ```python # use already made functions in 4.2 and dcst.py from dcst import dct, idct # YOUR CODE HERE data = read_dow_data('dow2.txt') dct_data = dct(data) dct_data_trimmed = data_trim(dct_data, 2) data_idct = idct(dct_data_trimmed) #raise NotImplementedError() # plotting # YOUR CODE HERE plt.plot(data, label='original') plt.plot(data_idct, label='idct') plt.legend() #raise NotImplementedError() plt.xlabel('days') plt.ylabel('DOW closing values') ``` ## Exercise 4.4: Image deconvolution (7 points) You've probably seen it on TV, in one of those crime drama shows. They have a blurry photo of a crime scene and they click a few buttons on the computer and magically the photo becomes sharp and clear, so you can make out someone's face, or some lettering on a sign. Surely (like almost everything else on such TV shows) this is just science fiction? Actually, no. It's not. It's real and in this exercise you'll write a program that does it. When a photo is blurred each point on the photo gets smeared out according to some "smearing distribution," which is technically called a *point spread function*. We can represent this smearing mathematically as follows. For simplicity let's assume we're working with a black and white photograph, so that the picture can be represented by a single function $a(x,y)$ which tells you the brightness at each point $(x,y)$. And let us denote the point spread function by $f(x,y)$. This means that a single bright dot at the origin ends up appearing as $f(x,y)$ instead. If $f(x,y)$ is a broad function then the picture is badly blurred. If it is a narrow peak then the picture is relatively sharp. In general the brightness $b(x,y)$ of the blurred photo at point $(x,y)$ is given by $$\begin{equation} b(x,y) = \int_0^K \int_0^L a(x',y') f(x-x',y-y') \>d x'\>d y', \end{equation}$$ where $K\times L$ is the dimension of the picture. This equation is called the *convolution* of the picture with the point spread function. Working with two-dimensional functions can get complicated, so to get the idea of how the math works, let's switch temporarily to a one-dimensional equivalent of our problem. Once we work out the details in 1D we'll return to the 2D version. The one-dimensional version of the convolution above would be $$\begin{equation} b(x) = \int_0^L a(x') f(x-x') \>d x'. \end{equation}$$ The function $b(x)$ can be represented by a Fourier series as in Eq. (7.5): $$\begin{equation} b(x) = \sum_{k=-\infty}^\infty \tilde{b}_k \exp\biggl( i {2\pi k x\over L} \biggr), \end{equation}$$ where $$\begin{equation} \tilde{b}_k = {1\over L} \int_0^L b(x) \exp\biggl( -i {2\pi k x\over L} \biggr) \>d x \end{equation}$$ are the Fourier coefficients. Substituting for $b(x)$ in this equation gives $$\begin{align*} \tilde{b}_k &= {1\over L} \int_0^L \int_0^L a(x') f(x-x') \exp\biggl( -i {2\pi k x\over L} \biggr) \>d x'\>d x \\ &= {1\over L} \int_0^L \int_0^L a(x') f(x-x') \exp\biggl( -i {2\pi k (x-x')\over L} \biggr) \exp\biggl( -i {2\pi k x'\over L} \biggr) \>d x'\>d x. \end{align*}$$ Now let us change variables to $X=x-x'$, and we get $$\begin{equation} \tilde{b}_k = {1\over L} \int_0^L a(x') \exp\biggl( -i {2\pi k x'\over L} \biggr) \int_{-x'}^{L-x'} f(X) \exp\biggl( -i {2\pi k X\over L} \biggr) \>d X \>d x'. \end{equation}$$ If we make $f(x)$ a periodic function in the standard fashion by repeating it infinitely many times to the left and right of the interval from 0 to~$L$, then the second integral above can be written as $$\begin{align*} \int_{-x'}^{L-x'} f(X) \exp\biggl( -i {2\pi k X\over L} \biggr) \>d X &= \int_{-x'}^0 f(X) \exp\biggl( -i {2\pi k X\over L} \biggr) \>d X \\ &\hspace{5em}{} + \int_0^{L-x'} f(X) \exp\biggl( -i {2\pi k X\over L} \biggr) \>d X \\ &\hspace{-12em} {} = \exp\biggl( i {2\pi k L\over L} \biggr) \int_{L-x'}^L f(X) \exp\biggl( -i {2\pi k X\over L} \biggr) \>d X + \int_0^{L-x'} f(X) \exp\biggl( -i {2\pi k X\over L} \biggr) \>d X \\ &\hspace{-12em} {} = \int_0^L f(X) \exp\biggl( -i {2\pi k X\over L} \biggr) \>d X, \end{align*}$$ which is simply $L$ times the Fourier transform $\tilde{f}_k$ of $f(x)$. Substituting this result back into our equation for $\tilde{b}_k$ we then get $$\begin{align*} \tilde{b}_k = \int_0^L a(x') \exp\biggl( -i {2\pi k x'\over L} \biggr) \tilde{f}_k \>d x' = L\,\tilde{a}_k\tilde{f}_k. \end{align*}$$ In other words, apart from the factor of $L$, the Fourier transform of the blurred photo is the product of the Fourier transforms of the unblurred photo and the point spread function. Now it is clear how we deblur our picture. We take the blurred picture and Fourier transform it to get $\tilde{b}_k = L\,\tilde{a}_k\tilde{f}_k$. We also take the point spread function and Fourier transform it to get~$\tilde{f}_k$. Then we divide one by the other: $$\begin{equation} {\tilde{b}_k\over L\tilde{f}_k} = \tilde{a}_k \end{equation}$$ which gives us the Fourier transform of the \emph{unblurred} picture. Then, finally, we do an inverse Fourier transform on $\tilde{a}_k$ to get back the unblurred picture. This process of recovering the unblurred picture from the blurred one, of reversing the convolution process, is called *deconvolution*. Real pictures are two-dimensional, but the mathematics follows through exactly the same. For a picture of dimensions $K\times L$ we find that the two-dimensional Fourier transforms are related by $$\begin{equation} \tilde{b}_{kl} = KL\tilde{a}_{kl}\tilde{f}_{kl}\,, \end{equation}$$ and again we just divide the blurred Fourier transform by the Fourier transform of the point spread function to get the Fourier transform of the unblurred picture. In the digital realm of computers, pictures are not pure functions $f(x,y)$ but rather grids of samples, and our Fourier transforms are discrete transforms not continuous ones. But the math works out the same again. The main complication with deblurring in practice is that we don't usually know the point spread function. Typically we have to experiment with different ones until we find something that works. For many cameras it's a reasonable approximation to assume the point spread function is Gaussian: $$\begin{equation} f(x,y) = \exp\biggl( -{x^2+y^2\over2\sigma^2} \biggr), \end{equation}$$ where $\sigma$ is the width of the Gaussian. Even with this assumption, however, we still don't know the value of $\sigma$ and we may have to experiment to find a value that works well. In the following exercise, for simplicity, we'll assume we know the value of $\sigma$. (a) In the folder that you obtained this notebook you will find a file called `blur.txt` that contains a grid of values representing brightness on a black-and-white photo---a badly out-of-focus one that has been deliberately blurred using a Gaussian point spread function of width $\sigma=25$. Write a program that reads the grid of values into a two-dimensional array of real numbers and then draws the values on the screen of the computer as a density plot. You should see the photo appear. If you get something wrong it might be upside-down. Work with the details of your program until you get it appearing correctly. (Hint: The picture has the sky, which is bright, at the top and the ground, which is dark, at the bottom.) ```python def read_2D_data(filename): """Reads 2D data Args: filename (str): name of the file Returns: numpy array: the data""" data = None # YOUR CODE HERE data = np.loadtxt(filename) #raise NotImplementedError() return data data = read_2D_data('blur.txt') # plotting # YOUR CODE HERE plt.imshow(data, cmap='gray') plt.show() #raise NotImplementedError() ``` ```python # validation data = read_2D_data('blur.txt') assert isinstance(data, np.ndarray), 'bad function' assert data.dtype == float, 'bad function' assert data.shape == (1024, 1024), 'bad function' ``` (b) Write another program that creates an array, of the same size as the photo, containing a grid of samples drawn from the Gaussian~$f(x,y)$ above with $\sigma=25$. Make a density plot of these values on the screen too, so that you get a visualization of your point spread function. Remember that the point spread function is periodic (along both axes), which means that the values for negative $x$ and $y$ are repeated at the end of the interval. Since the Gaussian is centered on the origin, this means there should be bright patches in each of the four corners of your picture, something like this: Note: This photo has a smaller shape, than the blur.txt, therefore the spreads will not be as drastic as in the photo. ```python def get_point_spread_function(data, sigma): """Retruns a gaussian point spread function Args: data (numpy array): the photo array to get the size of the spread function sigma (float): sigma of gaussian Returns: numpy array: the point spread function""" spread = np.zeros_like(data) # YOUR CODE HERE w = 2*sigma**2 # Upper left corner x,y = np.meshgrid(np.arange(data.shape[0]), np.arange(data.shape[1])) d = x*x + y*y spread += np.exp(-d/w) # Upper right corner x,y = np.meshgrid(np.arange(data.shape[0]-1,-1,-1), np.arange(data.shape[1])) d = x*x + y*y spread += np.exp(-d/w) # Lower left corner x,y = np.meshgrid(np.arange(data.shape[0]), np.arange(data.shape[1]-1,-1,-1)) d = x*x + y*y spread += np.exp(-d/w) # Lower right corner x,y = np.meshgrid(np.arange(data.shape[0]-1,-1,-1), np.arange(data.shape[1]-1,-1,-1)) d = x*x + y*y spread += np.exp(-d/w) #raise NotImplementedError() return spread point_func = get_point_spread_function(data, 25) # plotting # YOUR CODE HERE plt.imshow(point_func, cmap='gray') plt.show() #raise NotImplementedError() ``` ```python # validation fn = read_2D_data('blur.txt') pt_fn = get_point_spread_function(fn, 25) assert pt_fn.shape == fn.shape, 'shape mismatch' # checking 90 deg rotational symmetry, since the gaussian is even in all corners assert np.mean(np.abs(pt_fn - np.rot90(pt_fn, k=1))) <= 1e-4, 'bad function' ``` (c) Combine your two programs and add Fourier transforms using the functions `rfft2` and `irfft2` from `numpy.fft`, to make a program that does the following: i) Calculates Fourier transform of both, photo and point spread function ii) Divides one by the other iii) Performs an inverse transform to get the unblurred photo iv) Displays the unblurred photo on the screen When you are done, you should be able to make out the scene in the photo, although probably it will still not be perfectly sharp. Hint: One thing you'll need to deal with is what happens when the Fourier transform of the point spread function is zero, or close to zero. In that case if you divide by it you'll get an error (because you can't divide by zero) or just a very large number (because you're dividing by something small). A workable compromise is that if a value in the Fourier transform of the point spread function is smaller than a certain amount $\epsilon$ you don't divide by it---just leave that coefficient alone. The value of $\epsilon$ is not very critical but a reasonable value seems to be $10^{-3}$. ```python def deconvolve(data, point_function): """Deconvolves point_function from the data Args: data (numpy array): the 2D data to deconvolve point_dunction (numpy array): the point function Returns: numpy array: Deconvolved array""" deconv_data = np.zeros_like(data) epsilon = 1e-3 # YOUR CODE HERE # FFT for the blurred data rfft_data = np.fft.rfft2(data) # FFT for the spread function rfft_pf = np.fft.rfft2(point_function) # Assign elements lower than epsilon to 1 in spread func fft # (division by 1 = No division) rfft_pf[rfft_pf < epsilon] = 1 # a_kl = b_kl / (f_kl * K * L) conv_data = rfft_data / (rfft_pf * data.shape[0] * data.shape[1]) # Inverse FFT for the convoluted data deconv_data = np.fft.irfft2(conv_data) #raise NotImplementedError() return deconv_data data = read_2D_data('blur.txt') # try different values of sigma to get the best deconvolution without artefacts point_func = get_point_spread_function(data, 19) deconc_data = deconvolve(data, point_func) # plotting # YOUR CODE HERE plt.imshow(deconc_data, cmap='gray') plt.show() #raise NotImplementedError() ``` (d) Bearing in mind this last point about zeros in the Fourier transform, what is it that limits our ability to deblur a photo? Why can we not perfectly unblur any photo and make it completely sharp? We have seen this process in action here for a normal snapshot, but it is also used in many physics applications where one takes photos. For instance, it is used in astronomy to enhance photos taken by telescopes. It was famously used with images from the Hubble Space Telescope after it was realized that the telescope's main mirror had a serious manufacturing flaw and was returning blurry photos---scientists managed to partially correct the blurring using Fourier transform techniques. ### Answer (double click to edit) If the values in the fourier transformed point function become very small, those points cannot be divided, i.e. it is left "untreated", which decreases the unblurring. If enough points are left untouched, the image cannot be properly unblurred. Because the fourier transform produces very small values for at least some of the points, the unblurring can never be perfect. Also, if the point function parameter sigma is increased too much, artifacts are introduced to the image. While increasing the sigma makes the image sharper, at some point it start to draw grid-like dots on the image, which occurs because the Gaussians become too wide. ```python ```
\subsection{Enumeration types} \label{subsec:library_of_transformations:type_level_transformations:enumeration_types} \begin{figure}[H] \centering \begin{subfigure}{0.25\textwidth} \centering \includegraphics{images/05_library_of_transformations/02_type_level_transformations/04_enumeration_types/enum_type.pdf} \caption{$Tm_{Enum}$ with \\$name = .\type{Example}$ and \\$values = \{ \type{OPTION\_A},$\\$ \type{OPTION\_B}, \type{OPTION\_C} \}$} \label{fig:library_of_transformations:type_level_transformations:enumeration_types:visualisation:ecore} \end{subfigure} \\ \begin{subfigure}{0.65\textwidth} \centering \input{images/05_library_of_transformations/02_type_level_transformations/04_enumeration_types/enum_as_node_types.tikz} \caption{$TG_{EnumNodes}$ with $name = .\type{Example}$ and\\$values = \{ \type{OPTION\_A}, \type{OPTION\_B}, \type{OPTION\_C} \}$} \label{fig:library_of_transformations:type_level_transformations:enumeration_types:visualisation:groove_nodes} \end{subfigure} \begin{subfigure}{0.25\textwidth} \centering \input{images/05_library_of_transformations/02_type_level_transformations/04_enumeration_types/enum_as_flags.tikz} \caption{$TG_{EnumFlags}$ with \\$name = .\type{Example}$ and \\$values = \{ \type{OPTION\_A},$\\$ \type{OPTION\_B}, \type{OPTION\_C} \}$} \label{fig:library_of_transformations:type_level_transformations:enumeration_types:visualisation:groove_flags} \end{subfigure} \caption{Visualisations of the transformations of enumeration types} \label{fig:library_of_transformations:type_level_transformations:enumeration_types:visualisation} \end{figure} This section will define the transformation of an enumeration type. Within this transformation, a new enumeration type is introduced, including its possible values. The Ecore type model that introduces such a subclass is defined as follows: \begin{defin}[Type model $Tm_{Enum}$] \label{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum} Let $Tm_{Enum}$ be the type model containing a enumeration type with identifier $name$. The values of this enumeration type are defined as part of sequence $values$. $Tm_{Enum}$ is defined as: \begin{align*} Class =\ &\{\} \\ Enum =\ &\{name\} \\ UserDataType =\ &\{\} \\ Field =\ &\{\} \\ \mathrm{FieldSig} =\ &\{\} \\ EnumValue =\ &\{ (name, v) \mid v \in values \} \\ Inh =\ &\{\} \\ Prop =\ &\{\} \\ Constant =\ &\{\} \\ \mathrm{ConstType} =\ &\{\} \end{align*} \isabellelref{tmod_enum}{Ecore-GROOVE-Mapping-Library.EnumType} \end{defin} \begin{thm}[Correctness of $Tm_{Enum}$] \label{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum_correct} $Tm_{Subclass}$ (\cref{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum}) is a consistent type model in the sense of \cref{defin:formalisations:ecore_formalisation:type_models:type_model_consistency}. \isabellelref{tmod_enum_correct}{Ecore-GROOVE-Mapping-Library.EnumType} \end{thm} A visual representation of $Tm_{Enum}$ with $.\type{Example}$ as identifier for the new enumeration type and $\type{OPTION\_A}$, $\type{OPTION\_B}$ and $\type{OPTION\_C}$ as its values can be seen in \cref{fig:library_of_transformations:type_level_transformations:enumeration_types:visualisation:ecore}. The correctness proof of $Tm_{Enum}$ is trivial, and therefore not included here. The proof can be found as part of the Isabelle validated proofs. In order to make composing transformation functions possible, $Tm_{Enum}$ should be compatible with the type model it is combined with. \begin{thm}[Correctness of $\mathrm{combine}(Tm, Tm_{Enum})$] \label{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum_combine_correct} Assume a type model $Tm$ that is consistent in the sense of \cref{defin:formalisations:ecore_formalisation:type_models:type_model_consistency}. Then $Tm$ is compatible with $Tm_{Enum}$ (in the sense of \cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:compatibility}) if: \begin{itemize} \item The identifier of the enumeration type in $Tm_{Enum}$ is not yet an identifier for a class, enumeration type or user-defined data type in $Tm$; \item The identifier of the enumeration type in $Tm_{Enum}$ is not in the namespace of any class, enumeration type or user-defined data type in $Tm$; \item None of the identifiers in any class, enumeration type or user-defined data type in $Tm$ is in the namespace of the enumeration type in $Tm_{Enum}$. \end{itemize} \isabellelref{tmod_enum_combine_correct}{Ecore-GROOVE-Mapping-Library.EnumType} \end{thm} \begin{proof} Use \cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_models:tmod_combine_merge_correct}. It is possible to show that all assumptions hold. Now we have shown that $\mathrm{combine}(Tm, Tm_{Enum})$ is consistent in the sense of \cref{defin:formalisations:ecore_formalisation:type_models:type_model_consistency}. \end{proof} The definitions and theorems for a regular subclass within Ecore are now complete. \subsubsection{Encoding as node type} A possible encoding for enumeration types in Ecore is using node types in GROOVE. In this case, the enumeration type itself is transformed into an abstract node type. Each value of the enumeration type is converted to its own node type, extending the abstract node type. The encoding corresponding to $Tm_{Enum}$ can then be represented as $TG_{EnumNodes}$, defined in the following definition: \begin{defin}[Type graph $TG_{EnumNodes}$] \label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_node_types} Let $TG_{EnumNodes}$ be a type graph containing multiple node types. The first node type encodes the enumeration type $name$. The other node types encode the $values$ of enumeration type $name$. $TG_{EnumNodes}$ is defined as: \begin{align*} NT =\ &\{\mathrm{ns\_\!to\_\!list}(name)\} \cup \{ \mathrm{ns\_\!to\_\!list}(name) \append \langle v \rangle \mid v \in values \} \\ ET =\ &\{\} \\ \!\!\sqsubseteq\ =\ &\{(\mathrm{ns\_\!to\_\!list}(name), \mathrm{ns\_\!to\_\!list}(name))\}\ \cup \\& \{(\mathrm{ns\_\!to\_\!list}(name) \append \langle v \rangle, \mathrm{ns\_\!to\_\!list}(name) \append \langle v \rangle) \mid v \in values \}\ \cup \\& \{(\mathrm{ns\_\!to\_\!list}(name) \append \langle v \rangle, \mathrm{ns\_\!to\_\!list}(name)) \mid v \in values \} \\ abs =\ &\{\mathrm{ns\_\!to\_\!list}(name)\} \\ \mathrm{mult} =\ &\{\} \\ contains =\ &\{\} \end{align*} \isabellelref{tg_enum_as_node_types}{Ecore-GROOVE-Mapping-Library.EnumType} \end{defin} \begin{thm}[Correctness of $TG_{EnumNodes}$] \label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_node_types_correct} $TG_{EnumNodes}$ (\cref{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_node_types}) is a valid type graph in the sense of \cref{defin:formalisations:groove_formalisation:type_graphs:type_graph_validity}. \isabellelref{tg_enum_as_node_types_correct}{Ecore-GROOVE-Mapping-Library.EnumType} \end{thm} A visual representation of $TG_{EnumNodes}$ with $.\type{Example}$ as identifier for the encoded enumeration type and $\type{OPTION\_A}$, $\type{OPTION\_B}$ and $\type{OPTION\_C}$ as its values can be seen in \cref{fig:library_of_transformations:type_level_transformations:enumeration_types:visualisation:groove_nodes}. Please note that in this visualisation, the sequences are concatenated using the dollar sign $\$$. The correctness proof of $TG_{EnumNodes}$ is trivial, and therefore not included here. The proof can be found as part of the Isabelle validated proofs. In order to make composing transformation functions possible, $TG_{EnumNodes}$ should be compatible with the type graph it is combined with. \begin{thm}[Correctness of $\mathrm{combine}(TG, TG_{EnumNodes})$] \label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_node_types_combine_correct} Assume a type graph $TG$ that is valid in the sense of \cref{defin:formalisations:groove_formalisation:type_graphs:type_graph_validity}. Then $TG$ is compatible with $TG_{EnumNodes}$ (in the sense of \cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_graphs:compatibility}) if: \begin{itemize} \item There are no shared node types between $TG_{EnumNodes}$ and $TG$. \end{itemize} \isabellelref{tg_enum_as_node_types_combine_correct}{Ecore-GROOVE-Mapping-Library.EnumType} \end{thm} \begin{proof} Use \cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_graphs:tg_combine_merge_correct}. It is possible to show that all assumptions hold. Now we have shown that $\mathrm{combine}(TG, TG_{EnumNodes})$ is valid in the sense of \cref{defin:formalisations:groove_formalisation:type_graphs:type_graph_validity}. \end{proof} The next definitions define the transformation function from $Tm_{Enum}$ to $TG_{EnumNodes}$: \begin{defin}[Transformation function $f_{EnumNodes}$] \label{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum_to_tg_enum_as_node_types} The transformation function $f_{EnumNodes}(Tm)$ is defined as: \begin{align*} NT =\ &\{\mathrm{ns\_\!to\_\!list}(e) \mid e \in Enum_{Tm}\} \cup \{\mathrm{ns\_\!to\_\!list}(e) \append \langle v \rangle \mid (e, v) \in EnumValue_{Tm}\} \\ ET =\ &\{\} \\ \!\!\sqsubseteq\ =\ &\{(\mathrm{ns\_\!to\_\!list}(e_1), \mathrm{ns\_\!to\_\!list}(e_2)) \mid e_1 \in Enum_{Tm} \land e_2 \in Enum_{Tm} \}\ \cup \\& \{(\mathrm{ns\_\!to\_\!list}(i) \append \langle j \rangle, \mathrm{ns\_\!to\_\!list}(i) \append \langle j \rangle) \mid (i, j) \in EnumValue_{Tm} \}\ \cup \\& \{(\mathrm{ns\_\!to\_\!list}(i) \append \langle j \rangle, \mathrm{ns\_\!to\_\!list}(e)) \mid (i, j) \in EnumValue_{Tm} \land e \in Enum_{Tm} \} \\ abs =\ &\{\} \\ \mathrm{mult} =\ &\{\} \\ contains =\ &\{\} \end{align*} \isabellelref{tmod_enum_to_tg_enum_as_node_types}{Ecore-GROOVE-Mapping-Library.EnumType} \end{defin} \begin{thm}[Correctness of $f_{EnumNodes}$] \label{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum_to_tg_enum_as_node_types_func} $f_{EnumNodes}(Tm)$ (\cref{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum_to_tg_enum_as_node_types}) is a valid transformation function in the sense of \cref{defin:transformation_framework:type_models_and_type_graphs:combining_transformation_functions:transformation_function_type_model_type_graph} transforming $Tm_{Enum}$ into $TG_{EnumNodes}$. \isabellelref{tmod_enum_to_tg_enum_as_node_types_func}{Ecore-GROOVE-Mapping-Library.EnumType} \end{thm} The proof of the correctness of $f_{EnumNodes}$ will not be included here. Instead, it can be found in the validated Isabelle theories. Finally, to complete the transformation, the transformation function that transforms $TG_{EnumNodes}$ into $Tm_{Enum}$ is defined: \begin{defin}[Transformation function $f'_{EnumNodes}$] \label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_node_types_to_tmod_enum} The transformation function $f'_{EnumNodes}(TG, name)$ is defined as: \begin{align*} Class =\ &\{\} \\ Enum =\ &\{\mathrm{list\_\!to\_\!ns}(n) \mid n \in NT_{TG} \land n = \mathrm{id\_\!to\_\!name}(name)\} \\ UserDataType =\ &\{\} \\ Field =\ &\{\} \\ \mathrm{FieldSig} =\ &\{\} \\ EnumValue =\ &\{(\mathrm{list\_\!to\_\!ns}(e), v) \mid e \append \langle v \rangle \in NT_{TG} \land e \append \langle v \rangle \neq \mathrm{id\_\!to\_\!name}(name) \} \\ Inh =\ &\{\} \\ Prop =\ &\{\} \\ Constant =\ &\{\} \\ \mathrm{ConstType} =\ &\{\} \end{align*} \isabellelref{tg_enum_as_node_types_to_tmod_enum}{Ecore-GROOVE-Mapping-Library.EnumType} \end{defin} \begin{thm}[Correctness of $f'_{EnumNodes}$] \label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_node_types_to_tmod_enum_func} $f'_{EnumNodes}(TG, name)$ (\cref{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_node_types_to_tmod_enum}) is a valid transformation function in the sense of \cref{defin:transformation_framework:type_models_and_type_graphs:combining_transformation_functions:transformation_function_type_graph_type_model} transforming $TG_{EnumNodes}$ into $Tm_{Enum}$. \isabellelref{tg_enum_as_node_types_to_tmod_enum_func}{Ecore-GROOVE-Mapping-Library.EnumType} \end{thm} Once more, the correctness proof is not included here but can be found in the validated Isabelle proofs of this thesis. \subsubsection{Encoding as flags} Another possible encoding for enumeration types in Ecore is using flags in GROOVE. In this case, the enumeration type itself is transformed into a regular node type. Each value of the enumeration type is converted to a flag on this node type. The encoding corresponding to $Tm_{Enum}$ can then be represented as $TG_{EnumFlags}$, defined in the following definition: \begin{defin}[Type graph $TG_{EnumFlags}$] \label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_flags} Let $TG_{EnumFlags}$ be a type graph containing a single node type which encodes the enumeration type $name$. The flags on the node type of $name$ encode the different $values$. $TG_{EnumFlags}$ is defined as: \begin{align*} NT =\ &\{\mathrm{ns\_\!to\_\!list}(name)\} \\ ET =\ &\{ (\mathrm{ns\_\!to\_\!list}(name), \langle v \rangle, \mathrm{ns\_\!to\_\!list}(name)) \mid v \in values \}\\ \!\!\sqsubseteq\ =\ &\{(\mathrm{ns\_\!to\_\!list}(name), \mathrm{ns\_\!to\_\!list}(name))\} \\ abs =\ &\{\} \\ \mathrm{mult}(e) =\ &\begin{cases} (0..1, 0..1) &\mathrm{if}\ e \in ET_{TG_{EnumFlags}} \end{cases}\\ contains =\ &\{\} \end{align*} \isabellelref{tg_enum_as_flags}{Ecore-GROOVE-Mapping-Library.EnumType} \end{defin} \begin{thm}[Correctness of $TG_{EnumFlags}$] \label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_flags_correct} $TG_{EnumFlags}$ (\cref{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_flags}) is a valid type graph in the sense of \cref{defin:formalisations:groove_formalisation:type_graphs:type_graph_validity}. \isabellelref{tg_enum_as_flags_correct}{Ecore-GROOVE-Mapping-Library.EnumType} \end{thm} A visual representation of $TG_{EnumFlags}$ with $.\type{Example}$ as identifier for the encoded enumeration type and $\type{OPTION\_A}$, $\type{OPTION\_B}$ and $\type{OPTION\_C}$ as its values can be seen in \cref{fig:library_of_transformations:type_level_transformations:enumeration_types:visualisation:groove_flags}. The correctness proof of $TG_{EnumFlags}$ is trivial, and therefore not included here. The proof can be found as part of the Isabelle validated proofs. In order to make composing transformation functions possible, $TG_{EnumFlags}$ should be compatible with the type graph it is combined with. \begin{thm}[Correctness of $\mathrm{combine}(TG, TG_{EnumFlags})$] \label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_flags_combine_correct} Assume a type graph $TG$ that is valid in the sense of \cref{defin:formalisations:groove_formalisation:type_graphs:type_graph_validity}. Then $TG$ is compatible with $TG_{EnumFlags}$ (in the sense of \cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_graphs:compatibility}) if: \begin{itemize} \item There are no shared node types between $TG_{EnumFlags}$ and $TG$. \end{itemize} \isabellelref{tg_enum_as_flags_combine_correct}{Ecore-GROOVE-Mapping-Library.EnumType} \end{thm} \begin{proof} Use \cref{defin:transformation_framework:type_models_and_type_graphs:combining_type_graphs:tg_combine_merge_correct}. It is possible to show that all assumptions hold. Now we have shown that $\mathrm{combine}(TG, TG_{EnumFlags})$ is valid in the sense of \cref{defin:formalisations:groove_formalisation:type_graphs:type_graph_validity}. \end{proof} The next definitions define the transformation function from $Tm_{Enum}$ to $TG_{EnumFlags}$: \begin{defin}[Transformation function $f_{EnumFlags}$] \label{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum_to_tg_enum_as_flags} The transformation function $f_{EnumFlags}(Tm)$ is defined as: \begin{align*} NT =\ &\{\mathrm{ns\_\!to\_\!list}(e) \mid e \in Enum_{Tm}\} \\ ET =\ &\{(\mathrm{ns\_\!to\_\!list}(e), v, \mathrm{ns\_\!to\_\!list}(e)) \mid (e, v) \in EnumValue_{Tm}\} \\ \!\!\sqsubseteq\ =\ &\{(\mathrm{ns\_\!to\_\!list}(e_1), \mathrm{ns\_\!to\_\!list}(e_2)) \mid e_1 \in Enum_{Tm} \land e_2 \in Enum_{Tm} \} \\ abs =\ &\{\} \\ \mathrm{mult}(e) =\ &\begin{cases} (0..1, 0..1) &\mathrm{if}\ e \in \{(\mathrm{ns\_\!to\_\!list}(n), v, \mathrm{ns\_\!to\_\!list}(n)) \mid (n, v) \in EnumValue_{Tm}\} \end{cases}\\ contains =\ &\{\} \end{align*} \isabellelref{tmod_enum_to_tg_enum_as_flags}{Ecore-GROOVE-Mapping-Library.EnumType} \end{defin} \begin{thm}[Correctness of $f_{EnumFlags}$] \label{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum_to_tg_enum_as_flags_func} $f_{EnumFlags}(Tm)$ (\cref{defin:library_of_transformations:type_level_transformations:enumeration_types:tmod_enum_to_tg_enum_as_flags}) is a valid transformation function in the sense of \cref{defin:transformation_framework:type_models_and_type_graphs:combining_transformation_functions:transformation_function_type_model_type_graph} transforming $Tm_{Enum}$ into $TG_{EnumFlags}$. \isabellelref{tmod_enum_to_tg_enum_as_flags_func}{Ecore-GROOVE-Mapping-Library.EnumType} \end{thm} The proof of the correctness of $f_{EnumFlags}$ will not be included here. Instead, it can be found in the validated Isabelle theories. Finally, to complete the transformation, the transformation function that transforms $TG_{EnumFlags}$ into $Tm_{Enum}$ is defined: \begin{defin}[Transformation function $f'_{EnumFlags}$] \label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_flags_to_tmod_enum} The transformation function $f'_{EnumFlags}(TG)$ is defined as: \begin{align*} Class =\ &\{\} \\ Enum =\ &\{\mathrm{list\_\!to\_\!ns}(n) \mid n \in NT_{TG}\} \\ UserDataType =\ &\{\} \\ Field =\ &\{\} \\ \mathrm{FieldSig} =\ &\{\} \\ EnumValue =\ &\{(\mathrm{list\_\!to\_\!ns}(e), v) \mid (e, v, e) \in ET_{TG} \} \\ Inh =\ &\{\} \\ Prop =\ &\{\} \\ Constant =\ &\{\} \\ \mathrm{ConstType} =\ &\{\} \end{align*} \isabellelref{tg_enum_as_flags_to_tmod_enum}{Ecore-GROOVE-Mapping-Library.EnumType} \end{defin} \begin{thm}[Correctness of $f'_{EnumNodes}$] \label{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_flags_to_tmod_enum_func} $f'_{EnumFlags}(TG)$ (\cref{defin:library_of_transformations:type_level_transformations:enumeration_types:tg_enum_as_flags_to_tmod_enum}) is a valid transformation function in the sense of \cref{defin:transformation_framework:type_models_and_type_graphs:combining_transformation_functions:transformation_function_type_graph_type_model} transforming $TG_{EnumFlags}$ into $Tm_{Enum}$. \isabellelref{tg_enum_as_flags_to_tmod_enum_func}{Ecore-GROOVE-Mapping-Library.EnumType} \end{thm} Once more, the correctness proof is not included here but can be found in the validated Isabelle proofs of this thesis.
missingSum=function() { vec=c(1,2,3,4,NA,NA,NA,8,9,10) add=sum(vec,na.rm = TRUE) add } missingSum()
------------------------------------------------------------------------------ -- Common (interactive and automatic) properties using the induction principle ------------------------------------------------------------------------------ {-# OPTIONS --exact-split #-} {-# OPTIONS --no-sized-types #-} {-# OPTIONS --no-universe-polymorphism #-} {-# OPTIONS --without-K #-} module PA.Inductive.PropertiesByInduction where open import PA.Inductive.Base ------------------------------------------------------------------------------ -- Congruence properties succCong : ∀ {m n} → m ≡ n → succ m ≡ succ n succCong refl = refl ------------------------------------------------------------------------------ +-leftIdentity : ∀ n → zero + n ≡ n +-leftIdentity n = refl +-rightIdentity : ∀ n → n + zero ≡ n +-rightIdentity n = ℕ-ind A A0 is n where A : ℕ → Set A i = i + zero ≡ i A0 : A zero A0 = refl is : ∀ i → A i → A (succ i) is i ih = succCong ih +-assoc : ∀ m n o → m + n + o ≡ m + (n + o) +-assoc m n o = ℕ-ind A A0 is m where A : ℕ → Set A i = i + n + o ≡ i + (n + o) A0 : A zero A0 = refl is : ∀ i → A i → A (succ i) is i ih = succCong ih x+Sy≡S[x+y] : ∀ m n → m + succ n ≡ succ (m + n) x+Sy≡S[x+y] m n = ℕ-ind A A0 is m where A : ℕ → Set A i = i + succ n ≡ succ (i + n) A0 : A zero A0 = refl is : ∀ i → A i → A (succ i) is i ih = succCong ih
Formal statement is: lemma LIM_zero: "(f \<longlongrightarrow> l) F \<Longrightarrow> ((\<lambda>x. f x - l) \<longlongrightarrow> 0) F" for f :: "'a \<Rightarrow> 'b::real_normed_vector" Informal statement is: If $f$ converges to $l$, then $f - l$ converges to $0$.
1. Includes shares acquired under the Employee Stock Purchase Plan as of 3/2/19 and shares of restricted stock granted under the 2009 Stock Incentive Plan. 2. Represents the approximate number of shares of common stock for which the Reporting Person has the right to direct the vote under the Apogee 401(k) Retirement Plan per the Trustee's 3/2/19 statement. Shares of common stock are not directly allocated to the Plan participants, but are instead held in a unitized fund consisting primarily of common stock and a small percentage of short-term investments. Participants acquire units in this fund.
Biomedical Engineering advances fundamental medical concepts; creates knowledge from the molecular to the organ systems levels; and develops innovative biologics, materials, processes, implants, devices, and informatics approaches. These approaches are applied to the prevention, diagnosis, and treatment of disease. The objective is to prepare students for employment in companies that manufacture medical assist devices, human tissue products, and therapeutics. This program also prepares students to enter a graduate program in Biomedical Engineering or pursue professional degrees in medicine and related health fields. An example of what students in this major actually do can be seen here: Rural Dentistry Senior Design Fund 20110427 04:33:21 nbsp the most painful and rewarding major in davis! Users/bumblebee
State Before: α : Type ?u.402487 b : Bool n : Num ⊢ ↑(bit b n) = Nat.bit b ↑n State After: no goals Tactic: cases b <;> cases n <;> rfl
The trifluoride SbF
[STATEMENT] lemma stutter_selectionD_inside[dest]: assumes "stutter_selection s w" assumes "enat i < llength w" "enat (Suc k) < esize s" assumes "nth_least s k < i" "i < nth_least s (Suc k)" shows "w ?! i = w ?! nth_least s k" [PROOF STATE] proof (prove) goal (1 subgoal): 1. w ?! i = w ?! nth_least s k [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: stutter_selection s w enat i < llength w enat (Suc k) < esize s nth_least s k < i i < nth_least s (Suc k) goal (1 subgoal): 1. w ?! i = w ?! nth_least s k [PROOF STEP] unfolding stutter_selection_def [PROOF STATE] proof (prove) using this: 0 \<in> s \<and> (\<forall>k i. enat i < llength w \<longrightarrow> enat (Suc k) < esize s \<longrightarrow> nth_least s k < i \<longrightarrow> i < nth_least s (Suc k) \<longrightarrow> w ?! i = w ?! nth_least s k) \<and> (\<forall>i. enat i < llength w \<longrightarrow> finite s \<longrightarrow> Max s < i \<longrightarrow> w ?! i = w ?! Max s) enat i < llength w enat (Suc k) < esize s nth_least s k < i i < nth_least s (Suc k) goal (1 subgoal): 1. w ?! i = w ?! nth_least s k [PROOF STEP] by auto
PIResponse <- function(status = NULL, headers = NULL, content = NULL) { if (is.null(status) == FALSE) { if (check.integer(status) == FALSE) { return (print(paste0("Error: status must be an integer."))) } } if (is.null(headers) == FALSE) { } if (is.null(content) == FALSE) { } value <- list( Status = status, Headers = headers, Content = content) valueCleaned <- rmNullObs(value) attr(valueCleaned, "className") <- "PIResponse" return(valueCleaned) }
subroutine surev(idim,tu,nu,tv,nv,c,u,mu,v,mv,f,mf,wrk,lwrk, * iwrk,kwrk,ier) c subroutine surev evaluates on a grid (u(i),v(j)),i=1,...,mu; j=1,... c ,mv a bicubic spline surface of dimension idim, given in the c b-spline representation. c c calling sequence: c call surev(idim,tu,nu,tv,nv,c,u,mu,v,mv,f,mf,wrk,lwrk, c * iwrk,kwrk,ier) c c input parameters: c idim : integer, specifying the dimension of the spline surface. c tu : real array, length nu, which contains the position of the c knots in the u-direction. c nu : integer, giving the total number of knots in the u-direction c tv : real array, length nv, which contains the position of the c knots in the v-direction. c nv : integer, giving the total number of knots in the v-direction c c : real array, length (nu-4)*(nv-4)*idim, which contains the c b-spline coefficients. c u : real array of dimension (mu). c before entry u(i) must be set to the u co-ordinate of the c i-th grid point along the u-axis. c tu(4)<=u(i-1)<=u(i)<=tu(nu-3), i=2,...,mu. c mu : on entry mu must specify the number of grid points along c the u-axis. mu >=1. c v : real array of dimension (mv). c before entry v(j) must be set to the v co-ordinate of the c j-th grid point along the v-axis. c tv(4)<=v(j-1)<=v(j)<=tv(nv-3), j=2,...,mv. c mv : on entry mv must specify the number of grid points along c the v-axis. mv >=1. c mf : on entry, mf must specify the dimension of the array f. c mf >= mu*mv*idim c wrk : real array of dimension lwrk. used as workspace. c lwrk : integer, specifying the dimension of wrk. c lwrk >= 4*(mu+mv) c iwrk : integer array of dimension kwrk. used as workspace. c kwrk : integer, specifying the dimension of iwrk. kwrk >= mu+mv. c c output parameters: c f : real array of dimension (mf). c on succesful exit f(mu*mv*(l-1)+mv*(i-1)+j) contains the c l-th co-ordinate of the bicubic spline surface at the c point (u(i),v(j)),l=1,...,idim,i=1,...,mu;j=1,...,mv. c ier : integer error flag c ier=0 : normal return c ier=10: invalid input data (see restrictions) c c restrictions: c mu >=1, mv >=1, lwrk>=4*(mu+mv), kwrk>=mu+mv , mf>=mu*mv*idim c tu(4) <= u(i-1) <= u(i) <= tu(nu-3), i=2,...,mu c tv(4) <= v(j-1) <= v(j) <= tv(nv-3), j=2,...,mv c c other subroutines required: c fpsuev,fpbspl c c references : c de boor c : on calculating with b-splines, j. approximation theory c 6 (1972) 50-62. c cox m.g. : the numerical evaluation of b-splines, j. inst. maths c applics 10 (1972) 134-149. c dierckx p. : curve and surface fitting with splines, monographs on c numerical analysis, oxford university press, 1993. c c author : c p.dierckx c dept. computer science, k.u.leuven c celestijnenlaan 200a, b-3001 heverlee, belgium. c e-mail : [email protected] c c latest update : march 1987 c c ..scalar arguments.. integer idim,nu,nv,mu,mv,mf,lwrk,kwrk,ier c ..array arguments.. integer iwrk(kwrk) real*8 tu(nu),tv(nv),c((nu-4)*(nv-4)*idim),u(mu),v(mv),f(mf), * wrk(lwrk) c ..local scalars.. integer i,muv c .. c before starting computations a data check is made. if the input data c are invalid control is immediately repassed to the calling program. ier = 10 if(mf.lt.mu*mv*idim) go to 100 muv = mu+mv if(lwrk.lt.4*muv) go to 100 if(kwrk.lt.muv) go to 100 if (mu.lt.1) go to 100 if (mu.eq.1) go to 30 go to 10 10 do 20 i=2,mu if(u(i).lt.u(i-1)) go to 100 20 continue 30 if (mv.lt.1) go to 100 if (mv.eq.1) go to 60 go to 40 40 do 50 i=2,mv if(v(i).lt.v(i-1)) go to 100 50 continue 60 ier = 0 call fpsuev(idim,tu,nu,tv,nv,c,u,mu,v,mv,f,wrk(1),wrk(4*mu+1), * iwrk(1),iwrk(mu+1)) 100 return end
import os import sys, timeit sys.path.append('..') import json import numpy as np from utils import upmu_helpers from multiprocessing import Pool, Queue import multiprocessing import pandas as pd import pika, itertools import time,calendar import socket import json, hashlib # make sure ES is up and running import requests #pip install requests from elasticsearch import Elasticsearch,helpers #pip install elasticsearch5 from DataInt import * bc_app = DataInt() # a function to get an entry for a dvice from rime range startime to endtime # by default starts from 1475819580 (GMT: Friday, October 7, 2016 5:53:00 AM) # got error a month before this date # ID of other mpmu device P3001065 def getDataCassandra(device_id_input='P3001199', starttime = 1475819580.0, endtime = 1475819640.0): program = "DataInt" # fill in anything # Format the timestring so that cassandra understands it. times = [] #this variable is not used line_day = 0 times.append((program, line_day, float(starttime), float(endtime))) # Query cassandra to get data hostname = 'dash.lbl.gov' #candance.lbl.gov coltrane.lbl.gov the actuall databases, paralelize over these may give better result user = 'readonly' password = 'readonly' device_id = device_id_input #the device that you want to read from upmu_data = upmu_helpers.get_experiments_data(hostname, user, password, device_id, times, buf=0) if upmu_data.keys() == []: print("Error getting data") return False data_key = list(upmu_data[program].keys())[0] data = upmu_data[program][data_key] """ #use this to do the add/verify opration in parallel per process re = bc_app.verify( data=str(data), datatype="string") if not re: print("not found") """ return data # returns array of tuples [ (timestamp, data ....), (timestamp, data ....) ....] # this method prepare args for parallel processes # it reterns a generatoer for (device_id, starttime, endtime) def get_arg(endtime): device_id_input='P3001199' #start time (GMT: Friday, October 7, 2016 5:53:00 AM) starttime = 1475819580 min = 60 while starttime < endtime: starttime += min yield (device_id_input, starttime - min, starttime) def _verify(value): re = bc_app.verify( data=str(value), datatype="string") if not re: print("not found") return False return True def getCassandraDataPerHr(endtime=1475823180): # getDataCassandra() takes on avg 0.449 secs to get 1 min data. It reads from casandra # use the folloing to test # print(timeit.timeit("getDataCassandra()", setup="from __main__ import getDataCassandra", number=100 )) p = Pool(60) re = p.starmap_async(getDataCassandra, get_arg(endtime)) re.wait() double_array = re.get() # [ [return from getDataCassandra call] , [..], [..], ... ] the size is = len(get_arg()) # this loop writes every min of data to file and agregates file names in 'filenames' # you can pss this names to the blockchain writing fuction with -f option """filenames = [] for i in range(len(double_array)): fname = str(double_array[i][0][0]) f = open("outputs/"+fname, 'a') f.write(str(double_array[i][0])) filenames.append(fname) """ # or using this loop pass every min of data to the blockchain directly with -s option # use this for sequential add/verify oprations for i in range(len(double_array)): re = bc_app.add( data=str(double_array[i]), datatype="string") if re: print("add a min of record to blockchain") else: print("Error: " + double_array[i][0] + " is not added") if __name__ == "__main__": #getCassandraDataPerDay() endtime = 1475823180 # for 60 min #1475905980 # one day #time.time() getCassandraDataPerHr(endtime) # use this to measure the time taken by the given function #print(timeit.timeit("getCassandraDataPerHr()", setup="from __main__ import getCassandraDataPerHr", number=1))
module TestTimesteps using Mimi using Test import Mimi: AbstractTimestep, FixedTimestep, VariableTimestep, TimestepVector, TimestepMatrix, TimestepArray, next_timestep, hasvalue, getproperty, Clock, time_index, get_timestep_array #------------------------------------------------------------------------------ # Test basic timestep functions and Base functions for Fixed Timestep #------------------------------------------------------------------------------ t1 = FixedTimestep{1850, 10, 3000}(1) @test is_first(t1) @test t1 == TimestepIndex(1) @test t1 == TimestepValue(1850) @test TimestepIndex(1) == t1 # test both ways because to test both method definitions @test t1 == TimestepValue(1850) @test TimestepValue(1850) == t1 # test both ways because to test both method definitions @test_throws ErrorException t1_prev = t1-1 #first timestep, so cannot get previous t2 = next_timestep(t1) @test t2.t == 2 @test t2 == TimestepIndex(2) @test t2 == TimestepValue(1860) @test t2 > TimestepIndex(1) @test t2 > TimestepValue(1850) @test t2 < TimestepIndex(3) @test t2 < TimestepValue(1870) @test_throws ErrorException t2_prev = t2 - 2 #can't get before first timestep @test t2 == t1 + 1 @test t1 == t2 - 1 t3 = FixedTimestep{2000, 1, 2050}(51) @test is_last(t3) @test_throws ErrorException t3_next = t3 + 2 #can't go beyond last timestep t4 = next_timestep(t3) @test t4 == TimestepIndex(52) @test t4 == TimestepValue(2051) @test_throws ErrorException t_next = t4 + 1 @test_throws ErrorException next_timestep(t4) #------------------------------------------------------------------------------ # Test basic timestep functions and Base functions for Variable Timestep #------------------------------------------------------------------------------ years = Tuple([2000:1:2024; 2025:5:2105]) t1 = VariableTimestep{years}() @test is_first(t1) @test t1 == TimestepIndex(1) @test t1 == TimestepValue(2000) @test_throws ErrorException t1_prev = t1-1 #first timestep, so cannot get previous t2 = next_timestep(t1) @test t2.t == 2 @test t2 == TimestepIndex(2) @test t2 == TimestepValue(2001) @test TimestepIndex(1) < t2 @test TimestepValue(2000) < t2 @test TimestepIndex(3) > t2 @test TimestepValue(2002) > t2 @test_throws ErrorException t2_prev = t2 - 2 #can't get before first timestep @test t2 == t1 + 1 @test t1 == t2 - 1 t3 = VariableTimestep{years}(42) @test is_last(t3) @test ! is_first(t3) @test_throws ErrorException t3_next = t3 + 2 #can't go beyond last timestep t4 = next_timestep(t3) @test t4 == TimestepIndex(43) # note here that this comes back to an assumption made in variable # timesteps that we may assume the next step is 1 year for the final year in TIMES @test t4 == TimestepValue(2106) @test_throws ErrorException t_next = t4 + 1 @test_throws ErrorException next_timestep(t4) #------------------------------------------------------------------------------ # Test some basic functions for TimestepIndex and TimestepValue #------------------------------------------------------------------------------ start = 1 stop = 10 step = 2 # TimestepValue @test TimestepValue(2000, offset = 1) + 1 == TimestepValue(2000, offset = 2) @test TimestepValue(2000) + 1 == TimestepValue(2000, offset = 1) @test TimestepValue(2000, offset = 1) - 1 == TimestepValue(2000) # TimestepIndex @test TimestepIndex(start):TimestepIndex(stop) == TimestepIndex.([start:stop...]) @test TimestepIndex(start):TimestepIndex(stop) == TimestepIndex(start):1:TimestepIndex(stop) @test TimestepIndex(start):step:TimestepIndex(stop) == TimestepIndex.([start:step:stop...]) @test TimestepIndex(1) + 1 == TimestepIndex(2) @test TimestepIndex(2) - 1 == TimestepIndex(1) #------------------------------------------------------------------------------ # Test a model with components with different offsets #------------------------------------------------------------------------------ # we'll have Bar run from 2000 to 2010 # and Foo from 2005 to 2010 @defcomp Foo begin inputF = Parameter() output = Variable(index=[time]) function run_timestep(p, v, d, ts) v.output[ts] = p.inputF + ts.t end end @defcomp Bar begin inputB = Parameter(index=[time]) output = Variable(index=[time]) function run_timestep(p, v, d, ts) if ts < TimestepValue(2005) v.output[ts] = p.inputB[ts] else v.output[ts] = p.inputB[ts] * ts.t end end end years = 2000:2010 first_foo = 2005 m = Model() set_dimension!(m, :time, years) # test that you can only add components with first/last within model's time index range @test_throws ErrorException add_comp!(m, Foo; first=1900) @test_throws ErrorException add_comp!(m, Foo; last=2100) foo = add_comp!(m, Foo, first=first_foo) bar = add_comp!(m, Bar) set_param!(m, :Foo, :inputF, 5.) set_param!(m, :Bar, :inputB, collect(1:length(years))) run(m) @test length(m[:Foo, :output]) == length(years) @test length(m[:Bar, :output]) == length(years) yr_dim = Mimi.Dimension(years) idxs = yr_dim[first_foo]:yr_dim[years[end]] foo_output = m[:Foo, :output] offset = first_foo - years[1] for i in idxs @test foo_output[i] == 5+(i-offset) # incorporate offset into i now because we set ts.t to match component not model end for i in 1:5 @test m[:Bar, :output][i] == i end for i in 6:11 @test m[:Bar, :output][i] == i*i end #------------------------------------------------------------------------------ # test get_timestep_array #------------------------------------------------------------------------------ m = Model() #fixed timestep to start set_dimension!(m, :time, 2000:2009) vector = ones(5) matrix = ones(3,2) t_vector = get_timestep_array(m.md, Float64, 1, 1, vector) t_matrix = get_timestep_array(m.md, Float64, 2, 1, matrix) @test typeof(t_vector) <: TimestepVector @test typeof(t_matrix) <: TimestepMatrix # try with variable timestep set_dimension!(m, :time, [2000:1:2004; 2005:2:2009]) t_vector = get_timestep_array(m.md, Float64, 1, 1, vector) t_matrix = get_timestep_array(m.md, Float64, 2, 2, matrix) @test typeof(t_vector) <: TimestepVector @test typeof(t_matrix) <: TimestepMatrix #------------------------------------------------------------------------------ # Now build a model with connecting components #------------------------------------------------------------------------------ @defcomp Foo2 begin inputF = Parameter(index=[time]) output = Variable(index=[time]) function run_timestep(p, v, d, ts) v.output[ts] = p.inputF[ts] end end m2 = Model() set_dimension!(m2, :time, years) bar = add_comp!(m2, Bar) foo2 = add_comp!(m2, Foo2, first = first_foo) set_param!(m2, :Bar, :inputB, collect(1:length(years))) connect_param!(m2, :Foo2, :inputF, :Bar, :output) run(m2) foo_output2 = m2[:Foo2, :output][yr_dim[first_foo]:yr_dim[years[end]]] for i in 1:6 @test foo_output2[i] == (i+5)^2 end #------------------------------------------------------------------------------ # Connect them in the other direction #------------------------------------------------------------------------------ @defcomp Bar2 begin inputB = Parameter(index=[time]) output = Variable(index=[time]) function run_timestep(p, v, d, ts) v.output[ts] = p.inputB[ts] * ts.t end end years = 2000:2010 m3 = Model() set_dimension!(m3, :time, years) add_comp!(m3, Foo, first=2005) add_comp!(m3, Bar2) set_param!(m3, :Foo, :inputF, 5.) connect_param!(m3, :Bar2, :inputB, :Foo, :output, zeros(length(years))) run(m3) @test length(m3[:Foo, :output]) == 11 @test length(m3[:Bar2, :inputB]) == 11 @test length(m3[:Bar2, :output]) == 11 end
From Test Require Import tactic. Section FOFProblem. Variable Universe : Set. Variable UniverseElement : Universe. Variable wd_ : Universe -> Universe -> Prop. Variable col_ : Universe -> Universe -> Universe -> Prop. Variable col_swap1_1 : (forall A B C : Universe, (col_ A B C -> col_ B A C)). Variable col_swap2_2 : (forall A B C : Universe, (col_ A B C -> col_ B C A)). Variable col_triv_3 : (forall A B : Universe, col_ A B B). Variable wd_swap_4 : (forall A B : Universe, (wd_ A B -> wd_ B A)). Variable col_trans_5 : (forall P Q A B C : Universe, ((wd_ P Q /\ (col_ P Q A /\ (col_ P Q B /\ col_ P Q C))) -> col_ A B C)). Theorem pipo_6 : (forall O E Eprime AB CD : Universe, ((wd_ O E /\ (wd_ E Eprime /\ (wd_ O Eprime /\ (col_ O E AB /\ col_ O E CD)))) -> col_ O AB CD)). Proof. time tac. Qed. End FOFProblem.
% !TEX root = ../main.tex \section{Discussion} \label{sec:discussion} We presented \acrlong{PVI}, a flexible method designed to avoid bad local optima. We showed that classic \acrlong{VI} gets trapped in these local optima and cannot recover. The choice of proximity statistic $f$ and distance $d$ enables the design of a variety of constraints that improve optimization. As examples of proximity statistics, we gave the entropy, \gls{KL} divergence, orthogonal proximity statistic, and the mean and variance of the approximate posterior. We evaluated our method in four models to demonstrate that it is easy to implement, readily extensible, and leads to beneficial statistical properties of variational inference algorithms. The empirical results also yield guidelines for choosing proximity statistics. The entropy is useful for models with discrete latent variables which are prone to quickly getting stuck in local optima or flat regions of the objective. We also saw that the \gls{KL} statistic gives poor performance empirically, and that the orthogonal proximity statistic reduces pruning in deep generative models such as the variational autoencoder. In models like the deep exponential family model of text, the entropy is not tractable so the mean/variance proximity statistic is a natural choice. \paragraph{Future Work.} Simplifying optimization is necessary for truly black-box variational inference. An adaptive magnitude decay based on the value of the constraint should further improve the technique (this could be done per-parameter). New proximity constraints are also easy to design and test. For example, the variance of the gradients of the variational parameters is a valid proximity statistic---which can be used to avoid variational approximations that have high-variance gradients. Another set of interesting proximity statistics are empirical statistics of the variational distribution, such as the mean, for when analytic forms are unavailable. We also leave the design and study of constraints that admit coordinate updates to future work.
\chapter{Development of a Muon Identification acquisition and reconstruction framework for ALICE RUN3} \section{Motivation} % By 2021 ALICE will undergo a major upgrade concerning the luminosity achievable in Pb-Pb collisions. The second LHC run (RUN2) is over at the time of writing this thesis. After that, the LHC will stop for two years (second long shutdown), during which an upgrade that will increase the luminosity reach in $Pb-Pb$ from $\approx 1\ \rm Hz/mb$ to $\approx6\ \rm Hz/mb$ will be performed. At the same time, ALICE will undergo its major upgrade of detectors, electronics and readout that will allow the experiment to cope with the increased Pb-Pb interaction rate, and to also take pp interactions up to $\approx1\ \rm MHz$ \cite{Abelev:1625842, CERN-LHCC-2013-020, CERN-LHCC-2015-001, Antonioli:1603472, Buncic:2011297}. In addition to the machine development of the LHC, a massive upgrade of the acquisition logic for the whole ALICE apparatus will increase by a factor of $\approx50$ the read-out rate. In order to fit in the throughput limitations of the permanent storage the read-out events will be trimmed down to a value similar to the current $1\ \rm kHz$. Such selection will be performed online using specific algorithms, rather than hardware triggers and flat down-sampling. % After the Long Shutdown 2 (LS2 from now on) the delivered instantaneous luminosity will reach $6\cdot10^{27} cm^{-2}s^{-1}$ in Pb-Pb collisions, feeding the ALICE detectors with up to 50 kHz of minimum bias collision rate in Pb-Pb and 200 kHz in pp. % The $O^2$ project follows the upgrade of the LHC triggered by the increase of statistics necessary for new and improved measurements. A requirement of a total integrated luminosity of $13\ \rm nb^{-1}$ in Pb-Pb collisions was formulated with the ALICE Letter Of Intent (LOI) \cite{ALICE_LOI}, split in $10\ \rm nb^{-1}$ at nominal solenoid magnetic field and $3\ \rm nb^{-1}$ at a reduced field of $0.2\ \rm T$. These requirements are related to specific physics goals, concerning open heavy flavours, low mass dileptons and quarkonium measurements. In particular the plans for $J/\psi$ ($\psi(\mathrm{2S})$) foresee to measure $R_{\mathrm{AA}}$ down to $p_{\mathrm{T}} = 0$ with statistical precision higher than $1\%$ ($10\%$) over the whole rapidity interval and the elliptic flow, quantified through the $\nu_2$ coefficient \cite{Acharya:2017tgv}, down to $p_{\mathrm{T}} = 0$ with an absolute precision of $0.05$. Most of the physics topics addressed by ALICE concern low \pt physics probes characterized by very small signal-to-background ratios, which require the read-out of all Pb-Pb collisions. In order to obtain significant measurements it is important to collect very large statistics. The upgrade of the LHC builds up in this direction. The foreseen increase of the luminosity provided by the LHC will cause an increase of collected data rate. The upgrade of the electronics will allow one to increase the data to a value of about two orders of magnitude larger than the one that ALICE experienced during LHC RUN1 and RUN2. As mentioned above, one of the main goals of the new data campaign is the study of rare probes down to low transverse momenta, a region where the large background makes the triggering techniques very inefficient or even impossible in many situations. % Already in standard running conditions, the presence of a very large background makes standard triggering techniques very inefficient, and impossible in many situations. Such increase of data size, combined with the high collision and acquisition rates, makes standard approaches difficult to apply without enormous (technical and economical) efforts for the upgrade of computing capabilities. Since the required scaling of computing infrastructure cannot cope with the data throughput increase, a new acquisition and processing paradigm had to be developed. The basic idea is to reduce the data size as early as possible in the stream that goes from the detector to the storage and reconstruction (Fig. \ref{fig:O2_sketch}). This goal can be achieved adding pre-processing and reconstruction layers close to the detector acquisition logic. For example some detectors will be equipped with a zero suppression algorithm to reduce the volume of data without losing useful information. Such fast reconstruction will be performed synchronously with the data acquisition and will be based on preliminary calibration and alignment information. % At this stage the detectors will operate as standalone items and no merging of the data will be performed prior to the raw reconstruction. \begin{figure}[!t] \begin{center} \includegraphics[width=0.95\linewidth]{Chapters/O2/Figs/O2.pdf} \caption{Sketch of the conceptual structure of the $O^2$ framework. The detector electronics provides a continuous stream of raw data which is compressed, pre-processed and packed by the read-out logic. Partial information coming from different detectors and systems is aggregated. The full set of data is processed and reconstructed. Up to this step all the computation is performed synchronously. The processed data is then stored and retrieved later for the asynchronous reconstruction. From \cite{Buncic:2011297}} \label{fig:O2_sketch} \end{center} \end{figure} Thanks to this fast and partial reconstruction the amount of stored data will be reduced. % Thanks to this reconstruction procedure, the acquisition trigger will be generated based on finer decisions taken by algorithms able to evaluate the events topology and some physical measurements. This procedure will replace the hardware trigger, allowing one to perform precise selections focused on getting the maximum signal for rare and otherwise non-triggerable observables. A finer reconstruction will be performed offline to provide the best resolution possible. For this finer step the merging of data coming from different detectors will be possible and needed. % The added complexity and the cross-talk between different systems forces this step to be performed synchronously only during pp collisions. % An upgraded computing facility installed in place will store the raw data and perform such reconstruction before sending pp data to the CERN storage facility. Despite an upgraded private computing facility, during Pb-Pb collisions the reconstruction will be performed asynchronously and part of the data processing load will be shared between Tier 0 and Tier 1 computing sites of the WLCG (Worldwide LHC Computing GRID). Independently from the colliding system type the archival of data will be performed by Tier 0 and Tier 1 facilities. The combination of synchronous and asynchronous computing and reconstruction steps is well summarized by the name of the software/hardware upgrade project of ALICE. The Online Offline ($O^2$) project concerns the creation of a common computing system shared by all the ALICE systems and will include a definition of a common computing model, the development of a software framework and the planning and realization of new computing facilities. The $O^2$ computing facility will be a high-throughput system equipped with heterogeneous computing nodes similar to platforms currently used in several High Performance Computing (HPC) and cloud computing contexts. The computing nodes will integrate several hardware acceleration technologies, spanning from FPGAs to GPUs. The $O^2$ software framework will grant an adequate abstraction level so that common code can deliver the same functionality across various platforms. This characteristic hides part of the complexity deriving from different hardware choices and specializations of machines devoted to particular tasks, in fact the framework layer allows one to make use of multi-core processors (CPUs) in a way almost transparent to the programmer. Due to fundamental differences between GPU (Graphics Processing Units) and FPGA (Field-Programmable Gate Array) models, the code which is intended to be executed on such accelerators will still require some deep customization. In order to take full advantage of HPC-like infrastructures, as well as of several laptops or standard desktops connected together, the $O^2$ framework will introduce a concurrent computing model. While the current WLCG is a distributed computing framework, ideally made of lots of single instruction thread machines, the future development of the ALICE computing framework requires some more tuning to take full advantage of parallel processors. Since the first era of the HPC the Message Passing Interface has been used as a standard interconnection protocol for computing nodes in computer clusters. The ALICE computing effort follows a similar approach. The introduction of such MPI\footnote{Message Passing Interface. It is the standard communication protocol between machines belonging to a cluster and working is a shared-memory fashion.}-like process-based framework allows for dynamic spawning of workers, which is baked up with a message passing interface capable of using system buses and network interfaces seamlessly and constitutes the backbone of the new infrastructure. The $O^2$ project will make ALICE able to tackle the next running conditions without modifying the funding model followed during RUN1 and RUN2. % \section{Physics objectives of RUN3} % The $O^2$ project follows the upgrade of the LHC triggered by the increase of statistics necessary for new and improved measurements. % A requirement of a total integrated luminosity of $13\ nb^{-1}$ in Pb-Pb collisions was formulated with the ALICE Letter Of Intent (LOI) \cite{ALICE_LOI}, split in $10\ nb^{-1}$ at nominal solenoid magnetic field and $3\ nb^{-1}$ at a reduced field of $0.2\ T$. % These requirements are related to specific performance figures, concerning open heavy flavours, low mass dileptons and quarkonium measurements. % In particular the plans for $J/\psi$ ($\psi(\mathrm{2S})$) foresee to know its $R_{\mathrm{AA}}$ down to $p_{\mathrm{T}} = 0$ with statistical precision higher than $1\%$ ($10\%$) over the whole rapidity interval and its $\nu_2$ down to $p_{\mathrm{T}} = 0$ with an absolute precision of $0.05$. \section{Common software efforts} The $O^2$ project stands on a framework commonly developed by the joint scientific community of several experiments. $O^2$ aims at reducing the complexity of software deployment and to simplify the exploitation of multi- and many-cores architectures and accelerators, minimizing the development effort to be put. The $O^2$ software does not rely only on general libraries such as Boost, ROOT and CMake, but also on other two frameworks (Fig. \ref{fig:O2_soft_tree}). ALFA \cite{alfa} and FairROOT \cite{fairroot} are actively developed by ALICE at CERN and CMB and PANDA at GSI. \begin{figure}[!ht] \begin{center} \includegraphics[width=0.8\linewidth]{Chapters/O2/Figs/O2_soft_tree.pdf} \includegraphics[width=0.7\linewidth]{Chapters/O2/Figs/ALFA.pdf} \caption{Software topology of the $O^2$ project. $O^2$ stands on several software, sets of libraries and tools. The green boxes represents the low level libraries which constitutes the basis of the software. Some of them are ZeroMQ as message passing protocol, CMake as project build and test manager, Geant4 as particles propagation engine. The orange boxes represents ALFA, developed between ALICE and FAIR. This tool contains a set of high level tools, such as data transportation routines and the dynamic deployment system for the dynamic devices management. The blue box represents FairROOT, an evolution of ROOT focused on improved usability for the end-users. It allows for easy data visualization, storage, offline analysis and more. The ALICE $O^2$ stands on all these elements alongside other collaborations software (Panda, Cbm). From \cite{Buncic:2011297}} \label{fig:O2_soft_tree} \end{center} \end{figure} ALFA is a communication and concurrent computing framework. The handling of an heterogeneous computing system requires two fundamental aspects: communication and coordination. ALFA provides both aspects and has been developed with high throughput and low latency in mind. The communication layer is based on the ZeroMQ \cite{zeroMQ} library and allows the passing of binary messages either across network interfaces or between threads within the same machine, by passing memory references. ZeroMQ is a lightweight message passing interface which is based on a POSIX\footnote{Portable Operating System Interface for uniX. Is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines the application programming interface (API), along with command line shells and utility interfaces, for software compatibility with variants of Unix and other operating systems.} socket back-end, extending the socket characteristics to make them able to concatenate several messages to optimize transfer rates and to unfold them at destination. The messages transferred via ZeroMQ have to be serialized as binary buffers. The available serialization methods are based on Boost, Google's Protocol buffers \cite{googlepb} and ROOT streamers, while the ability to use user defined methods is still left as an option. The FairROOT framework is an object oriented simulation, reconstruction and data analysis framework developed for the FAIR project at GSI. It provides core services for Monte Carlo simulations, physics analysis, event visualization and other fundamental tasks. All the provided functions are accessible in a simple way, in order to simplify the detectors description as well as the creation of analysis workflows. \section{Data format} The $O^2$ project introduces a modern approach to the packing of data. The storage and acquisition model is aimed at reaching the highest rate capability. Each storage system packs, with the useful data, a bunch of metadata which constitute a overhead. Such overhead becomes important for both the transmission and for the storage of data, since part of the bandwidth and/or of the storage capacity is consumed by that. \begin{figure}[!] \begin{center} \includegraphics[width=0.9\linewidth]{Chapters/O2/Figs/TF.pdf} \caption{Sketch representing the acquisition flow with two detectors, A and B. The detector data samples are retrieved by the read-out logic in a continuous fashion, with the addition of heartbeat triggers interleaving for time stamping purposes. At the FLP level each data stream is time sliced, obtaining several patches which are compressed by fast processing and packed in sub TFs. The sub TFs are sent to the EPN farm and then aggregated into global TFs. Each TF has a full set of information regarding a given time interval. A global compression of around $\times14$ is achieved in the process. From \cite{Buncic:2011297}} \label{fig:O2_TF} \end{center} \end{figure} The solution introduced by $O^2$ is the so called Time Frame (TF). The TF is a container defined by two temporal boundaries which define its validity interval (Fig. \ref{fig:O2_TF}). It packs the data collected by the detectors within the validity interval. The format chosen for the TF comprehends a header which works as a summary, in order to ease the access to the contained data, and the detector data itself. The only constraints on the TF content regard the data header specification, while it was chosen to keep as much freedom as possible for what concerns the payload. For this reason the header must provide a complete description of the whole data structure. The raw data format cannot be made persistent during acquisition, therefore the raw data flow will be converted in the much more compressed TF format. % Since both at FLP (First Level Processor) and EPN (Event Processing Node) levels the data format is the TF to allow the interchangeable execution of tasks, $O^2$ foresees the possibility to have sub Time Frames which pack a reduced set of detector data. % During the LHC RUN3 ALICE will operate in continuous read-out mode. % The definition of event is difficult, since without performing a full reconstruction it will be difficult to isolate data belonging to each event. % For this reason the data stream will be split in arbitrary time-frames called SubTimeframes (STF), hence there is a non-null probability for an event data to get split between two STFs. % Each STF has an header of constant size plus some playload. % The overhead can be defined as the amount of delivered header data over the size of delivered payload. % The STF duration has been chosen looking for the best compromise between the overhead fraction and the fraction of lost events. The data stream of each detector are sent to the First Level Processor (FLP). At this level, only the information of one single detector or even part of it is available. The data format is therefore called Sub-Time Frame (STF). The processed data are then sent to the Event Processing Node (EPN), which collects the information of all detectors and aggregates them in the TF. The processing schema is shown in Fig. \ref{fig:O2_Compression}. % This is mainly needed at the FLP level, when the aggregation of data produced by different detectors is not possible. % The aggregation, based on the validity intervals of the sub TF, will happen later during the reconstruction stages. % The TF specification concerns the online part of $O^2$, and defines a standard data format for all the data processed by the reconstruction pipeline up to the stage of writing it in persistent formats. The TF data format requires all the data to be correctly time flagged, in order to be able to correctly aggregate data within the TF they belong to. For this reason the detectors raw data flows are interleaved with an heartbeat clock that can be used to attribute a time stamp to the detector data samples. % At the FLP level the samples belonging to different heartbeat trigger are sliced and packed in STF and sent to the EPNs. % At the EPN layer the sub TFs coming from different detectors are then aggregated in global TFs. % All the translation, packing and compression steps described before allow for a strong reduction of the required bandwidth without loosing too much useful data. \begin{figure}[!ht] \begin{center} \includegraphics[width=0.75\linewidth]{Chapters/O2/Figs/Compression_2.pdf} \caption{Computing infrastructure layers with quoted required input and output bandwidths. An overall factor of compression of $\approx14$ is to be achieved in the process. The network topology is not yet defined by the $O^2$ Technical Design Report since the technology growth is fast enough to require a shorter term planning later during the upgrade. From \cite{Buncic:2011297}} \label{fig:O2_Compression} \end{center} \end{figure} A total compression of around $\approx14$ \cite{o2compression} will be possible from the raw data to the storage elements and the first persistent format. The validity interval of the TF, also called duration, has to be tuned taking into account several criteria: \begin{itemize} \item the TPC drift time causes a loss of $0.1/t_{TF}$, with $t_{TF}$ expressed in ms, therefore a longer TF is better in this respect; % \item the calibration data produced during a TF has a fixed size and constitutes a fixed overhead which has to be sent to the Condition Database (CDB). A longer TF would minimize the overhead contribution to data rate and the number of CDB accesses; \item the TF should be a multiple of the shortest calibration update period. This value should be the TPC Space Charge Distortion one, scheduled each $5\ \rm ms$; \item in order to better balance the processing at the EPN level a shorter TF would be better. For the EPNs a buffer of at least three TFs (one receiving, one processing, one sending) is required to avoid dead times. \end{itemize} % The TF duration will be between limited to $\approx23\ ms$ from above. Given these requirements, the current understanding is that the TF will be limited to $\approx23 \rm ms$ which corresponds to $256$ beam orbits. The number of events packed inside a single TF will reach $1000$ interactions in normal running conditions (Pb-Pb $50\ \rm kHz$). The resulting TF size will be of $10GB$ on the EPN before compression and the unusable data because of the TPC drift time will be the $0.5\%$ of the total. Since the EPN farm will be composed by $1500$ machines, each EPN will receive a new TF to process every $30\ \rm s$. \section{Data Processing Layer} The tools provided by the default $O^2$ project are intended to be used by experts and require coding skills which are not typical for the physicists community. In particular the tasks are wrappers of part of a bigger algorithm and from now on they will be referred to as devices. They are fully described by a bunch of specifications, summarized below: \begin{enumerate} \item The specification of inputs is composed of the indication of the channel of delivery and the kind of data. It is necessary to correctly connect and feed the algorithmic item wrapped in the device. Some devices could be input-less (e.g. MC wrappers, clock generators). A complete set of inputs will be referred as "work item"; \item The internal state of the device, a set of variables capable of keeping information across several work items. This can be useful for distributed pseudo-random number generators, event counters, histograms and in general any kind of accumulation of results. The initialization of the internal state can be complex without affecting the online performances of the device. In addition some devices, for example those involved in pipeline computations, are "stateless devices", namely devices which do not need to keep a memory of previous computations. Such devices have no internal state; \item The computation specification is the algorithm that is called and executed on each complete set of inputs. Any optimization effort has to be put to this part of the device specification, since it represents the main bottleneck being executed in a loop-like fashion. This element is required for any device; \item The specification of outputs is similar to that of the inputs and consists of the indication of the channel on which the data has to be sent as well as the type of data. \end{enumerate} In this approach each device has to implement one and only one basic function. The devices are intended to be self contained and atomic. This opens up the possibility to spawn device clones or to kill unused devices to free resources for other tasks. For example if a given device (or a group of homologous devices) starts starving ($e.g.$ the CPU set waits for data since the computation is too fast with respect to the data flow) and a loss of computing efficiency is measured, it might be killed by a manager process. Similarly if a group of devices cannot cope with the input rate, the manager process can add some more in order to improve the throughput of the whole set of devices using the resources freed up by the killing of starving devices. Within the FairROOT framework, several utilities and libraries have already been implemented to simplify the configuration of new devices. In $O^2$ the description of the devices is even more trasparent to the end user thanks to an additional framework called Data Processing Layer (DPL). The DPL hides much of the complexity required by the MPI-like FairROOT devices. After some development efforts, the residual complexity left to the programmer by the DPL is negligible. Using advanced C++ techniques, available in the 11, 14 and 17 standards, the description of input and output channels is similar to the initialization of a list, while implementing the initialization and data processing functions is as complex as the required algorithm itself. The typical complexity of concurrent computing software framework is almost completely hidden, leaving much of the coding focus to the algorithmic part. During my thesis, I also participated in the effort of writing high level routines that can be easily adopted by the DPL framework to simplify the serialization of the messages. Such routines, based on \code{boost}, were extensively tested and are currently used many detector and subsystem-specific code and are requested to be included in the FairROOT core by its developers team. The DPL approach is being adopted by most part of the detectors and the systems included in the $O^2$ upgrade project, and the upgraded muon trigger software follows this schema. \section{Muon tagging algorithm} \label{MTR_tagging} The pre-upgrade offline muon tagging algorithm was intended to be executed during reconstruction, in an asynchronous computing model. Within the $O^2$ upgrade this algorithm will be modified to be fed with information computed synchronously, thus strongly improving the muon tagging capabilities of the system. It is based on the matching between tracks reconstructed in the muon tracker and the tracklets (straight tracks) reconstructed in the MTR. The tracks reconstructed within the muon chambers are obtained using a Kalman Filter algorithm. Since the five stations of muon chambers are placed upstream, inside and downstream of the dipole magnet, the reconstructed tracks are curved. The reconstructed tracks are extrapolated towards the muon trigger system. These pieces of information are then matched with the tracklets generated using the MTR data. % A tracklet is a set of crossing point and 3D slope, describing a straight segment. % The muon chamber tracks extrapolation uses the same format. The muon identification criteria is based on the fact that only the muon chamber tracks which are found to correspond to a muon trigger one are to be considered muons, since it is unlikely for other particles to cross the $1.2\ \rm m$ thick iron wall between the two stations of the muon trigger (Fig. \ref{fig:MTR_old}). \begin{figure}[!ht] \begin{center} \includegraphics[width=0.9\linewidth]{Chapters/O2/Figs/MTR_logic.pdf} \caption{In this picture the muon chamber and muon trigger planes are represented in yellow, the iron wall in purple and the dipole is shown in blue. The dashed line represents the true trajectory of the muon. The green line is the reconstructed track within the muon chambers, while the orange line is the tracklet reconstructed in the muon trigger.} \label{fig:MTR_old} \end{center} \end{figure} The generation of the tracklets in MTR was based on the MTR trigger algorithm, which is in turn based on the Local Boards, which collect the information of the fired strip in a projective region in the four detection plane. When a particle fires a strip in the first chamber, the local board searches for aligned strips in the other chambers, combining the information of the adjacent local boards in the bending plane. From this information the algorithm computes a hit position in the first chamber and a deviation, i.e. a tracklet. This algorithm, however, provides at most one response (and therefore one tracklet) per local board. In the case where more than one track crosses the same local board, the algorithm is tuned to chose the combination of hits providing the minimum deviation (i.e. largest $p_\mathrm{T}$) in order to keep the highest trigger efficiency. This however might result in a reconstruction of just one track, as shown in figure \ref{fig:MTR_loss}, or of a fake track that does not match any of the two real tracks. This limitation affects the most central heavy-ion collisions, where the large particle multiplicity results in a larger probability of having two muons crossing the same LB. The inefficiency was then caused by an algorithmic feature more than by the detector itself. \begin{figure}[!ht] \begin{center} \includegraphics[width=0.5\linewidth]{Chapters/O2/Figs/MTR_old.pdf} \caption{The MTR planes are shown in grey, while the hit local board is highlighted in yellow. Two real trajectories are represented by the lines. The algorithm is tuned to select the less sloped track in case of ambiguity, hence only the solid blue track would be recorded.} \label{fig:MTR_loss} \end{center} \end{figure} Some development of an algorithm capable of recovering the performance loss in the most central events was performed but never put in the production code. % Given the much higher luminosity and interaction rate foreseen for the LHC RUN3, this aspect should be fixed by the new implementation of the MID algorithm. The complex solution of implementing a tracking algorithm in using the former MTR, excluded for RUN2, was indeed the proposed solution for RUN3 running conditions. % The approach used during RUN2 allows for easier measurement of the matching efficiency, since the tracklets which get evaluated to generate the trigger signal are the same that offline are matched with the muon tracker tracks. % Implementing a tracking algorithm brings in the possibility to generate fake tracks which might match with muon tracker tracks. % This aspect causes some additional hassle in the evaluation of the matching efficiency and that solution was discarded for RUN2 operations. % With RUN3 such solution has become necessary and was implemented. \section{From Muon TRigger to Muon IDentifier} In the Run3, the MTR will lose its functionality of a triggering detector\footnote{although the possibility of providing a very basic trigger was kept in the electronics, mainly for studying muon production in ultra-peripheral Pb-Pb collisions}, and it will only be used to provide muon identification. Its name will be changed accordingly to reflect the change of functionality, thus passing from Muon TRigger to Muon IDentifier (MID). % The name of the ALICE muon trigger (MTR) will be modified from the introduction of the $O^2$ project. % This change of nomenclature is related to a change of its online functions. % The muon trigger provided various online acquisition triggers based on the detection of muons and worked as a muon tagger for the muon chambers tracks. % The MTR will see the upgrade of read-out electronics, already presented in previous chapters. % In addition to this hardware upgrade, the online function of the MTR system will change. % The MTR system will no longer provide an online trigger system for ALICE, since the acquisition paradigm will move to trigger-less. % Instead the system will become a stand alone muon tracking system. % Even if the tracking resolution of the muon trigger system is lower than that of the muon tracker and that of the future MFT (Muon Forward Tracker), the muon identification task will be achieved by the MTR which will then become the MID (Muon IDentifier). The muon identification (and hadron rejection) task will be performed combining data coming from the MCH and MID detectors. The addition of the Muon Forward Tracker (MFT) \cite{CERN-LHCC-2015-001} will improve the tracks resolution closer to the interaction point and make it possible to resolve secondary vertexes. The tracks reconstructed with MCH data will be identified as muons if a compatible track in the MID detector is present. % This task will be performed online, processing and reconstructing around $300\ MB/s$ \cite{Buncic:2011297} of data in Pb-Pb collisions. Even if the original idea at the base of the $O^2$ project was to perform an online reconstruction for all detectors and systems, the paradigm has been changed since the efforts needed for such implementation were difficult to sustain. Nowadays the common approach is to perform online computations only if they can lead to a compression of output data. Given the MID is a fast detector, the presence (absence) of detected particles could be evaluated online and used to decide to keep (discard) MCH data. Such decision would both avoid the CPU-heavy task of performing the tracking algorithm on MCH data and reduce the throughput of the MCH. For obvious reasons this MCH data rejection technique must be hot-plugable, in order to allow to perform systematic tests without this selection at the beginning of the data taking. The acquisition/reconstruction workflow is represented in figure \ref{fig:O2_sketch}. Data recorded by the FEE will be acquired via several GBTx link by the Common Readout Units (CRU), each one processing one half of the MID (inside and outside). The CRUs are implemented as PCI express boards equipped with two external GBTx ports and an on-board Altera Arria X FPGA. The CRUs will be installed in two dual CPU machines called First Level Processors (the FLPs) which will be placed in the counting rooms placed over the ALICE cavern, as close as possible to the detectors. The CRUs will perform the coding of the input stream in a binary format which can be sent and processed by the FLP (Fig. \ref{fig:O2_CRU}). Zero suppression and noisy/dead channels detection/suppression will be performed by the CRU. Finally, at the EPN level, the combination of MID data with data coming from other detectors will be possible. \begin{figure}[!ht] \begin{center} \includegraphics[width=0.9\linewidth]{Chapters/O2/Figs/CRU.pdf} \caption{Detailed sketch of a generic Common Readout Unit (CRU). The Front End Electronics (FEE) are connected to the CRU through 24 embedded GBT links. The green boxes are connected to the Central trigger Processor (CTP) and deliver timing information to time tag the raw data flow, performed by the detector specific logic. The raw data is translated in a binary format which can be processed by the FLP CPUs. The ouput of the CRU is performed by a standard PCI Express link. From \cite{Buncic:2011297}} \label{fig:O2_CRU} \end{center} \end{figure} \section{MID raw data format} The MID data format follows the directives of $O^2$ for what concerns the description of the payload by means of headers. A top level header defines the binary intervals at which what kind of information is found and constitutes a constant size overhead. The management of data inside the binary payload follows a tree pattern. At each branching of the pattern a description (header) describes the positions of the following branches. In turn each branch provides a self description needed to deserialize and decode the content. The data format requires a sequential access in order to correctly map its content to meaningful variables and structures. The data format has an implicit zero suppression, since only the hit strips are coded in a bit pattern which is then sent. \begin{figure}[!ht] \begin{center} \includegraphics[width=0.99\linewidth]{Chapters/O2/Figs/MID_format_2.pdf} \includegraphics[width=0.99\linewidth]{Chapters/O2/Figs/MID_format_1.pdf} \caption{Two CRU data format proposals. In the first option only one non bending pattern is sent from the CRU to the FLP, while the FEE sends to the CRU several copies of the same pattern since the horizontal strips are read by several local boards each. The CRU has to perform some operation in order to combine the multiple non bending plane patterns into a single one. The second format foresees to send to the FLP several non bending plane patterns, which are combined by the FLP itself.} \label{fig:MID_CRU_DF} \end{center} \end{figure} Each side of the MID serializes the information using as top level header the number of fired RPCs, which corresponds to the number of following branches. Each branch representing an RPC provides an header which quotes the RPC ID and the number of columns fired within that RPC (see Fig. \ref{fig:MID_CRU_DF}). Another branch level represents each of the fired columns and for each column both the column ID and the number of fired Local Boards (LB). The deepest branch level represents the LBs by giving the LB ID and the bit patterns of the LB. The patterns correspond to strip in the bending and non-bending direction. It is worth noting that the non-bending strip can cross several local boards, so each pattern is a copy, in that local board, of the non-bending information. In an alternative proposal, the non-bending information is stored only once per column (see Fig. \ref{fig:MID_CRU_DF} bottom). The advantage is that the information is not replicated, but in this case any mismatch in the local copy of the NB strip needs to be monitored at the CRU level. It is also worth noting that all of the patterns are coded in 16 bits, although some LBs are equipped with only 8 strips in the NB direction. % The patterns correspond to bending and non-bending strip directions and each pattern is coded in 16 bits, which are not always completely filled. % In fact some LBs are equipped in a given direction with less than 16 strips. In that case the pattern gets filled accordingly to the hits and the exceeding bits are set to 0. As already stated, the MID RPCs require to perform two kinds of calibration events in order to detect problematic channels. The issues can be either channels which starts to count continuously because of a discharge in the chamber or channels which stops counting because of detector or electronics failures. The characteristics of the two kinds of calibration events are intended to address the detection of both issues. % The first kind of calibration run is performed when no collision is happening (e.g. between two interactions). % In such situation the noisy channels can be detected since they would be the only ones counting. In one case the read-out of the detector is triggered asynchronously with respect to an interaction. In the absence of a cosmic event, only noisy channel will respond in this case. In a second case, the FEE injects charge above the threshold in all channels to check whether they are responsive or not. % The second kind of calibration run is performed using a FEE feature which provides an independent circuitry to inject an electric charge in the strip itself. During this calibration event all the strips are stimulated, therefore expected to be counting. This allows one to detect the presence of dead channels. The chosen MID raw data format is not efficient for the second kind of calibration event. In fact, since the dead channels are expected to be a small part of the total, during such events the bit patterns of almost the whole detector should be transferred. In order to optimize the data delivery process, by reducing the amount of useless information being sent, an additional bit can be delivered in order to flag the message payload as "straight" or "inverted". In the first case nothing changes and the overhead of the data format would be increased of 1 bit. In the second case only the dead channels are sent as if they would have been the only channels switched on. Thanks to the additional bit, the decoder will be able to invert the message to obtain the correct information. % In addition, in case of bandwidth bottlenecks, the inversion bit could become useful in case of high MID occupancy. % In case more than $50\%$ of the detector is switched on, the FEE could decide to deliver the inverted bit pattern flagged accordingly. % The expected MID occupancy is however expected to be low enough to discard the usage of the inversion bit for any event but for the calibration runs of second type. \section{MID reconstruction pipeline} The MID reconstruction pipeline is an algorithm which, from a global point of view, should convert the digits streams obtained from the CRUs to a stream of 3D tracks representing the detected muons. The digits stream coming from the CRU is decoded and, in case of the special software trigger, the noisy and dead channels are computed. The detection of noisy channels will allow for the generation of a mask that will have to be transferred to the local boards. This is fundamental because the presence of noise increases the bandwidth from the detector readout to the CRU, eventually leading to a saturation. The details of the transfer, however, are still under investigation. The information on dead channels and masks needs to be permanently stored so that it will become available for simulation and efficiency evaluation purposes. This will most likely be done in the Condition DataBase (CDB). Moreover, the detection of dead and noisy channels will be the first step of the Quality Control (QC) of the detector, since it allows one to pinpoint hot spots and dead zones of the RPC chambers. % This procedure is needed for two reasons. % First of all one wants to keep track of problematic strips in the CDB (Condition DataBase) to be able to highlight problematic RPC chambers and to detect hot spots and/or dead zones which can both lead to a loss of efficiency. % Moreover, concerning the noisy channels, their reading are not significant from a tracking point of view since they simulate a particle crossing which did not happen, hence one wants to mask out noisy channels in order to help the tracking algorithm. % While the record of the noisy and dead channels can be performed in a relaxed way, the masking of noisy channels should be capable of sustaining the same rate of the inputs in order to avoid the introduction of delays. % The applied mask has to be stored in the CDB as well, alongside a temporal validity range, to allow a granular reconstruction of the MID running condition for simulation adn efficiency evaluation purposes. The reconstruction steps for the MID are intended to be mainly (if not globally) executed on the detector FLPs. The MID will be equipped with one FLP per side (inside and outside) which won't be equipped with a cross connection, hence won't be able to exchange data. For this reason the MID has to be considered as a pair of independent detectors. Only at the EPN level data coming from both sides will be merged and combined. \begin{figure}[!ht] \begin{center} \includegraphics[width=1\linewidth]{Chapters/O2/Figs/MID_workflow.pdf} \caption{Schema of the MID reconstruction workflow obtained from the DPL Graphic User Interface (GUI). This workflow is intended to be executed in the FLP. Each box represents a device and the arrows represent a data stream. The first device, called ColDataStreamer, is a random generator of fake CRU messages able to emulate the CRU behaviour for testing purposes. The upper branch represents the asynchronous mask computing stage of the workflow. The last device, called sink, represents the connection to the EPN nodes and the second online processing step.} \label{fig:MID_workflow} \end{center} \end{figure} Regarding the acquisition, some logic steps to perform the conversion have been defined, in order to provide atomic computation items able to be packed in deployable and modular devices: \begin{itemize} \item the digits coming from the CRU are cloned towards two branches. The first branch leads to the mask generation and can be asynchronous with respect to the input data flow. The second branch has to present limited latency to avoid starvation of the following reconstruction devices; \item the mask generation branch begins with a rate computer, namely a device with an internal state which works as a per-strip counter. % The counters are sent to a mask generator device which reads the counters and spots the noisy channels; Two counter sets are available, one for the noisy and the other for the dead channels, incremented during the corresponding special events; \item a mask generator devices reads the recorded counters and spots dead and noisy channels by looking at the scalers incremented during calibration runs. % Two scalers sets will be available, the first being filled by the readings of the dead channels test, the second by the noisy channels one. % The channels switched on when no collision is happening are marked as noisy and propagated to the mask. % The channels not counting during the injection of charge in the electronics are marked as dead. The mask is sent to a filter device; \item a filter device is capable of applying the mask to the incoming digits. The application of the mask is the logic AND between the incoming patterns and the corresponding mask. In case no mask is present, or the mask is empty, the digits should simply be passed through as fast as possible. Achieving the lowest latency on this device is crucial; \item the stream of masked digits is then processed by a clusterizer device. The binary digits are here converted to 2D clusters, computing the centroids of the hits clusters. % The third coordinate of the cluster is extrapolated from the detector geometry and added to the planar coordinates. This computing step is a typical high throughput stateless computation; \item the 2D clusters in the local RPC reference frame are passed to a device that converts it in 3D clusters in the global reference frame and preforms the tracking through a Kalman Filter algorithm. The generated tracks are sent to the following reconstruction steps executed by the EPNs. \end{itemize} The MID reconstruction pipeline has been developed within the DPL framework. A schema of this pipeline, as provided by the DPL Graphical User Interface (GUI) itself, is shown in \ref{fig:MID_workflow}. \section{MID reconstruction performances} % The MID algorithm has to be validate in order to provide a performance similar to the old MTR offline reconstruction, with the added rate capability. The MID reconstruction algorithm is new compared with what was used for MTR, which was entirely based on the trigger algorithm. Both the clustering and the tracking algorithms need to be validated in Monte Carlo (MC) simulations. The framework for MC simulation for MID is work in progress, but, since the detector geometry and segmentation did not change with respect to MTR, the Run2 simulation can be used for the validation of the algorithms. In particular, a custom MC production using a \jpsi parametrization as input is used. The crossing points of the tracks in the RPCs are used by the MID digitizer algorithm to generate the digits on which the MID reconstruction chain is applied. The reconstructed clusters and tracks are then compared to the MC impact point and track parameters to estimate the residuals. The final aim is to study: \begin{itemize} \item the resolution of the algorithm in four variables: \begin{itemize} \item the cluster residuals (along x and y); \item the track resolution, i.e. the resolution on the track position (mainly along x and y) and slopes along the bending and non bending plane; \end{itemize} % $x$ and $y$ first crossing resolution and vertical and horizontal slope. The resolution should be studied both as a function of the detector element and of cinematic variables of the reconstructed particle. \item the muon reconstruction efficiency; \item the fraction of fake tracks, i.e. tracks reconstructed with the wrong parameters by mixing real hits from different particles or noise. The study should be performed as a function of the particle multiplicity in the MID chambers. \end{itemize} Some of these quantities have already been studied in details and the results will be presented in the following. The methodology for the studies that are not accomplished yet will be discussed as well. \subsection{Cluster residuals} % The overall reconstruction resolution is related to the cluster size. % Usually the cluster size is defined by the number of adjacent strips which are fired by a given particle. % Since such definition is not able to take into account different strip pitches, like the ones installed in the MID, a different definition is given and adopted from now on. % The cluster size is defined as the maximum distance between the first and the last strips of the cluster, both in $x$ and $y$ directions. The MID electronics does not provide any information on the deposited charge. For this reason, a charge centroid cannot be computed and the cluster centroid is purely geometrical. The centroids coordinates are computed as the average of the coordinates of the strips. Since a flat distribution of crossing probability has to be assumed within the cluster extension, the resolution is directly proportional to the cluster extension via the relation $\frac{CS}{\sqrt{12}}$ where $CS$ is the cluster size. % The cluster size has been studied using a single p-Pb run recorded during LHC RUN2. % A sample of the cluster sizes distribution of some RPCs is shown in figure \ref{fig:MID_CS}. % The distribution is strongly focused at low cluster sizes and over $3$ cm of displacement the fired probability drops under $5\%$. % The first test to be performed is the comparison of the updated algorithm with the old one. % The old algorithm performed well, despite some marginal flaws. % The new algorithm should add the online reconstruction capability performing at least as well as the old one. The performance of the algorithm has been evaluated running the reconstruction on simulated data. The cluster residuals between the reconstructed clusters and the generated clusters have been computed and represented in form of a distribution. The residuals distributions are generated as a function of the detection element ID (i.e. the RPC). Such distributions present some square shaped structures which are artifacts caused by the different strips pitches. In fact, while the RPCs closer to the beam line are equipped with strips $1$, $2$ and $4$ cm wide, other RPCs are equipped only with $2$ and $4$ cm or only with $4$ cm strips. % The square shaped artifacts reflect such distribution and reflect as well the spatial quantization due to the digital read-out. The residuals distribution is symmetric with respect to the $0$ and the $x$ ($y$) RMS is $0.9$ ($0.8$) cm. The distribution plots of the residuals are reported in figure \ref{fig:MID_CR}. \begin{figure}[!] \begin{center} \includegraphics[width=0.9\linewidth]{Chapters/O2/Figs/CRx.pdf} \includegraphics[width=0.9\linewidth]{Chapters/O2/Figs/CRy.pdf} \caption{Cluster residuals distribution as a function of the RPC ID. The $y$ bins are continuous values, while each $x$ axis bin represents a single RPC. The square shaped artifacts are related to the different strip pitches each RPC is equipped with. The RPCs equipped with strips down to $1$ cm wide present the hot spots due to the superposition of the residuals distributions of $1$, $2$ and $4$ cm wide strips. The $y$ distribution presents smaller structures since the average strip size is smaller. Each RPC distribution is not normalized on its irradiation hence the colour palette is the same for all the RPCs.} \label{fig:MID_CR} \end{center} \end{figure} \subsection{Track residuals} Another set of residuals has been computed comparing the generated information to the reconstructed tracks. In this case all the tracks are described by three spatial coordinates for the crossing point in the first chamber and two deviations, one along $x$, the other along $y$. The residuals between such parameters have been computed and shown as a function of the position within the RPCs as well as from the kinematic parameters of the track. This test can be performed using simulated muon tracks for RUN2. % The test consists in getting a list of reconstructed tracks from RUN2 data. % The same data file used for the cluster size and cluster residuals evaluation has been processed for this test. The tracking algorithm is applied to the set of digits and the reconstructed tracks are recorded in the form of a 3D crossing point on the first MID station and a 2D slope. % Such measurements are compared to the output of the old tracking algorithm. The residuals distributions of cluster positions and tracks comparison are generated as a function of the detection element (i.e. the RPC) and of the generated total momentum $p$ of the particle. % The action of the Kalman filter is the reduction of the effect of the spatial segmentation typical of a stripped/padded detector. % For this reason the tracks residuals are less affected by the strips size. % The residuals are shown as a function of the reconstructed momentum $p$ of the particles. The spatial resolution along $x$ and $y$ are shown in figures \ref{fig:MID_xpoint_x} and \ref{fig:MID_xpoint_y} respectively, as a function of the generated total momentum of the particle. The residuals normalized on the residual uncertainty are shown in figure \ref{fig:MID_TRm}. Most of the measurements are within 3 sigmas as expected, except for extremely low momenta particles. The distribution gets narrower moving to higher $p$ particles. It is worth noting that the binning of the histogram varies versus $p$, in particular going from $1\ \rm GeV/c$ to $2\ \rm GeV/c$ for $p\ =\ 20\ \rm GeV/c$. Both distributions are centered at $0$ cm. As expected, considering the detector morphology, the vertical resolution ($0.4$ cm) is better than the horizontal one ($0.7$ cm). % The distributions relative to the crossing point are reported in figures \ref{fig:MID_xpoint_x} and \ref{fig:MID_xpoint_y}. The spatial resolutions are reflected in the slope resolutions. In order to better understand the angular resolution, the distribution is shown as the residual divided by the uncertainty that is automatically calculated by the Kalman filter. Up to the $95\%$ of the distribution is within the $\pm1.96$ band in the vertical slope distribution. The distribution gets physiologically broader at lower $p_\mathrm{T}$. \begin{figure}[!ht] \begin{center} \includegraphics[width=0.99\linewidth]{Chapters/O2/Figs/TRx.pdf} \caption{Track residuals distribution of the horizontal coordinate. The $y$ axis represents the residual expressed in centimeters, while the $x$ axis is the generated momentum of the particle. The colour palette is in logarithmic scale. The core of the distribution is about $1$ cm wide and very few outliers cross the $\pm2$ cm band.} \label{fig:MID_xpoint_x} \end{center} \end{figure} \begin{figure}[!ht] \begin{center} \includegraphics[width=0.99\linewidth]{Chapters/O2/Figs/TRy.pdf} \caption{Track residuals distribution of the vertical coordinate. The $y$ axis represents the residual expressed in centimeters, while the $x$ axis is the reconstructed momentum of the particle. The colour palette is in logarithmic scale. The core of the distribution is about $0.5$ cm wide and like for the horizontal coordinate, very few outliers cross the $\pm2$ cm band.} \label{fig:MID_xpoint_y} \end{center} \end{figure} \begin{figure}[!h] \begin{center} \includegraphics[width=0.99\linewidth]{Chapters/O2/Figs/TRmx_sigma.pdf} \includegraphics[width=0.99\linewidth]{Chapters/O2/Figs/TRmy_sigma.pdf} \caption{Residuals of the vertical and horizontal slopes evaluation between the old MTR's algorithm and the new MID's one. The values are represented as residuals ($y$) divided by sigma as a function of the reconstructed particle momentum. The colour pallette is represented in logarithmic scale.} \label{fig:MID_TRm} \end{center} \end{figure} The overall resolution presents a clear dependence with respect to the particle momentum. % A lower resolution has been measured for low impulse particles, while the distribution spread decreases moving to higher momentum. The result is already rather good, but it is worth noting that the algorithm is not yet fine tuned and the resolution at very low \pt could be further improved. The fine tuning of the algorithm has not yet been performed and such optimization could help solving the issue. % \subsection{Algorithm resolution} % The residuals computed between two outputs are equivalent to the resolution plots of one of the two methods if and only if the other algorithm is the perfect or ideal one. % Since the MTR algorithm was not ideal, the comparison reported in the previous section is not equivalent to a resolution measurement. % A proper way to determine the reconstruction resolution of a given algorithm is to use as input and control variables the information generated by a simulation whose Monte Carlo truth is accessible. % The reconstruction algorithm is applied to the simulated data and its output is recorded. % Since using a Monte Carlo simulation allows one to access the true particle parameters, the residuals are computed between such parameters and the reconstructed tracks' ones. % The residuals distributions features, such as the mean values and the standard deviation, can be used to evaluate possible algorithmic biases leading to a polarized residuals distribution and, in general, to associate an error to the reconstructed parameters. % The Monte Carlo simulation used for such tests should emulate the tracks multiplicity expected in the real events. % In fact, the overlapping of clusters belonging to different particles might lead to worse performances caused by bad clusters selection or centroid computation. % This benchmark has not yet been performed and is expected as future development. \subsection{Tracking efficiency} The measurement of the algorithm resolution is not the only crucial test for a new tracking method. An algorithm might present exceptional resolution on a negligible fraction of the processed tracks. For this reason the evaluation of the tracking efficiency, defined as the ratio between processed particles and reconstructed ones, is crucial. % The study of the reconstruction efficiency can be performed using Monte Carlo simulations as input. % The simulations which can be used for such study are either full simulations or embedded simulations. % While the full simulations are events completely simulated using a generator, the embedded simulations are real events which are provided with an overlapped simulation of a specific signal. % In this case the embedded simulations are created generating a quarkonium state forced to decay in an unlike sign muon pair within the MID acceptance. % The efficiency of the reconstruction is the ratio between the number of reconstructed and generated muons. % The quarkonia states reconstruction efficiency is the product of the reconstruction efficiencies of the two muons. % It is important to evaluate the differential reconstruction efficiency with respect to cinematic variables such as rapidity and (transverse) momentum. The tracking efficiency was estimated using the same MC as the one used for the residuals. The results of this study are reported in figure \ref{fig:ID_eff}. The measured efficiency is very close to unity. Some bins at very high $p_{\mathrm{T}}$ and/or at the edge of the muon spectrometer $\eta$ acceptance, show an efficiency drop\footnote{Entries at zero efficiency mostly correspond to $p_{\mathrm{T}}$ and $y$ bins where no generated muon fell in.}. The study should be repeated in the future with simulations embedded in real events in order to assess the efficiency of the algorithm at high particle multiplicity. \begin{figure}[!b] \begin{center} \includegraphics[width=0.9\linewidth]{Chapters/O2/Figs/ID_Eff.pdf} \caption{Tracking efficiency computed as the ratio between the numbers of reconstructed and generated tracks.} \label{fig:ID_eff} \end{center} \end{figure} \subsection{PID characterization} The PID performance of the new algorithm has to be evaluated. First of all the PID efficiency has to be computed. This characteristic of the algorithm corresponds to its matching probability. Such measurement can be performed evaluating how many true muons are matched with muon tracker data, hence correctly flagged. Using Monte Carlo simulations one can measure such fraction computing the ratio between reconstructed muons and reconstructible muons. A reconstructible is a muon which has been generated within the muon spectrometer acceptance and produced hits in both MCH and MID. For what concerns MID the requirement is that a hit (both $x$ and $y$) in at least $3/4$ planes was detected. In case of missing bending or non-bending information on more than $1/4$ planes the tracking resolution will drop considerably. Concerning MCH the requirements will stay the same as in RUN2: at least $1/2$ plane hit in each of the three inner stations (1, 2, 3) and at least $3/4$ planes hit for the two remaining stations (4, 5). Secondly the fraction of mis-identified particles should be computed as well. Some particles which are not muons are detected and reconstructed in the MCH. If they get matched with some MID tracklets then become wrongly flagged as muons. In order to evaluate this mis-identification probability one should compute the ratio between the number of non-muons matched in the MID and the number of non-muons reconstructed in the MCH. Both these characterizations have not been performed yet. % The mis-identification probability is then evaluated using complete Monte Carlo simulations, in order to be able to know the real identity of each identified particle. % The probability of mis-identification is then evaluated as the ratio between the number of non-muons identified as such divided by the total number of identified particles. % Given a particle has been tagged as muon, the mis-identification probability corresponds to the inverse of the significance of the identification itself. % The density of non muons reaching the MID is higher closer to the beam pipe, at high rapidities. % For this reason the differential study is necessary to be sure that the mis-identification probability is low at least in the lowest rapidity region to limit as much as possible the pollution from other particles. % Such measurement has not been performed yet.
import tactic -- Let `Ω` be a "big underlying set" and let `X` and `Y` and `Z` be subsets variables (Ω : Type) (X Y Z : set Ω) (a b c x y z : Ω) namespace xena /-! # subsets Let's think about `X ⊆ Y`. Typeset `⊆` with `\sub` or `\ss` -/ -- `X ⊆ Y` is the same as `∀ a, a ∈ X → a ∈ Y` , by definition. lemma subset_def : X ⊆ Y ↔ ∀ a, a ∈ X → a ∈ Y := begin -- true by definition refl end lemma subset_refl : X ⊆ X := begin sorry, end lemma subset_trans (hXY : X ⊆ Y) (hYZ : Y ⊆ Z) : X ⊆ Z := begin -- If you start with `rw subset_def at *` then you -- will have things like `hYZ : ∀ (a : Ω), a ∈ Y → a ∈ Z` -- You need to think of `hYZ` as a function, which has two -- inputs: first a term `a` of type `Ω`, and second a proof `haY` that `a ∈ Y`. -- It then produces one output `haZ`, a proof that `a ∈ Z`. -- You can also think of it as an implication: -- "if a is in Ω, and if a ∈ Y, then a ∈ Z". Because it's an implication, -- you can `apply hYZ`. This is a really useful skill! sorry end /-! # Equality of sets Two sets are equal if and only if they have the same elements. The name of this theorem is `set.ext_iff`. -/ example : X = Y ↔ (∀ a, a ∈ X ↔ a ∈ Y) := begin exact set.ext_iff end -- In practice, you often have a goal `⊢ X = Y` and you want to reduce -- it to `a ∈ X ↔ a ∈ Y` for an arbitary `a : Ω`. This can be done with -- the `ext` tactic. lemma subset.antisymm (hXY : X ⊆ Y) (hYX : Y ⊆ X) : X = Y := begin -- start with `ext a`, sorry end /-! ### Unions and intersections Type `\cup` or `\un` for `∪`, and `\cap` or `\i` for `∩` -/ lemma union_def : a ∈ X ∪ Y ↔ a ∈ X ∨ a ∈ Y := begin -- true by definition refl, end lemma inter_def : a ∈ X ∩ Y ↔ a ∈ X ∧ a ∈ Y := begin -- true by definition refl, end -- You can rewrite with those lemmas above if you're not comfortable with -- assuming they're true by definition. -- union lemmas lemma union_self : X ∪ X = X := begin sorry end lemma subset_union_left : X ⊆ X ∪ Y := begin sorry end lemma subset_union_right : Y ⊆ X ∪ Y := begin sorry end lemma union_subset_iff : X ∪ Y ⊆ Z ↔ X ⊆ Z ∧ Y ⊆ Z := begin sorry end variable (W : set Ω) lemma union_subset_union (hWX : W ⊆ X) (hYZ : Y ⊆ Z) : W ∪ Y ⊆ X ∪ Z := begin sorry end lemma union_subset_union_left (hXY : X ⊆ Y) : X ∪ Z ⊆ Y ∪ Z := begin sorry end -- etc etc -- intersection lemmas lemma inter_subset_left : X ∩ Y ⊆ X := begin sorry end -- don't forget `ext` to make progress with equalities of sets lemma inter_self : X ∩ X = X := begin sorry end lemma inter_comm : X ∩ Y = Y ∩ X := begin sorry end lemma inter_assoc : X ∩ (Y ∩ Z) = (X ∩ Y) ∩ Z := begin sorry end /-! ### Forall and exists -/ lemma not_exists_iff_forall_not : ¬ (∃ a, a ∈ X) ↔ ∀ b, ¬ (b ∈ X) := begin sorry, end example : ¬ (∀ a, a ∈ X) ↔ ∃ b, ¬ (b ∈ X) := begin sorry, end end xena
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import data.set.function import logic.equiv.basic /-! # Equivalences and sets In this file we provide lemmas linking equivalences to sets. Some notable definitions are: * `equiv.of_injective`: an injective function is (noncomputably) equivalent to its range. * `equiv.set_congr`: two equal sets are equivalent as types. * `equiv.set.union`: a disjoint union of sets is equivalent to their `sum`. This file is separate from `equiv/basic` such that we do not require the full lattice structure on sets before defining what an equivalence is. -/ open function set universes u v w z variables {α : Sort u} {β : Sort v} {γ : Sort w} namespace equiv @[simp] lemma range_eq_univ {α : Type*} {β : Type*} (e : α ≃ β) : range e = univ := eq_univ_of_forall e.surjective protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s := set.ext $ λ x, mem_image_iff_of_inverse e.left_inv e.right_inv lemma _root_.set.mem_image_equiv {α β} {S : set α} {f : α ≃ β} {x : β} : x ∈ f '' S ↔ f.symm x ∈ S := set.ext_iff.mp (f.image_eq_preimage S) x /-- Alias for `equiv.image_eq_preimage` -/ lemma _root_.set.image_equiv_eq_preimage_symm {α β} (S : set α) (f : α ≃ β) : f '' S = f.symm ⁻¹' S := f.image_eq_preimage S /-- Alias for `equiv.image_eq_preimage` -/ lemma _root_.set.preimage_equiv_eq_image_symm {α β} (S : set α) (f : β ≃ α) : f ⁻¹' S = f.symm '' S := (f.symm.image_eq_preimage S).symm @[simp] protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) : e.symm '' t ⊆ s ↔ t ⊆ e '' s := by rw [image_subset_iff, e.image_eq_preimage] @[simp] protected lemma subset_image' {α β} (e : α ≃ β) (s : set α) (t : set β) : s ⊆ e.symm '' t ↔ e '' s ⊆ t := calc s ⊆ e.symm '' t ↔ e.symm.symm '' s ⊆ t : by rw e.symm.subset_image ... ↔ e '' s ⊆ t : by rw e.symm_symm @[simp] lemma symm_image_image {α β} (e : α ≃ β) (s : set α) : e.symm '' (e '' s) = s := e.left_inverse_symm.image_image s lemma eq_image_iff_symm_image_eq {α β} (e : α ≃ β) (s : set α) (t : set β) : t = e '' s ↔ e.symm '' t = s := (e.symm.injective.image_injective.eq_iff' (e.symm_image_image s)).symm @[simp] lemma image_symm_image {α β} (e : α ≃ β) (s : set β) : e '' (e.symm '' s) = s := e.symm.symm_image_image s @[simp] lemma image_preimage {α β} (e : α ≃ β) (s : set β) : e '' (e ⁻¹' s) = s := e.surjective.image_preimage s @[simp] lemma preimage_image {α β} (e : α ≃ β) (s : set α) : e ⁻¹' (e '' s) = s := e.injective.preimage_image s protected lemma image_compl {α β} (f : equiv α β) (s : set α) : f '' sᶜ = (f '' s)ᶜ := image_compl_eq f.bijective @[simp] lemma symm_preimage_preimage {α β} (e : α ≃ β) (s : set β) : e.symm ⁻¹' (e ⁻¹' s) = s := e.right_inverse_symm.preimage_preimage s @[simp] lemma preimage_symm_preimage {α β} (e : α ≃ β) (s : set α) : e ⁻¹' (e.symm ⁻¹' s) = s := e.left_inverse_symm.preimage_preimage s @[simp] @[simp] lemma image_subset {α β} (e : α ≃ β) (s t : set α) : e '' s ⊆ e '' t ↔ s ⊆ t := image_subset_image_iff e.injective @[simp] lemma image_eq_iff_eq {α β} (e : α ≃ β) (s t : set α) : e '' s = e '' t ↔ s = t := image_eq_image e.injective lemma preimage_eq_iff_eq_image {α β} (e : α ≃ β) (s t) : e ⁻¹' s = t ↔ s = e '' t := preimage_eq_iff_eq_image e.bijective lemma eq_preimage_iff_image_eq {α β} (e : α ≃ β) (s t) : s = e ⁻¹' t ↔ e '' s = t := eq_preimage_iff_image_eq e.bijective @[simp] lemma prod_comm_preimage {α β} {s : set α} {t : set β} : equiv.prod_comm α β ⁻¹' t ×ˢ s = s ×ˢ t := preimage_swap_prod lemma prod_comm_image {α β} {s : set α} {t : set β} : equiv.prod_comm α β '' s ×ˢ t = t ×ˢ s := image_swap_prod @[simp] lemma prod_assoc_preimage {α β γ} {s : set α} {t : set β} {u : set γ} : equiv.prod_assoc α β γ ⁻¹' s ×ˢ (t ×ˢ u) = (s ×ˢ t) ×ˢ u := by { ext, simp [and_assoc] } @[simp] lemma prod_assoc_symm_preimage {α β γ} {s : set α} {t : set β} {u : set γ} : (equiv.prod_assoc α β γ).symm ⁻¹' (s ×ˢ t) ×ˢ u = s ×ˢ (t ×ˢ u) := by { ext, simp [and_assoc] } -- `@[simp]` doesn't like these lemmas, as it uses `set.image_congr'` to turn `equiv.prod_assoc` -- into a lambda expression and then unfold it. lemma prod_assoc_image {α β γ} {s : set α} {t : set β} {u : set γ} : equiv.prod_assoc α β γ '' (s ×ˢ t) ×ˢ u = s ×ˢ (t ×ˢ u) := by simpa only [equiv.image_eq_preimage] using prod_assoc_symm_preimage lemma prod_assoc_symm_image {α β γ} {s : set α} {t : set β} {u : set γ} : (equiv.prod_assoc α β γ).symm '' s ×ˢ (t ×ˢ u) = (s ×ˢ t) ×ˢ u := by simpa only [equiv.image_eq_preimage] using prod_assoc_preimage /-- A set `s` in `α × β` is equivalent to the sigma-type `Σ x, {y | (x, y) ∈ s}`. -/ def set_prod_equiv_sigma {α β : Type*} (s : set (α × β)) : s ≃ Σ x : α, {y | (x, y) ∈ s} := { to_fun := λ x, ⟨x.1.1, x.1.2, by simp⟩, inv_fun := λ x, ⟨(x.1, x.2.1), x.2.2⟩, left_inv := λ ⟨⟨x, y⟩, h⟩, rfl, right_inv := λ ⟨x, y, h⟩, rfl } /-- The subtypes corresponding to equal sets are equivalent. -/ @[simps apply] def set_congr {α : Type*} {s t : set α} (h : s = t) : s ≃ t := subtype_equiv_prop h /-- A set is equivalent to its image under an equivalence. -/ -- We could construct this using `equiv.set.image e s e.injective`, -- but this definition provides an explicit inverse. @[simps] def image {α β : Type*} (e : α ≃ β) (s : set α) : s ≃ e '' s := { to_fun := λ x, ⟨e x.1, by simp⟩, inv_fun := λ y, ⟨e.symm y.1, by { rcases y with ⟨-, ⟨a, ⟨m, rfl⟩⟩⟩, simpa using m, }⟩, left_inv := λ x, by simp, right_inv := λ y, by simp, }. namespace set /-- `univ α` is equivalent to `α`. -/ @[simps apply symm_apply] protected def univ (α) : @univ α ≃ α := ⟨coe, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩ /-- An empty set is equivalent to the `empty` type. -/ protected def empty (α) : (∅ : set α) ≃ empty := equiv_empty _ /-- An empty set is equivalent to a `pempty` type. -/ protected def pempty (α) : (∅ : set α) ≃ pempty := equiv_pempty _ /-- If sets `s` and `t` are separated by a decidable predicate, then `s ∪ t` is equivalent to `s ⊕ t`. -/ protected def union' {α} {s t : set α} (p : α → Prop) [decidable_pred p] (hs : ∀ x ∈ s, p x) (ht : ∀ x ∈ t, ¬ p x) : (s ∪ t : set α) ≃ s ⊕ t := { to_fun := λ x, if hp : p x then sum.inl ⟨_, x.2.resolve_right (λ xt, ht _ xt hp)⟩ else sum.inr ⟨_, x.2.resolve_left (λ xs, hp (hs _ xs))⟩, inv_fun := λ o, match o with | (sum.inl x) := ⟨x, or.inl x.2⟩ | (sum.inr x) := ⟨x, or.inr x.2⟩ end, left_inv := λ ⟨x, h'⟩, by by_cases p x; simp [union'._match_1, h]; congr, right_inv := λ o, begin rcases o with ⟨x, h⟩ | ⟨x, h⟩; dsimp [union'._match_1]; [simp [hs _ h], simp [ht _ h]] end } /-- If sets `s` and `t` are disjoint, then `s ∪ t` is equivalent to `s ⊕ t`. -/ protected def union {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) : (s ∪ t : set α) ≃ s ⊕ t := set.union' (λ x, x ∈ s) (λ _, id) (λ x xt xs, H ⟨xs, xt⟩) lemma union_apply_left {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ s) : equiv.set.union H a = sum.inl ⟨a, ha⟩ := dif_pos ha lemma union_apply_right {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ t) : equiv.set.union H a = sum.inr ⟨a, ha⟩ := dif_neg $ λ h, H ⟨h, ha⟩ @[simp] lemma union_symm_apply_left {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) (a : s) : (equiv.set.union H).symm (sum.inl a) = ⟨a, subset_union_left _ _ a.2⟩ := rfl @[simp] lemma union_symm_apply_right {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) (a : t) : (equiv.set.union H).symm (sum.inr a) = ⟨a, subset_union_right _ _ a.2⟩ := rfl /-- A singleton set is equivalent to a `punit` type. -/ protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} := ⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩, λ ⟨x, h⟩, by { simp at h, subst x }, λ ⟨⟩, rfl⟩ /-- Equal sets are equivalent. TODO: this is the same as `equiv.set_congr`! -/ @[simps apply symm_apply] protected def of_eq {α : Type u} {s t : set α} (h : s = t) : s ≃ t := equiv.set_congr h /-- If `a ∉ s`, then `insert a s` is equivalent to `s ⊕ punit`. -/ protected def insert {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) : (insert a s : set α) ≃ s ⊕ punit.{u+1} := calc (insert a s : set α) ≃ ↥(s ∪ {a}) : equiv.set.of_eq (by simp) ... ≃ s ⊕ ({a} : set α) : equiv.set.union (λ x ⟨hx, hx'⟩, by simp [*] at *) ... ≃ s ⊕ punit.{u+1} : sum_congr (equiv.refl _) (equiv.set.singleton _) @[simp] lemma insert_symm_apply_inl {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) (b : s) : (equiv.set.insert H).symm (sum.inl b) = ⟨b, or.inr b.2⟩ := rfl @[simp] lemma insert_symm_apply_inr {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) (b : punit.{u+1}) : (equiv.set.insert H).symm (sum.inr b) = ⟨a, or.inl rfl⟩ := rfl @[simp] lemma insert_apply_left {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) : equiv.set.insert H ⟨a, or.inl rfl⟩ = sum.inr punit.star := (equiv.set.insert H).apply_eq_iff_eq_symm_apply.2 rfl @[simp] lemma insert_apply_right {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) (b : s) : equiv.set.insert H ⟨b, or.inr b.2⟩ = sum.inl b := (equiv.set.insert H).apply_eq_iff_eq_symm_apply.2 rfl /-- If `s : set α` is a set with decidable membership, then `s ⊕ sᶜ` is equivalent to `α`. -/ protected def sum_compl {α} (s : set α) [decidable_pred (∈ s)] : s ⊕ (sᶜ : set α) ≃ α := calc s ⊕ (sᶜ : set α) ≃ ↥(s ∪ sᶜ) : (equiv.set.union (by simp [set.ext_iff])).symm ... ≃ @univ α : equiv.set.of_eq (by simp) ... ≃ α : equiv.set.univ _ @[simp] lemma sum_compl_apply_inl {α : Type u} (s : set α) [decidable_pred (∈ s)] (x : s) : equiv.set.sum_compl s (sum.inl x) = x := rfl @[simp] lemma sum_compl_apply_inr {α : Type u} (s : set α) [decidable_pred (∈ s)] (x : sᶜ) : equiv.set.sum_compl s (sum.inr x) = x := rfl lemma sum_compl_symm_apply_of_mem {α : Type u} {s : set α} [decidable_pred (∈ s)] {x : α} (hx : x ∈ s) : (equiv.set.sum_compl s).symm x = sum.inl ⟨x, hx⟩ := have ↑(⟨x, or.inl hx⟩ : (s ∪ sᶜ : set α)) ∈ s, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_left _ this } lemma sum_compl_symm_apply_of_not_mem {α : Type u} {s : set α} [decidable_pred (∈ s)] {x : α} (hx : x ∉ s) : (equiv.set.sum_compl s).symm x = sum.inr ⟨x, hx⟩ := have ↑(⟨x, or.inr hx⟩ : (s ∪ sᶜ : set α)) ∈ sᶜ, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_right _ this } @[simp] lemma sum_compl_symm_apply {α : Type*} {s : set α} [decidable_pred (∈ s)] {x : s} : (equiv.set.sum_compl s).symm x = sum.inl x := by cases x with x hx; exact set.sum_compl_symm_apply_of_mem hx @[simp] lemma sum_compl_symm_apply_compl {α : Type*} {s : set α} [decidable_pred (∈ s)] {x : sᶜ} : (equiv.set.sum_compl s).symm x = sum.inr x := by cases x with x hx; exact set.sum_compl_symm_apply_of_not_mem hx /-- `sum_diff_subset s t` is the natural equivalence between `s ⊕ (t \ s)` and `t`, where `s` and `t` are two sets. -/ protected def sum_diff_subset {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] : s ⊕ (t \ s : set α) ≃ t := calc s ⊕ (t \ s : set α) ≃ (s ∪ (t \ s) : set α) : (equiv.set.union (by simp [inter_diff_self])).symm ... ≃ t : equiv.set.of_eq (by { simp [union_diff_self, union_eq_self_of_subset_left h] }) @[simp] lemma sum_diff_subset_apply_inl {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] (x : s) : equiv.set.sum_diff_subset h (sum.inl x) = inclusion h x := rfl @[simp] lemma sum_diff_subset_apply_inr {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] (x : t \ s) : equiv.set.sum_diff_subset h (sum.inr x) = inclusion (diff_subset t s) x := rfl lemma sum_diff_subset_symm_apply_of_mem {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] {x : t} (hx : x.1 ∈ s) : (equiv.set.sum_diff_subset h).symm x = sum.inl ⟨x, hx⟩ := begin apply (equiv.set.sum_diff_subset h).injective, simp only [apply_symm_apply, sum_diff_subset_apply_inl], exact subtype.eq rfl, end lemma sum_diff_subset_symm_apply_of_not_mem {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] {x : t} (hx : x.1 ∉ s) : (equiv.set.sum_diff_subset h).symm x = sum.inr ⟨x, ⟨x.2, hx⟩⟩ := begin apply (equiv.set.sum_diff_subset h).injective, simp only [apply_symm_apply, sum_diff_subset_apply_inr], exact subtype.eq rfl, end /-- If `s` is a set with decidable membership, then the sum of `s ∪ t` and `s ∩ t` is equivalent to `s ⊕ t`. -/ protected def union_sum_inter {α : Type u} (s t : set α) [decidable_pred (∈ s)] : (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ s ⊕ t := calc (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ (s ∪ t \ s : set α) ⊕ (s ∩ t : set α) : by rw [union_diff_self] ... ≃ (s ⊕ (t \ s : set α)) ⊕ (s ∩ t : set α) : sum_congr (set.union $ subset_empty_iff.2 (inter_diff_self _ _)) (equiv.refl _) ... ≃ s ⊕ (t \ s : set α) ⊕ (s ∩ t : set α) : sum_assoc _ _ _ ... ≃ s ⊕ (t \ s ∪ s ∩ t : set α) : sum_congr (equiv.refl _) begin refine (set.union' (∉ s) _ _).symm, exacts [λ x hx, hx.2, λ x hx, not_not_intro hx.1] end ... ≃ s ⊕ t : by { rw (_ : t \ s ∪ s ∩ t = t), rw [union_comm, inter_comm, inter_union_diff] } /-- Given an equivalence `e₀` between sets `s : set α` and `t : set β`, the set of equivalences `e : α ≃ β` such that `e ↑x = ↑(e₀ x)` for each `x : s` is equivalent to the set of equivalences between `sᶜ` and `tᶜ`. -/ protected def compl {α : Type u} {β : Type v} {s : set α} {t : set β} [decidable_pred (∈ s)] [decidable_pred (∈ t)] (e₀ : s ≃ t) : {e : α ≃ β // ∀ x : s, e x = e₀ x} ≃ ((sᶜ : set α) ≃ (tᶜ : set β)) := { to_fun := λ e, subtype_equiv e (λ a, not_congr $ iff.symm $ maps_to.mem_iff (maps_to_iff_exists_map_subtype.2 ⟨e₀, e.2⟩) (surj_on.maps_to_compl (surj_on_iff_exists_map_subtype.2 ⟨t, e₀, subset.refl t, e₀.surjective, e.2⟩) e.1.injective)), inv_fun := λ e₁, subtype.mk (calc α ≃ s ⊕ (sᶜ : set α) : (set.sum_compl s).symm ... ≃ t ⊕ (tᶜ : set β) : e₀.sum_congr e₁ ... ≃ β : set.sum_compl t) (λ x, by simp only [sum.map_inl, trans_apply, sum_congr_apply, set.sum_compl_apply_inl, set.sum_compl_symm_apply]), left_inv := λ e, begin ext x, by_cases hx : x ∈ s, { simp only [set.sum_compl_symm_apply_of_mem hx, ←e.prop ⟨x, hx⟩, sum.map_inl, sum_congr_apply, trans_apply, subtype.coe_mk, set.sum_compl_apply_inl] }, { simp only [set.sum_compl_symm_apply_of_not_mem hx, sum.map_inr, subtype_equiv_apply, set.sum_compl_apply_inr, trans_apply, sum_congr_apply, subtype.coe_mk] }, end, right_inv := λ e, equiv.ext $ λ x, by simp only [sum.map_inr, subtype_equiv_apply, set.sum_compl_apply_inr, function.comp_app, sum_congr_apply, equiv.coe_trans, subtype.coe_eta, subtype.coe_mk, set.sum_compl_symm_apply_compl] } /-- The set product of two sets is equivalent to the type product of their coercions to types. -/ protected def prod {α β} (s : set α) (t : set β) : ↥(s ×ˢ t) ≃ s × t := @subtype_prod_equiv_prod α β s t /-- If a function `f` is injective on a set `s`, then `s` is equivalent to `f '' s`. -/ protected noncomputable def image_of_inj_on {α β} (f : α → β) (s : set α) (H : inj_on f s) : s ≃ (f '' s) := ⟨λ p, ⟨f p, mem_image_of_mem f p.2⟩, λ p, ⟨classical.some p.2, (classical.some_spec p.2).1⟩, λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).1 h (classical.some_spec (mem_image_of_mem f h)).2), λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩ /-- If `f` is an injective function, then `s` is equivalent to `f '' s`. -/ @[simps apply] protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) := equiv.set.image_of_inj_on f s (H.inj_on s) @[simp] protected lemma image_symm_apply {α β} (f : α → β) (s : set α) (H : injective f) (x : α) (h : x ∈ s) : (set.image f s H).symm ⟨f x, ⟨x, ⟨h, rfl⟩⟩⟩ = ⟨x, h⟩ := begin apply (set.image f s H).injective, simp [(set.image f s H).apply_symm_apply], end lemma image_symm_preimage {α β} {f : α → β} (hf : injective f) (u s : set α) : (λ x, (set.image f s hf).symm x : f '' s → α) ⁻¹' u = coe ⁻¹' (f '' u) := begin ext ⟨b, a, has, rfl⟩, have : ∀(h : ∃a', a' ∈ s ∧ a' = a), classical.some h = a := λ h, (classical.some_spec h).2, simp [equiv.set.image, equiv.set.image_of_inj_on, hf.eq_iff, this], end /-- If `α` is equivalent to `β`, then `set α` is equivalent to `set β`. -/ @[simps] protected def congr {α β : Type*} (e : α ≃ β) : set α ≃ set β := ⟨λ s, e '' s, λ t, e.symm '' t, symm_image_image e, symm_image_image e.symm⟩ /-- The set `{x ∈ s | t x}` is equivalent to the set of `x : s` such that `t x`. -/ protected def sep {α : Type u} (s : set α) (t : α → Prop) : ({ x ∈ s | t x } : set α) ≃ { x : s | t x } := (equiv.subtype_subtype_equiv_subtype_inter s t).symm /-- The set `𝒫 S := {x | x ⊆ S}` is equivalent to the type `set S`. -/ protected def powerset {α} (S : set α) : 𝒫 S ≃ set S := { to_fun := λ x : 𝒫 S, coe ⁻¹' (x : set α), inv_fun := λ x : set S, ⟨coe '' x, by rintro _ ⟨a : S, _, rfl⟩; exact a.2⟩, left_inv := λ x, by ext y; exact ⟨λ ⟨⟨_, _⟩, h, rfl⟩, h, λ h, ⟨⟨_, x.2 h⟩, h, rfl⟩⟩, right_inv := λ x, by ext; simp } /-- If `s` is a set in `range f`, then its image under `range_splitting f` is in bijection (via `f`) with `s`. -/ @[simps] noncomputable def range_splitting_image_equiv {α β : Type*} (f : α → β) (s : set (range f)) : range_splitting f '' s ≃ s := { to_fun := λ x, ⟨⟨f x, by simp⟩, (by { rcases x with ⟨x, ⟨y, ⟨m, rfl⟩⟩⟩, simpa [apply_range_splitting f] using m, })⟩, inv_fun := λ x, ⟨range_splitting f x, ⟨x, ⟨x.2, rfl⟩⟩⟩, left_inv := λ x, by { rcases x with ⟨x, ⟨y, ⟨m, rfl⟩⟩⟩, simp [apply_range_splitting f] }, right_inv := λ x, by simp [apply_range_splitting f], } end set /-- If `f : α → β` has a left-inverse when `α` is nonempty, then `α` is computably equivalent to the range of `f`. While awkward, the `nonempty α` hypothesis on `f_inv` and `hf` allows this to be used when `α` is empty too. This hypothesis is absent on analogous definitions on stronger `equiv`s like `linear_equiv.of_left_inverse` and `ring_equiv.of_left_inverse` as their typeclass assumptions are already sufficient to ensure non-emptiness. -/ @[simps] def of_left_inverse {α β : Sort*} (f : α → β) (f_inv : nonempty α → β → α) (hf : Π h : nonempty α, left_inverse (f_inv h) f) : α ≃ range f := { to_fun := λ a, ⟨f a, a, rfl⟩, inv_fun := λ b, f_inv (nonempty_of_exists b.2) b, left_inv := λ a, hf ⟨a⟩ a, right_inv := λ ⟨b, a, ha⟩, subtype.eq $ show f (f_inv ⟨a⟩ b) = b, from eq.trans (congr_arg f $ by exact ha ▸ (hf _ a)) ha } /-- If `f : α → β` has a left-inverse, then `α` is computably equivalent to the range of `f`. Note that if `α` is empty, no such `f_inv` exists and so this definition can't be used, unlike the stronger but less convenient `of_left_inverse`. -/ abbreviation of_left_inverse' {α β : Sort*} (f : α → β) (f_inv : β → α) (hf : left_inverse f_inv f) : α ≃ range f := of_left_inverse f (λ _, f_inv) (λ _, hf) /-- If `f : α → β` is an injective function, then domain `α` is equivalent to the range of `f`. -/ @[simps apply] noncomputable def of_injective {α β} (f : α → β) (hf : injective f) : α ≃ range f := equiv.of_left_inverse f (λ h, by exactI function.inv_fun f) (λ h, by exactI function.left_inverse_inv_fun hf) theorem apply_of_injective_symm {α β} {f : α → β} (hf : injective f) (b : range f) : f ((of_injective f hf).symm b) = b := subtype.ext_iff.1 $ (of_injective f hf).apply_symm_apply b @[simp] theorem of_injective_symm_apply {α β} {f : α → β} (hf : injective f) (a : α) : (of_injective f hf).symm ⟨f a, ⟨a, rfl⟩⟩ = a := begin apply (of_injective f hf).injective, simp [apply_of_injective_symm hf], end lemma coe_of_injective_symm {α β} {f : α → β} (hf : injective f) : ((of_injective f hf).symm : range f → α) = range_splitting f := by { ext ⟨y, x, rfl⟩, apply hf, simp [apply_range_splitting f] } @[simp] lemma self_comp_of_injective_symm {α β} {f : α → β} (hf : injective f) : f ∘ ((of_injective f hf).symm) = coe := funext (λ x, apply_of_injective_symm hf x) lemma of_left_inverse_eq_of_injective {α β : Type*} (f : α → β) (f_inv : nonempty α → β → α) (hf : Π h : nonempty α, left_inverse (f_inv h) f) : of_left_inverse f f_inv hf = of_injective f ((em (nonempty α)).elim (λ h, (hf h).injective) (λ h _ _ _, by { haveI : subsingleton α := subsingleton_of_not_nonempty h, simp })) := by { ext, simp } lemma of_left_inverse'_eq_of_injective {α β : Type*} (f : α → β) (f_inv : β → α) (hf : left_inverse f_inv f) : of_left_inverse' f f_inv hf = of_injective f hf.injective := by { ext, simp } protected lemma set_forall_iff {α β} (e : α ≃ β) {p : set α → Prop} : (∀ a, p a) ↔ (∀ a, p (e ⁻¹' a)) := e.injective.preimage_surjective.forall lemma preimage_pi_equiv_pi_subtype_prod_symm_pi {α : Type*} {β : α → Type*} (p : α → Prop) [decidable_pred p] (s : Π i, set (β i)) : (pi_equiv_pi_subtype_prod p β).symm ⁻¹' pi univ s = (pi univ (λ i : {i // p i}, s i)) ×ˢ (pi univ (λ i : {i // ¬p i}, s i)) := begin ext ⟨f, g⟩, simp only [mem_preimage, mem_univ_pi, prod_mk_mem_set_prod_eq, subtype.forall, ← forall_and_distrib], refine forall_congr (λ i, _), dsimp only [subtype.coe_mk], by_cases hi : p i; simp [hi] end /-- `sigma_fiber_equiv f` for `f : α → β` is the natural equivalence between the type of all preimages of points under `f` and the total space `α`. -/ -- See also `equiv.sigma_fiber_equiv`. @[simps] def sigma_preimage_equiv {α β} (f : α → β) : (Σ b, f ⁻¹' {b}) ≃ α := sigma_fiber_equiv f /-- A family of equivalences between preimages of points gives an equivalence between domains. -/ -- See also `equiv.of_fiber_equiv`. @[simps] def of_preimage_equiv {α β γ} {f : α → γ} {g : β → γ} (e : Π c, (f ⁻¹' {c}) ≃ (g ⁻¹' {c})) : α ≃ β := equiv.of_fiber_equiv e lemma of_preimage_equiv_map {α β γ} {f : α → γ} {g : β → γ} (e : Π c, (f ⁻¹' {c}) ≃ (g ⁻¹' {c})) (a : α) : g (of_preimage_equiv e a) = f a := equiv.of_fiber_equiv_map e a end equiv /-- If a function is a bijection between two sets `s` and `t`, then it induces an equivalence between the types `↥s` and `↥t`. -/ noncomputable def set.bij_on.equiv {α : Type*} {β : Type*} {s : set α} {t : set β} (f : α → β) (h : bij_on f s t) : s ≃ t := equiv.of_bijective _ h.bijective /-- The composition of an updated function with an equiv on a subset can be expressed as an updated function. -/ lemma dite_comp_equiv_update {α : Type*} {β : Sort*} {γ : Sort*} {s : set α} (e : β ≃ s) (v : β → γ) (w : α → γ) (j : β) (x : γ) [decidable_eq β] [decidable_eq α] [∀ j, decidable (j ∈ s)] : (λ (i : α), if h : i ∈ s then (function.update v j x) (e.symm ⟨i, h⟩) else w i) = function.update (λ (i : α), if h : i ∈ s then v (e.symm ⟨i, h⟩) else w i) (e j) x := begin ext i, by_cases h : i ∈ s, { rw [dif_pos h, function.update_apply_equiv_apply, equiv.symm_symm, function.comp, function.update_apply, function.update_apply, dif_pos h], have h_coe : (⟨i, h⟩ : s) = e j ↔ i = e j := subtype.ext_iff.trans (by rw subtype.coe_mk), simp_rw h_coe }, { have : i ≠ e j, by { contrapose! h, have : (e j : α) ∈ s := (e j).2, rwa ← h at this }, simp [h, this] } end
= Zhou Tong ( archer ) =
module Text.WebIDL.Lexer import Data.List import Data.String import Text.Lexer import Text.WebIDL.Types %default total -- alias for `some` plus : Lexer -> Lexer plus = some -- alias for `some` star : Lexer -> Recognise False star = many -- /[1-9]/ nonZeroDigit : Lexer nonZeroDigit = pred $ \c => '1' <= c && c <= '9' -------------------------------------------------------------------------------- -- Numbers -------------------------------------------------------------------------------- parseInt : String -> IdlToken parseInt s = maybe (Invalid s) ILit $ readInt s parseFloat : String -> IdlToken parseFloat s = maybe (Invalid s) FLit $ readFloat s -- /0[Xx][0-9A-Fa-f]+/ hex : Lexer hex = (exact "0x" <|> exact "0X") <+> plus hexDigit -- /0[0-7]*/ oct : Lexer oct = is '0' <+> star octDigit -- any integer literal int : Lexer int = hex <|> oct <|> (opt (is '-') <+> plus digit) -- /[Ee][+-]?[0-9]+/ exp : Lexer exp = oneOf "Ee" <+> opt (oneOf "+-") <+> plus digit -- /([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([Ee][+-]?[0-9]+)?/ expOpt : Lexer expOpt = let pre = (plus digit <+> is '.' <+> star digit) <|> (star digit <+> is '.' <+> plus digit) in pre <+> opt exp -- [0-9]+[Ee][+-]?[0-9]+ expNonOpt : Lexer expNonOpt = plus digit <+> exp float : Lexer float = (opt (is '-') <+> (expOpt <|> expNonOpt)) -------------------------------------------------------------------------------- -- Others -------------------------------------------------------------------------------- -- [_-]?[A-Za-z][0-9A-Z_a-z-]* identifier : Lexer identifier = opt (oneOf "_-") <+> alpha <+> star (pred $ \c => isAlphaNum c || c == '_' || c == '-') -- Takes a valid identifier and converts it either -- to a FloatLit, a Keyword, or an Identifier ident : String -> IdlToken ident "Infinity" = FLit Infinity ident "-Infinity" = FLit NegativeInfinity ident "NaN" = FLit NaN ident s = maybe (Ident $ MkIdent s) Key (refine s) -- /\/\/.*/ comment : Lexer comment = lineComment (exact "//" ) <|> surround (exact "/*" ) (exact "*/") any -- /[^\t\n\r 0-9A-Za-z]/ other : Lexer other = pred $ \c => not (isAlpha c || isDigit c || isSpace c || isControl c) symbol : String -> IdlToken symbol "..." = Other Ellipsis symbol s = case fastUnpack s of [c] => Other (Symb c) _ => Invalid s -------------------------------------------------------------------------------- -- Lexing -------------------------------------------------------------------------------- tokenMap : TokenMap IdlToken tokenMap = [ (spaces, const Space) , (stringLit, SLit . MkStrLit) , (comment, Comment) , (identifier, ident) , (float, parseFloat) , (int, parseInt) , (exact "..." <|> other, symbol) ] isNoise : IdlToken -> Bool isNoise Space = True isNoise (Comment _) = True isNoise _ = False ||| Generates a list of IdlTokens (wrapped in TokenData, so ||| they come with line and position numbers) from an input ||| string. export lexIdl : String -> Either String $ List (WithBounds IdlToken) lexIdl s = case lex tokenMap s of (ts, (_,_,"")) => Right ts (_, t) => Left $ "Lexer aborted at " ++ show t ||| Generates a list of IdlTokens ||| from an input string, removing unnecessary tokens by ||| means of `isNoise`. export lexIdlNoNoise : String -> Either String $ List (WithBounds IdlToken) lexIdlNoNoise = map (filter (not . isNoise . val)) . lexIdl
open import Prelude open import Nat open import dynamics-core open import contexts module lemmas-gcomplete where -- if you add a complete type to a complete context, the result is also a -- complete context gcomp-extend : ∀{Γ τ x} → Γ gcomplete → τ tcomplete → x # Γ → (Γ ,, (x , τ)) gcomplete gcomp-extend {Γ} {τ} {x} gc tc apart x_query τ_query x₁ with natEQ x x_query gcomp-extend {Γ} {τ} {x} gc tc apart .x τ_query x₂ | Inl refl = tr (λ qq → qq tcomplete) (someinj x₂) tc gcomp-extend {Γ} {τ} {x} gc tc apart x_query τ_query x₂ | Inr x₁ = gc x_query τ_query x₂
``` # default_exp block_diagrams ``` ``` #hide %load_ext autoreload %autoreload 2 ``` ``` #export import numpy as np import matplotlib.pyplot as plt ``` ``` #hide %matplotlib inline ``` # Block diagrams This notebook will talk about: - Basic components of block diagrams - How to compose block diagrams together - Block diagrams and system properties (e.g., Stability, etc) ------------------ ## Block Diagrams - One of the control system engineer’s favorite tools for organizing, communicating, simulating and solving problems - Standard representation of interconnected systems and subsystems using Transfer Functions - Makes it easier to identify inputs, outputs and dynamic systems - Block diagrams show us the interrelationship of systems and how signals flow between them. - variables or signals: arrows ($\rightarrow$) - systems: blocks with a transfer function, and arrows going in (inputs) and out (outputs) - summation node: circle with arrows going in (with the appropriate signs) and an arrow going out - branching points: represents two or more variables are replicas of the variable before the branching point - Always useful during the analysis. For example: <tr> <td> </td> </tr> ## Block Diagram Albegra - Block diagrams can be quite complex, and when that happens it is useful to know how to calculate the transfer function between a specific input and a specific output. - For this, it is better to start with some easy cases: **Cascaded, Parallel and Feedback Loop.** - More complex cases are handled recursively applying these rules. Note that, given that we are restricting the analysis to linear systems, the impact of each input on a specific output is independent of other inputs that can be present (they can all be set to 0). ### Cascaded Blocks <table style='margin: 0 auto' rules=none> <tr> <td> </td> </tr> </table> This can be easily calculated using algebric manipulation: $$Y(s)=G_2(s)U(s)$$ $$U(s)=G_1(s)E(s)$$ which means: $$Y(s)=G_2(s)G_1(s)E(s) \Rightarrow G(s) = G_1(s)G_2(s)$$ ### Parallel <table style='margin: 0 auto' rules=none> <tr> <td> </td> </tr> </table> This can be easily calculated using algebric manipulation: $$Y(s)=G_1(s)R(s) + G_2(s)R(s) + G_3(s)R(s) = (G_1(s) + G_2(s) + G_3(s))R(s)$$ which means: $$ G(s) = G_1(s) + G_2(s) + G_3(s)$$ Note the presence of: - _take off points_: allow an unaltered signal to go along multiple paths. - _summing junctions_: sum or subtract signals ### Feedback Loop <table style='margin: 0 auto' rules=none> <tr> <td> </td> </tr> </table> So, how do we do this one? $$Y(s)=G_1(s)*E(s)$$ $$E(s)=R(s)-Y_m(s)$$ $$Y_m(s)=G_2(s)Y(s)$$ or $$Y(s)=G_1(s)*(R(s)-Y_m(s)) \rightarrow Y(s)=G_1(s)*(R(s)-G_2(s)Y(s)) $$ and finally: $$Y(s)+G_1(s)G_2(s)Y(s) = G_1(s)*R(s) $$ $$ G(s) = \frac{G_1(s)}{1 + G_1(s)G_2(s)} $$ ## Zero-Pole Cancellations - When we compose systems together we expect the order of the system being equal to the sum of the order of each individual system. - However, when we compose systems together and calculate the transfer function it might happen that the resulting function has less poles. - In this case, we have cancellations that correspond to "hidden" parts of the system. Let's consider an example: <table style='margin: 0 auto' rules=none> <tr> <td> </td> </tr> </table> where \begin{equation} G_1(s)=\frac{s+1}{s+2}\;\; \text{and}\;\; G_2(s)=\frac{1}{s} \end{equation} We reduce the feedback loop first: $$G_3(s)=\frac{1/s}{1+1/s} = \frac{1/s}{\frac{s+1}{s}} = \frac{1}{s+1}$$ Then the serie: $$G(s) = \frac{s+1}{s+2} \frac{1}{s+1} = \frac{1}{s+2} $$ This connection between two systems determined an "hidden" part, which is not visible in the input/output relationship and the system behaves like a first-order one. ### Observability and Controllobality of Interconnected Systems - Controllability measures the ability of a particular actuator configuration to control all the states of the system; - Observability measures the ability of the particular sensor configuration to supply all the information necessary to estimate all the states of the system. #### Cascaded Blocks <table style='margin: 0 auto' rules=none> <tr> <td> </td> </tr> </table> $$G(s) = G_1(s)G_2(s) = \frac{N_1(s)}{D_1(s)}\frac{N_2(s)}{D_2(s)}$$ - If $N_1(s)$ and $D_2(s)$ have roots in common, then $G(s)$ is not controllable (zero-pole cancellation) - If $N_2(s)$ and $D_1(s)$ have roots in common, then $G(s)$ is not observable (pole-zero cancellation) #### Parallel Blocks <table style='margin: 0 auto' rules=none> <tr> <td> </td> </tr> </table> $$G(s) = G_1(s) + G_2(s) = \frac{N_1(s)}{D_1(s)} + \frac{N_2(s)}{D_2(s)} = \frac{N_1(s)D_2(s) + N_2(s)D_1(s)}{D_1(s)D_2(s)}$$ - Cancellations can happen only when $D_1(s)$ and $D_2(s)$ have common roots (you can bring them out together in the numerator and then cancel them out with those in the denumerator). When this happens, we have a **non-observable and non-controllable** part of the system. #### Feedback Loop <table style='margin: 0 auto' rules=none> <tr> <td> </td> </tr> </table> $$G(s) = \frac{G_1(s)}{1 + G_1(s)G_2(s)} =\frac{\frac{N_1(s)}{D_1(s)}}{1 + \frac{N_1(s)}{D_1(s)}\frac{N_2(s)}{D_2(s)}} = \frac{N_1(s)D_2(s)}{D_1(s)D_2(s) + N_1(s)N_2(s)}$$ - We have the equivalent of a serie interconnection: $G_1(s)G_2(s)$, same rules apply - Cancellations occur when $N_1(s)$ and $D_2(s)$ have common factors (you can bring them out together in the numerator and then cancel them out with those in the denumerator): - When zero of $G_1(s)$ cancels a pole of $G_2(s)$ then we have a **non-observable and non-controllable** part of the system. - When pole of $G_1(s)$ cancels a zero of $G_2(s)$ then we still have a **fully observable and fully controllable** system. This is because the denominator of $G(s)$ does not lose its degree. Example: - zero of $G_1(s)$ cancels a pole of $G_2(s)$ $$G_1(s)=\frac{s+1}{s+2},\;\; G_2(s)=\frac{s+3}{s+1}$$ $$\Rightarrow G(s)= \frac{\frac{s+1}{s+2}}{1+\frac{s+3}{s+2}} = \frac{s+3}{1+(s+3)}$$ - pole of $G_1(s)$ cancels a zero of $G_2(s)$ $$G_1(s)=\frac{s+1}{s+2},\;\; G_2(s)=\frac{s+2}{s+3}$$ $$\Rightarrow G(s)= \frac{\frac{s+1}{s+2}}{1+\frac{s+1}{s+3}} = \frac{\frac{(s+1)(s+3)}{s+2}}{(s+3)+(s+1)} = \frac{(s+1)(s+3)}{(s+2)((s+3)+(s+1))}$$ ### Stability of Interconnected Systems Let's now analyse the stability of a system which is obtained through a composition of subsystems. Question: - Is the asymptotic stability of each indidual subsystem necessary/sufficient to guarantee the stability of the entire system? Assumption: - Each subsystem are represented by rational functions with numerator and denominator prime between them. #### Cascaded Blocks <table style='margin: 0 auto' rules=none> <tr> <td> </td> </tr> </table> $$G(s) = G_1(s)G_2(s) = \frac{N_1(s)}{D_1(s)}\frac{N_2(s)}{D_2(s)}$$ **No zero-pole cancellations** - The denominator of $G(s)$ is the product of each denominator, and the poles of $G(s)$ are the union of the poles of each subsystem. - If and only if, the poles of $G_1(s)$ and $G_2(s)$ have Re $<0$, then $G(s)$ is asymptotically stable. **Zero-pole/pole-zero cancellations** - In this case, the overall system has an hidden part corresponding to the zero-pole or pole-zero cancellation. In this case, _if the cancellation is of a pole with Re $\ge0$ then the hidden part is not stable and the entire system is not stable_. - We call these types of cancellations, **critical**. - Note that this is not visible directly from the transfer function! #### Parallel Blocks <table style='margin: 0 auto' rules=none> <tr> <td> </td> </tr> </table> $$G(s) = G_1(s) + G_2(s) = \frac{N_1(s)}{D_1(s)} + \frac{N_2(s)}{D_2(s)} = \frac{N_1(s)D_2(s) + N_2(s)D_1(s)}{D_1(s)D_2(s)}$$ The analysis is similar to the previous case (serie). If there are no cancellations, the poles of $G(s)$ are the product of the poles of $G_1(s)$ and of $G_2(s)$. - $G(s)$ is asymptotically stable, if and only if, the poles of $G_1(s)$ and $G_2(s)$ have Re $<0$. If there are cancellations, then the overall system has an hidden part corresponding to the zero-pole or pole-zero cancellation. If the cancellation is of a pole with Re $>=0$ then the hidden part is not stable and the entire system is not stable. Again, this is not visible analysing the final T.F. #### Feedback Loop <table style='margin: 0 auto' rules=none> <tr> <td> </td> </tr> </table> $$G(s) = \frac{G_1(s)}{1 + G_1(s)G_2(s)} =\frac{\frac{N_1(s)}{D_1(s)}}{1 + \frac{N_1(s)}{D_1(s)}\frac{N_2(s)}{D_2(s)}} = \frac{N_1(s)D_2(s)}{D_1(s)D_2(s) + N_1(s)N_2(s)}$$ - In this case, the poles of the entire system are not only dependednt on the poles of the two subsytems (the numerators are also playing a role). If we do not have cancellations, then the poles of the systems are the roots of the equation: $$D_1(s)D_2(s) + N_1(s)N_2(s) = 0$$ _this is called characteristic equation of the feedback system._ We can also write the equation above as: $$ 1 + \frac{N_1(s)D_2(s)}{D_1(s)D_2(s)} = 0$$ The feedback system is asymptotically stable if and only if the roots of the previous equation are with Re $<0$, but this does not depend on the stability property of the individual systems. **Critical cancellations** - Note that when we calculate $\frac{N_1(s)D_2(s)}{D_1(s)D_2(s)}$ we can have _critical cancellations_ and these would correspond to hidden parts of the system (Note that we are assuming to use $y$ or $y_m$ as output variables of the system). - As before, if these critical cancellations are of poles with Re $\ge0$, these hidden parts are not asymptotically stable and neither is the full system. - This is not visible from the analysis of the T.F. - We have to verify if there are _critical_ cancellations before we analyse the stability of the feedback system. Since the poles of the feedback system are, in general, different from the poles of the individual subsystems, we can use this connection to effectively modify the dynamics of the system, placing the poles where we need them. For example, it is possible to stabilise a non-stable system, or obtain desired performance. Note that the opposite is also true: we can have a non-stable system even if we the individual subsystems are stable. ## Equivalent block diagrams <table style='margin: 0 auto' rules=none> <tr> <td> </td> </tr> </table> ## BIBO Stability - A system is BIBO stable (Bounded Input, Bounded Output) if for each limited input, there is a limited output - For linear systems: BIBO stability if and only if poles of the transfer functions have Re $<0$ - **Caution! The poles of the T.F. are only those that are controllable and observable!** - BIBO stability only depends on the forced response of the system. # Example: Car driving uphill <table style='margin: 0 auto' rules=none> <tr> <td> </td> </tr> </table> We can model a car moving uphill using a linear model (small angle approximation) as: \begin{equation} A=\frac{df}{dx}= \begin{bmatrix} 0 & 1\\ 0 & -\frac{\beta}{m} \end{bmatrix} \end{equation} \begin{equation} B=\frac{df}{du}= \begin{bmatrix} 0 & 0\\ \frac{\gamma}{m} & -g \end{bmatrix} \end{equation} and $$\dot{\mathbf{x}}=A\mathbf{x}+B\mathbf{u}$$ $$y=[0 \; 1]\mathbf{x}$$ Note that: - If $\theta = 0$ and $u=0$ (no slope, and no input) - then the equilibrium is $\forall x_1$, $x_2=0$ (the position does not matter, speed is 0). - this system has two inputs: the pedal and gravity We can calculate the Matrix Transfer Function as: $$G(s)=C(sI-A)^{-1}Bu$$ \begin{equation} (sI-A) = \begin{bmatrix} s & -1\\ 0 & s+\frac{\beta}{m} \end{bmatrix} \end{equation} \begin{equation} (sI-A)^{-1} = \frac{1}{s(s+ \frac{\beta}{m})} \begin{bmatrix} s+ \frac{\beta}{m} & 1\\ 0 & s \end{bmatrix} \end{equation} \begin{equation} G(s) = \frac{1}{s(s+ \frac{\beta}{m})} \begin{bmatrix} s \frac{\gamma}{m} & -sg \end{bmatrix} = \begin{bmatrix} \frac{\frac{\gamma}{m}}{s+\frac{\beta}{m}} & \frac{-g}{s+\frac{\beta}{m}} \end{bmatrix} \end{equation} If we want to know the T.F. from the pedal to the velocity: $$G(s)=\frac{\frac{\gamma}{m}}{s+\frac{\beta}{m}}$$ What happens when we apply a step onto the pedal? Let's study the transfer function and include the input: $$Y(s) = G(s)U(s)=\frac{\frac{\gamma}{m}}{s+\frac{\beta}{m}} \frac{1}{s} = \frac{\alpha_1}{s+\frac{\beta}{m}} \frac{\alpha_2}{s}$$ where $$\alpha_1=-\frac{\gamma}{\beta}, \; \alpha_2=\frac{\gamma}{\beta}$$ and the inverse transform is: $$ y(t) = \alpha_1 e^{-\frac{\beta}{m}t} + \alpha_2 1(t)$$ We can implement this in Python: Let's define the step function first ``` from classical_control_theory.intro_to_control_theory import step # def step(t, step_time=0): # """Heaviside step function""" # return 1 * (t >= step_time) ``` And now we can plot the response of the system $y(t)$ to the step input: ``` # We decide the parameters of the car m = 1 beta = 1 gamma = 1 # We set the simulation parameters t = np.linspace(0, 15) # Now we can calculate the output of the system alpha_1 = -gamma/beta alpha_2 = gamma/beta y = alpha_1*np.exp(-beta/m*t) + alpha_2*step(t) ``` And we can plot it: ``` plt.plot(t, y, linewidth=4) plt.xlabel('time (s)') plt.ylabel('speed (m/s)') plt.grid() ``` Essentially we predict that the car will increase its speed to try and match our step input. But what does the actual car do? We implemented a car already in notebook `02_Intro_to_control_theory`, but here it is again for convenience: ``` class Car: _g = 9.8 # Gravity def __init__(self, x0, params): self._x_1 = x0[0] # position (along the road) self._x_2 = x0[1] # velocity (along the road) self._m, self._alpha, self._beta, self._gamma = params def step(self, dt, u, theta): self.theta = theta self._x_1 = self._x_1 + dt*self._x_2 self._x_2 = self._x_2 + dt*(-self._alpha/self._m*abs(self._x_2)*self._x_2 - \ self._beta/self._m*self._x_2 + self._gamma/self._m*u - \ Car._g*np.sin(theta)) def speedometer(self): v = self._x_2 return (v,) # Utility function to simplify plotting def sensor_i(self): # Rotation matrix to get back to the main frame. R = np.array(((np.cos(theta), -np.sin(theta)), (np.sin(theta), np.cos(theta)))) x_i, y_i = R.dot(np.array([[self._x_1],[0]])) v = self._x_2 return (x_i, y_i, v) ``` We can now run it: ``` # We define the parameters of the car m = 1 alpha = 1 beta = 1 gamma = 1 params = (m, alpha, beta, gamma) # Let's define its initial conditions x_0 = (0,0) # position and speed theta = np.radians(0) # no slope # Define the input: step function u = 1 # input (e.g. 0 or 1) # Create the car car = Car(x_0, params) # run it! t0, tf, dt = 0, 10, 0.1 #rotation to get back to the inertial frame.. c, s = np.cos(theta), np.sin(theta) R = np.array(((c, -s), (s, c))) position = [] velocity = [] time = [] for t in np.arange(t0, tf, dt): car.step(dt, u, theta) v = car.speedometer() # this is in the along road frame velocity.append(v) time.append(t) ``` ``` plt.plot(np.arange(t0, tf, dt), velocity, linewidth=3) plt.xlabel('time (s)') plt.ylabel('speed (m/s)') plt.grid() ``` Hmm, the speed has a step response but it does not go to 1... The reason is that the actual car does behave differently from our linear model. Let's try another car: ``` #export class SimplerCar: _g = 9.8 def __init__(self, x0, params): self._x_1 = x0[0] # position (along the road) self._x_2 = x0[1] # velocity self._m, self._alpha, self._beta, self._gamma = params def step(self, dt, u, theta): self.theta = theta self._x_1 = self._x_1 + dt*self._x_2 self._x_2 = self._x_2 + dt*(- self._beta/self._m*self._x_2 + \ self._gamma/self._m*u - Car._g*np.sin(theta)) def speedometer(self): v = self._x_2 return (v,) ``` And now we can run it again, ``` # We define the parameters of the car m = 1 alpha = 1 beta = 1 gamma = 1 params = (m, alpha, beta, gamma) # Let's define its initial conditions x_0 = (0,0) # position and speed theta = np.radians(0) # no slope # Define the input: step function u = 1 # input (e.g. 0 or 1) # Create the car car = SimplerCar(x_0, params) # run it! t0, tf, dt = 0, 10, 0.1 #rotation to get back to the inertial frame.. c, s = np.cos(theta), np.sin(theta) R = np.array(((c, -s), (s, c))) position = [] velocity = [] time = [] for t in np.arange(t0, tf, dt): car.step(dt, u, theta) v = car.speedometer() # this is in the along road frame velocity.append(v) time.append(t) ``` ``` plt.plot(time, velocity, linewidth=3) plt.xlabel('time (s)') plt.ylabel('speed (m/s)') plt.grid() ``` Alright! Our linear model represents this second car better. ------------------------------------ ## Simplifying block diagrams Let's now apply the block diagram algebra to some examples: ### Example 1: Let's suppose that we have a classic negative feedback: <table style='margin: 0 auto' rules=none> <tr> <td> </td> </tr> </table> $B$ and $C$ are in parallel and we can combine them into a single block: <table style='margin: 0 auto' rules=none> <tr> <td> </td> </tr> </table> We can now reduce the feedback loop: <table style='margin: 0 auto' rules=none> <tr> <td> </td> </tr> </table> And lastly we can combine the two blocks in series: <table style='margin: 0 auto' rules=none> <tr> <td> </td> </tr> </table> ### Creating Unity Feedback - Sometimes when we manipulate block diagrams we do not want to remove blocks to simplify the diagram, but we would like to restructure the diagram to have it in a specific form. - For example we would like to make the following equivalent: <table style='margin: 0 auto' rules=none> <tr> <td> </td> <td> </td> </tr> </table> - We need to determine an $R(s)$ value that makes the two systems equivalent. - We need to write the transfer function for each system, set the two equations equal to each other, and then solving for $R(s)$. $$ \frac{G(s)}{1+G(s)H(s)} = \frac{R(s)}{1+R(s)} $$ $$ \Downarrow $$ $$ \frac{G(s) (1+R(s))}{1+G(s)H(s)} = R(s) $$ $$ \Downarrow $$ $$ \frac{G(s)}{1+G(s)H(s)} = R(s) \bigg( 1- \frac{G(s)}{1+G(s)H(s)} \bigg) $$ $$ \Downarrow $$ $$ R(s) = \frac{G(s)}{1+G(s)H(s)-G(s)} $$ Note that we would not be able to easily use this method to go from a unity feedback system to a non-unity feedback system (there will be two unknown variables). ------------------------
(* Title: The pi-calculus Author/Maintainer: Jesper Bengtson (jebe.dk), 2012 *) theory Weak_Late_Cong_Pres imports Weak_Late_Cong Weak_Late_Step_Sim_Pres Weak_Late_Bisim_Pres begin lemma tauPres: fixes P :: pi and Q :: pi assumes "P \<simeq> Q" shows "\<tau>.(P) \<simeq> \<tau>.(Q)" using assms by(blast intro: unfoldI Weak_Late_Step_Sim_Pres.tauPres dest: congruenceWeakBisim symetric) lemma outputPres: fixes P :: pi and Q :: pi assumes "P \<simeq> Q" shows "a{b}.P \<simeq> a{b}.Q" using assms by(blast intro: unfoldI Weak_Late_Step_Sim_Pres.outputPres dest: congruenceWeakBisim symetric) lemma inputPres: fixes P :: pi and Q :: pi and a :: name and x :: name assumes PSimQ: "\<forall>y. P[x::=y] \<simeq> Q[x::=y]" shows "a<x>.P \<simeq> a<x>.Q" using assms apply(rule_tac unfoldI) apply(rule_tac Weak_Late_Step_Sim_Pres.inputPres, auto intro: congruenceWeakBisim) by(rule_tac Weak_Late_Step_Sim_Pres.inputPres, auto intro: congruenceWeakBisim Weak_Late_Bisim.symmetric) assumes "P \<simeq> Q" shows "[a\<frown>b]P \<simeq> [a\<frown>b]Q" using assms by(blast intro: unfoldI Weak_Late_Step_Sim_Pres.matchPres dest: unfoldE symetric) lemma mismatchPres: fixes P :: pi and Q :: pi and a :: name and b :: name assumes "P \<simeq> Q" shows "[a\<noteq>b]P \<simeq> [a\<noteq>b]Q" using assms by(blast intro: unfoldI Weak_Late_Step_Sim_Pres.mismatchPres dest: unfoldE symetric) lemma sumPres: fixes P :: pi and Q :: pi and R :: pi assumes "P \<simeq> Q" shows "P \<oplus> R \<simeq> Q \<oplus> R" using assms by(blast intro: Weak_Late_Bisim.reflexive unfoldI Weak_Late_Step_Sim_Pres.sumPres dest: unfoldE symetric) lemma parPres: fixes P :: pi and Q :: pi and R :: pi assumes "P \<simeq> Q" shows "P \<parallel> R \<simeq> Q \<parallel> R" proof - have "\<And>P Q R. \<lbrakk>P \<leadsto><weakBisim> Q; P \<approx> Q\<rbrakk> \<Longrightarrow> P \<parallel> R \<leadsto><weakBisim> Q \<parallel> R" proof - fix P Q R assume "P \<leadsto><weakBisim> Q" and "P \<approx> Q" thus "P \<parallel> R \<leadsto><weakBisim> Q \<parallel> R" using Weak_Late_Bisim_Pres.parPres Weak_Late_Bisim_Pres.resPres Weak_Late_Bisim.reflexive Weak_Late_Bisim.eqvt by(blast intro: Weak_Late_Step_Sim_Pres.parPres) qed with assms show ?thesis by(blast intro: unfoldI dest: congruenceWeakBisim unfoldE symetric) qed assumes PeqQ: "P \<simeq> Q" shows "<\<nu>x>P \<simeq> <\<nu>x>Q" proof - have "\<And>P Q x. P \<leadsto><weakBisim> Q \<Longrightarrow> <\<nu>x>P \<leadsto><weakBisim> <\<nu>x>Q" proof - fix P Q x assume "P \<leadsto><weakBisim> Q" with Weak_Late_Bisim.eqvt Weak_Late_Bisim_Pres.resPres show "<\<nu>x>P \<leadsto><weakBisim> <\<nu>x>Q" by(blast intro: Weak_Late_Step_Sim_Pres.resPres) qed with assms show ?thesis by(blast intro: unfoldI dest: congruenceWeakBisim unfoldE symetric) qed lemma congruenceBang: fixes P :: pi and Q :: pi assumes "P \<simeq> Q" shows "!P \<simeq> !Q" proof - have "\<And>P Q. \<lbrakk>P \<leadsto><weakBisim> Q; P \<simeq> Q\<rbrakk> \<Longrightarrow> !P \<leadsto><weakBisim> !Q" proof - fix P Q assume "P \<leadsto><weakBisim> Q" and "P \<simeq> Q" hence "!P \<leadsto><bangRel weakBisim> !Q" using unfoldE(1) congruenceWeakBisim Weak_Late_Bisim.eqvt by(rule Weak_Late_Step_Sim_Pres.bangPres) moreover have "bangRel weakBisim \<subseteq> weakBisim" proof auto fix a b assume "(a, b) \<in> bangRel weakBisim" thus "a \<approx> b" apply(induct rule: bangRel.induct) apply (metis Weak_Late_Bisim_Pres.bangPres) apply (metis Weak_Late_Bisim.reflexive Weak_Late_Bisim.symmetric Weak_Late_Bisim.transitive Weak_Late_Bisim_Pres.parPres Weak_Late_Bisim_SC.parSym) by (metis Weak_Late_Bisim_Pres.resPres) qed ultimately show"!P \<leadsto><weakBisim> !Q" by(rule Weak_Late_Step_Sim.monotonic) qed with assms show ?thesis by(blast intro: unfoldI dest: unfoldE symetric congruenceWeakBisim) qed end
import data.real.basic section variables a b : ℝ example (h : a < b) : ¬ b < a := begin intro h', have : a < a, from lt_trans h h', apply lt_irrefl a this, end def fn_ub (f : ℝ → ℝ) (a : ℝ) : Prop := ∀ x, f x ≤ a def fn_lb (f : ℝ → ℝ) (a : ℝ) : Prop := ∀ x, a ≤ f x def fn_has_ub (f : ℝ → ℝ) := ∃ a, fn_ub f a def fn_has_lb (f : ℝ → ℝ) := ∃ a, fn_lb f a variable f : ℝ → ℝ example (h : ∀ a, ∃ x, f x > a) : ¬ fn_has_ub f := begin intro fnub, cases fnub with a fnuba, cases h a with x hx, have : f x ≤ a, from fnuba x, linarith, end example (h : ∀ a, ∃ x, f x < a) : ¬ fn_has_lb f := begin rintro ⟨a, fnlba⟩, cases h a with x hx, have : f x ≥ a, from fnlba x, linarith, end example : ¬ fn_has_ub (λ x, x) := begin rintro ⟨a, fuba⟩, have : a + 1 ≤ a, from fuba (a + 1), linarith, end #check (not_le_of_gt : a > b → ¬ a ≤ b) #check (not_lt_of_ge : a ≥ b → ¬ a < b) #check (lt_of_not_ge : ¬ a ≥ b → a < b) #check (le_of_not_gt : ¬ a > b → a ≤ b) #print monotone #print le_of_not_gt example (h : monotone f) (h' : f a < f b) : a < b := begin apply lt_of_not_ge, intro h'', apply absurd h', apply not_lt_of_ge (h h''), end example (h : a ≤ b) (h' : f b < f a) : ¬ monotone f := begin intro hm, apply absurd h', apply not_lt_of_ge, apply hm h, end example : ¬ ∀ {f : ℝ → ℝ}, monotone f → ∀ {a b}, f a ≤ f b → a ≤ b := begin intro h, let f := λ x : ℝ, (0 : ℝ), have monof : monotone f, { intros a b aleb, linarith,}, have h' : f 1 ≤ f 0, from le_refl _, have : (1 : ℝ) ≤ 0, from h monof h', linarith, end example (x : ℝ) (h : ∀ ε > 0, x < ε) : x ≤ 0 := begin apply le_of_not_gt, intro xle, have : x < x, from h x xle, linarith, end end section variables {α : Type*} (P : α → Prop) (Q : Prop) example (h : ¬ ∃ x, P x) : ∀ x, ¬ P x := begin intros x px, have : ∃ x, P x := ⟨x, px⟩, from h this, end example (h : ∀ x, ¬ P x) : ¬ ∃ x, P x := begin rintro ⟨x, px⟩, from h x px, end open_locale classical example (h : ¬ ∀ x, P x) : ∃ x, ¬ P x := begin by_contradiction hn, apply h, intro x, show P x, by_contradiction hnn, from hn ⟨x, hnn⟩, end example (h : ∃ x, ¬ P x) : ¬ ∀ x, P x := begin cases h with x npx, by_contradiction hn, from npx (hn x), end example (h : ¬ ¬ Q) : Q := begin by_contra hn, from h hn, end example (h : Q) : ¬ ¬ Q := begin intro hn, from hn h, end end section open_locale classical variable (f : ℝ → ℝ) example (h : ¬ fn_has_ub f) : ∀ a, ∃ x, f x > a := begin intro a, by_contra hn, apply h, use a, intro x, apply le_of_not_gt, intro fxgta, apply hn, use x, from fxgta, end example (h : ¬ ∀ a, ∃ x, f x > a) : fn_has_ub f := begin push_neg at h, exact h end example (h : ¬ fn_has_ub f) : ∀ a, ∃ x, f x > a := begin simp only [fn_has_ub, fn_ub] at h, push_neg at h, exact h end example (h : ¬ monotone f) : ∃ x y, x ≤ y ∧ f y < f x := begin simp only [monotone] at h, push_neg at h, exact h, end example (h : ¬ fn_has_ub f) : ∀ a, ∃ x, f x > a := begin contrapose! h, exact h end example (x : ℝ) (h : ∀ ε > 0, x ≤ ε) : x ≤ 0 := begin contrapose! h, use x / 2, split; linarith end end variables (a : ℝ) example (h : 0 < 0) : a > 37 := begin exfalso, apply lt_irrefl 0 h end example (h : 0 < 0) : a > 37 := absurd h (lt_irrefl 0) example (h : 0 < 0) : a > 37 := begin have h' : ¬ 0 < 0, from lt_irrefl 0, contradiction end
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import algebra.big_operators.order import data.nat.basic /-! # Equitable functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines equitable functions. A function `f` is equitable on a set `s` if `f a₁ ≤ f a₂ + 1` for all `a₁, a₂ ∈ s`. This is mostly useful when the codomain of `f` is `ℕ` or `ℤ` (or more generally a successor order). ## TODO `ℕ` can be replaced by any `succ_order` + `conditionally_complete_monoid`, but we don't have the latter yet. -/ open_locale big_operators variables {α β : Type*} namespace set /-- A set is equitable if no element value is more than one bigger than another. -/ def equitable_on [has_le β] [has_add β] [has_one β] (s : set α) (f : α → β) : Prop := ∀ ⦃a₁ a₂⦄, a₁ ∈ s → a₂ ∈ s → f a₁ ≤ f a₂ + 1 @[simp] lemma equitable_on_empty [has_le β] [has_add β] [has_one β] (f : α → β) : equitable_on ∅ f := λ a _ ha, (set.not_mem_empty _ ha).elim lemma equitable_on_iff_exists_le_le_add_one {s : set α} {f : α → ℕ} : s.equitable_on f ↔ ∃ b, ∀ a ∈ s, b ≤ f a ∧ f a ≤ b + 1 := begin refine ⟨_, λ ⟨b, hb⟩ x y hx hy, (hb x hx).2.trans (add_le_add_right (hb y hy).1 _)⟩, obtain rfl | ⟨x, hx⟩ := s.eq_empty_or_nonempty, { simp }, intros hs, by_cases h : ∀ y ∈ s, f x ≤ f y, { exact ⟨f x, λ y hy, ⟨h _ hy, hs hy hx⟩⟩ }, push_neg at h, obtain ⟨w, hw, hwx⟩ := h, refine ⟨f w, λ y hy, ⟨nat.le_of_succ_le_succ _, hs hy hw⟩⟩, rw (nat.succ_le_of_lt hwx).antisymm (hs hx hw), exact hs hx hy, end lemma equitable_on_iff_exists_image_subset_Icc {s : set α} {f : α → ℕ} : s.equitable_on f ↔ ∃ b, f '' s ⊆ Icc b (b + 1) := by simpa only [image_subset_iff] using equitable_on_iff_exists_le_le_add_one lemma equitable_on_iff_exists_eq_eq_add_one {s : set α} {f : α → ℕ} : s.equitable_on f ↔ ∃ b, ∀ a ∈ s, f a = b ∨ f a = b + 1 := by simp_rw [equitable_on_iff_exists_le_le_add_one, nat.le_and_le_add_one_iff] section ordered_semiring variables [ordered_semiring β] lemma subsingleton.equitable_on {s : set α} (hs : s.subsingleton) (f : α → β) : s.equitable_on f := λ i j hi hj, by { rw hs hi hj, exact le_add_of_nonneg_right zero_le_one } lemma equitable_on_singleton (a : α) (f : α → β) : set.equitable_on {a} f := set.subsingleton_singleton.equitable_on f end ordered_semiring end set open set namespace finset variables {s : finset α} {f : α → ℕ} {a : α} lemma equitable_on.le (h : equitable_on (s : set α) f) (ha : a ∈ s) : (∑ i in s, f i) / s.card ≤ f a := (equitable_on_iff_le_le_add_one.1 h a ha).1 lemma equitable_on.le_add_one (h : equitable_on (s : set α) f) (ha : a ∈ s) : f a ≤ (∑ i in s, f i) / s.card + 1 := (equitable_on_iff_le_le_add_one.1 h a ha).2 lemma equitable_on_iff : equitable_on (s : set α) f ↔ ∀ a ∈ s, f a = (∑ i in s, f i) / s.card ∨ f a = (∑ i in s, f i) / s.card + 1 := by simp_rw [equitable_on_iff_le_le_add_one, nat.le_and_le_add_one_iff] end finset
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import field_theory.minpoly.field import field_theory.subfield import field_theory.tower /-! # Intermediate fields Let `L / K` be a field extension, given as an instance `algebra K L`. This file defines the type of fields in between `K` and `L`, `intermediate_field K L`. An `intermediate_field K L` is a subfield of `L` which contains (the image of) `K`, i.e. it is a `subfield L` and a `subalgebra K L`. ## Main definitions * `intermediate_field K L` : the type of intermediate fields between `K` and `L`. * `subalgebra.to_intermediate_field`: turns a subalgebra closed under `⁻¹` into an intermediate field * `subfield.to_intermediate_field`: turns a subfield containing the image of `K` into an intermediate field * `intermediate_field.map`: map an intermediate field along an `alg_hom` * `intermediate_field.restrict_scalars`: restrict the scalars of an intermediate field to a smaller field in a tower of fields. ## Implementation notes Intermediate fields are defined with a structure extending `subfield` and `subalgebra`. A `subalgebra` is closed under all operations except `⁻¹`, ## Tags intermediate field, field extension -/ open finite_dimensional polynomial open_locale big_operators polynomial variables (K L L' : Type*) [field K] [field L] [field L'] [algebra K L] [algebra K L'] /-- `S : intermediate_field K L` is a subset of `L` such that there is a field tower `L / S / K`. -/ structure intermediate_field extends subalgebra K L := (neg_mem' : ∀ x ∈ carrier, -x ∈ carrier) (inv_mem' : ∀ x ∈ carrier, x⁻¹ ∈ carrier) /-- Reinterpret an `intermediate_field` as a `subalgebra`. -/ add_decl_doc intermediate_field.to_subalgebra variables {K L L'} (S : intermediate_field K L) namespace intermediate_field /-- Reinterpret an `intermediate_field` as a `subfield`. -/ def to_subfield : subfield L := { ..S.to_subalgebra, ..S } instance : set_like (intermediate_field K L) L := ⟨λ S, S.to_subalgebra.carrier, by { rintros ⟨⟨⟩⟩ ⟨⟨⟩⟩ ⟨h⟩, congr, }⟩ instance : subfield_class (intermediate_field K L) L := { add_mem := λ s _ _, s.add_mem', zero_mem := λ s, s.zero_mem', neg_mem := neg_mem', mul_mem := λ s _ _, s.mul_mem', one_mem := λ s, s.one_mem', inv_mem := inv_mem' } @[simp] lemma mem_carrier {s : intermediate_field K L} {x : L} : x ∈ s.carrier ↔ x ∈ s := iff.rfl /-- Two intermediate fields are equal if they have the same elements. -/ @[ext] theorem ext {S T : intermediate_field K L} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h @[simp] lemma coe_to_subalgebra : (S.to_subalgebra : set L) = S := rfl @[simp] lemma coe_to_subfield : (S.to_subfield : set L) = S := rfl @[simp] lemma mem_mk (s : set L) (hK : ∀ x, algebra_map K L x ∈ s) (ho hm hz ha hn hi) (x : L) : x ∈ intermediate_field.mk (subalgebra.mk s ho hm hz ha hK) hn hi ↔ x ∈ s := iff.rfl @[simp] lemma mem_to_subalgebra (s : intermediate_field K L) (x : L) : x ∈ s.to_subalgebra ↔ x ∈ s := iff.rfl @[simp] lemma mem_to_subfield (s : intermediate_field K L) (x : L) : x ∈ s.to_subfield ↔ x ∈ s := iff.rfl /-- Copy of an intermediate field with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (S : intermediate_field K L) (s : set L) (hs : s = ↑S) : intermediate_field K L := { to_subalgebra := S.to_subalgebra.copy s (hs : s = (S.to_subalgebra).carrier), neg_mem' := have hs' : (S.to_subalgebra.copy s hs).carrier = (S.to_subalgebra).carrier := hs, hs'.symm ▸ S.neg_mem', inv_mem' := have hs' : (S.to_subalgebra.copy s hs).carrier = (S.to_subalgebra).carrier := hs, hs'.symm ▸ S.inv_mem' } @[simp] lemma coe_copy (S : intermediate_field K L) (s : set L) (hs : s = ↑S) : (S.copy s hs : set L) = s := rfl lemma copy_eq (S : intermediate_field K L) (s : set L) (hs : s = ↑S) : S.copy s hs = S := set_like.coe_injective hs section inherited_lemmas /-! ### Lemmas inherited from more general structures The declarations in this section derive from the fact that an `intermediate_field` is also a subalgebra or subfield. Their use should be replaceable with the corresponding lemma from a subobject class. -/ /-- An intermediate field contains the image of the smaller field. -/ theorem algebra_map_mem (x : K) : algebra_map K L x ∈ S := S.algebra_map_mem' x /-- An intermediate field is closed under scalar multiplication. -/ /-- An intermediate field contains the ring's 1. -/ protected theorem one_mem : (1 : L) ∈ S := one_mem S /-- An intermediate field contains the ring's 0. -/ protected theorem zero_mem : (0 : L) ∈ S := zero_mem S /-- An intermediate field is closed under multiplication. -/ protected theorem mul_mem {x y : L} : x ∈ S → y ∈ S → x * y ∈ S := mul_mem /-- An intermediate field is closed under addition. -/ protected theorem add_mem {x y : L} : x ∈ S → y ∈ S → x + y ∈ S := add_mem /-- An intermediate field is closed under subtraction -/ protected theorem sub_mem {x y : L} : x ∈ S → y ∈ S → x - y ∈ S := sub_mem /-- An intermediate field is closed under negation. -/ protected theorem neg_mem {x : L} : x ∈ S → -x ∈ S := neg_mem /-- An intermediate field is closed under inverses. -/ protected theorem inv_mem {x : L} : x ∈ S → x⁻¹ ∈ S := inv_mem /-- An intermediate field is closed under division. -/ protected theorem div_mem {x y : L} : x ∈ S → y ∈ S → x / y ∈ S := div_mem /-- Product of a list of elements in an intermediate_field is in the intermediate_field. -/ protected lemma list_prod_mem {l : list L} : (∀ x ∈ l, x ∈ S) → l.prod ∈ S := list_prod_mem /-- Sum of a list of elements in an intermediate field is in the intermediate_field. -/ protected lemma list_sum_mem {l : list L} : (∀ x ∈ l, x ∈ S) → l.sum ∈ S := list_sum_mem /-- Product of a multiset of elements in an intermediate field is in the intermediate_field. -/ protected lemma multiset_prod_mem (m : multiset L) : (∀ a ∈ m, a ∈ S) → m.prod ∈ S := multiset_prod_mem m /-- Sum of a multiset of elements in a `intermediate_field` is in the `intermediate_field`. -/ protected lemma multiset_sum_mem (m : multiset L) : (∀ a ∈ m, a ∈ S) → m.sum ∈ S := multiset_sum_mem m /-- Product of elements of an intermediate field indexed by a `finset` is in the intermediate_field. -/ protected lemma prod_mem {ι : Type*} {t : finset ι} {f : ι → L} (h : ∀ c ∈ t, f c ∈ S) : ∏ i in t, f i ∈ S := prod_mem h /-- Sum of elements in a `intermediate_field` indexed by a `finset` is in the `intermediate_field`. -/ protected lemma sum_mem {ι : Type*} {t : finset ι} {f : ι → L} (h : ∀ c ∈ t, f c ∈ S) : ∑ i in t, f i ∈ S := sum_mem h protected lemma pow_mem {x : L} (hx : x ∈ S) (n : ℤ) : x^n ∈ S := zpow_mem hx n protected lemma zsmul_mem {x : L} (hx : x ∈ S) (n : ℤ) : n • x ∈ S := zsmul_mem hx n protected lemma coe_int_mem (n : ℤ) : (n : L) ∈ S := coe_int_mem S n protected lemma coe_add (x y : S) : (↑(x + y) : L) = ↑x + ↑y := rfl protected lemma coe_neg (x : S) : (↑(-x) : L) = -↑x := rfl protected lemma coe_mul (x y : S) : (↑(x * y) : L) = ↑x * ↑y := rfl protected lemma coe_inv (x : S) : (↑(x⁻¹) : L) = (↑x)⁻¹ := rfl protected lemma coe_zero : ((0 : S) : L) = 0 := rfl protected lemma coe_one : ((1 : S) : L) = 1 := rfl protected lemma coe_pow (x : S) (n : ℕ) : (↑(x ^ n) : L) = ↑x ^ n := submonoid_class.coe_pow x n end inherited_lemmas lemma coe_nat_mem (n : ℕ) : (n : L) ∈ S := by simpa using coe_int_mem S n end intermediate_field /-- Turn a subalgebra closed under inverses into an intermediate field -/ def subalgebra.to_intermediate_field (S : subalgebra K L) (inv_mem : ∀ x ∈ S, x⁻¹ ∈ S) : intermediate_field K L := { neg_mem' := λ x, S.neg_mem, inv_mem' := inv_mem, .. S } @[simp] lemma to_subalgebra_to_intermediate_field (S : subalgebra K L) (inv_mem : ∀ x ∈ S, x⁻¹ ∈ S) : (S.to_intermediate_field inv_mem).to_subalgebra = S := by { ext, refl } @[simp] lemma to_intermediate_field_to_subalgebra (S : intermediate_field K L) : S.to_subalgebra.to_intermediate_field (λ x, S.inv_mem) = S := by { ext, refl } /-- Turn a subalgebra satisfying `is_field` into an intermediate_field -/ def subalgebra.to_intermediate_field' (S : subalgebra K L) (hS : is_field S) : intermediate_field K L := S.to_intermediate_field $ λ x hx, begin by_cases hx0 : x = 0, { rw [hx0, inv_zero], exact S.zero_mem }, letI hS' := hS.to_field, obtain ⟨y, hy⟩ := hS.mul_inv_cancel (show (⟨x, hx⟩ : S) ≠ 0, from subtype.ne_of_val_ne hx0), rw [subtype.ext_iff, S.coe_mul, S.coe_one, subtype.coe_mk, mul_eq_one_iff_inv_eq₀ hx0] at hy, exact hy.symm ▸ y.2, end @[simp] lemma to_subalgebra_to_intermediate_field' (S : subalgebra K L) (hS : is_field S) : (S.to_intermediate_field' hS).to_subalgebra = S := by { ext, refl } @[simp] lemma to_intermediate_field'_to_subalgebra (S : intermediate_field K L) : S.to_subalgebra.to_intermediate_field' (field.to_is_field S) = S := by { ext, refl } /-- Turn a subfield of `L` containing the image of `K` into an intermediate field -/ def subfield.to_intermediate_field (S : subfield L) (algebra_map_mem : ∀ x, algebra_map K L x ∈ S) : intermediate_field K L := { algebra_map_mem' := algebra_map_mem, .. S } namespace intermediate_field /-- An intermediate field inherits a field structure -/ instance to_field : field S := S.to_subfield.to_field @[simp, norm_cast] lemma coe_sum {ι : Type*} [fintype ι] (f : ι → S) : (↑∑ i, f i : L) = ∑ i, (f i : L) := begin classical, induction finset.univ using finset.induction_on with i s hi H, { simp }, { rw [finset.sum_insert hi, add_mem_class.coe_add, H, finset.sum_insert hi] } end @[simp, norm_cast] lemma coe_prod {ι : Type*} [fintype ι] (f : ι → S) : (↑∏ i, f i : L) = ∏ i, (f i : L) := begin classical, induction finset.univ using finset.induction_on with i s hi H, { simp }, { rw [finset.prod_insert hi, mul_mem_class.coe_mul, H, finset.prod_insert hi] } end /-! `intermediate_field`s inherit structure from their `subalgebra` coercions. -/ instance module' {R} [semiring R] [has_smul R K] [module R L] [is_scalar_tower R K L] : module R S := S.to_subalgebra.module' instance module : module K S := S.to_subalgebra.module instance is_scalar_tower {R} [semiring R] [has_smul R K] [module R L] [is_scalar_tower R K L] : is_scalar_tower R K S := S.to_subalgebra.is_scalar_tower @[simp] lemma coe_smul {R} [semiring R] [has_smul R K] [module R L] [is_scalar_tower R K L] (r : R) (x : S) : ↑(r • x) = (r • x : L) := rfl instance algebra' {K'} [comm_semiring K'] [has_smul K' K] [algebra K' L] [is_scalar_tower K' K L] : algebra K' S := S.to_subalgebra.algebra' instance algebra : algebra K S := S.to_subalgebra.algebra instance to_algebra {R : Type*} [semiring R] [algebra L R] : algebra S R := S.to_subalgebra.to_algebra instance is_scalar_tower_bot {R : Type*} [semiring R] [algebra L R] : is_scalar_tower S L R := is_scalar_tower.subalgebra _ _ _ S.to_subalgebra instance is_scalar_tower_mid {R : Type*} [semiring R] [algebra L R] [algebra K R] [is_scalar_tower K L R] : is_scalar_tower K S R := is_scalar_tower.subalgebra' _ _ _ S.to_subalgebra /-- Specialize `is_scalar_tower_mid` to the common case where the top field is `L` -/ instance is_scalar_tower_mid' : is_scalar_tower K S L := S.is_scalar_tower_mid /-- If `f : L →+* L'` fixes `K`, `S.map f` is the intermediate field between `L'` and `K` such that `x ∈ S ↔ f x ∈ S.map f`. -/ def map (f : L →ₐ[K] L') (S : intermediate_field K L) : intermediate_field K L' := { inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, S.inv_mem hx, map_inv₀ f x⟩ }, neg_mem' := λ x hx, (S.to_subalgebra.map f).neg_mem hx, .. S.to_subalgebra.map f} @[simp] lemma coe_map (f : L →ₐ[K] L') : (S.map f : set L') = f '' S := rfl lemma map_map {K L₁ L₂ L₃ : Type*} [field K] [field L₁] [algebra K L₁] [field L₂] [algebra K L₂] [field L₃] [algebra K L₃] (E : intermediate_field K L₁) (f : L₁ →ₐ[K] L₂) (g : L₂ →ₐ[K] L₃) : (E.map f).map g = E.map (g.comp f) := set_like.coe_injective $ set.image_image _ _ _ /-- Given an equivalence `e : L ≃ₐ[K] L'` of `K`-field extensions and an intermediate field `E` of `L/K`, `intermediate_field_equiv_map e E` is the induced equivalence between `E` and `E.map e` -/ def intermediate_field_map (e : L ≃ₐ[K] L') (E : intermediate_field K L) : E ≃ₐ[K] (E.map e.to_alg_hom) := e.subalgebra_map E.to_subalgebra /- We manually add these two simp lemmas because `@[simps]` before `intermediate_field_map` led to a timeout. -/ @[simp] lemma intermediate_field_map_apply_coe (e : L ≃ₐ[K] L') (E : intermediate_field K L) (a : E) : ↑(intermediate_field_map e E a) = e a := rfl @[simp] lemma intermediate_field_map_symm_apply_coe (e : L ≃ₐ[K] L') (E : intermediate_field K L) (a : E.map e.to_alg_hom) : ↑((intermediate_field_map e E).symm a) = e.symm a := rfl end intermediate_field namespace alg_hom variables (f : L →ₐ[K] L') /-- The range of an algebra homomorphism, as an intermediate field. -/ @[simps to_subalgebra] def field_range : intermediate_field K L' := { .. f.range, .. (f : L →+* L').field_range } @[simp] lemma coe_field_range : ↑f.field_range = set.range f := rfl @[simp] lemma field_range_to_subfield : f.field_range.to_subfield = (f : L →+* L').field_range := rfl variables {f} @[simp] lemma mem_field_range {y : L'} : y ∈ f.field_range ↔ ∃ x, f x = y := iff.rfl end alg_hom namespace intermediate_field /-- The embedding from an intermediate field of `L / K` to `L`. -/ def val : S →ₐ[K] L := S.to_subalgebra.val @[simp] theorem coe_val : ⇑S.val = coe := rfl @[simp] lemma val_mk {x : L} (hx : x ∈ S) : S.val ⟨x, hx⟩ = x := rfl lemma range_val : S.val.range = S.to_subalgebra := S.to_subalgebra.range_val lemma aeval_coe {R : Type*} [comm_ring R] [algebra R K] [algebra R L] [is_scalar_tower R K L] (x : S) (P : R[X]) : aeval (x : L) P = aeval x P := begin refine polynomial.induction_on' P (λ f g hf hg, _) (λ n r, _), { rw [aeval_add, aeval_add, add_mem_class.coe_add, hf, hg] }, { simp only [mul_mem_class.coe_mul, aeval_monomial, submonoid_class.coe_pow, mul_eq_mul_right_iff], left, refl } end lemma coe_is_integral_iff {R : Type*} [comm_ring R] [algebra R K] [algebra R L] [is_scalar_tower R K L] {x : S} : is_integral R (x : L) ↔ is_integral R x := begin refine ⟨λ h, _, λ h, _⟩, { obtain ⟨P, hPmo, hProot⟩ := h, refine ⟨P, hPmo, (injective_iff_map_eq_zero _).1 (algebra_map ↥S L).injective _ _⟩, letI : is_scalar_tower R S L := is_scalar_tower.of_algebra_map_eq (congr_fun rfl), rwa [eval₂_eq_eval_map, ← eval₂_at_apply, eval₂_eq_eval_map, polynomial.map_map, ← is_scalar_tower.algebra_map_eq, ← eval₂_eq_eval_map] }, { obtain ⟨P, hPmo, hProot⟩ := h, refine ⟨P, hPmo, _⟩, rw [← aeval_def, aeval_coe, aeval_def, hProot, zero_mem_class.coe_zero] }, end /-- The map `E → F` when `E` is an intermediate field contained in the intermediate field `F`. This is the intermediate field version of `subalgebra.inclusion`. -/ def inclusion {E F : intermediate_field K L} (hEF : E ≤ F) : E →ₐ[K] F := subalgebra.inclusion hEF lemma inclusion_injective {E F : intermediate_field K L} (hEF : E ≤ F) : function.injective (inclusion hEF) := subalgebra.inclusion_injective hEF @[simp] lemma inclusion_self {E : intermediate_field K L}: inclusion (le_refl E) = alg_hom.id K E := subalgebra.inclusion_self @[simp] lemma inclusion_inclusion {E F G : intermediate_field K L} (hEF : E ≤ F) (hFG : F ≤ G) (x : E) : inclusion hFG (inclusion hEF x) = inclusion (le_trans hEF hFG) x := subalgebra.inclusion_inclusion hEF hFG x @[simp] lemma coe_inclusion {E F : intermediate_field K L} (hEF : E ≤ F) (e : E) : (inclusion hEF e : L) = e := rfl variables {S} lemma to_subalgebra_injective {S S' : intermediate_field K L} (h : S.to_subalgebra = S'.to_subalgebra) : S = S' := by { ext, rw [← mem_to_subalgebra, ← mem_to_subalgebra, h] } variables (S) lemma set_range_subset : set.range (algebra_map K L) ⊆ S := S.to_subalgebra.range_subset lemma field_range_le : (algebra_map K L).field_range ≤ S.to_subfield := λ x hx, S.to_subalgebra.range_subset (by rwa [set.mem_range, ← ring_hom.mem_field_range]) @[simp] lemma to_subalgebra_le_to_subalgebra {S S' : intermediate_field K L} : S.to_subalgebra ≤ S'.to_subalgebra ↔ S ≤ S' := iff.rfl @[simp] lemma to_subalgebra_lt_to_subalgebra {S S' : intermediate_field K L} : S.to_subalgebra < S'.to_subalgebra ↔ S < S' := iff.rfl variables {S} section tower /-- Lift an intermediate_field of an intermediate_field -/ def lift {F : intermediate_field K L} (E : intermediate_field K F) : intermediate_field K L := E.map (val F) instance has_lift {F : intermediate_field K L} : has_lift_t (intermediate_field K F) (intermediate_field K L) := ⟨lift⟩ section restrict_scalars variables (K) [algebra L' L] [is_scalar_tower K L' L] /-- Given a tower `L / ↥E / L' / K` of field extensions, where `E` is an `L'`-intermediate field of `L`, reinterpret `E` as a `K`-intermediate field of `L`. -/ def restrict_scalars (E : intermediate_field L' L) : intermediate_field K L := { carrier := E.carrier, ..E.to_subfield, ..E.to_subalgebra.restrict_scalars K } @[simp] lemma coe_restrict_scalars {E : intermediate_field L' L} : (restrict_scalars K E : set L) = (E : set L) := rfl @[simp] lemma restrict_scalars_to_subalgebra {E : intermediate_field L' L} : (E.restrict_scalars K).to_subalgebra = E.to_subalgebra.restrict_scalars K := set_like.coe_injective rfl @[simp] lemma restrict_scalars_to_subfield {E : intermediate_field L' L} : (E.restrict_scalars K).to_subfield = E.to_subfield := set_like.coe_injective rfl @[simp] lemma mem_restrict_scalars {E : intermediate_field L' L} {x : L} : x ∈ restrict_scalars K E ↔ x ∈ E := iff.rfl lemma restrict_scalars_injective : function.injective (restrict_scalars K : intermediate_field L' L → intermediate_field K L) := λ U V H, ext $ λ x, by rw [← mem_restrict_scalars K, H, mem_restrict_scalars] end restrict_scalars /-- This was formerly an instance called `lift2_alg`, but an instance above already provides it. -/ example {F : intermediate_field K L} {E : intermediate_field F L} : algebra K E := by apply_instance end tower section finite_dimensional variables (F E : intermediate_field K L) instance finite_dimensional_left [finite_dimensional K L] : finite_dimensional K F := left K F L instance finite_dimensional_right [finite_dimensional K L] : finite_dimensional F L := right K F L @[simp] lemma dim_eq_dim_subalgebra : module.rank K F.to_subalgebra = module.rank K F := rfl @[simp] lemma finrank_eq_finrank_subalgebra : finrank K F.to_subalgebra = finrank K F := rfl variables {F} {E} @[simp] lemma to_subalgebra_eq_iff : F.to_subalgebra = E.to_subalgebra ↔ F = E := by { rw [set_like.ext_iff, set_like.ext'_iff, set.ext_iff], refl } lemma eq_of_le_of_finrank_le [finite_dimensional K L] (h_le : F ≤ E) (h_finrank : finrank K E ≤ finrank K F) : F = E := to_subalgebra_injective $ subalgebra.to_submodule.injective $ eq_of_le_of_finrank_le h_le h_finrank lemma eq_of_le_of_finrank_eq [finite_dimensional K L] (h_le : F ≤ E) (h_finrank : finrank K F = finrank K E) : F = E := eq_of_le_of_finrank_le h_le h_finrank.ge lemma eq_of_le_of_finrank_le' [finite_dimensional K L] (h_le : F ≤ E) (h_finrank : finrank F L ≤ finrank E L) : F = E := begin apply eq_of_le_of_finrank_le h_le, have h1 := finrank_mul_finrank K F L, have h2 := finrank_mul_finrank K E L, have h3 : 0 < finrank E L := finrank_pos, nlinarith, end lemma eq_of_le_of_finrank_eq' [finite_dimensional K L] (h_le : F ≤ E) (h_finrank : finrank F L = finrank E L) : F = E := eq_of_le_of_finrank_le' h_le h_finrank.le end finite_dimensional lemma is_algebraic_iff {x : S} : is_algebraic K x ↔ is_algebraic K (x : L) := (is_algebraic_algebra_map_iff (algebra_map S L).injective).symm lemma is_integral_iff {x : S} : is_integral K x ↔ is_integral K (x : L) := by rw [←is_algebraic_iff_is_integral, is_algebraic_iff, is_algebraic_iff_is_integral] lemma minpoly_eq (x : S) : minpoly K x = minpoly K (x : L) := begin by_cases hx : is_integral K x, { exact minpoly.eq_of_algebra_map_eq (algebra_map S L).injective hx rfl }, { exact (minpoly.eq_zero hx).trans (minpoly.eq_zero (mt is_integral_iff.mpr hx)).symm }, end end intermediate_field /-- If `L/K` is algebraic, the `K`-subalgebras of `L` are all fields. -/ def subalgebra_equiv_intermediate_field (alg : algebra.is_algebraic K L) : subalgebra K L ≃o intermediate_field K L := { to_fun := λ S, S.to_intermediate_field (λ x hx, S.inv_mem_of_algebraic (alg (⟨x, hx⟩ : S))), inv_fun := λ S, S.to_subalgebra, left_inv := λ S, to_subalgebra_to_intermediate_field _ _, right_inv := to_intermediate_field_to_subalgebra, map_rel_iff' := λ S S', iff.rfl } @[simp] lemma mem_subalgebra_equiv_intermediate_field (alg : algebra.is_algebraic K L) {S : subalgebra K L} {x : L} : x ∈ subalgebra_equiv_intermediate_field alg S ↔ x ∈ S := iff.rfl @[simp] lemma mem_subalgebra_equiv_intermediate_field_symm (alg : algebra.is_algebraic K L) {S : intermediate_field K L} {x : L} : x ∈ (subalgebra_equiv_intermediate_field alg).symm S ↔ x ∈ S := iff.rfl
Formal statement is: lemma global_primitive: assumes "connected S" and holf: "f holomorphic_on S" and prev: "\<And>\<gamma> f. \<lbrakk>valid_path \<gamma>; path_image \<gamma> \<subseteq> S; pathfinish \<gamma> = pathstart \<gamma>; f holomorphic_on S\<rbrakk> \<Longrightarrow> (f has_contour_integral 0) \<gamma>" shows "\<exists>h. \<forall>z \<in> S. (h has_field_derivative f z) (at z)" Informal statement is: If $f$ is a holomorphic function on a connected set $S$ and if $\gamma$ is a closed path in $S$, then $\int_\gamma f(z) dz = 0$. Then there exists a holomorphic function $h$ on $S$ such that $f = h'$.
Formal statement is: lemma emeasure_mono: "a \<subseteq> b \<Longrightarrow> b \<in> sets M \<Longrightarrow> emeasure M a \<le> emeasure M b" Informal statement is: If $a \subseteq b$ and $b$ is measurable, then $\mu(a) \leq \mu(b)$.
{-# LANGUAGE StandaloneDeriving #-} module Examples.Quantum where import LAoP.Utils import LAoP.Matrix.Type import Data.Complex import Prelude hiding (id, (.)) deriving instance Ord a => Ord (Complex a) xor :: (Bool, Bool) -> Bool xor (False, b) = b xor (True, b) = not b ker :: Num e => Matrix e a b -> Matrix e a a ker m = tr m . m cnot :: Matrix (Complex Double) (Bool, Bool) (Bool, Bool) cnot = kr fstM (fromF xor) ccnot :: (Num e, Ord e) => Matrix e ((Bool, Bool), Bool) ((Bool, Bool), Bool) ccnot = kr fstM (fromF f) where f = xor . tp (uncurry (&&)) id tp f g (a,b) = (f a, g b) had :: Matrix (Complex Double) Bool Bool had = (1/sqrt 2) .| fromLists [[1, 1], [1, -1]] bell :: Matrix (Complex Double) (Bool, Bool) (Bool, Bool) bell = cnot . (had >< iden)
(** Datatypes used in the binary parser. **) (* (C) J. Pichon - see LICENSE.txt *) Require Import common. Require Export numerics datatypes. From mathcomp Require Import ssreflect ssrfun ssrnat ssrbool eqtype seq. Require Import Ascii. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Definition expr := list basic_instruction. Inductive labelidx : Type := | Mk_labelidx : nat -> labelidx. Inductive funcidx : Type := | Mk_funcidx : nat -> funcidx. Inductive typeidx : Type := | Mk_typeidx : nat -> typeidx. Inductive localidx : Type := | Mk_localidx : nat -> localidx. Inductive globalidx : Type := | Mk_globalidx : nat -> globalidx. Record limits := Mk_limits { lim_min : nat; lim_max : option nat; }. Inductive elem_type : Type := | elem_type_tt : elem_type (* TODO: am I interpreting the spec correctly? *). Record table_type : Type := Mk_table_type { tt_limits : limits; tt_elem_type : elem_type; }. Record mem_type : Type := Mk_mem_type { mem_type_lims : limits }. Inductive import_desc : Type := | ID_func : nat -> import_desc | ID_table : table_type -> import_desc | ID_mem : mem_type -> import_desc | ID_global : global_type -> import_desc. Definition name := list ascii. Record import : Type := Mk_import { imp_module : name; imp_name : name; imp_desc : import_desc; }. Record table := Mk_table { t_type : table_type }. Definition mem := limits. Record global2 : Type := { g_type : global_type; g_init : expr; }. Record start := { start_func : nat; }. Record element : Type := { elem_table : nat; elem_offset : expr; elem_init : list nat; }. Record func : Type := { fc_locals : list value_type; fc_expr : expr; }. Record data : Type := { dt_data : nat; dt_offset : expr; dt_init : list ascii; }. Inductive export_desc : Type := | ED_func : nat -> export_desc | ED_table : nat -> export_desc | ED_mem : nat -> export_desc | ED_global : nat -> export_desc. Record export : Type := { exp_name : name; exp_desc : export_desc; }. Inductive section : Type := | Sec_custom : list ascii -> section | Sec_type : list function_type -> section | Sec_import : list import -> section | Sec_function : list typeidx -> section | Sec_table : list table -> section | Sec_memory : list mem -> section | Sec_global : list global2 -> section | Sec_export : list export -> section | Sec_start : start -> section | Sec_element : list element -> section | Sec_code : list func -> section | Sec_data : list data -> section. Record func2 : Type := { fc2_type : typeidx; fc2_locals : list value_type; fc2_body : expr; }. Record module : Type := { mod_types : list function_type; mod_funcs : list func2; mod_tables : list table; mod_mems : list mem; mod_globals : list global2; mod_elements : list element; mod_data : list data; mod_start : option start; mod_imports : list import; mod_exports : list export; }.
module Algebra.Semiring %default total infixl 8 |+| infixl 9 |*| ||| A Semiring has two binary operations and an identity for each public export interface Semiring a where (|+|) : a -> a -> a plusNeutral : a (|*|) : a -> a -> a timesNeutral : a ||| Erased linearity corresponds to the neutral for |+| public export erased : Semiring a => a erased = plusNeutral ||| Purely linear corresponds to the neutral for |*| public export linear : Semiring a => a linear = timesNeutral ||| A semiring eliminator public export elimSemi : (Semiring a, Eq a) => (zero : b) -> (one : b) -> (a -> b) -> a -> b elimSemi zero one other r {a} = if r == Semiring.plusNeutral {a} then zero else if r == Semiring.timesNeutral {a} then one else other r export isErased : (Semiring a, Eq a) => a -> Bool isErased = elimSemi True False (const False) export isLinear : (Semiring a, Eq a) => a -> Bool isLinear = elimSemi False True (const False) export isRigOther : (Semiring a, Eq a) => a -> Bool isRigOther = elimSemi False False (const True) export branchZero : (Semiring a, Eq a) => Lazy b -> Lazy b -> a -> b branchZero yes no rig = if isErased rig then yes else no export branchOne : (Semiring a, Eq a) => Lazy b -> Lazy b -> a -> b branchOne yes no rig = if isLinear rig then yes else no export branchVal : (Semiring a, Eq a) => Lazy b -> Lazy b -> a -> b branchVal yes no rig = if isRigOther rig then yes else no
import Mathlib.Init.Data.Nat.Lemmas import Mathlib.Init.Data.Int.Basic import Mathlib.Tactic.Spread /-! # Typeclasses for monoids and groups etc -/ local macro "ofNat_class" Class:ident n:num : command => let field := Lean.mkIdent <| Class.getId.eraseMacroScopes.getString!.toLower `(class $Class:ident.{u} (α : Type u) where $field:ident : α instance {α} [$Class α] : OfNat α (nat_lit $n) where ofNat := ‹$Class α›.1 instance {α} [OfNat α (nat_lit $n)] : $Class α where $field:ident := $n) ofNat_class Zero 0 ofNat_class One 1 class Inv (α : Type u) where inv : α → α postfix:max "⁻¹" => Inv.inv /- ## The trick for adding a natural action onto monoids -/ section nat_action variable {M : Type u} -- see npow_rec comment for explanation about why not nsmul_rec n a + a /-- The fundamental scalar multiplication in an additive monoid. `nsmul_rec n a = a+a+...+a` n times. Use instead `n • a`, which has better definitional behavior. -/ def nsmul_rec [Zero M] [Add M] : ℕ → M → M | 0 , a => 0 | n+1, a => a + nsmul_rec n a -- use `x * npow_rec n x` and not `npow_rec n x * x` in the definition to make sure that -- definitional unfolding of `npow_rec` is blocked, to avoid deep recursion issues. /-- The fundamental power operation in a monoid. `npow_rec n a = a*a*...*a` n times. Use instead `a ^ n`, which has better definitional behavior. -/ def npow_rec [One M] [Mul M] : ℕ → M → M | 0 , a => 1 | n+1, a => a * npow_rec n a end nat_action section int_action /-- The fundamental scalar multiplication in an additive group. `gsmul_rec n a = a+a+...+a` n times, for integer `n`. Use instead `n • a`, which has better definitional behavior. -/ def gsmul_rec {G : Type u} [Zero G] [Add G] [Neg G]: ℤ → G → G | (Int.ofNat n) , a => nsmul_rec n a | (Int.negSucc n), a => - (nsmul_rec n.succ a) /-- The fundamental power operation in a group. `gpow_rec n a = a*a*...*a` n times, for integer `n`. Use instead `a ^ n`, which has better definitional behavior. -/ def gpow_rec {G : Type u} [One G] [Mul G] [Inv G] : ℤ → G → G | (Int.ofNat n) , a => npow_rec n a | (Int.negSucc n), a => (npow_rec n.succ a) ⁻¹ end int_action /- ## Additive semigroups, monoids and groups -/ /- ### Semigroups -/ class AddSemigroup (A : Type u) extends Add A where add_assoc (a b c : A) : (a + b) + c = a + (b + c) theorem add_assoc {G : Type u} [AddSemigroup G] : ∀ a b c : G, (a + b) + c = a + (b + c) := AddSemigroup.add_assoc class AddCommSemigroup (A : Type u) extends AddSemigroup A where add_comm (a b : A) : a + b = b + a theorem add_comm {A : Type u} [AddCommSemigroup A] (a b : A) : a + b = b + a := AddCommSemigroup.add_comm a b /- ### Cancellative semigroups -/ class IsAddLeftCancel (A : Type u) [Add A] where add_left_cancel (a b c : A) : a + b = a + c → b = c class IsAddRightCancel (A : Type u) [Add A] where add_right_cancel (a b c : A) : b + a = c + a → b = c section AddLeftCancel_lemmas variable {A : Type u} [AddSemigroup A] [IsAddLeftCancel A] {a b c : A} theorem add_left_cancel : a + b = a + c → b = c := IsAddLeftCancel.add_left_cancel a b c theorem add_left_cancel_iff : a + b = a + c ↔ b = c := ⟨add_left_cancel, congrArg _⟩ -- no `function.injective`? --theorem add_right_injective (a : G) : function.injective (c * .) := --λ a b => add_left_cancel @[simp] theorem add_right_inj (a : A) {b c : A} : a + b = a + c ↔ b = c := ⟨add_left_cancel, congrArg _⟩ --theorem add_ne_add_right (a : A) {b c : A} : a + b ≠ a + c ↔ b ≠ c := --(add_right_injective a).ne_iff end AddLeftCancel_lemmas section AddRightCancel_lemmas variable {A : Type u} [AddSemigroup A] [IsAddRightCancel A] {a b c : A} theorem add_right_cancel : b + a = c + a → b = c := IsAddRightCancel.add_right_cancel a b c theorem add_right_cancel_iff : b + a = c + a ↔ b = c := ⟨add_right_cancel, λ h => h ▸ rfl⟩ @[simp] theorem add_left_inj (a : A) {b c : A} : b + a = c + a ↔ b = c := ⟨add_right_cancel, λ h => h ▸ rfl⟩ end AddRightCancel_lemmas /- ### Additive monoids -/ class AddMonoid (A : Type u) extends AddSemigroup A, Zero A where add_zero (a : A) : a + 0 = a zero_add (a : A) : 0 + a = a nsmul : ℕ → A → A := nsmul_rec nsmul_zero' : ∀ x, nsmul 0 x = 0 -- fill in with tactic once we can do this nsmul_succ' : ∀ (n : ℕ) x, nsmul n.succ x = x + nsmul n x -- fill in with tactic section AddMonoid_lemmas variable {A : Type u} [AddMonoid A] {a b c : A} @[simp] theorem add_zero (a : A) : a + 0 = a := AddMonoid.add_zero a @[simp] theorem zero_add (a : A) : 0 + a = a := AddMonoid.zero_add a theorem left_neg_eq_right_neg (hba : b + a = 0) (hac : a + c = 0) : b = c := by rw [←zero_add c, ←hba, add_assoc, hac, add_zero b] end AddMonoid_lemmas /-! ### Additive monoids with one -/ class AddMonoidWithOne (R : Type u) extends AddMonoid R, One R where natCast : ℕ → R natCast_zero : natCast 0 = 0 natCast_succ : ∀ n, natCast (n + 1) = natCast n + 1 @[coe] def Nat.cast [AddMonoidWithOne R] : ℕ → R := AddMonoidWithOne.natCast instance [AddMonoidWithOne R] : CoeTail ℕ R where coe := Nat.cast instance [AddMonoidWithOne R] : CoeHTCT ℕ R where coe := Nat.cast @[simp, norm_cast] theorem Nat.cast_zero [AddMonoidWithOne R] : ((0 : ℕ) : R) = 0 := AddMonoidWithOne.natCast_zero @[simp 500, norm_cast 500] theorem Nat.cast_succ [AddMonoidWithOne R] : ((Nat.succ n : ℕ) : R) = (n : R) + 1 := AddMonoidWithOne.natCast_succ _ @[simp, norm_cast] theorem Nat.cast_one [AddMonoidWithOne R] : ((1 : ℕ) : R) = 1 := by simp @[simp, norm_cast] theorem Nat.cast_add [AddMonoidWithOne R] : ((m + n : ℕ) : R) = (m : R) + n := by induction n <;> simp_all [add_succ, add_assoc] class Nat.AtLeastTwo (n : Nat) : Prop where prop : n ≥ 2 instance : Nat.AtLeastTwo (n + 2) where prop := Nat.succ_le_succ $ Nat.succ_le_succ $ Nat.zero_le _ instance [AddMonoidWithOne R] [Nat.AtLeastTwo n] : OfNat R n where ofNat := n.cast @[simp, norm_cast] theorem Nat.cast_ofNat [AddMonoidWithOne R] [Nat.AtLeastTwo n] : (Nat.cast (OfNat.ofNat n) : R) = OfNat.ofNat n := rfl /- ### Commutative additive monoids -/ class AddCommMonoid (A : Type u) extends AddMonoid A, AddCommSemigroup A where -- TODO: doesn't work zero_add a := (by rw [add_comm, add_zero]) add_zero a := (by rw [add_comm, zero_add]) /- ### sub_neg_monoids Additive groups can "pick up" several equal but not defeq actions of ℤ. This trick isolates one such action, `gsmul`, and decrees it to be "the canonical one". -/ class SubNegMonoid (A : Type u) extends AddMonoid A, Neg A, Sub A where sub := λ a b => a + -b sub_eq_add_neg : ∀ a b : A, a - b = a + -b gsmul : ℤ → A → A := gsmul_rec gsmul_zero' : ∀ (a : A), gsmul 0 a = 0 gsmul_succ' (n : ℕ) (a : A) : gsmul (Int.ofNat n.succ) a = a + gsmul (Int.ofNat n) a gsmul_neg' (n : ℕ) (a : A) : gsmul (Int.negSucc n) a = -(gsmul ↑(n.succ) a) export SubNegMonoid (sub_eq_add_neg) /- ### Additive groups -/ class AddGroup (A : Type u) extends SubNegMonoid A where add_left_neg (a : A) : -a + a = 0 section AddGroup_lemmas variable {A : Type u} [AddGroup A] {a b c : A} @[simp] theorem add_left_neg : ∀ a : A, -a + a = 0 := AddGroup.add_left_neg theorem neg_add_self (a : A) : -a + a = 0 := add_left_neg a @[simp] theorem neg_add_cancel_left (a b : A) : -a + (a + b) = b := by rw [← add_assoc, add_left_neg, zero_add] theorem neg_eq_of_add_eq_zero (h : a + b = 0) : -a = b := left_neg_eq_right_neg (neg_add_self a) h @[simp] theorem neg_neg (a : A) : -(-a) = a := neg_eq_of_add_eq_zero (add_left_neg a) @[simp] theorem add_right_neg (a : A) : a + -a = 0 := by rw [←add_left_neg (-a), neg_neg] -- synonym theorem add_neg_self (a : A) : a + -a = 0 := add_right_neg a @[simp] theorem add_neg_cancel_right (a b : A) : a + b + -b = a := by rw [add_assoc, add_right_neg, add_zero] instance (A : Type u) [AddGroup A] : IsAddRightCancel A where add_right_cancel a b c h := by rw [← add_neg_cancel_right b a, h, add_neg_cancel_right] instance (A : Type u) [AddGroup A] : IsAddLeftCancel A where add_left_cancel a b c h := by rw [← neg_add_cancel_left a b, h, neg_add_cancel_left] lemma eq_of_sub_eq_zero' (h : a - b = 0) : a = b := add_right_cancel <| show a + (-b) = b + (-b) by rw [← sub_eq_add_neg, h, add_neg_self] end AddGroup_lemmas class AddCommGroup (A : Type u) extends AddGroup A, AddCommMonoid A /-! ### Additive groups with one -/ class AddGroupWithOne (R : Type u) extends AddMonoidWithOne R, AddGroup R where intCast : ℤ → R intCast_ofNat : ∀ n : ℕ, intCast n = natCast n intCast_negSucc : ∀ n : ℕ, intCast (Int.negSucc n) = - natCast (n + 1) @[coe] def Int.cast [AddGroupWithOne R] : ℤ → R := AddGroupWithOne.intCast instance [AddGroupWithOne R] : CoeTail ℤ R where coe := Int.cast theorem Int.cast_ofNat [AddGroupWithOne R] : (Int.cast (Int.ofNat n) : R) = Nat.cast n := AddGroupWithOne.intCast_ofNat _ @[simp, norm_cast] theorem Int.cast_negSucc [AddGroupWithOne R] : (Int.cast (Int.negSucc n) : R) = (-(Nat.cast (n + 1)) : R) := AddGroupWithOne.intCast_negSucc _ @[simp, norm_cast] theorem Int.cast_zero [AddGroupWithOne R] : ((0 : ℤ) : R) = 0 := by erw [Int.cast_ofNat, Nat.cast_zero] @[simp, norm_cast] theorem Int.cast_one [AddGroupWithOne R] : ((1 : ℤ) : R) = 1 := by erw [Int.cast_ofNat, Nat.cast_one] /- ## Multiplicative semigroups, monoids and groups -/ /- ## Semigroups -/ class Semigroup (G : Type u) extends Mul G where mul_assoc (a b c : G) : (a * b) * c = a * (b * c) export Semigroup (mul_assoc) class CommSemigroup (G : Type u) extends Semigroup G where mul_comm (a b : G) : a * b = b * a export CommSemigroup (mul_comm) lemma mul_left_comm {M} [CommSemigroup M] (a b c : M) : a * (b * c) = b * (a * c) := by rw [← mul_assoc, mul_comm a, mul_assoc] -- Funky Lean 3 proof of the above: --left_comm has_mul.mul mul_comm mul_assoc lemma mul_right_comm {M} [CommSemigroup M] (a b c : M) : a * b * c = a * c * b := by rw [mul_assoc, mul_comm b c, mul_assoc] /-- Typeclass for expressing that a type `M` with multiplication and a one satisfies `1 * a = a` and `a * 1 = a` for all `a : M`. -/ class MulOneClass (M : Type u) extends One M, Mul M where one_mul : ∀ (a : M), 1 * a = a mul_one : ∀ (a : M), a * 1 = a /- ### Cancellative semigroups -/ class IsMulLeftCancel (G : Type u) [Mul G] where mul_left_cancel (a b c : G) : a * b = a * c → b = c class IsMulRightCancel (G : Type u) [Mul G] where mul_right_cancel (a b c : G) : b * a = c * a → b = c section MulLeftCancel variable {G : Type u} [Semigroup G] [IsMulLeftCancel G] {a b c : G} theorem mul_left_cancel : a * b = a * c → b = c := IsMulLeftCancel.mul_left_cancel a b c theorem mul_left_cancel_iff : a * b = a * c ↔ b = c := ⟨mul_left_cancel, congrArg _⟩ -- no `function.injective`? --theorem mul_right_injective (a : G) : function.injective (c * .) := --λ a b => mul_left_cancel @[simp] theorem mul_right_inj (a : G) {b c : G} : a * b = a * c ↔ b = c := ⟨mul_left_cancel, congrArg _⟩ --theorem mul_ne_mul_right (a : G) {b c : G} : a * b ≠ a * c ↔ b ≠ c := --(mul_right_injective a).ne_iff end MulLeftCancel section MulRightCancel variable {G : Type u} [Semigroup G] [IsMulRightCancel G] {a b c : G} theorem mul_right_cancel : b * a = c * a → b = c := IsMulRightCancel.mul_right_cancel a b c theorem mul_right_cancel_iff : b * a = c * a ↔ b = c := ⟨mul_right_cancel, λ h => h ▸ rfl⟩ @[simp] theorem mul_left_inj (a : G) {b c : G} : b * a = c * a ↔ b = c := ⟨mul_right_cancel, λ h => h ▸ rfl⟩ end MulRightCancel /- ### Monoids -/ class Monoid (M : Type u) extends Semigroup M, MulOneClass M where npow : ℕ → M → M := npow_rec npow_zero' : ∀ x, npow 0 x = 1 -- fill in with tactic once we can do this npow_succ' : ∀ (n : ℕ) x, npow n.succ x = x * npow n x -- fill in with tactic section Monoid variable {M : Type u} [Monoid M] @[defaultInstance high] instance Monoid.HPow : HPow M ℕ M := ⟨λ a n => Monoid.npow n a⟩ @[simp] theorem mul_one : ∀ (a : M), a * 1 = a := Monoid.mul_one @[simp] theorem one_mul : ∀ (a : M), 1 * a = a := Monoid.one_mul theorem npow_eq_pow (n : ℕ) (a : M) : Monoid.npow n a = a^n := rfl @[simp] theorem pow_zero : ∀ (a : M), a ^ (0:ℕ) = 1 := Monoid.npow_zero' theorem pow_succ' : ∀ (n : ℕ) (a : M), a ^ n.succ = a * a ^ n := Monoid.npow_succ' theorem pow_mul_comm (a : M) (n : ℕ) : a^n * a = a * a^n := by induction n with | zero => simp | succ n ih => simp [ih, pow_succ', mul_assoc] theorem pow_succ (n : ℕ) (a : M) : a ^ n.succ = a ^ n * a := by rw [pow_succ', pow_mul_comm] @[simp] theorem pow_one (a : M) : a ^ (1:ℕ) = a := by rw [Nat.one_eq_succ_zero, pow_succ, pow_zero, one_mul] theorem pow_add (a : M) (m n : ℕ) : a^(m + n) = a^m * a^n := by induction n with | zero => simp | succ n ih => rw [Nat.add_succ, pow_succ',ih, pow_succ', ← mul_assoc, ← mul_assoc, pow_mul_comm] theorem pow_mul {M} [Monoid M] (a : M) (m n : ℕ) : a^(m * n) = (a^m)^n := by induction n with | zero => simp | succ n ih => rw [Nat.mul_succ, pow_add, ih, pow_succ', pow_mul_comm] theorem left_inv_eq_right_inv {M : Type u} [Monoid M] {a b c : M} (hba : b * a = 1) (hac : a * c = 1) : b = c := by rw [←one_mul c, ←hba, mul_assoc, hac, mul_one b] end Monoid /- ### Commutative monoids -/ class CommMonoid (M : Type u) extends Monoid M where mul_comm (a b : M) : a * b = b * a section CommMonoid variable {M} [CommMonoid M] instance : CommSemigroup M where __ := ‹CommMonoid M› theorem mul_pow (a b : M) (n : ℕ) : (a * b)^n= a^n * b^n := by induction n with | zero => simp | succ n ih => simp only [pow_succ, ih, mul_assoc, mul_left_comm _ a] end CommMonoid /- ### Div inv monoids -/ class DivInvMonoid (G : Type u) extends Monoid G, Inv G, Div G := (div := λ a b => a * b⁻¹) (div_eq_mul_inv : ∀ a b : G, a / b = a * b⁻¹) (gpow : ℤ → G → G := gpow_rec) (gpow_zero' : ∀ (a : G), gpow 0 a = 1) (gpow_succ' : ∀ (n : ℕ) (a : G), gpow (Int.ofNat n.succ) a = a * gpow (Int.ofNat n) a) (gpow_neg' : ∀ (n : ℕ) (a : G), gpow (Int.negSucc n) a = (gpow (Int.ofNat n.succ) a) ⁻¹) /- ### Groups -/ class Group (G : Type u) extends DivInvMonoid G where mul_left_inv (a : G) : a⁻¹ * a = 1 section Group_lemmas variable {G : Type u} [Group G] {a b c : G} @[simp] theorem mul_left_inv : ∀ a : G, a⁻¹ * a = 1 := Group.mul_left_inv theorem inv_mul_self (a : G) : a⁻¹ * a = 1 := mul_left_inv a @[simp] theorem inv_mul_cancel_left (a b : G) : a⁻¹ * (a * b) = b := by rw [← mul_assoc, mul_left_inv, one_mul] @[simp] theorem inv_eq_of_mul_eq_one (h : a * b = 1) : a⁻¹ = b := left_inv_eq_right_inv (inv_mul_self a) h @[simp] theorem inv_inv (a : G) : (a⁻¹)⁻¹ = a := inv_eq_of_mul_eq_one (mul_left_inv a) @[simp] theorem mul_right_inv (a : G) : a * a⁻¹ = 1 := by rw [←mul_left_inv (a⁻¹), inv_inv] -- synonym theorem mul_inv_self (a : G) : a * a⁻¹ = 1 := mul_right_inv a @[simp] theorem mul_inv_cancel_right (a b : G) : a * b * b⁻¹ = a := by rw [mul_assoc, mul_right_inv, mul_one] end Group_lemmas class CommGroup (G : Type u) extends Group G where mul_comm (a b : G) : a * b = b * a instance (G : Type u) [CommGroup G] : CommMonoid G where __ := ‹CommGroup G›
xm = function(m,n=100) {(n-sqrt(n^2 - 4 *m * n))/2/n} pdf(width=5, height=4, file='fig1.pdf') x = seq(0,30,0.01) par(mar=c(2,4,1,1)) plot(c(),c(),xlim=c(0,33),ylim=c(0,0.19),yaxt='n',xaxt='n',ylab=NA, xlab=NA) axis(1,at=c(0,10,20,30), labels=c("0.00", "10.00", "20.00", "30.00")) axis(2,at=seq(0,0.18,by=0.02),las=2) n = 10000 for (m in c(5,10,20)){ p = m / n lines(x,dnorm(x,m=m,s=sqrt(n * p * (1-p))), lwd=2) lines(0:30,dbinom(0:30,size=n, prob=m/n), lwd=2, col='black', lty=2) } legend(17, 0.18, lty=c(1,2), legend=c("Normal", "Binomial")) dev.off()
[STATEMENT] lemma reduce_invertible_mat: assumes A': "A' \<in> carrier_mat m n" and a: "a<m" and j: "0<n" and b: "b<m" and ab: "a \<noteq> b" and A_def: "A = A' @\<^sub>r (D \<cdot>\<^sub>m (1\<^sub>m n))" and Aaj: "A $$ (a,0) \<noteq> 0" and a_less_b: "a < b" and mn: "m\<ge>n" and D_ge0: "D > 0" shows "\<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m+n) (m+n) \<and> (reduce a b D A) = P * A" (is ?thesis1) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] obtain p q u v d where pquvd: "(p,q,u,v,d) = euclid_ext2 (A$$(a,0)) (A$$(b,0))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>p q u v d. (p, q, u, v, d) = euclid_ext2 (A $$ (a, 0)) (A $$ (b, 0)) \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by (metis prod_cases5) [PROOF STATE] proof (state) this: (p, q, u, v, d) = euclid_ext2 (A $$ (a, 0)) (A $$ (b, 0)) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] let ?A = "Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i,k). if i = a then (p*A$$(a,k) + q*A$$(b,k)) else if i = b then u * A$$(a,k) + v * A$$(b,k) else A$$(i,k) )" [PROOF STATE] proof (state) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] have D: "D \<cdot>\<^sub>m 1\<^sub>m n \<in> carrier_mat n n" [PROOF STATE] proof (prove) goal (1 subgoal): 1. D \<cdot>\<^sub>m 1\<^sub>m n \<in> carrier_mat n n [PROOF STEP] by auto [PROOF STATE] proof (state) this: D \<cdot>\<^sub>m 1\<^sub>m n \<in> carrier_mat n n goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] have A: "A \<in> carrier_mat (m+n) n" [PROOF STATE] proof (prove) goal (1 subgoal): 1. A \<in> carrier_mat (m + n) n [PROOF STEP] using A_def A' [PROOF STATE] proof (prove) using this: A = A' @\<^sub>r D \<cdot>\<^sub>m 1\<^sub>m n A' \<in> carrier_mat m n goal (1 subgoal): 1. A \<in> carrier_mat (m + n) n [PROOF STEP] by simp [PROOF STATE] proof (state) this: A \<in> carrier_mat (m + n) n goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] hence A_carrier: "?A \<in> carrier_mat (m+n) n" [PROOF STATE] proof (prove) using this: A \<in> carrier_mat (m + n) n goal (1 subgoal): 1. Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) \<in> carrier_mat (m + n) n [PROOF STEP] by auto [PROOF STATE] proof (state) this: Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) \<in> carrier_mat (m + n) n goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] let ?BM = "bezout_matrix_JNF A a b 0 euclid_ext2" [PROOF STATE] proof (state) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] have A'_BZ_A: "?A = ?BM * A" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) = bezout_matrix_JNF A a b 0 euclid_ext2 * A [PROOF STEP] by (rule bezout_matrix_JNF_mult_eq[OF A' _ _ ab A_def D pquvd], insert a b, auto) [PROOF STATE] proof (state) this: Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) = bezout_matrix_JNF A a b 0 euclid_ext2 * A goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] have invertible_bezout: "invertible_mat ?BM" [PROOF STATE] proof (prove) goal (1 subgoal): 1. invertible_mat (bezout_matrix_JNF A a b 0 euclid_ext2) [PROOF STEP] by (rule invertible_bezout_matrix_JNF[OF A is_bezout_ext_euclid_ext2 a_less_b _ j Aaj], insert a_less_b b, auto) [PROOF STATE] proof (state) this: invertible_mat (bezout_matrix_JNF A a b 0 euclid_ext2) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] have BM: "?BM \<in> carrier_mat (m+n) (m+n)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. bezout_matrix_JNF A a b 0 euclid_ext2 \<in> carrier_mat (m + n) (m + n) [PROOF STEP] unfolding bezout_matrix_JNF_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat (dim_row A) (dim_row A) (\<lambda>(x, y). let (p, q, u, v, d) = euclid_ext2 (A $$ (a, 0)) (A $$ (b, 0)) in if x = a \<and> y = a then p else if x = a \<and> y = b then q else if x = b \<and> y = a then u else if x = b \<and> y = b then v else if x = y then 1 else 0) \<in> carrier_mat (m + n) (m + n) [PROOF STEP] using A [PROOF STATE] proof (prove) using this: A \<in> carrier_mat (m + n) n goal (1 subgoal): 1. Matrix.mat (dim_row A) (dim_row A) (\<lambda>(x, y). let (p, q, u, v, d) = euclid_ext2 (A $$ (a, 0)) (A $$ (b, 0)) in if x = a \<and> y = a then p else if x = a \<and> y = b then q else if x = b \<and> y = a then u else if x = b \<and> y = b then v else if x = y then 1 else 0) \<in> carrier_mat (m + n) (m + n) [PROOF STEP] by auto [PROOF STATE] proof (state) this: bezout_matrix_JNF A a b 0 euclid_ext2 \<in> carrier_mat (m + n) (m + n) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] define xs where "xs = [0..<n]" [PROOF STATE] proof (state) this: xs = [0..<n] goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] let ?reduce_a = "reduce_row_mod_D ?A a xs D m" [PROOF STATE] proof (state) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] let ?A' = "mat_of_rows n [Matrix.row ?A i. i \<leftarrow> [0..<m]]" [PROOF STATE] proof (state) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] have A_A'_D: "?A = ?A' @\<^sub>r D \<cdot>\<^sub>m 1\<^sub>m n" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) = mat_of_rows n (map (row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) [0..<m]) @\<^sub>r D \<cdot>\<^sub>m 1\<^sub>m n [PROOF STEP] proof (rule matrix_append_rows_eq_if_preserves[OF A_carrier D], rule+) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>i j. \<lbrakk>i \<in> {m..<m + n}; j < n\<rbrakk> \<Longrightarrow> Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] fix i j [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>i j. \<lbrakk>i \<in> {m..<m + n}; j < n\<rbrakk> \<Longrightarrow> Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] assume i: "i \<in> {m..<m + n}" and j: "j < n" [PROOF STATE] proof (state) this: i \<in> {m..<m + n} j < n goal (1 subgoal): 1. \<And>i j. \<lbrakk>i \<in> {m..<m + n}; j < n\<rbrakk> \<Longrightarrow> Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] have "?A $$ (i,j) = A $$ (i,j)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, j) = A $$ (i, j) [PROOF STEP] using i a b A j [PROOF STATE] proof (prove) using this: i \<in> {m..<m + n} a < m b < m A \<in> carrier_mat (m + n) n j < n goal (1 subgoal): 1. Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, j) = A $$ (i, j) [PROOF STEP] by auto [PROOF STATE] proof (state) this: Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, j) = A $$ (i, j) goal (1 subgoal): 1. \<And>i j. \<lbrakk>i \<in> {m..<m + n}; j < n\<rbrakk> \<Longrightarrow> Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] also [PROOF STATE] proof (state) this: Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, j) = A $$ (i, j) goal (1 subgoal): 1. \<And>i j. \<lbrakk>i \<in> {m..<m + n}; j < n\<rbrakk> \<Longrightarrow> Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] have "... = (if i < dim_row A' then A' $$(i,j) else (D \<cdot>\<^sub>m (1\<^sub>m n))$$(i-m,j))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. A $$ (i, j) = (if i < dim_row A' then A' $$ (i, j) else (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j)) [PROOF STEP] by (unfold A_def, rule append_rows_nth[OF A' D _ j], insert i, auto) [PROOF STATE] proof (state) this: A $$ (i, j) = (if i < dim_row A' then A' $$ (i, j) else (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j)) goal (1 subgoal): 1. \<And>i j. \<lbrakk>i \<in> {m..<m + n}; j < n\<rbrakk> \<Longrightarrow> Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] also [PROOF STATE] proof (state) this: A $$ (i, j) = (if i < dim_row A' then A' $$ (i, j) else (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j)) goal (1 subgoal): 1. \<And>i j. \<lbrakk>i \<in> {m..<m + n}; j < n\<rbrakk> \<Longrightarrow> Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] have "... = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (if i < dim_row A' then A' $$ (i, j) else (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j)) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] using i A' [PROOF STATE] proof (prove) using this: i \<in> {m..<m + n} A' \<in> carrier_mat m n goal (1 subgoal): 1. (if i < dim_row A' then A' $$ (i, j) else (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j)) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] by auto [PROOF STATE] proof (state) this: (if i < dim_row A' then A' $$ (i, j) else (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j)) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) goal (1 subgoal): 1. \<And>i j. \<lbrakk>i \<in> {m..<m + n}; j < n\<rbrakk> \<Longrightarrow> Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] show "?A $$ (i,j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j)" [PROOF STATE] proof (prove) using this: Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) goal (1 subgoal): 1. Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] . [PROOF STATE] proof (state) this: Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) = mat_of_rows n (map (row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) [0..<m]) @\<^sub>r D \<cdot>\<^sub>m 1\<^sub>m n goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] have reduce_a_eq: "?reduce_a = Matrix.mat (dim_row ?A) (dim_col ?A) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd ?A$$(i,k) then D else ?A $$ (i, k) else ?A $$ (i, k) gmod D else ?A $$ (i, k))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m = Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) [PROOF STEP] by (rule reduce_row_mod_D[OF A_A'_D _ a _], insert xs_def mn D_ge0, auto) [PROOF STATE] proof (state) this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m = Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] have reduce_a: "?reduce_a \<in> carrier_mat (m+n) n" [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m \<in> carrier_mat (m + n) n [PROOF STEP] using reduce_a_eq A [PROOF STATE] proof (prove) using this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m = Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) A \<in> carrier_mat (m + n) n goal (1 subgoal): 1. reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m \<in> carrier_mat (m + n) n [PROOF STEP] by auto [PROOF STATE] proof (state) this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m \<in> carrier_mat (m + n) n goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] have "\<exists>P. P \<in> carrier_mat (m + n) (m + n) \<and> invertible_mat P \<and> ?reduce_a = P * ?A" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>P. P \<in> carrier_mat (m + n) (m + n) \<and> invertible_mat P \<and> reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m = P * Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) [PROOF STEP] by (rule reduce_row_mod_D_invertible_mat[OF A_A'_D _ a], insert xs_def mn, auto) [PROOF STATE] proof (state) this: \<exists>P. P \<in> carrier_mat (m + n) (m + n) \<and> invertible_mat P \<and> reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m = P * Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] from this [PROOF STATE] proof (chain) picking this: \<exists>P. P \<in> carrier_mat (m + n) (m + n) \<and> invertible_mat P \<and> reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m = P * Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) [PROOF STEP] obtain P where P: "P \<in> carrier_mat (m + n) (m + n)" and inv_P: "invertible_mat P" and reduce_a_PA: "?reduce_a = P * ?A" [PROOF STATE] proof (prove) using this: \<exists>P. P \<in> carrier_mat (m + n) (m + n) \<and> invertible_mat P \<and> reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m = P * Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) goal (1 subgoal): 1. (\<And>P. \<lbrakk>P \<in> carrier_mat (m + n) (m + n); invertible_mat P; reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m = P * Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by blast [PROOF STATE] proof (state) this: P \<in> carrier_mat (m + n) (m + n) invertible_mat P reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m = P * Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] define ys where "ys = [1..<n]" [PROOF STATE] proof (state) this: ys = [1..<n] goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] let ?reduce_b = "reduce_row_mod_D ?reduce_a b ys D m" [PROOF STATE] proof (state) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] let ?B' = "mat_of_rows n [Matrix.row ?reduce_a i. i \<leftarrow> [0..<m]]" [PROOF STATE] proof (state) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] have reduce_a_B'_D: "?reduce_a = ?B' @\<^sub>r D \<cdot>\<^sub>m 1\<^sub>m n" [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m = mat_of_rows n (map (row (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) [0..<m]) @\<^sub>r D \<cdot>\<^sub>m 1\<^sub>m n [PROOF STEP] proof (rule matrix_append_rows_eq_if_preserves[OF reduce_a D], rule+) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>i j. \<lbrakk>i \<in> {m..<m + n}; j < n\<rbrakk> \<Longrightarrow> reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] fix i ja [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>i j. \<lbrakk>i \<in> {m..<m + n}; j < n\<rbrakk> \<Longrightarrow> reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] assume i: "i \<in> {m..<m + n}" and ja: "ja < n" [PROOF STATE] proof (state) this: i \<in> {m..<m + n} ja < n goal (1 subgoal): 1. \<And>i j. \<lbrakk>i \<in> {m..<m + n}; j < n\<rbrakk> \<Longrightarrow> reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] have i_not_a:"i\<noteq>a" and i_not_b: "i\<noteq>b" [PROOF STATE] proof (prove) goal (1 subgoal): 1. i \<noteq> a &&& i \<noteq> b [PROOF STEP] using i a b [PROOF STATE] proof (prove) using this: i \<in> {m..<m + n} a < m b < m goal (1 subgoal): 1. i \<noteq> a &&& i \<noteq> b [PROOF STEP] by auto [PROOF STATE] proof (state) this: i \<noteq> a i \<noteq> b goal (1 subgoal): 1. \<And>i j. \<lbrakk>i \<in> {m..<m + n}; j < n\<rbrakk> \<Longrightarrow> reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] have "?reduce_a $$ (i,ja) = ?A $$ (i, ja)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) [PROOF STEP] unfolding reduce_a_eq [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) [PROOF STEP] using i i_not_a i_not_b ja A [PROOF STATE] proof (prove) using this: i \<in> {m..<m + n} i \<noteq> a i \<noteq> b ja < n A \<in> carrier_mat (m + n) n goal (1 subgoal): 1. Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) [PROOF STEP] by auto [PROOF STATE] proof (state) this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) goal (1 subgoal): 1. \<And>i j. \<lbrakk>i \<in> {m..<m + n}; j < n\<rbrakk> \<Longrightarrow> reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] also [PROOF STATE] proof (state) this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) goal (1 subgoal): 1. \<And>i j. \<lbrakk>i \<in> {m..<m + n}; j < n\<rbrakk> \<Longrightarrow> reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] have "... = A $$ (i,ja)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) = A $$ (i, ja) [PROOF STEP] using i i_not_a i_not_b ja A [PROOF STATE] proof (prove) using this: i \<in> {m..<m + n} i \<noteq> a i \<noteq> b ja < n A \<in> carrier_mat (m + n) n goal (1 subgoal): 1. Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) = A $$ (i, ja) [PROOF STEP] by auto [PROOF STATE] proof (state) this: Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) = A $$ (i, ja) goal (1 subgoal): 1. \<And>i j. \<lbrakk>i \<in> {m..<m + n}; j < n\<rbrakk> \<Longrightarrow> reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] also [PROOF STATE] proof (state) this: Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) = A $$ (i, ja) goal (1 subgoal): 1. \<And>i j. \<lbrakk>i \<in> {m..<m + n}; j < n\<rbrakk> \<Longrightarrow> reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] have "... = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, ja)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. A $$ (i, ja) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, ja) [PROOF STEP] by (smt D append_rows_nth A' A_def atLeastLessThan_iff carrier_matD(1) i ja less_irrefl_nat nat_SN.compat) [PROOF STATE] proof (state) this: A $$ (i, ja) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, ja) goal (1 subgoal): 1. \<And>i j. \<lbrakk>i \<in> {m..<m + n}; j < n\<rbrakk> \<Longrightarrow> reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, j) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, j) [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, ja) [PROOF STEP] show "?reduce_a $$ (i,ja) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, ja)" [PROOF STATE] proof (prove) using this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, ja) goal (1 subgoal): 1. reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, ja) [PROOF STEP] . [PROOF STATE] proof (state) this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = (D \<cdot>\<^sub>m 1\<^sub>m n) $$ (i - m, ja) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m = mat_of_rows n (map (row (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) [0..<m]) @\<^sub>r D \<cdot>\<^sub>m 1\<^sub>m n goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] have reduce_b_eq: "?reduce_b = Matrix.mat (dim_row ?reduce_a) (dim_col ?reduce_a) (\<lambda>(i, k). if i = b \<and> k \<in> set ys then if k = 0 then if D dvd ?reduce_a$$(i,k) then D else ?reduce_a $$ (i, k) else ?reduce_a $$ (i, k) gmod D else ?reduce_a $$ (i, k))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m = Matrix.mat (dim_row (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) (dim_col (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) (\<lambda>(i, k). if i = b \<and> k \<in> set ys then if k = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) then D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) gmod D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k)) [PROOF STEP] by (rule reduce_row_mod_D[OF reduce_a_B'_D _ b _ _ mn], unfold ys_def, insert D_ge0, auto) [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m = Matrix.mat (dim_row (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) (dim_col (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) (\<lambda>(i, k). if i = b \<and> k \<in> set ys then if k = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) then D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) gmod D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k)) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] have "\<exists>P. P \<in> carrier_mat (m + n) (m + n) \<and> invertible_mat P \<and> ?reduce_b = P * ?reduce_a" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>P. P \<in> carrier_mat (m + n) (m + n) \<and> invertible_mat P \<and> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m = P * reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m [PROOF STEP] by (rule reduce_row_mod_D_invertible_mat[OF reduce_a_B'_D _ b _ mn], insert ys_def, auto) [PROOF STATE] proof (state) this: \<exists>P. P \<in> carrier_mat (m + n) (m + n) \<and> invertible_mat P \<and> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m = P * reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] from this [PROOF STATE] proof (chain) picking this: \<exists>P. P \<in> carrier_mat (m + n) (m + n) \<and> invertible_mat P \<and> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m = P * reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m [PROOF STEP] obtain Q where Q: "Q \<in> carrier_mat (m + n) (m + n)" and inv_Q: "invertible_mat Q" and reduce_b_Q_reduce: "?reduce_b = Q * ?reduce_a" [PROOF STATE] proof (prove) using this: \<exists>P. P \<in> carrier_mat (m + n) (m + n) \<and> invertible_mat P \<and> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m = P * reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m goal (1 subgoal): 1. (\<And>Q. \<lbrakk>Q \<in> carrier_mat (m + n) (m + n); invertible_mat Q; reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m = Q * reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by blast [PROOF STATE] proof (state) this: Q \<in> carrier_mat (m + n) (m + n) invertible_mat Q reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m = Q * reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] have reduce_b_eq_reduce: "?reduce_b = (reduce a b D A)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m = reduce a b D A [PROOF STEP] proof (rule eq_matI) [PROOF STATE] proof (state) goal (3 subgoals): 1. \<And>i j. \<lbrakk>i < dim_row (reduce a b D A); j < dim_col (reduce a b D A)\<rbrakk> \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, j) = reduce a b D A $$ (i, j) 2. dim_row (reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m) = dim_row (reduce a b D A) 3. dim_col (reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m) = dim_col (reduce a b D A) [PROOF STEP] show dr_eq: "dim_row ?reduce_b = dim_row (reduce a b D A)" and dc_eq: "dim_col ?reduce_b = dim_col (reduce a b D A)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. dim_row (reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m) = dim_row (reduce a b D A) &&& dim_col (reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m) = dim_col (reduce a b D A) [PROOF STEP] using reduce_preserves_dimensions [PROOF STATE] proof (prove) using this: dim_row (reduce ?a ?b ?D ?A) = dim_row ?A dim_col (reduce ?a ?b ?D ?A) = dim_col ?A dim_row (reduce_abs ?a ?b ?D ?A) = dim_row ?A dim_col (reduce_abs ?a ?b ?D ?A) = dim_col ?A goal (1 subgoal): 1. dim_row (reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m) = dim_row (reduce a b D A) &&& dim_col (reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m) = dim_col (reduce a b D A) [PROOF STEP] by auto [PROOF STATE] proof (state) this: dim_row (reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m) = dim_row (reduce a b D A) dim_col (reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m) = dim_col (reduce a b D A) goal (1 subgoal): 1. \<And>i j. \<lbrakk>i < dim_row (reduce a b D A); j < dim_col (reduce a b D A)\<rbrakk> \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, j) = reduce a b D A $$ (i, j) [PROOF STEP] fix i ja [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>i j. \<lbrakk>i < dim_row (reduce a b D A); j < dim_col (reduce a b D A)\<rbrakk> \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, j) = reduce a b D A $$ (i, j) [PROOF STEP] assume i: "i<dim_row (reduce a b D A)" and ja: "ja< dim_col (reduce a b D A)" [PROOF STATE] proof (state) this: i < dim_row (reduce a b D A) ja < dim_col (reduce a b D A) goal (1 subgoal): 1. \<And>i j. \<lbrakk>i < dim_row (reduce a b D A); j < dim_col (reduce a b D A)\<rbrakk> \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, j) = reduce a b D A $$ (i, j) [PROOF STEP] have im: "i<m+n" [PROOF STATE] proof (prove) goal (1 subgoal): 1. i < m + n [PROOF STEP] using A i reduce_preserves_dimensions(1) [PROOF STATE] proof (prove) using this: A \<in> carrier_mat (m + n) n i < dim_row (reduce a b D A) dim_row (reduce ?a ?b ?D ?A) = dim_row ?A goal (1 subgoal): 1. i < m + n [PROOF STEP] by auto [PROOF STATE] proof (state) this: i < m + n goal (1 subgoal): 1. \<And>i j. \<lbrakk>i < dim_row (reduce a b D A); j < dim_col (reduce a b D A)\<rbrakk> \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, j) = reduce a b D A $$ (i, j) [PROOF STEP] have ja_n: "ja<n" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ja < n [PROOF STEP] using A ja reduce_preserves_dimensions(2) [PROOF STATE] proof (prove) using this: A \<in> carrier_mat (m + n) n ja < dim_col (reduce a b D A) dim_col (reduce ?a ?b ?D ?A) = dim_col ?A goal (1 subgoal): 1. ja < n [PROOF STEP] by auto [PROOF STATE] proof (state) this: ja < n goal (1 subgoal): 1. \<And>i j. \<lbrakk>i < dim_row (reduce a b D A); j < dim_col (reduce a b D A)\<rbrakk> \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, j) = reduce a b D A $$ (i, j) [PROOF STEP] show "?reduce_b $$ (i,ja) = (reduce a b D A) $$ (i,ja)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] proof (cases "(i\<noteq>a \<and> i\<noteq>b)") [PROOF STATE] proof (state) goal (2 subgoals): 1. i \<noteq> a \<and> i \<noteq> b \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. \<not> (i \<noteq> a \<and> i \<noteq> b) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] case True [PROOF STATE] proof (state) this: i \<noteq> a \<and> i \<noteq> b goal (2 subgoals): 1. i \<noteq> a \<and> i \<noteq> b \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. \<not> (i \<noteq> a \<and> i \<noteq> b) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have "?reduce_b $$ (i,ja) = ?reduce_a $$ (i,ja)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) [PROOF STEP] unfolding reduce_b_eq [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat (dim_row (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) (dim_col (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) (\<lambda>(i, k). if i = b \<and> k \<in> set ys then if k = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) then D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) gmod D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k)) $$ (i, ja) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) [PROOF STEP] by (smt True dr_eq dc_eq i index_mat(1) ja prod.simps(2) reduce_row_mod_D_preserves_dimensions) [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) goal (2 subgoals): 1. i \<noteq> a \<and> i \<noteq> b \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. \<not> (i \<noteq> a \<and> i \<noteq> b) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] also [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) goal (2 subgoals): 1. i \<noteq> a \<and> i \<noteq> b \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. \<not> (i \<noteq> a \<and> i \<noteq> b) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have "... = ?A $$ (i,ja)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) [PROOF STEP] by (smt A True carrier_matD(2) dim_col_mat(1) dim_row_mat(1) i index_mat(1) ja_n reduce_a_eq reduce_preserves_dimensions(1) split_conv) [PROOF STATE] proof (state) this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) goal (2 subgoals): 1. i \<noteq> a \<and> i \<noteq> b \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. \<not> (i \<noteq> a \<and> i \<noteq> b) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] also [PROOF STATE] proof (state) this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) goal (2 subgoals): 1. i \<noteq> a \<and> i \<noteq> b \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. \<not> (i \<noteq> a \<and> i \<noteq> b) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have "... = A $$ (i,ja)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) = A $$ (i, ja) [PROOF STEP] using A True im ja_n [PROOF STATE] proof (prove) using this: A \<in> carrier_mat (m + n) n i \<noteq> a \<and> i \<noteq> b i < m + n ja < n goal (1 subgoal): 1. Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) = A $$ (i, ja) [PROOF STEP] by auto [PROOF STATE] proof (state) this: Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) = A $$ (i, ja) goal (2 subgoals): 1. i \<noteq> a \<and> i \<noteq> b \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. \<not> (i \<noteq> a \<and> i \<noteq> b) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] also [PROOF STATE] proof (state) this: Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) = A $$ (i, ja) goal (2 subgoals): 1. i \<noteq> a \<and> i \<noteq> b \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. \<not> (i \<noteq> a \<and> i \<noteq> b) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have "... = (reduce a b D A) $$ (i,ja)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. A $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] unfolding reduce_alt_def_not0[OF Aaj pquvd] [PROOF STATE] proof (prove) goal (1 subgoal): 1. A $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then let r = p * A $$ (a, k) + q * A $$ (b, k) in if k = 0 then if D dvd r then D else r else r gmod D else if i = b then let r = u * A $$ (a, k) + v * A $$ (b, k) in if k = 0 then r else r gmod D else A $$ (i, k)) $$ (i, ja) [PROOF STEP] using im ja_n A True [PROOF STATE] proof (prove) using this: i < m + n ja < n A \<in> carrier_mat (m + n) n i \<noteq> a \<and> i \<noteq> b goal (1 subgoal): 1. A $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then let r = p * A $$ (a, k) + q * A $$ (b, k) in if k = 0 then if D dvd r then D else r else r gmod D else if i = b then let r = u * A $$ (a, k) + v * A $$ (b, k) in if k = 0 then r else r gmod D else A $$ (i, k)) $$ (i, ja) [PROOF STEP] by auto [PROOF STATE] proof (state) this: A $$ (i, ja) = reduce a b D A $$ (i, ja) goal (2 subgoals): 1. i \<noteq> a \<and> i \<noteq> b \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. \<not> (i \<noteq> a \<and> i \<noteq> b) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] . [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) goal (1 subgoal): 1. \<not> (i \<noteq> a \<and> i \<noteq> b) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<not> (i \<noteq> a \<and> i \<noteq> b) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] case False [PROOF STATE] proof (state) this: \<not> (i \<noteq> a \<and> i \<noteq> b) goal (1 subgoal): 1. \<not> (i \<noteq> a \<and> i \<noteq> b) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] note a_or_b = False [PROOF STATE] proof (state) this: \<not> (i \<noteq> a \<and> i \<noteq> b) goal (1 subgoal): 1. \<not> (i \<noteq> a \<and> i \<noteq> b) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] proof (cases "i=a") [PROOF STATE] proof (state) goal (2 subgoals): 1. i = a \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. i \<noteq> a \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] case True [PROOF STATE] proof (state) this: i = a goal (2 subgoals): 1. i = a \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. i \<noteq> a \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] note ia = True [PROOF STATE] proof (state) this: i = a goal (2 subgoals): 1. i = a \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. i \<noteq> a \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] hence i_not_b: "i\<noteq>b" [PROOF STATE] proof (prove) using this: i = a goal (1 subgoal): 1. i \<noteq> b [PROOF STEP] using ab [PROOF STATE] proof (prove) using this: i = a a \<noteq> b goal (1 subgoal): 1. i \<noteq> b [PROOF STEP] by auto [PROOF STATE] proof (state) this: i \<noteq> b goal (2 subgoals): 1. i = a \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. i \<noteq> a \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have ja_in_xs: "ja \<in> set xs" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ja \<in> set xs [PROOF STEP] unfolding xs_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. ja \<in> set [0..<n] [PROOF STEP] using True ja_n im a A [PROOF STATE] proof (prove) using this: i = a ja < n i < m + n a < m A \<in> carrier_mat (m + n) n goal (1 subgoal): 1. ja \<in> set [0..<n] [PROOF STEP] unfolding set_filter [PROOF STATE] proof (prove) using this: i = a ja < n i < m + n a < m A \<in> carrier_mat (m + n) n goal (1 subgoal): 1. ja \<in> set [0..<n] [PROOF STEP] by auto [PROOF STATE] proof (state) this: ja \<in> set xs goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have 1: "?reduce_b $$ (i,ja) = ?reduce_a $$ (i,ja)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) [PROOF STEP] unfolding reduce_b_eq [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat (dim_row (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) (dim_col (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) (\<lambda>(i, k). if i = b \<and> k \<in> set ys then if k = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) then D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) gmod D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k)) $$ (i, ja) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) [PROOF STEP] by (smt ab dc_eq dim_row_mat(1) dr_eq i ia index_mat(1) ja prod.simps(2) reduce_b_eq reduce_row_mod_D_preserves_dimensions(2)) [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] proof (cases "ja = 0 \<and> D dvd p*A$$(a,ja) + q*A$$(b,ja)") [PROOF STATE] proof (state) goal (2 subgoals): 1. ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. \<not> (ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja)) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] case True [PROOF STATE] proof (state) this: ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja) goal (2 subgoals): 1. ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. \<not> (ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja)) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have "?reduce_a $$ (i,ja) = D" [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = D [PROOF STEP] unfolding reduce_a_eq [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) $$ (i, ja) = D [PROOF STEP] using True ab a_or_b i_not_b ja_n im a A ja_in_xs False [PROOF STATE] proof (prove) using this: ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja) a \<noteq> b \<not> (i \<noteq> a \<and> i \<noteq> b) i \<noteq> b ja < n i < m + n a < m A \<in> carrier_mat (m + n) n ja \<in> set xs \<not> (i \<noteq> a \<and> i \<noteq> b) goal (1 subgoal): 1. Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) $$ (i, ja) = D [PROOF STEP] by auto [PROOF STATE] proof (state) this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = D goal (2 subgoals): 1. ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. \<not> (ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja)) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] also [PROOF STATE] proof (state) this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = D goal (2 subgoals): 1. ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. \<not> (ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja)) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have "... = (reduce a b D A) $$ (i,ja)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. D = reduce a b D A $$ (i, ja) [PROOF STEP] unfolding reduce_alt_def_not0[OF Aaj pquvd] [PROOF STATE] proof (prove) goal (1 subgoal): 1. D = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then let r = p * A $$ (a, k) + q * A $$ (b, k) in if k = 0 then if D dvd r then D else r else r gmod D else if i = b then let r = u * A $$ (a, k) + v * A $$ (b, k) in if k = 0 then r else r gmod D else A $$ (i, k)) $$ (i, ja) [PROOF STEP] using True a_or_b i_not_b ja_n im A False [PROOF STATE] proof (prove) using this: ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja) \<not> (i \<noteq> a \<and> i \<noteq> b) i \<noteq> b ja < n i < m + n A \<in> carrier_mat (m + n) n \<not> (i \<noteq> a \<and> i \<noteq> b) goal (1 subgoal): 1. D = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then let r = p * A $$ (a, k) + q * A $$ (b, k) in if k = 0 then if D dvd r then D else r else r gmod D else if i = b then let r = u * A $$ (a, k) + v * A $$ (b, k) in if k = 0 then r else r gmod D else A $$ (i, k)) $$ (i, ja) [PROOF STEP] by auto [PROOF STATE] proof (state) this: D = reduce a b D A $$ (i, ja) goal (2 subgoals): 1. ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. \<not> (ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja)) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = reduce a b D A $$ (i, ja) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] using 1 [PROOF STATE] proof (prove) using this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = reduce a b D A $$ (i, ja) reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] by simp [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) goal (1 subgoal): 1. \<not> (ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja)) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<not> (ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja)) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] case False [PROOF STATE] proof (state) this: \<not> (ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja)) goal (1 subgoal): 1. \<not> (ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja)) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] note nc1 = False [PROOF STATE] proof (state) this: \<not> (ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja)) goal (1 subgoal): 1. \<not> (ja = 0 \<and> D dvd p * A $$ (a, ja) + q * A $$ (b, ja)) \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] proof (cases "ja=0") [PROOF STATE] proof (state) goal (2 subgoals): 1. ja = 0 \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. ja \<noteq> 0 \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] case True [PROOF STATE] proof (state) this: ja = 0 goal (2 subgoals): 1. ja = 0 \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. ja \<noteq> 0 \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: ja = 0 [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: ja = 0 goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] by (smt (z3) "1" A assms(3) assms(7) dim_col_mat(1) dim_row_mat(1) euclid_ext2_works i ia im index_mat(1) ja ja_in_xs old.prod.case pquvd reduce_gcd reduce_preserves_dimensions reduce_a_eq) [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) goal (1 subgoal): 1. ja \<noteq> 0 \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. ja \<noteq> 0 \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] case False [PROOF STATE] proof (state) this: ja \<noteq> 0 goal (1 subgoal): 1. ja \<noteq> 0 \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have "?reduce_a $$ (i,ja) = ?A $$ (i, ja) gmod D" [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D [PROOF STEP] unfolding reduce_a_eq [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D [PROOF STEP] using True ab a_or_b i_not_b ja_n im a A ja_in_xs False [PROOF STATE] proof (prove) using this: i = a a \<noteq> b \<not> (i \<noteq> a \<and> i \<noteq> b) i \<noteq> b ja < n i < m + n a < m A \<in> carrier_mat (m + n) n ja \<in> set xs ja \<noteq> 0 goal (1 subgoal): 1. Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D [PROOF STEP] by auto [PROOF STATE] proof (state) this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D goal (1 subgoal): 1. ja \<noteq> 0 \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] also [PROOF STATE] proof (state) this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D goal (1 subgoal): 1. ja \<noteq> 0 \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have "... = (reduce a b D A) $$ (i,ja)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D = reduce a b D A $$ (i, ja) [PROOF STEP] unfolding reduce_alt_def_not0[OF Aaj pquvd] [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then let r = p * A $$ (a, k) + q * A $$ (b, k) in if k = 0 then if D dvd r then D else r else r gmod D else if i = b then let r = u * A $$ (a, k) + v * A $$ (b, k) in if k = 0 then r else r gmod D else A $$ (i, k)) $$ (i, ja) [PROOF STEP] using True a_or_b i_not_b ja_n im A False [PROOF STATE] proof (prove) using this: i = a \<not> (i \<noteq> a \<and> i \<noteq> b) i \<noteq> b ja < n i < m + n A \<in> carrier_mat (m + n) n ja \<noteq> 0 goal (1 subgoal): 1. Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then let r = p * A $$ (a, k) + q * A $$ (b, k) in if k = 0 then if D dvd r then D else r else r gmod D else if i = b then let r = u * A $$ (a, k) + v * A $$ (b, k) in if k = 0 then r else r gmod D else A $$ (i, k)) $$ (i, ja) [PROOF STEP] by auto [PROOF STATE] proof (state) this: Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D = reduce a b D A $$ (i, ja) goal (1 subgoal): 1. ja \<noteq> 0 \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = reduce a b D A $$ (i, ja) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] using 1 [PROOF STATE] proof (prove) using this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = reduce a b D A $$ (i, ja) reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] by simp [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) goal (1 subgoal): 1. i \<noteq> a \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. i \<noteq> a \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] case False [PROOF STATE] proof (state) this: i \<noteq> a goal (1 subgoal): 1. i \<noteq> a \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] note i_not_a = False [PROOF STATE] proof (state) this: i \<noteq> a goal (1 subgoal): 1. i \<noteq> a \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have i_drb: "i<dim_row ?reduce_b" and i_dra: "i<dim_row ?reduce_a" and ja_drb: "ja < dim_col ?reduce_b" and ja_dra: "ja < dim_col ?reduce_a" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (i < dim_row (reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m) &&& i < dim_row (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) &&& ja < dim_col (reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m) &&& ja < dim_col (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) [PROOF STEP] using reduce_carrier[OF A] i ja A dr_eq dc_eq [PROOF STATE] proof (prove) using this: reduce ?a ?b ?D A \<in> carrier_mat (m + n) n reduce_abs ?a ?b ?D A \<in> carrier_mat (m + n) n i < dim_row (reduce a b D A) ja < dim_col (reduce a b D A) A \<in> carrier_mat (m + n) n dim_row (reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m) = dim_row (reduce a b D A) dim_col (reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m) = dim_col (reduce a b D A) goal (1 subgoal): 1. (i < dim_row (reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m) &&& i < dim_row (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) &&& ja < dim_col (reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m) &&& ja < dim_col (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) [PROOF STEP] by auto [PROOF STATE] proof (state) this: i < dim_row (reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m) i < dim_row (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) ja < dim_col (reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m) ja < dim_col (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) goal (1 subgoal): 1. i \<noteq> a \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have ib: "i=b" [PROOF STATE] proof (prove) goal (1 subgoal): 1. i = b [PROOF STEP] using False a_or_b [PROOF STATE] proof (prove) using this: i \<noteq> a \<not> (i \<noteq> a \<and> i \<noteq> b) goal (1 subgoal): 1. i = b [PROOF STEP] by auto [PROOF STATE] proof (state) this: i = b goal (1 subgoal): 1. i \<noteq> a \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] proof (cases "ja \<in> set ys") [PROOF STATE] proof (state) goal (2 subgoals): 1. ja \<in> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] case True [PROOF STATE] proof (state) this: ja \<in> set ys goal (2 subgoals): 1. ja \<in> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] note ja_in_ys = True [PROOF STATE] proof (state) this: ja \<in> set ys goal (2 subgoals): 1. ja \<in> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] hence ja_not0: "ja \<noteq> 0" [PROOF STATE] proof (prove) using this: ja \<in> set ys goal (1 subgoal): 1. ja \<noteq> 0 [PROOF STEP] unfolding ys_def [PROOF STATE] proof (prove) using this: ja \<in> set [1..<n] goal (1 subgoal): 1. ja \<noteq> 0 [PROOF STEP] by auto [PROOF STATE] proof (state) this: ja \<noteq> 0 goal (2 subgoals): 1. ja \<in> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have "?reduce_b $$ (i,ja) = (if ja = 0 then if D dvd ?reduce_a$$(i,ja) then D else ?reduce_a $$ (i, ja) else ?reduce_a $$ (i, ja) gmod D)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = (if ja = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) then D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) gmod D) [PROOF STEP] unfolding reduce_b_eq [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat (dim_row (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) (dim_col (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) (\<lambda>(i, k). if i = b \<and> k \<in> set ys then if k = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) then D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) gmod D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k)) $$ (i, ja) = (if ja = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) then D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) gmod D) [PROOF STEP] using i_not_a True ja ja_in_ys [PROOF STATE] proof (prove) using this: i \<noteq> a ja \<in> set ys ja < dim_col (reduce a b D A) ja \<in> set ys goal (1 subgoal): 1. Matrix.mat (dim_row (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) (dim_col (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) (\<lambda>(i, k). if i = b \<and> k \<in> set ys then if k = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) then D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) gmod D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k)) $$ (i, ja) = (if ja = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) then D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) gmod D) [PROOF STEP] by (smt i_dra ja_dra a_or_b index_mat(1) prod.simps(2)) [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = (if ja = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) then D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) gmod D) goal (2 subgoals): 1. ja \<in> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] also [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = (if ja = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) then D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) gmod D) goal (2 subgoals): 1. ja \<in> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have "... = (if ja = 0 then if D dvd ?reduce_a$$(i,ja) then D else ?A $$ (i, ja) else ?A $$ (i, ja) gmod D)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (if ja = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) then D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) gmod D) = (if ja = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D) [PROOF STEP] unfolding reduce_a_eq [PROOF STATE] proof (prove) goal (1 subgoal): 1. (if ja = 0 then if D dvd Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) $$ (i, ja) then D else Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) $$ (i, ja) else Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) $$ (i, ja) gmod D) = (if ja = 0 then if D dvd Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) $$ (i, ja) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D) [PROOF STEP] using True ab a_or_b ib False ja_n im a A ja_in_ys [PROOF STATE] proof (prove) using this: ja \<in> set ys a \<noteq> b \<not> (i \<noteq> a \<and> i \<noteq> b) i = b i \<noteq> a ja < n i < m + n a < m A \<in> carrier_mat (m + n) n ja \<in> set ys goal (1 subgoal): 1. (if ja = 0 then if D dvd Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) $$ (i, ja) then D else Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) $$ (i, ja) else Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) $$ (i, ja) gmod D) = (if ja = 0 then if D dvd Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) $$ (i, ja) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D) [PROOF STEP] by auto [PROOF STATE] proof (state) this: (if ja = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) then D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) gmod D) = (if ja = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D) goal (2 subgoals): 1. ja \<in> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] also [PROOF STATE] proof (state) this: (if ja = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) then D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) gmod D) = (if ja = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D) goal (2 subgoals): 1. ja \<in> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have "... = (reduce a b D A) $$ (i,ja)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (if ja = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D) = reduce a b D A $$ (i, ja) [PROOF STEP] unfolding reduce_alt_def_not0[OF Aaj pquvd] [PROOF STATE] proof (prove) goal (1 subgoal): 1. (if ja = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then let r = p * A $$ (a, k) + q * A $$ (b, k) in if k = 0 then if D dvd r then D else r else r gmod D else if i = b then let r = u * A $$ (a, k) + v * A $$ (b, k) in if k = 0 then r else r gmod D else A $$ (i, k)) $$ (i, ja) [PROOF STEP] using True ja_not0 False a_or_b ib ja_n im A [PROOF STATE] proof (prove) using this: ja \<in> set ys ja \<noteq> 0 i \<noteq> a \<not> (i \<noteq> a \<and> i \<noteq> b) i = b ja < n i < m + n A \<in> carrier_mat (m + n) n goal (1 subgoal): 1. (if ja = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then let r = p * A $$ (a, k) + q * A $$ (b, k) in if k = 0 then if D dvd r then D else r else r gmod D else if i = b then let r = u * A $$ (a, k) + v * A $$ (b, k) in if k = 0 then r else r gmod D else A $$ (i, k)) $$ (i, ja) [PROOF STEP] using i_not_a [PROOF STATE] proof (prove) using this: ja \<in> set ys ja \<noteq> 0 i \<noteq> a \<not> (i \<noteq> a \<and> i \<noteq> b) i = b ja < n i < m + n A \<in> carrier_mat (m + n) n i \<noteq> a goal (1 subgoal): 1. (if ja = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then let r = p * A $$ (a, k) + q * A $$ (b, k) in if k = 0 then if D dvd r then D else r else r gmod D else if i = b then let r = u * A $$ (a, k) + v * A $$ (b, k) in if k = 0 then r else r gmod D else A $$ (i, k)) $$ (i, ja) [PROOF STEP] by auto [PROOF STATE] proof (state) this: (if ja = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) gmod D) = reduce a b D A $$ (i, ja) goal (2 subgoals): 1. ja \<in> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) 2. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] . [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) goal (1 subgoal): 1. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] case False [PROOF STATE] proof (state) this: ja \<notin> set ys goal (1 subgoal): 1. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] hence ja0:"ja = 0" [PROOF STATE] proof (prove) using this: ja \<notin> set ys goal (1 subgoal): 1. ja = 0 [PROOF STEP] using ja_n [PROOF STATE] proof (prove) using this: ja \<notin> set ys ja < n goal (1 subgoal): 1. ja = 0 [PROOF STEP] unfolding ys_def [PROOF STATE] proof (prove) using this: ja \<notin> set [1..<n] ja < n goal (1 subgoal): 1. ja = 0 [PROOF STEP] by auto [PROOF STATE] proof (state) this: ja = 0 goal (1 subgoal): 1. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have rw0: "u * A $$ (a, ja) + v * A $$ (b, ja) = 0" [PROOF STATE] proof (prove) goal (1 subgoal): 1. u * A $$ (a, ja) + v * A $$ (b, ja) = 0 [PROOF STEP] unfolding euclid_ext2_works[OF pquvd[symmetric]] ja0 [PROOF STATE] proof (prove) goal (1 subgoal): 1. - A $$ (b, 0) div gcd (A $$ (a, 0)) (A $$ (b, 0)) * A $$ (a, 0) + A $$ (a, 0) div gcd (A $$ (a, 0)) (A $$ (b, 0)) * A $$ (b, 0) = 0 [PROOF STEP] by (smt euclid_ext2_works[OF pquvd[symmetric]] more_arith_simps(11) mult.commute mult_minus_left) [PROOF STATE] proof (state) this: u * A $$ (a, ja) + v * A $$ (b, ja) = 0 goal (1 subgoal): 1. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have "?reduce_b $$ (i,ja) = ?reduce_a $$ (i,ja)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) [PROOF STEP] unfolding reduce_b_eq [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat (dim_row (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) (dim_col (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m)) (\<lambda>(i, k). if i = b \<and> k \<in> set ys then if k = 0 then if D dvd reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) then D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k) gmod D else reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, k)) $$ (i, ja) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) [PROOF STEP] by (smt False a_or_b dc_eq dim_row_mat(1) dr_eq i index_mat(1) ja prod.simps(2) reduce_b_eq reduce_row_mod_D_preserves_dimensions(2)) [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) goal (1 subgoal): 1. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] also [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) goal (1 subgoal): 1. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have "... = ?A $$ (i, ja)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) [PROOF STEP] unfolding reduce_a_eq [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) [PROOF STEP] using False ab a_or_b i_not_a ja_n im a A [PROOF STATE] proof (prove) using this: ja \<notin> set ys a \<noteq> b \<not> (i \<noteq> a \<and> i \<noteq> b) i \<noteq> a ja < n i < m + n a < m A \<in> carrier_mat (m + n) n goal (1 subgoal): 1. Matrix.mat (dim_row (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (dim_col (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)))) (\<lambda>(i, k). if i = a \<and> k \<in> set xs then if k = 0 then if D dvd Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) then D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k) gmod D else Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, k)) $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) [PROOF STEP] by auto [PROOF STATE] proof (state) this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) goal (1 subgoal): 1. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] also [PROOF STATE] proof (state) this: reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m $$ (i, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) goal (1 subgoal): 1. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have "... = u * A $$ (a, ja) + v * A $$ (b, ja)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) = u * A $$ (a, ja) + v * A $$ (b, ja) [PROOF STEP] by (smt (verit, ccfv_SIG) A \<open>ja = 0\<close> assms(3) assms(5) carrier_matD(2) i ib index_mat(1) old.prod.case reduce_preserves_dimensions(1)) [PROOF STATE] proof (state) this: Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) = u * A $$ (a, ja) + v * A $$ (b, ja) goal (1 subgoal): 1. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] also [PROOF STATE] proof (state) this: Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) $$ (i, ja) = u * A $$ (a, ja) + v * A $$ (b, ja) goal (1 subgoal): 1. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] have "... = (reduce a b D A) $$ (i,ja)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. u * A $$ (a, ja) + v * A $$ (b, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] unfolding reduce_alt_def_not0[OF Aaj pquvd] [PROOF STATE] proof (prove) goal (1 subgoal): 1. u * A $$ (a, ja) + v * A $$ (b, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then let r = p * A $$ (a, k) + q * A $$ (b, k) in if k = 0 then if D dvd r then D else r else r gmod D else if i = b then let r = u * A $$ (a, k) + v * A $$ (b, k) in if k = 0 then r else r gmod D else A $$ (i, k)) $$ (i, ja) [PROOF STEP] using False a_or_b i_not_a ja_n im A ja0 [PROOF STATE] proof (prove) using this: ja \<notin> set ys \<not> (i \<noteq> a \<and> i \<noteq> b) i \<noteq> a ja < n i < m + n A \<in> carrier_mat (m + n) n ja = 0 goal (1 subgoal): 1. u * A $$ (a, ja) + v * A $$ (b, ja) = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then let r = p * A $$ (a, k) + q * A $$ (b, k) in if k = 0 then if D dvd r then D else r else r gmod D else if i = b then let r = u * A $$ (a, k) + v * A $$ (b, k) in if k = 0 then r else r gmod D else A $$ (i, k)) $$ (i, ja) [PROOF STEP] by auto [PROOF STATE] proof (state) this: u * A $$ (a, ja) + v * A $$ (b, ja) = reduce a b D A $$ (i, ja) goal (1 subgoal): 1. ja \<notin> set ys \<Longrightarrow> reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) goal (1 subgoal): 1. reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) [PROOF STEP] . [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m $$ (i, ja) = reduce a b D A $$ (i, ja) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m = reduce a b D A goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] have inv_QPBM: "invertible_mat (Q * P * ?BM)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. invertible_mat (Q * P * bezout_matrix_JNF A a b 0 euclid_ext2) [PROOF STEP] by (meson BM P Q inv_P inv_Q invertible_bezout invertible_mult_JNF mult_carrier_mat) [PROOF STATE] proof (state) this: invertible_mat (Q * P * bezout_matrix_JNF A a b 0 euclid_ext2) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] moreover [PROOF STATE] proof (state) this: invertible_mat (Q * P * bezout_matrix_JNF A a b 0 euclid_ext2) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] have "(Q*P*?BM) \<in> carrier_mat (m + n) (m + n)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Q * P * bezout_matrix_JNF A a b 0 euclid_ext2 \<in> carrier_mat (m + n) (m + n) [PROOF STEP] using BM P Q [PROOF STATE] proof (prove) using this: bezout_matrix_JNF A a b 0 euclid_ext2 \<in> carrier_mat (m + n) (m + n) P \<in> carrier_mat (m + n) (m + n) Q \<in> carrier_mat (m + n) (m + n) goal (1 subgoal): 1. Q * P * bezout_matrix_JNF A a b 0 euclid_ext2 \<in> carrier_mat (m + n) (m + n) [PROOF STEP] by auto [PROOF STATE] proof (state) this: Q * P * bezout_matrix_JNF A a b 0 euclid_ext2 \<in> carrier_mat (m + n) (m + n) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] moreover [PROOF STATE] proof (state) this: Q * P * bezout_matrix_JNF A a b 0 euclid_ext2 \<in> carrier_mat (m + n) (m + n) goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] have "(reduce a b D A) = (Q*P*?BM) * A" [PROOF STATE] proof (prove) goal (1 subgoal): 1. reduce a b D A = Q * P * bezout_matrix_JNF A a b 0 euclid_ext2 * A [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. reduce a b D A = Q * P * bezout_matrix_JNF A a b 0 euclid_ext2 * A [PROOF STEP] have "?BM * A = ?A" [PROOF STATE] proof (prove) goal (1 subgoal): 1. bezout_matrix_JNF A a b 0 euclid_ext2 * A = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) [PROOF STEP] using A'_BZ_A [PROOF STATE] proof (prove) using this: Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) = bezout_matrix_JNF A a b 0 euclid_ext2 * A goal (1 subgoal): 1. bezout_matrix_JNF A a b 0 euclid_ext2 * A = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) [PROOF STEP] by auto [PROOF STATE] proof (state) this: bezout_matrix_JNF A a b 0 euclid_ext2 * A = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) goal (1 subgoal): 1. reduce a b D A = Q * P * bezout_matrix_JNF A a b 0 euclid_ext2 * A [PROOF STEP] hence "P * (?BM * A) = ?reduce_a" [PROOF STATE] proof (prove) using this: bezout_matrix_JNF A a b 0 euclid_ext2 * A = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) goal (1 subgoal): 1. P * (bezout_matrix_JNF A a b 0 euclid_ext2 * A) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m [PROOF STEP] using reduce_a_PA [PROOF STATE] proof (prove) using this: bezout_matrix_JNF A a b 0 euclid_ext2 * A = Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m = P * Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k)) goal (1 subgoal): 1. P * (bezout_matrix_JNF A a b 0 euclid_ext2 * A) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m [PROOF STEP] by auto [PROOF STATE] proof (state) this: P * (bezout_matrix_JNF A a b 0 euclid_ext2 * A) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m goal (1 subgoal): 1. reduce a b D A = Q * P * bezout_matrix_JNF A a b 0 euclid_ext2 * A [PROOF STEP] hence "Q * (P * (?BM * A)) = ?reduce_b" [PROOF STATE] proof (prove) using this: P * (bezout_matrix_JNF A a b 0 euclid_ext2 * A) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m goal (1 subgoal): 1. Q * (P * (bezout_matrix_JNF A a b 0 euclid_ext2 * A)) = reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m [PROOF STEP] using reduce_b_Q_reduce [PROOF STATE] proof (prove) using this: P * (bezout_matrix_JNF A a b 0 euclid_ext2 * A) = reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m = Q * reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m goal (1 subgoal): 1. Q * (P * (bezout_matrix_JNF A a b 0 euclid_ext2 * A)) = reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m [PROOF STEP] by auto [PROOF STATE] proof (state) this: Q * (P * (bezout_matrix_JNF A a b 0 euclid_ext2 * A)) = reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m goal (1 subgoal): 1. reduce a b D A = Q * P * bezout_matrix_JNF A a b 0 euclid_ext2 * A [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: Q * (P * (bezout_matrix_JNF A a b 0 euclid_ext2 * A)) = reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m goal (1 subgoal): 1. reduce a b D A = Q * P * bezout_matrix_JNF A a b 0 euclid_ext2 * A [PROOF STEP] using reduce_b_eq_reduce [PROOF STATE] proof (prove) using this: Q * (P * (bezout_matrix_JNF A a b 0 euclid_ext2 * A)) = reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m reduce_row_mod_D (reduce_row_mod_D (Matrix.mat (dim_row A) (dim_col A) (\<lambda>(i, k). if i = a then p * A $$ (a, k) + q * A $$ (b, k) else if i = b then u * A $$ (a, k) + v * A $$ (b, k) else A $$ (i, k))) a xs D m) b ys D m = reduce a b D A goal (1 subgoal): 1. reduce a b D A = Q * P * bezout_matrix_JNF A a b 0 euclid_ext2 * A [PROOF STEP] by (smt A A'_BZ_A A_carrier BM P Q assoc_mult_mat mn mult_carrier_mat reduce_a_PA) [PROOF STATE] proof (state) this: reduce a b D A = Q * P * bezout_matrix_JNF A a b 0 euclid_ext2 * A goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: reduce a b D A = Q * P * bezout_matrix_JNF A a b 0 euclid_ext2 * A goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: invertible_mat (Q * P * bezout_matrix_JNF A a b 0 euclid_ext2) Q * P * bezout_matrix_JNF A a b 0 euclid_ext2 \<in> carrier_mat (m + n) (m + n) reduce a b D A = Q * P * bezout_matrix_JNF A a b 0 euclid_ext2 * A [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: invertible_mat (Q * P * bezout_matrix_JNF A a b 0 euclid_ext2) Q * P * bezout_matrix_JNF A a b 0 euclid_ext2 \<in> carrier_mat (m + n) (m + n) reduce a b D A = Q * P * bezout_matrix_JNF A a b 0 euclid_ext2 * A goal (1 subgoal): 1. \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A [PROOF STEP] by blast [PROOF STATE] proof (state) this: \<exists>P. invertible_mat P \<and> P \<in> carrier_mat (m + n) (m + n) \<and> reduce a b D A = P * A goal: No subgoals! [PROOF STEP] qed
State Before: F : Type ?u.306605 α : Type u β : Type v γ : Type w inst✝² : TopologicalSpace α inst✝¹ : PseudoMetricSpace β inst✝ : PseudoMetricSpace γ f g : α →ᵇ β x : α C : ℝ ⊢ dist f g = ⨆ (x : α), dist (↑f x) (↑g x) State After: case inl F : Type ?u.306605 α : Type u β : Type v γ : Type w inst✝² : TopologicalSpace α inst✝¹ : PseudoMetricSpace β inst✝ : PseudoMetricSpace γ f g : α →ᵇ β x : α C : ℝ h✝ : IsEmpty α ⊢ dist f g = ⨆ (x : α), dist (↑f x) (↑g x) case inr F : Type ?u.306605 α : Type u β : Type v γ : Type w inst✝² : TopologicalSpace α inst✝¹ : PseudoMetricSpace β inst✝ : PseudoMetricSpace γ f g : α →ᵇ β x : α C : ℝ h✝ : Nonempty α ⊢ dist f g = ⨆ (x : α), dist (↑f x) (↑g x) Tactic: cases isEmpty_or_nonempty α State Before: case inr F : Type ?u.306605 α : Type u β : Type v γ : Type w inst✝² : TopologicalSpace α inst✝¹ : PseudoMetricSpace β inst✝ : PseudoMetricSpace γ f g : α →ᵇ β x : α C : ℝ h✝ : Nonempty α ⊢ dist f g = ⨆ (x : α), dist (↑f x) (↑g x) State After: case inr F : Type ?u.306605 α : Type u β : Type v γ : Type w inst✝² : TopologicalSpace α inst✝¹ : PseudoMetricSpace β inst✝ : PseudoMetricSpace γ f g : α →ᵇ β x : α C : ℝ h✝ : Nonempty α ⊢ BddAbove (range fun x => dist (↑f x) (↑g x)) Tactic: refine' (dist_le_iff_of_nonempty.mpr <| le_ciSup _).antisymm (ciSup_le dist_coe_le_dist) State Before: case inr F : Type ?u.306605 α : Type u β : Type v γ : Type w inst✝² : TopologicalSpace α inst✝¹ : PseudoMetricSpace β inst✝ : PseudoMetricSpace γ f g : α →ᵇ β x : α C : ℝ h✝ : Nonempty α ⊢ BddAbove (range fun x => dist (↑f x) (↑g x)) State After: no goals Tactic: exact dist_set_exists.imp fun C hC => forall_range_iff.2 hC.2 State Before: case inl F : Type ?u.306605 α : Type u β : Type v γ : Type w inst✝² : TopologicalSpace α inst✝¹ : PseudoMetricSpace β inst✝ : PseudoMetricSpace γ f g : α →ᵇ β x : α C : ℝ h✝ : IsEmpty α ⊢ dist f g = ⨆ (x : α), dist (↑f x) (↑g x) State After: no goals Tactic: rw [iSup_of_empty', Real.sSup_empty, dist_zero_of_empty]
{-# OPTIONS --without-K #-} {- In this module, we derive the truncations of * a truncated type, * the unit type, * dependent sums (and product types), * path spaces given truncations of their components. More commonly later on, we will be given a truncation operator Tr that returns a truncation for any given input type (at a fixed level). Instead of trying to show, say, Tr (Σ A (B ∘ cons (Tr A))) ≃ Σ (Tr A) (Tr ∘ B), directly, it turns out to be much easier to just *derive* the truncation on the left-hand side from Tr A and Tr ∘ B and then use unicity of truncation to deduce the above equivalence. Significant parts of the unicity proof would be duplicated in any direct proof of equivalence, while this approach allows us to avoid a number of manual elimination and propositional reduction steps. -} module Universe.Trunc.TypeConstructors where open import lib.Basics open import lib.NType2 open import lib.Equivalences2 open import lib.types.Unit open import lib.types.Nat hiding (_+_) open import lib.types.Pi open import lib.types.Sigma open import lib.types.Paths open import Universe.Utility.General open import Universe.Utility.TruncUniverse open import Universe.Trunc.Universal open import Universe.Trunc.Basics open trunc-ty open trunc-props module trunc-self {i} {n : ℕ₋₂} (A : n -Type i) where trunc : ∀ {j} → trunc-ty n ⟦ A ⟧ j trunc = record { type = A ; cons = idf _ ; univ = λ _ → snd (ide _) } module trunc-⊤ {n : ℕ₋₂} = trunc-self {n = n} ⊤-≤ -- *** Lemma 6.9 *** {- The truncation of a dependent sum type (where the family depends only on the truncation of the first component) is the dependent sums of the truncations. -} module trunc-Σ {ia ib j} {n : ℕ₋₂} {A : Type ia} (TrA : trunc-ty n A (ia ⊔ ib ⊔ j)) {B : ⟦ type TrA ⟧ → Type ib} (TrB : (ta : ⟦ type TrA ⟧) → trunc-ty n (B ta) (ib ⊔ j)) where trunc : trunc-ty n (Σ A (B ∘ cons TrA)) (ib ⊔ j) trunc = record { type = Σ-≤ (type TrA) (type ∘ TrB) ; cons = λ {(a , b) → (cons TrA a , cons (TrB (cons TrA a)) b)} ; univ = snd ∘ e } where e : (U : n -Type _) → _ e U = (⟦ Σ-≤ (type TrA) (type ∘ TrB) ⟧ → ⟦ U ⟧) ≃⟨ curry-equiv ⟩ ((ta : ⟦ type TrA ⟧) → ⟦ type (TrB ta) ⟧ → ⟦ U ⟧) ≃⟨ equiv-Π-r eb ⟩ ((ta : ⟦ type TrA ⟧) → B ta → ⟦ U ⟧) ≃⟨ ea ⟩ ((a : A) → B (cons TrA a) → ⟦ U ⟧) ≃⟨ curry-equiv ⁻¹ ⟩ (Σ A (B ∘ cons TrA) → ⟦ U ⟧) ≃∎ where ea = dup {j = ib ⊔ j} TrA (λ ta → B ta →-≤ U) eb = λ ta → up {j = ib ⊔ j} (TrB ta) U -- Products are a special case of dependent sums. module trunc-× {ia ib j} {n : ℕ₋₂} {A : Type ia} {B : Type ib} (TrA : trunc-ty n A (ia ⊔ ib ⊔ j)) (TrB : trunc-ty n B (ib ⊔ j)) = trunc-Σ {j = j} TrA (λ _ → TrB) -- *** Lemma 6.10 *** {- The n-truncation of a path space is the path space of the (n+1)-truncation. The use of the encode-decode method is the reason why we have to assume elimination into Type (lsucc i): large recursion is used to define the type of codes. -} module trunc-path {i j} {n : ℕ₋₂} {A : Type i} (TrA : trunc-ty (S n) A (lsucc (i ⊔ j))) where private l : ULevel l = i ⊔ j TrAA : trunc-ty (S n) (A × A) (lsucc l) TrAA = trunc-×.trunc {j = lsucc l} TrA TrA module MA = trunc-props {j = lsucc l} {k = l} TrA module MAA = trunc-props {j = lsucc l} {k = l} TrAA -- module MAL = trunc-elim {j = _} TrAA {- There is some Yoneda hidden here that would enable us to express the final equivalence e neatly as a sequence of trivial steps like in trunc-Σ; unfortunately we lack the necessary category theoretic framework in this code base. -} module code (U : n -Type l) where abstract {- Large recursion used here. Since we cannot talk about the truncation of a₀ == a₁ yet, we instead talk about the continuation type (a₀ == a₁ → U) → U for any n-type U instead. -} code : ⟦ type TrAA ⟧ → n -Type l code = rec {j = lsucc l} TrAA (n -Type-≤ l) (λ {(a₀ , a₁) → (a₀ == a₁ → ⟦ U ⟧) →-≤ U}) code-β : {a₀ a₁ : A} → ⟦ code (cons TrAA (a₀ , a₁)) ⟧ ≃ ((a₀ == a₁ → ⟦ U ⟧) → ⟦ U ⟧) code-β = coe-equiv (ap ⟦_⟧ (rec-β TrAA _)) -- We can encode a path in the truncation, ... encode : {ta₀ ta₁ : ⟦ type TrA ⟧} → ta₀ == ta₁ → ⟦ code (ta₀ , ta₁) ⟧ encode idp = MA.elim (λ ta → raise (code (ta , ta))) (λ _ → <– code-β (λ f → f idp)) _ --- ...reducing when coming from a path in the original type. encode-β : {a₀ a₁ : A} (p : a₀ == a₁) (f : a₀ == a₁ → ⟦ U ⟧) → –> code-β (encode (ap (cons TrA) p)) f == f p encode-β idp = app= (ap (–> code-β) (MA.elim-β _) ∙ <–-inv-r code-β _) -- We can decode into the U-continuation of a path in the truncation, ... decode : {ta₀ ta₁ : ⟦ type TrA ⟧} → ⟦ code (ta₀ , ta₁) ⟧ → (ta₀ == ta₁ → ⟦ U ⟧) → ⟦ U ⟧ decode = MAA.elim (λ {(ta₀ , ta₁) → _ →-≤ (ta₀ == ta₁ → ⟦ U ⟧) →-≤ raise U}) (λ _ c g → –> code-β c (g ∘ ap (cons TrA))) _ where -- ...reducing decode-β : {a₀ a₁ : A} (c : ⟦ code (cons TrAA (a₀ , a₁)) ⟧) (g : cons TrA a₀ == cons TrA a₁ → ⟦ U ⟧) → decode c g == –> code-β c (g ∘ ap (cons TrA)) decode-β = app= ∘ app= (MAA.elim-β _) -- encoding followed by decoding produces the expected continuation decode-encode : {ta₀ ta₁ : ⟦ type TrA ⟧} (q : ta₀ == ta₁) (g : ta₀ == ta₁ → ⟦ U ⟧) → decode (encode q) g == g q decode-encode idp = MA.elim (λ ta → Π-≤ (ta == ta → ⟦ U ⟧) (λ g → Path-≤ (raise U) (decode (encode idp) g) (g idp))) (λ _ g → decode-β (encode idp) g ∙ encode-β idp (g ∘ ap (cons TrA))) _ trunc : (a₀ a₁ : A) → trunc-ty n (a₀ == a₁) l trunc a₀ a₁ = record { type = Path-< (type TrA) (cons TrA a₀) (cons TrA a₁) ; cons = ap (cons TrA) ; univ = snd ∘ e } where e : (U : _) → (cons TrA a₀ == cons TrA a₁ → ⟦ U ⟧) ≃ (a₀ == a₁ → ⟦ U ⟧) e U = equiv u v u-v v-u where open code U u : (cons TrA a₀ == cons TrA a₁ → ⟦ U ⟧) → a₀ == a₁ → ⟦ U ⟧ u g = g ∘ ap (cons TrA) v : (a₀ == a₁ → ⟦ U ⟧) → cons TrA a₀ == cons TrA a₁ → ⟦ U ⟧ v f q = –> code-β (encode q) f u-v : (f : a₀ == a₁ → ⟦ U ⟧) → u (v f) == f u-v f = λ= (λ p → encode-β p f) v-u : (g : cons TrA a₀ == cons TrA a₁ → ⟦ U ⟧) → v (u g) == g v-u g = λ= (λ q → ! (decode-β (encode q) g) ∙ decode-encode q g)
Formal statement is: lemma dist_triangle_le: "dist x z + dist y z \<le> e \<Longrightarrow> dist x y \<le> e" Informal statement is: The distance between two points is less than or equal to the sum of the distances from each point to a third point.
% nlsS = getNLSStruct( extra, dispOn, zoom) % % extra.tVec : defining TIs % (not called TIVec because it looks too much like T1Vec) % extra.T1Vec : defining T1s % dispOn : 1 - display the struct at the end % 0 (or omitted) - no display % zoom : 1 (or omitted) - do a non-zoomed search % x>1 - do an iterative zoomed search (x-1) times (slower search) % NOTE: When zooming in, convergence is not guaranteed. % % Data Model : a + b*exp(-TI/T1) % % written by J. Barral, M. Etezadi-Amoli, E. Gudmundson, and N. Stikov, 2009 % (c) Board of Trustees, Leland Stanford Junior University function nlsS = getNLSStruct(extra, dispOn, zoom) nlsS.tVec = extra.tVec(:); nlsS.N = length(nlsS.tVec); nlsS.T1Vec = extra.T1Vec(:); nlsS.T1Start = nlsS.T1Vec(1); nlsS.T1Stop = nlsS.T1Vec(end); nlsS.T1Len = length(nlsS.T1Vec); % The search algorithm to be used nlsS.nlsAlg = 'grid'; % Grid search % Display the struct so that the user can see it went ok if nargin < 2 dispOn = 0; end % Set the number of times you zoom the grid search in, 1 = no zoom % Setting this greater than 1 will reduce the step size in the grid search % (and slow down the fit significantly) if nargin < 3 nlsS.nbrOfZoom = 2; else nlsS.nbrOfZoom = zoom; end if nlsS.nbrOfZoom > 1 nlsS.T1LenZ = 21; % Length of the zoomed search end if dispOn % Display the structure for inspection nlsS end % Set the help variables that can be precomputed: % alpha is 1/T1, % theExp is a matrix of exp(-TI/T1) for different TI and T1, % rhoNormVec is a vector containing the norm-squared of rho over TI, % where rho = exp(-TI/T1), for different T1's. switch(nlsS.nlsAlg) case{'grid'} alphaVec = 1./nlsS.T1Vec; nlsS.theExp = exp( -nlsS.tVec*alphaVec' ); nlsS.rhoNormVec = ... sum( nlsS.theExp.^2, 1)' - ... 1/nlsS.N*(sum(nlsS.theExp,1)').^2; end
open import Relation.Binary.PropositionalEquality using (_≡_; refl; sym) module AKS.Nat.WellFounded where open import AKS.Nat.Base using (ℕ; _+_; _∸_; _≤_; _<_; lte) open ℕ open import AKS.Nat.Properties using (+-identityʳ; +-suc; ∸-mono-<ˡ; ∸-mono-<ʳ; suc-injective) data Acc {A : Set} (_≺_ : A → A → Set) (bound : A) : Set where acc : (∀ {lower : A} → lower ≺ bound → Acc _≺_ lower) → Acc _≺_ bound subrelation : ∀ {A : Set} {B : Set} {_≺₁_ : A → A → Set} {_≺₂_ : B → B → Set} {f : B → A} {n : B} → (∀ {x y} → x ≺₂ y → f x ≺₁ f y) → Acc _≺₁_ (f n) → Acc _≺₂_ n subrelation ≺₂⇒≺₁ (acc down) = acc λ x≺₂n → subrelation ≺₂⇒≺₁ (down (≺₂⇒≺₁ x≺₂n)) data _≤ⁱ_ : ℕ → ℕ → Set where ≤-same : ∀ {n} → n ≤ⁱ n ≤-step : ∀ {n m} → n ≤ⁱ m → n ≤ⁱ suc m _<ⁱ_ : ℕ → ℕ → Set n <ⁱ m = suc n ≤ⁱ m <⇒<ⁱ : ∀ {n m} → n < m → n <ⁱ m <⇒<ⁱ {n} {m} (lte zero refl) rewrite +-identityʳ n = ≤-same <⇒<ⁱ {n} {m} (lte (suc k) refl) = ≤-step (<⇒<ⁱ (lte k (sym (+-suc n k)))) <-well-founded : ∀ {n} → Acc _<_ n <-well-founded {n} = wf₁ n where wf₁ : ∀ t → Acc _<_ t wf₂ : ∀ t b → b <ⁱ t → Acc _<_ b wf₁ t = acc λ {b} b<t → wf₂ t b (<⇒<ⁱ b<t) wf₂ (suc t) b ≤-same = wf₁ t wf₂ (suc t) b (≤-step b<ⁱt) = wf₂ t b b<ⁱt record [_,_] (low : ℕ) (high : ℕ) : Set where inductive constructor acc field downward : ∀ {mid} → low ≤ mid → mid < high → [ low , mid ] upward : ∀ {mid} → low < mid → mid ≤ high → [ mid , high ] binary-search : ∀ {n m} → [ n , m ] binary-search {n} {m} = loop n m <-well-founded where loop : ∀ low high → Acc _<_ (high ∸ low) → [ low , high ] loop low high (acc next) = acc (λ {mid} low≤mid mid<high → loop low mid (next {mid ∸ low} (∸-mono-<ˡ low≤mid mid<high))) (λ {mid} low<mid mid≤high → loop mid high (next {high ∸ mid} (∸-mono-<ʳ mid≤high low<mid))) open import AKS.Unsafe using (trustMe) record Interval : Set where constructor [_,_∣_] field inf : ℕ sup : ℕ inf≤sup : inf ≤ sup open Interval width : Interval → ℕ width i = sup i ∸ inf i data _⊂_ (i₁ : Interval) (i₂ : Interval) : Set where downward : inf i₂ ≤ inf i₁ → sup i₁ < sup i₂ → i₁ ⊂ i₂ upward : inf i₂ < inf i₁ → sup i₁ ≤ sup i₂ → i₁ ⊂ i₂ ∸-monoˡ-< : ∀ {l₁ h₁ l₂ h₂} → l₁ ≤ h₁ → l₂ ≤ h₂ → l₂ ≤ l₁ → h₁ < h₂ → h₁ ∸ l₁ < h₂ ∸ l₂ ∸-monoˡ-< {l₁} {h₁} {l₂} {h₂} l₁≤h₁ l₂≤h₂ l₂≤l₁ h₁<h₂ = lte ((h₂ ∸ l₂) ∸ suc (h₁ ∸ l₁)) trustMe -- TODO: EVIL ∸-monoʳ-< : ∀ {l₁ h₁ l₂ h₂} → l₁ ≤ h₁ → l₂ ≤ h₂ → l₂ < l₁ → h₁ ≤ h₂ → h₁ ∸ l₁ < h₂ ∸ l₂ ∸-monoʳ-< {l₁} {h₁} {l₂} {h₂} l₁≤h₁ l₂≤h₂ l₂<l₁ h₁≤h₂ = lte ((h₂ ∸ l₂) ∸ suc (h₁ ∸ l₁)) trustMe ⊂⇒< : ∀ {i₁ i₂} → i₁ ⊂ i₂ → width i₁ < width i₂ ⊂⇒< {[ inf-i₁ , sup-i₁ ∣ inf-i₁≤sup-i₁ ]} {[ inf-i₂ , sup-i₂ ∣ inf-i₂≤sup-i₂ ]} (downward inf-i₂≤inf-i₁ sup-i₁<sup-i₂) = ∸-monoˡ-< inf-i₁≤sup-i₁ inf-i₂≤sup-i₂ inf-i₂≤inf-i₁ sup-i₁<sup-i₂ ⊂⇒< {[ inf-i₁ , sup-i₁ ∣ inf-i₁≤sup-i₁ ]} {[ inf-i₂ , sup-i₂ ∣ inf-i₂≤sup-i₂ ]} (upward inf-i₂<inf-i₁ sup-i₁≤sup-i₂) = ∸-monoʳ-< inf-i₁≤sup-i₁ inf-i₂≤sup-i₂ inf-i₂<inf-i₁ sup-i₁≤sup-i₂ ⊂-well-founded : ∀ {i} → Acc _⊂_ i ⊂-well-founded = subrelation ⊂⇒< <-well-founded
-- {-# OPTIONS -v tc.size.solve:60 #-} module Issue300 where open import Common.Size data Nat : Size → Set where zero : (i : Size) → Nat (↑ i) suc : (i : Size) → Nat i → Nat (↑ i) -- Size meta used in a different context than the one created in A : Set₁ A = (Id : (i : Size) → Nat _ → Set) (k : Size) (m : Nat (↑ k)) (p : Id k m) → (j : Size) (n : Nat j ) → Id j n -- should solve _ with ↑ i -- 1) Id,k,m |- ↑ 1 ≤ X 1 ==> ↑ 4 ≤ X 4 -- 2) Id,k,m,p,j,n |- 1 ≤ X 1 -- Unfixed by fix for #1914 (Andreas, 2016-04-08).
% Scheme 48 documentation \documentclass[twoside,11pt]{report} \usepackage{hyperlatex} \T\usepackage{longtable} \T\usepackage{myindex} \T\usepackage{palatino} \W\include{latex-index} \T\textwidth5.7in \T\textheight8.9in \T\oddsidemargin10pt\evensidemargin20pt %\T\advance\textwidth by 4em \makeindex \W\include{my-sequential} \include{proto} \include{hacks} %\includeonly{posix} % Make a few big HTML files, and not a lot of small ones. \setcounter{htmldepth}{3} % Put the html code in its own directory. \htmldirectory{manual} % Set the html base name. \htmlname{s48manual} % Add sections to main menu \setcounter{htmlautomenu}{2} % White background \htmlattributes{BODY}{BGCOLOR="#ffffff"} \htmltitle{Scheme 48 Manual} % Suppress navigation panel for first page. \htmlpanel{0} %%% End preamble \begin{document} \label{top_node} \T\sloppy % Tells TeX not to worry too much about line breaks. \title{{\large The Incomplete} \\ Scheme 48 Reference Manual \\ {\large for release \input{version-number}}} % December 25, 1994 \author{Richard Kelsey and Jonathan Rees \\ {\normalsize with a chapter by Mike Sperber}} \date{} %\date{October 31, 1995} \T\cleardoublepage\pagenumbering{roman} \maketitle % For some reason the tabbing doesn't work here in html mode. \texonly{ \begin{verse} A line may take us hours, yet if it does not seem a moment's thought \\ All our stitching and unstitching has been as nought. \end{verse} \begin{tabbing} A line may take us hours, yet if it does not seem\= \kill \> Yeats \\ \> {\em Adam's Curse} \end{tabbing} } \htmlonly{ \begin{center} \begin{tabbing} A line may take us hours, yet if it does not seem\= a moment's thought \\ All our stitching and unstitching has been as nought. \\ \> Yeats \\ \> {\em Adam's Curse} \end{tabbing} \end{center} } \htmlpanel{1} \chapter*{Acknowledgements} Thanks to Scheme~48's users for their suggestions, bug reports, and forbearance. Thanks also to Deborah Tatar for providing the Yeats quotation. \T\tableofcontents \T\cleardoublepage\pagenumbering{arabic}\setcounter{page}{1} \setcounter{htmlautomenu}{1} \include{intro} \include{user-guide} \include{command} \include{module} \include{utilities} \include{external} \include{ascii} \include{bibliography} \texonly{ \begin{myindex} \addtocounter{chapter}{1} \addcontentsline{toc}{chapter}{\protect\numberline{\thechapter}{Index}} The principal entry for each term, procedure, or keyword is listed first, separated from the other entries by a semicolon. \bigskip \input{index} \end{myindex} } \htmlonly{ \chapter*{Index} \htmlprintindex } \end{document}
function rhs = globRHSIFE3DFace(fun, funB, fem, femIF, d1) %% USAGE: generate global matrix on a 3D mesh Face % % INPUTS: % fun --- coefficient function % mesh --- a struct data contains very rich mesh information. % fem1 --- global DoF for test function space % fem2 --- global DoF for trial function space % d1 --- derivative info for test function % d2 --- derivative info for trial function % d = [0,0,0]: function value % d = [1,0,0]: Dx value % d = [0,1,0]: Dy value % d = [0,0,1]: Dz value % % OUTPUTS: % matrix --- global (mass, stiffness, ...) matrix. % Last Modified: 08/02/2020 by Xu Zhang %% 1. RHS on Boundary Interface Faces dof = fem.ldof; if strcmp(fem.type,'P1')||strcmp(fem.type,'DGP1')||strcmp(fem.type,'CR') feEvalBas = @evalP1Bas3D; elseif strcmp(fem.type,'P2')||strcmp(fem.type,'DGP2') feEvalBas = @evalP2Bas3D; end rhs = zeros(length(fem.p),1); if size(femIF.tB,1) ~= 0 nmB = femIF.normalB; AB = femIF.areaB; gxB = femIF.gxB; gyB = femIF.gyB; gzB = femIF.gzB; gw = femIF.gw; nt = size(femIF.tB,1); % not number of interface element, but quadrature element ntot = nt*dof; IB = zeros(ntot,1); XB = zeros(ntot,1); coef = feval(fun,gxB,gyB,gzB); bval = feval(funB,gxB,gyB,gzB); IbasB = cell(dof,1); if d1 == 0 for i = 1:dof IbasB{i} = feEvalBas(femIF.basB(:,:,i), gxB, gyB, gzB, [0,0,0]); end elseif d1 == 1 for i = 1:dof IbasBx = feEvalBas(femIF.basB(:,:,i), gxB, gyB, gzB, [1,0,0]); IbasBy = feEvalBas(femIF.basB(:,:,i), gxB, gyB, gzB, [0,1,0]); IbasBz = feEvalBas(femIF.basB(:,:,i), gxB, gyB, gzB, [0,0,1]); IbasB{i} = IbasBx.*nmB(:,1) + IbasBy.*nmB(:,2) + IbasBz.*nmB(:,3); end end ind = 0; for i = 1:dof IB(ind+1:ind+nt) = femIF.tB(:,i); XB(ind+1:ind+nt) = AB.*sum((((IbasB{i}.*coef).*bval).*gw'),2); ind = ind + nt; end ID = find(XB~=0); rhs = sparse(IB(ID),1,XB(ID),length(fem.p),1); end
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau The functor Grp → Ab which is the left adjoint of the forgetful functor Ab → Grp. -/ import group_theory.quotient_group universes u v variables (α : Type u) [group α] def commutator : set α := { x | ∃ L : list α, (∀ z ∈ L, ∃ p q, p * q * p⁻¹ * q⁻¹ = z) ∧ L.prod = x } instance : normal_subgroup (commutator α) := { one_mem := ⟨[], by simp⟩, mul_mem := λ x y ⟨L1, HL1, HP1⟩ ⟨L2, HL2, HP2⟩, ⟨L1 ++ L2, list.forall_mem_append.2 ⟨HL1, HL2⟩, by simp*⟩, inv_mem := λ x ⟨L, HL, HP⟩, ⟨L.reverse.map has_inv.inv, λ x hx, let ⟨y, h3, h4⟩ := list.exists_of_mem_map hx in let ⟨p, q, h5⟩ := HL y (list.mem_reverse.1 h3) in ⟨q, p, by rw [← h4, ← h5]; simp [mul_assoc]⟩, by rw ← HP; from list.rec_on L (by simp) (λ hd tl ih, by rw [list.reverse_cons, list.map_append, list.prod_append, ih]; simp)⟩, normal := λ x ⟨L, HL, HP⟩ g, ⟨L.map $ λ z, g * z * g⁻¹, λ x hx, let ⟨y, h3, h4⟩ := list.exists_of_mem_map hx in let ⟨p, q, h5⟩ := HL y h3 in ⟨g * p * g⁻¹, g * q * g⁻¹, by rw [← h4, ← h5]; simp [mul_assoc]⟩, by rw ← HP; from list.rec_on L (by simp) (λ hd tl ih, by rw [list.map_cons, list.prod_cons, ih]; simp [mul_assoc])⟩, } def abelianization : Type u := quotient_group.quotient $ commutator α namespace abelianization local attribute [instance] quotient_group.left_rel normal_subgroup.to_is_subgroup instance : comm_group (abelianization α) := { mul_comm := λ x y, quotient.induction_on₂ x y $ λ m n, quotient.sound $ ⟨[n⁻¹*m⁻¹*n*m], by simp; refine ⟨n⁻¹, m⁻¹, _⟩; simp, by simp [mul_assoc]⟩, .. quotient_group.group _ } variable {α} def of (x : α) : abelianization α := quotient.mk x instance of.is_group_hom : is_group_hom (@of α _) := ⟨λ _ _, rfl⟩ section lift variables {β : Type v} [comm_group β] (f : α → β) [is_group_hom f] def lift : abelianization α → β := quotient_group.lift _ f $ λ x ⟨L, HL, hx⟩, hx ▸ list.rec_on L (λ _, is_group_hom.one f) (λ hd tl HL ih, by rw [list.forall_mem_cons] at ih; rcases ih with ⟨⟨p, q, hpq⟩, ih⟩; specialize HL ih; rw [list.prod_cons, is_group_hom.mul f, ← hpq, HL]; simp [is_group_hom.mul f, is_group_hom.inv f, mul_comm]) HL instance lift.is_group_hom : is_group_hom (lift f) := quotient_group.is_group_hom_quotient_lift _ _ _ @[simp] lemma lift.of (x : α) : lift f (of x) = f x := rfl theorem lift.unique (g : abelianization α → β) [is_group_hom g] (hg : ∀ x, g (of x) = f x) {x} : g x = lift f x := quotient.induction_on x $ λ m, hg m end lift end abelianization
struct DiscreteHilbert <: AbstractHilbert shape::Vector{Int} end DiscreteHilbert(Nsites, hilb_dim) = DiscreteHilbert(fill(hilb_dim, Nsites)) @inline shape(h::DiscreteHilbert) = h.shape @inline nsites(h::DiscreteHilbert) = length(shape(h)) @inline spacedimension(hilb::DiscreteHilbert) = prod(shape) @inline is_homogeneous(h::DiscreteHilbert) = all(first(h.shape) .== h.shape)
# 2. faza: Uvoz podatkov sl <- locale("sl", decimal_mark=",", grouping_mark=".") # Funkcija, ki uvozi regije iz Wikipedije uvozi.regije <- function() { link <- "http://sl.wikipedia.org/wiki/Seznam_ob%C4%8Din_v_Sloveniji" stran <- html_session(link) %>% read_html() tabela <- stran %>% html_nodes(xpath="//table[@class='wikitable sortable']") %>% .[[1]] %>% html_table(dec=",") for (i in 1:ncol(tabela)) { if (is.character(tabela[[i]])) { Encoding(tabela[[i]]) <- "UTF-8" } } colnames(tabela) <- c("obcina", "povrsina", "prebivalci", "gostota", "naselja", "ustanovitev", "pokrajina", "Regija", "odcepitev") tabela$Regija <- gsub('Jugovzhodna', 'Jugovzhodna Slovenija', tabela$Regija) tabela$Regija <- gsub('Spodnjeposavska', 'Posavska', tabela$Regija) for (col in c("povrsina", "prebivalci", "gostota", "naselja", "ustanovitev")) { if (is.character(tabela[[col]])) { tabela[[col]] <- parse_number(tabela[[col]], na="-", locale=sl) } } for (col in c("obcina", "pokrajina", "Regija")) { tabela[[col]] <- factor(tabela[[col]]) } return(tabela) } Slovenski_podatki <- uvozi.regije() Slovenske_regije <- Slovenski_podatki %>% group_by(Regija) %>% summarise(Regija,povrsina=sum(povrsina)) %>% unique() Sloveski_podatki_urejeni <- Slovenski_podatki %>% group_by(Regija) %>% summarise(Povrsina = sum(povrsina), Prebivalci = sum(prebivalci), Naselja=sum(naselja), Gostota = Prebivalci/Povrsina) Sloveski_podatki_urejeni$Regija <- gsub('Notranjsko-kraška', 'Primorsko-notranjska', Sloveski_podatki_urejeni$Regija) #Preberem povprecni pridelek Slovenije podatki_Slovenija <- read_xlsx("podatki/Povprecje_pridelkov_slovenija.xlsx") %>% pivot_longer(-(1), names_to="leto", values_to="Kolicina") podatki_Slovenija %>% write.csv2("podatki/Povprecje_pridelkov_slovenija_Predelano.csv",fileEncoding = "utf8", row.names = FALSE) #Preberem povprecni pridelek Slovenskih regij podatki_Regija <- read_xlsx("podatki/Pregled_pridelkov_regije.xlsx", na=c("", " ", "-")) %>% fill(1:2) %>% drop_na("Kolicina") podatki_Regija %>% write.csv2("podatki/Pregled_pridelkov_regije_Predelano.csv",fileEncoding = "utf8", row.names = FALSE) ############################################# ##Preberem povprecni pridelek Regije za 2010 #podatki_Regija_2010 <- read_xlsx("podatki/Pregled_pridelkov_regije_2010.xlsx", na=c("", " ", "-")) %>% pivot_longer(-(1), names_to="Proizvodno leto", values_to="Kolicina") %>% drop_na("Kolicina") #podatki_Regija_2010 %>% write.csv2("podatki/Pregled_pridelkov_regije_2010_Predelano.csv",fileEncoding = "utf8", row.names = FALSE) #Preberem povprecni pridelek Regije za 2019 #podatki_Regija_2019 <- read_xlsx("podatki/Pregled_pridelkov_regije_2019.xlsx", na=c("", " ", "-")) %>% pivot_longer(-(1), names_to="Proizvodno leto", values_to="Kolicina") %>% drop_na("Kolicina") #podatki_Regija_2019 %>% write.csv2("podatki/Pregled_pridelkov_regije_2019_Predelano.csv",fileEncoding = "utf8", row.names = FALSE) ############################################# Skupna_tabela <- left_join(podatki_Regija, Sloveski_podatki_urejeni, by=c('Regija')) # Graf: Zemljevid Slovenija <- uvozi.zemljevid("http://biogeo.ucdavis.edu/data/gadm2.8/shp/SVN_adm_shp.zip", "SVN_adm1", encoding = "UTF-8") %>% fortify() colnames(Slovenija)[12] <- 'Regija' Slovenija$Regija <- gsub('Spodnjeposavska', 'Posavska', Slovenija$Regija) Slovenija$Regija <- gsub('Goriška', 'Goriška', Slovenija$Regija) Slovenija$Regija <- gsub('Obalno-kraška', 'Obalno-kraška', Slovenija$Regija) Slovenija$Regija <- gsub('Notranjsko-kraška', 'Notranjsko-kraška', Slovenija$Regija) Slovenija$Regija <- gsub('Koroška', 'Koroška', Slovenija$Regija)
## Performance Indicator It is fundamental for any algorithm to measure the performance. In a multi-objective scenario, we can not calculate the distance to the true global optimum but must consider a set of solutions. Moreover, sometimes the optimum is not even known, and other techniques must be used. First, let us consider a scenario where the Pareto-front is known: ```python import numpy as np from pymoo.factory import get_problem from pymoo.visualization.scatter import Scatter # The pareto front of a scaled zdt1 problem pf = get_problem("zdt1").pareto_front() # The result found by an algorithm A = pf[::10] * 1.1 # plot the result Scatter(legend=True).add(pf, label="Pareto-front").add(A, label="Result").show() ``` ### Generational Distance (GD) The GD performance indicator <cite data-cite="gd"></cite> measure the distance from solution to the Pareto-front. Let us assume the points found by our algorithm are the objective vector set $A=\{a_1, a_2, \ldots, a_{|A|}\}$ and the reference points set (Pareto-front) is $Z=\{z_1, z_2, \ldots, z_{|Z|}\}$. Then, \begin{align} \begin{split} \text{GD}(A) & = & \; \frac{1}{|A|} \; \bigg( \sum_{i=1}^{|A|} d_i^p \bigg)^{1/p}\\[2mm] \end{split} \end{align} where $d_i$ represents the Euclidean distance (p=2) from $a_i$ to its nearest reference point in $Z$. Basically, this results in the average distance from any point $A$ to the closest point in the Pareto-front. ```python from pymoo.factory import get_performance_indicator gd = get_performance_indicator("gd", pf) print("GD", gd.calc(A)) ``` GD 0.05497689467314528 ### Generational Distance Plus (GD+) Ishibushi et. al. proposed in <cite data-cite="igd_plus"></cite> GD+: \begin{align} \begin{split} \text{GD}^+(A) & = & \; \frac{1}{|A|} \; \bigg( \sum_{i=1}^{|A|} {d_i^{+}}^2 \bigg)^{1/2}\\[2mm] \end{split} \end{align} where for minimization $d_i^{+} = max \{ a_i - z_i, 0\}$ represents the modified distance from $a_i$ to its nearest reference point in $Z$ with the corresponding value $z_i$. ```python from pymoo.factory import get_performance_indicator gd_plus = get_performance_indicator("gd+", pf) print("GD+", gd_plus.calc(A)) ``` GD+ 0.05497689467314528 ### Inverted Generational Distance (IGD) The IGD performance indicator <cite data-cite="igd"></cite> inverts the generational distance and measures the distance from any point in $Z$ to the closest point in $A$. \begin{align} \begin{split} \text{IGD}(A) & = & \; \frac{1}{|Z|} \; \bigg( \sum_{i=1}^{|Z|} \hat{d_i}^p \bigg)^{1/p}\\[2mm] \end{split} \end{align} where $\hat{d_i}$ represents the euclidean distance (p=2) from $z_i$ to its nearest reference point in $A$. ```python from pymoo.factory import get_performance_indicator igd = get_performance_indicator("igd", pf) print("IGD", igd.calc(A)) ``` IGD 0.06690908300327662 ### Inverted Generational Distance Plus (IGD+) In <cite data-cite="igd_plus"></cite> Ishibushi et. al. proposed IGD+ which is weakly Pareto compliant wheres the original IGD is not. \begin{align} \begin{split} \text{IGD}^{+}(A) & = & \; \frac{1}{|Z|} \; \bigg( \sum_{i=1}^{|Z|} {d_i^{+}}^2 \bigg)^{1/2}\\[2mm] \end{split} \end{align} where for minimization $d_i^{+} = max \{ a_i - z_i, 0\}$ represents the modified distance from $z_i$ to the closest solution in $A$ with the corresponding value $a_i$. ```python from pymoo.factory import get_performance_indicator igd_plus = get_performance_indicator("igd+", pf) print("IGD+", igd_plus.calc(A)) ``` IGD+ 0.06466828842775944 ### Hypervolume For all performance indicators showed so far, a target set needs to be known. For Hypervolume only a reference point needs to be provided. First, I would like to mention that we are using the Hypervolume implementation from [DEAP](https://deap.readthedocs.io/en/master/). It calculates the area/volume, which is dominated by the provided set of solutions with respect to a reference point. <div style="display: block;margin-left: auto;margin-right: auto;width: 40%;"> </div> This image is taken from <cite data-cite="hv"></cite> and illustrates a two objective example where the area which is dominated by a set of points is shown in grey. Whereas for the other metrics, the goal was to minimize the distance to the Pareto-front, here, we desire to maximize the performance metric. ```python from pymoo.factory import get_performance_indicator hv = get_performance_indicator("hv", ref_point=np.array([1.2, 1.2])) print("hv", hv.calc(A)) ``` hv 0.9631646448182305
[STATEMENT] lemma uinfo_empty[dest]: "(ainfo, hfs) \<in> auth_seg2 uinfo \<Longrightarrow> uinfo = \<epsilon>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (ainfo, hfs) \<in> auth_seg2 uinfo \<Longrightarrow> uinfo = \<epsilon> [PROOF STEP] by(auto simp add: auth_seg2_def auth_restrict_def)
In March 2009 , Nesbitt signed a contract with the American talent agency United Talent Agency , as the global financial crisis was restricting roles in British television . He continued to be represented in the United Kingdom by Artists Rights Group . The next year Nesbitt played the hunter Cathal in the low @-@ budget British horror film Outcast , which was a departure from his previous character types . After screening at major international film festivals in early 2010 , the film had a general release in the latter part of the year . Nesbitt had previously worked with the film 's director and co @-@ writer Colm McCarthy on Murphy 's Law , which was one reason he took the role . He researched the mythical aspects of the character by reading about Irish folklore and beliefs . He also starred alongside Minnie Driver and his Welcome to Sarajevo co @-@ star Goran Višnjić in the Tiger Aspect television serial The Deep . In the five @-@ part drama , Nesbitt played submarine engineer Clem Donnelly . The serial was filmed over 12 weeks at BBC Scotland 's studios in Dumbarton . August 2010 saw the release of Nadia <unk> 's film Matching Jack , in which Nesbitt plays the leading role of Connor . He became involved in the film after reading an early script draft in 2006 . In 2008 , the global financial crisis severely reduced the budget of the film , and Nesbitt volunteered a reduction in his salary so the film could still be made . The film was shot over eight weeks in Melbourne in 2009 and released in 2010 .
State Before: R : Type u inst✝⁴ : CommSemiring R A : Type v₁ inst✝³ : Semiring A inst✝² : Algebra R A B : Type v₂ inst✝¹ : Semiring B inst✝ : Algebra R B x y z : A ⊗[R] B ⊢ ∀ (a₁ a₂ a₃ : A) (b₁ b₂ b₃ : B), ↑(↑mul (↑(↑mul (a₁ ⊗ₜ[R] b₁)) (a₂ ⊗ₜ[R] b₂))) (a₃ ⊗ₜ[R] b₃) = ↑(↑mul (a₁ ⊗ₜ[R] b₁)) (↑(↑mul (a₂ ⊗ₜ[R] b₂)) (a₃ ⊗ₜ[R] b₃)) State After: R : Type u inst✝⁴ : CommSemiring R A : Type v₁ inst✝³ : Semiring A inst✝² : Algebra R A B : Type v₂ inst✝¹ : Semiring B inst✝ : Algebra R B x y z : A ⊗[R] B a₁✝ a₂✝ a₃✝ : A b₁✝ b₂✝ b₃✝ : B ⊢ ↑(↑mul (↑(↑mul (a₁✝ ⊗ₜ[R] b₁✝)) (a₂✝ ⊗ₜ[R] b₂✝))) (a₃✝ ⊗ₜ[R] b₃✝) = ↑(↑mul (a₁✝ ⊗ₜ[R] b₁✝)) (↑(↑mul (a₂✝ ⊗ₜ[R] b₂✝)) (a₃✝ ⊗ₜ[R] b₃✝)) Tactic: intros State Before: R : Type u inst✝⁴ : CommSemiring R A : Type v₁ inst✝³ : Semiring A inst✝² : Algebra R A B : Type v₂ inst✝¹ : Semiring B inst✝ : Algebra R B x y z : A ⊗[R] B a₁✝ a₂✝ a₃✝ : A b₁✝ b₂✝ b₃✝ : B ⊢ ↑(↑mul (↑(↑mul (a₁✝ ⊗ₜ[R] b₁✝)) (a₂✝ ⊗ₜ[R] b₂✝))) (a₃✝ ⊗ₜ[R] b₃✝) = ↑(↑mul (a₁✝ ⊗ₜ[R] b₁✝)) (↑(↑mul (a₂✝ ⊗ₜ[R] b₂✝)) (a₃✝ ⊗ₜ[R] b₃✝)) State After: no goals Tactic: simp only [mul_apply, mul_assoc]