Datasets:
AI4M
/

text
stringlengths
0
3.34M
module Main %foreign "Dart:cantUseBool,lib.dart" cantUseBool : Bool -> Int main : IO () main = printLn (cantUseBool True)
#ifdef HAVE_CONFIG_H #include "config.h" #endif #include <php.h> #include <cblas.h> #include <lapacke.h> #include "kernel/operators.h" /** * Matrix-matrix multiplication i.e. linear transformation of matrices A and B. * * @param return_value * @param a * @param b */ void tensor_matmul(zval * return_value, zval * a, zval * b) { unsigned int i, j; Bucket * row; zval rowC, c; zend_array * aa = Z_ARR_P(a); zend_array * ab = Z_ARR_P(b); Bucket * ba = aa->arData; Bucket * bb = ab->arData; unsigned int m = zend_array_count(aa); unsigned int p = zend_array_count(ab); unsigned int n = zend_array_count(Z_ARR(bb[0].val)); double * va = emalloc(m * p * sizeof(double)); double * vb = emalloc(n * p * sizeof(double)); double * vc = emalloc(m * n * sizeof(double)); for (i = 0; i < m; ++i) { row = Z_ARR(ba[i].val)->arData; for (j = 0; j < p; ++j) { va[i * p + j] = zephir_get_doubleval(&row[j].val); } } for (i = 0; i < p; ++i) { row = Z_ARR(bb[i].val)->arData; for (j = 0; j < n; ++j) { vb[i * n + j] = zephir_get_doubleval(&row[j].val); } } cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, p, 1.0, va, p, vb, n, 0.0, vc, n); array_init_size(&c, m); for (i = 0; i < m; ++i) { array_init_size(&rowC, n); for (j = 0; j < n; ++j) { add_next_index_double(&rowC, vc[i * n + j]); } add_next_index_zval(&c, &rowC); } RETVAL_ARR(Z_ARR(c)); efree(va); efree(vb); efree(vc); } /** * Dot product between vectors A and B. * * @param return_value * @param a * @param b */ void tensor_dot(zval * return_value, zval * a, zval * b) { unsigned int i; zend_array * aa = Z_ARR_P(a); zend_array * ab = Z_ARR_P(b); Bucket * ba = aa->arData; Bucket * bb = ab->arData; unsigned int n = zend_array_count(aa); double sigma = 0.0; for (i = 0; i < n; ++i) { sigma += zephir_get_doubleval(&ba[i].val) * zephir_get_doubleval(&bb[i].val); } RETVAL_DOUBLE(sigma); } /** * Return the multiplicative inverse of a square matrix A. * * @param return_value * @param a */ void tensor_inverse(zval * return_value, zval * a) { unsigned int i, j; Bucket * row; zval rowB, b; zend_array * aa = Z_ARR_P(a); Bucket * ba = aa->arData; unsigned int n = zend_array_count(aa); double * va = emalloc(n * n * sizeof(double)); int * pivots = emalloc(n * sizeof(int)); for (i = 0; i < n; ++i) { row = Z_ARR(ba[i].val)->arData; for (j = 0; j < n; ++j) { va[i * n + j] = zephir_get_doubleval(&row[j].val); } } lapack_int status; status = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, va, n, pivots); if (status != 0) { RETURN_NULL(); } status = LAPACKE_dgetri(LAPACK_ROW_MAJOR, n, va, n, pivots); if (status != 0) { RETURN_NULL(); } array_init_size(&b, n); for (i = 0; i < n; ++i) { array_init_size(&rowB, n); for (j = 0; j < n; ++j) { add_next_index_double(&rowB, va[i * n + j]); } add_next_index_zval(&b, &rowB); } RETVAL_ARR(Z_ARR(b)); efree(va); efree(pivots); } /** * Return the (Moore-Penrose) pseudoinverse of a general matrix A. * * @param return_value * @param a */ void tensor_pseudoinverse(zval * return_value, zval * a) { unsigned int i, j; Bucket * row; zval b, rowB; zend_array * aa = Z_ARR_P(a); Bucket * ba = aa->arData; unsigned int m = zend_array_count(aa); unsigned int n = zend_array_count(Z_ARR(ba[0].val)); unsigned int k = MIN(m, n); double * va = emalloc(m * n * sizeof(double)); double * vu = emalloc(m * m * sizeof(double)); double * vs = emalloc(k * sizeof(double)); double * vvt = emalloc(n * n * sizeof(double)); double * vb = emalloc(n * m * sizeof(double)); for (i = 0; i < m; ++i) { row = Z_ARR(ba[i].val)->arData; for (j = 0; j < n; ++j) { va[i * n + j] = zephir_get_doubleval(&row[j].val); } } lapack_int status = LAPACKE_dgesdd(LAPACK_ROW_MAJOR, 'A', m, n, va, n, vs, vu, m, vvt, n); if (status != 0) { RETURN_NULL(); } for (i = 0; i < k; ++i) { cblas_dscal(m, 1.0 / vs[i], &vu[i], m); } cblas_dgemm(CblasRowMajor, CblasTrans, CblasTrans, n, m, m, 1.0, vvt, n, vu, m, 0.0, vb, m); array_init_size(&b, n); for (i = 0; i < n; ++i) { array_init_size(&rowB, m); for (j = 0; j < m; ++j) { add_next_index_double(&rowB, vb[i * m + j]); } add_next_index_zval(&b, &rowB); } RETVAL_ARR(Z_ARR(b)); efree(va); efree(vu); efree(vs); efree(vvt); efree(vb); } /** * Return the row echelon form of matrix A. * * @param return_value * @param a */ void tensor_ref(zval * return_value, zval * a) { unsigned int i, j; Bucket * row; zval rowB, b; zval tuple; zend_array * aa = Z_ARR_P(a); Bucket * ba = aa->arData; unsigned int m = zend_array_count(aa); unsigned int n = zend_array_count(Z_ARR(ba[0].val)); double * va = emalloc(m * n * sizeof(double)); int * pivots = emalloc(MIN(m, n) * sizeof(int)); for (i = 0; i < m; ++i) { row = Z_ARR(ba[i].val)->arData; for (j = 0; j < n; ++j) { va[i * n + j] = zephir_get_doubleval(&row[j].val); } } lapack_int status = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, m, n, va, n, pivots); if (status != 0) { RETURN_NULL(); } array_init_size(&b, m); long swaps = 0; for (i = 0; i < m; ++i) { array_init_size(&rowB, n); for (j = 0; j < i; ++j) { add_next_index_double(&rowB, 0.0); } for (j = i; j < n; ++j) { add_next_index_double(&rowB, va[i * n + j]); } add_next_index_zval(&b, &rowB); if (i + 1 != pivots[i]) { ++swaps; } } array_init_size(&tuple, 2); add_next_index_zval(&tuple, &b); add_next_index_long(&tuple, swaps); RETVAL_ARR(Z_ARR(tuple)); efree(va); efree(pivots); } /** * Compute the Cholesky decomposition of matrix A and return the lower triangular matrix. * * @param return_value * @param a */ void tensor_cholesky(zval * return_value, zval * a) { unsigned int i, j; Bucket * row; zval rowB, b; zend_array * aa = Z_ARR_P(a); Bucket * ba = aa->arData; unsigned int n = zend_array_count(aa); double * va = emalloc(n * n * sizeof(double)); for (i = 0; i < n; ++i) { row = Z_ARR(ba[i].val)->arData; for (j = 0; j < n; ++j) { va[i * n + j] = zephir_get_doubleval(&row[j].val); } } lapack_int status = LAPACKE_dpotrf(LAPACK_ROW_MAJOR, 'L', n, va, n); if (status != 0) { RETURN_NULL(); } array_init_size(&b, n); for (i = 0; i < n; ++i) { array_init_size(&rowB, n); for (j = 0; j <= i; ++j) { add_next_index_double(&rowB, va[i * n + j]); } for (j = i + 1; j < n; ++j) { add_next_index_double(&rowB, 0.0); } add_next_index_zval(&b, &rowB); } RETVAL_ARR(Z_ARR(b)); efree(va); } /** * Compute the LU factorization of matrix A and return a tuple with lower, upper, and permutation matrices. * * @param return_value * @param a */ void tensor_lu(zval * return_value, zval * a) { unsigned int i, j; Bucket * row; zval rowL, l, rowU, u, rowP, p; zval tuple; zend_array * aa = Z_ARR_P(a); Bucket * ba = aa->arData; unsigned int n = zend_array_count(aa); double * va = emalloc(n * n * sizeof(double)); int * pivots = emalloc(n * sizeof(int)); for (i = 0; i < n; ++i) { row = Z_ARR(ba[i].val)->arData; for (j = 0; j < n; ++j) { va[i * n + j] = zephir_get_doubleval(&row[j].val); } } lapack_int status = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, va, n, pivots); if (status != 0) { RETURN_NULL(); } array_init_size(&l, n); array_init_size(&u, n); array_init_size(&p, n); for (i = 0; i < n; ++i) { array_init_size(&rowL, n); for (j = 0; j < i; ++j) { add_next_index_double(&rowL, va[i * n + j]); } add_next_index_double(&rowL, 1.0); for (j = i + 1; j < n; ++j) { add_next_index_double(&rowL, 0.0); } add_next_index_zval(&l, &rowL); } for (i = 0; i < n; ++i) { array_init_size(&rowU, n); for (j = 0; j < i; ++j) { add_next_index_double(&rowU, 0.0); } for (j = i; j < n; ++j) { add_next_index_double(&rowU, va[i * n + j]); } add_next_index_zval(&u, &rowU); } for (i = 0; i < n; ++i) { array_init_size(&rowP, n); for (j = 0; j < n; ++j) { if (j == pivots[i] - 1) { add_next_index_long(&rowP, 1); } else { add_next_index_long(&rowP, 0); } } add_next_index_zval(&p, &rowP); } array_init_size(&tuple, 3); add_next_index_zval(&tuple, &l); add_next_index_zval(&tuple, &u); add_next_index_zval(&tuple, &p); RETVAL_ARR(Z_ARR(tuple)); efree(va); efree(pivots); } /** * Compute the eigendecomposition of a general matrix A and return the eigenvalues and eigenvectors in a tuple. * * @param return_value * @param a */ void tensor_eig(zval * return_value, zval * a) { unsigned int i, j; Bucket * row; zval eigenvalues; zval eigenvectors; zval eigenvector; zval tuple; zend_array * aa = Z_ARR_P(a); Bucket * ba = aa->arData; unsigned int n = zend_array_count(aa); double * va = emalloc(n * n * sizeof(double)); double * wr = emalloc(n * sizeof(double)); double * wi = emalloc(n * sizeof(double)); double * vr = emalloc(n * n * sizeof(double)); for (i = 0; i < n; ++i) { row = Z_ARR(ba[i].val)->arData; for (j = 0; j < n; ++j) { va[i * n + j] = zephir_get_doubleval(&row[j].val); } } lapack_int status = LAPACKE_dgeev(LAPACK_ROW_MAJOR, 'N', 'V', n, va, n, wr, wi, NULL, n, vr, n); if (status != 0) { RETURN_NULL(); } array_init_size(&eigenvalues, n); array_init_size(&eigenvectors, n); for (i = 0; i < n; ++i) { add_next_index_double(&eigenvalues, wr[i]); array_init_size(&eigenvector, n); for (j = 0; j < n; ++j) { add_next_index_double(&eigenvector, vr[i * n + j]); } add_next_index_zval(&eigenvectors, &eigenvector); } array_init_size(&tuple, 2); add_next_index_zval(&tuple, &eigenvalues); add_next_index_zval(&tuple, &eigenvectors); RETVAL_ARR(Z_ARR(tuple)); efree(va); efree(wr); efree(wi); efree(vr); } /** * Compute the eigendecomposition of a symmetric matrix A and return the eigenvalues and eigenvectors in a tuple. * * @param return_value * @param a */ void tensor_eig_symmetric(zval * return_value, zval * a) { unsigned int i, j; Bucket * row; zval eigenvalues; zval eigenvectors; zval eigenvector; zval tuple; zend_array * aa = Z_ARR_P(a); Bucket * ba = aa->arData; unsigned int n = zend_array_count(aa); double * va = emalloc(n * n * sizeof(double)); double * wr = emalloc(n * sizeof(double)); for (i = 0; i < n; ++i) { row = Z_ARR(ba[i].val)->arData; for (j = 0; j < n; ++j) { va[i * n + j] = zephir_get_doubleval(&row[j].val); } } lapack_int status = LAPACKE_dsyev(LAPACK_ROW_MAJOR, 'V', 'U', n, va, n, wr); if (status != 0) { RETURN_NULL(); } array_init_size(&eigenvalues, n); array_init_size(&eigenvectors, n); for (i = 0; i < n; ++i) { add_next_index_double(&eigenvalues, wr[i]); array_init_size(&eigenvector, n); for (j = 0; j < n; ++j) { add_next_index_double(&eigenvector, va[i * n + j]); } add_next_index_zval(&eigenvectors, &eigenvector); } array_init_size(&tuple, 2); add_next_index_zval(&tuple, &eigenvalues); add_next_index_zval(&tuple, &eigenvectors); RETVAL_ARR(Z_ARR(tuple)); efree(va); efree(wr); } /** * Compute the singular value decomposition of a matrix A and return the singular values, and unitary matrices U and VT in a tuple. * * @param return_value * @param a */ void tensor_svd(zval * return_value, zval * a) { unsigned int i, j; Bucket * row; zval u, rowU; zval s; zval vt, rowVt; zval tuple; zend_array * aa = Z_ARR_P(a); Bucket * ba = aa->arData; unsigned int m = zend_array_count(aa); unsigned int n = zend_array_count(Z_ARR(ba[0].val)); unsigned int k = MIN(m, n); double * va = emalloc(m * n * sizeof(double)); double * vu = emalloc(m * m * sizeof(double)); double * vs = emalloc(k * sizeof(double)); double * vvt = emalloc(n * n * sizeof(double)); for (i = 0; i < m; ++i) { row = Z_ARR(ba[i].val)->arData; for (j = 0; j < n; ++j) { va[i * n + j] = zephir_get_doubleval(&row[j].val); } } lapack_int status = LAPACKE_dgesdd(LAPACK_ROW_MAJOR, 'A', m, n, va, n, vs, vu, m, vvt, n); if (status != 0) { RETURN_NULL(); } array_init_size(&u, m); array_init_size(&s, k); array_init_size(&vt, n); for (i = 0; i < m; ++i) { array_init_size(&rowU, m); for (j = 0; j < m; ++j) { add_next_index_double(&rowU, vu[i * m + j]); } add_next_index_zval(&u, &rowU); } for (i = 0; i < k; ++i) { add_next_index_double(&s, vs[i]); } for (i = 0; i < n; ++i) { array_init_size(&rowVt, n); for (j = 0; j < n; ++j) { add_next_index_double(&rowVt, vvt[i * n + j]); } add_next_index_zval(&vt, &rowVt); } array_init_size(&tuple, 3); add_next_index_zval(&tuple, &u); add_next_index_zval(&tuple, &s); add_next_index_zval(&tuple, &vt); RETVAL_ARR(Z_ARR(tuple)); efree(va); efree(vu); efree(vs); efree(vvt); }
import topology.sheaves.sheaf import algebra.category.Group.limits import oc import data.nat.parity import new.unordered.C import lemmas.about_opens import lemmas.lemmas noncomputable theory section open topological_space Top Top.sheaf open category_theory open opposite universe u variables {X : Top.{u}} (𝓕 : sheaf Ab X) (U : X.oc) structure vec_o (n : ℕ) : Type u := (to_fun : fin n → U.ι) (is_strict_mono : strict_mono to_fun) def vec_o.zero : vec_o U 0 := { to_fun := λ ⟨i, hi⟩, by linarith, is_strict_mono := λ ⟨i, hi⟩ _ _, by linarith } @[ext] lemma vec_o_ext {n : ℕ} {α β : vec_o U n} (h1 : α.to_fun = β.to_fun) : α = β := begin cases α, cases β, dsimp at *, subst h1, end lemma vec_o.zero_uniq (α : vec_o U 0) : α = vec_o.zero _ := begin ext j, rcases j with ⟨j, hj⟩, linarith end instance (n : ℕ) : has_coe_to_fun (vec_o U n) (λ _, fin n → U.ι) := { coe := λ α, α.to_fun } instance (n : ℕ) : has_coe (vec_o U n) (fin n → U.ι) := { coe := λ α, α.to_fun } def C_o.pre (n : ℕ) : Type u := Π (α : vec_o U n), 𝓕.1.obj (op $ face α) section variables {𝓕 U} lemma map_congr.vec_o_eq {n} (f : C_o.pre 𝓕 U n) {α β : vec_o U n} (EQ : α = β) : f α = 𝓕.1.map (eq_to_hom $ by rw EQ).op (f β) := begin subst EQ, rw [eq_to_hom_op, eq_to_hom_map, eq_to_hom_refl, id_apply], end end namespace C_o_pre variable (n : ℕ) variables {𝓕 U} instance : has_add (C_o.pre 𝓕 U n) := { add := λ f g α, f α + g α } lemma add_assoc (f g h : C_o.pre 𝓕 U n) : f + g + h = f + (g + h) := begin ext α, simp [pi.add_apply, add_assoc], end lemma add_comm (f g : C_o.pre 𝓕 U n) : f + g = g + f := funext $ λ _, by simp [add_comm] instance : has_zero (C_o.pre 𝓕 U n) := { zero := λ α, 0 } lemma zero_add (f : C_o.pre 𝓕 U n) : 0 + f = f := funext $ λ α, by simp lemma add_zero (f : C_o.pre 𝓕 U n) : f + 0 = f := funext $ λ _, by simp instance (α : Type*) [Π (O : opens X), has_scalar α (𝓕.1.obj (op O))] : has_scalar α (C_o.pre 𝓕 U n) := { smul := λ m f β, m • (f β) } lemma nsmul_zero (f : C_o.pre 𝓕 U n): 0 • f = 0 := funext $ λ _, by simp lemma zsmul_zero (f : C_o.pre 𝓕 U n) : (0 : ℤ) • f = 0 := funext $ λ _, by simp lemma nsmul_succ (m : ℕ) (f : C_o.pre 𝓕 U n) : m.succ • f = f + m • f := funext $ λ α, by simp [add_nsmul, nat.succ_eq_add_one, _root_.add_comm] lemma zsmul_succ (m : ℕ) (f : C_o.pre 𝓕 U n) : int.of_nat (m.succ) • f = f + int.of_nat m • f := funext $ λ α, by simp [add_smul, _root_.add_comm] instance : has_neg (C_o.pre 𝓕 U n) := { neg := λ f α, - f α } lemma add_left_neg (f : C_o.pre 𝓕 U n) : (-f) + f = 0 := funext $ λ _, by simp instance : has_sub (C_o.pre 𝓕 U n) := { sub := λ f g α, f α - g α } lemma sub_eq_add_neg (f g : C_o.pre 𝓕 U n) : f - g = f + (- g) := funext $ λ α, calc (f - g) α = f α - g α : rfl ... = f α + (- g α) : by abel end C_o_pre instance (n : ℕ) : add_comm_group (C_o.pre 𝓕 U n) := { add := (+), add_assoc := C_o_pre.add_assoc n, zero := 0, zero_add := C_o_pre.zero_add n, add_zero := C_o_pre.add_zero n, nsmul := (•), nsmul_zero' := C_o_pre.nsmul_zero n, nsmul_succ' := C_o_pre.nsmul_succ n, neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := C_o_pre.sub_eq_add_neg n, zsmul := (•), zsmul_zero' := C_o_pre.zsmul_zero n, zsmul_succ' := C_o_pre.zsmul_succ n, zsmul_neg' := λ m f, funext $ λ α, by simp [add_smul], add_left_neg := C_o_pre.add_left_neg n, add_comm := C_o_pre.add_comm n } def C_o (n : ℕ) : Ab := AddCommGroup.of (C_o.pre 𝓕 U n) section ignore_o variable (n : ℕ) variables {U 𝓕 n} def ignore_o (α : vec_o U (n + 1)) (k : fin (n + 1)) : vec_o U n := { to_fun := ignore α.to_fun k, is_strict_mono := λ i j h, begin by_cases ineq1 : j.1 < k.1, { rw ignore.apply_lt, work_on_goal 2 { transitivity j.1, exact h, exact ineq1, }, rw ignore.apply_lt, work_on_goal 2 { assumption, }, apply α.2, exact h }, -- rw not_lt at ineq1, { rw ignore.apply_not_lt α.1 _ ineq1, rw not_lt at ineq1, rw ignore.apply_ite, split_ifs with ineq2, { apply α.2, change i.1 < j.1.pred, sorry }, { apply α.2, change i.1.pred < j.1.pred, sorry }, }, end } def ignore_o₂ (α : vec_o U (n + 2)) (i : fin (n + 2)) (j : fin (n + 1)) : vec_o U n := ignore_o (ignore_o α i) j lemma ignore_o₂_symm' {n : ℕ} (α : vec_o U (n+2)) {i : ℕ} (hi : i ∈ finset.range n.succ) {j : ℕ} (hj : j ∈ finset.Ico i n.succ) : -- i ≤ j ignore_o₂ α ⟨j + 1, begin rw finset.mem_Ico at hj, rw nat.succ_lt_succ_iff, exact hj.2 end⟩ ⟨i, finset.mem_range.mp hi⟩ = ignore_o₂ α ⟨i, lt_trans (finset.mem_range.mp hi) (lt_add_one _)⟩ ⟨j, (finset.mem_Ico.mp hj).2⟩ := begin sorry end lemma ignore_o.apply_lt (α : vec_o U (n + 1)) (k : fin (n + 1)) (i : fin n) (ineq : i.1 < k.1) : ignore_o α k i = α ⟨i.1, lt_trans i.2 (lt_add_one _)⟩ := begin change ignore α.to_fun k i = α.1 _, rw ignore.apply_lt, exact ineq end lemma ignore_o.apply_not_lt (α : vec_o U (n + 1)) (k : fin (n + 1)) (i : fin n) (ineq : ¬ i.1 < k.1) : ignore_o α k i = α ⟨i.1.pred, begin rw nat.lt_succ_iff, refine le_of_lt _, exact lt_of_le_of_lt (nat.pred_le _) i.2, end⟩ := begin change ignore α.to_fun k i = α.1 _, rw ignore.apply_not_lt, exact ineq, end def face_o (α : vec_o U n) : opens X := infi (λ (k : fin n), U.cover $ α k) lemma face.le_ignore_o (α : vec_o U (n + 1)) (k : fin (n + 1)) : face_o α ≤ face_o (ignore_o α k) := λ p hp, begin rw opens.mem_coe at hp ⊢, erw opens.fintype_infi at hp ⊢, rintros ⟨i, hi⟩, by_cases ineq : i < k.1, { specialize hp ⟨i, _⟩, { refine lt_trans hi _, exact lt_add_one n, }, rw ignore_o.apply_lt, swap, exact ineq, exact hp, }, { specialize hp ⟨i.pred, _⟩, { rw nat.lt_succ_iff, by_cases i = 0, { subst h, exact nat.zero_le _, }, refine le_of_lt _, refine lt_trans _ hi, exact nat.pred_lt h, }, rw ignore_o.apply_not_lt, convert hp, exact ineq, } end lemma face.le_ignore_o₂ (α : vec_o U (n + 2)) (i : fin (n + 2)) (j : fin (n + 1)) : face_o α ≤ face_o (ignore_o₂ α i j) := le_trans (face.le_ignore_o _ i) (face.le_ignore_o _ _) lemma face.vec_o_zero : face (vec_o.zero U) = ⊤ := begin rw eq_top_iff, rintros p -, erw [opens.mem_coe, opens.fintype_infi], rintros ⟨j, hj⟩, linarith, end end ignore_o def C_o.zeroth : C_o 𝓕 U 0 ≅ 𝓕.1.obj (op ⊤) := { hom := { to_fun := λ f, 𝓕.1.map (eq_to_hom (face.vec_o_zero).symm).op $ f (vec_o.zero U), map_zero' := begin rw [pi.zero_apply, map_zero], end, map_add' := λ f g, begin rw [pi.add_apply, map_add], end }, inv := { to_fun := λ s α, 𝓕.1.map (hom_of_le $ le_top).op s, map_zero' := begin ext α, rw [map_zero, pi.zero_apply], end, map_add' := λ f g, begin ext α, rw [pi.add_apply, map_add], end }, hom_inv_id' := begin ext f α, change (𝓕.1.map _ ≫ 𝓕.1.map _) _ = _, simp only [id_apply], rw map_congr.vec_o_eq f (vec_o.zero_uniq U α), rw ← 𝓕.1.map_comp, congr, end, inv_hom_id' := begin ext f, change (𝓕.1.map _ ≫ 𝓕.1.map _) _ = _, rw [id_apply, ← 𝓕.1.map_comp], have : 𝓕.val.map (𝟙 (op ⊤)) f = f, { rw 𝓕.1.map_id, rw id_apply, }, convert this, end } section d_o open nat open_locale big_operators variable (n : ℕ) variables {𝓕 U n} def d_o.to_fun.component' (α : vec_o U (n + 1)) (k : fin (n + 1)) (f : C_o.pre 𝓕 U n) : 𝓕.1.obj (op (face α)) := (ite (even k.1) id (has_neg.neg)) $ 𝓕.1.map (hom_of_le $ face.le_ignore α k).op $ f (ignore_o α k) def d_o.to_fun.component (k : fin (n + 1)) : C_o.pre 𝓕 U n → C_o.pre 𝓕 U (n + 1) := λ f α, d_o.to_fun.component' α k f def d_o.to_fun (f : C_o.pre 𝓕 U n) (α : vec_o U (n + 1)) : 𝓕.1.obj (op (face α)) := ∑ (k : fin (n + 1)), d_o.to_fun.component k f α variables (n 𝓕 U) def d_o : C_o 𝓕 U n ⟶ C_o 𝓕 U (n + 1) := { to_fun := d_o.to_fun, map_zero' := funext $ λ α, begin simp only [pi.zero_apply], change ∑ _, _ = _, rw finset.sum_eq_zero, intros i hi, change (ite _ id has_neg.neg) _ = _, split_ifs with e, { rw [id, pi.zero_apply, map_zero], }, { rw [pi.zero_apply, map_zero, neg_zero], }, end, map_add' := λ f g, funext $ λ α, begin rw pi.add_apply, change ∑ _, _ = ∑ _, _ + ∑ _, _, rw ← finset.sum_add_distrib, rw finset.sum_congr rfl, intros i _, change (ite _ id _) _ = (ite _ id _) _ + (ite _ id _) _, split_ifs with e, { rw [id, id, id, pi.add_apply, map_add], }, { rw [pi.add_apply, map_add, neg_add], }, end } abbreviation dd_o : C_o 𝓕 U n ⟶ C_o 𝓕 U (n + 2) := d_o _ _ _ ≫ d_o _ _ _ namespace dd_o_aux lemma d_o_def (f : C_o 𝓕 U n) (α : vec_o U (n + 1)) : d_o 𝓕 U n f α = ∑ (i : fin (n+1)), (ite (even i.1) id has_neg.neg) 𝓕.1.map (hom_of_le $ face.le_ignore_o α i).op (f (ignore_o α i)) := begin rw [d_o], simp only [add_monoid_hom.coe_mk, fin.val_eq_coe], change ∑ _, _ = _, rw finset.sum_congr rfl, intros i _, change (ite _ id _) _ = _, split_ifs, { rw [id, id], refl, }, { simpa, }, end lemma eq1 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = d_o 𝓕 U (n + 1) (d_o 𝓕 U n f) α := rfl lemma eq2 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = ∑ (i : fin (n + 2)), (ite (even i.1) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore_o α i)).op (d_o 𝓕 U n f (ignore_o α i))) := begin rw [eq1, d_o_def, finset.sum_congr rfl], intros i _, split_ifs, { simp }, { simp }, end lemma eq3 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = ∑ (i : fin (n + 2)), (ite (even i.1) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore α i)).op (∑ (j : fin (n + 1)), (ite (even j.1) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore (ignore_o α i) j)).op (f (ignore_o (ignore_o α i) j))))) := begin rw [eq2, finset.sum_congr rfl], intros i _, rw [d_o_def], split_ifs, { simp only [id.def], rw [add_monoid_hom.map_sum, add_monoid_hom.map_sum, finset.sum_congr rfl], intros j _, split_ifs, { rw [id, id], refl, }, { simp only [pi.neg_apply, add_monoid_hom.neg_apply], refl, }, }, { congr' 2, rw [finset.sum_congr rfl], intros j _, split_ifs, { rw [id, id], refl, }, { simp only [pi.neg_apply, add_monoid_hom.neg_apply, neg_inj], refl, } }, end lemma eq4 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = ∑ (i : fin (n + 2)), (ite (even i.1) id has_neg.neg) (∑ (j : fin (n + 1)), 𝓕.1.map (hom_of_le (face.le_ignore_o α i)).op ((ite (even j.1) id has_neg.neg) 𝓕.1.map (hom_of_le (face.le_ignore_o (ignore_o α i) j)).op (f (ignore_o (ignore_o α i) j)))) := begin rw [eq3, finset.sum_congr rfl], intros i _, split_ifs, { rw [add_monoid_hom.map_sum, id, id, finset.sum_congr rfl], intros j _, split_ifs, { rw [id, id], refl, }, { simpa }, }, { rw [add_monoid_hom.map_sum, finset.neg_sum, finset.neg_sum, finset.sum_congr rfl], intros j _, split_ifs, { rw [id, id], refl, }, { simpa }, }, end lemma eq5 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = ∑ (i : fin (n + 2)), (ite (even i.1) id has_neg.neg) (∑ (j : fin (n + 1)), (ite (even j.1) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore_o α i)).op (𝓕.1.map (hom_of_le (face.le_ignore_o (ignore_o α i) j)).op (f (ignore_o (ignore_o α i) j))))) := begin rw [eq4, finset.sum_congr rfl], intros i _, split_ifs, { rw [id, id, finset.sum_congr rfl], intros j _, split_ifs, { rw [id, id], }, { simp }, }, { rw [finset.neg_sum, finset.neg_sum, finset.sum_congr rfl], intros j _, split_ifs, { rw [id, id], }, { simp, }, }, end lemma eq6₀ (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = ∑ (i : fin (n + 2)), (ite (even i.1) id has_neg.neg) (∑ (j : fin (n + 1)), (ite (even j.1) id has_neg.neg) (𝓕.1.map ((hom_of_le (face.le_ignore (ignore α i) j)).op ≫ (hom_of_le (face.le_ignore α i)).op) (f (ignore_o (ignore_o α i) j)))) := begin rw [eq5, finset.sum_congr rfl], intros i _, split_ifs, { rw [id, id, finset.sum_congr rfl], intros j _, split_ifs, { rw [id, id, 𝓕.1.map_comp, comp_apply], refl, }, { rw [𝓕.1.map_comp, comp_apply], refl, }, }, { rw [finset.neg_sum, finset.neg_sum, finset.sum_congr rfl], intros j _, split_ifs, { rw [id, id, 𝓕.1.map_comp, comp_apply], refl, }, { rw [neg_neg, neg_neg, 𝓕.1.map_comp, comp_apply], refl, }, } end lemma eq6₁ (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = ∑ (i : fin (n + 2)), (ite (even i.1) id has_neg.neg) (∑ (j : fin (n + 1)), (ite (even j.1) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore α i) ≫ hom_of_le (face.le_ignore (ignore α i) j)).op) (f (ignore_o (ignore_o α i) j))) := begin rw [eq6₀, finset.sum_congr rfl], intros i _, split_ifs, { rw [id, id, finset.sum_congr rfl], intros j _, split_ifs, { rw [id, id, op_comp], }, { rw [op_comp], simp }, }, { rw [finset.neg_sum, finset.neg_sum, finset.sum_congr rfl], intros j _, split_ifs, { rw [id, id, op_comp] }, { rw [op_comp], simp }, } end lemma eq6₂ (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = ∑ (i : fin (n + 2)), (ite (even i.1) id has_neg.neg) (∑ (j : fin (n + 1)), (ite (even j.1) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore_o₂ α i j)).op) (f (ignore_o₂ α i j))) := begin rw [eq6₁, finset.sum_congr rfl], intros i _, split_ifs, { rw [id, id, finset.sum_congr rfl], intros j _, split_ifs, { rw [id, id], congr, }, { congr, }, }, { rw [finset.neg_sum, finset.neg_sum, finset.sum_congr rfl], intros j _, split_ifs, { rw [id, id], congr, }, { congr }, }, end lemma eq7 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = ∑ (i : fin (n + 2)), ∑ (j : fin (n + 1)), (ite (even i.1) id has_neg.neg) (ite (even j.1) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore_o₂ α i j)).op) (f (ignore_o₂ α i j)) := begin rw [eq6₂, finset.sum_congr rfl], intros i _, split_ifs, { rw [id, finset.sum_congr rfl], intros j _, split_ifs, { rw [id, id, id], }, { rw [id], }, }, { rw [finset.neg_sum, finset.sum_congr rfl], intros j _, split_ifs, { rw [id, pi.neg_apply, id], congr, }, { rw [pi.neg_apply, neg_neg, add_monoid_hom.neg_apply, neg_neg], }, }, end lemma eq8 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = ∑ (i : fin (n + 2)), ∑ (j : fin (n + 1)), (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α i j)).op) (f (ignore_o₂ α i j)) := begin rw [eq7, finset.sum_congr rfl], intros i _, rw [finset.sum_congr rfl], intros j _, split_ifs with h1 h2 h12, { refl, }, { exfalso, apply h12, exact even.add_even h1 h2 }, { exfalso, rw ← nat.odd_iff_not_even at h2, have := even.add_odd h1 h2, rw nat.odd_iff_not_even at this, apply this, exact h, }, { rw [id], refl, }, { rw ← nat.odd_iff_not_even at h1, have := odd.add_even h1 h, rw nat.odd_iff_not_even at this, exfalso, apply this, assumption, }, { rw [pi.neg_apply, id], refl, }, { rw [pi.neg_apply, neg_neg, id], refl, }, { rw ← nat.odd_iff_not_even at *, have := odd.add_odd h1 h, rw nat.even_iff_not_odd at this, exfalso, apply this, assumption }, end lemma eq9 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = ∑ (i : fin (n + 2)), ((∑ (j : fin (n + 1)) in finset.univ.filter (λ (j : fin (n + 1)), i.1 ≤ j.1), (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α i j)).op) (f (ignore_o₂ α i j))) + (∑ (j : fin (n + 1)) in finset.univ.filter (λ (j : fin (n + 1)), j.1 < i.1), (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α i j)).op) (f (ignore_o₂ α i j)))) := begin rw [eq8, finset.sum_congr rfl], intros i _, have : (finset.univ.filter (λ (j : fin (n + 1)), j.1 < i.val)) = (finset.univ.filter (λ (j : fin (n + 1)), i.val ≤ j.val))ᶜ, { ext1 k, split; intros hk; simp only [finset.compl_filter, not_le, finset.mem_filter, finset.mem_univ, true_and] at hk ⊢; assumption, }, rw [this, finset.sum_add_sum_compl], end lemma eq11 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = (∑ (i : fin (n + 2)), ∑ (j : fin (n + 1)) in finset.univ.filter (λ (j : fin (n + 1)), i.1 ≤ j.1), (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α i j)).op) (f (ignore_o₂ α i j))) + (∑ (i : fin (n + 2)), ∑ (j : fin (n + 1)) in finset.univ.filter (λ (j : fin (n + 1)), j.1 < i.1), (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α i j)).op) (f (ignore_o₂ α i j))) := begin rw [eq9, finset.sum_add_distrib], end lemma eq13 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = (∑ (i : fin (n + 2)), ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α i ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α i ⟨j.1, _⟩))) + (∑ (i : fin (n + 2)), ∑ (j : fin (n + 1)) in finset.univ.filter (λ (j : fin (n + 1)), j.1 < i.1), (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α i j)).op) (f (ignore_o₂ α i j))) := begin rw [eq11], congr' 1, rw [finset.sum_congr rfl], intros i _, apply finset.sum_bij, work_on_goal 5 { intros j hj, refine ⟨j.1, _⟩, rw finset.mem_Ico, rw finset.mem_filter at hj, refine ⟨hj.2, _⟩, exact j.2 }, { intros j hj, dsimp only, rw finset.mem_filter at hj, apply finset.mem_attach, }, { intros j hj, dsimp only, split_ifs, { rw [id, id], rw map_congr.vec_o_eq f (_ : ignore_o₂ α i j = ignore_o₂ α i ⟨j.1, _⟩), rw [← comp_apply, ← 𝓕.1.map_comp, ← op_comp], congr, congr' 1, rw subtype.ext_iff_val, }, { rw [add_monoid_hom.neg_apply, add_monoid_hom.neg_apply], rw map_congr.vec_o_eq f (_ : ignore_o₂ α i j = ignore_o₂ α i ⟨j.1, _⟩), rw [← comp_apply, ← 𝓕.1.map_comp, ← op_comp], congr, congr' 1, rw subtype.ext_iff_val, }, }, { intros j1 j2 h1 h2 H, dsimp only at H, rw subtype.ext_iff_val at *, assumption }, { intros j _, have hj := j.2, rw finset.mem_Ico at hj, refine ⟨⟨j.1, hj.2⟩, _, _⟩, rw finset.mem_filter, refine ⟨finset.mem_univ ⟨j.val, _⟩, hj.1⟩, dsimp only, rw subtype.ext_iff_val, }, end lemma eq14 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = (∑ (i : fin (n + 2)), ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α i ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α i ⟨j.1, _⟩))) + (∑ (i : fin (n + 2)), ∑ j in (finset.range i.1).attach, (ite (even (i.1 + j)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α i ⟨j.1, begin have hj := j.2, rw finset.mem_range at hj, have hi : i.1 ≤ n+1, { linarith [i.2], }, linarith, end⟩)).op) (f (ignore_o₂ α i ⟨j.1, _⟩))) := begin rw [eq13], congr' 1, rw [finset.sum_congr rfl], intros i hi, apply finset.sum_bij', work_on_goal 4 { intros j hj, rw finset.mem_filter at hj, refine ⟨j.1, _⟩, rw finset.mem_range, exact hj.2 }, work_on_goal 5 { intros j _, have hj := j.2, rw finset.mem_range at hj, refine ⟨j.1, _⟩, linarith [i.2], }, { intros j hj, dsimp only, split_ifs, { rw [id, id], rw map_congr.vec_o_eq f (_ : ignore_o₂ α i j = ignore_o₂ α i ⟨j.1, _⟩), rw [← comp_apply, ← 𝓕.1.map_comp, ← op_comp], congr, congr' 1, rw subtype.ext_iff_val, }, { rw [add_monoid_hom.neg_apply, add_monoid_hom.neg_apply], rw map_congr.vec_o_eq f (_ : ignore_o₂ α i j = ignore_o₂ α i ⟨j.1, _⟩), rw [← comp_apply, ← 𝓕.1.map_comp, ← op_comp], congr, congr' 1, rw subtype.ext_iff_val, }, }, { intros j hj, dsimp only, rw subtype.ext_iff_val, }, { intros j hj, rw subtype.ext_iff_val, }, { intros j hj, apply finset.mem_attach, }, { intros j _, have hj := j.2, rw finset.mem_range at hj, rw finset.mem_filter, dsimp only, refine ⟨_, hj⟩, apply finset.mem_univ, }, end lemma eq15 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = (∑ (i : fin (n + 2)), ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α i ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α i ⟨j.1, _⟩))) + (∑ j in (finset.range n.succ).attach, ∑ i in (finset.Ico j.1.succ n.succ.succ).attach, (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨i.1, begin have hi := i.2, rwa finset.mem_Ico at hi, exact hi.2, end⟩ ⟨j.1, begin have hj := j.2, rwa finset.mem_range at hj, end⟩)).op) (f (ignore_o₂ α _ _))) := begin rw [eq14], congr' 1, rw [finset.sum_sigma', finset.sum_sigma'], apply finset.sum_bij', work_on_goal 4 { refine λ x h, ⟨⟨x.2.1, begin have hx2 := x.2.2, have hx1 := x.1.2, rw finset.mem_range at hx2 ⊢, have : x.1.1 ≤ n + 1, { linarith }, refine lt_of_lt_of_le hx2 this, end⟩, ⟨x.1.1, _⟩⟩, }, work_on_goal 6 { refine λ x h, ⟨⟨x.2.1, begin have hx1 := x.1.2, have hx2 := x.2.2, rw finset.mem_range at hx1, rw finset.mem_Ico at hx2, exact hx2.2, end⟩, ⟨x.1.1, begin have hx1 := x.1.2, have hx2 := x.2.2, rw finset.mem_range at hx1 ⊢, rw finset.mem_Ico at hx2, refine lt_of_le_of_lt _ hx2.1, refl, end⟩⟩, }, { rintros ⟨⟨i, hi⟩, j⟩ h, dsimp only, congr, }, { rintros ⟨⟨i, hi⟩, j⟩ h, simp only, split, refl, rw heq_iff_eq, rw subtype.ext_iff_val, }, { rintros ⟨i, j⟩ h, simp only, split, rw subtype.ext_iff_val, rw heq_iff_eq, rw subtype.ext_iff_val, }, { have hx1 := x.1.2, have hx2 := x.2.2, rw finset.mem_range at hx2, rw finset.mem_Ico, refine ⟨_, hx1⟩, exact hx2, }, { rintros ⟨i, j⟩ h, rw finset.mem_sigma, split, apply finset.mem_attach, apply finset.mem_attach }, { intros x h, rw finset.mem_sigma, split, apply finset.mem_univ, apply finset.mem_attach, }, end lemma eq16 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = (∑ (i : fin (n + 2)), ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α i ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α i ⟨j.1, _⟩))) + (∑ i in (finset.range n.succ).attach, ∑ j in (finset.Ico i.1.succ n.succ.succ).attach, (ite (even (j.1 + i.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨j.1, begin have hi := j.2, rwa finset.mem_Ico at hi, exact hi.2, end⟩ ⟨i.1, begin have hj := i.2, rwa finset.mem_range at hj, end⟩)).op) (f (ignore_o₂ α _ _))) := begin rw [eq15], end lemma eq17 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = (∑ (i : fin (n + 2)), ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α i ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α i ⟨j.1, _⟩))) + (∑ i in (finset.range n.succ).attach, ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even ((j.1 + 1) + i.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨j.1 + 1, begin have hi := j.2, rw finset.mem_Ico at hi, rw succ_lt_succ_iff, exact hi.2, end⟩ ⟨i.1, begin have hj := i.2, rwa finset.mem_range at hj, end⟩)).op) (f (ignore_o₂ α ⟨j.1 + 1, _⟩ ⟨i.1, _⟩))) := begin rw [eq16], congr' 1, rw finset.sum_congr rfl, intros i hi, apply finset.sum_bij', work_on_goal 4 { intros j _, refine ⟨j.1.pred, _⟩, have hj := j.2, rw finset.mem_Ico at hj ⊢, rcases hj with ⟨hj1, hj2⟩, have ineq0 : 0 < j.1, { refine lt_of_lt_of_le _ hj1, exact nat.zero_lt_succ _, }, have eq1 : j.1 = j.1.pred.succ, { rwa nat.succ_pred_eq_of_pos, }, split, rw eq1 at hj1, rwa succ_le_succ_iff at hj1, rw eq1 at hj2, rwa succ_lt_succ_iff at hj2 }, work_on_goal 5 { intros j _, refine ⟨j.1 + 1, _⟩, have hj := j.2, rw finset.mem_Ico at hj ⊢, rcases hj with ⟨hj1, hj2⟩, split, rwa succ_le_succ_iff, rwa succ_lt_succ_iff, }, { intros j hj, dsimp only, rw map_congr.vec_o_eq f (_ : ignore_o₂ α ⟨j.1, _⟩ ⟨i.1, _⟩ = ignore_o₂ α ⟨j.1.pred + 1, _⟩ ⟨i.1, _⟩), by_cases e1 : even (j.1 + i.1), { rw [if_pos e1, if_pos, id, id, ← comp_apply, ← 𝓕.1.map_comp], congr, rwa [← nat.succ_eq_add_one, nat.succ_pred_eq_of_pos], have hj := j.2, rw finset.mem_Ico at hj, refine lt_of_lt_of_le _ hj.1, exact nat.zero_lt_succ _, }, { rw [if_neg e1, if_neg, add_monoid_hom.neg_apply, add_monoid_hom.neg_apply, ← comp_apply, ← 𝓕.1.map_comp], congr, rwa [← nat.succ_eq_add_one, nat.succ_pred_eq_of_pos], have hj := j.2, rw finset.mem_Ico at hj, refine lt_of_lt_of_le _ hj.1, exact nat.zero_lt_succ _, }, congr, rwa [← nat.succ_eq_add_one, nat.succ_pred_eq_of_pos], have hj := j.2, rw finset.mem_Ico at hj, refine lt_of_lt_of_le _ hj.1, exact nat.zero_lt_succ _, }, { intros j hj, simp only, rw subtype.ext_iff_val, dsimp only, rw [← nat.succ_eq_add_one, nat.succ_pred_eq_of_pos], have hj := j.2, rw finset.mem_Ico at hj, refine lt_of_lt_of_le _ hj.1, exact nat.zero_lt_succ _, }, { intros j hj, simp only, rw subtype.ext_iff_val, dsimp only, rw nat.pred_succ, }, { intros j hj, apply finset.mem_attach, }, { intros j hj, apply finset.mem_attach, }, end lemma eq18 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = (∑ (i : fin (n + 2)), ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α i ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α i ⟨j.1, _⟩))) + (∑ i in (finset.range n.succ).attach, ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even ((j.1 + 1) + i.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨i.1, begin have hi := i.2, rw finset.mem_range at hi, refine lt_trans hi _, exact lt_add_one _, end⟩ ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α ⟨i.1, _⟩ ⟨j.1, _⟩))) := begin rw eq17 𝓕 U n f α, apply congr_arg2 (+) rfl _, rw [finset.sum_congr rfl], intros i hi, rw [finset.sum_congr rfl], intros j hj, generalize_proofs _ h1 h2 h3 h4 h5, rw map_congr.vec_o_eq f (_ : ignore_o₂ α ⟨j.1 + 1, h1⟩ ⟨i.1, h2⟩ = ignore_o₂ α ⟨i.1, h4⟩ ⟨j.1, _⟩), split_ifs, { rw [id, id, ← comp_apply, ← 𝓕.1.map_comp], congr }, { rw [add_monoid_hom.neg_apply, add_monoid_hom.neg_apply, ← comp_apply, ← 𝓕.1.map_comp], congr }, have := ignore_o₂_symm' α i.2 j.2, convert ← this, end lemma eq19 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = (∑ (i : fin (n + 2)), ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α i ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α i ⟨j.1, _⟩))) + (∑ i in (finset.range n.succ).attach, - ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (j.1 + i.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨i.1, begin have hi := i.2, rw finset.mem_range at hi, refine lt_trans hi _, exact lt_add_one _, end⟩ ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α ⟨i.1, _⟩ ⟨j.1, _⟩))) := begin rw [eq18], congr' 1, rw [finset.sum_congr rfl], intros i _, rw [finset.neg_sum, finset.sum_congr rfl], intros j _, split_ifs with h1 h2, { exfalso, have o1 : odd (1 : ℕ) := odd_one, have := even.add_odd h2 o1, rw nat.odd_iff_not_even at this, apply this, convert h1 using 1, abel, }, { rw [id, add_monoid_hom.neg_apply, neg_neg], }, { rw [id, add_monoid_hom.neg_apply], }, { rw ← nat.odd_iff_not_even at h h1, have o1 : odd (1 : ℕ) := odd_one, have := odd.add_odd h o1, rw nat.even_iff_not_odd at this, exfalso, apply this, convert h1 using 1, abel, }, end lemma eq20₀ (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = (∑ i in (finset.range (n+2)).attach, ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨i.1, begin have hi := i.2, exact finset.mem_range.mp hi, end⟩ ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α ⟨i.1, _⟩ ⟨j.1, _⟩))) + (∑ i in (finset.range n.succ).attach, - ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (j.1 + i.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨i.1, begin have hi := i.2, rw finset.mem_range at hi, refine lt_trans hi _, exact lt_add_one _, end⟩ ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α ⟨i.1, _⟩ ⟨j.1, _⟩))) := begin rw [eq19], congr' 1, rw finset.sum_fin_eq_sum_range, rw ← finset.sum_attach, rw finset.sum_congr rfl, intros i hi, rw dif_pos, refl, end lemma eq20₁ (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = (∑ i in (finset.range (n+1)).attach, ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨i.1, begin have hi := i.2, refine lt_trans (finset.mem_range.mp hi) _, exact lt_add_one _, end⟩ ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α ⟨i.1, _⟩ ⟨j.1, _⟩))) + (∑ j in (finset.Ico n.succ n.succ).attach, (ite (even (n.succ + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨n.succ, begin exact lt_add_one _, end⟩ ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α ⟨n.succ, _⟩ ⟨j.1, _⟩))) + (∑ i in (finset.range n.succ).attach, - ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (j.1 + i.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨i.1, begin have hi := i.2, rw finset.mem_range at hi, refine lt_trans hi _, exact lt_add_one _, end⟩ ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α ⟨i.1, _⟩ ⟨j.1, _⟩))) := have eq0 : ∑ i in (finset.range (n+2)).attach, ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨i.1, begin have hi := i.2, exact finset.mem_range.mp hi, end⟩ ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α ⟨i.1, _⟩ ⟨j.1, _⟩)) = ∑ i in (insert n.succ (finset.range (n+1))).attach, ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨i.1, begin have hi := i.2, rw finset.mem_insert at hi, cases hi, rw hi, exact lt_add_one _, rw finset.mem_range at hi, refine lt_trans hi _, exact lt_add_one _, end⟩ ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α ⟨i.1, _⟩ ⟨j.1, _⟩)), begin rw finset.sum_bij', work_on_goal 4 { intros a _, refine ⟨a.1, _⟩, rw finset.mem_insert, have ha := a.2, by_cases a.1 = n.succ, left, assumption, right, rw finset.mem_range at ha ⊢, contrapose! h, have ha' : a.1 ≤ n+1, linarith, refine le_antisymm ha' h, }, work_on_goal 5 { intros a _, refine ⟨a.1, _⟩, have ha := a.2, rw finset.mem_insert at ha, rw finset.mem_range at ha ⊢, cases ha, rw ha, exact lt_add_one _, linarith, }, { intros, simp only, }, { intros, simp only, rw subtype.ext_iff_val, }, { intros, simp only, rw subtype.ext_iff_val, }, { intros, simp only, apply finset.mem_attach }, { intros, apply finset.mem_attach }, end, begin rw [eq20₀], apply congr_arg2 (+) _ rfl, rw eq0, rw finset.attach_insert, rw finset.sum_insert, conv_lhs { simp only [add_comm] }, congr' 1, { simp only [finset.sum_image, subtype.forall, subtype.coe_mk, imp_self, implies_true_iff], }, { rw finset.mem_image, push_neg, intros a _, have ha := a.2, rw finset.mem_range at ha, intro r, rw r at ha, apply lt_irrefl _ ha, }, end lemma eq21 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = (∑ i in (finset.range (n+1)).attach, ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨i.1, begin have hi := i.2, refine lt_trans (finset.mem_range.mp hi) _, exact lt_add_one _, end⟩ ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α ⟨i.1, _⟩ ⟨j.1, _⟩))) + (∑ i in (finset.range n.succ).attach, - ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (j.1 + i.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨i.1, begin have hi := i.2, rw finset.mem_range at hi, refine lt_trans hi _, exact lt_add_one _, end⟩ ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α ⟨i.1, _⟩ ⟨j.1, _⟩))) + (∑ j in (finset.Ico n.succ n.succ).attach, (ite (even (n.succ + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨n.succ, begin exact lt_add_one _, end⟩ ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α ⟨n.succ, _⟩ ⟨j.1, _⟩))) := begin rw [eq20₁], abel, end lemma eq22 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = (∑ i in (finset.range (n+1)).attach, ((∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (i.1 + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨i.1, begin have hi := i.2, refine lt_trans (finset.mem_range.mp hi) _, exact lt_add_one _, end⟩ ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α ⟨i.1, _⟩ ⟨j.1, _⟩))) + (- ∑ j in (finset.Ico i.1 n.succ).attach, (ite (even (j.1 + i.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨i.1, begin have hi := i.2, rw finset.mem_range at hi, refine lt_trans hi _, exact lt_add_one _, end⟩ ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α ⟨i.1, _⟩ ⟨j.1, _⟩))))) + (∑ j in (finset.Ico n.succ n.succ).attach, (ite (even (n.succ + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨n.succ, begin exact lt_add_one _, end⟩ ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α ⟨n.succ, _⟩ ⟨j.1, _⟩))) := begin rw [eq21, finset.sum_add_distrib], end lemma eq23 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = (∑ i in (finset.range (n+1)).attach, 0) + (∑ j in (finset.Ico n.succ n.succ).attach, (ite (even (n.succ + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨n.succ, begin exact lt_add_one _, end⟩ ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α ⟨n.succ, _⟩ ⟨j.1, _⟩))) := begin rw [eq22], congr' 1, rw finset.sum_congr rfl, intros i _, simp_rw [add_comm], rw add_neg_eq_zero, end lemma eq24 (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = 0 + (∑ j in (finset.Ico n.succ n.succ).attach, (ite (even (n.succ + j.1)) id has_neg.neg) (𝓕.1.map (hom_of_le (face.le_ignore₂ α ⟨n.succ, begin exact lt_add_one _, end⟩ ⟨j.1, begin have hj := j.2, rw finset.mem_Ico at hj, exact hj.2, end⟩)).op) (f (ignore_o₂ α ⟨n.succ, _⟩ ⟨j.1, _⟩))) := begin rw [eq23], congr', rw finset.sum_eq_zero, intros, refl, end lemma eq_zero (f : C_o 𝓕 U n) (α : vec_o U (n+2)) : dd_o 𝓕 U n f α = 0 := begin rw [eq24, zero_add], convert finset.sum_empty, rw finset.Ico_self, rw finset.attach_empty end end dd_o_aux lemma dd_o_eq_zero' (n : ℕ) : dd_o 𝓕 U n = 0 := begin ext f α, convert dd_o_aux.eq_zero 𝓕 U n f α, end lemma dd_o_eq_zero (n : ℕ) (f α) : d_o 𝓕 U (n+1) (d_o 𝓕 U n f) α = 0 := begin have : dd_o 𝓕 U n f α = 0, { rw dd_o_eq_zero', simp }, exact this, end end d_o namespace d_o_small open_locale big_operators lemma vec_one_ignore_eq (α : vec_o U 1) : ignore_o α 0 = vec_o.zero U := begin ext j, rcases j with ⟨j, hj⟩, linarith, end lemma d_o.zeroth_apply (f : C_o 𝓕 U 0) (α : vec_o U 1) : d_o 𝓕 U _ f α = 𝓕.1.map (hom_of_le $ begin rw face.vec_o_zero, exact le_top, end).op (f (vec_o.zero U)) := begin rw dd_o_aux.d_o_def, rw finset.sum_fin_eq_sum_range, rw finset.sum_range_one, rw dif_pos, swap, exact nat.zero_lt_succ _, rw if_pos, swap, exact even_zero, rw [id], erw map_congr.vec_o_eq f (vec_one_ignore_eq U α), rw [← comp_apply, ← 𝓕.1.map_comp], congr' 1, end lemma d_o.one_apply (f : C_o 𝓕 U 1) (α : vec_o U 2) : d_o 𝓕 U 1 f α = 𝓕.1.map (hom_of_le (face.le_ignore_o _ _)).op (f (ignore_o α 0)) - 𝓕.1.map (hom_of_le (face.le_ignore_o _ _)).op (f (ignore_o α 1)) := begin rw dd_o_aux.d_o_def, rw finset.sum_fin_eq_sum_range, have seteq : finset.range (1 + 1) = {0, 1}, { norm_num, ext, split, { intros h, rw finset.mem_range at h, rw [finset.mem_insert, finset.mem_singleton], interval_cases a; cc, }, { intros h, rw [finset.mem_insert, finset.mem_singleton] at h, rw finset.mem_range, rcases h with rfl|rfl; linarith, }, }, rw [seteq, finset.sum_pair], swap, linarith, rw [dif_pos (nat.zero_lt_succ _), if_pos (even_zero), id, dif_pos (lt_add_one 1), if_neg], swap, rw ← nat.odd_iff_not_even, exact odd_one, change _ + (- 𝓕.1.map _ _) = _, rw ← sub_eq_add_neg, refl, end end d_o_small end
\documentclass[./main.tex]{subfiles} \begin{document} \chapter{Eldritch Influences} \subfile{new_mechanics/eldritch_influences/monstrosity.tex} \subfile{new_mechanics/eldritch_influences/crossingover.tex} \subfile{new_mechanics/eldritch_influences/eldritchbloodline.tex} \chapter{Grand Strategy} \subfile{new_mechanics/grand_strategy/overview.tex} \chapter{Elixirs and Gadgets} \subfile{new_mechanics/elixirs/elixirs.tex} \subfile{new_mechanics/gadgets/gadgets.tex} \end{document}
Require Import Coq.Lists.List. Module List. Definition enumerate {A} (ls : list A) : list (nat * A) := combine (seq 0 (length ls)) ls. Definition find_index {A} (f : A -> bool) (xs : list A) : option nat := option_map (@fst _ _) (find (fun v => f (snd v)) (enumerate xs)). End List.
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.logic.function.basic import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib /-! # Semiconjugate and commuting maps We define the following predicates: * `function.semiconj`: `f : α → β` semiconjugates `ga : α → α` to `gb : β → β` if `f ∘ ga = gb ∘ f`; * `function.semiconj₂: `f : α → β` semiconjugates a binary operation `ga : α → α → α` to `gb : β → β → β` if `f (ga x y) = gb (f x) (f y)`; * `f : α → α` commutes with `g : α → α` if `f ∘ g = g ∘ f`, or equivalently `semiconj f g g`. -/ namespace function /-- We say that `f : α → β` semiconjugates `ga : α → α` to `gb : β → β` if `f ∘ ga = gb ∘ f`. -/ def semiconj {α : Type u_1} {β : Type u_2} (f : α → β) (ga : α → α) (gb : β → β) := ∀ (x : α), f (ga x) = gb (f x) namespace semiconj protected theorem comp_eq {α : Type u_1} {β : Type u_2} {f : α → β} {ga : α → α} {gb : β → β} (h : semiconj f ga gb) : f ∘ ga = gb ∘ f := funext h protected theorem eq {α : Type u_1} {β : Type u_2} {f : α → β} {ga : α → α} {gb : β → β} (h : semiconj f ga gb) (x : α) : f (ga x) = gb (f x) := h x theorem comp_right {α : Type u_1} {β : Type u_2} {f : α → β} {ga : α → α} {ga' : α → α} {gb : β → β} {gb' : β → β} (h : semiconj f ga gb) (h' : semiconj f ga' gb') : semiconj f (ga ∘ ga') (gb ∘ gb') := sorry theorem comp_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} {fab : α → β} {fbc : β → γ} {ga : α → α} {gb : β → β} {gc : γ → γ} (hab : semiconj fab ga gb) (hbc : semiconj fbc gb gc) : semiconj (fbc ∘ fab) ga gc := sorry theorem id_right {α : Type u_1} {β : Type u_2} {f : α → β} : semiconj f id id := fun (_x : α) => rfl theorem id_left {α : Type u_1} {ga : α → α} : semiconj id ga ga := fun (_x : α) => rfl theorem inverses_right {α : Type u_1} {β : Type u_2} {f : α → β} {ga : α → α} {ga' : α → α} {gb : β → β} {gb' : β → β} (h : semiconj f ga gb) (ha : right_inverse ga' ga) (hb : left_inverse gb' gb) : semiconj f ga' gb' := sorry end semiconj /-- Two maps `f g : α → α` commute if `f ∘ g = g ∘ f`. -/ def commute {α : Type u_1} (f : α → α) (g : α → α) := semiconj f g g theorem semiconj.commute {α : Type u_1} {f : α → α} {g : α → α} (h : semiconj f g g) : commute f g := h namespace commute theorem refl {α : Type u_1} (f : α → α) : commute f f := fun (_x : α) => Eq.refl (f (f _x)) theorem symm {α : Type u_1} {f : α → α} {g : α → α} (h : commute f g) : commute g f := fun (x : α) => Eq.symm (h x) theorem comp_right {α : Type u_1} {f : α → α} {g : α → α} {g' : α → α} (h : commute f g) (h' : commute f g') : commute f (g ∘ g') := semiconj.comp_right h h' theorem comp_left {α : Type u_1} {f : α → α} {f' : α → α} {g : α → α} (h : commute f g) (h' : commute f' g) : commute (f ∘ f') g := symm (comp_right (symm h) (symm h')) theorem id_right {α : Type u_1} {f : α → α} : commute f id := semiconj.id_right theorem id_left {α : Type u_1} {f : α → α} : commute id f := semiconj.id_left end commute /-- A map `f` semiconjugates a binary operation `ga` to a binary operation `gb` if for all `x`, `y` we have `f (ga x y) = gb (f x) (f y)`. E.g., a `monoid_hom` semiconjugates `(*)` to `(*)`. -/ def semiconj₂ {α : Type u_1} {β : Type u_2} (f : α → β) (ga : α → α → α) (gb : β → β → β) := ∀ (x y : α), f (ga x y) = gb (f x) (f y) namespace semiconj₂ protected theorem eq {α : Type u_1} {β : Type u_2} {f : α → β} {ga : α → α → α} {gb : β → β → β} (h : semiconj₂ f ga gb) (x : α) (y : α) : f (ga x y) = gb (f x) (f y) := h x y protected theorem comp_eq {α : Type u_1} {β : Type u_2} {f : α → β} {ga : α → α → α} {gb : β → β → β} (h : semiconj₂ f ga gb) : bicompr f ga = bicompl gb f f := funext fun (x : α) => funext (h x) theorem id_left {α : Type u_1} (op : α → α → α) : semiconj₂ id op op := fun (_x _x_1 : α) => rfl theorem comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} {f : α → β} {ga : α → α → α} {gb : β → β → β} {f' : β → γ} {gc : γ → γ → γ} (hf' : semiconj₂ f' gb gc) (hf : semiconj₂ f ga gb) : semiconj₂ (f' ∘ f) ga gc := sorry theorem is_associative_right {α : Type u_1} {β : Type u_2} {f : α → β} {ga : α → α → α} {gb : β → β → β} [is_associative α ga] (h : semiconj₂ f ga gb) (h_surj : surjective f) : is_associative β gb := sorry theorem is_associative_left {α : Type u_1} {β : Type u_2} {f : α → β} {ga : α → α → α} {gb : β → β → β} [is_associative β gb] (h : semiconj₂ f ga gb) (h_inj : injective f) : is_associative α ga := sorry theorem is_idempotent_right {α : Type u_1} {β : Type u_2} {f : α → β} {ga : α → α → α} {gb : β → β → β} [is_idempotent α ga] (h : semiconj₂ f ga gb) (h_surj : surjective f) : is_idempotent β gb := sorry theorem is_idempotent_left {α : Type u_1} {β : Type u_2} {f : α → β} {ga : α → α → α} {gb : β → β → β} [is_idempotent β gb] (h : semiconj₂ f ga gb) (h_inj : injective f) : is_idempotent α ga := sorry
The coefficient of the $i$th term of the sum of polynomials is the sum of the coefficients of the $i$th term of each polynomial.
# QGS model: Manually setting the basis and the inner products definition ## Atmosphere coupled to an ocean with special boundary conditions In this notebook, we describe how to setup a user-defined basis for one of the model’s component. We will do it for the ocean, but the approach is similar for the other components. We will project the ocean equations on four modes proposed in * S. Pierini. *Low-frequency variability, coherence resonance, and phase selection in a low-order model of the wind-driven ocean circulation.* Journal of Physical Oceanography, **41**(9):1585–1604, 2011. [doi:10.1175/JPO-D-10-05018.1](https://journals.ametsoc.org/doi/full/10.1175/JPO-D-10-05018.1). * S. Vannitsem and L. De Cruz. *A 24-variable low-order coupled ocean–atmosphere model: OA-QG-WS v2*. Geoscientific Model Development, 7(2):649–662, 2014. [doi:10.5194/gmd-7-649-2014](https://doi.org/10.5194/gmd-7-649-2014). These four modes are given by * $\tilde\phi_1(x,y)=2 \, e^{−\alpha x} \sin(n x/2) \sin(y)$ * $\tilde\phi_2(x,y)=2 \, e^{−\alpha x} \sin(n x) \sin(y)$ * $\tilde\phi_3(x,y)=2 \, e^{−\alpha x} \sin(n x/2) \sin(2y)$ * $\tilde\phi_4(x,y)=2 \, e^{−\alpha x} \sin(n x) \sin(2y)$ The exponential factors represent an intensification of the flows, forcings and heat exchanges in the western part of the domain. This ocean is then connected to a channel atmosphere using a symbolic basis of functions. ### Warning ! This initialization method is not yet well-defined in qgs. It builds the model block by block to construct an ad-hoc model version. It is an advanced and somewhat experimental feature of the model. ## Modules import First, setting the path and loading of some modules ```python import sys, os, warnings ``` ```python sys.path.extend([os.path.abspath('../')]) ``` ```python import numpy as np import matplotlib.pyplot as plt from numba import njit ``` ```python from matplotlib import rc rc('font',**{'family':'serif','sans-serif':['Times'],'size':12}) ``` Initializing the random number generator (for reproducibility). -- Disable if needed. ```python np.random.seed(210217) ``` Importing the model's modules ```python from qgs.params.params import QgParams from qgs.basis.base import SymbolicBasis from qgs.inner_products.definition import StandardSymbolicInnerProductDefinition from qgs.inner_products.symbolic import AtmosphericSymbolicInnerProducts, OceanicSymbolicInnerProducts from qgs.tensors.qgtensor import QgsTensor from qgs.functions.sparse_mul import sparse_mul3 from qgs.integrators.integrator import RungeKuttaIntegrator ``` and diagnostics ```python from qgs.diagnostics.streamfunctions import MiddleAtmosphericStreamfunctionDiagnostic, OceanicLayerStreamfunctionDiagnostic from qgs.diagnostics.temperatures import MiddleAtmosphericTemperatureDiagnostic, OceanicLayerTemperatureDiagnostic from qgs.diagnostics.variables import VariablesDiagnostic, GeopotentialHeightDifferenceDiagnostic from qgs.diagnostics.multi import MultiDiagnostic ``` and some SymPy functions ```python from sympy import symbols, sin, exp, pi ``` ## Systems definition General parameters ```python # Time parameters dt = 0.1 # Saving the model state n steps write_steps = 100 number_of_trajectories = 1 ``` Setting some model parameters and setting the atmosphere basis ```python # Model parameters instantiation with some non-default specs model_parameters = QgParams({'n': 1.5}) # Mode truncation at the wavenumber 2 in both x and y spatial # coordinates for the atmosphere model_parameters.set_atmospheric_channel_fourier_modes(2, 2, mode="symbolic") ``` Creating the ocean basis ```python ocean_basis = SymbolicBasis() x, y = symbols('x y') # x and y coordinates on the model's spatial domain n, al = symbols('n al', real=True, nonnegative=True) # aspect ratio and alpha coefficients for i in range(1, 3): for j in range(1, 3): ocean_basis.functions.append(2 * exp(- al * x) * sin(j * n * x / 2) * sin(i * y)) ``` We then set the value of the parameter α to a certain value (here α=1). Please note that the α is then an extrinsic parameter of the model that you have to specify through a substitution: ```python ocean_basis.substitutions.append((al, 1.)) ocean_basis.substitutions.append((n, model_parameters.scale_params.n)) ``` Setting now the ocean basis ```python model_parameters.set_oceanic_modes(ocean_basis) ``` Additionally, for these particular ocean basis functions, a special inner product needs to be defined instead of the standard one proposed. We consider thus as in the publication linked above the following inner product: ```python class UserInnerProductDefinition(StandardSymbolicInnerProductDefinition): def symbolic_inner_product(self, S, G, symbolic_expr=False, integrand=False): """Function defining the inner product to be computed symbolically: :math:`(S, G) = \\frac{n}{2\\pi^2}\\int_0^\\pi\\int_0^{2\\pi/n} e^{2 \\alpha x} \\, S(x,y)\\, G(x,y)\\, \\mathrm{d} x \\, \\mathrm{d} y`. Parameters ---------- S: Sympy expression Left-hand side function of the product. G: Sympy expression Right-hand side function of the product. symbolic_expr: bool, optional If `True`, return the integral as a symbolic expression object. Else, return the integral performed symbolically. integrand: bool, optional If `True`, return the integrand of the integral and its integration limits as a list of symbolic expression object. Else, return the integral performed symbolically. Returns ------- Sympy expression The result of the symbolic integration """ expr = (n / (2 * pi ** 2)) * exp(2 * al * x) * S * G if integrand: return expr, (x, 0, 2 * pi / n), (y, 0, pi) else: return self.integrate_over_domain(self.optimizer(expr), symbolic_expr=symbolic_expr) ``` Finally setting some other model's parameters: ```python # Setting MAOOAM parameters according to the publication linked above model_parameters.set_params({'kd': 0.029, 'kdp': 0.029, 'r': 1.0e-7, 'h': 136.5, 'd': 1.1e-7}) model_parameters.atemperature_params.set_params({'eps': 0.76, 'T0': 289.3, 'hlambda': 15.06}) model_parameters.gotemperature_params.set_params({'gamma': 5.6e8, 'T0': 301.46}) ``` Setting the short-wave radiation component as in the publication above: $C_{\text{a},1}$ and $C_{\text{o},1}$ ```python model_parameters.atemperature_params.set_insolation(103.3333, 0) model_parameters.gotemperature_params.set_insolation(310, 0) ``` Printing the model's parameters ```python model_parameters.print_params() ``` We now construct the tendencies of the model by first constructing the ocean and atmosphere inner products objects. In addition, a inner product definition instance defined above must be passed to the ocean inner products object: ```python with warnings.catch_warnings(): warnings.simplefilter("ignore") ip = UserInnerProductDefinition() aip = AtmosphericSymbolicInnerProducts(model_parameters) oip = OceanicSymbolicInnerProducts(model_parameters, inner_product_definition=ip) ``` and finally we create manually the tendencies function, first by creating the tensor object: ```python aotensor = QgsTensor(model_parameters, aip, oip) ``` and then the Python-[Numba](https://numba.pydata.org/) callable for the model’s tendencies $\boldsymbol{f}$ : ```python coo = aotensor.tensor.coords.T val = aotensor.tensor.data @njit def f(t, x): xx = np.concatenate((np.full((1,), 1.), x)) xr = sparse_mul3(coo, val, xx, xx) return xr[1:] ``` ## Time integration Defining an integrator ```python integrator = RungeKuttaIntegrator() integrator.set_func(f) ``` Start on a random initial condition and integrate over a transient time to obtain an initial condition on the attractors ```python %%time ## Might take several minutes, depending on your cpu computational power. ic = np.random.rand(model_parameters.ndim)*0.0001 integrator.integrate(0., 3000000., dt, ic=ic, write_steps=0) time, ic = integrator.get_trajectories() ``` Now integrate to obtain a trajectory on the attractor ```python %%time integrator.integrate(0., 500000., dt, ic=ic, write_steps=write_steps) reference_time, reference_traj = integrator.get_trajectories() ``` Plotting the result in 3D and 2D ```python varx = 21 vary = 25 varz = 0 fig = plt.figure(figsize=(10, 8)) axi = fig.add_subplot(111, projection='3d') axi.scatter(reference_traj[varx], reference_traj[vary], reference_traj[varz], s=0.2); axi.set_xlabel('$'+model_parameters.latex_var_string[varx]+'$') axi.set_ylabel('$'+model_parameters.latex_var_string[vary]+'$') axi.set_zlabel('$'+model_parameters.latex_var_string[varz]+'$'); ``` ```python varx = 21 vary = 25 plt.figure(figsize=(10, 8)) plt.plot(reference_traj[varx], reference_traj[vary], marker='o', ms=0.1, ls='') plt.xlabel('$'+model_parameters.latex_var_string[varx]+'$') plt.ylabel('$'+model_parameters.latex_var_string[vary]+'$'); ``` ```python var = 21 plt.figure(figsize=(10, 8)) plt.plot(model_parameters.dimensional_time*reference_time, reference_traj[var]) plt.xlabel('time (days)') plt.ylabel('$'+model_parameters.latex_var_string[var]+'$'); ``` ## Showing the resulting fields (animation) Here, we want to show that the diagnostics adapt to the manually set basis. This is an advanced feature showing the time evolution of diagnostic of the model. It shows simultaneously a scatter plot of the variable $\psi_{{\rm a}, 1}$, $\psi_{{\rm o}, 2}$ and $\theta_{{\rm o}, 2}$, with the corresponding atmospheric and oceanic streamfunctions and temperature at 500 hPa. Please read the documentation for more information. Creating the diagnostics (for field plots, we must specify the grid step): * For the 500hPa geopotential height: ```python psi_a = MiddleAtmosphericStreamfunctionDiagnostic(model_parameters, delta_x=0.1, delta_y=0.1, geopotential=True) ``` * For the 500hPa atmospheric temperature: ```python theta_a = MiddleAtmosphericTemperatureDiagnostic(model_parameters, delta_x=0.1, delta_y=0.1) ``` * For the ocean streamfunction: ```python psi_o = OceanicLayerStreamfunctionDiagnostic(model_parameters, delta_x=0.1, delta_y=0.1, conserved=False) ``` * For the ocean temperature: ```python theta_o = OceanicLayerTemperatureDiagnostic(model_parameters, delta_x=0.1, delta_y=0.1) ``` * For the nondimensional variables $\psi_{{\rm a}, 1}$, $\psi_{{\rm o}, 2}$ and $\theta_{{\rm o}, 2}$: ```python variable_nondim = VariablesDiagnostic([21, 25, 0], model_parameters, False) ``` * For the geopotential height difference between North and South: ```python geopot_dim = GeopotentialHeightDifferenceDiagnostic([[[np.pi/model_parameters.scale_params.n, np.pi/4], [np.pi/model_parameters.scale_params.n, 3*np.pi/4]]], model_parameters, True) ``` ```python # setting also the background background = VariablesDiagnostic([21, 25, 0], model_parameters, False) background.set_data(reference_time, reference_traj) ``` Selecting a subset of the data to plot: ```python stride = 10 time = reference_time[10000:10000+5200*stride:stride] traj = reference_traj[:, 10000:10000+5200*stride:stride] ``` Creating a multi diagnostic with both: ```python m = MultiDiagnostic(2,3) m.add_diagnostic(geopot_dim, diagnostic_kwargs={'style':'moving-timeserie'}) m.add_diagnostic(theta_a, diagnostic_kwargs={'show_time':False}) m.add_diagnostic(theta_o, diagnostic_kwargs={'show_time':False}) m.add_diagnostic(variable_nondim, diagnostic_kwargs={'show_time':False, 'background': background, 'style':'3Dscatter'}, plot_kwargs={'ms': 0.2}) m.add_diagnostic(psi_a, diagnostic_kwargs={'show_time':False}) m.add_diagnostic(psi_o, diagnostic_kwargs={'show_time':False}) m.set_data(time, traj) ``` and show an interactive animation: ```python rc('font',**{'family':'serif','sans-serif':['Times'],'size':12}) m.animate(figsize=(23,12)) ``` or a movie (may takes some minutes to compute): ```python %%time rc('font',**{'family':'serif','sans-serif':['Times'],'size':12}) m.movie(figsize=(23.5,12), anim_kwargs={'interval': 100, 'frames':2000}) ```
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.specific_limits.basic import topology.metric_space.isometry import topology.instances.ennreal /-! # Hausdorff distance The Hausdorff distance on subsets of a metric (or emetric) space. Given two subsets `s` and `t` of a metric space, their Hausdorff distance is the smallest `d` such that any point `s` is within `d` of a point in `t`, and conversely. This quantity is often infinite (think of `s` bounded and `t` unbounded), and therefore better expressed in the setting of emetric spaces. ## Main definitions This files introduces: * `inf_edist x s`, the infimum edistance of a point `x` to a set `s` in an emetric space * `Hausdorff_edist s t`, the Hausdorff edistance of two sets in an emetric space * Versions of these notions on metric spaces, called respectively `inf_dist` and `Hausdorff_dist` * `thickening δ s`, the open thickening by radius `δ` of a set `s` in a pseudo emetric space. * `cthickening δ s`, the closed thickening by radius `δ` of a set `s` in a pseudo emetric space. -/ noncomputable theory open_locale classical nnreal ennreal topological_space universes u v w open classical set function topological_space filter variables {ι : Sort*} {α : Type u} {β : Type v} namespace emetric section inf_edist variables [pseudo_emetric_space α] [pseudo_emetric_space β] {x y : α} {s t : set α} {Φ : α → β} /-! ### Distance of a point to a set as a function into `ℝ≥0∞`. -/ /-- The minimal edistance of a point to a set -/ def inf_edist (x : α) (s : set α) : ℝ≥0∞ := ⨅ y ∈ s, edist x y @[simp] lemma inf_edist_empty : inf_edist x ∅ = ∞ := infi_emptyset lemma le_inf_edist {d} : d ≤ inf_edist x s ↔ ∀ y ∈ s, d ≤ edist x y := by simp only [inf_edist, le_infi_iff] /-- The edist to a union is the minimum of the edists -/ @[simp] lemma inf_edist_union : inf_edist x (s ∪ t) = inf_edist x s ⊓ inf_edist x t := infi_union @[simp] lemma inf_edist_Union (f : ι → set α) (x : α) : inf_edist x (⋃ i, f i) = ⨅ i, inf_edist x (f i) := infi_Union f _ /-- The edist to a singleton is the edistance to the single point of this singleton -/ @[simp] lemma inf_edist_singleton : inf_edist x {y} = edist x y := infi_singleton /-- The edist to a set is bounded above by the edist to any of its points -/ lemma inf_edist_le_edist_of_mem (h : y ∈ s) : inf_edist x s ≤ edist x y := infi₂_le _ h /-- If a point `x` belongs to `s`, then its edist to `s` vanishes -/ lemma inf_edist_zero_of_mem (h : x ∈ s) : inf_edist x s = 0 := nonpos_iff_eq_zero.1 $ @edist_self _ _ x ▸ inf_edist_le_edist_of_mem h /-- The edist is antitone with respect to inclusion. -/ lemma inf_edist_anti (h : s ⊆ t) : inf_edist x t ≤ inf_edist x s := infi_le_infi_of_subset h /-- The edist to a set is `< r` iff there exists a point in the set at edistance `< r` -/ lemma inf_edist_lt_iff {r : ℝ≥0∞} : inf_edist x s < r ↔ ∃ y ∈ s, edist x y < r := by simp_rw [inf_edist, infi_lt_iff] /-- The edist of `x` to `s` is bounded by the sum of the edist of `y` to `s` and the edist from `x` to `y` -/ lemma inf_edist_le_inf_edist_add_edist : inf_edist x s ≤ inf_edist y s + edist x y := calc (⨅ z ∈ s, edist x z) ≤ ⨅ z ∈ s, edist y z + edist x y : infi₂_mono $ λ z hz, (edist_triangle _ _ _).trans_eq (add_comm _ _) ... = (⨅ z ∈ s, edist y z) + edist x y : by simp only [ennreal.infi_add] lemma inf_edist_le_edist_add_inf_edist : inf_edist x s ≤ edist x y + inf_edist y s := by { rw add_comm, exact inf_edist_le_inf_edist_add_edist } /-- The edist to a set depends continuously on the point -/ @[continuity] lemma continuous_inf_edist : continuous (λx, inf_edist x s) := continuous_of_le_add_edist 1 (by simp) $ by simp only [one_mul, inf_edist_le_inf_edist_add_edist, forall_2_true_iff] /-- The edist to a set and to its closure coincide -/ lemma inf_edist_closure : inf_edist x (closure s) = inf_edist x s := begin refine le_antisymm (inf_edist_anti subset_closure) _, refine ennreal.le_of_forall_pos_le_add (λε εpos h, _), have ε0 : 0 < (ε / 2 : ℝ≥0∞) := by simpa [pos_iff_ne_zero] using εpos, have : inf_edist x (closure s) < inf_edist x (closure s) + ε/2, from ennreal.lt_add_right h.ne ε0.ne', rcases inf_edist_lt_iff.mp this with ⟨y, ycs, hy⟩, -- y : α, ycs : y ∈ closure s, hy : edist x y < inf_edist x (closure s) + ↑ε / 2 rcases emetric.mem_closure_iff.1 ycs (ε/2) ε0 with ⟨z, zs, dyz⟩, -- z : α, zs : z ∈ s, dyz : edist y z < ↑ε / 2 calc inf_edist x s ≤ edist x z : inf_edist_le_edist_of_mem zs ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... ≤ (inf_edist x (closure s) + ε / 2) + (ε/2) : add_le_add (le_of_lt hy) (le_of_lt dyz) ... = inf_edist x (closure s) + ↑ε : by rw [add_assoc, ennreal.add_halves] end /-- A point belongs to the closure of `s` iff its infimum edistance to this set vanishes -/ lemma mem_closure_iff_inf_edist_zero : x ∈ closure s ↔ inf_edist x s = 0 := ⟨λ h, by { rw ← inf_edist_closure, exact inf_edist_zero_of_mem h }, λ h, emetric.mem_closure_iff.2 $ λ ε εpos, inf_edist_lt_iff.mp $ by rwa h⟩ /-- Given a closed set `s`, a point belongs to `s` iff its infimum edistance to this set vanishes -/ lemma mem_iff_inf_edist_zero_of_closed (h : is_closed s) : x ∈ s ↔ inf_edist x s = 0 := begin convert ← mem_closure_iff_inf_edist_zero, exact h.closure_eq end lemma disjoint_closed_ball_of_lt_inf_edist {r : ℝ≥0∞} (h : r < inf_edist x s) : disjoint (closed_ball x r) s := begin rw disjoint_left, assume y hy h'y, apply lt_irrefl (inf_edist x s), calc inf_edist x s ≤ edist x y : inf_edist_le_edist_of_mem h'y ... ≤ r : by rwa [mem_closed_ball, edist_comm] at hy ... < inf_edist x s : h end /-- The infimum edistance is invariant under isometries -/ lemma inf_edist_image (hΦ : isometry Φ) : inf_edist (Φ x) (Φ '' t) = inf_edist x t := by simp only [inf_edist, infi_image, hΦ.edist_eq] lemma _root_.is_open.exists_Union_is_closed {U : set α} (hU : is_open U) : ∃ F : ℕ → set α, (∀ n, is_closed (F n)) ∧ (∀ n, F n ⊆ U) ∧ ((⋃ n, F n) = U) ∧ monotone F := begin obtain ⟨a, a_pos, a_lt_one⟩ : ∃ (a : ℝ≥0∞), 0 < a ∧ a < 1 := exists_between (ennreal.zero_lt_one), let F := λ (n : ℕ), (λ x, inf_edist x Uᶜ) ⁻¹' (Ici (a^n)), have F_subset : ∀ n, F n ⊆ U, { assume n x hx, have : inf_edist x Uᶜ ≠ 0 := ((ennreal.pow_pos a_pos _).trans_le hx).ne', contrapose! this, exact inf_edist_zero_of_mem this }, refine ⟨F, λ n, is_closed.preimage continuous_inf_edist is_closed_Ici, F_subset, _, _⟩, show monotone F, { assume m n hmn x hx, simp only [mem_Ici, mem_preimage] at hx ⊢, apply le_trans (ennreal.pow_le_pow_of_le_one a_lt_one.le hmn) hx }, show (⋃ n, F n) = U, { refine subset.antisymm (by simp only [Union_subset_iff, F_subset, forall_const]) (λ x hx, _), have : ¬(x ∈ Uᶜ), by simpa using hx, rw mem_iff_inf_edist_zero_of_closed hU.is_closed_compl at this, have B : 0 < inf_edist x Uᶜ, by simpa [pos_iff_ne_zero] using this, have : filter.tendsto (λ n, a^n) at_top (𝓝 0) := ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 a_lt_one, rcases ((tendsto_order.1 this).2 _ B).exists with ⟨n, hn⟩, simp only [mem_Union, mem_Ici, mem_preimage], exact ⟨n, hn.le⟩ }, end lemma _root_.is_compact.exists_inf_edist_eq_edist (hs : is_compact s) (hne : s.nonempty) (x : α) : ∃ y ∈ s, inf_edist x s = edist x y := begin have A : continuous (λ y, edist x y) := continuous_const.edist continuous_id, obtain ⟨y, ys, hy⟩ : ∃ y ∈ s, ∀ z, z ∈ s → edist x y ≤ edist x z := hs.exists_forall_le hne A.continuous_on, exact ⟨y, ys, le_antisymm (inf_edist_le_edist_of_mem ys) (by rwa le_inf_edist)⟩ end lemma exists_pos_forall_le_edist (hs : is_compact s) (hs' : s.nonempty) (ht : is_closed t) (hst : disjoint s t) : ∃ r, 0 < r ∧ ∀ (x ∈ s) (y ∈ t), r ≤ edist x y := begin obtain ⟨x, hx, h⟩ : ∃ x ∈ s, ∀ y ∈ s, inf_edist x t ≤ inf_edist y t := hs.exists_forall_le hs' continuous_inf_edist.continuous_on, refine ⟨inf_edist x t, pos_iff_ne_zero.2 $ λ H, hst ⟨hx, _⟩, λ y hy, le_inf_edist.1 $ h y hy⟩, rw ←ht.closure_eq, exact mem_closure_iff_inf_edist_zero.2 H, end end inf_edist --section /-! ### The Hausdorff distance as a function into `ℝ≥0∞`. -/ /-- The Hausdorff edistance between two sets is the smallest `r` such that each set is contained in the `r`-neighborhood of the other one -/ @[irreducible] def Hausdorff_edist {α : Type u} [pseudo_emetric_space α] (s t : set α) : ℝ≥0∞ := (⨆ x ∈ s, inf_edist x t) ⊔ (⨆ y ∈ t, inf_edist y s) lemma Hausdorff_edist_def {α : Type u} [pseudo_emetric_space α] (s t : set α) : Hausdorff_edist s t = (⨆ x ∈ s, inf_edist x t) ⊔ (⨆ y ∈ t, inf_edist y s) := by rw Hausdorff_edist section Hausdorff_edist variables [pseudo_emetric_space α] [pseudo_emetric_space β] {x y : α} {s t u : set α} {Φ : α → β} /-- The Hausdorff edistance of a set to itself vanishes -/ @[simp] lemma Hausdorff_edist_self : Hausdorff_edist s s = 0 := begin simp only [Hausdorff_edist_def, sup_idem, ennreal.supr_eq_zero], exact λ x hx, inf_edist_zero_of_mem hx end /-- The Haudorff edistances of `s` to `t` and of `t` to `s` coincide -/ lemma Hausdorff_edist_comm : Hausdorff_edist s t = Hausdorff_edist t s := by unfold Hausdorff_edist; apply sup_comm /-- Bounding the Hausdorff edistance by bounding the edistance of any point in each set to the other set -/ lemma Hausdorff_edist_le_of_inf_edist {r : ℝ≥0∞} (H1 : ∀x ∈ s, inf_edist x t ≤ r) (H2 : ∀x ∈ t, inf_edist x s ≤ r) : Hausdorff_edist s t ≤ r := begin simp only [Hausdorff_edist, sup_le_iff, supr_le_iff], exact ⟨H1, H2⟩ end /-- Bounding the Hausdorff edistance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_edist_le_of_mem_edist {r : ℝ≥0∞} (H1 : ∀x ∈ s, ∃y ∈ t, edist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, edist x y ≤ r) : Hausdorff_edist s t ≤ r := begin refine Hausdorff_edist_le_of_inf_edist _ _, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_edist_le_edist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_edist_le_edist_of_mem ys) hy } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_edist_le_Hausdorff_edist_of_mem (h : x ∈ s) : inf_edist x t ≤ Hausdorff_edist s t := begin rw Hausdorff_edist_def, refine le_trans _ le_sup_left, exact le_supr₂ x h end /-- If the Hausdorff distance is `<r`, then any point in one of the sets has a corresponding point at distance `<r` in the other set -/ lemma exists_edist_lt_of_Hausdorff_edist_lt {r : ℝ≥0∞} (h : x ∈ s) (H : Hausdorff_edist s t < r) : ∃ y ∈ t, edist x y < r := inf_edist_lt_iff.mp $ calc inf_edist x t ≤ Hausdorff_edist s t : inf_edist_le_Hausdorff_edist_of_mem h ... < r : H /-- The distance from `x` to `s` or `t` is controlled in terms of the Hausdorff distance between `s` and `t` -/ lemma inf_edist_le_inf_edist_add_Hausdorff_edist : inf_edist x t ≤ inf_edist x s + Hausdorff_edist s t := ennreal.le_of_forall_pos_le_add $ λε εpos h, begin have ε0 : (ε / 2 : ℝ≥0∞) ≠ 0 := by simpa [pos_iff_ne_zero] using εpos, have : inf_edist x s < inf_edist x s + ε/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).1.ne ε0, rcases inf_edist_lt_iff.mp this with ⟨y, ys, dxy⟩, -- y : α, ys : y ∈ s, dxy : edist x y < inf_edist x s + ↑ε / 2 have : Hausdorff_edist s t < Hausdorff_edist s t + ε/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).2.ne ε0, rcases exists_edist_lt_of_Hausdorff_edist_lt ys this with ⟨z, zt, dyz⟩, -- z : α, zt : z ∈ t, dyz : edist y z < Hausdorff_edist s t + ↑ε / 2 calc inf_edist x t ≤ edist x z : inf_edist_le_edist_of_mem zt ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... ≤ (inf_edist x s + ε/2) + (Hausdorff_edist s t + ε/2) : add_le_add dxy.le dyz.le ... = inf_edist x s + Hausdorff_edist s t + ε : by simp [ennreal.add_halves, add_comm, add_left_comm] end /-- The Hausdorff edistance is invariant under eisometries -/ lemma Hausdorff_edist_image (h : isometry Φ) : Hausdorff_edist (Φ '' s) (Φ '' t) = Hausdorff_edist s t := by simp only [Hausdorff_edist_def, supr_image, inf_edist_image h] /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_edist_le_ediam (hs : s.nonempty) (ht : t.nonempty) : Hausdorff_edist s t ≤ diam (s ∪ t) := begin rcases hs with ⟨x, xs⟩, rcases ht with ⟨y, yt⟩, refine Hausdorff_edist_le_of_mem_edist _ _, { intros z hz, exact ⟨y, yt, edist_le_diam_of_mem (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { intros z hz, exact ⟨x, xs, edist_le_diam_of_mem (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_edist_triangle : Hausdorff_edist s u ≤ Hausdorff_edist s t + Hausdorff_edist t u := begin rw Hausdorff_edist_def, simp only [sup_le_iff, supr_le_iff], split, show ∀x ∈ s, inf_edist x u ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xs, calc inf_edist x u ≤ inf_edist x t + Hausdorff_edist t u : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ Hausdorff_edist s t + Hausdorff_edist t u : add_le_add_right (inf_edist_le_Hausdorff_edist_of_mem xs) _, show ∀x ∈ u, inf_edist x s ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xu, calc inf_edist x s ≤ inf_edist x t + Hausdorff_edist t s : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ Hausdorff_edist u t + Hausdorff_edist t s : add_le_add_right (inf_edist_le_Hausdorff_edist_of_mem xu) _ ... = Hausdorff_edist s t + Hausdorff_edist t u : by simp [Hausdorff_edist_comm, add_comm] end /-- Two sets are at zero Hausdorff edistance if and only if they have the same closure -/ lemma Hausdorff_edist_zero_iff_closure_eq_closure : Hausdorff_edist s t = 0 ↔ closure s = closure t := calc Hausdorff_edist s t = 0 ↔ s ⊆ closure t ∧ t ⊆ closure s : by simp only [Hausdorff_edist_def, ennreal.sup_eq_zero, ennreal.supr_eq_zero, ← mem_closure_iff_inf_edist_zero, subset_def] ... ↔ closure s = closure t : ⟨λ h, subset.antisymm (closure_minimal h.1 is_closed_closure) (closure_minimal h.2 is_closed_closure), λ h, ⟨h ▸ subset_closure, h.symm ▸ subset_closure⟩⟩ /-- The Hausdorff edistance between a set and its closure vanishes -/ @[simp, priority 1100] lemma Hausdorff_edist_self_closure : Hausdorff_edist s (closure s) = 0 := by rw [Hausdorff_edist_zero_iff_closure_eq_closure, closure_closure] /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closure₁ : Hausdorff_edist (closure s) t = Hausdorff_edist s t := begin refine le_antisymm _ _, { calc _ ≤ Hausdorff_edist (closure s) s + Hausdorff_edist s t : Hausdorff_edist_triangle ... = Hausdorff_edist s t : by simp [Hausdorff_edist_comm] }, { calc _ ≤ Hausdorff_edist s (closure s) + Hausdorff_edist (closure s) t : Hausdorff_edist_triangle ... = Hausdorff_edist (closure s) t : by simp } end /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closure₂ : Hausdorff_edist s (closure t) = Hausdorff_edist s t := by simp [@Hausdorff_edist_comm _ _ s _] /-- The Hausdorff edistance between sets or their closures is the same -/ @[simp] lemma Hausdorff_edist_closure : Hausdorff_edist (closure s) (closure t) = Hausdorff_edist s t := by simp /-- Two closed sets are at zero Hausdorff edistance if and only if they coincide -/ lemma Hausdorff_edist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t) : Hausdorff_edist s t = 0 ↔ s = t := by rw [Hausdorff_edist_zero_iff_closure_eq_closure, hs.closure_eq, ht.closure_eq] /-- The Haudorff edistance to the empty set is infinite -/ lemma Hausdorff_edist_empty (ne : s.nonempty) : Hausdorff_edist s ∅ = ∞ := begin rcases ne with ⟨x, xs⟩, have : inf_edist x ∅ ≤ Hausdorff_edist s ∅ := inf_edist_le_Hausdorff_edist_of_mem xs, simpa using this, end /-- If a set is at finite Hausdorff edistance of a nonempty set, it is nonempty -/ lemma nonempty_of_Hausdorff_edist_ne_top (hs : s.nonempty) (fin : Hausdorff_edist s t ≠ ⊤) : t.nonempty := t.eq_empty_or_nonempty.elim (λ ht, (fin $ ht.symm ▸ Hausdorff_edist_empty hs).elim) id lemma empty_or_nonempty_of_Hausdorff_edist_ne_top (fin : Hausdorff_edist s t ≠ ⊤) : s = ∅ ∧ t = ∅ ∨ s.nonempty ∧ t.nonempty := begin cases s.eq_empty_or_nonempty with hs hs, { cases t.eq_empty_or_nonempty with ht ht, { exact or.inl ⟨hs, ht⟩ }, { rw Hausdorff_edist_comm at fin, exact or.inr ⟨nonempty_of_Hausdorff_edist_ne_top ht fin, ht⟩ } }, { exact or.inr ⟨hs, nonempty_of_Hausdorff_edist_ne_top hs fin⟩ } end end Hausdorff_edist -- section end emetric --namespace /-! Now, we turn to the same notions in metric spaces. To avoid the difficulties related to `Inf` and `Sup` on `ℝ` (which is only conditionally complete), we use the notions in `ℝ≥0∞` formulated in terms of the edistance, and coerce them to `ℝ`. Then their properties follow readily from the corresponding properties in `ℝ≥0∞`, modulo some tedious rewriting of inequalities from one to the other. -/ namespace metric section variables [pseudo_metric_space α] [pseudo_metric_space β] {s t u : set α} {x y : α} {Φ : α → β} open emetric /-! ### Distance of a point to a set as a function into `ℝ`. -/ /-- The minimal distance of a point to a set -/ def inf_dist (x : α) (s : set α) : ℝ := ennreal.to_real (inf_edist x s) /-- the minimal distance is always nonnegative -/ lemma inf_dist_nonneg : 0 ≤ inf_dist x s := by simp [inf_dist] /-- the minimal distance to the empty set is 0 (if you want to have the more reasonable value ∞ instead, use `inf_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma inf_dist_empty : inf_dist x ∅ = 0 := by simp [inf_dist] /-- In a metric space, the minimal edistance to a nonempty set is finite -/ lemma inf_edist_ne_top (h : s.nonempty) : inf_edist x s ≠ ⊤ := begin rcases h with ⟨y, hy⟩, apply lt_top_iff_ne_top.1, calc inf_edist x s ≤ edist x y : inf_edist_le_edist_of_mem hy ... < ⊤ : lt_top_iff_ne_top.2 (edist_ne_top _ _) end /-- The minimal distance of a point to a set containing it vanishes -/ lemma inf_dist_zero_of_mem (h : x ∈ s) : inf_dist x s = 0 := by simp [inf_edist_zero_of_mem h, inf_dist] /-- The minimal distance to a singleton is the distance to the unique point in this singleton -/ @[simp] lemma inf_dist_singleton : inf_dist x {y} = dist x y := by simp [inf_dist, inf_edist, dist_edist] /-- The minimal distance to a set is bounded by the distance to any point in this set -/ lemma inf_dist_le_dist_of_mem (h : y ∈ s) : inf_dist x s ≤ dist x y := begin rw [dist_edist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ⟨_, h⟩) (edist_ne_top _ _)], exact inf_edist_le_edist_of_mem h end /-- The minimal distance is monotonous with respect to inclusion -/ lemma inf_dist_le_inf_dist_of_subset (h : s ⊆ t) (hs : s.nonempty) : inf_dist x t ≤ inf_dist x s := begin have ht : t.nonempty := hs.mono h, rw [inf_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) (inf_edist_ne_top hs)], exact inf_edist_anti h end /-- The minimal distance to a set is `< r` iff there exists a point in this set at distance `< r` -/ lemma inf_dist_lt_iff {r : ℝ} (hs : s.nonempty) : inf_dist x s < r ↔ ∃ y ∈ s, dist x y < r := by simp_rw [inf_dist, ← ennreal.lt_of_real_iff_to_real_lt (inf_edist_ne_top hs), inf_edist_lt_iff, ennreal.lt_of_real_iff_to_real_lt (edist_ne_top _ _), ← dist_edist] /-- The minimal distance from `x` to `s` is bounded by the distance from `y` to `s`, modulo the distance between `x` and `y` -/ lemma inf_dist_le_inf_dist_add_dist : inf_dist x s ≤ inf_dist y s + dist x y := begin cases s.eq_empty_or_nonempty with hs hs, { simp [hs, dist_nonneg] }, { rw [inf_dist, inf_dist, dist_edist, ← ennreal.to_real_add (inf_edist_ne_top hs) (edist_ne_top _ _), ennreal.to_real_le_to_real (inf_edist_ne_top hs)], { exact inf_edist_le_inf_edist_add_edist }, { simp [ennreal.add_eq_top, inf_edist_ne_top hs, edist_ne_top] }} end lemma not_mem_of_dist_lt_inf_dist (h : dist x y < inf_dist x s) : y ∉ s := λ hy, h.not_le $ inf_dist_le_dist_of_mem hy lemma disjoint_ball_inf_dist : disjoint (ball x (inf_dist x s)) s := disjoint_left.2 $ λ y hy, not_mem_of_dist_lt_inf_dist $ calc dist x y = dist y x : dist_comm _ _ ... < inf_dist x s : hy lemma ball_inf_dist_subset_compl : ball x (inf_dist x s) ⊆ sᶜ := disjoint_iff_subset_compl_right.1 disjoint_ball_inf_dist lemma ball_inf_dist_compl_subset : ball x (inf_dist x sᶜ) ⊆ s := ball_inf_dist_subset_compl.trans (compl_compl s).subset lemma disjoint_closed_ball_of_lt_inf_dist {r : ℝ} (h : r < inf_dist x s) : disjoint (closed_ball x r) s := disjoint_ball_inf_dist.mono_left $ closed_ball_subset_ball h variable (s) /-- The minimal distance to a set is Lipschitz in point with constant 1 -/ lemma lipschitz_inf_dist_pt : lipschitz_with 1 (λx, inf_dist x s) := lipschitz_with.of_le_add $ λ x y, inf_dist_le_inf_dist_add_dist /-- The minimal distance to a set is uniformly continuous in point -/ /-- The minimal distance to a set is continuous in point -/ @[continuity] lemma continuous_inf_dist_pt : continuous (λx, inf_dist x s) := (uniform_continuous_inf_dist_pt s).continuous variable {s} /-- The minimal distance to a set and its closure coincide -/ lemma inf_dist_eq_closure : inf_dist x (closure s) = inf_dist x s := by simp [inf_dist, inf_edist_closure] /-- If a point belongs to the closure of `s`, then its infimum distance to `s` equals zero. The converse is true provided that `s` is nonempty, see `mem_closure_iff_inf_dist_zero`. -/ lemma inf_dist_zero_of_mem_closure (hx : x ∈ closure s) : inf_dist x s = 0 := by { rw ← inf_dist_eq_closure, exact inf_dist_zero_of_mem hx } /-- A point belongs to the closure of `s` iff its infimum distance to this set vanishes -/ lemma mem_closure_iff_inf_dist_zero (h : s.nonempty) : x ∈ closure s ↔ inf_dist x s = 0 := by simp [mem_closure_iff_inf_edist_zero, inf_dist, ennreal.to_real_eq_zero_iff, inf_edist_ne_top h] /-- Given a closed set `s`, a point belongs to `s` iff its infimum distance to this set vanishes -/ lemma _root_.is_closed.mem_iff_inf_dist_zero (h : is_closed s) (hs : s.nonempty) : x ∈ s ↔ inf_dist x s = 0 := by rw [←mem_closure_iff_inf_dist_zero hs, h.closure_eq] /-- Given a closed set `s`, a point belongs to `s` iff its infimum distance to this set vanishes -/ lemma _root_.is_closed.not_mem_iff_inf_dist_pos (h : is_closed s) (hs : s.nonempty) : x ∉ s ↔ 0 < inf_dist x s := begin rw ← not_iff_not, push_neg, simp [h.mem_iff_inf_dist_zero hs, le_antisymm_iff, inf_dist_nonneg], end /-- The infimum distance is invariant under isometries -/ lemma inf_dist_image (hΦ : isometry Φ) : inf_dist (Φ x) (Φ '' t) = inf_dist x t := by simp [inf_dist, inf_edist_image hΦ] lemma inf_dist_inter_closed_ball_of_mem (h : y ∈ s) : inf_dist x (s ∩ closed_ball x (dist y x)) = inf_dist x s := begin replace h : y ∈ s ∩ closed_ball x (dist y x) := ⟨h, mem_closed_ball.2 le_rfl⟩, refine le_antisymm _ (inf_dist_le_inf_dist_of_subset (inter_subset_left _ _) ⟨y, h⟩), refine not_lt.1 (λ hlt, _), rcases (inf_dist_lt_iff ⟨y, h.1⟩).mp hlt with ⟨z, hzs, hz⟩, cases le_or_lt (dist z x) (dist y x) with hle hlt, { exact hz.not_le (inf_dist_le_dist_of_mem ⟨hzs, hle⟩) }, { rw [dist_comm z, dist_comm y] at hlt, exact (hlt.trans hz).not_le (inf_dist_le_dist_of_mem h) } end lemma _root_.is_compact.exists_inf_dist_eq_dist (h : is_compact s) (hne : s.nonempty) (x : α) : ∃ y ∈ s, inf_dist x s = dist x y := let ⟨y, hys, hy⟩ := h.exists_inf_edist_eq_edist hne x in ⟨y, hys, by rw [inf_dist, dist_edist, hy]⟩ lemma _root_.is_closed.exists_inf_dist_eq_dist [proper_space α] (h : is_closed s) (hne : s.nonempty) (x : α) : ∃ y ∈ s, inf_dist x s = dist x y := begin rcases hne with ⟨z, hz⟩, rw ← inf_dist_inter_closed_ball_of_mem hz, set t := s ∩ closed_ball x (dist z x), have htc : is_compact t := (is_compact_closed_ball x (dist z x)).inter_left h, have htne : t.nonempty := ⟨z, hz, mem_closed_ball.2 le_rfl⟩, obtain ⟨y, ⟨hys, hyx⟩, hyd⟩ : ∃ y ∈ t, inf_dist x t = dist x y := htc.exists_inf_dist_eq_dist htne x, exact ⟨y, hys, hyd⟩ end lemma exists_mem_closure_inf_dist_eq_dist [proper_space α] (hne : s.nonempty) (x : α) : ∃ y ∈ closure s, inf_dist x s = dist x y := by simpa only [inf_dist_eq_closure] using is_closed_closure.exists_inf_dist_eq_dist hne.closure x /-! ### Distance of a point to a set as a function into `ℝ≥0`. -/ /-- The minimal distance of a point to a set as a `ℝ≥0` -/ def inf_nndist (x : α) (s : set α) : ℝ≥0 := ennreal.to_nnreal (inf_edist x s) @[simp] lemma coe_inf_nndist : (inf_nndist x s : ℝ) = inf_dist x s := rfl /-- The minimal distance to a set (as `ℝ≥0`) is Lipschitz in point with constant 1 -/ lemma lipschitz_inf_nndist_pt (s : set α) : lipschitz_with 1 (λx, inf_nndist x s) := lipschitz_with.of_le_add $ λ x y, inf_dist_le_inf_dist_add_dist /-- The minimal distance to a set (as `ℝ≥0`) is uniformly continuous in point -/ lemma uniform_continuous_inf_nndist_pt (s : set α) : uniform_continuous (λx, inf_nndist x s) := (lipschitz_inf_nndist_pt s).uniform_continuous /-- The minimal distance to a set (as `ℝ≥0`) is continuous in point -/ lemma continuous_inf_nndist_pt (s : set α) : continuous (λx, inf_nndist x s) := (uniform_continuous_inf_nndist_pt s).continuous /-! ### The Hausdorff distance as a function into `ℝ`. -/ /-- The Hausdorff distance between two sets is the smallest nonnegative `r` such that each set is included in the `r`-neighborhood of the other. If there is no such `r`, it is defined to be `0`, arbitrarily -/ def Hausdorff_dist (s t : set α) : ℝ := ennreal.to_real (Hausdorff_edist s t) /-- The Hausdorff distance is nonnegative -/ lemma Hausdorff_dist_nonneg : 0 ≤ Hausdorff_dist s t := by simp [Hausdorff_dist] /-- If two sets are nonempty and bounded in a metric space, they are at finite Hausdorff edistance. -/ lemma Hausdorff_edist_ne_top_of_nonempty_of_bounded (hs : s.nonempty) (ht : t.nonempty) (bs : bounded s) (bt : bounded t) : Hausdorff_edist s t ≠ ⊤ := begin rcases hs with ⟨cs, hcs⟩, rcases ht with ⟨ct, hct⟩, rcases (bounded_iff_subset_ball ct).1 bs with ⟨rs, hrs⟩, rcases (bounded_iff_subset_ball cs).1 bt with ⟨rt, hrt⟩, have : Hausdorff_edist s t ≤ ennreal.of_real (max rs rt), { apply Hausdorff_edist_le_of_mem_edist, { assume x xs, existsi [ct, hct], have : dist x ct ≤ max rs rt := le_trans (hrs xs) (le_max_left _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }, { assume x xt, existsi [cs, hcs], have : dist x cs ≤ max rs rt := le_trans (hrt xt) (le_max_right _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }}, exact ne_top_of_le_ne_top ennreal.of_real_ne_top this end /-- The Hausdorff distance between a set and itself is zero -/ @[simp] lemma Hausdorff_dist_self_zero : Hausdorff_dist s s = 0 := by simp [Hausdorff_dist] /-- The Hausdorff distance from `s` to `t` and from `t` to `s` coincide -/ lemma Hausdorff_dist_comm : Hausdorff_dist s t = Hausdorff_dist t s := by simp [Hausdorff_dist, Hausdorff_edist_comm] /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma Hausdorff_dist_empty : Hausdorff_dist s ∅ = 0 := begin cases s.eq_empty_or_nonempty with h h, { simp [h] }, { simp [Hausdorff_dist, Hausdorff_edist_empty h] } end /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma Hausdorff_dist_empty' : Hausdorff_dist ∅ s = 0 := by simp [Hausdorff_dist_comm] /-- Bounding the Hausdorff distance by bounding the distance of any point in each set to the other set -/ lemma Hausdorff_dist_le_of_inf_dist {r : ℝ} (hr : 0 ≤ r) (H1 : ∀x ∈ s, inf_dist x t ≤ r) (H2 : ∀x ∈ t, inf_dist x s ≤ r) : Hausdorff_dist s t ≤ r := begin by_cases h1 : Hausdorff_edist s t = ⊤, { rwa [Hausdorff_dist, h1, ennreal.top_to_real] }, cases s.eq_empty_or_nonempty with hs hs, { rwa [hs, Hausdorff_dist_empty'] }, cases t.eq_empty_or_nonempty with ht ht, { rwa [ht, Hausdorff_dist_empty] }, have : Hausdorff_edist s t ≤ ennreal.of_real r, { apply Hausdorff_edist_le_of_inf_edist _ _, { assume x hx, have I := H1 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top ht) ennreal.of_real_ne_top] at I }, { assume x hx, have I := H2 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top hs) ennreal.of_real_ne_top] at I }}, rwa [Hausdorff_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real h1 ennreal.of_real_ne_top] end /-- Bounding the Hausdorff distance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_dist_le_of_mem_dist {r : ℝ} (hr : 0 ≤ r) (H1 : ∀x ∈ s, ∃y ∈ t, dist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, dist x y ≤ r) : Hausdorff_dist s t ≤ r := begin apply Hausdorff_dist_le_of_inf_dist hr, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_dist_le_dist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_dist_le_dist_of_mem ys) hy } end /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_dist_le_diam (hs : s.nonempty) (bs : bounded s) (ht : t.nonempty) (bt : bounded t) : Hausdorff_dist s t ≤ diam (s ∪ t) := begin rcases hs with ⟨x, xs⟩, rcases ht with ⟨y, yt⟩, refine Hausdorff_dist_le_of_mem_dist diam_nonneg _ _, { exact λz hz, ⟨y, yt, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { exact λz hz, ⟨x, xs, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_dist_le_Hausdorff_dist_of_mem (hx : x ∈ s) (fin : Hausdorff_edist s t ≠ ⊤) : inf_dist x t ≤ Hausdorff_dist s t := begin have ht : t.nonempty := nonempty_of_Hausdorff_edist_ne_top ⟨x, hx⟩ fin, rw [Hausdorff_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) fin], exact inf_edist_le_Hausdorff_edist_of_mem hx end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt {r : ℝ} (h : x ∈ s) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t ≠ ⊤) : ∃y∈t, dist x y < r := begin have r0 : 0 < r := lt_of_le_of_lt (Hausdorff_dist_nonneg) H, have : Hausdorff_edist s t < ennreal.of_real r, { rwa [Hausdorff_dist, ← ennreal.to_real_of_real (le_of_lt r0), ennreal.to_real_lt_to_real fin (ennreal.of_real_ne_top)] at H }, rcases exists_edist_lt_of_Hausdorff_edist_lt h this with ⟨y, hy, yr⟩, rw [edist_dist, ennreal.of_real_lt_of_real_iff r0] at yr, exact ⟨y, hy, yr⟩ end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt' {r : ℝ} (h : y ∈ t) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t ≠ ⊤) : ∃x∈s, dist x y < r := begin rw Hausdorff_dist_comm at H, rw Hausdorff_edist_comm at fin, simpa [dist_comm] using exists_dist_lt_of_Hausdorff_dist_lt h H fin end /-- The infimum distance to `s` and `t` are the same, up to the Hausdorff distance between `s` and `t` -/ lemma inf_dist_le_inf_dist_add_Hausdorff_dist (fin : Hausdorff_edist s t ≠ ⊤) : inf_dist x t ≤ inf_dist x s + Hausdorff_dist s t := begin rcases empty_or_nonempty_of_Hausdorff_edist_ne_top fin with ⟨hs,ht⟩|⟨hs,ht⟩, { simp only [hs, ht, Hausdorff_dist_empty, inf_dist_empty, zero_add] }, rw [inf_dist, inf_dist, Hausdorff_dist, ← ennreal.to_real_add (inf_edist_ne_top hs) fin, ennreal.to_real_le_to_real (inf_edist_ne_top ht)], { exact inf_edist_le_inf_edist_add_Hausdorff_edist }, { exact ennreal.add_ne_top.2 ⟨inf_edist_ne_top hs, fin⟩ } end /-- The Hausdorff distance is invariant under isometries -/ lemma Hausdorff_dist_image (h : isometry Φ) : Hausdorff_dist (Φ '' s) (Φ '' t) = Hausdorff_dist s t := by simp [Hausdorff_dist, Hausdorff_edist_image h] /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u := begin by_cases Hausdorff_edist s u = ⊤, { calc Hausdorff_dist s u = 0 + 0 : by simp [Hausdorff_dist, h] ... ≤ Hausdorff_dist s t + Hausdorff_dist t u : add_le_add (Hausdorff_dist_nonneg) (Hausdorff_dist_nonneg) }, { have Dtu : Hausdorff_edist t u < ⊤ := calc Hausdorff_edist t u ≤ Hausdorff_edist t s + Hausdorff_edist s u : Hausdorff_edist_triangle ... = Hausdorff_edist s t + Hausdorff_edist s u : by simp [Hausdorff_edist_comm] ... < ⊤ : lt_top_iff_ne_top.mpr $ ennreal.add_ne_top.mpr ⟨fin, h⟩, rw [Hausdorff_dist, Hausdorff_dist, Hausdorff_dist, ← ennreal.to_real_add fin Dtu.ne, ennreal.to_real_le_to_real h], { exact Hausdorff_edist_triangle }, { simp [ennreal.add_eq_top, lt_top_iff_ne_top.1 Dtu, fin] }} end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle' (fin : Hausdorff_edist t u ≠ ⊤) : Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u := begin rw Hausdorff_edist_comm at fin, have I : Hausdorff_dist u s ≤ Hausdorff_dist u t + Hausdorff_dist t s := Hausdorff_dist_triangle fin, simpa [add_comm, Hausdorff_dist_comm] using I end /-- The Hausdorff distance between a set and its closure vanish -/ @[simp, priority 1100] lemma Hausdorff_dist_self_closure : Hausdorff_dist s (closure s) = 0 := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closure₁ : Hausdorff_dist (closure s) t = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closure₂ : Hausdorff_dist s (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- The Hausdorff distance between two sets and their closures coincide -/ @[simp] lemma Hausdorff_dist_closure : Hausdorff_dist (closure s) (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Two sets are at zero Hausdorff distance if and only if they have the same closures -/ lemma Hausdorff_dist_zero_iff_closure_eq_closure (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ closure s = closure t := by simp [Hausdorff_edist_zero_iff_closure_eq_closure.symm, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] /-- Two closed sets are at zero Hausdorff distance if and only if they coincide -/ lemma _root_.is_closed.Hausdorff_dist_zero_iff_eq (hs : is_closed s) (ht : is_closed t) (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ s = t := by simp [←Hausdorff_edist_zero_iff_eq_of_closed hs ht, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] end --section section thickening variables [pseudo_emetric_space α] {δ : ℝ} {s : set α} {x : α} open emetric /-- The (open) `δ`-thickening `thickening δ E` of a subset `E` in a pseudo emetric space consists of those points that are at distance less than `δ` from some point of `E`. -/ def thickening (δ : ℝ) (E : set α) : set α := {x : α | inf_edist x E < ennreal.of_real δ} lemma mem_thickening_iff_inf_edist_lt : x ∈ thickening δ s ↔ inf_edist x s < ennreal.of_real δ := iff.rfl /-- The (open) thickening equals the preimage of an open interval under `inf_edist`. -/ lemma thickening_eq_preimage_inf_edist (δ : ℝ) (E : set α) : thickening δ E = (λ x, inf_edist x E) ⁻¹' (Iio (ennreal.of_real δ)) := rfl /-- The (open) thickening is an open set. -/ lemma is_open_thickening {δ : ℝ} {E : set α} : is_open (thickening δ E) := continuous.is_open_preimage continuous_inf_edist _ is_open_Iio /-- The (open) thickening of the empty set is empty. -/ @[simp] lemma thickening_empty (δ : ℝ) : thickening δ (∅ : set α) = ∅ := by simp only [thickening, set_of_false, inf_edist_empty, not_top_lt] lemma thickening_of_nonpos (hδ : δ ≤ 0) (s : set α) : thickening δ s = ∅ := eq_empty_of_forall_not_mem $ λ x, ((ennreal.of_real_of_nonpos hδ).trans_le bot_le).not_lt /-- The (open) thickening `thickening δ E` of a fixed subset `E` is an increasing function of the thickening radius `δ`. -/ lemma thickening_mono {δ₁ δ₂ : ℝ} (hle : δ₁ ≤ δ₂) (E : set α) : thickening δ₁ E ⊆ thickening δ₂ E := preimage_mono (Iio_subset_Iio (ennreal.of_real_le_of_real hle)) /-- The (open) thickening `thickening δ E` with a fixed thickening radius `δ` is an increasing function of the subset `E`. -/ lemma thickening_subset_of_subset (δ : ℝ) {E₁ E₂ : set α} (h : E₁ ⊆ E₂) : thickening δ E₁ ⊆ thickening δ E₂ := λ _ hx, lt_of_le_of_lt (inf_edist_anti h) hx lemma mem_thickening_iff_exists_edist_lt {δ : ℝ} (E : set α) (x : α) : x ∈ thickening δ E ↔ ∃ z ∈ E, edist x z < ennreal.of_real δ := inf_edist_lt_iff variables {X : Type u} [pseudo_metric_space X] /-- A point in a metric space belongs to the (open) `δ`-thickening of a subset `E` if and only if it is at distance less than `δ` from some point of `E`. -/ lemma mem_thickening_iff {E : set X} {x : X} : x ∈ thickening δ E ↔ (∃ z ∈ E, dist x z < δ) := begin have key_iff : ∀ (z : X), edist x z < ennreal.of_real δ ↔ dist x z < δ, { intros z, rw dist_edist, have d_lt_top : edist x z < ∞, by simp only [edist_dist, ennreal.of_real_lt_top], have key := (@ennreal.of_real_lt_of_real_iff_of_nonneg ((edist x z).to_real) δ (ennreal.to_real_nonneg)), rwa ennreal.of_real_to_real d_lt_top.ne at key, }, simp_rw [mem_thickening_iff_exists_edist_lt, key_iff], end @[simp] lemma thickening_singleton (δ : ℝ) (x : X) : thickening δ ({x} : set X) = ball x δ := by { ext, simp [mem_thickening_iff] } /-- The (open) `δ`-thickening `thickening δ E` of a subset `E` in a metric space equals the union of balls of radius `δ` centered at points of `E`. -/ lemma thickening_eq_bUnion_ball {δ : ℝ} {E : set X} : thickening δ E = ⋃ x ∈ E, ball x δ := by { ext x, rw mem_Union₂, exact mem_thickening_iff } lemma bounded.thickening {δ : ℝ} {E : set X} (h : bounded E) : bounded (thickening δ E) := begin refine bounded_iff_mem_bounded.2 (λ x hx, _), rcases h.subset_ball x with ⟨R, hR⟩, refine (bounded_iff_subset_ball x).2 ⟨R + δ, _⟩, assume y hy, rcases mem_thickening_iff.1 hy with ⟨z, zE, hz⟩, calc dist y x ≤ dist z x + dist y z : by { rw add_comm, exact dist_triangle _ _ _ } ... ≤ R + δ : add_le_add (hR zE) hz.le end end thickening --section section cthickening variables [pseudo_emetric_space α] {δ ε : ℝ} {s t : set α} {x : α} open emetric /-- The closed `δ`-thickening `cthickening δ E` of a subset `E` in a pseudo emetric space consists of those points that are at infimum distance at most `δ` from `E`. -/ def cthickening (δ : ℝ) (E : set α) : set α := {x : α | inf_edist x E ≤ ennreal.of_real δ} @[simp] lemma mem_cthickening_iff : x ∈ cthickening δ s ↔ inf_edist x s ≤ ennreal.of_real δ := iff.rfl lemma mem_cthickening_of_edist_le (x y : α) (δ : ℝ) (E : set α) (h : y ∈ E) (h' : edist x y ≤ ennreal.of_real δ) : x ∈ cthickening δ E := (inf_edist_le_edist_of_mem h).trans h' lemma mem_cthickening_of_dist_le {α : Type*} [pseudo_metric_space α] (x y : α) (δ : ℝ) (E : set α) (h : y ∈ E) (h' : dist x y ≤ δ) : x ∈ cthickening δ E := begin apply mem_cthickening_of_edist_le x y δ E h, rw edist_dist, exact ennreal.of_real_le_of_real h', end lemma cthickening_eq_preimage_inf_edist (δ : ℝ) (E : set α) : cthickening δ E = (λ x, inf_edist x E) ⁻¹' (Iic (ennreal.of_real δ)) := rfl /-- The closed thickening is a closed set. -/ lemma is_closed_cthickening {δ : ℝ} {E : set α} : is_closed (cthickening δ E) := is_closed.preimage continuous_inf_edist is_closed_Iic /-- The closed thickening of the empty set is empty. -/ @[simp] lemma cthickening_empty (δ : ℝ) : cthickening δ (∅ : set α) = ∅ := by simp only [cthickening, ennreal.of_real_ne_top, set_of_false, inf_edist_empty, top_le_iff] lemma cthickening_of_nonpos {δ : ℝ} (hδ : δ ≤ 0) (E : set α) : cthickening δ E = closure E := by { ext x, simp [mem_closure_iff_inf_edist_zero, cthickening, ennreal.of_real_eq_zero.2 hδ] } /-- The closed thickening with radius zero is the closure of the set. -/ @[simp] lemma cthickening_zero (E : set α) : cthickening 0 E = closure E := cthickening_of_nonpos le_rfl E /-- The closed thickening `cthickening δ E` of a fixed subset `E` is an increasing function of the thickening radius `δ`. -/ lemma cthickening_mono {δ₁ δ₂ : ℝ} (hle : δ₁ ≤ δ₂) (E : set α) : cthickening δ₁ E ⊆ cthickening δ₂ E := preimage_mono (Iic_subset_Iic.mpr (ennreal.of_real_le_of_real hle)) @[simp] lemma cthickening_singleton {α : Type*} [pseudo_metric_space α] (x : α) {δ : ℝ} (hδ : 0 ≤ δ) : cthickening δ ({x} : set α) = closed_ball x δ := by { ext y, simp [cthickening, edist_dist, ennreal.of_real_le_of_real_iff hδ] } lemma closed_ball_subset_cthickening_singleton {α : Type*} [pseudo_metric_space α] (x : α) (δ : ℝ) : closed_ball x δ ⊆ cthickening δ ({x} : set α) := begin rcases lt_or_le δ 0 with hδ|hδ, { simp only [closed_ball_eq_empty.mpr hδ, empty_subset] }, { simp only [cthickening_singleton x hδ] } end /-- The closed thickening `cthickening δ E` with a fixed thickening radius `δ` is an increasing function of the subset `E`. -/ lemma cthickening_subset_of_subset (δ : ℝ) {E₁ E₂ : set α} (h : E₁ ⊆ E₂) : cthickening δ E₁ ⊆ cthickening δ E₂ := λ _ hx, le_trans (inf_edist_anti h) hx lemma cthickening_subset_thickening {δ₁ : ℝ≥0} {δ₂ : ℝ} (hlt : (δ₁ : ℝ) < δ₂) (E : set α) : cthickening δ₁ E ⊆ thickening δ₂ E := λ _ hx, lt_of_le_of_lt hx ((ennreal.of_real_lt_of_real_iff (lt_of_le_of_lt δ₁.prop hlt)).mpr hlt) /-- The closed thickening `cthickening δ₁ E` is contained in the open thickening `thickening δ₂ E` if the radius of the latter is positive and larger. -/ lemma cthickening_subset_thickening' {δ₁ δ₂ : ℝ} (δ₂_pos : 0 < δ₂) (hlt : δ₁ < δ₂) (E : set α) : cthickening δ₁ E ⊆ thickening δ₂ E := λ _ hx, lt_of_le_of_lt hx ((ennreal.of_real_lt_of_real_iff δ₂_pos).mpr hlt) /-- The open thickening `thickening δ E` is contained in the closed thickening `cthickening δ E` with the same radius. -/ lemma thickening_subset_cthickening (δ : ℝ) (E : set α) : thickening δ E ⊆ cthickening δ E := by { intros x hx, rw [thickening, mem_set_of_eq] at hx, exact hx.le, } lemma thickening_subset_cthickening_of_le {δ₁ δ₂ : ℝ} (hle : δ₁ ≤ δ₂) (E : set α) : thickening δ₁ E ⊆ cthickening δ₂ E := (thickening_subset_cthickening δ₁ E).trans (cthickening_mono hle E) lemma bounded.cthickening {α : Type*} [pseudo_metric_space α] {δ : ℝ} {E : set α} (h : bounded E) : bounded (cthickening δ E) := begin have : bounded (thickening (max (δ + 1) 1) E) := h.thickening, apply bounded.mono _ this, exact cthickening_subset_thickening' (zero_lt_one.trans_le (le_max_right _ _)) ((lt_add_one _).trans_le (le_max_left _ _)) _ end lemma thickening_subset_interior_cthickening (δ : ℝ) (E : set α) : thickening δ E ⊆ interior (cthickening δ E) := (subset_interior_iff_open.mpr (is_open_thickening)).trans (interior_mono (thickening_subset_cthickening δ E)) lemma closure_thickening_subset_cthickening (δ : ℝ) (E : set α) : closure (thickening δ E) ⊆ cthickening δ E := (closure_mono (thickening_subset_cthickening δ E)).trans is_closed_cthickening.closure_subset /-- The closed thickening of a set contains the closure of the set. -/ lemma closure_subset_cthickening (δ : ℝ) (E : set α) : closure E ⊆ cthickening δ E := by { rw ← cthickening_of_nonpos (min_le_right δ 0), exact cthickening_mono (min_le_left δ 0) E, } /-- The (open) thickening of a set contains the closure of the set. -/ lemma closure_subset_thickening {δ : ℝ} (δ_pos : 0 < δ) (E : set α) : closure E ⊆ thickening δ E := by { rw ← cthickening_zero, exact cthickening_subset_thickening' δ_pos δ_pos E, } /-- A set is contained in its own (open) thickening. -/ lemma self_subset_thickening {δ : ℝ} (δ_pos : 0 < δ) (E : set α) : E ⊆ thickening δ E := (@subset_closure _ _ E).trans (closure_subset_thickening δ_pos E) /-- A set is contained in its own closed thickening. -/ lemma self_subset_cthickening {δ : ℝ} (E : set α) : E ⊆ cthickening δ E := subset_closure.trans (closure_subset_cthickening δ E) @[simp] lemma thickening_union (δ : ℝ) (s t : set α) : thickening δ (s ∪ t) = thickening δ s ∪ thickening δ t := by simp_rw [thickening, inf_edist_union, inf_eq_min, min_lt_iff, set_of_or] @[simp] lemma cthickening_union (δ : ℝ) (s t : set α) : cthickening δ (s ∪ t) = cthickening δ s ∪ cthickening δ t := by simp_rw [cthickening, inf_edist_union, inf_eq_min, min_le_iff, set_of_or] @[simp] lemma thickening_Union (δ : ℝ) (f : ι → set α) : thickening δ (⋃ i, f i) = ⋃ i, thickening δ (f i) := by simp_rw [thickening, inf_edist_Union, infi_lt_iff, set_of_exists] @[simp] lemma thickening_closure : thickening δ (closure s) = thickening δ s := by simp_rw [thickening, inf_edist_closure] @[simp] lemma cthickening_closure : cthickening δ (closure s) = cthickening δ s := by simp_rw [cthickening, inf_edist_closure] open ennreal lemma _root_.disjoint.exists_thickenings (hst : disjoint s t) (hs : is_compact s) (ht : is_closed t) : ∃ δ, 0 < δ ∧ disjoint (thickening δ s) (thickening δ t) := begin obtain rfl | hs' := s.eq_empty_or_nonempty, { simp_rw thickening_empty, exact ⟨1, zero_lt_one, empty_disjoint _⟩ }, obtain ⟨r, hr, h⟩ := exists_pos_forall_le_edist hs hs' ht hst, refine ⟨(min 1 (r/2)).to_real, to_real_pos (lt_min ennreal.zero_lt_one $ half_pos hr.ne').ne' (min_lt_of_left_lt one_lt_top).ne, _⟩, rintro z ⟨hzs, hzt⟩, rw mem_thickening_iff_exists_edist_lt at hzs hzt, obtain ⟨x, hx, hzx⟩ := hzs, obtain ⟨y, hy, hzy⟩ := hzt, refine (((h _ hx _ hy).trans $ edist_triangle_left _ _ _).trans_lt $ ennreal.add_lt_add hzx hzy).not_le _, rw ←two_mul, exact ennreal.mul_le_of_le_div' (of_real_to_real_le.trans $ min_le_right _ _), end lemma _root_.disjoint.exists_cthickenings (hst : disjoint s t) (hs : is_compact s) (ht : is_closed t) : ∃ δ, 0 < δ ∧ disjoint (cthickening δ s) (cthickening δ t) := begin obtain ⟨δ, hδ, h⟩ := hst.exists_thickenings hs ht, refine ⟨δ / 2, half_pos hδ, h.mono _ _⟩; exact (cthickening_subset_thickening' hδ (half_lt_self hδ) _), end lemma cthickening_eq_Inter_cthickening' {δ : ℝ} (s : set ℝ) (hsδ : s ⊆ Ioi δ) (hs : ∀ ε, δ < ε → (s ∩ (Ioc δ ε)).nonempty) (E : set α) : cthickening δ E = ⋂ ε ∈ s, cthickening ε E := begin apply subset.antisymm, { exact subset_Inter₂ (λ _ hε, cthickening_mono (le_of_lt (hsδ hε)) E), }, { unfold thickening cthickening, intros x hx, simp only [mem_Inter, mem_set_of_eq] at *, apply ennreal.le_of_forall_pos_le_add, intros η η_pos _, rcases hs (δ + η) (lt_add_of_pos_right _ (nnreal.coe_pos.mpr η_pos)) with ⟨ε, ⟨hsε, hε⟩⟩, apply ((hx ε hsε).trans (ennreal.of_real_le_of_real hε.2)).trans, rw ennreal.coe_nnreal_eq η, exact ennreal.of_real_add_le, }, end lemma cthickening_eq_Inter_cthickening {δ : ℝ} (E : set α) : cthickening δ E = ⋂ (ε : ℝ) (h : δ < ε), cthickening ε E := begin apply cthickening_eq_Inter_cthickening' (Ioi δ) rfl.subset, simp_rw inter_eq_right_iff_subset.mpr Ioc_subset_Ioi_self, exact λ _ hε, nonempty_Ioc.mpr hε, end lemma cthickening_eq_Inter_thickening' {δ : ℝ} (δ_nn : 0 ≤ δ) (s : set ℝ) (hsδ : s ⊆ Ioi δ) (hs : ∀ ε, δ < ε → (s ∩ (Ioc δ ε)).nonempty) (E : set α) : cthickening δ E = ⋂ ε ∈ s, thickening ε E := begin refine (subset_Inter₂ $ λ ε hε, _).antisymm _, { obtain ⟨ε', hsε', hε'⟩ := hs ε (hsδ hε), have ss := cthickening_subset_thickening' (lt_of_le_of_lt δ_nn hε'.1) hε'.1 E, exact ss.trans (thickening_mono hε'.2 E), }, { rw cthickening_eq_Inter_cthickening' s hsδ hs E, exact Inter₂_mono (λ ε hε, thickening_subset_cthickening ε E) } end lemma cthickening_eq_Inter_thickening {δ : ℝ} (δ_nn : 0 ≤ δ) (E : set α) : cthickening δ E = ⋂ (ε : ℝ) (h : δ < ε), thickening ε E := begin apply cthickening_eq_Inter_thickening' δ_nn (Ioi δ) rfl.subset, simp_rw inter_eq_right_iff_subset.mpr Ioc_subset_Ioi_self, exact λ _ hε, nonempty_Ioc.mpr hε, end /-- The closure of a set equals the intersection of its closed thickenings of positive radii accumulating at zero. -/ lemma closure_eq_Inter_cthickening' (E : set α) (s : set ℝ) (hs : ∀ ε, 0 < ε → (s ∩ (Ioc 0 ε)).nonempty) : closure E = ⋂ δ ∈ s, cthickening δ E := begin by_cases hs₀ : s ⊆ Ioi 0, { rw ← cthickening_zero, apply cthickening_eq_Inter_cthickening' _ hs₀ hs, }, obtain ⟨δ, hδs, δ_nonpos⟩ := not_subset.mp hs₀, rw [set.mem_Ioi, not_lt] at δ_nonpos, apply subset.antisymm, { exact subset_Inter₂ (λ ε _, closure_subset_cthickening ε E), }, { rw ← cthickening_of_nonpos δ_nonpos E, exact bInter_subset_of_mem hδs, }, end /-- The closure of a set equals the intersection of its closed thickenings of positive radii. -/ lemma closure_eq_Inter_cthickening (E : set α) : closure E = ⋂ (δ : ℝ) (h : 0 < δ), cthickening δ E := by { rw ← cthickening_zero, exact cthickening_eq_Inter_cthickening E, } /-- The closure of a set equals the intersection of its open thickenings of positive radii accumulating at zero. -/ lemma closure_eq_Inter_thickening' (E : set α) (s : set ℝ) (hs₀ : s ⊆ Ioi 0) (hs : ∀ ε, 0 < ε → (s ∩ (Ioc 0 ε)).nonempty) : closure E = ⋂ δ ∈ s, thickening δ E := by { rw ← cthickening_zero, apply cthickening_eq_Inter_thickening' le_rfl _ hs₀ hs, } /-- The closure of a set equals the intersection of its (open) thickenings of positive radii. -/ lemma closure_eq_Inter_thickening (E : set α) : closure E = ⋂ (δ : ℝ) (h : 0 < δ), thickening δ E := by { rw ← cthickening_zero, exact cthickening_eq_Inter_thickening rfl.ge E, } /-- The frontier of the (open) thickening of a set is contained in an `inf_edist` level set. -/ lemma frontier_thickening_subset (E : set α) {δ : ℝ} (δ_pos : 0 < δ) : frontier (thickening δ E) ⊆ {x : α | inf_edist x E = ennreal.of_real δ} := begin have singleton_preim : {x : α | inf_edist x E = ennreal.of_real δ } = (λ x , inf_edist x E) ⁻¹' {ennreal.of_real δ}, { simp only [preimage, mem_singleton_iff] }, rw [thickening_eq_preimage_inf_edist, singleton_preim, ← (frontier_Iio' ⟨(0 : ℝ≥0∞), ennreal.of_real_pos.mpr δ_pos⟩)], exact continuous_inf_edist.frontier_preimage_subset (Iio (ennreal.of_real δ)), end /-- The frontier of the closed thickening of a set is contained in an `inf_edist` level set. -/ lemma frontier_cthickening_subset (E : set α) {δ : ℝ} : frontier (cthickening δ E) ⊆ {x : α | inf_edist x E = ennreal.of_real δ} := begin have singleton_preim : {x : α | inf_edist x E = ennreal.of_real δ } = (λ x , inf_edist x E) ⁻¹' {ennreal.of_real δ}, { simp only [preimage, mem_singleton_iff] }, rw [cthickening_eq_preimage_inf_edist, singleton_preim, ← frontier_Iic' ⟨∞, ennreal.of_real_lt_top⟩], exact continuous_inf_edist.frontier_preimage_subset (Iic (ennreal.of_real δ)), end /-- The closed ball of radius `δ` centered at a point of `E` is included in the closed thickening of `E`. -/ lemma closed_ball_subset_cthickening {α : Type*} [pseudo_metric_space α] {x : α} {E : set α} (hx : x ∈ E) (δ : ℝ) : closed_ball x δ ⊆ cthickening δ E := begin refine (closed_ball_subset_cthickening_singleton _ _).trans (cthickening_subset_of_subset _ _), simpa using hx, end /-- The closed thickening of a compact set `E` is the union of the balls `closed_ball x δ` over `x ∈ E`. -/ lemma _root_.is_compact.cthickening_eq_bUnion_closed_ball {α : Type*} [pseudo_metric_space α] {δ : ℝ} {E : set α} (hE : is_compact E) (hδ : 0 ≤ δ) : cthickening δ E = ⋃ x ∈ E, closed_ball x δ := begin rcases eq_empty_or_nonempty E with rfl|hne, { simp only [cthickening_empty, Union_false, Union_empty] }, refine subset.antisymm (λ x hx, _) (Union₂_subset $ λ x hx, closed_ball_subset_cthickening hx _), obtain ⟨y, yE, hy⟩ : ∃ y ∈ E, emetric.inf_edist x E = edist x y := hE.exists_inf_edist_eq_edist hne _, have D1 : edist x y ≤ ennreal.of_real δ := (le_of_eq hy.symm).trans hx, have D2 : dist x y ≤ δ, { rw edist_dist at D1, exact (ennreal.of_real_le_of_real_iff hδ).1 D1 }, exact mem_bUnion yE D2, end /-- For the equality, see `inf_edist_cthickening`. -/ lemma inf_edist_le_inf_edist_cthickening_add : inf_edist x s ≤ inf_edist x (cthickening δ s) + ennreal.of_real δ := begin refine le_of_forall_lt' (λ r h, _), simp_rw [←lt_tsub_iff_right, inf_edist_lt_iff, mem_cthickening_iff] at h, obtain ⟨y, hy, hxy⟩ := h, exact inf_edist_le_edist_add_inf_edist.trans_lt ((ennreal.add_lt_add_of_lt_of_le (hy.trans_lt ennreal.of_real_lt_top).ne hxy hy).trans_le (tsub_add_cancel_of_le $ le_self_add.trans (lt_tsub_iff_left.1 hxy).le).le), end /-- For the equality, see `inf_edist_thickening`. -/ lemma inf_edist_le_inf_edist_thickening_add : inf_edist x s ≤ inf_edist x (thickening δ s) + ennreal.of_real δ := inf_edist_le_inf_edist_cthickening_add.trans $ add_le_add_right (inf_edist_anti $ thickening_subset_cthickening _ _) _ /-- For the equality, see `thickening_thickening`. -/ @[simp] lemma thickening_thickening_subset (ε δ : ℝ) (s : set α) : thickening ε (thickening δ s) ⊆ thickening (ε + δ) s := begin obtain hε | hε := le_total ε 0, { simp only [thickening_of_nonpos hε, empty_subset] }, obtain hδ | hδ := le_total δ 0, { simp only [thickening_of_nonpos hδ, thickening_empty, empty_subset] }, intros x, simp_rw [mem_thickening_iff_exists_edist_lt, ennreal.of_real_add hε hδ], exact λ ⟨y, ⟨z, hz, hy⟩, hx⟩, ⟨z, hz, (edist_triangle _ _ _).trans_lt $ ennreal.add_lt_add hx hy⟩, end /-- For the equality, see `thickening_cthickening`. -/ @[simp] lemma thickening_cthickening_subset (ε : ℝ) (hδ : 0 ≤ δ) (s : set α) : thickening ε (cthickening δ s) ⊆ thickening (ε + δ) s := begin obtain hε | hε := le_total ε 0, { simp only [thickening_of_nonpos hε, empty_subset] }, intro x, simp_rw [mem_thickening_iff_exists_edist_lt, mem_cthickening_iff, ←inf_edist_lt_iff, ennreal.of_real_add hε hδ], rintro ⟨y, hy, hxy⟩, exact inf_edist_le_edist_add_inf_edist.trans_lt (ennreal.add_lt_add_of_lt_of_le (hy.trans_lt ennreal.of_real_lt_top).ne hxy hy), end /-- For the equality, see `cthickening_thickening`. -/ @[simp] lemma cthickening_thickening_subset (hε : 0 ≤ ε) (δ : ℝ) (s : set α) : cthickening ε (thickening δ s) ⊆ cthickening (ε + δ) s := begin obtain hδ | hδ := le_total δ 0, { simp only [thickening_of_nonpos hδ, cthickening_empty, empty_subset] }, intro x, simp_rw [mem_cthickening_iff, ennreal.of_real_add hε hδ], exact λ hx, inf_edist_le_inf_edist_thickening_add.trans (add_le_add_right hx _), end /-- For the equality, see `cthickening_cthickening`. -/ @[simp] lemma cthickening_cthickening_subset (hε : 0 ≤ ε) (hδ : 0 ≤ δ) (s : set α) : cthickening ε (cthickening δ s) ⊆ cthickening (ε + δ) s := begin intro x, simp_rw [mem_cthickening_iff, ennreal.of_real_add hε hδ], exact λ hx, inf_edist_le_inf_edist_cthickening_add.trans (add_le_add_right hx _), end end cthickening --section end metric --namespace
Vanille opens with a shot of rum flavored with an orange rind and spiced with cloves. Amber and tonka further warm up this brew as ylang-ylang's sharp sweetness joins with rich vanilla. Gaiac wood adds incensey smoke as woody notes from vetiver and sandalwood help to create an elegant finish. But the real star of the show, not surprisingly, is vanilla. Instead of using ethyl vanillin, one of vanilla's main components that can come across as powdery and sugary, Mona di Orio used pure vanilla in this elixir. For a moment — amid this elegant orchestral arrangement of notes in the key of Vanilla — the pulpy, sensual creaminess of a split vanilla bean is right there in front of your nose. Delicious! Great and yes I would buy from you again.
#!/usr/bin/env python3 import numpy as np from scipy import interpolate def interpolate_traj(x_queue, x, y, interpolate_kind): # if interpolate_kind == 'traj' # interpolate the desired trajectory by time value # x_queue is the interpolated point/points # if x_queue is 1-D numpy array, then the output is 2-D numpy array # if x_queue is a float, then the output is 2-D numpy array, but only has one column # x is 1-D numpy array (1 by n), y is 2-D numpy array (m by n) # default is linear interpolation # when x_queue exceeds the range of x, function returns the boundary value of y # if interpolate_kind == 'cmd' # interpolate the commands by the machine time by Zero-Order Hold # x_queue is the interpolated machine time # assume x_queue is always 1-D numpy array, and the output is 2-D numpy array # time before the first timestamp, commands are zeros # time after the last timestamp, commands are the last ones. if interpolate_kind == 'traj': boundary = (y[:, 0], y[:, -1]) f = interpolate.interp1d(x, y, kind='linear', bounds_error=False, fill_value=boundary) y_raw = f(x_queue) if isinstance(x_queue, float): y_queue = y_raw.reshape(y_raw.shape[0], -1) else: y_queue = y_raw elif interpolate_kind == 'cmd': boundary = (np.zeros(4), y[:, -1]) f = interpolate.interp1d(x, y, kind='zero', bounds_error=False, fill_value=boundary) y_queue = f(x_queue) else: y_queue = [] raise Exception("The interpolation type is wrong!") return y_queue if __name__ == "__main__": x = np.array([0, 2, 4, 6, 8, 10]) y = np.array([[0, 1, 2, 3, 4, 5], [0, -1, -2, -3, -4, -5], [10, 20, 30, 40, 50, 60], [-10, -20, -30, -40, -50, -60], [0.5, 1.5, 2.5, 3.5, 4.5, 5.5]]) x_queue = 1 print(x) print(y) y_queue = interpolate_traj(x_queue, x, y, 'traj') print(y_queue)
(* Definitions and Properties of First-Order Terms *) (* with holes in [nat] for de Bruijn indices *) From Coq Require Export PeanoNat List. From OLlibs Require Import List_more. From OLlibs Require Export dectype. From Quantifiers Require Export term_tactics. Set Implicit Arguments. (* Extensional equality of functions *) Definition ext_eq {A B} (f g : A -> B) := forall a, f a = g a. Notation " f ~ g " := (ext_eq f g) (at level 60). (** * First-Order Terms *) Section Terms. Context {vatom : DecType} {tatom : Type}. (** terms with quantifiable variables arity not given meaning that we have a copy of each function name for each arity - [evar] for De Bruijn style eigen variables in proofs, type for these indices as parameter called the eigen type, but mostly used with [nat]. Other values can be used (for terms without indices, use [Empty_set]). - [tvar] for quantified variables in formulas *) Inductive term T := | evar : T -> term T | tvar : vatom -> term T | tconstr : tatom -> list (term T) -> term T. Arguments evar {T}. (** appropriate induction for [term] (with list inside): so called "nested fix" *) Fixpoint term_ind_list_Forall T t : forall P : term T -> Prop, (forall n, P (evar n)) -> (forall x, P (tvar T x)) -> (forall f l, Forall P l -> P (tconstr f l)) -> P t := fun P Pevar Ptvar Pconstr => match t with | evar n => Pevar n | tvar _ x => Ptvar x | tconstr c l => Pconstr c l ((fix l_ind l' : Forall P l' := match l' with | nil => Forall_nil P | cons t1 l1 => Forall_cons _ (term_ind_list_Forall t1 Pevar Ptvar Pconstr) (l_ind l1) end) l) end. Ltac term_induction t := (try intros until t); let nn := fresh "n" in let xx := fresh "x" in let cc := fresh "c" in let ll := fresh "l" in let IHll := fresh "IHl" in let i := fresh "i" in let Hi := fresh "Hi" in apply (term_ind_list_Forall t); [ intros nn; try (now intuition); simpl | intros xx; try (now intuition); simpl | intros cc ll IHll; simpl; intros; try (apply (f_equal (tconstr _))); rewrite ? flat_map_concat_map, ? map_map; try (apply (f_equal (@concat _))); match goal with | |- map _ ?l = ?l => rewrite <- (map_id l) at 2 | _ => idtac end; try (apply map_ext_in; intros i Hi; specialize_Forall_all i); try (apply Forall_forall; intros i Hi; specialize_Forall_all i); try (intuition; fail) ]; try (now rcauto). (** * Monad structure on [term] via substitution *) (** substitutes the [term] [r n] for index [n] in [term] [t] *) Fixpoint tesubs T1 T2 (r : T1 -> term T2) (t : term T1) := match t with | tvar _ x => tvar T2 x | evar k => r k | tconstr f l => tconstr f (map (tesubs r) l) end. Notation "t ⟦ r ⟧" := (tesubs r t) (at level 8, left associativity, format "t ⟦ r ⟧"). (** monad structure induced on [term] *) Lemma evar_tesubs T1 T2 (r : T1 -> term T2) x : (evar x)⟦r⟧ = r x. Proof. reflexivity. Qed. Hint Rewrite evar_tesubs : term_db. Lemma tesubs_evar T (t : term T) : t⟦evar⟧ = t. Proof. term_induction t. Qed. Hint Rewrite tesubs_evar : term_db. Definition fecomp T1 T2 T3 (r : T1 -> term T2) (s : T2 -> term T3) := fun x => (r x)⟦s⟧. Notation "r ;; s" := (fecomp r s) (at level 20, format "r ;; s"). Lemma tesubs_comp T1 T2 T3 (r : T1 -> term T2) (s : T2 -> term T3) t : t⟦r⟧⟦s⟧ = t⟦r ;; s⟧. Proof. term_induction t. Qed. Hint Rewrite tesubs_comp : term_db. (* the result of substitution depends extensionnaly on the substituting function *) Lemma tesubs_ext T1 T2 (r1 r2 : T1 -> term T2) : r1 ~ r2 -> forall t, t⟦r1⟧ = t⟦r2⟧. Proof. term_induction t. Qed. Hint Resolve tesubs_ext : term_db. (* TODO could be turned into a morphism *) Section Fixed_Eigen_Type. Variable T : Type. Implicit Type t : term T. Arguments tvar {T} _. (** * Term substitution *) (** substitutes [term] [u] for variable [x] in [term] [t] *) Fixpoint tsubs x u t := match t with | tvar y => if eq_dt_dec y x then u else tvar y | evar k => evar k | tconstr c l => tconstr c (map (tsubs x u) l) end. Notation "t [ u // x ]" := (tsubs x u t) (at level 8, format "t [ u // x ]"). Lemma tsubs_tsubs_eq : forall x u v t, t[v//x][u//x] = t[v[u//x]//x]. Proof. term_induction t. Qed. Hint Rewrite tsubs_tsubs_eq : term_db. (** * Variables *) Fixpoint tvars t := match t with | tvar x => x :: nil | evar _ => nil | tconstr _ l => flat_map tvars l end. Notation "x ∈ t" := (In x (tvars t)) (at level 30). Notation "x ∉ t" := (~ In x (tvars t)) (at level 30). Notation closed t := (tvars t = nil). Lemma closed_notvars t x : closed t -> x ∉ t. Proof. intros -> []. Qed. Hint Resolve closed_notvars : term_db. Lemma tvars_tsubs_closed x u (Hc : closed u) t : tvars t[u//x] = remove eq_dt_dec x (tvars t). Proof. term_induction t. rewrite remove_concat, flat_map_concat_map, map_map. f_equal. apply map_ext_in. intros v Hv. specialize_Forall IHl with v. exact IHl. Qed. Hint Rewrite tvars_tsubs_closed using intuition; fail : term_db. Lemma notin_tsubs : forall x u t, x ∉ t -> t[u//x] = t. Proof. term_induction t; try rcauto. apply IHl. intros Hx. apply H, in_flat_map. exists i. split; assumption. Qed. Hint Rewrite notin_tsubs using try (intuition; fail); try apply closed_notvars; intuition; fail : term_db. Lemma tsubs_tsubs x v y u : x <> y -> x ∉ u -> forall t, t[v//x][u//y] = t[u//y][v[u//y]//x]. Proof. term_induction t. Qed. Hint Rewrite tsubs_tsubs using try (intuition; fail); try apply closed_notvars; intuition; fail : term_db. Lemma notin_tsubs_bivar x y t : x ∉ t -> t[tvar x//y][tvar y//x] = t. Proof. term_induction t. apply IHl. intros Hx. apply H, in_flat_map. exists i. split; assumption. Qed. Hint Rewrite notin_tsubs_bivar using try (intuition; fail); try apply closed_notvars; (intuition; fail) : term_db. End Fixed_Eigen_Type. Section Two_Eigen_Types. Variable T1 T2 : Type. Variable r : T1 -> term T2. Notation closed t := (tvars t = nil). Notation rclosed := (forall n, closed (r n)). Notation "t [ u // x ]" := (tsubs x u t) (at level 8, format "t [ u // x ]"). Hint Rewrite notin_tsubs using try (intuition; fail); try apply closed_notvars; intuition; fail : term_db. (** * Additional results with variable eigen type *) Lemma tvars_tesubs_closed t : rclosed -> tvars t⟦r⟧ = tvars t. Proof. term_induction t. Qed. Hint Rewrite tvars_tesubs_closed using intuition; fail : term_db. Lemma tsubs_tesubs x u t : rclosed -> t[u//x]⟦r⟧ = t⟦r⟧[u⟦r⟧//x]. Proof. term_induction t. Qed. Hint Rewrite tsubs_tesubs using intuition; fail : term_db. End Two_Eigen_Types. (* We restrict to [term nat] *) Section Eigen_nat. Hint Rewrite tvars_tesubs_closed using intuition; fail : term_db. Notation term := (term nat). Notation tvar := (tvar nat). Notation "t [ u // x ]" := (tsubs x u t) (at level 8, format "t [ u // x ]"). Notation "x ∈ t" := (In x (tvars t)) (at level 30). Notation "x ∉ t" := (~ In x (tvars t)) (at level 30). Notation closed t := (tvars t = nil). Notation rclosed r := (forall n, closed (r n)). Definition fup := fun n => evar (S n). Notation "⇑" := fup. Notation "t ↑" := (t⟦⇑⟧) (at level 8, format "t ↑"). Lemma closed_fup : rclosed ⇑. Proof. reflexivity. Qed. Hint Rewrite closed_fup : term_db. Lemma tvars_fup t : tvars t↑ = tvars t. Proof. rcauto. Qed. Hint Rewrite tvars_fup : term_db. (* general shape, unused, generated through ↑ Definition fesubs k v := fun n => match n ?= k with | Lt => evar n | Eq => v | Gt => evar (pred n) end. Notation "v // ↓ k" := (fesubs k v) (at level 18, format "v // ↓ k"). Lemma closed_fesubs : forall k v, closed v -> rclosed (v//↓k). Proof. e_case_intuition unfolding fesubs. Qed. Hint Resolve closed_fesubs : term_db. Lemma fesubs_fup k v : ⇑ ;; v↑//↓(S k) == v//↓k ;; ⇑. Proof. intros ?; unfold fesubs, fup, fecomp; e_case_intuition. Qed. *) Definition fesubs v := fun n => match n with | 0 => v | S n => evar n end. Notation "v ⇓" := (fesubs v) (at level 18, format "v ⇓"). Lemma closed_fesubs v : closed v -> rclosed (v⇓). Proof. now intros Hc [|]. Qed. Hint Resolve closed_fesubs : term_db. Lemma fesubs_fup v : ⇑ ;; v⇓ ~ evar. Proof. intro. reflexivity. Qed. Lemma tesubs_fup v t : t↑⟦v⇓⟧ = t. Proof. rcauto. Qed. Hint Rewrite tesubs_fup : term_db. (* In practive only the case [u = evar 0] will be used *) Definition felift u r := fun n => match n with | 0 => u | S k => (r k)↑ end. Notation "⇑[ u ] r" := (felift u r) (at level 25, format "⇑[ u ] r"). Lemma closed_felift u r : closed u -> rclosed r -> rclosed (⇑[u]r). Proof. rnow intros ? ? [|]. Qed. Hint Resolve closed_felift : term_db. Lemma felift_comp u r : r ;; ⇑ ~ ⇑ ;; ⇑[u]r. Proof. intro. reflexivity. Qed. Hint Rewrite felift_comp : term_db. Lemma felift_tesubs u r t : t⟦r⟧↑ = t↑⟦⇑[u]r⟧. Proof. rcauto. Qed. Hint Rewrite felift_tesubs : term_db. End Eigen_nat. End Terms. Ltac term_induction t := (try intros until t); let nn := fresh "n" in let xx := fresh "x" in let cc := fresh "c" in let ll := fresh "l" in let IHll := fresh "IHl" in let i := fresh "i" in let Hi := fresh "Hi" in apply (term_ind_list_Forall t); [ intros nn; try (now intuition); simpl | intros xx; try (now intuition); simpl | intros cc ll IHll; simpl; intros; try (apply (f_equal (tconstr _))); rewrite ? flat_map_concat_map, ? map_map; try (apply (f_equal (@concat _))); match goal with | |- map _ ?l = ?l => rewrite <- (map_id l) at 2 | _ => idtac end; try (apply map_ext_in; intros i Hi; specialize_Forall_all i); try (apply Forall_forall; intros i Hi; specialize_Forall_all i); try (now intuition) ]; try (now (rnow idtac)); try (now rcauto).
// Copyright 2015-2020 The ALMA Project Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. /// @file /// Test whether the functions designed to deal with the "/scattering" /// group in HDF5 files work correctly. #include <iostream> #include <string> #include <boost/filesystem.hpp> #include <boost/mpi.hpp> #include "gtest/gtest.h" #include <vasp_io.hpp> #include <qpoint_grid.hpp> #include <processes.hpp> #include <bulk_hdf5.hpp> TEST(hdf5_scattering_case, hdf5_scattering_test) { boost::mpi::environment env; // Load some data for Si. auto basedir = boost::filesystem::path(TEST_RESOURCE_DIR); auto si_dir = basedir / boost::filesystem::path("Si"); auto poscar_path = si_dir / boost::filesystem::path("POSCAR"); auto ifc_path = si_dir / boost::filesystem::path("FORCE_CONSTANTS"); auto thirdorder_path = si_dir / boost::filesystem::path("FORCE_CONSTANTS_3RD"); auto poscar = alma::load_POSCAR(poscar_path.string().c_str()); auto syms = alma::Symmetry_operations(*poscar); auto force_constants = alma::load_FORCE_CONSTANTS(ifc_path.string().c_str(), *poscar, 5, 5, 5); auto thirdorder = alma::load_FORCE_CONSTANTS_3RD( thirdorder_path.string().c_str(), *poscar); // Create a trivially small q point grid. auto grid = std::make_unique<alma::Gamma_grid>( *poscar, syms, *force_constants, 4, 4, 4); grid->enforce_asr(); // Look for three-phonon processes. boost::mpi::communicator world; auto my_id = world.rank(); auto processes = alma::find_allowed_threeph(*grid, world, 0.1); // Precompute everything possible. for (auto& p : processes) { p.compute_gaussian(); p.compute_vp2(*poscar, *grid, *thirdorder); } // Create a temporary file name to write the information. auto h5fn = boost::filesystem::unique_path(); alma::save_bulk_hdf5(h5fn.string().c_str(), "Si test", *poscar, syms, *grid, processes, world); // Get a list of scattering subgroups in the file (should be empty // at this point). auto subgroups = alma::list_scattering_subgroups(h5fn.string().c_str(), world); ASSERT_EQ(0u, subgroups.size()); // Add a subgroup (containing random data) to the file. std::size_t nmodes = grid->get_spectrum_at_q(0).omega.size(); std::size_t nqpoints = grid->nqpoints; Eigen::ArrayXXd w0{nmodes, nqpoints}; if (my_id == 0) w0.setRandom(nmodes, nqpoints); boost::mpi::broadcast(world, w0.data(), w0.size(), 0); alma::Scattering_subgroup subgroup{ "test_subgroup", false, "This is a test subgroup", w0}; alma::write_scattering_subgroup(h5fn.string().c_str(), subgroup, world); // Try to add a second subgroup with the wrong shape, and test // that the code throws an exception. if (my_id == 0) { Eigen::ArrayXXd w0p{nmodes / 3, nqpoints}; alma::Scattering_subgroup subgroup2{ "test_subgroup", false, "This is a test subgroup", w0p}; EXPECT_THROW(alma::write_scattering_subgroup( h5fn.string().c_str(), subgroup2, world), alma::value_error); } // Now there should be one subgroup. subgroups = alma::list_scattering_subgroups(h5fn.string().c_str(), world); ASSERT_EQ(1u, subgroups.size()); // Test that everything has been written correctly and can be // loaded. auto loaded = alma::load_scattering_subgroup( h5fn.string().c_str(), "test_subgroup", world); EXPECT_EQ(loaded.name, subgroup.name); EXPECT_EQ(loaded.preserves_symmetry, subgroup.preserves_symmetry); EXPECT_EQ(loaded.description, subgroup.description); EXPECT_EQ(loaded.w0.rows(), subgroup.w0.rows()); EXPECT_EQ(loaded.w0.cols(), subgroup.w0.cols()); for (std::size_t i = 0; i < nmodes; ++i) for (std::size_t j = 0; j < nqpoints; ++j) EXPECT_TRUE(alma::almost_equal(loaded.w0(i, j), subgroup.w0(i, j))); EXPECT_EQ(loaded.attributes, subgroup.attributes); EXPECT_EQ(loaded.datasets, subgroup.datasets); EXPECT_EQ(loaded.groups, subgroup.groups); // Remove the temporary file. if (my_id == 0) boost::filesystem::remove(h5fn); }
import tactic set_option pp.generalized_field_notation false open nat namespace training def powerOf2 : ℕ → ℕ | 0 := 1 | (n+1) := 2 * powerOf2 n lemma lowerBoundPowerOf2 (n : ℕ) : 1 ≤ powerOf2 n := begin induction n; simp [powerOf2], linarith, end lemma sumSamePowerOf2 (n : ℕ) : powerOf2 n + powerOf2 n == 2 * powerOf2 n := by ring lemma monotonicPowerOf2 : ∀ {n m}, n ≤ m → powerOf2 n ≤ powerOf2 m | 0 m le := lowerBoundPowerOf2 m | (n+1) 0 le := by cases le | (n+1) (m+1) le := begin simp [powerOf2], apply monotonicPowerOf2, linarith, end lemma addPowerOf2 (n m : ℕ) : powerOf2 n * powerOf2 m = powerOf2 (n + m) := begin induction n; simp [powerOf2], rw [mul_assoc, n_ih, succ_add], simp [powerOf2], end inductive tree : Type | leaf : tree | node : tree → tree → tree namespace tree def height : tree → ℕ | leaf := 1 | (node l r) := max (height l) (height r) + 1 def nodeCount : tree → ℕ | leaf := 1 | (node l r) := nodeCount l + nodeCount r + 1 def leafCount : tree → ℕ | leaf := 1 | (node l r) := leafCount l + leafCount r -- Move - 1 to LHS to avoid nat subtraction lemma upperboundForNodeCount (root : tree) : nodeCount root + 1 ≤ powerOf2 (height root) := begin induction root with l r ih_l ih_r; simp [height, nodeCount, powerOf2], set hl := height l, set hr := height r, calc nodeCount (node l r) + 1 = nodeCount l + nodeCount r + 1 + 1 : rfl ... ≤ powerOf2 hl + powerOf2 hr : by linarith ... ≤ powerOf2 (max hl hr) + powerOf2 (max hl hr) : by linarith [ monotonicPowerOf2 (le_max_left hl hr) , monotonicPowerOf2 (le_max_right hl hr) ] ... = 2 * powerOf2 (max hl hr) : by ring ... = powerOf2 (max hl hr + 1) : rfl ... = powerOf2 (height (node l r)) : rfl end end tree end training
MODULE xlinbcg_data_sp USE mo_kind, ONLY: sprs2_sp TYPE(sprs2_sp) :: sa END MODULE xlinbcg_data_sp
! { dg-do run } ! PR42090 Problems reading partial records in formatted direct access files ! Test case from PR, prepared by Jerry DeLisle <[email protected]> program da_good_now implicit none real :: a, b a = 1.111111111 b = 2.222222222 open( 10, file = 't.dat', form = 'formatted', access = 'direct', recl = 12 ) write( 10, rec = 1, fmt = '( f6.4, /, f6.4 )' ) a, b close( 10 ) a = -1.0 b = -1.0 open( 10, file = 't.dat', form = 'formatted', access = 'direct', recl = 12 ) read( 10, rec = 1, fmt = '( f6.4, /, f6.4 )' ) a, b !write( *, '( "partial record 1", t25, 2( f6.4, 1x ) )' ) a, b a = -1.0 b = -1.0 read( 10, rec = 1, fmt = '( f6.4 )' ) a, b !write( *, '( "partial record 2", t25, 2( f6.4, 1x ) )' ) a, b if (a /= 1.1111 .and. b /= 2.2222) STOP 1 a = -1.0 b = -1.0 read( 10, rec = 1, fmt = '( f12.4, /, f12.4 )' ) a, b !write( *, '( "full record 1", t25, 2( f6.4, 1x ) )' ) a, b if (a /= 1.1111 .and. b /= 2.2222) STOP 2 a = -1.0 b = -1.0 read( 10, rec = 1, fmt = '( f12.4 )' ) a, b !write( *, '( "full record 2", t25, 2( f6.4, 1x ) )' ) a, b if (a /= 1.1111 .and. b /= 2.2222) STOP 3 a = -1.0 b = -1.0 read( 10, rec = 1, fmt = '( f6.4, 6x, /, f6.4, 6x )' ) a, b !write( *, '( "full record with 6x", t25, 2( f6.4, 1x ) )' ) a, b if (a /= 1.1111 .and. b /= 2.2222) STOP 4 a = -1.0 b = -1.0 read( 10, rec = 1, fmt = '( f6.4 )' ) a read( 10, rec = 2, fmt = '( f6.4 )' ) b !write( *, '( "record at a time", t25, 2( f6.4, 1x ) )' ) a, b if (a /= 1.1111 .and. b /= 2.2222) STOP 5 close( 10, status="delete") end program da_good_now
= = = Hereford United = = =
data Vect : Nat -> Type -> Type where Nil : Vect Z a (::) : a -> Vect k a -> Vect (S k) a %name Vect xs, ys, zs transpose : {m : Nat} -> Vect n (Vect m a) -> Vect m (Vect n a) transpose [] = ?empties transpose (x :: xs) = let xs_trans = transpose xs in ?transposeHelper
-- Exponential and compatible strengths module SOAS.Abstract.ExpStrength {T : Set} where open import SOAS.Families.Core {T} open import SOAS.Context open import SOAS.Variable open import SOAS.ContextMaps.Combinators open import SOAS.ContextMaps.CategoryOfRenamings open import SOAS.Common open import SOAS.Coalgebraic.Strength import SOAS.Abstract.Coalgebra as →□ open →□.Sorted open →□.Unsorted using (⊤ᵇ) renaming (Coalg to UCoalg ; Coalg⇒ to UCoalg⇒ ; □ᵇ to □ᵘᵇ) import SOAS.Abstract.Box as □ ; open □.Sorted open import SOAS.Families.BCCC using (⊤ₘ) private variable X : Family 𝒴 𝒵 : Familyₛ Γ Δ Θ : Ctx α : T -- Mixed-sorted Cartesian and linear exponentials _⇨_ : Family → Familyₛ → Familyₛ (X ⇨ 𝒴) τ Γ = X Γ → 𝒴 τ Γ _➡_ : Family → Familyₛ → Familyₛ X ➡ 𝒴 = □ (X ⇨ 𝒴) _⊸_ : Family → Familyₛ → Familyₛ (X ⊸ 𝒴) α Γ = {Δ : Ctx} → X Δ → 𝒴 α (Γ ∔ Δ) [_⊸_] : Familyₛ → Familyₛ → Family [ 𝒳 ⊸ 𝒴 ] Γ = {τ : T}{Δ : Ctx} → 𝒳 τ Δ → 𝒴 τ (Δ ∔ Γ) -- Linear exponential [ 𝒳 ⊸ 𝒴 ] is an unsorted coalgebra if 𝒴 is sorted coalgebra [_⊸_]ᵇ : (𝒳 {𝒴} : Familyₛ) → Coalg 𝒴 → UCoalg ([ 𝒳 ⊸ 𝒴 ]) [ 𝒳 ⊸ 𝒴ᵇ ]ᵇ = record { r = λ l ρ {_}{Δ} x → r (l x) (Δ ∔∣ ρ) ; counit = λ{ {Γ = Γ}{t = l} → iext (dext λ {Δ} ρ → trans (r≈₂ (Concatʳ.identity Γ {Δ})) counit) } ; comult = λ{ {Γ = Γ}{Δ}{Θ}{ρ = ρ}{ϱ}{l} → iext (dext λ {Ξ} x → trans (r≈₂ (Functor.homomorphism (Ξ ∔F-))) comult) } } where open Coalg 𝒴ᵇ -- Shorthands ⟅_⇨_⟆ : Familyₛ → Familyₛ → Familyₛ ⟅ 𝒳 ⇨ 𝒴 ⟆ = [ 𝒳 ⊸ 𝒴 ] ⇨ 𝒴 ⟅_➡_⟆ : Familyₛ → Familyₛ → Familyₛ ⟅ 𝒳 ➡ 𝒴 ⟆ = [ 𝒳 ⊸ 𝒴 ] ➡ 𝒴 ⟅_⊸_⟆ : Familyₛ → Familyₛ → Familyₛ ⟅ 𝒳 ⊸ 𝒴 ⟆ = [ 𝒳 ⊸ 𝒴 ] ⊸ 𝒴 -- Exponential strength of an endofunctor record ExpStrength (Fᶠ : Functor 𝔽amiliesₛ 𝔽amiliesₛ) : Set₁ where open Functor Fᶠ field -- Strength transformation that lifts a 𝒫-substitution over an endofunctor F₀ estr : {X : Family}(Xᵇ : UCoalg X)(𝒴 : Familyₛ) → F₀ (X ⇨ 𝒴) ⇾̣ (X ⇨ F₀ 𝒴) -- Naturality conditions for the two components estr-nat₁ : {X X′ : Family}{Xᵇ : UCoalg X}{X′ᵇ : UCoalg X′}{𝒴 : Familyₛ} → {f : X′ ⇾ X}(fᵇ⇒ : UCoalg⇒ X′ᵇ Xᵇ f) → (e : F₀ (X ⇨ 𝒴) α Γ) (x : X′ Γ) → estr Xᵇ 𝒴 e (f x) ≡ estr X′ᵇ 𝒴 (F₁ (λ e x → e (f x)) e) x estr-nat₂ : {X : Family}{Xᵇ : UCoalg X}{𝒴 𝒴′ : Familyₛ} → (g : 𝒴 ⇾̣ 𝒴′)(e : F₀ (X ⇨ 𝒴) α Γ)(x : X Γ) → estr Xᵇ 𝒴′ (F₁ (λ e x → g (e x)) e) x ≡ F₁ g (estr Xᵇ 𝒴 e x) estr-unit : {𝒴 : Familyₛ}{e : F₀ (⊤ₘ ⇨ 𝒴) α Γ} → estr ⊤ᵇ 𝒴 e tt ≡ F₁ (λ e′ → e′ tt) e -- Derived unit law estr-unit′ : {X : Family}{Xᵇ : UCoalg X}{𝒴 : Familyₛ}{e : F₀ (X ⇨ 𝒴) α Γ} {x : {Γ : Ctx} → X Γ}(fᵇ⇒ : UCoalg⇒ ⊤ᵇ Xᵇ (λ _ → x)) → estr Xᵇ 𝒴 e x ≡ F₁ (λ e′ → e′ x) e estr-unit′ {X = X}{Xᵇ}{𝒴}{e}{x} fᵇ⇒ = begin estr Xᵇ 𝒴 e x ≡⟨⟩ estr Xᵇ 𝒴 e ((λ _ → x) tt) ≡⟨ estr-nat₁ fᵇ⇒ e tt ⟩ estr ⊤ᵇ 𝒴 (F₁ (λ e′ _ → e′ x) e) tt ≡⟨ estr-unit ⟩ F₁ (λ e′ → e′ tt) (F₁ (λ e′ _ → e′ x) e) ≡˘⟨ homomorphism ⟩ F₁ (λ e′ → e′ x) e ∎ where open ≡-Reasoning -- Combination of coalgebraic and exponential strength over X ➡ 𝒴 = □ (X ⇨ 𝒴) module ➡-Strength (F:Str : Strength Fᶠ) where open Strength F:Str open ≡-Reasoning □estr : (Xᵇ : UCoalg X)(𝒴 : Familyₛ) → F₀ (X ➡ 𝒴) ⇾̣ (X ➡ F₀ 𝒴) □estr {X} Xᵇ 𝒴 e ρ x = estr Xᵇ 𝒴 (str ℐᴮ (X ⇨ 𝒴) e ρ) x -- Compatible exponential and coalgebraic strengths -- (for now no extra condition) record CompatStrengths (Fᶠ : Functor 𝔽amiliesₛ 𝔽amiliesₛ) : Set₁ where open Functor Fᶠ field CoalgStr : Strength Fᶠ ExpStr : ExpStrength Fᶠ open Strength CoalgStr public open ExpStrength ExpStr public open ➡-Strength CoalgStr public
(*************************************************************************** * Safety for Simply Typed Lambda Calculus (CBV) - Definitions * * Brian Aydemir & Arthur Chargueraud, July 2007 * ***************************************************************************) Set Implicit Arguments. Require Import LibLN. Implicit Types x : var. (** Grammar of types. *) Inductive typ : Set := | typ_var : var -> typ | typ_arrow : typ -> typ -> typ. (** Grammar of pre-terms. *) Inductive trm : Set := | trm_bvar : nat -> trm | trm_fvar : var -> trm | trm_abs : trm -> trm | trm_app : trm -> trm -> trm. (** Opening up abstractions *) Fixpoint open_rec (k : nat) (u : trm) (t : trm) {struct t} : trm := match t with | trm_bvar i => If k = i then u else (trm_bvar i) | trm_fvar x => trm_fvar x | trm_abs t1 => trm_abs (open_rec (S k) u t1) | trm_app t1 t2 => trm_app (open_rec k u t1) (open_rec k u t2) end. Definition open t u := open_rec 0 u t. Notation "{ k ~> u } t" := (open_rec k u t) (at level 67). Notation "t ^^ u" := (open t u) (at level 67). Notation "t ^ x" := (open t (trm_fvar x)). (** Terms are locally-closed pre-terms *) Inductive term : trm -> Prop := | term_var : forall x, term (trm_fvar x) | term_abs : forall L t1, (forall x, x \notin L -> term (t1 ^ x)) -> term (trm_abs t1) | term_app : forall t1 t2, term t1 -> term t2 -> term (trm_app t1 t2). (** Environment is an associative list mapping variables to types. *) Definition env := LibEnv.env typ. (** Typing relation *) Reserved Notation "E |= t ~: T" (at level 69). Inductive typing : env -> trm -> typ -> Prop := | typing_var : forall E x T, ok E -> binds x T E -> E |= (trm_fvar x) ~: T | typing_abs : forall L E U T t1, (forall x, x \notin L -> (E & x ~ U) |= t1 ^ x ~: T) -> E |= (trm_abs t1) ~: (typ_arrow U T) | typing_app : forall S T E t1 t2, E |= t1 ~: (typ_arrow S T) -> E |= t2 ~: S -> E |= (trm_app t1 t2) ~: T where "E |= t ~: T" := (typing E t T). (** Definition of values (only abstractions are values) *) Inductive value : trm -> Prop := | value_abs : forall t1, term (trm_abs t1) -> value (trm_abs t1). (** Reduction relation - one step in call-by-value *) Inductive red : trm -> trm -> Prop := | red_beta : forall t1 t2, term (trm_abs t1) -> value t2 -> red (trm_app (trm_abs t1) t2) (t1 ^^ t2) | red_app_1 : forall t1 t1' t2, term t2 -> red t1 t1' -> red (trm_app t1 t2) (trm_app t1' t2) | red_app_2 : forall t1 t2 t2', value t1 -> red t2 t2' -> red (trm_app t1 t2) (trm_app t1 t2'). Notation "t --> t'" := (red t t') (at level 68). (** Goal is to prove preservation and progress *) Definition preservation := forall E t t' T, E |= t ~: T -> t --> t' -> E |= t' ~: T. Definition progress := forall t T, empty |= t ~: T -> value t \/ exists t', t --> t'.
lemma residue_lmul: assumes "open s" "z \<in> s" and f_holo: "f holomorphic_on s - {z}" shows "residue (\<lambda>z. c * (f z)) z= c * residue f z"
(* Title: HOL/Probability/Discrete_Topology.thy Author: Fabian Immler, TU München *) theory Discrete_Topology imports "HOL-Analysis.Analysis" begin text \<open>Copy of discrete types with discrete topology. This space is polish.\<close> typedef 'a discrete = "UNIV::'a set" morphisms of_discrete discrete .. instantiation discrete :: (type) metric_space begin definition dist_discrete :: "'a discrete \<Rightarrow> 'a discrete \<Rightarrow> real" where "dist_discrete n m = (if n = m then 0 else 1)" definition uniformity_discrete :: "('a discrete \<times> 'a discrete) filter" where "(uniformity::('a discrete \<times> 'a discrete) filter) = (INF e\<in>{0 <..}. principal {(x, y). dist x y < e})" definition "open_discrete" :: "'a discrete set \<Rightarrow> bool" where "(open::'a discrete set \<Rightarrow> bool) U \<longleftrightarrow> (\<forall>x\<in>U. eventually (\<lambda>(x', y). x' = x \<longrightarrow> y \<in> U) uniformity)" instance proof qed (auto simp: uniformity_discrete_def open_discrete_def dist_discrete_def intro: exI[where x=1]) end lemma open_discrete: "open (S :: 'a discrete set)" unfolding open_dist dist_discrete_def by (auto intro!: exI[of _ "1 / 2"]) instance discrete :: (type) complete_space proof fix X::"nat\<Rightarrow>'a discrete" assume "Cauchy X" hence "\<exists>n. \<forall>m\<ge>n. X n = X m" by (force simp: dist_discrete_def Cauchy_def split: if_split_asm dest:spec[where x=1]) then guess n .. thus "convergent X" by (intro convergentI[where L="X n"] tendstoI eventually_sequentiallyI[of n]) (simp add: dist_discrete_def) qed instance discrete :: (countable) countable proof have "inj (\<lambda>c::'a discrete. to_nat (of_discrete c))" by (simp add: inj_on_def of_discrete_inject) thus "\<exists>f::'a discrete \<Rightarrow> nat. inj f" by blast qed instance discrete :: (countable) second_countable_topology proof let ?B = "range (\<lambda>n::'a discrete. {n})" have "\<And>S. generate_topology ?B (\<Union>x\<in>S. {x})" by (intro generate_topology_Union) (auto intro: generate_topology.intros) then have "open = generate_topology ?B" by (auto intro!: ext simp: open_discrete) moreover have "countable ?B" by simp ultimately show "\<exists>B::'a discrete set set. countable B \<and> open = generate_topology B" by blast qed instance discrete :: (countable) polish_space .. end
-- -------------------------------------------------------------- [ Lens.idr ] -- Description : Idris port of Control.Lens -- Copyright : (c) Huw Campbell -- --------------------------------------------------------------------- [ EOH ] module Control.Lens.Types import Control.Lens.Const import Data.Contravariant import Control.Lens.First import Control.Monad.Identity import Data.Bifunctor import Data.Profunctor import Data.Tagged %default total public export Optic : (Type -> Type -> Type) -> (Type -> Type) -> Type -> Type -> Type -> Type -> Type Optic p f s t a b = p a (f b) -> p s (f t) public export Simple : (Type -> Type -> Type -> Type -> Type) -> Type -> Type -> Type Simple p s a = p s s a a public export Optic' : (Type -> Type -> Type) -> (Type -> Type) -> Type -> Type -> Type Optic' p f = Simple (Optic p f) public export LensLike : (Type -> Type) -> Type -> Type -> Type -> Type -> Type LensLike = Optic Morphism public export LensLike' : (Type -> Type) -> Type -> Type -> Type LensLike' f = Simple (LensLike f) -- type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t public export Lens : Type -> Type -> Type -> Type -> Type Lens s t a b = { f : Type -> Type } -> Functor f => LensLike f s t a b -- type Lens' s a = Lens s s a a public export Lens' : Type -> Type -> Type Lens' = Simple Lens -- type Getting r s a = (a -> Const r a) -> s -> Const r s public export Getting : Type -> Type -> Type -> Type Getting r = LensLike' (Const r) -- type Getter s a = forall f. (Contravariant f, Functor f) => (a -> f a) -> s -> f s public export Getter : Type -> Type -> Type Getter s a = { f : Type -> Type } -> (Contravariant f, Functor f) => LensLike' f s a -- type ASetter s t a b = (a -> Identity b) -> s -> Identity t public export Setter : Type -> Type -> Type -> Type -> Type Setter = LensLike Identity public export Setter' : Type -> Type -> Type Setter' = Simple Setter -- type Traversal s t a b = forall f. Applicative f => (a -> f b) -> s -> f t public export Traversal : Type -> Type -> Type -> Type -> Type Traversal s t a b = { f : Type -> Type } -> Applicative f => LensLike f s t a b -- type Traversal' s a = Traversal s s a a public export Traversal' : Type -> Type -> Type Traversal' = Simple Traversal -- type Prism s t a b = forall p f. (Choice p, Applicative f) => p a (f b) -> p s (f t) -- The choice of `Choice p` for a valid `Traversal` is the `(->)` implementation. Which is used -- when using a prism as a getter or setter. public export Prism : Type -> Type -> Type -> Type -> Type Prism s t a b = {p : Type -> Type -> Type} -> { f : Type -> Type } -> (Choice p,Applicative f) => Optic p f s t a b public export Prism' : Type -> Type -> Type Prism' = Simple Prism public export Iso : Type -> Type -> Type -> Type -> Type Iso s t a b = {p : Type -> Type -> Type} -> {f : Type -> Type} -> (Profunctor p,Functor f) => Optic p f s t a b public export Iso' : Type -> Type -> Type Iso' = Simple Iso -- type Review t b = forall p f. (Choice p, Bifunctor p, Settable f) => Optic' p f t b public export Review : Type -> Type -> Type -> Type -> Type Review s t a b = { p : Type -> Type -> Type } -> { f : Type -> Type } -> (Choice p, Bifunctor p) => Optic p Identity s t a b -- type AReview t b = Optic' Tagged Identity t b public export AReview : Type -> Type -> Type AReview t b = Optic' Tagged Identity t b -- --------------------------------------------------------------------- [ EOF ]
#include "compi.hpp" #include <complex> #include <unordered_map> #include <algorithm> #include <utility> #include <boost/math/quadrature/gauss_kronrod.hpp> #include <boost/math/tools/precision.hpp> extern "C" { #include "integration_routines.h" } #include "integration_routines_template.hpp" #include "IntegrandFunctionWrapper.hpp" #include "utils.hpp" struct GaussKronrodParameters: public RoutineParametersBase{ Real x_min; Real x_max; unsigned points = 31; GaussKronrodParameters(PyObject* routine_args, PyObject* routine_kwargs){ constexpr std::array<const char*,0> dumby_arg = {}; constexpr std::array<const char*,1> keyword_only_args = {"points"}; constexpr auto keywords = generate_keyword_list<IntegralRange::finite>(dumby_arg,dumby_arg,keyword_only_args); if(!PyArg_ParseTupleAndKeywords(routine_args,routine_kwargs,"Odd|OO$pIdI",const_cast<char**>(keywords.data()), &integrand,&x_min,&x_max, &args,&kw, &full_output, &max_levels,&tolerance,&points)){ throw could_not_parse_arguments("Unable to parse python arguments to C variables"); } } }; GaussKronrodParameters::result_type run_integration_routine(const compi_internal::IntegrandFunctionWrapper& f, const GaussKronrodParameters& parameters){ using std::complex; using namespace compi_internal; using boost::math::quadrature::gauss_kronrod; using IntegrationRoutine = complex<Real>(*)(IntegrandFunctionWrapper, Real, Real, unsigned, Real, Real*, Real*); // The possible tempates for the different allowed numbers of divisions are instasiated, // so that the Python runtime can select which one to use static const std::unordered_map<unsigned,IntegrationRoutine> integration_routines{{15,gauss_kronrod<Real,15>::integrate}, {31,gauss_kronrod<Real,31>::integrate}, {41,gauss_kronrod<Real,41>::integrate}, {51,gauss_kronrod<Real,51>::integrate}, {61,gauss_kronrod<Real,61>::integrate} }; GaussKronrodParameters::result_type result; try{ result.result = integration_routines.at(parameters.points)(f,parameters.x_min,parameters.x_max,parameters.max_levels,parameters.tolerance,&(result.err),&(result.l1)); } catch (const std::out_of_range& e){ PyErr_SetString(PyExc_ValueError,"Invalid number of points for gauss_kronrod"); throw unable_to_call_integration_routine("Invalid number of points for gauss_kronrod"); } return result; } template<unsigned points> std::pair<PyObject*, PyObject*> get_abscissa_and_weights() noexcept{ auto abscissa = compi_internal::py_list_from_real_container(boost::math::quadrature::gauss_kronrod<Real,points>::abscissa()); if(abscissa == NULL){ return std::make_pair<PyObject*,PyObject*>(NULL,NULL); } auto weights = compi_internal::py_list_from_real_container(boost::math::quadrature::gauss_kronrod<Real,points>::weights()); if(weights == NULL){ Py_DECREF(abscissa); return std::make_pair<PyObject*,PyObject*>(NULL,NULL); } return std::make_pair(abscissa,weights); } template<> PyObject* generate_full_output_dict(const GaussKronrodParameters::result_type& result, const GaussKronrodParameters& parameters) noexcept{ // The boost API returning the abscissa and weights simply spesifies that // they are returned as a (reference to a) random access container. // Since this could (reasonably) depend on points (e.g. array<Real,points>) // it is awkward to use the map based appraoch in run_integation_routine // and instead we use more verbose a template/switch based approach std::pair<PyObject*,PyObject*> abscissa_and_weights; switch(parameters.points){ case 15: abscissa_and_weights = get_abscissa_and_weights<15>(); break; case 31: abscissa_and_weights = get_abscissa_and_weights<31>(); break; case 41: abscissa_and_weights = get_abscissa_and_weights<41>(); break; case 51: abscissa_and_weights = get_abscissa_and_weights<51>(); break; case 61: abscissa_and_weights = get_abscissa_and_weights<61>(); break; default: // Should never get here as have already checked the value of points is valid PyErr_SetString(PyExc_NotImplementedError,"Unable to generate abscissa and weights for the given number of points.\nPlease report this bug"); return NULL; } if(abscissa_and_weights.first == NULL || abscissa_and_weights.second == NULL){ return NULL; } return Py_BuildValue("{sfsOsO}","L1 norm",result.l1,"abscissa",abscissa_and_weights.first,"weights",abscissa_and_weights.second); } // Integrates a Python function returning a complex over a finite interval using // Gauss-Kronrod adaptive quadrature extern "C" PyObject* gauss_kronrod(PyObject* self, PyObject* args, PyObject* kwargs){ return integration_routine<GaussKronrodParameters>(args,kwargs); }
[STATEMENT] lemma monotone_rel_prod_iff: "monotone (rel_prod orda ordb) ordc f \<longleftrightarrow> (\<forall>a. monotone ordb ordc (\<lambda>b. f (a, b))) \<and> (\<forall>b. monotone orda ordc (\<lambda>a. f (a, b)))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. monotone (rel_prod orda ordb) ordc f = ((\<forall>a. monotone ordb ordc (\<lambda>b. f (a, b))) \<and> (\<forall>b. monotone orda ordc (\<lambda>a. f (a, b)))) [PROOF STEP] using a b c [PROOF STATE] proof (prove) using this: class.preorder orda (mk_less orda) class.preorder ordb (mk_less ordb) class.preorder ordc (mk_less ordc) goal (1 subgoal): 1. monotone (rel_prod orda ordb) ordc f = ((\<forall>a. monotone ordb ordc (\<lambda>b. f (a, b))) \<and> (\<forall>b. monotone orda ordc (\<lambda>a. f (a, b)))) [PROOF STEP] by(blast intro: monotone_rel_prodI dest: monotone_rel_prodD1 monotone_rel_prodD2)
Formal statement is: lemma continuous_map_real_mult_right: "continuous_map X euclideanreal f \<Longrightarrow> continuous_map X euclideanreal (\<lambda>x. f x * c)" Informal statement is: If $f$ is a continuous real-valued function, then so is $f \cdot c$ for any constant $c$.
/- Copyright (c) 2020 The Xena project. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard. Thanks: Imperial College London, leanprover-community -/ -- We will assume that the real numbers are a field. import data.real.basic /-! # The complex numbers We define the complex numbers, and prove that they are a ring. We also "extract some basic API" (e.g. we prove that two complex numbers are equal iff they have the same real and imaginary parts) This file has no `sorry`s in. All of the other levels: `Level_01_of_real.lean` `Level_02_I.lean` `Level_03_conj.lean` `Level_04_norm_sq.lean` `Level_05_field.lean` `Level_06_alg_closed.lean` have sorrys, indicating puzzles to be solved. # Main Definitions `zero` : the complex number 0 `one` : the complex number 1 `add` -- addition of two complex numbers `neg` -- negation of a complex number `mul` -- multiplication of two complex numbers # Main Theorem `comm_ring` : The complex numbers are a commutative ring. -/ /-- A complex number is defined to be a structure consisting of two real numbers, the real part and the imaginary part of the complex numberd. -/ structure complex : Type := (re : ℝ) (im : ℝ) -- Let's use the usual notation for the complex numbers notation `ℂ` := complex -- You make the complex number with real part 3 and imaginary part 4 like this: example : ℂ := { re := 3, im := 4 } -- Or like this: example : ℂ := complex.mk 3 4 -- or like this: example : ℂ := ⟨3, 4⟩ -- They all give the same complex number. example : complex.mk 3 4 = ⟨3, 4⟩ := begin refl end -- "true by definition" -- All of our definitions, like `zero` and `one`, will all -- live in the `complex` namespace. namespace complex -- If you have a complex number, then you can get its real and -- imaginary parts with the `re` and `im` functions. example : ℝ := re(mk 3 4) -- this term is (3 : ℝ) example : re(mk 3 4) = 3 := begin refl end -- Computer scientists prefer the style `z.re` to `re(z)` for some reason. example : (mk 3 4).re = 3 := begin refl end example (z : ℂ) : re(z) = z.re := begin refl end -- Before we start making the basic -- We now prove the basic theorems and make the basic definitions for -- complex numbers. For example, we will define addition and multiplication on -- the complex numbers, and prove that it is a commutative ring. -- TODO fix /-! # Defining the ring structure on ℂ -/ -- Our main goal is to prove that the complexes are a ring. Let's -- define the structure first; the zero, one, addition and multiplication -- on the complexes. /-! ## zero (0) -/ /-- The complex number with real part 0 and imaginary part 0 -/ def zero : ℂ := ⟨0, 0⟩ -- Now we set up notation so that `0 : ℂ` will mean `zero`. /-- notation `0` for `zero` -/ instance : has_zero ℂ := ⟨zero⟩ -- Let's prove the two basic properties, both of which are true by definition, -- and then tag them with the appropriate attributes. @[simp] lemma zero_re : re(0 : ℂ) = 0 := begin refl end @[simp] lemma zero_im : im(0 : ℂ) = 0 := begin refl end /-! ## one (1) -/ -- Now let's do the same thing for 1. /-- The complex number with real part 1 and imaginary part 0 -/ def one : ℂ := ⟨1, 0⟩ /-- Notation `1` for `one` -/ instance : has_one ℂ := ⟨one⟩ -- name the basic properties and tag them with `simp` @[simp] lemma one_re : re(1 : ℂ) = 1 := begin refl end @[simp] lemma one_im : im(1 : ℂ) = 0 := begin refl end /-! ## add (+) -/ -- Now let's define addition /-- addition `z+w` of complex numbers -/ def add (z w : ℂ) : ℂ := ⟨z.re + w.re, z.im + w.im⟩ /-- Notation `+` for addition -/ instance : has_add ℂ := ⟨add⟩ -- basic properties @[simp] lemma add_re (z w : ℂ) : re(z + w) = re(z) + re(w) := begin refl end @[simp] lemma add_im (z w : ℂ) : im(z + w) = im(z) + im(w) := begin refl end /-! ## neg (-) -/ -- negation /-- The negation `-z` of a complex number `z` -/ def neg (z : ℂ) : ℂ := ⟨-re(z), -im(z)⟩ /-- Notation `-` for negation -/ instance : has_neg ℂ := ⟨neg⟩ -- how neg interacts with re and im @[simp] lemma neg_re (z : ℂ) : re(-z) = -re(z) := begin refl end @[simp] lemma neg_im (z : ℂ) : im(-z) = -im(z) := begin refl end /-! ## mul (*) -/ -- multiplication /-- Multiplication `z*w` of two complex numbers -/ def mul (z w : ℂ) : ℂ := ⟨re(z) * re(w) - im(z) * im(w), re(z) * im(w) + im(z) * re(w)⟩ /-- Notation `*` for multiplication -/ instance : has_mul ℂ := ⟨mul⟩ -- how `mul` reacts with `re` and `im` @[simp] lemma mul_re (z w : ℂ) : re(z * w) = re(z) * re(w) - im(z) * im(w) := begin refl end @[simp] lemma mul_im (z w : ℂ) : im(z * w) = re(z) * im(w) + im(z) * re(w) := rfl /-! ## Example of what `simp` can now do example (a b c : ℂ) : re(a*(b+c)) = re(a) * (re(b) + re(c)) - im(a) * (im(b) + im(c)) := begin simp, end -/ /-! # `ext` : A mathematical triviality -/ /- Two complex numbers with the same and imaginary parts are equal. This is an "extensionality lemma", i.e. a lemma of the form "if two things are made from the same pieces, they are equal". This is not hard to prove, but we want to give the result a name so we can tag it with the `ext` attribute, meaning that the `ext` tactic will know it. To add to the confusion, let's call the theorem `ext` :-) -/ /-- If two complex numbers z and w have equal real and imaginary parts, they are equal -/ @[ext] theorem ext {z w : ℂ} (hre : re(z) = re(w)) (him : im(z) = im(w)) : z = w := begin cases z with zr zi, cases w with ww wi, simp * at *, end /-! # Theorem: The complex numbers are a commutative ring Proof: we've defined all the structure, and every axiom can be checked by reducing it to checking real and imaginary parts with `ext`, expanding everything out with `simp`, and then using the fact that the real numbers are a commutative ring (which we already know) -/ /-- The complex numbers are a commutative ring -/ instance : comm_ring ℂ := begin -- first the data refine_struct { zero := (0 : ℂ), add := (+), neg := has_neg.neg, one := 1, mul := (*), ..}; -- now the axioms -- of which there seem to be 11 -- Note the semicolons, which mean "apply next tactic to all goals". -- First introduce the variables intros; -- we now have to prove an equality between two complex numbers. -- It suffices to check on real and imaginary parts ext; -- the simplifier can simplify stuff like re(a+0) simp; -- all the goals now are identities between *real* numbers, -- and the reals are already known to be a ring ring, end /- That is the end of the proof that the complexes form a ring. We built a basic API which was honed towards the general idea that to prove certain statements about the complex numbers, for example distributivity, we could just check on real and imaginary parts. We trained the simplifier to expand out things like re(z*w) in terms of re(z), im(z), re(w), im(w). -/ /-! # Optional (for mathematicians) : more basic infrastructure, and term mode -/ /-! ## `ext` revisited Recall extensionality: theorem ext {z w : ℂ} (hre : re(z) = re(w)) (him : im(z) = im(w)) : z = w := ... Here is another tactic mode proof of extensionality. Note that we have moved the hypotheses to the other side of the colon; this does not change the theorem. This proof shows the power of the `rintros` tactic. -/ theorem ext' : ∀ z w : ℂ, z.re = w.re → z.im = w.im → z = w := begin rintros ⟨zr, zi⟩ ⟨_, _⟩ ⟨rfl⟩ ⟨rfl⟩, refl, end /-! Explanation: `rintros` does `cases` as many times as you like using this cool `⟨ ⟩` syntax for the case splits. Note that if you say that a proof of `a = b` is `rfl` then Lean will define a to be b, or b to be a, and not even introduce new notation for it. -/ -- Here is the same proof in term mode. theorem ext'' : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w | ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl /-! ## `eta` -/ /- We prove the mathematically obvious statement that the complex number whose real part is re(z) and whose imaginary part is im(z) is of course equal to z. -/ /-- ⟨z.re, z.im⟩ is equal to z -/ @[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z := begin intro z, cases z with x y, /- goal now looks complicated, and contains terms which look like {re := a, im := b}.re which obviously simplify to a. The `dsimp` tactic will do some tidying up for us, although it is not logically necessary. `dsimp` does definitional simplification. -/ dsimp, -- Now we see the goal can be solved by reflexivity refl, end /- The proof was "unfold everything, and it's true by definition". This proof does not teach a mathematician anything, so we may as well write it in term mode. Many tactics have term mode equivalent. The equation compiler does the `intro` and `cases` steps, and `dsimp` was unnecessary -- the two sides of the equation were definitionally equal. -/ theorem eta' : ∀ z : ℂ, complex.mk z.re z.im = z | ⟨x, y⟩ := rfl /-! ## ext_iff -/ /- Note that `ext` is an implication -- if re(z)=re(w) and im(z)=im(w) then z=w. The below variant `ext_iff` is the two-way implication: two complex numbers are equal if and only if they have the same real and imaginary part. Let's first see a tactic mode proof. See how the `ext` tactic is used? After it is applied, we have two goals, both of which are hypotheses. The semicolon means "apply the next tactic to all the goals produced by this one" -/ theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im := begin split, { intro H, simp [H]}, { rintro ⟨hre, him⟩, ext; assumption, } end -- Again this is easy to write in term mode, and no mathematician -- wants to read the proof anyway. theorem ext_iff' {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im := ⟨λ H, by simp [H], and.rec ext⟩ end complex /-! # some last comments on the `simp` tactic Some equalities, even if obvious, had to be given names, because we want `simp` to be able to use them. In short, the `simp` tactic tries to solve goals of the form A = B, when `refl` doesn't work (i.e. the goals are not definitionally equal) but when any mathematician would be able to simplify A and B via "obvious" steps such as `0 + x = x` or `⟨z.re, z.im⟩ = z`. These things are sometimes not true by definition, but they should be tagged as being well-known ways to simplify an equality. When building our API for the complex numbers, if we prove a theorem of the form `A = B` where `B` is a bit simpler than `A`, we should probably tag it with the `@[simp]` attribute, so `simp` can use it. Note: `simp` does *not* prove "all simple things". It proves *equalities*. It proves `A = B` when, and only when, it can do it by applying its "simplification rules", where a simplification rule is simply a proof of a theorem of the form `A = B` and `B` is simpler than `A`. -/
C Copyright(C) 1999-2020 National Technology & Engineering Solutions C of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with C NTESS, the U.S. Government retains certain rights in this software. C C See packages/seacas/LICENSE for details C======================================================================= SUBROUTINE PLTMG2(MAP,N,XV,YV,NO,XVO,YVO) REAL MAP(*) INTEGER N REAL XV(*),YV(*) INTEGER NO REAL XVO(*),YVO(*) REAL XWORK(50),YWORK(50) INTEGER NWORK NOSAVE = NO AXX = MAP(1) AYY = MAP(4) AXY = MAP(3) AYX = MAP(2) BX = MAP(5) BY = MAP(6) DO 2220 I = 1,N XVO(I) = AXX*XV(I) + AXY*YV(I) + BX YVO(I) = AYX*XV(I) + AYY*YV(I) + BY 2220 CONTINUE NWORK = 50 CALL PLTCG2(N,XVO,YVO,NWORK,XWORK,YWORK,MAP(7),MAP(9)) NO = NOSAVE CALL PLTCG2(NWORK,XWORK,YWORK,NO,XVO,YVO,MAP(9),MAP(11)) NWORK = 50 CALL PLTCG2(NO,XVO,YVO,NWORK,XWORK,YWORK,MAP(11),MAP(13)) NO = NOSAVE CALL PLTCG2(NWORK,XWORK,YWORK,NO,XVO,YVO,MAP(13),MAP(7)) RETURN END
If the degree of a polynomial $p$ is less than $n$, then the coefficient of $x^n$ in $p$ is zero.
import numpy as np import pandas as pd from tqdm import tqdm def rle_decode(rle_mask): ''' rle_mask: run-length as string formated (start length) shape: (height,width) of array to return Returns numpy array, 1 - mask, 0 - background ''' s = rle_mask.split() starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])] starts -= 1 ends = starts + lengths img = np.zeros(101*101, dtype=np.uint8) for lo, hi in zip(starts, ends): img[lo:hi] = 1 return img.reshape(101,101) """ used for converting the decoded image to rle mask """ def rle_encode(im): ''' im: numpy array, 1 - mask, 0 - background Returns run length as string formated ''' pixels = im.flatten() pixels = np.concatenate([[0], pixels, [0]]) runs = np.where(pixels[1:] != pixels[:-1])[0] + 1 runs[1::2] -= runs[::2] return ' '.join(str(x) for x in runs) df_1 = pd.read_csv('../submission/submission_1.csv') df_2 = pd.read_csv('../submission/submission_2.csv') df_3 = pd.read_csv('../submission/submission_3.csv') df_4 = pd.read_csv('../submission/submission_4.csv') df_5 = pd.read_csv('../submission/submission_5.csv') df_1_id = pd.read_csv('../submission/submission_1.csv', index_col="rle_mask") df_2_id = pd.read_csv('../submission/submission_2.csv', index_col="rle_mask") df_3_id = pd.read_csv('../submission/submission_3.csv', index_col="rle_mask") df_4_id = pd.read_csv('../submission/submission_4.csv', index_col="rle_mask") df_5_id = pd.read_csv('../submission/submission_5.csv', index_col="rle_mask") d1 = df_1_id.values.tolist() d2 = df_2_id.values.tolist() d3 = df_3_id.values.tolist() d4 = df_4_id.values.tolist() d5 = df_5_id.values.tolist() """ Applying vote on the predicted mask """ for i in tqdm(range(df_1.shape[0])): name = df_1_id.values[i] index_1 = d1.index(name) index_2 = d2.index(name) index_3 = d3.index(name) index_4 = d4.index(name) index_5 = d5.index(name) if str(df_1.loc[index_1,'rle_mask'])!=str(np.nan): decoded_mask_1 = rle_decode(df_1.loc[index_1,'rle_mask']) else: decoded_mask_1 = np.zeros((101, 101), np.int8) if str(df_2.loc[index_2, 'rle_mask']) != str(np.nan): decoded_mask_2 = rle_decode(df_2.loc[index_2, 'rle_mask']) else: decoded_mask_2 = np.zeros((101, 101), np.int8) if str(df_3.loc[index_3, 'rle_mask']) != str(np.nan): decoded_mask_3 = rle_decode(df_3.loc[index_3, 'rle_mask']) else: decoded_mask_3 = np.zeros((101, 101), np.int8) if str(df_4.loc[index_4, 'rle_mask']) != str(np.nan): decoded_mask_4 = rle_decode(df_4.loc[index_4, 'rle_mask']) else: decoded_mask_4 = np.zeros((101, 101), np.int8) if str(df_5.loc[index_5, 'rle_mask']) != str(np.nan): decoded_mask_5 = rle_decode(df_5.loc[index_5, 'rle_mask']) else: decoded_mask_5 = np.zeros((101, 101), np.int8) decoded_masks = decoded_mask_1 + decoded_mask_2 + decoded_mask_3 + decoded_mask_4 + decoded_mask_5 decoded_masks = decoded_masks / 5.0 df_1.loc[index_1, 'rle_mask'] = rle_encode(np.round(decoded_masks >= 0.5)) df_1.to_csv('../submission/vote_correction.csv',index=False)
Formal statement is: lemma summable_imp_bounded: fixes f :: "nat \<Rightarrow> 'a::real_normed_vector" shows "summable f \<Longrightarrow> bounded (range f)" Informal statement is: If a sequence of real numbers is summable, then the sequence is bounded.
[STATEMENT] lemma mult_bot_omega: "(x * bot)\<^sup>\<omega> = x * bot" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x * bot)\<^sup>\<omega> = x * bot [PROOF STEP] by (metis mult_left_zero omega_slide)
State Before: α : Sort u_1 β : Sort u_2 inst✝ : Nonempty α f : α → β a : α b✝ : β g : β → α hf : Injective f hg : RightInverse g f b : β ⊢ f (invFun f b) = f (g b) State After: α : Sort u_1 β : Sort u_2 inst✝ : Nonempty α f : α → β a : α b✝ : β g : β → α hf : Injective f hg : RightInverse g f b : β ⊢ f (invFun f b) = b Tactic: rw [hg b] State Before: α : Sort u_1 β : Sort u_2 inst✝ : Nonempty α f : α → β a : α b✝ : β g : β → α hf : Injective f hg : RightInverse g f b : β ⊢ f (invFun f b) = b State After: no goals Tactic: exact invFun_eq ⟨g b, hg b⟩
State Before: ι : Type ?u.2724 F : Type u_3 α : Type u_1 β : Type u_2 γ : Type ?u.2736 δ : Type ?u.2739 inst✝³ : Group α inst✝² : CommSemigroup β inst✝¹ : LE β inst✝ : SubmultiplicativeHomClass F α β f : F a b : α ⊢ ↑f a ≤ ↑f b * ↑f (a / b) State After: no goals Tactic: simpa only [mul_comm, div_mul_cancel'] using map_mul_le_mul f (a / b) b
library(extraDistr) # sample: r, pdf: d, cdf: p, quantile: q x = 3 lRange = 1; uRange = 9; rdunif(1,lRange,uRange); ddunif(x,lRange,uRange); pdunif(x,lRange,uRange); qdunif(0.2,lRange,uRange); # from extraDistr p = 0.8; rbern(1,p); dbern(1,p); pbern(1,p); qbern(0.2,p); # from extraDistr n = 20; p = 0.8; rbinom(1,n,p); dbinom(x,n,p); pbinom(x,n,p); qbinom(0.2,n,p); ps = c(0.2,0.5,0.2,0.1); rcat(1,ps); dcat(x,ps); pcat(x,ps); qcat(0.2,ps); # from extraDistr p = 0.2; rgeom(1,p); dgeom(x,p); pgeom(x,p); qgeom(0.2,p); sAv = 10; fAv = 20; nTrials = 3; rhyper(1, sAv, fAv, nTrials); dhyper(x, sAv, fAv, nTrials); phyper(x, sAv, fAv, nTrials); qhyper(0.2, sAv, fAv, nTrials) rate = 10; rpois(1,rate); dpois(x,rate); ppois(x,rate); qpois(0.2,rate) nSucc =10; p = 0.2; rnbinom(1, nSucc,p); dnbinom(x, nSucc,p); pnbinom(1, nSucc,p); qnbinom(0.2, nSucc,p); # Return the number of failures before n successes instead of total trials to n successes lRange = 1; uRange = 9; runif(1,lRange,uRange); dunif(x,lRange,uRange); punif(x,lRange,uRange); qunif(0.2,lRange,uRange); rate = 2.5; rexp(1,rate); dexp(x,rate); pexp(x,rate); qexp(0.2,rate); μ = 2; σsq = 5 ; rnorm(1,μ,sqrt(σsq)); dnorm(x,μ,sqrt(σsq)); pnorm(x,μ,sqrt(σsq)); qnorm(0.2,μ,sqrt(σsq)); n = 5; rate = 2.5; #use gamma, as erlang special case of it when shape is integer μ = 2.5; σ = 2.5; rcauchy(1,μ,σ); dcauchy(x,μ,σ); pcauchy(x,μ,σ); qcauchy(0.2,μ,σ) df = 3; rchisq(1,df); dchisq(x,df); pchisq(x,df); qchisq(0.2,df); df = 4.5; rt(1,df); dt(x,df); pt(x,df); qt(0.2,df); df1 = 6 ; df2 = 7; rf(1,df1,df2); df(x,df1,df2); pf(x,df1,df2); qf(0.2,df1,df2); shapeα = 2.5; shapeβ=4.5; rbeta(1,shapeα,shapeβ); dbeta(x,shapeα,shapeβ); pbeta(x,shapeα,shapeβ); qbeta(0.2,shapeα,shapeβ) shapeα = 2.5; rateβ = 4.5; rgamma(1,shapeα,1/rateβ); dgamma(x,shapeα,1/rateβ); pgamma(x,shapeα,1/rateβ); qgamma(0.2,shapeα,1/rateβ) xs = c(3,12,5) n=20; ps = c(0.2,0.5,0.3); rmnom(1,n,ps); dmnom(xs,n,ps); # from extraDistr initialNByCat = c(5,14,7); nTrials=20 ; rmvhyper(1,initialNByCat,nTrials); dmvhyper(xs,initialNByCat,nTrials) # from extraDistr
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta ! This file was ported from Lean 3 source module category_theory.limits.preserves.limits ! leanprover-community/mathlib commit e97cf15cd1aec9bd5c193b2ffac5a6dc9118912b ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.CategoryTheory.Limits.Preserves.Basic /-! # Isomorphisms about functors which preserve (co)limits If `G` preserves limits, and `C` and `D` have limits, then for any diagram `F : J ⥤ C` we have a canonical isomorphism `preservesLimitsIso : G.obj (Limit F) ≅ Limit (F ⋙ G)`. We also show that we can commute `IsLimit.lift` of a preserved limit with `functor.map_cone`: `(PreservesLimit.preserves t).lift (G.mapCone c₂) = G.map (t.lift c₂)`. The duals of these are also given. For functors which preserve (co)limits of specific shapes, see `preserves/shapes.lean`. -/ universe w' w v₁ v₂ u₁ u₂ noncomputable section namespace CategoryTheory open Category Limits variable {C : Type u₁} [Category.{v₁} C] variable {D : Type u₂} [Category.{v₂} D] variable (G : C ⥤ D) variable {J : Type w} [Category.{w'} J] variable (F : J ⥤ C) section variable [PreservesLimit F G] @[simp] theorem preserves_lift_mapCone (c₁ c₂ : Cone F) (t : IsLimit c₁) : (PreservesLimit.preserves t).lift (G.mapCone c₂) = G.map (t.lift c₂) := ((PreservesLimit.preserves t).uniq (G.mapCone c₂) _ (by simp [← G.map_comp])).symm #align category_theory.preserves_lift_map_cone CategoryTheory.preserves_lift_mapCone variable [HasLimit F] [HasLimit (F ⋙ G)] /-- If `G` preserves limits, we have an isomorphism from the image of the limit of a functor `F` to the limit of the functor `F ⋙ G`. -/ def preservesLimitIso : G.obj (limit F) ≅ limit (F ⋙ G) := (PreservesLimit.preserves (limit.isLimit _)).conePointUniqueUpToIso (limit.isLimit _) #align category_theory.preserves_limit_iso CategoryTheory.preservesLimitIso @[reassoc (attr := simp)] theorem preservesLimitsIso_hom_π (j) : (preservesLimitIso G F).hom ≫ limit.π _ j = G.map (limit.π F j) := IsLimit.conePointUniqueUpToIso_hom_comp _ _ j #align category_theory.preserves_limits_iso_hom_π CategoryTheory.preservesLimitsIso_hom_π @[reassoc (attr := simp)] theorem preservesLimitsIso_inv_π (j) : (preservesLimitIso G F).inv ≫ G.map (limit.π F j) = limit.π _ j := IsLimit.conePointUniqueUpToIso_inv_comp _ _ j #align category_theory.preserves_limits_iso_inv_π CategoryTheory.preservesLimitsIso_inv_π @[reassoc (attr := simp)] theorem lift_comp_preservesLimitsIso_hom (t : Cone F) : G.map (limit.lift _ t) ≫ (preservesLimitIso G F).hom = limit.lift (F ⋙ G) (G.mapCone _) := by ext simp [← G.map_comp] #align category_theory.lift_comp_preserves_limits_iso_hom CategoryTheory.lift_comp_preservesLimitsIso_hom variable [PreservesLimitsOfShape J G] [HasLimitsOfShape J D] [HasLimitsOfShape J C] /-- If `C, D` has all limits of shape `J`, and `G` preserves them, then `preservesLimitsIso` is functorial wrt `F`. -/ @[simps!] def preservesLimitNatIso : lim ⋙ G ≅ (whiskeringRight J C D).obj G ⋙ lim := NatIso.ofComponents (fun F => preservesLimitIso G F) (by intro _ _ f apply Limits.limit.hom_ext; intro j dsimp simp only [preservesLimitsIso_hom_π, whiskerRight_app, limMap_π, Category.assoc, preservesLimitsIso_hom_π_assoc, ← G.map_comp]) #align category_theory.preserves_limit_nat_iso CategoryTheory.preservesLimitNatIso end section variable [PreservesColimit F G] @[simp] theorem preserves_desc_mapCocone (c₁ c₂ : Cocone F) (t : IsColimit c₁) : (PreservesColimit.preserves t).desc (G.mapCocone _) = G.map (t.desc c₂) := ((PreservesColimit.preserves t).uniq (G.mapCocone _) _ (by simp [← G.map_comp])).symm #align category_theory.preserves_desc_map_cocone CategoryTheory.preserves_desc_mapCocone variable [HasColimit F] [HasColimit (F ⋙ G)] -- TODO: think about swapping the order here /-- If `G` preserves colimits, we have an isomorphism from the image of the colimit of a functor `F` to the colimit of the functor `F ⋙ G`. -/ def preservesColimitIso : G.obj (colimit F) ≅ colimit (F ⋙ G) := (PreservesColimit.preserves (colimit.isColimit _)).coconePointUniqueUpToIso (colimit.isColimit _) #align category_theory.preserves_colimit_iso CategoryTheory.preservesColimitIso @[reassoc (attr := simp)] theorem ι_preservesColimitsIso_inv (j : J) : colimit.ι _ j ≫ (preservesColimitIso G F).inv = G.map (colimit.ι F j) := IsColimit.comp_coconePointUniqueUpToIso_inv _ (colimit.isColimit (F ⋙ G)) j #align category_theory.ι_preserves_colimits_iso_inv CategoryTheory.ι_preservesColimitsIso_inv @[reassoc (attr := simp)] theorem ι_preservesColimitsIso_hom (j : J) : G.map (colimit.ι F j) ≫ (preservesColimitIso G F).hom = colimit.ι (F ⋙ G) j := (PreservesColimit.preserves (colimit.isColimit _)).comp_coconePointUniqueUpToIso_hom _ j #align category_theory.ι_preserves_colimits_iso_hom CategoryTheory.ι_preservesColimitsIso_hom @[reassoc (attr := simp)] theorem preservesColimitsIso_inv_comp_desc (t : Cocone F) : (preservesColimitIso G F).inv ≫ G.map (colimit.desc _ t) = colimit.desc _ (G.mapCocone t) := by ext simp [← G.map_comp] #align category_theory.preserves_colimits_iso_inv_comp_desc CategoryTheory.preservesColimitsIso_inv_comp_desc variable [PreservesColimitsOfShape J G] [HasColimitsOfShape J D] [HasColimitsOfShape J C] /-- If `C, D` has all colimits of shape `J`, and `G` preserves them, then `preservesColimitIso` is functorial wrt `F`. -/ @[simps!] def preservesColimitNatIso : colim ⋙ G ≅ (whiskeringRight J C D).obj G ⋙ colim := NatIso.ofComponents (fun F => preservesColimitIso G F) (by intro _ _ f rw [← Iso.inv_comp_eq, ← Category.assoc, ← Iso.eq_comp_inv] apply Limits.colimit.hom_ext; intro j dsimp erw [ι_colimMap_assoc] simp only [ι_preservesColimitsIso_inv, whiskerRight_app, Category.assoc, ι_preservesColimitsIso_inv_assoc, ← G.map_comp] erw [ι_colimMap]) #align category_theory.preserves_colimit_nat_iso CategoryTheory.preservesColimitNatIso end end CategoryTheory
[STATEMENT] lemma node_relatorD: "node_relator x y \<Longrightarrow> x \<in> y" [PROOF STATE] proof (prove) goal (1 subgoal): 1. node_relator x y \<Longrightarrow> x \<in> y [PROOF STEP] unfolding node_relator_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. x \<in> y \<Longrightarrow> x \<in> y [PROOF STEP] .
module OCaml.IO %default total %access public export --------- The OCaml FFI data OCamlRaw : Type -> Type where MkOCamlRaw : (x:t) -> OCamlRaw t %used MkOCamlRaw x data Module : List (String, Type) -> Type val : String -> Type -> (String, Type) val s t = (s,t) data Abstr1 : Type -> Type mutual data OCaml_IntTypes : Type -> Type where OCaml_IntChar : OCaml_IntTypes Char OCaml_IntNative : OCaml_IntTypes Int OCaml_IntBits32 : OCaml_IntTypes Bits32 OCaml_IntBits64 : OCaml_IntTypes Bits64 data OCaml_FnTypes : Type -> Type where OCaml_Fn : OCaml_Types s -> OCaml_FnTypes t -> OCaml_FnTypes (s -> t) OCaml_FnIO : OCaml_Types s -> OCaml_Types t -> OCaml_FnTypes (s -> IO' l t) OCaml_FnBase : OCaml_Types s -> OCaml_Types t -> OCaml_FnTypes (s -> t) data OCamlTypeList : List (String, Type) -> Type where Done : OCamlTypeList [] Next : OCaml_Types a -> OCamlTypeList tys -> OCamlTypeList ((l, a) :: tys) data OCaml_Types : Type -> Type where OCaml_Str : OCaml_Types String OCaml_Float : OCaml_Types Double OCaml_Bool : OCaml_Types Bool OCaml_Abstr1: OCaml_Types (Abstr1 a) OCaml_Ptr : OCaml_Types Ptr OCaml_Unit : OCaml_Types () OCaml_Any : OCaml_Types (OCamlRaw a) OCaml_FnT : OCaml_FnTypes a -> OCaml_Types a OCaml_Pair : OCaml_Types a -> OCaml_Types b -> OCaml_Types (a, b) OCaml_List : OCaml_Types a -> OCaml_Types (List a) OCaml_Maybe : OCaml_Types a -> OCaml_Types (Maybe a) OCaml_IntT : OCaml_IntTypes i -> OCaml_Types i OCaml_Mod : OCamlTypeList tys -> OCaml_Types (Module tys) %error_reverse FFI_OCaml : FFI FFI_OCaml = MkFFI OCaml_Types String String %error_reverse OCaml_IO : Type -> Type OCaml_IO = IO' FFI_OCaml mutual -- Translates an OCaml-conventions function to an Idris-conventions -- one by inserting an additional dummy 'world' argument. --%inline fromOCamlFn : OCaml_FnTypes a -> a -> a fromOCamlFn (OCaml_Fn s t) f = \x => fromOCamlFn t (f (toOCaml s x)) fromOCamlFn (OCaml_FnIO s t) f = \x => pure (fromOCaml t (believe_me (f (toOCaml s x)))) fromOCamlFn (OCaml_FnBase s t) f = \x => fromOCaml t (f (toOCaml s x)) -- %inline fromOCaml : OCaml_Types a -> a -> a fromOCaml OCaml_Str s = s fromOCaml OCaml_Float f = f fromOCaml OCaml_Bool b = b fromOCaml OCaml_Ptr p = p fromOCaml OCaml_Abstr1 x = x fromOCaml OCaml_Unit u = u fromOCaml OCaml_Any a = a fromOCaml (OCaml_FnT t) f = fromOCamlFn t f fromOCaml (OCaml_Pair s t) p = (fromOCaml s (fst p), fromOCaml t (snd p)) fromOCaml (OCaml_List s) l = map (fromOCaml s) l fromOCaml (OCaml_Maybe s) m = map (fromOCaml s) m fromOCaml (OCaml_IntT _) i = i fromOCaml (OCaml_Mod ts) m = m --%inline toOCamlFn : OCaml_FnTypes a -> a -> a toOCamlFn (OCaml_Fn s t) f = \x => toOCamlFn t (f (fromOCaml s x)) toOCamlFn (OCaml_FnIO s t) f = \x => believe_me (toOCaml t (unsafePerformIO (f (fromOCaml s x)))) toOCamlFn (OCaml_FnBase s t) f = \x => toOCaml t (f (fromOCaml s x)) -- %inline toOCaml : OCaml_Types a -> a -> a toOCaml OCaml_Str s = s toOCaml OCaml_Float f = f toOCaml OCaml_Bool b = b toOCaml OCaml_Ptr p = p toOCaml OCaml_Abstr1 x = x toOCaml OCaml_Unit u = u toOCaml OCaml_Any a = a toOCaml (OCaml_FnT t) f = toOCamlFn t f toOCaml (OCaml_Pair s t) p = (toOCaml s (fst p), toOCaml t (snd p)) toOCaml (OCaml_List s) l = map (toOCaml s) l toOCaml (OCaml_Maybe s) m = map (toOCaml s) m toOCaml (OCaml_IntT _) i = i toOCaml (OCaml_Mod ts) m = m %inline fromOCamlFTy : FTy FFI_OCaml xs ty -> ty -> ty fromOCamlFTy (FRet t) f = do x <- f; pure (fromOCaml t x) fromOCamlFTy (FFun s t) f = \x => fromOCamlFTy t (f (toOCaml s x)) %inline ocamlCall : (fname : String) -> (ty : Type) -> {auto fty : FTy FFI_OCaml [] ty} -> ty ocamlCall fname ty {fty} = fromOCamlFTy fty (foreign FFI_OCaml fname ty) printLn : Show a => a -> OCaml_IO () printLn = printLn' putStrLn : String -> OCaml_IO () putStrLn = putStrLn' print : Show a => a -> OCaml_IO () print = print' putStr : String -> OCaml_IO () putStr = putStr' getLine : OCaml_IO String getLine = getLine' -- Some specific functions from the Stdlib module print_endline : String -> OCaml_IO () print_endline s = ocamlCall "Stdlib.print_endline" (String -> OCaml_IO ()) s -- Modules data StrItem : String -> Type -> Type where Let : (s : String) -> t -> StrItem s t data Values : List (String, Type) -> Type where Nil : Values [] (::) : StrItem s t -> Values tys -> Values ((s, t) :: tys) assocIdx : String -> Int -> List (String, Type) -> Maybe (Int, Type) assocIdx k i [] = Nothing assocIdx k i ((k',t)::tys) = if k == k' then Just (i,t) else assocIdx k (i+1) tys infixl 1 # %inline (#) : Module tys -> (nm : String) -> {auto ok : assocIdx nm 0 tys = Just (i, a)} -> {auto p : OCaml_Types a} -> {auto q : OCamlTypeList tys} -> a (#) {tys} {a} {i} m nm = unsafePerformIO $ ocamlCall "Idrisobj.field" (Module tys -> Int -> OCaml_IO a) m i %inline struct : Values tys -> {auto p : OCamlTypeList tys} -> Module tys struct {tys} vs {p} = unsafePerformIO (go vs p 0) where %inline go : Values tys2 -> OCamlTypeList tys2 -> Int -> OCaml_IO (Module tys) go {tys2 = []} Nil Done n = ocamlCall "Idrisobj.new_block" (Int -> Int -> OCaml_IO (Module tys)) 0 n go {tys2 = (_, ty) :: tys2} (Let _ v :: vs) (Next t q) n = do m <- go vs q (n + 1) ocamlCall "Idrisobj.set_field" (Module tys -> Int -> ty -> OCaml_IO ()) m n v pure m
module Package.IkanAst import Package.IpkgAst import Control.Monad.Freer import Debug.Trace import Control.Monad.Id import Data.Fin import Control.Monad.State %access public export data IkanData : Type -> Type where AddDependencies : List String -> IkanData Unit AddSourcepaths : List String -> IkanData Unit IkanDataT : Type IkanDataT = Freer IkanData Unit implicit liftd : IkanData a -> Freer IkanData a liftd = liftF {- ex1:IkanDataT ex1 = do AddDependencies [] AddSourcepaths [] -}
With changing times, it has almost become the need of the hour for every member of a household to have a personal laptop! While the proposition has a very appealing sound to it, this can often become a daunting idea after all. We say so, for the simple reason, that every once in a while, your laptop might need a good services in terms of the hardware or software, for it to run smoothly, more efficiently. As you must have experienced, quite often a good laptop service center is the solution for this problem. But how do you what makes a service center good or bad? Well, let’s take a look with respect to what a good service center should constitute of, and then you can be the judge of it yourself! Since working schedules are becoming tighter with each passing day especially in large cosmopolitan cities, it is extremely important that your laptop is up and running at all times. This however is possible only when your Laptop Service Center in Noida is open on all days and avails it services rather instantaneously. For the simple reason that money is rather difficult to come by and then stay, it is important for us all to save as much money as we can. This makes it imperative for our Laptop Service Centre to offer the best of services priced in an optimal manner so that it doesn’t burn a hole in our pockets. As clichéd as it may sound, we all know that what makes for a good Dell Service Center is the fact that it offers quite a friendly environment, that doesn’t let you think twice before entering it. And to think about it, it’s rather important for things to be so, considering that it’ll help you a great deal in explain to the technicians the problems that you’re facing and coming up with an optimal solution for the same through an open dialogue with them. This goes almost without saying that a trusted Service Center must offer all services with utmost efficiency, without any inadmissible lag in the time taken for the delivery of the repaired laptop, or discrepancy in the final billing for the services offered!
-- BOTH: import analysis.special_functions.log.basic variables a b c d e : ℝ open real /- TEXT: .. _using_theorems_and_lemmas: Using Theorems and Lemmas ------------------------- .. index:: inequalities Rewriting is great for proving equations, but what about other sorts of theorems? For example, how can we prove an inequality, like the fact that :math:`a + e^b \le a + e^c` holds whenever :math:`b \le c`? We have already seen that theorems can be applied to arguments and hypotheses, and that the ``apply`` and ``exact`` tactics can be used to solve goals. In this section, we will make good use of these tools. Consider the library theorems ``le_refl`` and ``le_trans``: TEXT. -/ -- QUOTE: #check (le_refl : ∀ a : ℝ, a ≤ a) #check (le_trans : a ≤ b → b ≤ c → a ≤ c) -- QUOTE. /- TEXT: As we explain in more detail in :numref:`implication_and_the_universal_quantifier`, the implicit parentheses in the statement of ``le_trans`` associate to the right, so it should be interpreted as ``a ≤ b → (b ≤ c → a ≤ c)``. The library designers have set the arguments to ``le_trans`` implicit, so that Lean will *not* let you provide them explicitly (unless you really insist, as we will discuss later). Rather, it expects to infer them from the context in which they are used. For example, when hypotheses ``h : a ≤ b`` and ``h' : b ≤ c`` are in the context, all the following work: TEXT. -/ section -- QUOTE: variables (h : a ≤ b) (h' : b ≤ c) #check (le_refl : ∀ a : real, a ≤ a) #check (le_refl a : a ≤ a) #check (le_trans : a ≤ b → b ≤ c → a ≤ c) #check (le_trans h : b ≤ c → a ≤ c) #check (le_trans h h' : a ≤ c) -- QUOTE. end /- TEXT: .. index:: apply, tactics ; apply The ``apply`` tactic takes a proof of a general statement or implication, tries to match the conclusion with the current goal, and leaves the hypotheses, if any, as new goals. If the given proof matches the goal exactly (modulo *definitional* equality), you can use the ``exact`` tactic instead of ``apply``. So, all of these work: TEXT. -/ -- QUOTE: example (x y z : ℝ) (h₀ : x ≤ y) (h₁ : y ≤ z) : x ≤ z := begin apply le_trans, { apply h₀ }, apply h₁ end example (x y z : ℝ) (h₀ : x ≤ y) (h₁ : y ≤ z) : x ≤ z := begin apply le_trans h₀, apply h₁ end example (x y z : ℝ) (h₀ : x ≤ y) (h₁ : y ≤ z) : x ≤ z := by exact le_trans h₀ h₁ example (x y z : ℝ) (h₀ : x ≤ y) (h₁ : y ≤ z) : x ≤ z := le_trans h₀ h₁ example (x : ℝ) : x ≤ x := by apply le_refl example (x : ℝ) : x ≤ x := by exact le_refl x example (x : ℝ) : x ≤ x := le_refl x -- QUOTE. /- TEXT: In the first example, applying ``le_trans`` creates two goals, and we use the curly braces to enclose the proof of the first one. In the fourth example and in the last example, we avoid going into tactic mode entirely: ``le_trans h₀ h₁`` and ``le_refl x`` are the proof terms we need. Here are a few more library theorems: TEXT. -/ -- QUOTE: #check (le_refl : ∀ a, a ≤ a) #check (le_trans : a ≤ b → b ≤ c → a ≤ c) #check (lt_of_le_of_lt : a ≤ b → b < c → a < c) #check (lt_of_lt_of_le : a < b → b ≤ c → a < c) #check (lt_trans : a < b → b < c → a < c) -- QUOTE. /- TEXT: Use them together with ``apply`` and ``exact`` to prove the following: TEXT. -/ /- Try this. -/ -- QUOTE: example (h₀ : a ≤ b) (h₁ : b < c) (h₂ : c ≤ d) (h₃ : d < e) : a < e := sorry -- QUOTE. -- SOLUTIONS: example (h₀ : a ≤ b) (h₁ : b < c) (h₂ : c ≤ d) (h₃ : d < e) : a < e := begin apply lt_of_le_of_lt h₀, apply lt_trans h₁, exact lt_of_le_of_lt h₂ h₃ end /- TEXT: .. index:: linarith, tactics ; linarith In fact, Lean has a tactic that does this sort of thing automatically: TEXT. -/ -- QUOTE: example (h₀ : a ≤ b) (h₁ : b < c) (h₂ : c ≤ d) (h₃ : d < e) : a < e := by linarith -- QUOTE. /- TEXT: The ``linarith`` tactic is designed to handle *linear arithmetic*. TEXT. -/ section -- QUOTE: example (h : 2 * a ≤ 3 * b) (h' : 1 ≤ a) (h'' : d = 2) : d + a ≤ 5 * b := by linarith -- QUOTE. end /- TEXT: In addition to equations and inequalities in the context, ``linarith`` will use additional inequalities that you pass as arguments. In the next example, ``exp_le_exp.mpr h'`` is a proof of ``exp b ≤ exp c``, as we will explain in a moment. Notice that, in Lean, we write ``f x`` to denote the application of a function ``f`` to the argument ``x``, exactly the same way we write ``h x`` to denote the result of applying a fact or theorem ``h`` to the argument ``x``. Parentheses are only needed for compound arguments, as in ``f (x + y)``. Without the parentheses, ``f x + y`` would be parsed as ``(f x) + y``. TEXT. -/ -- QUOTE: example (h : 1 ≤ a) (h' : b ≤ c) : 2 + a + exp b ≤ 3 * a + exp c := by linarith [exp_le_exp.mpr h'] -- QUOTE. /- TEXT: .. index:: exponential, logarithm Here are some more theorems in the library that can be used to establish inequalities on the real numbers. TEXT. -/ -- QUOTE: #check (exp_le_exp : exp a ≤ exp b ↔ a ≤ b) #check (exp_lt_exp : exp a < exp b ↔ a < b) #check (log_le_log : 0 < a → 0 < b → (log a ≤ log b ↔ a ≤ b)) #check (log_lt_log : 0 < a → a < b → log a < log b) #check (add_le_add : a ≤ b → c ≤ d → a + c ≤ b + d) #check (add_le_add_left : a ≤ b → ∀ c, c + a ≤ c + b) #check (add_le_add_right : a ≤ b → ∀ c, a + c ≤ b + c) #check (add_lt_add_of_le_of_lt : a ≤ b → c < d → a + c < b + d) #check (add_lt_add_of_lt_of_le : a < b → c ≤ d → a + c < b + d) #check (add_lt_add_left : a < b → ∀ c, c + a < c + b) #check (add_lt_add_right : a < b → ∀ c, a + c < b + c) #check (add_nonneg : 0 ≤ a → 0 ≤ b → 0 ≤ a + b) #check (add_pos : 0 < a → 0 < b → 0 < a + b) #check (add_pos_of_pos_of_nonneg : 0 < a → 0 ≤ b → 0 < a + b) #check (exp_pos : ∀ a, 0 < exp a) #check @add_le_add_left -- QUOTE. /- TEXT: Some of the theorems, ``exp_le_exp``, ``exp_lt_exp``, and ``log_le_log`` use a *bi-implication*, which represents the phrase "if and only if." (You can type it in VS Code with ``\lr`` of ``\iff``). We will discuss this connective in greater detail in the next chapter. Such a theorem can be used with ``rw`` to rewrite a goal to an equivalent one: TEXT. -/ -- QUOTE: example (h : a ≤ b) : exp a ≤ exp b := begin rw exp_le_exp, exact h end -- QUOTE. /- TEXT: In this section, however, we will use the fact that if ``h : A ↔ B`` is such an equivalence, then ``h.mp`` establishes the forward direction, ``A → B``, and ``h.mpr`` establishes the reverse direction, ``B → A``. Here, ``mp`` stands for "modus ponens" and ``mpr`` stands for "modus ponens reverse." You can also use ``h.1`` and ``h.2`` for ``h.mp`` and ``h.mpr``, respectively, if you prefer. Thus the following proof works: TEXT. -/ -- QUOTE: example (h₀ : a ≤ b) (h₁ : c < d) : a + exp c + e < b + exp d + e := begin apply add_lt_add_of_lt_of_le, { apply add_lt_add_of_le_of_lt h₀, apply exp_lt_exp.mpr h₁ }, apply le_refl end -- QUOTE. /- TEXT: The first line, ``apply add_lt_add_of_lt_of_le``, creates two goals, and once again we use the curly brackets to separate the proof of the first from the proof of the second. .. index:: norm_num, tactics ; norm_num Try the following examples on your own. The example in the middle shows you that the ``norm_num`` tactic can be used to solve concrete numeric goals. TEXT. -/ -- QUOTE: example (h₀ : d ≤ e) : c + exp (a + d) ≤ c + exp (a + e) := begin sorry end example : (0 : ℝ) < 1 := by norm_num example (h : a ≤ b) : log (1 + exp a) ≤ log (1 + exp b) := begin have h₀ : 0 < 1 + exp a, { sorry }, have h₁ : 0 < 1 + exp b, { sorry }, apply (log_le_log h₀ h₁).mpr, sorry end -- QUOTE. -- SOLUTIONS: example (h₀ : d ≤ e) : c + exp (a + d) ≤ c + exp (a + e) := begin apply add_le_add_left, rw exp_le_exp, apply add_le_add_left h₀ end -- an alterantive using `linarith`. example (h₀ : d ≤ e) : c + exp (a + d) ≤ c + exp (a + e) := begin have : exp (a + d) ≤ exp (a + e), { rw exp_le_exp, linarith }, linarith [this] end example (h : a ≤ b) : log (1 + exp a) ≤ log (1 + exp b) := begin have h₀ : 0 < 1 + exp a, { linarith [exp_pos a]}, have h₁ : 0 < 1 + exp b, { linarith [exp_pos b] }, apply (log_le_log h₀ h₁).mpr, apply add_le_add_left (exp_le_exp.mpr h), end -- SOLUTION. /- TEXT: From these examples, it should be clear that being able to find the library theorems you need constitutes an important part of formalization. There are a number of strategies you can use: * You can browse mathlib in its `GitHub repository <https://github.com/leanprover-community/mathlib>`_. * You can use the API documentation on the mathlib `web pages <https://leanprover-community.github.io/mathlib_docs/>`_. * You can rely on mathlib naming conventions and tab completion in the editor to guess a theorem name. In Lean, a theorem named ``A_of_B_of_C`` establishes something of the form ``A`` from hypotheses of the form ``B`` and ``C``, where ``A``, ``B``, and ``C`` approximate the way we might read the goals out loud. So a theorem establishing something like ``x + y ≤ ...`` will probably start with ``add_le``. Typing ``add_le`` and hitting tab will give you some helpful choices. * If you right-click on an existing theorem name in VS Code, the editor will show a menu with the option to jump to the file where the theorem is defined, and you can find similar theorems nearby. * You can use the ``library_search`` tactic, which tries to find the relevant theorem in the library. TEXT. -/ -- QUOTE: example : 0 ≤ a^2 := begin -- library_search, exact pow_two_nonneg a end -- QUOTE. /- TEXT: To try out ``library_search`` in this example, delete the ``exact`` command and uncomment the previous line. If you replace ``library_search`` with ``suggest``, you'll see a long list of suggestions. In this case, the suggestions are not helpful, but in other cases it does better. Using these tricks, see if you can find what you need to do the next example: TEXT. -/ -- QUOTE: example (h : a ≤ b) : c - exp b ≤ c - exp a := sorry -- QUOTE. -- SOLUTIONS: example (h : a ≤ b) : c - exp b ≤ c - exp a := begin apply sub_le_sub_left, exact exp_le_exp.mpr h end -- alternatively: example (h : a ≤ b) : c - exp b ≤ c - exp a := by linarith [exp_le_exp.mpr h] /- TEXT: Using the same tricks, confirm that ``linarith`` instead of ``library_search`` can also finish the job. Here is another example of an inequality: TEXT. -/ -- QUOTE: example : 2*a*b ≤ a^2 + b^2 := begin have h : 0 ≤ a^2 - 2*a*b + b^2, calc a^2 - 2*a*b + b^2 = (a - b)^2 : by ring ... ≥ 0 : by apply pow_two_nonneg, calc 2*a*b = 2*a*b + 0 : by ring ... ≤ 2*a*b + (a^2 - 2*a*b + b^2) : add_le_add (le_refl _) h ... = a^2 + b^2 : by ring end -- QUOTE. /- TEXT: Mathlib tends to put spaces around binary operations like ``*`` and ``^``, but in this example, the more compressed format increases readability. There are a number of things worth noticing. First, an expression ``s ≥ t`` is definitionally equivalent to ``t ≤ s``. In principle, this means one should be able to use them interchangeably. But some of Lean's automation does not recognize the equivalence, so mathlib tends to favor ``≤`` over ``≥``. Second, we have used the ``ring`` tactic extensively. It is a real timesaver! Finally, notice that in the second line of the second ``calc`` proof, instead of writing ``by exact add_le_add (le_refl _) h``, we can simply write the proof term ``add_le_add (le_refl _) h``. In fact, the only cleverness in the proof above is figuring out the hypothesis ``h``. Once we have it, the second calculation involves only linear arithmetic, and ``linarith`` can handle it: TEXT. -/ -- QUOTE: example : 2*a*b ≤ a^2 + b^2 := begin have h : 0 ≤ a^2 - 2*a*b + b^2, calc a^2 - 2*a*b + b^2 = (a - b)^2 : by ring ... ≥ 0 : by apply pow_two_nonneg, linarith end -- QUOTE. /- TEXT: How nice! We challenge you to use these ideas to prove the following theorem. You can use the theorem ``abs_le'.mpr``. TEXT. -/ -- QUOTE: example : abs (a*b) ≤ (a^2 + b^2) / 2 := sorry #check abs_le'.mpr -- QUOTE. -- SOLUTIONS: theorem fact1 : a*b*2 ≤ a^2 + b^2 := begin have h : 0 ≤ a^2 - 2*a*b + b^2, calc a^2 - 2*a*b + b^2 = (a - b)^2 : by ring ... ≥ 0 : by apply pow_two_nonneg, linarith end theorem fact2 : -(a*b)*2 ≤ a^2 + b^2 := begin have h : 0 ≤ a^2 + 2*a*b + b^2, calc a^2 + 2*a*b + b^2 = (a + b)^2 : by ring ... ≥ 0 : by apply pow_two_nonneg, linarith end example : abs (a*b) ≤ (a^2 + b^2) / 2 := begin have h : (0 : ℝ) < 2, { norm_num }, apply abs_le'.mpr, split, { rw le_div_iff h, apply fact1 }, rw le_div_iff h, apply fact2, end /- TEXT: If you managed to solve this, congratulations! You are well on your way to becoming a master formalizer. TEXT. -/
using Plots using PyCall using DifferentialEquations using Statistics using Base.Iterators function rossler(du,u,p,t) x, y, z = u a, b, c = p du[1] = -y -z du[2] = x + a*y du[3] = b + z*(x-c) end p = [0.1,0.1,18] u0 = [5., 5., 1.] tspan = (0.0,1000.0) prob = ODEProblem(rossler, u0, tspan, p) tmp = solve(prob, abstol=1e-9) prob = ODEProblem(rossler, tmp.u[end], (0.0,5000.0), p) sol = solve(prob, abstol=1e-9) pyplot() pygui(false) plot(sol,vars=(1,2,3), lw=0.1, legend=false) savefig("rossler_c13.pdf") function local_maxima(x::Vector{T}) where T<:Real y = [] for i in 2:length(x)-1 if x[i-1] < x[i] && x[i] > x[i+1] push!(y, x[i]) end end return y end z = map(v->v[3], sol.u) zmax = local_maxima(z) pygui(false) scatter( [zmax[i] for i in 1:(length(zmax)-1)], [zmax[i] for i in 2:length(zmax)], markersize=1, markerstrokealpha=0.0, markercolor = :black, legend=false, xlabel = "z[k]", ylabel = "z[k+1]" ) include("FractalDimensions.jl") d, N, ε = box_counting_dimension(sol.u, 8) loglog_regression(N,ε) plot(-log.(ε), log.(N), xlabel="-ln ε", ylabel="ln N", marker=:d, legend=false) C, r = correlation_dimension(sol.u, 15) loglog_regression(C,r) plot(log.(r), log.(C), xlabel="ln r", ylabel="ln C", marker=:d, legend=false) savefig("cordim_rossler.pdf") using DynamicalSystems using ChaosTools # almost feels like cheating r = Systems.roessler(a=0.1,b=0.1,c=18) lyapunov(r,1000.0) λ = lyapunovs(r,1000.0) kaplanyorke_dim(λ) # Lyapunov dimension crange = LinRange(1,18,1000) n = 5000 Ttr = 2000 # bifurcation diagram of the Poincaré map of the z coordinate on the plane y=0 diagram = produce_orbitdiagram(r, (2,0.0), 3, 3, crange; n=n, Ttr=Ttr) L = length(crange) x = [] y = [] for j in 1:L, z in diagram[j] push!(x,crange[j]) push!(y,z) end plotlyjs() scatter( x, y, markersize=0.5, markerstrokealpha=0.0, markercolor = :black, legend=false, grid = false, xlabel = "c", ylabel = "z" ) savefig("rossler_bifurcation.pdf")
#= # 301: 3D Laplace equation ([source code](SOURCE_URL)) =# module Example301_Laplace3D using VoronoiFVM,ExtendableGrids using GridVisualize ## Flux function which describes the flux ## between neigboring control volumes function g!(f,u,edge) f[1]=u[1,1]-u[1,2] end function s(f,node) n=view(node.coord,:,node.index) f[1]=n[1]*sin(5.0*n[2])*exp(n[3]) end function main(;Plotter=nothing,n=5) nspecies=1 ispec=1 X=collect(0:1/n:1) grid=VoronoiFVM.Grid(X,X,X) physics=VoronoiFVM.Physics(flux=g!,source=s) sys=VoronoiFVM.System(grid,physics) enable_species!(sys,ispec,[1]) boundary_dirichlet!(sys,ispec,5,0.0) boundary_dirichlet!(sys,ispec,6,0.0) inival=unknowns(sys,inival=0) solution=unknowns(sys) solve!(solution,inival,sys) scalarplot(grid,solution[1,:],Plotter=Plotter,zplane=0.5, flevel=0.5) return solution[43] end ## Called by unit test function test() main() ≈ 0.012234524449380824 end end
proposition locally_connected_quotient_image: assumes lcS: "locally connected S" and oo: "\<And>T. T \<subseteq> f ` S \<Longrightarrow> openin (top_of_set S) (S \<inter> f -` T) \<longleftrightarrow> openin (top_of_set (f ` S)) T" shows "locally connected (f ` S)"
State Before: α : Type ?u.304571 m n : PosNum h : ↑m = ↑n ⊢ pos m = pos n State After: no goals Tactic: rw [← PosNum.of_to_nat, ← PosNum.of_to_nat, h]
[GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R : ℝ z w : ℂ f : ℂ → E ⊢ Periodic (circleTransformDeriv R z w f) (2 * π) [PROOFSTEP] have := periodic_circleMap [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R : ℝ z w : ℂ f : ℂ → E this : ∀ (c : ℂ) (R : ℝ), Periodic (circleMap c R) (2 * π) ⊢ Periodic (circleTransformDeriv R z w f) (2 * π) [PROOFSTEP] simp_rw [Periodic] at * [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R : ℝ z w : ℂ f : ℂ → E this : ∀ (c : ℂ) (R x : ℝ), circleMap c R (x + 2 * π) = circleMap c R x ⊢ ∀ (x : ℝ), circleTransformDeriv R z w f (x + 2 * π) = circleTransformDeriv R z w f x [PROOFSTEP] intro x [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R : ℝ z w : ℂ f : ℂ → E this : ∀ (c : ℂ) (R x : ℝ), circleMap c R (x + 2 * π) = circleMap c R x x : ℝ ⊢ circleTransformDeriv R z w f (x + 2 * π) = circleTransformDeriv R z w f x [PROOFSTEP] simp_rw [circleTransformDeriv, this] [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R : ℝ z w : ℂ f : ℂ → E this : ∀ (c : ℂ) (R x : ℝ), circleMap c R (x + 2 * π) = circleMap c R x x : ℝ ⊢ (2 * ↑π * I)⁻¹ • deriv (circleMap z R) (x + 2 * π) • ((circleMap z R x - w) ^ 2)⁻¹ • f (circleMap z R x) = (2 * ↑π * I)⁻¹ • deriv (circleMap z R) x • ((circleMap z R x - w) ^ 2)⁻¹ • f (circleMap z R x) [PROOFSTEP] congr 2 [GOAL] case e_a.e_a E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R : ℝ z w : ℂ f : ℂ → E this : ∀ (c : ℂ) (R x : ℝ), circleMap c R (x + 2 * π) = circleMap c R x x : ℝ ⊢ deriv (circleMap z R) (x + 2 * π) = deriv (circleMap z R) x [PROOFSTEP] simp [this] [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R : ℝ z w : ℂ f : ℂ → E ⊢ circleTransformDeriv R z w f = fun θ => (circleMap z R θ - w)⁻¹ • circleTransform R z w f θ [PROOFSTEP] ext [GOAL] case h E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R : ℝ z w : ℂ f : ℂ → E x✝ : ℝ ⊢ circleTransformDeriv R z w f x✝ = (circleMap z R x✝ - w)⁻¹ • circleTransform R z w f x✝ [PROOFSTEP] simp_rw [circleTransformDeriv, circleTransform, ← mul_smul, ← mul_assoc] [GOAL] case h E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R : ℝ z w : ℂ f : ℂ → E x✝ : ℝ ⊢ ((2 * ↑π * I)⁻¹ * deriv (circleMap z R) x✝ * ((circleMap z R x✝ - w) ^ 2)⁻¹) • f (circleMap z R x✝) = ((circleMap z R x✝ - w)⁻¹ * (2 * ↑π * I)⁻¹ * deriv (circleMap z R) x✝ * (circleMap z R x✝ - w)⁻¹) • f (circleMap z R x✝) [PROOFSTEP] ring_nf [GOAL] case h E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R : ℝ z w : ℂ f : ℂ → E x✝ : ℝ ⊢ ((↑π)⁻¹ * I⁻¹ * deriv (circleMap z R) x✝ * (-(circleMap z R x✝ * w * 2) + circleMap z R x✝ ^ 2 + w ^ 2)⁻¹ * (↑(Int.ofNat 1) / ↑2)) • f (circleMap z R x✝) = ((↑π)⁻¹ * I⁻¹ * deriv (circleMap z R) x✝ * (circleMap z R x✝ - w)⁻¹ ^ 2 * (↑(Int.ofNat 1) / ↑2)) • f (circleMap z R x✝) [PROOFSTEP] rw [inv_pow] [GOAL] case h E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R : ℝ z w : ℂ f : ℂ → E x✝ : ℝ ⊢ ((↑π)⁻¹ * I⁻¹ * deriv (circleMap z R) x✝ * (-(circleMap z R x✝ * w * 2) + circleMap z R x✝ ^ 2 + w ^ 2)⁻¹ * (↑(Int.ofNat 1) / ↑2)) • f (circleMap z R x✝) = ((↑π)⁻¹ * I⁻¹ * deriv (circleMap z R) x✝ * ((circleMap z R x✝ - w) ^ 2)⁻¹ * (↑(Int.ofNat 1) / ↑2)) • f (circleMap z R x✝) [PROOFSTEP] congr [GOAL] case h.e_a.e_a.e_a.e_a E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R : ℝ z w : ℂ f : ℂ → E x✝ : ℝ ⊢ -(circleMap z R x✝ * w * 2) + circleMap z R x✝ ^ 2 + w ^ 2 = (circleMap z R x✝ - w) ^ 2 [PROOFSTEP] ring [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R : ℝ z w : ℂ f : ℂ → E ⊢ ∫ (θ : ℝ) in 0 ..2 * π, circleTransform R z w f θ = (2 * ↑π * I)⁻¹ • ∮ (z : ℂ) in C(z, R), (z - w)⁻¹ • f z [PROOFSTEP] simp_rw [circleTransform, circleIntegral, deriv_circleMap, circleMap] [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R : ℝ z w : ℂ f : ℂ → E ⊢ ∫ (θ : ℝ) in 0 ..2 * π, (2 * ↑π * I)⁻¹ • ((0 + ↑R * exp (↑θ * I)) * I) • (z + ↑R * exp (↑θ * I) - w)⁻¹ • f (z + ↑R * exp (↑θ * I)) = (2 * ↑π * I)⁻¹ • ∫ (θ : ℝ) in 0 ..2 * π, ((0 + ↑R * exp (↑θ * I)) * I) • (z + ↑R * exp (↑θ * I) - w)⁻¹ • f (z + ↑R * exp (↑θ * I)) [PROOFSTEP] simp [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w✝ : ℂ R : ℝ hR : 0 < R f : ℂ → E z w : ℂ hf : ContinuousOn f (sphere z R) hw : w ∈ ball z R ⊢ Continuous (circleTransform R z w f) [PROOFSTEP] apply_rules [Continuous.smul, continuous_const] [GOAL] case hg.hf E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w✝ : ℂ R : ℝ hR : 0 < R f : ℂ → E z w : ℂ hf : ContinuousOn f (sphere z R) hw : w ∈ ball z R ⊢ Continuous fun x => deriv (circleMap z R) x case hg.hg.hf E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w✝ : ℂ R : ℝ hR : 0 < R f : ℂ → E z w : ℂ hf : ContinuousOn f (sphere z R) hw : w ∈ ball z R ⊢ Continuous fun x => (circleMap z R x - w)⁻¹ case hg.hg.hg E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w✝ : ℂ R : ℝ hR : 0 < R f : ℂ → E z w : ℂ hf : ContinuousOn f (sphere z R) hw : w ∈ ball z R ⊢ Continuous fun x => f (circleMap z R x) [PROOFSTEP] simp_rw [deriv_circleMap] [GOAL] case hg.hf E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w✝ : ℂ R : ℝ hR : 0 < R f : ℂ → E z w : ℂ hf : ContinuousOn f (sphere z R) hw : w ∈ ball z R ⊢ Continuous fun x => circleMap 0 R x * I case hg.hg.hf E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w✝ : ℂ R : ℝ hR : 0 < R f : ℂ → E z w : ℂ hf : ContinuousOn f (sphere z R) hw : w ∈ ball z R ⊢ Continuous fun x => (circleMap z R x - w)⁻¹ case hg.hg.hg E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w✝ : ℂ R : ℝ hR : 0 < R f : ℂ → E z w : ℂ hf : ContinuousOn f (sphere z R) hw : w ∈ ball z R ⊢ Continuous fun x => f (circleMap z R x) [PROOFSTEP] apply_rules [Continuous.mul, continuous_circleMap 0 R, continuous_const] [GOAL] case hg.hg.hf E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w✝ : ℂ R : ℝ hR : 0 < R f : ℂ → E z w : ℂ hf : ContinuousOn f (sphere z R) hw : w ∈ ball z R ⊢ Continuous fun x => (circleMap z R x - w)⁻¹ [PROOFSTEP] apply continuous_circleMap_inv hw [GOAL] case hg.hg.hg E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w✝ : ℂ R : ℝ hR : 0 < R f : ℂ → E z w : ℂ hf : ContinuousOn f (sphere z R) hw : w ∈ ball z R ⊢ Continuous fun x => f (circleMap z R x) [PROOFSTEP] apply ContinuousOn.comp_continuous hf (continuous_circleMap z R) [GOAL] case hg.hg.hg E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w✝ : ℂ R : ℝ hR : 0 < R f : ℂ → E z w : ℂ hf : ContinuousOn f (sphere z R) hw : w ∈ ball z R ⊢ ∀ (x : ℝ), circleMap z R x ∈ sphere z R [PROOFSTEP] exact fun _ => (circleMap_mem_sphere _ hR.le) _ [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w✝ : ℂ R : ℝ hR : 0 < R f : ℂ → E z w : ℂ hf : ContinuousOn f (sphere z R) hw : w ∈ ball z R ⊢ Continuous (circleTransformDeriv R z w f) [PROOFSTEP] rw [circleTransformDeriv_eq] [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w✝ : ℂ R : ℝ hR : 0 < R f : ℂ → E z w : ℂ hf : ContinuousOn f (sphere z R) hw : w ∈ ball z R ⊢ Continuous fun θ => (circleMap z R θ - w)⁻¹ • circleTransform R z w f θ [PROOFSTEP] exact (continuous_circleMap_inv hw).smul (continuous_circleTransform hR hf hw) [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ ⊢ ContinuousOn (fun w => (circleMap z R w.snd - w.fst)⁻¹ ^ 2) (closedBall z r ×ˢ univ) [PROOFSTEP] simp_rw [← one_div] [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ ⊢ ContinuousOn (fun w => (1 / (circleMap z R w.snd - w.fst)) ^ 2) (closedBall z r ×ˢ univ) [PROOFSTEP] apply_rules [ContinuousOn.pow, ContinuousOn.div, continuousOn_const] [GOAL] case hf.hg E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ ⊢ ContinuousOn (fun x => circleMap z R x.snd - x.fst) (closedBall z r ×ˢ univ) case hf.h₀ E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ ⊢ ∀ (x : ℂ × ℝ), x ∈ closedBall z r ×ˢ univ → circleMap z R x.snd - x.fst ≠ 0 [PROOFSTEP] refine' ((continuous_circleMap z R).continuousOn.comp continuousOn_snd fun _ => And.right).sub (continuousOn_id.comp continuousOn_fst fun _ => And.left) [GOAL] case hf.h₀ E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ ⊢ ∀ (x : ℂ × ℝ), x ∈ closedBall z r ×ˢ univ → circleMap z R x.snd - x.fst ≠ 0 [PROOFSTEP] simp only [mem_prod, Ne.def, and_imp, Prod.forall] [GOAL] case hf.h₀ E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ ⊢ ∀ (a : ℂ) (b : ℝ), a ∈ closedBall z r → b ∈ univ → ¬circleMap z R b - a = 0 [PROOFSTEP] intro a b ha _ [GOAL] case hf.h₀ E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z a : ℂ b : ℝ ha : a ∈ closedBall z r a✝ : b ∈ univ ⊢ ¬circleMap z R b - a = 0 [PROOFSTEP] have ha2 : a ∈ ball z R := by simp at *; linarith [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z a : ℂ b : ℝ ha : a ∈ closedBall z r a✝ : b ∈ univ ⊢ a ∈ ball z R [PROOFSTEP] simp at * [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z a : ℂ b : ℝ ha : dist a z ≤ r a✝ : True ⊢ dist a z < R [PROOFSTEP] linarith [GOAL] case hf.h₀ E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z a : ℂ b : ℝ ha : a ∈ closedBall z r a✝ : b ∈ univ ha2 : a ∈ ball z R ⊢ ¬circleMap z R b - a = 0 [PROOFSTEP] exact sub_ne_zero.2 (circleMap_ne_mem_ball ha2 b) [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ ⊢ ContinuousOn (↑abs ∘ fun t => circleTransformBoundingFunction R z t) (closedBall z r ×ˢ univ) [PROOFSTEP] have : ContinuousOn (circleTransformBoundingFunction R z) (closedBall z r ×ˢ (⊤ : Set ℝ)) := by apply_rules [ContinuousOn.smul, continuousOn_const] simp only [deriv_circleMap] have c := (continuous_circleMap 0 R).continuousOn (s := ⊤) apply_rules [ContinuousOn.mul, c.comp continuousOn_snd fun _ => And.right, continuousOn_const] simp_rw [← inv_pow] apply continuousOn_prod_circle_transform_function hr [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ ⊢ ContinuousOn (circleTransformBoundingFunction R z) (closedBall z r ×ˢ ⊤) [PROOFSTEP] apply_rules [ContinuousOn.smul, continuousOn_const] [GOAL] case hg.hf E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ ⊢ ContinuousOn (fun x => deriv (circleMap z R) x.snd) (closedBall z r ×ˢ ⊤) case hg.hg.hf E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ ⊢ ContinuousOn (fun x => ((circleMap z R x.snd - x.fst) ^ 2)⁻¹) (closedBall z r ×ˢ ⊤) [PROOFSTEP] simp only [deriv_circleMap] [GOAL] case hg.hf E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ ⊢ ContinuousOn (fun x => circleMap 0 R x.snd * I) (closedBall z r ×ˢ ⊤) case hg.hg.hf E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ ⊢ ContinuousOn (fun x => ((circleMap z R x.snd - x.fst) ^ 2)⁻¹) (closedBall z r ×ˢ ⊤) [PROOFSTEP] have c := (continuous_circleMap 0 R).continuousOn (s := ⊤) [GOAL] case hg.hf E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ c : ContinuousOn (circleMap 0 R) ⊤ ⊢ ContinuousOn (fun x => circleMap 0 R x.snd * I) (closedBall z r ×ˢ ⊤) case hg.hg.hf E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ ⊢ ContinuousOn (fun x => ((circleMap z R x.snd - x.fst) ^ 2)⁻¹) (closedBall z r ×ˢ ⊤) [PROOFSTEP] apply_rules [ContinuousOn.mul, c.comp continuousOn_snd fun _ => And.right, continuousOn_const] [GOAL] case hg.hg.hf E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ ⊢ ContinuousOn (fun x => ((circleMap z R x.snd - x.fst) ^ 2)⁻¹) (closedBall z r ×ˢ ⊤) [PROOFSTEP] simp_rw [← inv_pow] [GOAL] case hg.hg.hf E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ ⊢ ContinuousOn (fun x => (circleMap z R x.snd - x.fst)⁻¹ ^ 2) (closedBall z r ×ˢ ⊤) [PROOFSTEP] apply continuousOn_prod_circle_transform_function hr [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ this : ContinuousOn (circleTransformBoundingFunction R z) (closedBall z r ×ˢ ⊤) ⊢ ContinuousOn (↑abs ∘ fun t => circleTransformBoundingFunction R z t) (closedBall z r ×ˢ univ) [PROOFSTEP] refine' continuous_abs.continuousOn (s := ⊤).comp this _ [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ this : ContinuousOn (circleTransformBoundingFunction R z) (closedBall z r ×ˢ ⊤) ⊢ MapsTo (fun t => circleTransformBoundingFunction R z t) (closedBall z r ×ˢ univ) ⊤ [PROOFSTEP] show MapsTo _ _ (⊤ : Set ℂ) [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R z : ℂ this : ContinuousOn (circleTransformBoundingFunction R z) (closedBall z r ×ˢ ⊤) ⊢ MapsTo (fun t => circleTransformBoundingFunction R z t) (closedBall z r ×ˢ univ) ⊤ [PROOFSTEP] simp [MapsTo] [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R hr' : 0 ≤ r z : ℂ ⊢ ∃ x, ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑x) [PROOFSTEP] have cts := continuousOn_abs_circleTransformBoundingFunction hr z [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R hr' : 0 ≤ r z : ℂ cts : ContinuousOn (↑abs ∘ fun t => circleTransformBoundingFunction R z t) (closedBall z r ×ˢ univ) ⊢ ∃ x, ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑x) [PROOFSTEP] have comp : IsCompact (closedBall z r ×ˢ [[0, 2 * π]]) := by apply_rules [IsCompact.prod, ProperSpace.isCompact_closedBall z r, isCompact_uIcc] [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R hr' : 0 ≤ r z : ℂ cts : ContinuousOn (↑abs ∘ fun t => circleTransformBoundingFunction R z t) (closedBall z r ×ˢ univ) ⊢ IsCompact (closedBall z r ×ˢ [[0, 2 * π]]) [PROOFSTEP] apply_rules [IsCompact.prod, ProperSpace.isCompact_closedBall z r, isCompact_uIcc] [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R hr' : 0 ≤ r z : ℂ cts : ContinuousOn (↑abs ∘ fun t => circleTransformBoundingFunction R z t) (closedBall z r ×ˢ univ) comp : IsCompact (closedBall z r ×ˢ [[0, 2 * π]]) ⊢ ∃ x, ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑x) [PROOFSTEP] have none : (closedBall z r ×ˢ [[0, 2 * π]]).Nonempty := (nonempty_closedBall.2 hr').prod nonempty_uIcc [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R hr' : 0 ≤ r z : ℂ cts : ContinuousOn (↑abs ∘ fun t => circleTransformBoundingFunction R z t) (closedBall z r ×ˢ univ) comp : IsCompact (closedBall z r ×ˢ [[0, 2 * π]]) none : Set.Nonempty (closedBall z r ×ˢ [[0, 2 * π]]) ⊢ ∃ x, ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑x) [PROOFSTEP] have := IsCompact.exists_isMaxOn comp none (cts.mono (by intro z; simp only [mem_prod, mem_closedBall, mem_univ, and_true_iff, and_imp]; tauto)) [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R hr' : 0 ≤ r z : ℂ cts : ContinuousOn (↑abs ∘ fun t => circleTransformBoundingFunction R z t) (closedBall z r ×ˢ univ) comp : IsCompact (closedBall z r ×ˢ [[0, 2 * π]]) none : Set.Nonempty (closedBall z r ×ˢ [[0, 2 * π]]) ⊢ closedBall z r ×ˢ [[0, 2 * π]] ⊆ closedBall z r ×ˢ univ [PROOFSTEP] intro z [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝¹ w : ℂ R r : ℝ hr : r < R hr' : 0 ≤ r z✝ : ℂ cts : ContinuousOn (↑abs ∘ fun t => circleTransformBoundingFunction R z✝ t) (closedBall z✝ r ×ˢ univ) comp : IsCompact (closedBall z✝ r ×ˢ [[0, 2 * π]]) none : Set.Nonempty (closedBall z✝ r ×ˢ [[0, 2 * π]]) z : ℂ × ℝ ⊢ z ∈ closedBall z✝ r ×ˢ [[0, 2 * π]] → z ∈ closedBall z✝ r ×ˢ univ [PROOFSTEP] simp only [mem_prod, mem_closedBall, mem_univ, and_true_iff, and_imp] [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝¹ w : ℂ R r : ℝ hr : r < R hr' : 0 ≤ r z✝ : ℂ cts : ContinuousOn (↑abs ∘ fun t => circleTransformBoundingFunction R z✝ t) (closedBall z✝ r ×ˢ univ) comp : IsCompact (closedBall z✝ r ×ˢ [[0, 2 * π]]) none : Set.Nonempty (closedBall z✝ r ×ˢ [[0, 2 * π]]) z : ℂ × ℝ ⊢ dist z.fst z✝ ≤ r → z.snd ∈ [[0, 2 * π]] → dist z.fst z✝ ≤ r [PROOFSTEP] tauto [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R hr' : 0 ≤ r z : ℂ cts : ContinuousOn (↑abs ∘ fun t => circleTransformBoundingFunction R z t) (closedBall z r ×ˢ univ) comp : IsCompact (closedBall z r ×ˢ [[0, 2 * π]]) none : Set.Nonempty (closedBall z r ×ˢ [[0, 2 * π]]) this : ∃ x, x ∈ closedBall z r ×ˢ [[0, 2 * π]] ∧ IsMaxOn (↑abs ∘ fun t => circleTransformBoundingFunction R z t) (closedBall z r ×ˢ [[0, 2 * π]]) x ⊢ ∃ x, ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑x) [PROOFSTEP] simp only [IsMaxOn, IsMaxFilter] at this [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R r : ℝ hr : r < R hr' : 0 ≤ r z : ℂ cts : ContinuousOn (↑abs ∘ fun t => circleTransformBoundingFunction R z t) (closedBall z r ×ˢ univ) comp : IsCompact (closedBall z r ×ˢ [[0, 2 * π]]) none : Set.Nonempty (closedBall z r ×ˢ [[0, 2 * π]]) this : ∃ x, x ∈ closedBall z r ×ˢ [[0, 2 * π]] ∧ ∀ᶠ (x_1 : ℂ × ℝ) in 𝓟 (closedBall z r ×ˢ [[0, 2 * π]]), (↑abs ∘ fun t => circleTransformBoundingFunction R z t) x_1 ≤ (↑abs ∘ fun t => circleTransformBoundingFunction R z t) x ⊢ ∃ x, ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑x) [PROOFSTEP] simpa [SetCoe.forall, Subtype.coe_mk, SetCoe.exists] [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) ⊢ ∃ B ε, 0 < ε ∧ ball x ε ⊆ ball z R ∧ ∀ (t : ℝ) (y : ℂ), y ∈ ball x ε → ‖circleTransformDeriv R z y f t‖ ≤ B [PROOFSTEP] obtain ⟨r, hr, hrx⟩ := exists_lt_mem_ball_of_mem_ball hx [GOAL] case intro.intro E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ⊢ ∃ B ε, 0 < ε ∧ ball x ε ⊆ ball z R ∧ ∀ (t : ℝ) (y : ℂ), y ∈ ball x ε → ‖circleTransformDeriv R z y f t‖ ≤ B [PROOFSTEP] obtain ⟨ε', hε', H⟩ := exists_ball_subset_ball hrx [GOAL] case intro.intro.intro.intro E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r ⊢ ∃ B ε, 0 < ε ∧ ball x ε ⊆ ball z R ∧ ∀ (t : ℝ) (y : ℂ), y ∈ ball x ε → ‖circleTransformDeriv R z y f t‖ ≤ B [PROOFSTEP] obtain ⟨⟨⟨a, b⟩, ⟨ha, hb⟩⟩, hab⟩ := abs_circleTransformBoundingFunction_le hr (pos_of_mem_ball hrx).le z [GOAL] case intro.intro.intro.intro.intro.mk.mk.intro E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) ⊢ ∃ B ε, 0 < ε ∧ ball x ε ⊆ ball z R ∧ ∀ (t : ℝ) (y : ℂ), y ∈ ball x ε → ‖circleTransformDeriv R z y f t‖ ≤ B [PROOFSTEP] let V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun _ => 1) θ [GOAL] case intro.intro.intro.intro.intro.mk.mk.intro E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ ⊢ ∃ B ε, 0 < ε ∧ ball x ε ⊆ ball z R ∧ ∀ (t : ℝ) (y : ℂ), y ∈ ball x ε → ‖circleTransformDeriv R z y f t‖ ≤ B [PROOFSTEP] have funccomp : ContinuousOn (fun r => abs (f r)) (sphere z R) := by have cabs : ContinuousOn abs ⊤ := by apply continuous_abs.continuousOn apply cabs.comp hf; rw [MapsTo]; tauto [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ ⊢ ContinuousOn (fun r => ↑abs (f r)) (sphere z R) [PROOFSTEP] have cabs : ContinuousOn abs ⊤ := by apply continuous_abs.continuousOn [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ ⊢ ContinuousOn ↑abs ⊤ [PROOFSTEP] apply continuous_abs.continuousOn [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ cabs : ContinuousOn ↑abs ⊤ ⊢ ContinuousOn (fun r => ↑abs (f r)) (sphere z R) [PROOFSTEP] apply cabs.comp hf [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ cabs : ContinuousOn ↑abs ⊤ ⊢ MapsTo f (sphere z R) ⊤ [PROOFSTEP] rw [MapsTo] [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ cabs : ContinuousOn ↑abs ⊤ ⊢ ∀ ⦃x : ℂ⦄, x ∈ sphere z R → f x ∈ ⊤ [PROOFSTEP] tauto [GOAL] case intro.intro.intro.intro.intro.mk.mk.intro E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ funccomp : ContinuousOn (fun r => ↑abs (f r)) (sphere z R) ⊢ ∃ B ε, 0 < ε ∧ ball x ε ⊆ ball z R ∧ ∀ (t : ℝ) (y : ℂ), y ∈ ball x ε → ‖circleTransformDeriv R z y f t‖ ≤ B [PROOFSTEP] have sbou := IsCompact.exists_isMaxOn (isCompact_sphere z R) (NormedSpace.sphere_nonempty.2 hR.le) funccomp [GOAL] case intro.intro.intro.intro.intro.mk.mk.intro E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ funccomp : ContinuousOn (fun r => ↑abs (f r)) (sphere z R) sbou : ∃ x, x ∈ sphere z R ∧ IsMaxOn (fun r => ↑abs (f r)) (sphere z R) x ⊢ ∃ B ε, 0 < ε ∧ ball x ε ⊆ ball z R ∧ ∀ (t : ℝ) (y : ℂ), y ∈ ball x ε → ‖circleTransformDeriv R z y f t‖ ≤ B [PROOFSTEP] obtain ⟨X, HX, HX2⟩ := sbou [GOAL] case intro.intro.intro.intro.intro.mk.mk.intro.intro.intro E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ funccomp : ContinuousOn (fun r => ↑abs (f r)) (sphere z R) X : ℂ HX : X ∈ sphere z R HX2 : IsMaxOn (fun r => ↑abs (f r)) (sphere z R) X ⊢ ∃ B ε, 0 < ε ∧ ball x ε ⊆ ball z R ∧ ∀ (t : ℝ) (y : ℂ), y ∈ ball x ε → ‖circleTransformDeriv R z y f t‖ ≤ B [PROOFSTEP] refine' ⟨abs (V b a) * abs (f X), ε', hε', Subset.trans H (ball_subset_ball hr.le), _⟩ [GOAL] case intro.intro.intro.intro.intro.mk.mk.intro.intro.intro E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ funccomp : ContinuousOn (fun r => ↑abs (f r)) (sphere z R) X : ℂ HX : X ∈ sphere z R HX2 : IsMaxOn (fun r => ↑abs (f r)) (sphere z R) X ⊢ ∀ (t : ℝ) (y : ℂ), y ∈ ball x ε' → ‖circleTransformDeriv R z y f t‖ ≤ ↑abs (V b a) * ↑abs (f X) [PROOFSTEP] intro y v hv [GOAL] case intro.intro.intro.intro.intro.mk.mk.intro.intro.intro E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ funccomp : ContinuousOn (fun r => ↑abs (f r)) (sphere z R) X : ℂ HX : X ∈ sphere z R HX2 : IsMaxOn (fun r => ↑abs (f r)) (sphere z R) X y : ℝ v : ℂ hv : v ∈ ball x ε' ⊢ ‖circleTransformDeriv R z v f y‖ ≤ ↑abs (V b a) * ↑abs (f X) [PROOFSTEP] obtain ⟨y1, hy1, hfun⟩ := Periodic.exists_mem_Ico₀ (circleTransformDeriv_periodic R z v f) Real.two_pi_pos y [GOAL] case intro.intro.intro.intro.intro.mk.mk.intro.intro.intro.intro.intro E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ funccomp : ContinuousOn (fun r => ↑abs (f r)) (sphere z R) X : ℂ HX : X ∈ sphere z R HX2 : IsMaxOn (fun r => ↑abs (f r)) (sphere z R) X y : ℝ v : ℂ hv : v ∈ ball x ε' y1 : ℝ hy1 : y1 ∈ Ico 0 (2 * π) hfun : circleTransformDeriv R z v f y = circleTransformDeriv R z v f y1 ⊢ ‖circleTransformDeriv R z v f y‖ ≤ ↑abs (V b a) * ↑abs (f X) [PROOFSTEP] have hy2 : y1 ∈ [[0, 2 * π]] := by convert Ico_subset_Icc_self hy1 using 1 simp [uIcc_of_le Real.two_pi_pos.le] [GOAL] E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ funccomp : ContinuousOn (fun r => ↑abs (f r)) (sphere z R) X : ℂ HX : X ∈ sphere z R HX2 : IsMaxOn (fun r => ↑abs (f r)) (sphere z R) X y : ℝ v : ℂ hv : v ∈ ball x ε' y1 : ℝ hy1 : y1 ∈ Ico 0 (2 * π) hfun : circleTransformDeriv R z v f y = circleTransformDeriv R z v f y1 ⊢ y1 ∈ [[0, 2 * π]] [PROOFSTEP] convert Ico_subset_Icc_self hy1 using 1 [GOAL] case h.e'_5 E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ funccomp : ContinuousOn (fun r => ↑abs (f r)) (sphere z R) X : ℂ HX : X ∈ sphere z R HX2 : IsMaxOn (fun r => ↑abs (f r)) (sphere z R) X y : ℝ v : ℂ hv : v ∈ ball x ε' y1 : ℝ hy1 : y1 ∈ Ico 0 (2 * π) hfun : circleTransformDeriv R z v f y = circleTransformDeriv R z v f y1 ⊢ [[0, 2 * π]] = Icc 0 (2 * π) [PROOFSTEP] simp [uIcc_of_le Real.two_pi_pos.le] [GOAL] case intro.intro.intro.intro.intro.mk.mk.intro.intro.intro.intro.intro E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ funccomp : ContinuousOn (fun r => ↑abs (f r)) (sphere z R) X : ℂ HX : X ∈ sphere z R HX2 : IsMaxOn (fun r => ↑abs (f r)) (sphere z R) X y : ℝ v : ℂ hv : v ∈ ball x ε' y1 : ℝ hy1 : y1 ∈ Ico 0 (2 * π) hfun : circleTransformDeriv R z v f y = circleTransformDeriv R z v f y1 hy2 : y1 ∈ [[0, 2 * π]] ⊢ ‖circleTransformDeriv R z v f y‖ ≤ ↑abs (V b a) * ↑abs (f X) [PROOFSTEP] simp only [IsMaxOn, IsMaxFilter, eventually_principal, mem_sphere_iff_norm, norm_eq_abs] at HX2 [GOAL] case intro.intro.intro.intro.intro.mk.mk.intro.intro.intro.intro.intro E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ funccomp : ContinuousOn (fun r => ↑abs (f r)) (sphere z R) X : ℂ HX : X ∈ sphere z R y : ℝ v : ℂ hv : v ∈ ball x ε' y1 : ℝ hy1 : y1 ∈ Ico 0 (2 * π) hfun : circleTransformDeriv R z v f y = circleTransformDeriv R z v f y1 hy2 : y1 ∈ [[0, 2 * π]] HX2 : ∀ (x : ℂ), ↑abs (x - z) = R → ↑abs (f x) ≤ ↑abs (f X) ⊢ ‖circleTransformDeriv R z v f y‖ ≤ ↑abs (V b a) * ↑abs (f X) [PROOFSTEP] have := mul_le_mul (hab ⟨⟨v, y1⟩, ⟨ball_subset_closedBall (H hv), hy2⟩⟩) (HX2 (circleMap z R y1) (circleMap_mem_sphere z hR.le y1)) (Complex.abs.nonneg _) (Complex.abs.nonneg _) [GOAL] case intro.intro.intro.intro.intro.mk.mk.intro.intro.intro.intro.intro E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ funccomp : ContinuousOn (fun r => ↑abs (f r)) (sphere z R) X : ℂ HX : X ∈ sphere z R y : ℝ v : ℂ hv : v ∈ ball x ε' y1 : ℝ hy1 : y1 ∈ Ico 0 (2 * π) hfun : circleTransformDeriv R z v f y = circleTransformDeriv R z v f y1 hy2 : y1 ∈ [[0, 2 * π]] HX2 : ∀ (x : ℂ), ↑abs (x - z) = R → ↑abs (f x) ≤ ↑abs (f X) this : ↑abs (circleTransformBoundingFunction R z ↑{ val := (v, y1), property := (_ : (v, y1).fst ∈ closedBall z r ∧ (v, y1).snd ∈ [[0, 2 * π]]) }) * ↑abs (f (circleMap z R y1)) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) * ↑abs (f X) ⊢ ‖circleTransformDeriv R z v f y‖ ≤ ↑abs (V b a) * ↑abs (f X) [PROOFSTEP] simp_rw [hfun] [GOAL] case intro.intro.intro.intro.intro.mk.mk.intro.intro.intro.intro.intro E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hx : x ∈ ball z R hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R hrx : x ∈ ball z r ε' : ℝ hε' : ε' > 0 H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] hab : ∀ (y : ↑(closedBall z r ×ˢ [[0, 2 * π]])), ↑abs (circleTransformBoundingFunction R z ↑y) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ funccomp : ContinuousOn (fun r => ↑abs (f r)) (sphere z R) X : ℂ HX : X ∈ sphere z R y : ℝ v : ℂ hv : v ∈ ball x ε' y1 : ℝ hy1 : y1 ∈ Ico 0 (2 * π) hfun : circleTransformDeriv R z v f y = circleTransformDeriv R z v f y1 hy2 : y1 ∈ [[0, 2 * π]] HX2 : ∀ (x : ℂ), ↑abs (x - z) = R → ↑abs (f x) ≤ ↑abs (f X) this : ↑abs (circleTransformBoundingFunction R z ↑{ val := (v, y1), property := (_ : (v, y1).fst ∈ closedBall z r ∧ (v, y1).snd ∈ [[0, 2 * π]]) }) * ↑abs (f (circleMap z R y1)) ≤ ↑abs (circleTransformBoundingFunction R z ↑{ val := (a, b), property := (_ : (a, b).fst ∈ closedBall z r ∧ (a, b).snd ∈ [[0, 2 * π]]) }) * ↑abs (f X) ⊢ ‖circleTransformDeriv R z v f y1‖ ≤ ↑abs (circleTransformDeriv R z a (fun x => 1) b) * ↑abs (f X) [PROOFSTEP] simp only [circleTransformBoundingFunction, circleTransformDeriv, norm_eq_abs, Algebra.id.smul_eq_mul, deriv_circleMap, map_mul, abs_circleMap_zero, abs_I, mul_one, ← mul_assoc, mul_inv_rev, inv_I, abs_neg, abs_inv, abs_ofReal, one_mul, abs_two, abs_pow, mem_ball, gt_iff_lt, Subtype.coe_mk, SetCoe.forall, mem_prod, mem_closedBall, and_imp, Prod.forall, NormedSpace.sphere_nonempty, mem_sphere_iff_norm] at * [GOAL] case intro.intro.intro.intro.intro.mk.mk.intro.intro.intro.intro.intro E : Type u_1 inst✝¹ : NormedAddCommGroup E inst✝ : NormedSpace ℂ E R✝ : ℝ z✝ w : ℂ R : ℝ hR : 0 < R z x : ℂ f : ℂ → ℂ hf : ContinuousOn f (sphere z R) r : ℝ hr : r < R ε' : ℝ H : ball x ε' ⊆ ball z r a : ℂ b : ℝ ha : (a, b).fst ∈ closedBall z r hb : (a, b).snd ∈ [[0, 2 * π]] V : ℝ → ℂ → ℂ := fun θ w => circleTransformDeriv R z w (fun x => 1) θ funccomp : ContinuousOn (fun r => ↑abs (f r)) (sphere z R) X : ℂ y : ℝ v : ℂ hv : v ∈ ball x ε' y1 : ℝ hy1 : y1 ∈ Ico 0 (2 * π) hy2 : y1 ∈ [[0, 2 * π]] HX2 : ∀ (x : ℂ), ↑abs (x - z) = R → ↑abs (f x) ≤ ↑abs (f X) hx : dist x z < R hrx : dist x z < r hε' : 0 < ε' hab : ∀ (a_1 : ℂ) (b_1 : ℝ), dist a_1 z ≤ r → b_1 ∈ [[0, 2 * π]] → ↑abs (-I) * ↑abs (↑π)⁻¹ * ↑abs 2⁻¹ * |R| * ↑abs ((circleMap z R b_1 - a_1) ^ 2)⁻¹ ≤ ↑abs (-I) * ↑abs (↑π)⁻¹ * ↑abs 2⁻¹ * |R| * ↑abs ((circleMap z R b - a) ^ 2)⁻¹ HX : ↑abs (X - z) = R hfun : -I * (↑π)⁻¹ * 2⁻¹ * circleMap 0 R y * I * ((circleMap z R y - v) ^ 2)⁻¹ * f (circleMap z R y) = -I * (↑π)⁻¹ * 2⁻¹ * circleMap 0 R y1 * I * ((circleMap z R y1 - v) ^ 2)⁻¹ * f (circleMap z R y1) this : ↑abs (-I) * ↑abs (↑π)⁻¹ * ↑abs 2⁻¹ * |R| * ↑abs ((circleMap z R y1 - v) ^ 2)⁻¹ * ↑abs (f (circleMap z R y1)) ≤ ↑abs (-I) * ↑abs (↑π)⁻¹ * ↑abs 2⁻¹ * |R| * ↑abs ((circleMap z R b - a) ^ 2)⁻¹ * ↑abs (f X) ⊢ ↑abs (-I) * ↑abs (↑π)⁻¹ * ↑abs 2⁻¹ * |R| * ↑abs ((circleMap z R y1 - v) ^ 2)⁻¹ * ↑abs (f (circleMap z R y1)) ≤ ↑abs (-I) * ↑abs (↑π)⁻¹ * ↑abs 2⁻¹ * |R| * ↑abs ((circleMap z R b - a) ^ 2)⁻¹ * ↑abs (f X) [PROOFSTEP] exact this
# For today's code challenge you will be reviewing yesterdays lecture material. Have fun! ### if you get done early check out [these videos](https://www.3blue1brown.com/neural-networks). # The Perceptron The first and simplest kind of neural network that we could talk about is the perceptron. A perceptron is just a single node or neuron of a neural network with nothing else. It can take any number of inputs and spit out an output. What a neuron does is it takes each of the input values, multplies each of them by a weight, sums all of these products up, and then passes the sum through what is called an "activation function" the result of which is the final value. I really like figure 2.1 found in this [pdf](http://www.uta.fi/sis/tie/neuro/index/Neurocomputing2.pdf) even though it doesn't have bias term represented there. If we were to write what is happening in some verbose mathematical notation, it might look something like this: \begin{align} y = sigmoid(\sum(weight_{1}input_{1} + weight_{2}input_{2} + weight_{3}input_{3}) + bias) \end{align} Understanding what happens with a single neuron is important because this is the same pattern that will take place for all of our networks. When imagining a neural network I like to think about the arrows as representing the weights, like a wire that has a certain amount of resistance and only lets a certain amount of current through. And I like to think about the node itselef as containing the prescribed activation function that neuron will use to decide how much signal to pass onto the next layer. # Activation Functions (transfer functions) In Neural Networks, each node has an activation function. Each node in a given layer typically has the same activation function. These activation functions are the biggest piece of neural networks that have been inspired by actual biology. The activation function decides whether a cell "fires" or not. Sometimes it is said that the cell is "activated" or not. In Artificial Neural Networks activation functions decide how much signal to pass onto the next layer. This is why they are sometimes referred to as transfer functions because they determine how much signal is transferred to the next layer. ## Common Activation Functions: # Implementing a Perceptron from scratch in Python ### Establish training data ```python import numpy as np np.random.seed(812) inputs = np.array([ [0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1] ]) correct_outputs = [[0], [1], [1], [0]] ``` ### Sigmoid activation function and its derivative for updating weights ```python def sigmoid(x): return 1 / (1 + np.exp(-x)) def sigmoid_derivative(x): sx = sigmoid(x) return sx * (1 - sx) ``` ## Updating weights with derivative of sigmoid function: ### Initialize random weights for our three inputs ```python weights = np.random.rand(3,1) weights ``` array([[0.32659171], [0.59345002], [0.25569456]]) ### Calculate weighted sum of inputs and weights ```python weighted_sum = np.dot(inputs,weights) ``` ### Output the activated value for the end of 1 training epoch ```python activated_value = sigmoid(weighted_sum) activated_value ``` array([[0.56357763], [0.76418031], [0.64159331], [0.70038767]]) ### take difference of output and true values to calculate error ```python error = correct_outputs - activated_value error ``` array([[-0.56357763], [ 0.23581969], [ 0.35840669], [-0.70038767]]) ```python derivative = sigmoid_derivative(error) derivative ``` array([[0.23115422], [0.24655628], [0.24214035], [0.22168396]]) ### Put it all together ```python weights += np.dot(inputs,derivative) ``` ```python ```
[STATEMENT] lemma \<Delta>_positive: "\<Delta> > 0" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (0::'a) < \<Delta> [PROOF STEP] unfolding \<Delta>_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. (0::'a) < min (excess f u) (cf (u, v)) [PROOF STEP] using excess_u_pos uv_cf_edge[unfolded cf.E_def] resE_positive [PROOF STATE] proof (prove) using this: (0::'a) < excess f u (u, v) \<in> {(u, v). cf (u, v) \<noteq> (0::'a)} ?e \<in> cf.E \<Longrightarrow> (0::'a) < cf ?e goal (1 subgoal): 1. (0::'a) < min (excess f u) (cf (u, v)) [PROOF STEP] by auto
module Main import Control.App import Control.App.Console import Decidable.Equality import Test.Unit.Spec import Data.Strings import Data.String.Missing partial main : IO () main = run $ consoleRunSpecSimple $ do describe "Data.String.Missing" $ do describe "strIndexV" $ do tests "basic" $ do let str0 = "0123456789" let len0 = length str0 assertEqual '0' $ strIndexV{pr0=believe_me (Refl{x=True})} 0 str0 assertEqual '1' $ strIndexV{pr0=believe_me (Refl{x=True})} 1 str0 assertEqual '9' $ strIndexV{pr0=believe_me (Refl{x=True})} 9 str0 describe "strSplit" $ do tests "basic" $ do let str0 = "0123456789" assertEqual ("012", "3456789") $ strSplit 3 str0 assertEqual ("", "0123456789") $ strSplit 0 str0 assertEqual ("0123456789", "") $ strSplit 10 str0 assertEqual ("0123456789", "") $ strSplit 20 str0 describe "strFindV" $ do tests "basic" $ do let str0 = "01234567890123456789" assertEqual (Just 0) $ map fst $ strFindrV (== '0') str0 assertEqual (Just 2) $ map fst $ strFindrV (== '2') str0 assertEqual (Just 9) $ map fst $ strFindrV (== '9') str0 assertEqual Nothing $ map fst $ strFindrV (== 'A') str0 describe "strFindrV" $ do tests "basic" $ do let str0 = "01234567890123456789" assertEqual (Just 10) $ map fst $ strFindrV (== '0') str0 assertEqual (Just 12) $ map fst $ strFindrV (== '2') str0 assertEqual (Just 19) $ map fst $ strFindrV (== '9') str0 assertEqual Nothing $ map fst $ strFindrV (== 'A') str0 describe "isPrefixOf" $ do tests "basic" $ do assertTrue $ isPrefixOf "123" "123456" assertTrue $ isPrefixOf "abcde" "abcde" assertFalse $ isPrefixOf "123" "12456" assertFalse $ isPrefixOf "abcde" ""
(* Author: Norbert Schirmer Maintainer: Norbert Schirmer, norbert.schirmer at web de License: LGPL *) (* Title: Semantic.thy Author: Norbert Schirmer, TU Muenchen Copyright (C) 2004-2008 Norbert Schirmer Some rights reserved, TU Muenchen This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) section \<open>Big-Step Semantics for Simpl\<close> theory Semantic imports Language begin notation restrict_map ("_|\<^bsub>_\<^esub>" [90, 91] 90) datatype ('s,'f) xstate = Normal 's | Abrupt 's | Fault 'f | Stuck definition isAbr::"('s,'f) xstate \<Rightarrow> bool" where "isAbr S = (\<exists>s. S=Abrupt s)" lemma isAbr_simps [simp]: "isAbr (Normal s) = False" "isAbr (Abrupt s) = True" "isAbr (Fault f) = False" "isAbr Stuck = False" by (auto simp add: isAbr_def) lemma isAbrE [consumes 1, elim?]: "\<lbrakk>isAbr S; \<And>s. S=Abrupt s \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P" by (auto simp add: isAbr_def) lemma not_isAbrD: "\<not> isAbr s \<Longrightarrow> (\<exists>s'. s=Normal s') \<or> s = Stuck \<or> (\<exists>f. s=Fault f)" by (cases s) auto definition isFault:: "('s,'f) xstate \<Rightarrow> bool" where "isFault S = (\<exists>f. S=Fault f)" lemma isFault_simps [simp]: "isFault (Normal s) = False" "isFault (Abrupt s) = False" "isFault (Fault f) = True" "isFault Stuck = False" by (auto simp add: isFault_def) lemma isFaultE [consumes 1, elim?]: "\<lbrakk>isFault s; \<And>f. s=Fault f \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P" by (auto simp add: isFault_def) lemma not_isFault_iff: "(\<not> isFault t) = (\<forall>f. t \<noteq> Fault f)" by (auto elim: isFaultE) (* ************************************************************************* *) subsection \<open>Big-Step Execution: \<open>\<Gamma>\<turnstile>\<langle>c, s\<rangle> \<Rightarrow> t\<close>\<close> (* ************************************************************************* *) text \<open>The procedure environment\<close> type_synonym ('s,'p,'f) body = "'p \<Rightarrow> ('s,'p,'f) com option" inductive "exec"::"[('s,'p,'f) body,('s,'p,'f) com,('s,'f) xstate,('s,'f) xstate] \<Rightarrow> bool" ("_\<turnstile> \<langle>_,_\<rangle> \<Rightarrow> _" [60,20,98,98] 89) for \<Gamma>::"('s,'p,'f) body" where Skip: "\<Gamma>\<turnstile>\<langle>Skip,Normal s\<rangle> \<Rightarrow> Normal s" | Guard: "\<lbrakk>s\<in>g; \<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Guard f g c,Normal s\<rangle> \<Rightarrow> t" | GuardFault: "s\<notin>g \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Guard f g c,Normal s\<rangle> \<Rightarrow> Fault f" | FaultProp [intro,simp]: "\<Gamma>\<turnstile>\<langle>c,Fault f\<rangle> \<Rightarrow> Fault f" | Basic: "\<Gamma>\<turnstile>\<langle>Basic f,Normal s\<rangle> \<Rightarrow> Normal (f s)" | Spec: "(s,t) \<in> r \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Spec r,Normal s\<rangle> \<Rightarrow> Normal t" | SpecStuck: "\<forall>t. (s,t) \<notin> r \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Spec r,Normal s\<rangle> \<Rightarrow> Stuck" | Seq: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal s\<rangle> \<Rightarrow> s'; \<Gamma>\<turnstile>\<langle>c\<^sub>2,s'\<rangle> \<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Seq c\<^sub>1 c\<^sub>2,Normal s\<rangle> \<Rightarrow> t" | CondTrue: "\<lbrakk>s \<in> b; \<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal s\<rangle> \<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Cond b c\<^sub>1 c\<^sub>2,Normal s\<rangle> \<Rightarrow> t" | CondFalse: "\<lbrakk>s \<notin> b; \<Gamma>\<turnstile>\<langle>c\<^sub>2,Normal s\<rangle> \<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Cond b c\<^sub>1 c\<^sub>2,Normal s\<rangle> \<Rightarrow> t" | WhileTrue: "\<lbrakk>s \<in> b; \<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow> s'; \<Gamma>\<turnstile>\<langle>While b c,s'\<rangle> \<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>While b c,Normal s\<rangle> \<Rightarrow> t" | WhileFalse: "\<lbrakk>s \<notin> b\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>While b c,Normal s\<rangle> \<Rightarrow> Normal s" | Call: "\<lbrakk>\<Gamma> p=Some bdy;\<Gamma>\<turnstile>\<langle>bdy,Normal s\<rangle> \<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow> t" | CallUndefined: "\<lbrakk>\<Gamma> p=None\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow> Stuck" | StuckProp [intro,simp]: "\<Gamma>\<turnstile>\<langle>c,Stuck\<rangle> \<Rightarrow> Stuck" | DynCom: "\<lbrakk>\<Gamma>\<turnstile>\<langle>(c s),Normal s\<rangle> \<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>DynCom c,Normal s\<rangle> \<Rightarrow> t" | Throw: "\<Gamma>\<turnstile>\<langle>Throw,Normal s\<rangle> \<Rightarrow> Abrupt s" | AbruptProp [intro,simp]: "\<Gamma>\<turnstile>\<langle>c,Abrupt s\<rangle> \<Rightarrow> Abrupt s" | CatchMatch: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal s\<rangle> \<Rightarrow> Abrupt s'; \<Gamma>\<turnstile>\<langle>c\<^sub>2,Normal s'\<rangle> \<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal s\<rangle> \<Rightarrow> t" | CatchMiss: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal s\<rangle> \<Rightarrow> t; \<not>isAbr t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal s\<rangle> \<Rightarrow> t" inductive_cases exec_elim_cases [cases set]: "\<Gamma>\<turnstile>\<langle>c,Fault f\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>c,Stuck\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>c,Abrupt s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Skip,s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Seq c1 c2,s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Guard f g c,s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Basic f,s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Spec r,s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Cond b c1 c2,s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>While b c,s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Call p,s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>DynCom c,s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Throw,s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Catch c1 c2,s\<rangle> \<Rightarrow> t" inductive_cases exec_Normal_elim_cases [cases set]: "\<Gamma>\<turnstile>\<langle>c,Fault f\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>c,Stuck\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>c,Abrupt s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Skip,Normal s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Guard f g c,Normal s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Basic f,Normal s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Spec r,Normal s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Seq c1 c2,Normal s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Cond b c1 c2,Normal s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>While b c,Normal s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>DynCom c,Normal s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Throw,Normal s\<rangle> \<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow> t" lemma exec_block: "\<lbrakk>\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> \<Rightarrow> Normal t; \<Gamma>\<turnstile>\<langle>c s t,Normal (return s t)\<rangle> \<Rightarrow> u\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>block init bdy return c,Normal s\<rangle> \<Rightarrow> u" apply (unfold block_def) by (fastforce intro: exec.intros) lemma exec_blockAbrupt: "\<lbrakk>\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> \<Rightarrow> Abrupt t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>block init bdy return c,Normal s\<rangle> \<Rightarrow> Abrupt (return s t)" apply (unfold block_def) by (fastforce intro: exec.intros) lemma exec_blockFault: "\<lbrakk>\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> \<Rightarrow> Fault f\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>block init bdy return c,Normal s\<rangle> \<Rightarrow> Fault f" apply (unfold block_def) by (fastforce intro: exec.intros) lemma exec_blockStuck: "\<lbrakk>\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> \<Rightarrow> Stuck\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>block init bdy return c,Normal s\<rangle> \<Rightarrow> Stuck" apply (unfold block_def) by (fastforce intro: exec.intros) lemma exec_call: "\<lbrakk>\<Gamma> p=Some bdy;\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> \<Rightarrow> Normal t; \<Gamma>\<turnstile>\<langle>c s t,Normal (return s t)\<rangle> \<Rightarrow> u\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>call init p return c,Normal s\<rangle> \<Rightarrow> u" apply (simp add: call_def) apply (rule exec_block) apply (erule (1) Call) apply assumption done lemma exec_callAbrupt: "\<lbrakk>\<Gamma> p=Some bdy;\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> \<Rightarrow> Abrupt t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>call init p return c,Normal s\<rangle> \<Rightarrow> Abrupt (return s t)" apply (simp add: call_def) apply (rule exec_blockAbrupt) apply (erule (1) Call) done lemma exec_callFault: "\<lbrakk>\<Gamma> p=Some bdy; \<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> \<Rightarrow> Fault f\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>call init p return c,Normal s\<rangle> \<Rightarrow> Fault f" apply (simp add: call_def) apply (rule exec_blockFault) apply (erule (1) Call) done lemma exec_callStuck: "\<lbrakk>\<Gamma> p=Some bdy; \<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> \<Rightarrow> Stuck\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>call init p return c,Normal s\<rangle> \<Rightarrow> Stuck" apply (simp add: call_def) apply (rule exec_blockStuck) apply (erule (1) Call) done lemma exec_callUndefined: "\<lbrakk>\<Gamma> p=None\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>call init p return c,Normal s\<rangle> \<Rightarrow> Stuck" apply (simp add: call_def) apply (rule exec_blockStuck) apply (erule CallUndefined) done lemma Fault_end: assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" and s: "s=Fault f" shows "t=Fault f" using exec s by (induct) auto lemma Stuck_end: assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" and s: "s=Stuck" shows "t=Stuck" using exec s by (induct) auto lemma Abrupt_end: assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" and s: "s=Abrupt s'" shows "t=Abrupt s'" using exec s by (induct) auto lemma exec_Call_body_aux: "\<Gamma> p=Some bdy \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Call p,s\<rangle> \<Rightarrow> t = \<Gamma>\<turnstile>\<langle>bdy,s\<rangle> \<Rightarrow> t" apply (rule) apply (fastforce elim: exec_elim_cases ) apply (cases s) apply (cases t) apply (auto intro: exec.intros dest: Fault_end Stuck_end Abrupt_end) done lemma exec_Call_body': "p \<in> dom \<Gamma> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Call p,s\<rangle> \<Rightarrow> t = \<Gamma>\<turnstile>\<langle>the (\<Gamma> p),s\<rangle> \<Rightarrow> t" apply clarsimp by (rule exec_Call_body_aux) lemma exec_block_Normal_elim [consumes 1]: assumes exec_block: "\<Gamma>\<turnstile>\<langle>block init bdy return c,Normal s\<rangle> \<Rightarrow> t" assumes Normal: "\<And>t'. \<lbrakk>\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> \<Rightarrow> Normal t'; \<Gamma>\<turnstile>\<langle>c s t',Normal (return s t')\<rangle> \<Rightarrow> t\<rbrakk> \<Longrightarrow> P" assumes Abrupt: "\<And>t'. \<lbrakk>\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> \<Rightarrow> Abrupt t'; t = Abrupt (return s t')\<rbrakk> \<Longrightarrow> P" assumes Fault: "\<And>f. \<lbrakk>\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> \<Rightarrow> Fault f; t = Fault f\<rbrakk> \<Longrightarrow> P" assumes Stuck: "\<lbrakk>\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> \<Rightarrow> Stuck; t = Stuck\<rbrakk> \<Longrightarrow> P" assumes "\<lbrakk>\<Gamma> p = None; t = Stuck\<rbrakk> \<Longrightarrow> P" shows "P" using exec_block apply (unfold block_def) apply (elim exec_Normal_elim_cases) apply simp_all apply (case_tac s') apply simp_all apply (elim exec_Normal_elim_cases) apply simp apply (drule Abrupt_end) apply simp apply (erule exec_Normal_elim_cases) apply simp apply (rule Abrupt,assumption+) apply (drule Fault_end) apply simp apply (erule exec_Normal_elim_cases) apply simp apply (drule Stuck_end) apply simp apply (erule exec_Normal_elim_cases) apply simp apply (case_tac s') apply simp_all apply (elim exec_Normal_elim_cases) apply simp apply (rule Normal, assumption+) apply (drule Fault_end) apply simp apply (rule Fault,assumption+) apply (drule Stuck_end) apply simp apply (rule Stuck,assumption+) done lemma exec_call_Normal_elim [consumes 1]: assumes exec_call: "\<Gamma>\<turnstile>\<langle>call init p return c,Normal s\<rangle> \<Rightarrow> t" assumes Normal: "\<And>bdy t'. \<lbrakk>\<Gamma> p = Some bdy; \<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> \<Rightarrow> Normal t'; \<Gamma>\<turnstile>\<langle>c s t',Normal (return s t')\<rangle> \<Rightarrow> t\<rbrakk> \<Longrightarrow> P" assumes Abrupt: "\<And>bdy t'. \<lbrakk>\<Gamma> p = Some bdy; \<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> \<Rightarrow> Abrupt t'; t = Abrupt (return s t')\<rbrakk> \<Longrightarrow> P" assumes Fault: "\<And>bdy f. \<lbrakk>\<Gamma> p = Some bdy; \<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> \<Rightarrow> Fault f; t = Fault f\<rbrakk> \<Longrightarrow> P" assumes Stuck: "\<And>bdy. \<lbrakk>\<Gamma> p = Some bdy; \<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> \<Rightarrow> Stuck; t = Stuck\<rbrakk> \<Longrightarrow> P" assumes Undef: "\<lbrakk>\<Gamma> p = None; t = Stuck\<rbrakk> \<Longrightarrow> P" shows "P" using exec_call apply (unfold call_def) apply (cases "\<Gamma> p") apply (erule exec_block_Normal_elim) apply (elim exec_Normal_elim_cases) apply simp apply simp apply (elim exec_Normal_elim_cases) apply simp apply simp apply (elim exec_Normal_elim_cases) apply simp apply simp apply (elim exec_Normal_elim_cases) apply simp apply (rule Undef,assumption,assumption) apply (rule Undef,assumption+) apply (erule exec_block_Normal_elim) apply (elim exec_Normal_elim_cases) apply simp apply (rule Normal,assumption+) apply simp apply (elim exec_Normal_elim_cases) apply simp apply (rule Abrupt,assumption+) apply simp apply (elim exec_Normal_elim_cases) apply simp apply (rule Fault, assumption+) apply simp apply (elim exec_Normal_elim_cases) apply simp apply (rule Stuck,assumption,assumption,assumption) apply simp apply (rule Undef,assumption+) done lemma exec_dynCall: "\<lbrakk>\<Gamma>\<turnstile>\<langle>call init (p s) return c,Normal s\<rangle> \<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>dynCall init p return c,Normal s\<rangle> \<Rightarrow> t" apply (simp add: dynCall_def) by (rule DynCom) lemma exec_dynCall_Normal_elim: assumes exec: "\<Gamma>\<turnstile>\<langle>dynCall init p return c,Normal s\<rangle> \<Rightarrow> t" assumes call: "\<Gamma>\<turnstile>\<langle>call init (p s) return c,Normal s\<rangle> \<Rightarrow> t \<Longrightarrow> P" shows "P" using exec apply (simp add: dynCall_def) apply (erule exec_Normal_elim_cases) apply (rule call,assumption) done lemma exec_Seq': "\<lbrakk>\<Gamma>\<turnstile>\<langle>c1,s\<rangle> \<Rightarrow> s'; \<Gamma>\<turnstile>\<langle>c2,s'\<rangle> \<Rightarrow> s''\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Seq c1 c2,s\<rangle> \<Rightarrow> s''" apply (cases s) apply (fastforce intro: exec.intros) apply (fastforce dest: Abrupt_end) apply (fastforce dest: Fault_end) apply (fastforce dest: Stuck_end) done lemma exec_assoc: "\<Gamma>\<turnstile>\<langle>Seq c1 (Seq c2 c3),s\<rangle> \<Rightarrow> t = \<Gamma>\<turnstile>\<langle>Seq (Seq c1 c2) c3,s\<rangle> \<Rightarrow> t" by (blast elim!: exec_elim_cases intro: exec_Seq' ) (* ************************************************************************* *) subsection \<open>Big-Step Execution with Recursion Limit: \<open>\<Gamma>\<turnstile>\<langle>c, s\<rangle> =n\<Rightarrow> t\<close>\<close> (* ************************************************************************* *) inductive "execn"::"[('s,'p,'f) body,('s,'p,'f) com,('s,'f) xstate,nat,('s,'f) xstate] \<Rightarrow> bool" ("_\<turnstile> \<langle>_,_\<rangle> =_\<Rightarrow> _" [60,20,98,65,98] 89) for \<Gamma>::"('s,'p,'f) body" where Skip: "\<Gamma>\<turnstile>\<langle>Skip,Normal s\<rangle> =n\<Rightarrow> Normal s" | Guard: "\<lbrakk>s\<in>g; \<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t" | GuardFault: "s\<notin>g \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> Fault f" | FaultProp [intro,simp]: "\<Gamma>\<turnstile>\<langle>c,Fault f\<rangle> =n\<Rightarrow> Fault f" | Basic: "\<Gamma>\<turnstile>\<langle>Basic f,Normal s\<rangle> =n\<Rightarrow> Normal (f s)" | Spec: "(s,t) \<in> r \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Spec r,Normal s\<rangle> =n\<Rightarrow> Normal t" | SpecStuck: "\<forall>t. (s,t) \<notin> r \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Spec r,Normal s\<rangle> =n\<Rightarrow> Stuck" | Seq: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> s'; \<Gamma>\<turnstile>\<langle>c\<^sub>2,s'\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Seq c\<^sub>1 c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t" | CondTrue: "\<lbrakk>s \<in> b; \<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Cond b c\<^sub>1 c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t" | CondFalse: "\<lbrakk>s \<notin> b; \<Gamma>\<turnstile>\<langle>c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Cond b c\<^sub>1 c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t" | WhileTrue: "\<lbrakk>s \<in> b; \<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> s'; \<Gamma>\<turnstile>\<langle>While b c,s'\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>While b c,Normal s\<rangle> =n\<Rightarrow> t" | WhileFalse: "\<lbrakk>s \<notin> b\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>While b c,Normal s\<rangle> =n\<Rightarrow> Normal s" | Call: "\<lbrakk>\<Gamma> p=Some bdy;\<Gamma>\<turnstile>\<langle>bdy,Normal s\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Call p ,Normal s\<rangle> =Suc n\<Rightarrow> t" | CallUndefined: "\<lbrakk>\<Gamma> p=None\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Call p ,Normal s\<rangle> =Suc n\<Rightarrow> Stuck" | StuckProp [intro,simp]: "\<Gamma>\<turnstile>\<langle>c,Stuck\<rangle> =n\<Rightarrow> Stuck" | DynCom: "\<lbrakk>\<Gamma>\<turnstile>\<langle>(c s),Normal s\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>DynCom c,Normal s\<rangle> =n\<Rightarrow> t" | Throw: "\<Gamma>\<turnstile>\<langle>Throw,Normal s\<rangle> =n\<Rightarrow> Abrupt s" | AbruptProp [intro,simp]: "\<Gamma>\<turnstile>\<langle>c,Abrupt s\<rangle> =n\<Rightarrow> Abrupt s" | CatchMatch: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> Abrupt s'; \<Gamma>\<turnstile>\<langle>c\<^sub>2,Normal s'\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t" | CatchMiss: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<not>isAbr t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t" inductive_cases execn_elim_cases [cases set]: "\<Gamma>\<turnstile>\<langle>c,Fault f\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>c,Stuck\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>c,Abrupt s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Skip,s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Seq c1 c2,s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Guard f g c,s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Basic f,s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Spec r,s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Cond b c1 c2,s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>While b c,s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Call p ,s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>DynCom c,s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Throw,s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Catch c1 c2,s\<rangle> =n\<Rightarrow> t" inductive_cases execn_Normal_elim_cases [cases set]: "\<Gamma>\<turnstile>\<langle>c,Fault f\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>c,Stuck\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>c,Abrupt s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Skip,Normal s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Basic f,Normal s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Spec r,Normal s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Seq c1 c2,Normal s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Cond b c1 c2,Normal s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>While b c,Normal s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>DynCom c,Normal s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Throw,Normal s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> =n\<Rightarrow> t" lemma execn_Skip': "\<Gamma>\<turnstile>\<langle>Skip,t\<rangle> =n\<Rightarrow> t" by (cases t) (auto intro: execn.intros) lemma execn_Fault_end: assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" and s: "s=Fault f" shows "t=Fault f" using exec s by (induct) auto lemma execn_Stuck_end: assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" and s: "s=Stuck" shows "t=Stuck" using exec s by (induct) auto lemma execn_Abrupt_end: assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" and s: "s=Abrupt s'" shows "t=Abrupt s'" using exec s by (induct) auto lemma execn_block: "\<lbrakk>\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> =n\<Rightarrow> Normal t; \<Gamma>\<turnstile>\<langle>c s t,Normal (return s t)\<rangle> =n\<Rightarrow> u\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>block init bdy return c,Normal s\<rangle> =n\<Rightarrow> u" apply (unfold block_def) by (fastforce intro: execn.intros) lemma execn_blockAbrupt: "\<lbrakk>\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> =n\<Rightarrow> Abrupt t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>block init bdy return c,Normal s\<rangle> =n\<Rightarrow> Abrupt (return s t)" apply (unfold block_def) by (fastforce intro: execn.intros) lemma execn_blockFault: "\<lbrakk>\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> =n\<Rightarrow> Fault f\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>block init bdy return c,Normal s\<rangle> =n\<Rightarrow> Fault f" apply (unfold block_def) by (fastforce intro: execn.intros) lemma execn_blockStuck: "\<lbrakk>\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> =n\<Rightarrow> Stuck\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>block init bdy return c,Normal s\<rangle> =n\<Rightarrow> Stuck" apply (unfold block_def) by (fastforce intro: execn.intros) lemma execn_call: "\<lbrakk>\<Gamma> p=Some bdy;\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> =n\<Rightarrow> Normal t; \<Gamma>\<turnstile>\<langle>c s t,Normal (return s t)\<rangle> =Suc n\<Rightarrow> u\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>call init p return c,Normal s\<rangle> =Suc n\<Rightarrow> u" apply (simp add: call_def) apply (rule execn_block) apply (erule (1) Call) apply assumption done lemma execn_callAbrupt: "\<lbrakk>\<Gamma> p=Some bdy;\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> =n\<Rightarrow> Abrupt t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>call init p return c,Normal s\<rangle> =Suc n\<Rightarrow> Abrupt (return s t)" apply (simp add: call_def) apply (rule execn_blockAbrupt) apply (erule (1) Call) done lemma execn_callFault: "\<lbrakk>\<Gamma> p=Some bdy; \<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> =n\<Rightarrow> Fault f\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>call init p return c,Normal s\<rangle> =Suc n\<Rightarrow> Fault f" apply (simp add: call_def) apply (rule execn_blockFault) apply (erule (1) Call) done lemma execn_callStuck: "\<lbrakk>\<Gamma> p=Some bdy; \<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> =n\<Rightarrow> Stuck\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>call init p return c,Normal s\<rangle> =Suc n\<Rightarrow> Stuck" apply (simp add: call_def) apply (rule execn_blockStuck) apply (erule (1) Call) done lemma execn_callUndefined: "\<lbrakk>\<Gamma> p=None\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>call init p return c,Normal s\<rangle> =Suc n\<Rightarrow> Stuck" apply (simp add: call_def) apply (rule execn_blockStuck) apply (erule CallUndefined) done lemma execn_block_Normal_elim [consumes 1]: assumes execn_block: "\<Gamma>\<turnstile>\<langle>block init bdy return c,Normal s\<rangle> =n\<Rightarrow> t" assumes Normal: "\<And>t'. \<lbrakk>\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> =n\<Rightarrow> Normal t'; \<Gamma>\<turnstile>\<langle>c s t',Normal (return s t')\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> P" assumes Abrupt: "\<And>t'. \<lbrakk>\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> =n\<Rightarrow> Abrupt t'; t = Abrupt (return s t')\<rbrakk> \<Longrightarrow> P" assumes Fault: "\<And>f. \<lbrakk>\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> =n\<Rightarrow> Fault f; t = Fault f\<rbrakk> \<Longrightarrow> P" assumes Stuck: "\<lbrakk>\<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> =n\<Rightarrow> Stuck; t = Stuck\<rbrakk> \<Longrightarrow> P" assumes Undef: "\<lbrakk>\<Gamma> p = None; t = Stuck\<rbrakk> \<Longrightarrow> P" shows "P" using execn_block apply (unfold block_def) apply (elim execn_Normal_elim_cases) apply simp_all apply (case_tac s') apply simp_all apply (elim execn_Normal_elim_cases) apply simp apply (drule execn_Abrupt_end) apply simp apply (erule execn_Normal_elim_cases) apply simp apply (rule Abrupt,assumption+) apply (drule execn_Fault_end) apply simp apply (erule execn_Normal_elim_cases) apply simp apply (drule execn_Stuck_end) apply simp apply (erule execn_Normal_elim_cases) apply simp apply (case_tac s') apply simp_all apply (elim execn_Normal_elim_cases) apply simp apply (rule Normal,assumption+) apply (drule execn_Fault_end) apply simp apply (rule Fault,assumption+) apply (drule execn_Stuck_end) apply simp apply (rule Stuck,assumption+) done lemma execn_call_Normal_elim [consumes 1]: assumes exec_call: "\<Gamma>\<turnstile>\<langle>call init p return c,Normal s\<rangle> =n\<Rightarrow> t" assumes Normal: "\<And>bdy i t'. \<lbrakk>\<Gamma> p = Some bdy; \<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> =i\<Rightarrow> Normal t'; \<Gamma>\<turnstile>\<langle>c s t',Normal (return s t')\<rangle> =Suc i\<Rightarrow> t; n = Suc i\<rbrakk> \<Longrightarrow> P" assumes Abrupt: "\<And>bdy i t'. \<lbrakk>\<Gamma> p = Some bdy; \<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> =i\<Rightarrow> Abrupt t'; n = Suc i; t = Abrupt (return s t')\<rbrakk> \<Longrightarrow> P" assumes Fault: "\<And>bdy i f. \<lbrakk>\<Gamma> p = Some bdy; \<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> =i\<Rightarrow> Fault f; n = Suc i; t = Fault f\<rbrakk> \<Longrightarrow> P" assumes Stuck: "\<And>bdy i. \<lbrakk>\<Gamma> p = Some bdy; \<Gamma>\<turnstile>\<langle>bdy,Normal (init s)\<rangle> =i\<Rightarrow> Stuck; n = Suc i; t = Stuck\<rbrakk> \<Longrightarrow> P" assumes Undef: "\<And>i. \<lbrakk>\<Gamma> p = None; n = Suc i; t = Stuck\<rbrakk> \<Longrightarrow> P" shows "P" using exec_call apply (unfold call_def) apply (cases n) apply (simp only: block_def) apply (fastforce elim: execn_Normal_elim_cases) apply (cases "\<Gamma> p") apply (erule execn_block_Normal_elim) apply (elim execn_Normal_elim_cases) apply simp apply simp apply (elim execn_Normal_elim_cases) apply simp apply simp apply (elim execn_Normal_elim_cases) apply simp apply simp apply (elim execn_Normal_elim_cases) apply simp apply (rule Undef,assumption,assumption,assumption) apply (rule Undef,assumption+) apply (erule execn_block_Normal_elim) apply (elim execn_Normal_elim_cases) apply simp apply (rule Normal,assumption+) apply simp apply (elim execn_Normal_elim_cases) apply simp apply (rule Abrupt,assumption+) apply simp apply (elim execn_Normal_elim_cases) apply simp apply (rule Fault,assumption+) apply simp apply (elim execn_Normal_elim_cases) apply simp apply (rule Stuck,assumption,assumption,assumption,assumption) apply (rule Undef,assumption,assumption,assumption) apply (rule Undef,assumption+) done lemma execn_dynCall: "\<lbrakk>\<Gamma>\<turnstile>\<langle>call init (p s) return c,Normal s\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>dynCall init p return c,Normal s\<rangle> =n\<Rightarrow> t" apply (simp add: dynCall_def) by (rule DynCom) lemma execn_Seq': "\<lbrakk>\<Gamma>\<turnstile>\<langle>c1,s\<rangle> =n\<Rightarrow> s'; \<Gamma>\<turnstile>\<langle>c2,s'\<rangle> =n\<Rightarrow> s''\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Seq c1 c2,s\<rangle> =n\<Rightarrow> s''" apply (cases s) apply (fastforce intro: execn.intros) apply (fastforce dest: execn_Abrupt_end) apply (fastforce dest: execn_Fault_end) apply (fastforce dest: execn_Stuck_end) done lemma execn_mono: assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" shows "\<And> m. n \<le> m \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c,s\<rangle> =m\<Rightarrow> t" using exec by (induct) (auto intro: execn.intros dest: Suc_le_D) lemma execn_Suc: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c,s\<rangle> =Suc n\<Rightarrow> t" by (rule execn_mono [OF _ le_refl [THEN le_SucI]]) lemma execn_assoc: "\<Gamma>\<turnstile>\<langle>Seq c1 (Seq c2 c3),s\<rangle> =n\<Rightarrow> t = \<Gamma>\<turnstile>\<langle>Seq (Seq c1 c2) c3,s\<rangle> =n\<Rightarrow> t" by (auto elim!: execn_elim_cases intro: execn_Seq') lemma execn_to_exec: assumes execn: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" shows "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" using execn by induct (auto intro: exec.intros) lemma exec_to_execn: assumes execn: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" shows "\<exists>n. \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" using execn proof (induct) case Skip thus ?case by (iprover intro: execn.intros) next case Guard thus ?case by (iprover intro: execn.intros) next case GuardFault thus ?case by (iprover intro: execn.intros) next case FaultProp thus ?case by (iprover intro: execn.intros) next case Basic thus ?case by (iprover intro: execn.intros) next case Spec thus ?case by (iprover intro: execn.intros) next case SpecStuck thus ?case by (iprover intro: execn.intros) next case (Seq c1 s s' c2 s'') then obtain n m where "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> =n\<Rightarrow> s'" "\<Gamma>\<turnstile>\<langle>c2,s'\<rangle> =m\<Rightarrow> s''" by blast then have "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> =max n m\<Rightarrow> s'" "\<Gamma>\<turnstile>\<langle>c2,s'\<rangle> =max n m\<Rightarrow> s''" by (auto elim!: execn_mono intro: max.cobounded1 max.cobounded2) thus ?case by (iprover intro: execn.intros) next case CondTrue thus ?case by (iprover intro: execn.intros) next case CondFalse thus ?case by (iprover intro: execn.intros) next case (WhileTrue s b c s' s'') then obtain n m where "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> s'" "\<Gamma>\<turnstile>\<langle>While b c,s'\<rangle> =m\<Rightarrow> s''" by blast then have "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =max n m\<Rightarrow> s'" "\<Gamma>\<turnstile>\<langle>While b c,s'\<rangle> =max n m\<Rightarrow> s''" by (auto elim!: execn_mono intro: max.cobounded1 max.cobounded2) with WhileTrue show ?case by (iprover intro: execn.intros) next case WhileFalse thus ?case by (iprover intro: execn.intros) next case Call thus ?case by (iprover intro: execn.intros) next case CallUndefined thus ?case by (iprover intro: execn.intros) next case StuckProp thus ?case by (iprover intro: execn.intros) next case DynCom thus ?case by (iprover intro: execn.intros) next case Throw thus ?case by (iprover intro: execn.intros) next case AbruptProp thus ?case by (iprover intro: execn.intros) next case (CatchMatch c1 s s' c2 s'') then obtain n m where "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> =n\<Rightarrow> Abrupt s'" "\<Gamma>\<turnstile>\<langle>c2,Normal s'\<rangle> =m\<Rightarrow> s''" by blast then have "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> =max n m\<Rightarrow> Abrupt s'" "\<Gamma>\<turnstile>\<langle>c2,Normal s'\<rangle> =max n m\<Rightarrow> s''" by (auto elim!: execn_mono intro: max.cobounded1 max.cobounded2) with CatchMatch.hyps show ?case by (iprover intro: execn.intros) next case CatchMiss thus ?case by (iprover intro: execn.intros) qed theorem exec_iff_execn: "(\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t) = (\<exists>n. \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t)" by (iprover intro: exec_to_execn execn_to_exec) definition nfinal_notin:: "('s,'p,'f) body \<Rightarrow> ('s,'p,'f) com \<Rightarrow> ('s,'f) xstate \<Rightarrow> nat \<Rightarrow> ('s,'f) xstate set \<Rightarrow> bool" ("_\<turnstile> \<langle>_,_\<rangle> =_\<Rightarrow>\<notin>_" [60,20,98,65,60] 89) where "\<Gamma>\<turnstile> \<langle>c,s\<rangle> =n\<Rightarrow>\<notin>T = (\<forall>t. \<Gamma>\<turnstile> \<langle>c,s\<rangle> =n\<Rightarrow> t \<longrightarrow> t\<notin>T)" definition final_notin:: "('s,'p,'f) body \<Rightarrow> ('s,'p,'f) com \<Rightarrow> ('s,'f) xstate \<Rightarrow> ('s,'f) xstate set \<Rightarrow> bool" ("_\<turnstile> \<langle>_,_\<rangle> \<Rightarrow>\<notin>_" [60,20,98,60] 89) where "\<Gamma>\<turnstile> \<langle>c,s\<rangle> \<Rightarrow>\<notin>T = (\<forall>t. \<Gamma>\<turnstile> \<langle>c,s\<rangle> \<Rightarrow>t \<longrightarrow> t\<notin>T)" lemma final_notinI: "\<lbrakk>\<And>t. \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t \<Longrightarrow> t \<notin> T\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>T" by (simp add: final_notin_def) lemma noFaultStuck_Call_body': "p \<in> dom \<Gamma> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F)) = \<Gamma>\<turnstile>\<langle>the (\<Gamma> p),Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))" by (clarsimp simp add: final_notin_def exec_Call_body) lemma noFault_startn: assumes execn: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" and t: "t\<noteq>Fault f" shows "s\<noteq>Fault f" using execn t by (induct) auto lemma noFault_start: assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" and t: "t\<noteq>Fault f" shows "s\<noteq>Fault f" using exec t by (induct) auto lemma noStuck_startn: assumes execn: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" and t: "t\<noteq>Stuck" shows "s\<noteq>Stuck" using execn t by (induct) auto lemma noStuck_start: assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" and t: "t\<noteq>Stuck" shows "s\<noteq>Stuck" using exec t by (induct) auto lemma noAbrupt_startn: assumes execn: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" and t: "\<forall>t'. t\<noteq>Abrupt t'" shows "s\<noteq>Abrupt s'" using execn t by (induct) auto lemma noAbrupt_start: assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" and t: "\<forall>t'. t\<noteq>Abrupt t'" shows "s\<noteq>Abrupt s'" using exec t by (induct) auto lemma noFaultn_startD: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> Normal t \<Longrightarrow> s \<noteq> Fault f" by (auto dest: noFault_startn) lemma noFaultn_startD': "t\<noteq>Fault f \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t \<Longrightarrow> s \<noteq> Fault f" by (auto dest: noFault_startn) lemma noFault_startD: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> Normal t \<Longrightarrow> s \<noteq> Fault f" by (auto dest: noFault_start) lemma noFault_startD': "t\<noteq>Fault f\<Longrightarrow> \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t \<Longrightarrow> s \<noteq> Fault f" by (auto dest: noFault_start) lemma noStuckn_startD: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> Normal t \<Longrightarrow> s \<noteq> Stuck" by (auto dest: noStuck_startn) lemma noStuckn_startD': "t\<noteq>Stuck \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t \<Longrightarrow> s \<noteq> Stuck" by (auto dest: noStuck_startn) lemma noStuck_startD: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> Normal t \<Longrightarrow> s \<noteq> Stuck" by (auto dest: noStuck_start) lemma noStuck_startD': "t\<noteq>Stuck \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t \<Longrightarrow> s \<noteq> Stuck" by (auto dest: noStuck_start) lemma noAbruptn_startD: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> Normal t \<Longrightarrow> s \<noteq> Abrupt s'" by (auto dest: noAbrupt_startn) lemma noAbrupt_startD: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> Normal t \<Longrightarrow> s \<noteq> Abrupt s'" by (auto dest: noAbrupt_start) lemma noFaultnI: "\<lbrakk>\<And>t. \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>t \<Longrightarrow> t\<noteq>Fault f\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>\<notin>{Fault f}" by (simp add: nfinal_notin_def) lemma noFaultnI': assumes contr: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> Fault f \<Longrightarrow> False" shows "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>\<notin>{Fault f}" proof (rule noFaultnI) fix t assume "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" with contr show "t \<noteq> Fault f" by (cases "t=Fault f") auto qed lemma noFaultn_def': "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>\<notin>{Fault f} = (\<not>\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> Fault f)" apply rule apply (fastforce simp add: nfinal_notin_def) apply (fastforce intro: noFaultnI') done lemma noStucknI': assumes contr: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> Stuck \<Longrightarrow> False" shows "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>\<notin>{Stuck}" proof (rule noStucknI) fix t assume "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" with contr show "t \<noteq> Stuck" by (cases t) auto qed lemma noStuckn_def': "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>\<notin>{Stuck} = (\<not>\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> Stuck)" apply rule apply (fastforce simp add: nfinal_notin_def) apply (fastforce intro: noStucknI') done lemma noFaultI: "\<lbrakk>\<And>t. \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>t \<Longrightarrow> t\<noteq>Fault f\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>{Fault f}" by (simp add: final_notin_def) lemma noFaultI': assumes contr: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> Fault f\<Longrightarrow> False" shows "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>{Fault f}" proof (rule noFaultI) fix t assume "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" with contr show "t \<noteq> Fault f" by (cases "t=Fault f") auto qed lemma noFaultE: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>{Fault f}; \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> Fault f\<rbrakk> \<Longrightarrow> P" by (auto simp add: final_notin_def) lemma noStuckI: "\<lbrakk>\<And>t. \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>t \<Longrightarrow> t\<noteq>Stuck\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>{Stuck}" by (simp add: final_notin_def) lemma noStuckI': assumes contr: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> Stuck \<Longrightarrow> False" shows "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>{Stuck}" proof (rule noStuckI) fix t assume "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" with contr show "t \<noteq> Stuck" by (cases t) auto qed lemma noStuckE: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>{Stuck}; \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> Stuck\<rbrakk> \<Longrightarrow> P" by (auto simp add: final_notin_def) lemma noStuck_def': "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>{Stuck} = (\<not>\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> Stuck)" apply rule apply (fastforce simp add: final_notin_def) apply (fastforce intro: noStuckI') done lemma noFaultn_execD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>\<notin>{Fault f}; \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>t\<rbrakk> \<Longrightarrow> t\<noteq>Fault f" by (simp add: nfinal_notin_def) lemma noFault_execD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>{Fault f}; \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>t\<rbrakk> \<Longrightarrow> t\<noteq>Fault f" by (simp add: final_notin_def) lemma noFaultn_exec_startD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>\<notin>{Fault f}; \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>t\<rbrakk> \<Longrightarrow> s\<noteq>Fault f" by (auto simp add: nfinal_notin_def dest: noFaultn_startD) lemma noFault_exec_startD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>{Fault f}; \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>t\<rbrakk> \<Longrightarrow> s\<noteq>Fault f" by (auto simp add: final_notin_def dest: noFault_startD) lemma noStuckn_execD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>\<notin>{Stuck}; \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>t\<rbrakk> \<Longrightarrow> t\<noteq>Stuck" by (simp add: nfinal_notin_def) lemma noStuck_execD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>{Stuck}; \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>t\<rbrakk> \<Longrightarrow> t\<noteq>Stuck" by (simp add: final_notin_def) lemma noStuckn_exec_startD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>\<notin>{Stuck}; \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>t\<rbrakk> \<Longrightarrow> s\<noteq>Stuck" by (auto simp add: nfinal_notin_def dest: noStuckn_startD) lemma noStuck_exec_startD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>{Stuck}; \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>t\<rbrakk> \<Longrightarrow> s\<noteq>Stuck" by (auto simp add: final_notin_def dest: noStuck_startD) lemma noFaultStuckn_execD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>\<notin>{Fault True,Fault False,Stuck}; \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>t\<rbrakk> \<Longrightarrow> t\<notin>{Fault True,Fault False,Stuck}" by (simp add: nfinal_notin_def) lemma noFaultStuck_execD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>{Fault True,Fault False,Stuck}; \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>t\<rbrakk> \<Longrightarrow> t\<notin>{Fault True,Fault False,Stuck}" by (simp add: final_notin_def) lemma noFaultStuckn_exec_startD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>\<notin>{Fault True, Fault False,Stuck}; \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>t\<rbrakk> \<Longrightarrow> s\<notin>{Fault True,Fault False,Stuck}" by (auto simp add: nfinal_notin_def ) lemma noFaultStuck_exec_startD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>{Fault True, Fault False,Stuck}; \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>t\<rbrakk> \<Longrightarrow> s\<notin>{Fault True,Fault False,Stuck}" by (auto simp add: final_notin_def ) lemma noStuck_Call: assumes noStuck: "\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}" shows "p \<in> dom \<Gamma>" proof (cases "p \<in> dom \<Gamma>") case True thus ?thesis by simp next case False hence "\<Gamma> p = None" by auto hence "\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>Stuck" by (rule exec.CallUndefined) with noStuck show ?thesis by (auto simp add: final_notin_def) qed lemma Guard_noFaultStuckD: assumes "\<Gamma>\<turnstile>\<langle>Guard f g c,Normal s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` (-F))" assumes "f \<notin> F" shows "s \<in> g" using assms by (auto simp add: final_notin_def intro: exec.intros) lemma final_notin_to_finaln: assumes notin: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>T" shows "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>\<notin>T" proof (clarsimp simp add: nfinal_notin_def) fix t assume "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" and "t\<in>T" with notin show "False" by (auto intro: execn_to_exec simp add: final_notin_def) qed lemma noFault_Call_body: "\<Gamma> p=Some bdy\<Longrightarrow> \<Gamma>\<turnstile>\<langle>Call p ,Normal s\<rangle> \<Rightarrow>\<notin>{Fault f} = \<Gamma>\<turnstile>\<langle>the (\<Gamma> p),Normal s\<rangle> \<Rightarrow>\<notin>{Fault f}" by (simp add: noFault_def' exec_Call_body) lemma noStuck_Call_body: "\<Gamma> p=Some bdy\<Longrightarrow> \<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck} = \<Gamma>\<turnstile>\<langle>the (\<Gamma> p),Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}" by (simp add: noStuck_def' exec_Call_body) lemma exec_final_notin_to_execn: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>T \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>\<notin>T" by (auto simp add: final_notin_def nfinal_notin_def dest: execn_to_exec) lemma execn_final_notin_to_exec: "\<forall>n. \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>\<notin>T \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>T" by (auto simp add: final_notin_def nfinal_notin_def dest: exec_to_execn) lemma exec_final_notin_iff_execn: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow>\<notin>T = (\<forall>n. \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>\<notin>T)" by (auto intro: exec_final_notin_to_execn execn_final_notin_to_exec) lemma Seq_NoFaultStuckD2: assumes noabort: "\<Gamma>\<turnstile>\<langle>Seq c1 c2,s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` F)" shows "\<forall>t. \<Gamma>\<turnstile>\<langle>c1,s\<rangle> \<Rightarrow> t \<longrightarrow> t\<notin> ({Stuck} \<union> Fault ` F) \<longrightarrow> \<Gamma>\<turnstile>\<langle>c2,t\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` F)" using noabort by (auto simp add: final_notin_def intro: exec_Seq') lemma Seq_NoFaultStuckD1: assumes noabort: "\<Gamma>\<turnstile>\<langle>Seq c1 c2,s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` F)" shows "\<Gamma>\<turnstile>\<langle>c1,s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` F)" proof (rule final_notinI) fix t assume exec_c1: "\<Gamma>\<turnstile>\<langle>c1,s\<rangle> \<Rightarrow> t" show "t \<notin> {Stuck} \<union> Fault ` F" proof assume "t \<in> {Stuck} \<union> Fault ` F" moreover { assume "t = Stuck" with exec_c1 have "\<Gamma>\<turnstile>\<langle>Seq c1 c2,s\<rangle> \<Rightarrow> Stuck" by (auto intro: exec_Seq') with noabort have False by (auto simp add: final_notin_def) hence False .. } moreover { assume "t \<in> Fault ` F" then obtain f where t: "t=Fault f" and f: "f \<in> F" by auto from t exec_c1 have "\<Gamma>\<turnstile>\<langle>Seq c1 c2,s\<rangle> \<Rightarrow> Fault f" by (auto intro: exec_Seq') with noabort f have False by (auto simp add: final_notin_def) hence False .. } ultimately show False by auto qed qed lemma Seq_NoFaultStuckD2': assumes noabort: "\<Gamma>\<turnstile>\<langle>Seq c1 c2,s\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` F)" shows "\<forall>t. \<Gamma>\<turnstile>\<langle>c1,s\<rangle> \<Rightarrow> t \<longrightarrow> t\<notin> ({Stuck} \<union> Fault ` F) \<longrightarrow> \<Gamma>\<turnstile>\<langle>c2,t\<rangle> \<Rightarrow>\<notin>({Stuck} \<union> Fault ` F)" using noabort by (auto simp add: final_notin_def intro: exec_Seq') (* ************************************************************************* *) subsection \<open>Lemmas about @{const "sequence"}, @{const "flatten"} and @{const "normalize"}\<close> (* ************************************************************************ *) lemma execn_sequence_app: "\<And>s s' t. \<lbrakk>\<Gamma>\<turnstile>\<langle>sequence Seq xs,Normal s\<rangle> =n\<Rightarrow> s'; \<Gamma>\<turnstile>\<langle>sequence Seq ys,s'\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>sequence Seq (xs@ys),Normal s\<rangle> =n\<Rightarrow> t" proof (induct xs) case Nil thus ?case by (auto elim: execn_Normal_elim_cases) next case (Cons x xs) have exec_x_xs: "\<Gamma>\<turnstile>\<langle>sequence Seq (x # xs),Normal s\<rangle> =n\<Rightarrow> s'" by fact have exec_ys: "\<Gamma>\<turnstile>\<langle>sequence Seq ys,s'\<rangle> =n\<Rightarrow> t" by fact show ?case proof (cases xs) case Nil with exec_x_xs have "\<Gamma>\<turnstile>\<langle>x,Normal s\<rangle> =n\<Rightarrow> s'" by (auto elim: execn_Normal_elim_cases ) with Nil exec_ys show ?thesis by (cases ys) (auto intro: execn.intros elim: execn_elim_cases) next case Cons with exec_x_xs obtain s'' where exec_x: "\<Gamma>\<turnstile>\<langle>x,Normal s\<rangle> =n\<Rightarrow> s''" and exec_xs: "\<Gamma>\<turnstile>\<langle>sequence Seq xs,s''\<rangle> =n\<Rightarrow> s'" by (auto elim: execn_Normal_elim_cases ) show ?thesis proof (cases s'') case (Normal s''') from Cons.hyps [OF exec_xs [simplified Normal] exec_ys] have "\<Gamma>\<turnstile>\<langle>sequence Seq (xs @ ys),Normal s'''\<rangle> =n\<Rightarrow> t" . with Cons exec_x Normal show ?thesis by (auto intro: execn.intros) next case (Abrupt s''') with exec_xs have "s'=Abrupt s'''" by (auto dest: execn_Abrupt_end) with exec_ys have "t=Abrupt s'''" by (auto dest: execn_Abrupt_end) with exec_x Abrupt Cons show ?thesis by (auto intro: execn.intros) next case (Fault f) with exec_xs have "s'=Fault f" by (auto dest: execn_Fault_end) with exec_ys have "t=Fault f" by (auto dest: execn_Fault_end) with exec_x Fault Cons show ?thesis by (auto intro: execn.intros) next case Stuck with exec_xs have "s'=Stuck" by (auto dest: execn_Stuck_end) with exec_ys have "t=Stuck" by (auto dest: execn_Stuck_end) with exec_x Stuck Cons show ?thesis by (auto intro: execn.intros) qed qed qed lemma execn_sequence_appD: "\<And>s t. \<Gamma>\<turnstile>\<langle>sequence Seq (xs @ ys),Normal s\<rangle> =n\<Rightarrow> t \<Longrightarrow> \<exists>s'. \<Gamma>\<turnstile>\<langle>sequence Seq xs,Normal s\<rangle> =n\<Rightarrow> s' \<and> \<Gamma>\<turnstile>\<langle>sequence Seq ys,s'\<rangle> =n\<Rightarrow> t" proof (induct xs) case Nil thus ?case by (auto intro: execn.intros) next case (Cons x xs) have exec_app: "\<Gamma>\<turnstile>\<langle>sequence Seq ((x # xs) @ ys),Normal s\<rangle> =n\<Rightarrow> t" by fact show ?case proof (cases xs) case Nil with exec_app show ?thesis by (cases ys) (auto elim: execn_Normal_elim_cases intro: execn_Skip') next case Cons with exec_app obtain s' where exec_x: "\<Gamma>\<turnstile>\<langle>x,Normal s\<rangle> =n\<Rightarrow> s'" and exec_xs_ys: "\<Gamma>\<turnstile>\<langle>sequence Seq (xs @ ys),s'\<rangle> =n\<Rightarrow> t" by (auto elim: execn_Normal_elim_cases) show ?thesis proof (cases s') case (Normal s'') from Cons.hyps [OF exec_xs_ys [simplified Normal]] Normal exec_x Cons show ?thesis by (auto intro: execn.intros) next case (Abrupt s'') with exec_xs_ys have "t=Abrupt s''" by (auto dest: execn_Abrupt_end) with Abrupt exec_x Cons show ?thesis by (auto intro: execn.intros) next case (Fault f) with exec_xs_ys have "t=Fault f" by (auto dest: execn_Fault_end) with Fault exec_x Cons show ?thesis by (auto intro: execn.intros) next case Stuck with exec_xs_ys have "t=Stuck" by (auto dest: execn_Stuck_end) with Stuck exec_x Cons show ?thesis by (auto intro: execn.intros) qed qed qed lemma execn_sequence_appE [consumes 1]: "\<lbrakk>\<Gamma>\<turnstile>\<langle>sequence Seq (xs @ ys),Normal s\<rangle> =n\<Rightarrow> t; \<And>s'. \<lbrakk>\<Gamma>\<turnstile>\<langle>sequence Seq xs,Normal s\<rangle> =n\<Rightarrow> s';\<Gamma>\<turnstile>\<langle>sequence Seq ys,s'\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" by (auto dest: execn_sequence_appD) lemma execn_to_execn_sequence_flatten: assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" shows "\<Gamma>\<turnstile>\<langle>sequence Seq (flatten c),s\<rangle> =n\<Rightarrow> t" using exec proof induct case (Seq c1 c2 n s s' s'') thus ?case by (auto intro: execn.intros execn_sequence_app) qed (auto intro: execn.intros) lemma execn_to_execn_normalize: assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" shows "\<Gamma>\<turnstile>\<langle>normalize c,s\<rangle> =n\<Rightarrow> t" using exec proof induct case (Seq c1 c2 n s s' s'') thus ?case by (auto intro: execn_to_execn_sequence_flatten execn_sequence_app ) qed (auto intro: execn.intros) lemma execn_sequence_flatten_to_execn: shows "\<And>s t. \<Gamma>\<turnstile>\<langle>sequence Seq (flatten c),s\<rangle> =n\<Rightarrow> t \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" proof (induct c) case (Seq c1 c2) have exec_seq: "\<Gamma>\<turnstile>\<langle>sequence Seq (flatten (Seq c1 c2)),s\<rangle> =n\<Rightarrow> t" by fact show ?case proof (cases s) case (Normal s') with exec_seq obtain s'' where "\<Gamma>\<turnstile>\<langle>sequence Seq (flatten c1),Normal s'\<rangle> =n\<Rightarrow> s''" and "\<Gamma>\<turnstile>\<langle>sequence Seq (flatten c2),s''\<rangle> =n\<Rightarrow> t" by (auto elim: execn_sequence_appE) with Seq.hyps Normal show ?thesis by (fastforce intro: execn.intros) next case Abrupt with exec_seq show ?thesis by (auto intro: execn.intros dest: execn_Abrupt_end) next case Fault with exec_seq show ?thesis by (auto intro: execn.intros dest: execn_Fault_end) next case Stuck with exec_seq show ?thesis by (auto intro: execn.intros dest: execn_Stuck_end) qed qed auto lemma execn_normalize_to_execn: shows "\<And>s t n. \<Gamma>\<turnstile>\<langle>normalize c,s\<rangle> =n\<Rightarrow> t \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" proof (induct c) case Skip thus ?case by simp next case Basic thus ?case by simp next case Spec thus ?case by simp next case (Seq c1 c2) have "\<Gamma>\<turnstile>\<langle>normalize (Seq c1 c2),s\<rangle> =n\<Rightarrow> t" by fact hence exec_norm_seq: "\<Gamma>\<turnstile>\<langle>sequence Seq (flatten (normalize c1) @ flatten (normalize c2)),s\<rangle> =n\<Rightarrow> t" by simp show ?case proof (cases s) case (Normal s') with exec_norm_seq obtain s'' where exec_norm_c1: "\<Gamma>\<turnstile>\<langle>sequence Seq (flatten (normalize c1)),Normal s'\<rangle> =n\<Rightarrow> s''" and exec_norm_c2: "\<Gamma>\<turnstile>\<langle>sequence Seq (flatten (normalize c2)),s''\<rangle> =n\<Rightarrow> t" by (auto elim: execn_sequence_appE) from execn_sequence_flatten_to_execn [OF exec_norm_c1] execn_sequence_flatten_to_execn [OF exec_norm_c2] Seq.hyps Normal show ?thesis by (fastforce intro: execn.intros) next case (Abrupt s') with exec_norm_seq have "t=Abrupt s'" by (auto dest: execn_Abrupt_end) with Abrupt show ?thesis by (auto intro: execn.intros) next case (Fault f) with exec_norm_seq have "t=Fault f" by (auto dest: execn_Fault_end) with Fault show ?thesis by (auto intro: execn.intros) next case Stuck with exec_norm_seq have "t=Stuck" by (auto dest: execn_Stuck_end) with Stuck show ?thesis by (auto intro: execn.intros) qed next case Cond thus ?case by (auto intro: execn.intros elim!: execn_elim_cases) next case (While b c) have "\<Gamma>\<turnstile>\<langle>normalize (While b c),s\<rangle> =n\<Rightarrow> t" by fact hence exec_norm_w: "\<Gamma>\<turnstile>\<langle>While b (normalize c),s\<rangle> =n\<Rightarrow> t" by simp { fix s t w assume exec_w: "\<Gamma>\<turnstile>\<langle>w,s\<rangle> =n\<Rightarrow> t" have "w=While b (normalize c) \<Longrightarrow> \<Gamma>\<turnstile>\<langle>While b c,s\<rangle> =n\<Rightarrow> t" using exec_w proof (induct) case (WhileTrue s b' c' n w t) from WhileTrue obtain s_in_b: "s \<in> b" and exec_c: "\<Gamma>\<turnstile>\<langle>normalize c,Normal s\<rangle> =n\<Rightarrow> w" and hyp_w: "\<Gamma>\<turnstile>\<langle>While b c,w\<rangle> =n\<Rightarrow> t" by simp from While.hyps [OF exec_c] have "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> w" by simp with hyp_w s_in_b have "\<Gamma>\<turnstile>\<langle>While b c,Normal s\<rangle> =n\<Rightarrow> t" by (auto intro: execn.intros) with WhileTrue show ?case by simp qed (auto intro: execn.intros) } from this [OF exec_norm_w] show ?case by simp next case Call thus ?case by simp next case DynCom thus ?case by (auto intro: execn.intros elim!: execn_elim_cases) next case Guard thus ?case by (auto intro: execn.intros elim!: execn_elim_cases) next case Throw thus ?case by simp next case Catch thus ?case by (fastforce intro: execn.intros elim!: execn_elim_cases) qed lemma execn_normalize_iff_execn: "\<Gamma>\<turnstile>\<langle>normalize c,s\<rangle> =n\<Rightarrow> t = \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" by (auto intro: execn_to_execn_normalize execn_normalize_to_execn) lemma exec_sequence_app: assumes exec_xs: "\<Gamma>\<turnstile>\<langle>sequence Seq xs,Normal s\<rangle> \<Rightarrow> s'" assumes exec_ys: "\<Gamma>\<turnstile>\<langle>sequence Seq ys,s'\<rangle> \<Rightarrow> t" shows "\<Gamma>\<turnstile>\<langle>sequence Seq (xs@ys),Normal s\<rangle> \<Rightarrow> t" proof - from exec_to_execn [OF exec_xs] obtain n where execn_xs: "\<Gamma>\<turnstile>\<langle>sequence Seq xs,Normal s\<rangle> =n\<Rightarrow> s'".. from exec_to_execn [OF exec_ys] obtain m where execn_ys: "\<Gamma>\<turnstile>\<langle>sequence Seq ys,s'\<rangle> =m\<Rightarrow> t".. with execn_xs obtain "\<Gamma>\<turnstile>\<langle>sequence Seq xs,Normal s\<rangle> =max n m\<Rightarrow> s'" "\<Gamma>\<turnstile>\<langle>sequence Seq ys,s'\<rangle> =max n m\<Rightarrow> t" by (auto intro: execn_mono max.cobounded1 max.cobounded2) from execn_sequence_app [OF this] have "\<Gamma>\<turnstile>\<langle>sequence Seq (xs @ ys),Normal s\<rangle> =max n m\<Rightarrow> t" . thus ?thesis by (rule execn_to_exec) qed lemma exec_sequence_appD: assumes exec_xs_ys: "\<Gamma>\<turnstile>\<langle>sequence Seq (xs @ ys),Normal s\<rangle> \<Rightarrow> t" shows "\<exists>s'. \<Gamma>\<turnstile>\<langle>sequence Seq xs,Normal s\<rangle> \<Rightarrow> s' \<and> \<Gamma>\<turnstile>\<langle>sequence Seq ys,s'\<rangle> \<Rightarrow> t" proof - from exec_to_execn [OF exec_xs_ys] obtain n where "\<Gamma>\<turnstile>\<langle>sequence Seq (xs @ ys),Normal s\<rangle> =n\<Rightarrow> t".. thus ?thesis by (cases rule: execn_sequence_appE) (auto intro: execn_to_exec) qed lemma exec_sequence_appE [consumes 1]: "\<lbrakk>\<Gamma>\<turnstile>\<langle>sequence Seq (xs @ ys),Normal s\<rangle> \<Rightarrow> t; \<And>s'. \<lbrakk>\<Gamma>\<turnstile>\<langle>sequence Seq xs,Normal s\<rangle> \<Rightarrow> s';\<Gamma>\<turnstile>\<langle>sequence Seq ys,s'\<rangle> \<Rightarrow> t\<rbrakk> \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" by (auto dest: exec_sequence_appD) lemma exec_to_exec_sequence_flatten: assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" shows "\<Gamma>\<turnstile>\<langle>sequence Seq (flatten c),s\<rangle> \<Rightarrow> t" proof - from exec_to_execn [OF exec] obtain n where "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t".. from execn_to_execn_sequence_flatten [OF this] show ?thesis by (rule execn_to_exec) qed lemma exec_sequence_flatten_to_exec: assumes exec_seq: "\<Gamma>\<turnstile>\<langle>sequence Seq (flatten c),s\<rangle> \<Rightarrow> t" shows "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" proof - from exec_to_execn [OF exec_seq] obtain n where "\<Gamma>\<turnstile>\<langle>sequence Seq (flatten c),s\<rangle> =n\<Rightarrow> t".. from execn_sequence_flatten_to_execn [OF this] show ?thesis by (rule execn_to_exec) qed lemma exec_to_exec_normalize: assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" shows "\<Gamma>\<turnstile>\<langle>normalize c,s\<rangle> \<Rightarrow> t" proof - from exec_to_execn [OF exec] obtain n where "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t".. hence "\<Gamma>\<turnstile>\<langle>normalize c,s\<rangle> =n\<Rightarrow> t" by (rule execn_to_execn_normalize) thus ?thesis by (rule execn_to_exec) qed lemma exec_normalize_to_exec: assumes exec: "\<Gamma>\<turnstile>\<langle>normalize c,s\<rangle> \<Rightarrow> t" shows "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" proof - from exec_to_execn [OF exec] obtain n where "\<Gamma>\<turnstile>\<langle>normalize c,s\<rangle> =n\<Rightarrow> t".. hence "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" by (rule execn_normalize_to_execn) thus ?thesis by (rule execn_to_exec) qed (* ************************************************************************* *) subsection \<open>Lemmas about @{term "c\<^sub>1 \<subseteq>\<^sub>g c\<^sub>2"}\<close> (* ************************************************************************ *) lemma execn_to_execn_subseteq_guards: "\<And>c s t n. \<lbrakk>c \<subseteq>\<^sub>g c'; \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> \<exists>t'. \<Gamma>\<turnstile>\<langle>c',s\<rangle> =n\<Rightarrow> t' \<and> (isFault t \<longrightarrow> isFault t') \<and> (\<not> isFault t' \<longrightarrow> t'=t)" proof (induct c') case Skip thus ?case by (fastforce dest: subseteq_guardsD elim: execn_elim_cases) next case Basic thus ?case by (fastforce dest: subseteq_guardsD elim: execn_elim_cases) next case Spec thus ?case by (fastforce dest: subseteq_guardsD elim: execn_elim_cases) next case (Seq c1' c2') have "c \<subseteq>\<^sub>g Seq c1' c2'" by fact from subseteq_guards_Seq [OF this] obtain c1 c2 where c: "c = Seq c1 c2" and c1_c1': "c1 \<subseteq>\<^sub>g c1'" and c2_c2': "c2 \<subseteq>\<^sub>g c2'" by blast have exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" by fact with c obtain w where exec_c1: "\<Gamma>\<turnstile>\<langle>c1,s\<rangle> =n\<Rightarrow> w" and exec_c2: "\<Gamma>\<turnstile>\<langle>c2,w\<rangle> =n\<Rightarrow> t" by (auto elim: execn_elim_cases) from exec_c1 Seq.hyps c1_c1' obtain w' where exec_c1': "\<Gamma>\<turnstile>\<langle>c1',s\<rangle> =n\<Rightarrow> w'" and w_Fault: "isFault w \<longrightarrow> isFault w'" and w'_noFault: "\<not> isFault w' \<longrightarrow> w'=w" by blast show ?case proof (cases "s") case (Fault f) with exec have "t=Fault f" by (auto dest: execn_Fault_end) with Fault show ?thesis by auto next case Stuck with exec have "t=Stuck" by (auto dest: execn_Stuck_end) with Stuck show ?thesis by auto next case (Abrupt s') with exec have "t=Abrupt s'" by (auto dest: execn_Abrupt_end) with Abrupt show ?thesis by auto next case (Normal s') show ?thesis proof (cases "isFault w") case True then obtain f where w': "w=Fault f".. moreover with exec_c2 have t: "t=Fault f" by (auto dest: execn_Fault_end) ultimately show ?thesis using Normal w_Fault exec_c1' by (fastforce intro: execn.intros elim: isFaultE) next case False note noFault_w = this show ?thesis proof (cases "isFault w'") case True then obtain f' where w': "w'=Fault f'".. with Normal exec_c1' have exec: "\<Gamma>\<turnstile>\<langle>Seq c1' c2',s\<rangle> =n\<Rightarrow> Fault f'" by (auto intro: execn.intros) then show ?thesis by auto next case False with w'_noFault have w': "w'=w" by simp from Seq.hyps exec_c2 c2_c2' obtain t' where "\<Gamma>\<turnstile>\<langle>c2',w\<rangle> =n\<Rightarrow> t'" and "isFault t \<longrightarrow> isFault t'" and "\<not> isFault t' \<longrightarrow> t'=t" by blast with Normal exec_c1' w' show ?thesis by (fastforce intro: execn.intros) qed qed qed next case (Cond b c1' c2') have exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" by fact have "c \<subseteq>\<^sub>g Cond b c1' c2'" by fact from subseteq_guards_Cond [OF this] obtain c1 c2 where c: "c = Cond b c1 c2" and c1_c1': "c1 \<subseteq>\<^sub>g c1'" and c2_c2': "c2 \<subseteq>\<^sub>g c2'" by blast show ?case proof (cases "s") case (Fault f) with exec have "t=Fault f" by (auto dest: execn_Fault_end) with Fault show ?thesis by auto next case Stuck with exec have "t=Stuck" by (auto dest: execn_Stuck_end) with Stuck show ?thesis by auto next case (Abrupt s') with exec have "t=Abrupt s'" by (auto dest: execn_Abrupt_end) with Abrupt show ?thesis by auto next case (Normal s') from exec [simplified c Normal] show ?thesis proof (cases) assume s'_in_b: "s' \<in> b" assume "\<Gamma>\<turnstile>\<langle>c1,Normal s'\<rangle> =n\<Rightarrow> t" with c1_c1' Normal Cond.hyps obtain t' where "\<Gamma>\<turnstile>\<langle>c1',Normal s'\<rangle> =n\<Rightarrow> t'" "isFault t \<longrightarrow> isFault t'" "\<not> isFault t' \<longrightarrow> t' = t" by blast with s'_in_b Normal show ?thesis by (fastforce intro: execn.intros) next assume s'_notin_b: "s' \<notin> b" assume "\<Gamma>\<turnstile>\<langle>c2,Normal s'\<rangle> =n\<Rightarrow> t" with c2_c2' Normal Cond.hyps obtain t' where "\<Gamma>\<turnstile>\<langle>c2',Normal s'\<rangle> =n\<Rightarrow> t'" "isFault t \<longrightarrow> isFault t'" "\<not> isFault t' \<longrightarrow> t' = t" by blast with s'_notin_b Normal show ?thesis by (fastforce intro: execn.intros) qed qed next case (While b c') have exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" by fact have "c \<subseteq>\<^sub>g While b c'" by fact from subseteq_guards_While [OF this] obtain c'' where c: "c = While b c''" and c''_c': "c'' \<subseteq>\<^sub>g c'" by blast { fix c r w assume exec: "\<Gamma>\<turnstile>\<langle>c,r\<rangle> =n\<Rightarrow> w" assume c: "c=While b c''" have "\<exists>w'. \<Gamma>\<turnstile>\<langle>While b c',r\<rangle> =n\<Rightarrow> w' \<and> (isFault w \<longrightarrow> isFault w') \<and> (\<not> isFault w' \<longrightarrow> w'=w)" using exec c proof (induct) case (WhileTrue r b' ca n u w) have eqs: "While b' ca = While b c''" by fact from WhileTrue have r_in_b: "r \<in> b" by simp from WhileTrue have exec_c'': "\<Gamma>\<turnstile>\<langle>c'',Normal r\<rangle> =n\<Rightarrow> u" by simp from While.hyps [OF c''_c' exec_c''] obtain u' where exec_c': "\<Gamma>\<turnstile>\<langle>c',Normal r\<rangle> =n\<Rightarrow> u'" and u_Fault: "isFault u \<longrightarrow> isFault u' "and u'_noFault: "\<not> isFault u' \<longrightarrow> u' = u" by blast from WhileTrue obtain w' where exec_w: "\<Gamma>\<turnstile>\<langle>While b c',u\<rangle> =n\<Rightarrow> w'" and w_Fault: "isFault w \<longrightarrow> isFault w'" and w'_noFault: "\<not> isFault w' \<longrightarrow> w' = w" by blast show ?case proof (cases "isFault u'") case True with exec_c' r_in_b show ?thesis by (fastforce intro: execn.intros elim: isFaultE) next case False with exec_c' r_in_b u'_noFault exec_w w_Fault w'_noFault show ?thesis by (fastforce intro: execn.intros) qed next case WhileFalse thus ?case by (fastforce intro: execn.intros) qed auto } from this [OF exec c] show ?case . next case Call thus ?case by (fastforce dest: subseteq_guardsD elim: execn_elim_cases) next case (DynCom C') have exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" by fact have "c \<subseteq>\<^sub>g DynCom C'" by fact from subseteq_guards_DynCom [OF this] obtain C where c: "c = DynCom C" and C_C': "\<forall>s. C s \<subseteq>\<^sub>g C' s" by blast show ?case proof (cases "s") case (Fault f) with exec have "t=Fault f" by (auto dest: execn_Fault_end) with Fault show ?thesis by auto next case Stuck with exec have "t=Stuck" by (auto dest: execn_Stuck_end) with Stuck show ?thesis by auto next case (Abrupt s') with exec have "t=Abrupt s'" by (auto dest: execn_Abrupt_end) with Abrupt show ?thesis by auto next case (Normal s') from exec [simplified c Normal] have "\<Gamma>\<turnstile>\<langle>C s',Normal s'\<rangle> =n\<Rightarrow> t" by cases from DynCom.hyps C_C' [rule_format] this obtain t' where "\<Gamma>\<turnstile>\<langle>C' s',Normal s'\<rangle> =n\<Rightarrow> t'" "isFault t \<longrightarrow> isFault t'" "\<not> isFault t' \<longrightarrow> t' = t" by blast with Normal show ?thesis by (fastforce intro: execn.intros) qed next case (Guard f' g' c') have exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" by fact have "c \<subseteq>\<^sub>g Guard f' g' c'" by fact hence subset_cases: "(c \<subseteq>\<^sub>g c') \<or> (\<exists>c''. c = Guard f' g' c'' \<and> (c'' \<subseteq>\<^sub>g c'))" by (rule subseteq_guards_Guard) show ?case proof (cases "s") case (Fault f) with exec have "t=Fault f" by (auto dest: execn_Fault_end) with Fault show ?thesis by auto next case Stuck with exec have "t=Stuck" by (auto dest: execn_Stuck_end) with Stuck show ?thesis by auto next case (Abrupt s') with exec have "t=Abrupt s'" by (auto dest: execn_Abrupt_end) with Abrupt show ?thesis by auto next case (Normal s') from subset_cases show ?thesis proof assume c_c': "c \<subseteq>\<^sub>g c'" from Guard.hyps [OF this exec] Normal obtain t' where exec_c': "\<Gamma>\<turnstile>\<langle>c',Normal s'\<rangle> =n\<Rightarrow> t'" and t_Fault: "isFault t \<longrightarrow> isFault t'" and t_noFault: "\<not> isFault t' \<longrightarrow> t' = t" by blast with Normal show ?thesis by (cases "s' \<in> g'") (fastforce intro: execn.intros)+ next assume "\<exists>c''. c = Guard f' g' c'' \<and> (c'' \<subseteq>\<^sub>g c')" then obtain c'' where c: "c = Guard f' g' c''" and c''_c': "c'' \<subseteq>\<^sub>g c'" by blast from c exec Normal have exec_Guard': "\<Gamma>\<turnstile>\<langle>Guard f' g' c'',Normal s'\<rangle> =n\<Rightarrow> t" by simp thus ?thesis proof (cases) assume s'_in_g': "s' \<in> g'" assume exec_c'': "\<Gamma>\<turnstile>\<langle>c'',Normal s'\<rangle> =n\<Rightarrow> t" from Guard.hyps [OF c''_c' exec_c''] obtain t' where exec_c': "\<Gamma>\<turnstile>\<langle>c',Normal s'\<rangle> =n\<Rightarrow> t'" and t_Fault: "isFault t \<longrightarrow> isFault t'" and t_noFault: "\<not> isFault t' \<longrightarrow> t' = t" by blast with Normal s'_in_g' show ?thesis by (fastforce intro: execn.intros) next assume "s' \<notin> g'" "t=Fault f'" with Normal show ?thesis by (fastforce intro: execn.intros) qed qed qed next case Throw thus ?case by (fastforce dest: subseteq_guardsD intro: execn.intros elim: execn_elim_cases) next case (Catch c1' c2') have "c \<subseteq>\<^sub>g Catch c1' c2'" by fact from subseteq_guards_Catch [OF this] obtain c1 c2 where c: "c = Catch c1 c2" and c1_c1': "c1 \<subseteq>\<^sub>g c1'" and c2_c2': "c2 \<subseteq>\<^sub>g c2'" by blast have exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" by fact show ?case proof (cases "s") case (Fault f) with exec have "t=Fault f" by (auto dest: execn_Fault_end) with Fault show ?thesis by auto next case Stuck with exec have "t=Stuck" by (auto dest: execn_Stuck_end) with Stuck show ?thesis by auto next case (Abrupt s') with exec have "t=Abrupt s'" by (auto dest: execn_Abrupt_end) with Abrupt show ?thesis by auto next case (Normal s') from exec [simplified c Normal] show ?thesis proof (cases) fix w assume exec_c1: "\<Gamma>\<turnstile>\<langle>c1,Normal s'\<rangle> =n\<Rightarrow> Abrupt w" assume exec_c2: "\<Gamma>\<turnstile>\<langle>c2,Normal w\<rangle> =n\<Rightarrow> t" from Normal exec_c1 c1_c1' Catch.hyps obtain w' where exec_c1': "\<Gamma>\<turnstile>\<langle>c1',Normal s'\<rangle> =n\<Rightarrow> w'" and w'_noFault: "\<not> isFault w' \<longrightarrow> w' = Abrupt w" by blast show ?thesis proof (cases "isFault w'") case True with exec_c1' Normal show ?thesis by (fastforce intro: execn.intros elim: isFaultE) next case False with w'_noFault have w': "w'=Abrupt w" by simp from Normal exec_c2 c2_c2' Catch.hyps obtain t' where "\<Gamma>\<turnstile>\<langle>c2',Normal w\<rangle> =n\<Rightarrow> t'" "isFault t \<longrightarrow> isFault t'" "\<not> isFault t' \<longrightarrow> t' = t" by blast with exec_c1' w' Normal show ?thesis by (fastforce intro: execn.intros ) qed next assume exec_c1: "\<Gamma>\<turnstile>\<langle>c1,Normal s'\<rangle> =n\<Rightarrow> t" assume t: "\<not> isAbr t" from Normal exec_c1 c1_c1' Catch.hyps obtain t' where exec_c1': "\<Gamma>\<turnstile>\<langle>c1',Normal s'\<rangle> =n\<Rightarrow> t'" and t_Fault: "isFault t \<longrightarrow> isFault t'" and t'_noFault: "\<not> isFault t' \<longrightarrow> t' = t" by blast show ?thesis proof (cases "isFault t'") case True with exec_c1' Normal show ?thesis by (fastforce intro: execn.intros elim: isFaultE) next case False with exec_c1' Normal t_Fault t'_noFault t show ?thesis by (fastforce intro: execn.intros) qed qed qed qed lemma exec_to_exec_subseteq_guards: assumes c_c': "c \<subseteq>\<^sub>g c'" assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" shows "\<exists>t'. \<Gamma>\<turnstile>\<langle>c',s\<rangle> \<Rightarrow> t' \<and> (isFault t \<longrightarrow> isFault t') \<and> (\<not> isFault t' \<longrightarrow> t'=t)" proof - from exec_to_execn [OF exec] obtain n where "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" .. from execn_to_execn_subseteq_guards [OF c_c' this] show ?thesis by (blast intro: execn_to_exec) qed (* ************************************************************************* *) subsection \<open>Lemmas about @{const "merge_guards"}\<close> (* ************************************************************************ *) theorem execn_to_execn_merge_guards: assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" shows "\<Gamma>\<turnstile>\<langle>merge_guards c,s\<rangle> =n\<Rightarrow> t " using exec_c proof (induct) case (Guard s g c n t f) have s_in_g: "s \<in> g" by fact have exec_merge_c: "\<Gamma>\<turnstile>\<langle>merge_guards c,Normal s\<rangle> =n\<Rightarrow> t" by fact show ?case proof (cases "\<exists>f' g' c'. merge_guards c = Guard f' g' c'") case False with exec_merge_c s_in_g show ?thesis by (cases "merge_guards c") (auto intro: execn.intros simp add: Let_def) next case True then obtain f' g' c' where merge_guards_c: "merge_guards c = Guard f' g' c'" by iprover show ?thesis proof (cases "f=f'") case False from exec_merge_c s_in_g merge_guards_c False show ?thesis by (auto intro: execn.intros simp add: Let_def) next case True from exec_merge_c s_in_g merge_guards_c True show ?thesis by (fastforce intro: execn.intros elim: execn.cases) qed qed next case (GuardFault s g f c n) have s_notin_g: "s \<notin> g" by fact show ?case proof (cases "\<exists>f' g' c'. merge_guards c = Guard f' g' c'") case False with s_notin_g show ?thesis by (cases "merge_guards c") (auto intro: execn.intros simp add: Let_def) next case True then obtain f' g' c' where merge_guards_c: "merge_guards c = Guard f' g' c'" by iprover show ?thesis proof (cases "f=f'") case False from s_notin_g merge_guards_c False show ?thesis by (auto intro: execn.intros simp add: Let_def) next case True from s_notin_g merge_guards_c True show ?thesis by (fastforce intro: execn.intros) qed qed qed (fastforce intro: execn.intros)+ lemma execn_merge_guards_to_execn_Normal: "\<And>s n t. \<Gamma>\<turnstile>\<langle>merge_guards c,Normal s\<rangle> =n\<Rightarrow> t \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> t" proof (induct c) case Skip thus ?case by auto next case Basic thus ?case by auto next case Spec thus ?case by auto next case (Seq c1 c2) have "\<Gamma>\<turnstile>\<langle>merge_guards (Seq c1 c2),Normal s\<rangle> =n\<Rightarrow> t" by fact hence exec_merge: "\<Gamma>\<turnstile>\<langle>Seq (merge_guards c1) (merge_guards c2),Normal s\<rangle> =n\<Rightarrow> t" by simp then obtain s' where exec_merge_c1: "\<Gamma>\<turnstile>\<langle>merge_guards c1,Normal s\<rangle> =n\<Rightarrow> s'" and exec_merge_c2: "\<Gamma>\<turnstile>\<langle>merge_guards c2,s'\<rangle> =n\<Rightarrow> t" by cases from exec_merge_c1 have exec_c1: "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> =n\<Rightarrow> s'" by (rule Seq.hyps) show ?case proof (cases s') case (Normal s'') with exec_merge_c2 have "\<Gamma>\<turnstile>\<langle>c2,s'\<rangle> =n\<Rightarrow> t" by (auto intro: Seq.hyps) with exec_c1 show ?thesis by (auto intro: execn.intros) next case (Abrupt s'') with exec_merge_c2 have "t=Abrupt s''" by (auto dest: execn_Abrupt_end) with exec_c1 Abrupt show ?thesis by (auto intro: execn.intros) next case (Fault f) with exec_merge_c2 have "t=Fault f" by (auto dest: execn_Fault_end) with exec_c1 Fault show ?thesis by (auto intro: execn.intros) next case Stuck with exec_merge_c2 have "t=Stuck" by (auto dest: execn_Stuck_end) with exec_c1 Stuck show ?thesis by (auto intro: execn.intros) qed next case Cond thus ?case by (fastforce intro: execn.intros elim: execn_Normal_elim_cases) next case (While b c) { fix c' r w assume exec_c': "\<Gamma>\<turnstile>\<langle>c',r\<rangle> =n\<Rightarrow> w" assume c': "c'=While b (merge_guards c)" have "\<Gamma>\<turnstile>\<langle>While b c,r\<rangle> =n\<Rightarrow> w" using exec_c' c' proof (induct) case (WhileTrue r b' c'' n u w) have eqs: "While b' c'' = While b (merge_guards c)" by fact from WhileTrue have r_in_b: "r \<in> b" by simp from WhileTrue While.hyps have exec_c: "\<Gamma>\<turnstile>\<langle>c,Normal r\<rangle> =n\<Rightarrow> u" by simp from WhileTrue have exec_w: "\<Gamma>\<turnstile>\<langle>While b c,u\<rangle> =n\<Rightarrow> w" by simp from r_in_b exec_c exec_w show ?case by (rule execn.WhileTrue) next case WhileFalse thus ?case by (auto intro: execn.WhileFalse) qed auto } with While.prems show ?case by (auto) next case Call thus ?case by simp next case DynCom thus ?case by (fastforce intro: execn.intros elim: execn_Normal_elim_cases) next case (Guard f g c) have exec_merge: "\<Gamma>\<turnstile>\<langle>merge_guards (Guard f g c),Normal s\<rangle> =n\<Rightarrow> t" by fact show ?case proof (cases "s \<in> g") case False with exec_merge have "t=Fault f" by (auto split: com.splits if_split_asm elim: execn_Normal_elim_cases simp add: Let_def is_Guard_def) with False show ?thesis by (auto intro: execn.intros) next case True note s_in_g = this show ?thesis proof (cases "\<exists>f' g' c'. merge_guards c = Guard f' g' c'") case False then have "merge_guards (Guard f g c) = Guard f g (merge_guards c)" by (cases "merge_guards c") (auto simp add: Let_def) with exec_merge s_in_g obtain "\<Gamma>\<turnstile>\<langle>merge_guards c,Normal s\<rangle> =n\<Rightarrow> t" by (auto elim: execn_Normal_elim_cases) from Guard.hyps [OF this] s_in_g show ?thesis by (auto intro: execn.intros) next case True then obtain f' g' c' where merge_guards_c: "merge_guards c = Guard f' g' c'" by iprover show ?thesis proof (cases "f=f'") case False with merge_guards_c have "merge_guards (Guard f g c) = Guard f g (merge_guards c)" by (simp add: Let_def) with exec_merge s_in_g obtain "\<Gamma>\<turnstile>\<langle>merge_guards c,Normal s\<rangle> =n\<Rightarrow> t" by (auto elim: execn_Normal_elim_cases) from Guard.hyps [OF this] s_in_g show ?thesis by (auto intro: execn.intros) next case True note f_eq_f' = this with merge_guards_c have merge_guards_Guard: "merge_guards (Guard f g c) = Guard f (g \<inter> g') c'" by simp show ?thesis proof (cases "s \<in> g'") case True with exec_merge merge_guards_Guard merge_guards_c s_in_g have "\<Gamma>\<turnstile>\<langle>merge_guards c,Normal s\<rangle> =n\<Rightarrow> t" by (auto intro: execn.intros elim: execn_Normal_elim_cases) with Guard.hyps [OF this] s_in_g show ?thesis by (auto intro: execn.intros) next case False with exec_merge merge_guards_Guard have "t=Fault f" by (auto elim: execn_Normal_elim_cases) with merge_guards_c f_eq_f' False have "\<Gamma>\<turnstile>\<langle>merge_guards c,Normal s\<rangle> =n\<Rightarrow> t" by (auto intro: execn.intros) from Guard.hyps [OF this] s_in_g show ?thesis by (auto intro: execn.intros) qed qed qed qed next case Throw thus ?case by simp next case (Catch c1 c2) have "\<Gamma>\<turnstile>\<langle>merge_guards (Catch c1 c2),Normal s\<rangle> =n\<Rightarrow> t" by fact hence "\<Gamma>\<turnstile>\<langle>Catch (merge_guards c1) (merge_guards c2),Normal s\<rangle> =n\<Rightarrow> t" by simp thus ?case by cases (auto intro: execn.intros Catch.hyps) qed theorem execn_merge_guards_to_execn: "\<Gamma>\<turnstile>\<langle>merge_guards c,s\<rangle> =n\<Rightarrow> t \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c, s\<rangle> =n\<Rightarrow> t" apply (cases s) apply (fastforce intro: execn_merge_guards_to_execn_Normal) apply (fastforce dest: execn_Abrupt_end) apply (fastforce dest: execn_Fault_end) apply (fastforce dest: execn_Stuck_end) done corollary execn_iff_execn_merge_guards: "\<Gamma>\<turnstile>\<langle>c, s\<rangle> =n\<Rightarrow> t = \<Gamma>\<turnstile>\<langle>merge_guards c,s\<rangle> =n\<Rightarrow> t" by (blast intro: execn_merge_guards_to_execn execn_to_execn_merge_guards) theorem exec_iff_exec_merge_guards: "\<Gamma>\<turnstile>\<langle>c, s\<rangle> \<Rightarrow> t = \<Gamma>\<turnstile>\<langle>merge_guards c,s\<rangle> \<Rightarrow> t" by (blast dest: exec_to_execn intro: execn_to_exec intro: execn_to_execn_merge_guards execn_merge_guards_to_execn) corollary exec_to_exec_merge_guards: "\<Gamma>\<turnstile>\<langle>c, s\<rangle> \<Rightarrow> t \<Longrightarrow> \<Gamma>\<turnstile>\<langle>merge_guards c,s\<rangle> \<Rightarrow> t" by (rule iffD1 [OF exec_iff_exec_merge_guards]) corollary exec_merge_guards_to_exec: "\<Gamma>\<turnstile>\<langle>merge_guards c,s\<rangle> \<Rightarrow> t \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c, s\<rangle> \<Rightarrow> t" by (rule iffD2 [OF exec_iff_exec_merge_guards]) (* ************************************************************************* *) subsection \<open>Lemmas about @{const "mark_guards"}\<close> (* ************************************************************************ *) lemma execn_to_execn_mark_guards: assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" assumes t_not_Fault: "\<not> isFault t" shows "\<Gamma>\<turnstile>\<langle>mark_guards f c,s\<rangle> =n\<Rightarrow> t " using exec_c t_not_Fault [simplified not_isFault_iff] by (induct) (auto intro: execn.intros dest: noFaultn_startD') lemma execn_to_execn_mark_guards_Fault: assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" shows "\<And>f. \<lbrakk>t=Fault f\<rbrakk> \<Longrightarrow> \<exists>f'. \<Gamma>\<turnstile>\<langle>mark_guards x c,s\<rangle> =n\<Rightarrow> Fault f'" using exec_c proof (induct) case Skip thus ?case by auto next case Guard thus ?case by (fastforce intro: execn.intros) next case GuardFault thus ?case by (fastforce intro: execn.intros) next case FaultProp thus ?case by auto next case Basic thus ?case by auto next case Spec thus ?case by auto next case SpecStuck thus ?case by auto next case (Seq c1 s n w c2 t) have exec_c1: "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> =n\<Rightarrow> w" by fact have exec_c2: "\<Gamma>\<turnstile>\<langle>c2,w\<rangle> =n\<Rightarrow> t" by fact have t: "t=Fault f" by fact show ?case proof (cases w) case (Fault f') with exec_c2 t have "f'=f" by (auto dest: execn_Fault_end) with Fault Seq.hyps obtain f'' where "\<Gamma>\<turnstile>\<langle>mark_guards x c1,Normal s\<rangle> =n\<Rightarrow> Fault f''" by auto moreover have "\<Gamma>\<turnstile>\<langle>mark_guards x c2,Fault f''\<rangle> =n\<Rightarrow> Fault f''" by auto ultimately show ?thesis by (auto intro: execn.intros) next case (Normal s') with execn_to_execn_mark_guards [OF exec_c1] have exec_mark_c1: "\<Gamma>\<turnstile>\<langle>mark_guards x c1,Normal s\<rangle> =n\<Rightarrow> w" by simp with Seq.hyps t obtain f' where "\<Gamma>\<turnstile>\<langle>mark_guards x c2,w\<rangle> =n\<Rightarrow> Fault f'" by blast with exec_mark_c1 show ?thesis by (auto intro: execn.intros) next case (Abrupt s') with execn_to_execn_mark_guards [OF exec_c1] have exec_mark_c1: "\<Gamma>\<turnstile>\<langle>mark_guards x c1,Normal s\<rangle> =n\<Rightarrow> w" by simp with Seq.hyps t obtain f' where "\<Gamma>\<turnstile>\<langle>mark_guards x c2,w\<rangle> =n\<Rightarrow> Fault f'" by (auto intro: execn.intros) with exec_mark_c1 show ?thesis by (auto intro: execn.intros) next case Stuck with exec_c2 have "t=Stuck" by (auto dest: execn_Stuck_end) with t show ?thesis by simp qed next case CondTrue thus ?case by (fastforce intro: execn.intros) next case CondFalse thus ?case by (fastforce intro: execn.intros) next case (WhileTrue s b c n w t) have exec_c: "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> w" by fact have exec_w: "\<Gamma>\<turnstile>\<langle>While b c,w\<rangle> =n\<Rightarrow> t" by fact have t: "t = Fault f" by fact have s_in_b: "s \<in> b" by fact show ?case proof (cases w) case (Fault f') with exec_w t have "f'=f" by (auto dest: execn_Fault_end) with Fault WhileTrue.hyps obtain f'' where "\<Gamma>\<turnstile>\<langle>mark_guards x c,Normal s\<rangle> =n\<Rightarrow> Fault f''" by auto moreover have "\<Gamma>\<turnstile>\<langle>mark_guards x (While b c),Fault f''\<rangle> =n\<Rightarrow> Fault f''" by auto ultimately show ?thesis using s_in_b by (auto intro: execn.intros) next case (Normal s') with execn_to_execn_mark_guards [OF exec_c] have exec_mark_c: "\<Gamma>\<turnstile>\<langle>mark_guards x c,Normal s\<rangle> =n\<Rightarrow> w" by simp with WhileTrue.hyps t obtain f' where "\<Gamma>\<turnstile>\<langle>mark_guards x (While b c),w\<rangle> =n\<Rightarrow> Fault f'" by blast with exec_mark_c s_in_b show ?thesis by (auto intro: execn.intros) next case (Abrupt s') with execn_to_execn_mark_guards [OF exec_c] have exec_mark_c: "\<Gamma>\<turnstile>\<langle>mark_guards x c,Normal s\<rangle> =n\<Rightarrow> w" by simp with WhileTrue.hyps t obtain f' where "\<Gamma>\<turnstile>\<langle>mark_guards x (While b c),w\<rangle> =n\<Rightarrow> Fault f'" by (auto intro: execn.intros) with exec_mark_c s_in_b show ?thesis by (auto intro: execn.intros) next case Stuck with exec_w have "t=Stuck" by (auto dest: execn_Stuck_end) with t show ?thesis by simp qed next case WhileFalse thus ?case by (fastforce intro: execn.intros) next case Call thus ?case by (fastforce intro: execn.intros) next case CallUndefined thus ?case by simp next case StuckProp thus ?case by simp next case DynCom thus ?case by (fastforce intro: execn.intros) next case Throw thus ?case by simp next case AbruptProp thus ?case by simp next case (CatchMatch c1 s n w c2 t) have exec_c1: "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> =n\<Rightarrow> Abrupt w" by fact have exec_c2: "\<Gamma>\<turnstile>\<langle>c2,Normal w\<rangle> =n\<Rightarrow> t" by fact have t: "t = Fault f" by fact from execn_to_execn_mark_guards [OF exec_c1] have exec_mark_c1: "\<Gamma>\<turnstile>\<langle>mark_guards x c1,Normal s\<rangle> =n\<Rightarrow> Abrupt w" by simp with CatchMatch.hyps t obtain f' where "\<Gamma>\<turnstile>\<langle>mark_guards x c2,Normal w\<rangle> =n\<Rightarrow> Fault f'" by blast with exec_mark_c1 show ?case by (auto intro: execn.intros) next case CatchMiss thus ?case by (fastforce intro: execn.intros) qed lemma execn_mark_guards_to_execn: "\<And>s n t. \<Gamma>\<turnstile>\<langle>mark_guards f c,s\<rangle> =n\<Rightarrow> t \<Longrightarrow> \<exists>t'. \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t' \<and> (isFault t \<longrightarrow> isFault t') \<and> (t' = Fault f \<longrightarrow> t'=t) \<and> (isFault t' \<longrightarrow> isFault t) \<and> (\<not> isFault t' \<longrightarrow> t'=t)" proof (induct c) case Skip thus ?case by auto next case Basic thus ?case by auto next case Spec thus ?case by auto next case (Seq c1 c2 s n t) have exec_mark: "\<Gamma>\<turnstile>\<langle>mark_guards f (Seq c1 c2),s\<rangle> =n\<Rightarrow> t" by fact then obtain w where exec_mark_c1: "\<Gamma>\<turnstile>\<langle>mark_guards f c1,s\<rangle> =n\<Rightarrow> w" and exec_mark_c2: "\<Gamma>\<turnstile>\<langle>mark_guards f c2,w\<rangle> =n\<Rightarrow> t" by (auto elim: execn_elim_cases) from Seq.hyps exec_mark_c1 obtain w' where exec_c1: "\<Gamma>\<turnstile>\<langle>c1,s\<rangle> =n\<Rightarrow> w'" and w_Fault: "isFault w \<longrightarrow> isFault w'" and w'_Fault_f: "w' = Fault f \<longrightarrow> w'=w" and w'_Fault: "isFault w' \<longrightarrow> isFault w" and w'_noFault: "\<not> isFault w' \<longrightarrow> w'=w" by blast show ?case proof (cases "s") case (Fault f) with exec_mark have "t=Fault f" by (auto dest: execn_Fault_end) with Fault show ?thesis by auto next case Stuck with exec_mark have "t=Stuck" by (auto dest: execn_Stuck_end) with Stuck show ?thesis by auto next case (Abrupt s') with exec_mark have "t=Abrupt s'" by (auto dest: execn_Abrupt_end) with Abrupt show ?thesis by auto next case (Normal s') show ?thesis proof (cases "isFault w") case True then obtain f where w': "w=Fault f".. moreover with exec_mark_c2 have t: "t=Fault f" by (auto dest: execn_Fault_end) ultimately show ?thesis using Normal w_Fault w'_Fault_f exec_c1 by (fastforce intro: execn.intros elim: isFaultE) next case False note noFault_w = this show ?thesis proof (cases "isFault w'") case True then obtain f' where w': "w'=Fault f'".. with Normal exec_c1 have exec: "\<Gamma>\<turnstile>\<langle>Seq c1 c2,s\<rangle> =n\<Rightarrow> Fault f'" by (auto intro: execn.intros) from w'_Fault_f w' noFault_w have "f' \<noteq> f" by (cases w) auto moreover from w' w'_Fault exec_mark_c2 have "isFault t" by (auto dest: execn_Fault_end elim: isFaultE) ultimately show ?thesis using exec by auto next case False with w'_noFault have w': "w'=w" by simp from Seq.hyps exec_mark_c2 obtain t' where "\<Gamma>\<turnstile>\<langle>c2,w\<rangle> =n\<Rightarrow> t'" and "isFault t \<longrightarrow> isFault t'" and "t' = Fault f \<longrightarrow> t'=t" and "isFault t' \<longrightarrow> isFault t" and "\<not> isFault t' \<longrightarrow> t'=t" by blast with Normal exec_c1 w' show ?thesis by (fastforce intro: execn.intros) qed qed qed next case (Cond b c1 c2 s n t) have exec_mark: "\<Gamma>\<turnstile>\<langle>mark_guards f (Cond b c1 c2),s\<rangle> =n\<Rightarrow> t" by fact show ?case proof (cases s) case (Fault f) with exec_mark have "t=Fault f" by (auto dest: execn_Fault_end) with Fault show ?thesis by auto next case Stuck with exec_mark have "t=Stuck" by (auto dest: execn_Stuck_end) with Stuck show ?thesis by auto next case (Abrupt s') with exec_mark have "t=Abrupt s'" by (auto dest: execn_Abrupt_end) with Abrupt show ?thesis by auto next case (Normal s') show ?thesis proof (cases "s'\<in> b") case True with Normal exec_mark have "\<Gamma>\<turnstile>\<langle>mark_guards f c1 ,Normal s'\<rangle> =n\<Rightarrow> t" by (auto elim: execn_Normal_elim_cases) with Normal True Cond.hyps obtain t' where "\<Gamma>\<turnstile>\<langle>c1,Normal s'\<rangle> =n\<Rightarrow> t'" "isFault t \<longrightarrow> isFault t'" "t' = Fault f \<longrightarrow> t'=t" "isFault t' \<longrightarrow> isFault t" "\<not> isFault t' \<longrightarrow> t' = t" by blast with Normal True show ?thesis by (blast intro: execn.intros) next case False with Normal exec_mark have "\<Gamma>\<turnstile>\<langle>mark_guards f c2 ,Normal s'\<rangle> =n\<Rightarrow> t" by (auto elim: execn_Normal_elim_cases) with Normal False Cond.hyps obtain t' where "\<Gamma>\<turnstile>\<langle>c2,Normal s'\<rangle> =n\<Rightarrow> t'" "isFault t \<longrightarrow> isFault t'" "t' = Fault f \<longrightarrow> t'=t" "isFault t' \<longrightarrow> isFault t" "\<not> isFault t' \<longrightarrow> t' = t" by blast with Normal False show ?thesis by (blast intro: execn.intros) qed qed next case (While b c s n t) have exec_mark: "\<Gamma>\<turnstile>\<langle>mark_guards f (While b c),s\<rangle> =n\<Rightarrow> t" by fact show ?case proof (cases s) case (Fault f) with exec_mark have "t=Fault f" by (auto dest: execn_Fault_end) with Fault show ?thesis by auto next case Stuck with exec_mark have "t=Stuck" by (auto dest: execn_Stuck_end) with Stuck show ?thesis by auto next case (Abrupt s') with exec_mark have "t=Abrupt s'" by (auto dest: execn_Abrupt_end) with Abrupt show ?thesis by auto next case (Normal s') { fix c' r w assume exec_c': "\<Gamma>\<turnstile>\<langle>c',r\<rangle> =n\<Rightarrow> w" assume c': "c'=While b (mark_guards f c)" have "\<exists>w'. \<Gamma>\<turnstile>\<langle>While b c,r\<rangle> =n\<Rightarrow> w' \<and> (isFault w \<longrightarrow> isFault w') \<and> (w' = Fault f \<longrightarrow> w'=w) \<and> (isFault w' \<longrightarrow> isFault w) \<and> (\<not> isFault w' \<longrightarrow> w'=w)" using exec_c' c' proof (induct) case (WhileTrue r b' c'' n u w) have eqs: "While b' c'' = While b (mark_guards f c)" by fact from WhileTrue.hyps eqs have r_in_b: "r\<in>b" by simp from WhileTrue.hyps eqs have exec_mark_c: "\<Gamma>\<turnstile>\<langle>mark_guards f c,Normal r\<rangle> =n\<Rightarrow> u" by simp from WhileTrue.hyps eqs have exec_mark_w: "\<Gamma>\<turnstile>\<langle>While b (mark_guards f c),u\<rangle> =n\<Rightarrow> w" by simp show ?case proof - from WhileTrue.hyps eqs have "\<Gamma>\<turnstile>\<langle>mark_guards f c,Normal r\<rangle> =n\<Rightarrow> u" by simp with While.hyps obtain u' where exec_c: "\<Gamma>\<turnstile>\<langle>c,Normal r\<rangle> =n\<Rightarrow> u'" and u_Fault: "isFault u \<longrightarrow> isFault u'" and u'_Fault_f: "u' = Fault f \<longrightarrow> u'=u" and u'_Fault: "isFault u' \<longrightarrow> isFault u" and u'_noFault: "\<not> isFault u' \<longrightarrow> u'=u" by blast show ?thesis proof (cases "isFault u'") case False with u'_noFault have u': "u'=u" by simp from WhileTrue.hyps eqs obtain w' where "\<Gamma>\<turnstile>\<langle>While b c,u\<rangle> =n\<Rightarrow> w'" "isFault w \<longrightarrow> isFault w'" "w' = Fault f \<longrightarrow> w'=w" "isFault w' \<longrightarrow> isFault w" "\<not> isFault w' \<longrightarrow> w' = w" by blast with u' exec_c r_in_b show ?thesis by (blast intro: execn.WhileTrue) next case True then obtain f' where u': "u'=Fault f'".. with exec_c r_in_b have exec: "\<Gamma>\<turnstile>\<langle>While b c,Normal r\<rangle> =n\<Rightarrow> Fault f'" by (blast intro: execn.intros) from True u'_Fault have "isFault u" by simp then obtain f where u: "u=Fault f".. with exec_mark_w have "w=Fault f" by (auto dest: execn_Fault_end) with exec u' u u'_Fault_f show ?thesis by auto qed qed next case (WhileFalse r b' c'' n) have eqs: "While b' c'' = While b (mark_guards f c)" by fact from WhileFalse.hyps eqs have r_not_in_b: "r\<notin>b" by simp show ?case proof - from r_not_in_b have "\<Gamma>\<turnstile>\<langle>While b c,Normal r\<rangle> =n\<Rightarrow> Normal r" by (rule execn.WhileFalse) thus ?thesis by blast qed qed auto } note hyp_while = this show ?thesis proof (cases "s'\<in>b") case False with Normal exec_mark have "t=s" by (auto elim: execn_Normal_elim_cases) with Normal False show ?thesis by (auto intro: execn.intros) next case True note s'_in_b = this with Normal exec_mark obtain r where exec_mark_c: "\<Gamma>\<turnstile>\<langle>mark_guards f c,Normal s'\<rangle> =n\<Rightarrow> r" and exec_mark_w: "\<Gamma>\<turnstile>\<langle>While b (mark_guards f c),r\<rangle> =n\<Rightarrow> t" by (auto elim: execn_Normal_elim_cases) from While.hyps exec_mark_c obtain r' where exec_c: "\<Gamma>\<turnstile>\<langle>c,Normal s'\<rangle> =n\<Rightarrow> r'" and r_Fault: "isFault r \<longrightarrow> isFault r'" and r'_Fault_f: "r' = Fault f \<longrightarrow> r'=r" and r'_Fault: "isFault r' \<longrightarrow> isFault r" and r'_noFault: "\<not> isFault r' \<longrightarrow> r'=r" by blast show ?thesis proof (cases "isFault r'") case False with r'_noFault have r': "r'=r" by simp from hyp_while exec_mark_w obtain t' where "\<Gamma>\<turnstile>\<langle>While b c,r\<rangle> =n\<Rightarrow> t'" "isFault t \<longrightarrow> isFault t'" "t' = Fault f \<longrightarrow> t'=t" "isFault t' \<longrightarrow> isFault t" "\<not> isFault t' \<longrightarrow> t'=t" by blast with r' exec_c Normal s'_in_b show ?thesis by (blast intro: execn.intros) next case True then obtain f' where r': "r'=Fault f'".. hence "\<Gamma>\<turnstile>\<langle>While b c,r'\<rangle> =n\<Rightarrow> Fault f'" by auto with Normal s'_in_b exec_c have exec: "\<Gamma>\<turnstile>\<langle>While b c,Normal s'\<rangle> =n\<Rightarrow> Fault f'" by (auto intro: execn.intros) from True r'_Fault have "isFault r" by simp then obtain f where r: "r=Fault f".. with exec_mark_w have "t=Fault f" by (auto dest: execn_Fault_end) with Normal exec r' r r'_Fault_f show ?thesis by auto qed qed qed next case Call thus ?case by auto next case DynCom thus ?case by (fastforce elim!: execn_elim_cases intro: execn.intros) next case (Guard f' g c s n t) have exec_mark: "\<Gamma>\<turnstile>\<langle>mark_guards f (Guard f' g c),s\<rangle> =n\<Rightarrow> t" by fact show ?case proof (cases s) case (Fault f) with exec_mark have "t=Fault f" by (auto dest: execn_Fault_end) with Fault show ?thesis by auto next case Stuck with exec_mark have "t=Stuck" by (auto dest: execn_Stuck_end) with Stuck show ?thesis by auto next case (Abrupt s') with exec_mark have "t=Abrupt s'" by (auto dest: execn_Abrupt_end) with Abrupt show ?thesis by auto next case (Normal s') show ?thesis proof (cases "s'\<in>g") case False with Normal exec_mark have t: "t=Fault f" by (auto elim: execn_Normal_elim_cases) from False have "\<Gamma>\<turnstile>\<langle>Guard f' g c,Normal s'\<rangle> =n\<Rightarrow> Fault f'" by (blast intro: execn.intros) with Normal t show ?thesis by auto next case True with exec_mark Normal have "\<Gamma>\<turnstile>\<langle>mark_guards f c,Normal s'\<rangle> =n\<Rightarrow> t" by (auto elim: execn_Normal_elim_cases) with Guard.hyps obtain t' where "\<Gamma>\<turnstile>\<langle>c,Normal s'\<rangle> =n\<Rightarrow> t'" and "isFault t \<longrightarrow> isFault t'" and "t' = Fault f \<longrightarrow> t'=t" and "isFault t' \<longrightarrow> isFault t" and "\<not> isFault t' \<longrightarrow> t'=t" by blast with Normal True show ?thesis by (blast intro: execn.intros) qed qed next case Throw thus ?case by auto next case (Catch c1 c2 s n t) have exec_mark: "\<Gamma>\<turnstile>\<langle>mark_guards f (Catch c1 c2),s\<rangle> =n\<Rightarrow> t" by fact show ?case proof (cases "s") case (Fault f) with exec_mark have "t=Fault f" by (auto dest: execn_Fault_end) with Fault show ?thesis by auto next case Stuck with exec_mark have "t=Stuck" by (auto dest: execn_Stuck_end) with Stuck show ?thesis by auto next case (Abrupt s') with exec_mark have "t=Abrupt s'" by (auto dest: execn_Abrupt_end) with Abrupt show ?thesis by auto next case (Normal s') note s=this with exec_mark have "\<Gamma>\<turnstile>\<langle>Catch (mark_guards f c1) (mark_guards f c2),Normal s'\<rangle> =n\<Rightarrow> t" by simp thus ?thesis proof (cases) fix w assume exec_mark_c1: "\<Gamma>\<turnstile>\<langle>mark_guards f c1,Normal s'\<rangle> =n\<Rightarrow> Abrupt w" assume exec_mark_c2: "\<Gamma>\<turnstile>\<langle>mark_guards f c2,Normal w\<rangle> =n\<Rightarrow> t" from exec_mark_c1 Catch.hyps obtain w' where exec_c1: "\<Gamma>\<turnstile>\<langle>c1,Normal s'\<rangle> =n\<Rightarrow> w'" and w'_Fault_f: "w' = Fault f \<longrightarrow> w'=Abrupt w" and w'_Fault: "isFault w' \<longrightarrow> isFault (Abrupt w)" and w'_noFault: "\<not> isFault w' \<longrightarrow> w'=Abrupt w" by fastforce show ?thesis proof (cases "w'") case (Fault f') with Normal exec_c1 have "\<Gamma>\<turnstile>\<langle>Catch c1 c2,s\<rangle> =n\<Rightarrow> Fault f'" by (auto intro: execn.intros) with w'_Fault Fault show ?thesis by auto next case Stuck with w'_noFault have False by simp thus ?thesis .. next case (Normal w'') with w'_noFault have False by simp thus ?thesis .. next case (Abrupt w'') with w'_noFault have w'': "w''=w" by simp from exec_mark_c2 Catch.hyps obtain t' where "\<Gamma>\<turnstile>\<langle>c2,Normal w\<rangle> =n\<Rightarrow> t'" "isFault t \<longrightarrow> isFault t'" "t' = Fault f \<longrightarrow> t'=t" "isFault t' \<longrightarrow> isFault t" "\<not> isFault t' \<longrightarrow> t'=t" by blast with w'' Abrupt s exec_c1 show ?thesis by (blast intro: execn.intros) qed next assume t: "\<not> isAbr t" assume "\<Gamma>\<turnstile>\<langle>mark_guards f c1,Normal s'\<rangle> =n\<Rightarrow> t" with Catch.hyps obtain t' where exec_c1: "\<Gamma>\<turnstile>\<langle>c1,Normal s'\<rangle> =n\<Rightarrow> t'" and t_Fault: "isFault t \<longrightarrow> isFault t'" and t'_Fault_f: "t' = Fault f \<longrightarrow> t'=t" and t'_Fault: "isFault t' \<longrightarrow> isFault t" and t'_noFault: "\<not> isFault t' \<longrightarrow> t'=t" by blast show ?thesis proof (cases "isFault t'") case True then obtain f' where t': "t'=Fault f'".. with exec_c1 have "\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s'\<rangle> =n\<Rightarrow> Fault f'" by (auto intro: execn.intros) with t'_Fault_f t'_Fault t' s show ?thesis by auto next case False with t'_noFault have "t'=t" by simp with t exec_c1 s show ?thesis by (blast intro: execn.intros) qed qed qed qed lemma exec_to_exec_mark_guards: assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" assumes t_not_Fault: "\<not> isFault t" shows "\<Gamma>\<turnstile>\<langle>mark_guards f c,s\<rangle> \<Rightarrow> t " proof - from exec_to_execn [OF exec_c] obtain n where "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" .. from execn_to_execn_mark_guards [OF this t_not_Fault] show ?thesis by (blast intro: execn_to_exec) qed lemma exec_to_exec_mark_guards_Fault: assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> Fault f" shows "\<exists>f'. \<Gamma>\<turnstile>\<langle>mark_guards x c,s\<rangle> \<Rightarrow> Fault f'" proof - from exec_to_execn [OF exec_c] obtain n where "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> Fault f" .. from execn_to_execn_mark_guards_Fault [OF this] show ?thesis by (blast intro: execn_to_exec) qed lemma exec_mark_guards_to_exec: assumes exec_mark: "\<Gamma>\<turnstile>\<langle>mark_guards f c,s\<rangle> \<Rightarrow> t" shows "\<exists>t'. \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t' \<and> (isFault t \<longrightarrow> isFault t') \<and> (t' = Fault f \<longrightarrow> t'=t) \<and> (isFault t' \<longrightarrow> isFault t) \<and> (\<not> isFault t' \<longrightarrow> t'=t)" proof - from exec_to_execn [OF exec_mark] obtain n where "\<Gamma>\<turnstile>\<langle>mark_guards f c,s\<rangle> =n\<Rightarrow> t" .. from execn_mark_guards_to_execn [OF this] show ?thesis by (blast intro: execn_to_exec) qed (* ************************************************************************* *) subsection \<open>Lemmas about @{const "strip_guards"}\<close> (* ************************************************************************* *) lemma execn_to_execn_strip_guards: assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" assumes t_not_Fault: "\<not> isFault t" shows "\<Gamma>\<turnstile>\<langle>strip_guards F c,s\<rangle> =n\<Rightarrow> t " using exec_c t_not_Fault [simplified not_isFault_iff] by (induct) (auto intro: execn.intros dest: noFaultn_startD') lemma execn_to_execn_strip_guards_Fault: assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" shows "\<And>f. \<lbrakk>t=Fault f; f \<notin> F\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>strip_guards F c,s\<rangle> =n\<Rightarrow> Fault f" using exec_c proof (induct) case Skip thus ?case by auto next case Guard thus ?case by (fastforce intro: execn.intros) next case GuardFault thus ?case by (fastforce intro: execn.intros) next case FaultProp thus ?case by auto next case Basic thus ?case by auto next case Spec thus ?case by auto next case SpecStuck thus ?case by auto next case (Seq c1 s n w c2 t) have exec_c1: "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> =n\<Rightarrow> w" by fact have exec_c2: "\<Gamma>\<turnstile>\<langle>c2,w\<rangle> =n\<Rightarrow> t" by fact have t: "t=Fault f" by fact have notinF: "f \<notin> F" by fact show ?case proof (cases w) case (Fault f') with exec_c2 t have "f'=f" by (auto dest: execn_Fault_end) with Fault notinF Seq.hyps have "\<Gamma>\<turnstile>\<langle>strip_guards F c1,Normal s\<rangle> =n\<Rightarrow> Fault f" by auto moreover have "\<Gamma>\<turnstile>\<langle>strip_guards F c2,Fault f\<rangle> =n\<Rightarrow> Fault f" by auto ultimately show ?thesis by (auto intro: execn.intros) next case (Normal s') with execn_to_execn_strip_guards [OF exec_c1] have exec_strip_c1: "\<Gamma>\<turnstile>\<langle>strip_guards F c1,Normal s\<rangle> =n\<Rightarrow> w" by simp with Seq.hyps t notinF have "\<Gamma>\<turnstile>\<langle>strip_guards F c2,w\<rangle> =n\<Rightarrow> Fault f" by blast with exec_strip_c1 show ?thesis by (auto intro: execn.intros) next case (Abrupt s') with execn_to_execn_strip_guards [OF exec_c1] have exec_strip_c1: "\<Gamma>\<turnstile>\<langle>strip_guards F c1,Normal s\<rangle> =n\<Rightarrow> w" by simp with Seq.hyps t notinF have "\<Gamma>\<turnstile>\<langle>strip_guards F c2,w\<rangle> =n\<Rightarrow> Fault f" by (auto intro: execn.intros) with exec_strip_c1 show ?thesis by (auto intro: execn.intros) next case Stuck with exec_c2 have "t=Stuck" by (auto dest: execn_Stuck_end) with t show ?thesis by simp qed next case CondTrue thus ?case by (fastforce intro: execn.intros) next case CondFalse thus ?case by (fastforce intro: execn.intros) next case (WhileTrue s b c n w t) have exec_c: "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> w" by fact have exec_w: "\<Gamma>\<turnstile>\<langle>While b c,w\<rangle> =n\<Rightarrow> t" by fact have t: "t = Fault f" by fact have notinF: "f \<notin> F" by fact have s_in_b: "s \<in> b" by fact show ?case proof (cases w) case (Fault f') with exec_w t have "f'=f" by (auto dest: execn_Fault_end) with Fault notinF WhileTrue.hyps have "\<Gamma>\<turnstile>\<langle>strip_guards F c,Normal s\<rangle> =n\<Rightarrow> Fault f" by auto moreover have "\<Gamma>\<turnstile>\<langle>strip_guards F (While b c),Fault f\<rangle> =n\<Rightarrow> Fault f" by auto ultimately show ?thesis using s_in_b by (auto intro: execn.intros) next case (Normal s') with execn_to_execn_strip_guards [OF exec_c] have exec_strip_c: "\<Gamma>\<turnstile>\<langle>strip_guards F c,Normal s\<rangle> =n\<Rightarrow> w" by simp with WhileTrue.hyps t notinF have "\<Gamma>\<turnstile>\<langle>strip_guards F (While b c),w\<rangle> =n\<Rightarrow> Fault f" by blast with exec_strip_c s_in_b show ?thesis by (auto intro: execn.intros) next case (Abrupt s') with execn_to_execn_strip_guards [OF exec_c] have exec_strip_c: "\<Gamma>\<turnstile>\<langle>strip_guards F c,Normal s\<rangle> =n\<Rightarrow> w" by simp with WhileTrue.hyps t notinF have "\<Gamma>\<turnstile>\<langle>strip_guards F (While b c),w\<rangle> =n\<Rightarrow> Fault f" by (auto intro: execn.intros) with exec_strip_c s_in_b show ?thesis by (auto intro: execn.intros) next case Stuck with exec_w have "t=Stuck" by (auto dest: execn_Stuck_end) with t show ?thesis by simp qed next case WhileFalse thus ?case by (fastforce intro: execn.intros) next case Call thus ?case by (fastforce intro: execn.intros) next case CallUndefined thus ?case by simp next case StuckProp thus ?case by simp next case DynCom thus ?case by (fastforce intro: execn.intros) next case Throw thus ?case by simp next case AbruptProp thus ?case by simp next case (CatchMatch c1 s n w c2 t) have exec_c1: "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> =n\<Rightarrow> Abrupt w" by fact have exec_c2: "\<Gamma>\<turnstile>\<langle>c2,Normal w\<rangle> =n\<Rightarrow> t" by fact have t: "t = Fault f" by fact have notinF: "f \<notin> F" by fact from execn_to_execn_strip_guards [OF exec_c1] have exec_strip_c1: "\<Gamma>\<turnstile>\<langle>strip_guards F c1,Normal s\<rangle> =n\<Rightarrow> Abrupt w" by simp with CatchMatch.hyps t notinF have "\<Gamma>\<turnstile>\<langle>strip_guards F c2,Normal w\<rangle> =n\<Rightarrow> Fault f" by blast with exec_strip_c1 show ?case by (auto intro: execn.intros) next case CatchMiss thus ?case by (fastforce intro: execn.intros) qed lemma execn_to_execn_strip_guards': assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" assumes t_not_Fault: "t \<notin> Fault ` F" shows "\<Gamma>\<turnstile>\<langle>strip_guards F c,s\<rangle> =n\<Rightarrow> t" proof (cases t) case (Fault f) with t_not_Fault exec_c show ?thesis by (auto intro: execn_to_execn_strip_guards_Fault) qed (insert exec_c, auto intro: execn_to_execn_strip_guards) lemma execn_strip_guards_to_execn: "\<And>s n t. \<Gamma>\<turnstile>\<langle>strip_guards F c,s\<rangle> =n\<Rightarrow> t \<Longrightarrow> \<exists>t'. \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t' \<and> (isFault t \<longrightarrow> isFault t') \<and> (t' \<in> Fault ` (- F) \<longrightarrow> t'=t) \<and> (\<not> isFault t' \<longrightarrow> t'=t)" proof (induct c) case Skip thus ?case by auto next case Basic thus ?case by auto next case Spec thus ?case by auto next case (Seq c1 c2 s n t) have exec_strip: "\<Gamma>\<turnstile>\<langle>strip_guards F (Seq c1 c2),s\<rangle> =n\<Rightarrow> t" by fact then obtain w where exec_strip_c1: "\<Gamma>\<turnstile>\<langle>strip_guards F c1,s\<rangle> =n\<Rightarrow> w" and exec_strip_c2: "\<Gamma>\<turnstile>\<langle>strip_guards F c2,w\<rangle> =n\<Rightarrow> t" by (auto elim: execn_elim_cases) from Seq.hyps exec_strip_c1 obtain w' where exec_c1: "\<Gamma>\<turnstile>\<langle>c1,s\<rangle> =n\<Rightarrow> w'" and w_Fault: "isFault w \<longrightarrow> isFault w'" and w'_Fault: "w' \<in> Fault ` (- F) \<longrightarrow> w'=w" and w'_noFault: "\<not> isFault w' \<longrightarrow> w'=w" by blast show ?case proof (cases "s") case (Fault f) with exec_strip have "t=Fault f" by (auto dest: execn_Fault_end) with Fault show ?thesis by auto next case Stuck with exec_strip have "t=Stuck" by (auto dest: execn_Stuck_end) with Stuck show ?thesis by auto next case (Abrupt s') with exec_strip have "t=Abrupt s'" by (auto dest: execn_Abrupt_end) with Abrupt show ?thesis by auto next case (Normal s') show ?thesis proof (cases "isFault w") case True then obtain f where w': "w=Fault f".. moreover with exec_strip_c2 have t: "t=Fault f" by (auto dest: execn_Fault_end) ultimately show ?thesis using Normal w_Fault w'_Fault exec_c1 by (fastforce intro: execn.intros elim: isFaultE) next case False note noFault_w = this show ?thesis proof (cases "isFault w'") case True then obtain f' where w': "w'=Fault f'".. with Normal exec_c1 have exec: "\<Gamma>\<turnstile>\<langle>Seq c1 c2,s\<rangle> =n\<Rightarrow> Fault f'" by (auto intro: execn.intros) from w'_Fault w' noFault_w have "f' \<in> F" by (cases w) auto with exec show ?thesis by auto next case False with w'_noFault have w': "w'=w" by simp from Seq.hyps exec_strip_c2 obtain t' where "\<Gamma>\<turnstile>\<langle>c2,w\<rangle> =n\<Rightarrow> t'" and "isFault t \<longrightarrow> isFault t'" and "t' \<in> Fault ` (-F) \<longrightarrow> t'=t" and "\<not> isFault t' \<longrightarrow> t'=t" by blast with Normal exec_c1 w' show ?thesis by (fastforce intro: execn.intros) qed qed qed next next case (Cond b c1 c2 s n t) have exec_strip: "\<Gamma>\<turnstile>\<langle>strip_guards F (Cond b c1 c2),s\<rangle> =n\<Rightarrow> t" by fact show ?case proof (cases s) case (Fault f) with exec_strip have "t=Fault f" by (auto dest: execn_Fault_end) with Fault show ?thesis by auto next case Stuck with exec_strip have "t=Stuck" by (auto dest: execn_Stuck_end) with Stuck show ?thesis by auto next case (Abrupt s') with exec_strip have "t=Abrupt s'" by (auto dest: execn_Abrupt_end) with Abrupt show ?thesis by auto next case (Normal s') show ?thesis proof (cases "s'\<in> b") case True with Normal exec_strip have "\<Gamma>\<turnstile>\<langle>strip_guards F c1 ,Normal s'\<rangle> =n\<Rightarrow> t" by (auto elim: execn_Normal_elim_cases) with Normal True Cond.hyps obtain t' where "\<Gamma>\<turnstile>\<langle>c1,Normal s'\<rangle> =n\<Rightarrow> t'" "isFault t \<longrightarrow> isFault t'" "t' \<in> Fault ` (-F) \<longrightarrow> t'=t" "\<not> isFault t' \<longrightarrow> t' = t" by blast with Normal True show ?thesis by (blast intro: execn.intros) next case False with Normal exec_strip have "\<Gamma>\<turnstile>\<langle>strip_guards F c2 ,Normal s'\<rangle> =n\<Rightarrow> t" by (auto elim: execn_Normal_elim_cases) with Normal False Cond.hyps obtain t' where "\<Gamma>\<turnstile>\<langle>c2,Normal s'\<rangle> =n\<Rightarrow> t'" "isFault t \<longrightarrow> isFault t'" "t' \<in> Fault ` (-F) \<longrightarrow> t'=t" "\<not> isFault t' \<longrightarrow> t' = t" by blast with Normal False show ?thesis by (blast intro: execn.intros) qed qed next case (While b c s n t) have exec_strip: "\<Gamma>\<turnstile>\<langle>strip_guards F (While b c),s\<rangle> =n\<Rightarrow> t" by fact show ?case proof (cases s) case (Fault f) with exec_strip have "t=Fault f" by (auto dest: execn_Fault_end) with Fault show ?thesis by auto next case Stuck with exec_strip have "t=Stuck" by (auto dest: execn_Stuck_end) with Stuck show ?thesis by auto next case (Abrupt s') with exec_strip have "t=Abrupt s'" by (auto dest: execn_Abrupt_end) with Abrupt show ?thesis by auto next case (Normal s') { fix c' r w assume exec_c': "\<Gamma>\<turnstile>\<langle>c',r\<rangle> =n\<Rightarrow> w" assume c': "c'=While b (strip_guards F c)" have "\<exists>w'. \<Gamma>\<turnstile>\<langle>While b c,r\<rangle> =n\<Rightarrow> w' \<and> (isFault w \<longrightarrow> isFault w') \<and> (w' \<in> Fault ` (-F) \<longrightarrow> w'=w) \<and> (\<not> isFault w' \<longrightarrow> w'=w)" using exec_c' c' proof (induct) case (WhileTrue r b' c'' n u w) have eqs: "While b' c'' = While b (strip_guards F c)" by fact from WhileTrue.hyps eqs have r_in_b: "r\<in>b" by simp from WhileTrue.hyps eqs have exec_strip_c: "\<Gamma>\<turnstile>\<langle>strip_guards F c,Normal r\<rangle> =n\<Rightarrow> u" by simp from WhileTrue.hyps eqs have exec_strip_w: "\<Gamma>\<turnstile>\<langle>While b (strip_guards F c),u\<rangle> =n\<Rightarrow> w" by simp show ?case proof - from WhileTrue.hyps eqs have "\<Gamma>\<turnstile>\<langle>strip_guards F c,Normal r\<rangle> =n\<Rightarrow> u" by simp with While.hyps obtain u' where exec_c: "\<Gamma>\<turnstile>\<langle>c,Normal r\<rangle> =n\<Rightarrow> u'" and u_Fault: "isFault u \<longrightarrow> isFault u'" and u'_Fault: "u' \<in> Fault ` (-F) \<longrightarrow> u'=u" and u'_noFault: "\<not> isFault u' \<longrightarrow> u'=u" by blast show ?thesis proof (cases "isFault u'") case False with u'_noFault have u': "u'=u" by simp from WhileTrue.hyps eqs obtain w' where "\<Gamma>\<turnstile>\<langle>While b c,u\<rangle> =n\<Rightarrow> w'" "isFault w \<longrightarrow> isFault w'" "w' \<in> Fault ` (-F) \<longrightarrow> w'=w" "\<not> isFault w' \<longrightarrow> w' = w" by blast with u' exec_c r_in_b show ?thesis by (blast intro: execn.WhileTrue) next case True then obtain f' where u': "u'=Fault f'".. with exec_c r_in_b have exec: "\<Gamma>\<turnstile>\<langle>While b c,Normal r\<rangle> =n\<Rightarrow> Fault f'" by (blast intro: execn.intros) show ?thesis proof (cases "isFault u") case True then obtain f where u: "u=Fault f".. with exec_strip_w have "w=Fault f" by (auto dest: execn_Fault_end) with exec u' u u'_Fault show ?thesis by auto next case False with u'_Fault u' have "f' \<in> F" by (cases u) auto with exec show ?thesis by auto qed qed qed next case (WhileFalse r b' c'' n) have eqs: "While b' c'' = While b (strip_guards F c)" by fact from WhileFalse.hyps eqs have r_not_in_b: "r\<notin>b" by simp show ?case proof - from r_not_in_b have "\<Gamma>\<turnstile>\<langle>While b c,Normal r\<rangle> =n\<Rightarrow> Normal r" by (rule execn.WhileFalse) thus ?thesis by blast qed qed auto } note hyp_while = this show ?thesis proof (cases "s'\<in>b") case False with Normal exec_strip have "t=s" by (auto elim: execn_Normal_elim_cases) with Normal False show ?thesis by (auto intro: execn.intros) next case True note s'_in_b = this with Normal exec_strip obtain r where exec_strip_c: "\<Gamma>\<turnstile>\<langle>strip_guards F c,Normal s'\<rangle> =n\<Rightarrow> r" and exec_strip_w: "\<Gamma>\<turnstile>\<langle>While b (strip_guards F c),r\<rangle> =n\<Rightarrow> t" by (auto elim: execn_Normal_elim_cases) from While.hyps exec_strip_c obtain r' where exec_c: "\<Gamma>\<turnstile>\<langle>c,Normal s'\<rangle> =n\<Rightarrow> r'" and r_Fault: "isFault r \<longrightarrow> isFault r'" and r'_Fault: "r' \<in> Fault ` (-F) \<longrightarrow> r'=r" and r'_noFault: "\<not> isFault r' \<longrightarrow> r'=r" by blast show ?thesis proof (cases "isFault r'") case False with r'_noFault have r': "r'=r" by simp from hyp_while exec_strip_w obtain t' where "\<Gamma>\<turnstile>\<langle>While b c,r\<rangle> =n\<Rightarrow> t'" "isFault t \<longrightarrow> isFault t'" "t' \<in> Fault ` (-F) \<longrightarrow> t'=t" "\<not> isFault t' \<longrightarrow> t'=t" by blast with r' exec_c Normal s'_in_b show ?thesis by (blast intro: execn.intros) next case True then obtain f' where r': "r'=Fault f'".. hence "\<Gamma>\<turnstile>\<langle>While b c,r'\<rangle> =n\<Rightarrow> Fault f'" by auto with Normal s'_in_b exec_c have exec: "\<Gamma>\<turnstile>\<langle>While b c,Normal s'\<rangle> =n\<Rightarrow> Fault f'" by (auto intro: execn.intros) show ?thesis proof (cases "isFault r") case True then obtain f where r: "r=Fault f".. with exec_strip_w have "t=Fault f" by (auto dest: execn_Fault_end) with Normal exec r' r r'_Fault show ?thesis by auto next case False with r'_Fault r' have "f' \<in> F" by (cases r) auto with Normal exec show ?thesis by auto qed qed qed qed next case Call thus ?case by auto next case DynCom thus ?case by (fastforce elim!: execn_elim_cases intro: execn.intros) next case (Guard f g c s n t) have exec_strip: "\<Gamma>\<turnstile>\<langle>strip_guards F (Guard f g c),s\<rangle> =n\<Rightarrow> t" by fact show ?case proof (cases s) case (Fault f) with exec_strip have "t=Fault f" by (auto dest: execn_Fault_end) with Fault show ?thesis by auto next case Stuck with exec_strip have "t=Stuck" by (auto dest: execn_Stuck_end) with Stuck show ?thesis by auto next case (Abrupt s') with exec_strip have "t=Abrupt s'" by (auto dest: execn_Abrupt_end) with Abrupt show ?thesis by auto next case (Normal s') show ?thesis proof (cases "f\<in>F") case True with exec_strip Normal have exec_strip_c: "\<Gamma>\<turnstile>\<langle>strip_guards F c,Normal s'\<rangle> =n\<Rightarrow> t" by simp with Guard.hyps obtain t' where "\<Gamma>\<turnstile>\<langle>c,Normal s'\<rangle> =n\<Rightarrow> t'" and "isFault t \<longrightarrow> isFault t'" and "t' \<in> Fault ` (-F) \<longrightarrow> t'=t" and "\<not> isFault t' \<longrightarrow> t'=t" by blast with Normal True show ?thesis by (cases "s'\<in> g") (fastforce intro: execn.intros)+ next case False note f_notin_F = this show ?thesis proof (cases "s'\<in>g") case False with Normal exec_strip f_notin_F have t: "t=Fault f" by (auto elim: execn_Normal_elim_cases) from False have "\<Gamma>\<turnstile>\<langle>Guard f g c,Normal s'\<rangle> =n\<Rightarrow> Fault f" by (blast intro: execn.intros) with False Normal t show ?thesis by auto next case True with exec_strip Normal f_notin_F have "\<Gamma>\<turnstile>\<langle>strip_guards F c,Normal s'\<rangle> =n\<Rightarrow> t" by (auto elim: execn_Normal_elim_cases) with Guard.hyps obtain t' where "\<Gamma>\<turnstile>\<langle>c,Normal s'\<rangle> =n\<Rightarrow> t'" and "isFault t \<longrightarrow> isFault t'" and "t' \<in> Fault ` (-F) \<longrightarrow> t'=t" and "\<not> isFault t' \<longrightarrow> t'=t" by blast with Normal True show ?thesis by (blast intro: execn.intros) qed qed qed next case Throw thus ?case by auto next case (Catch c1 c2 s n t) have exec_strip: "\<Gamma>\<turnstile>\<langle>strip_guards F (Catch c1 c2),s\<rangle> =n\<Rightarrow> t" by fact show ?case proof (cases "s") case (Fault f) with exec_strip have "t=Fault f" by (auto dest: execn_Fault_end) with Fault show ?thesis by auto next case Stuck with exec_strip have "t=Stuck" by (auto dest: execn_Stuck_end) with Stuck show ?thesis by auto next case (Abrupt s') with exec_strip have "t=Abrupt s'" by (auto dest: execn_Abrupt_end) with Abrupt show ?thesis by auto next case (Normal s') note s=this with exec_strip have "\<Gamma>\<turnstile>\<langle>Catch (strip_guards F c1) (strip_guards F c2),Normal s'\<rangle> =n\<Rightarrow> t" by simp thus ?thesis proof (cases) fix w assume exec_strip_c1: "\<Gamma>\<turnstile>\<langle>strip_guards F c1,Normal s'\<rangle> =n\<Rightarrow> Abrupt w" assume exec_strip_c2: "\<Gamma>\<turnstile>\<langle>strip_guards F c2,Normal w\<rangle> =n\<Rightarrow> t" from exec_strip_c1 Catch.hyps obtain w' where exec_c1: "\<Gamma>\<turnstile>\<langle>c1,Normal s'\<rangle> =n\<Rightarrow> w'" and w'_Fault: "w' \<in> Fault ` (-F) \<longrightarrow> w'=Abrupt w" and w'_noFault: "\<not> isFault w' \<longrightarrow> w'=Abrupt w" by blast show ?thesis proof (cases "w'") case (Fault f') with Normal exec_c1 have "\<Gamma>\<turnstile>\<langle>Catch c1 c2,s\<rangle> =n\<Rightarrow> Fault f'" by (auto intro: execn.intros) with w'_Fault Fault show ?thesis by auto next case Stuck with w'_noFault have False by simp thus ?thesis .. next case (Normal w'') with w'_noFault have False by simp thus ?thesis .. next case (Abrupt w'') with w'_noFault have w'': "w''=w" by simp from exec_strip_c2 Catch.hyps obtain t' where "\<Gamma>\<turnstile>\<langle>c2,Normal w\<rangle> =n\<Rightarrow> t'" "isFault t \<longrightarrow> isFault t'" "t' \<in> Fault ` (-F) \<longrightarrow> t'=t" "\<not> isFault t' \<longrightarrow> t'=t" by blast with w'' Abrupt s exec_c1 show ?thesis by (blast intro: execn.intros) qed next assume t: "\<not> isAbr t" assume "\<Gamma>\<turnstile>\<langle>strip_guards F c1,Normal s'\<rangle> =n\<Rightarrow> t" with Catch.hyps obtain t' where exec_c1: "\<Gamma>\<turnstile>\<langle>c1,Normal s'\<rangle> =n\<Rightarrow> t'" and t_Fault: "isFault t \<longrightarrow> isFault t'" and t'_Fault: "t' \<in> Fault ` (-F) \<longrightarrow> t'=t" and t'_noFault: "\<not> isFault t' \<longrightarrow> t'=t" by blast show ?thesis proof (cases "isFault t'") case True then obtain f' where t': "t'=Fault f'".. with exec_c1 have "\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s'\<rangle> =n\<Rightarrow> Fault f'" by (auto intro: execn.intros) with t'_Fault t' s show ?thesis by auto next case False with t'_noFault have "t'=t" by simp with t exec_c1 s show ?thesis by (blast intro: execn.intros) qed qed qed qed lemma execn_strip_to_execn: assumes exec_strip: "strip F \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" shows "\<exists>t'. \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t' \<and> (isFault t \<longrightarrow> isFault t') \<and> (t' \<in> Fault ` (- F) \<longrightarrow> t'=t) \<and> (\<not> isFault t' \<longrightarrow> t'=t)" using exec_strip proof (induct) case Skip thus ?case by (blast intro: execn.intros) next case Guard thus ?case by (blast intro: execn.intros) next case GuardFault thus ?case by (blast intro: execn.intros) next case FaultProp thus ?case by (blast intro: execn.intros) next case Basic thus ?case by (blast intro: execn.intros) next case Spec thus ?case by (blast intro: execn.intros) next case SpecStuck thus ?case by (blast intro: execn.intros) next case Seq thus ?case by (blast intro: execn.intros elim: isFaultE) next case CondTrue thus ?case by (blast intro: execn.intros) next case CondFalse thus ?case by (blast intro: execn.intros) next case WhileTrue thus ?case by (blast intro: execn.intros elim: isFaultE) next case WhileFalse thus ?case by (blast intro: execn.intros) next case Call thus ?case by simp (blast intro: execn.intros dest: execn_strip_guards_to_execn) next case CallUndefined thus ?case by simp (blast intro: execn.intros) next case StuckProp thus ?case by blast next case DynCom thus ?case by (blast intro: execn.intros) next case Throw thus ?case by (blast intro: execn.intros) next case AbruptProp thus ?case by (blast intro: execn.intros) next case (CatchMatch c1 s n r c2 t) then obtain r' t' where exec_c1: "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> =n\<Rightarrow> r'" and r'_Fault: "r' \<in> Fault ` (-F) \<longrightarrow> r' = Abrupt r" and r'_noFault: "\<not> isFault r' \<longrightarrow> r' = Abrupt r" and exec_c2: "\<Gamma>\<turnstile>\<langle>c2,Normal r\<rangle> =n\<Rightarrow> t'" and t_Fault: "isFault t \<longrightarrow> isFault t'" and t'_Fault: "t' \<in> Fault ` (-F) \<longrightarrow> t' = t" and t'_noFault: "\<not> isFault t' \<longrightarrow> t' = t" by blast show ?case proof (cases "isFault r'") case True then obtain f' where r': "r'=Fault f'".. with exec_c1 have "\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> =n\<Rightarrow> Fault f'" by (auto intro: execn.intros) with r' r'_Fault show ?thesis by (auto intro: execn.intros) next case False with r'_noFault have "r'=Abrupt r" by simp with exec_c1 exec_c2 t_Fault t'_noFault t'_Fault show ?thesis by (blast intro: execn.intros) qed next case CatchMiss thus ?case by (fastforce intro: execn.intros elim: isFaultE) qed lemma exec_strip_guards_to_exec: assumes exec_strip: "\<Gamma>\<turnstile>\<langle>strip_guards F c,s\<rangle> \<Rightarrow> t" shows "\<exists>t'. \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t' \<and> (isFault t \<longrightarrow> isFault t') \<and> (t' \<in> Fault ` (-F) \<longrightarrow> t'=t) \<and> (\<not> isFault t' \<longrightarrow> t'=t)" proof - from exec_strip obtain n where execn_strip: "\<Gamma>\<turnstile>\<langle>strip_guards F c,s\<rangle> =n\<Rightarrow> t" by (auto simp add: exec_iff_execn) then obtain t' where "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t'" "isFault t \<longrightarrow> isFault t'" "t' \<in> Fault ` (-F) \<longrightarrow> t'=t" "\<not> isFault t' \<longrightarrow> t'=t" by (blast dest: execn_strip_guards_to_execn) thus ?thesis by (blast intro: execn_to_exec) qed lemma exec_strip_to_exec: assumes exec_strip: "strip F \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" shows "\<exists>t'. \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t' \<and> (isFault t \<longrightarrow> isFault t') \<and> (t' \<in> Fault ` (-F) \<longrightarrow> t'=t) \<and> (\<not> isFault t' \<longrightarrow> t'=t)" proof - from exec_strip obtain n where execn_strip: "strip F \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" by (auto simp add: exec_iff_execn) then obtain t' where "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t'" "isFault t \<longrightarrow> isFault t'" "t' \<in> Fault ` (-F) \<longrightarrow> t'=t" "\<not> isFault t' \<longrightarrow> t'=t" by (blast dest: execn_strip_to_execn) thus ?thesis by (blast intro: execn_to_exec) qed lemma exec_to_exec_strip_guards: assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" assumes t_not_Fault: "\<not> isFault t" shows "\<Gamma>\<turnstile>\<langle>strip_guards F c,s\<rangle> \<Rightarrow> t" proof - from exec_c obtain n where "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>t" by (auto simp add: exec_iff_execn) from this t_not_Fault have "\<Gamma>\<turnstile>\<langle>strip_guards F c,s\<rangle> =n\<Rightarrow> t" by (rule execn_to_execn_strip_guards ) thus "\<Gamma>\<turnstile>\<langle>strip_guards F c,s\<rangle> \<Rightarrow> t" by (rule execn_to_exec) qed lemma exec_to_exec_strip_guards': assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" assumes t_not_Fault: "t \<notin> Fault ` F" shows "\<Gamma>\<turnstile>\<langle>strip_guards F c,s\<rangle> \<Rightarrow> t" proof - from exec_c obtain n where "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>t" by (auto simp add: exec_iff_execn) from this t_not_Fault have "\<Gamma>\<turnstile>\<langle>strip_guards F c,s\<rangle> =n\<Rightarrow> t" by (rule execn_to_execn_strip_guards' ) thus "\<Gamma>\<turnstile>\<langle>strip_guards F c,s\<rangle> \<Rightarrow> t" by (rule execn_to_exec) qed lemma execn_to_execn_strip: assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" assumes t_not_Fault: "\<not> isFault t" shows "strip F \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" using exec_c t_not_Fault proof (induct) case (Call p bdy s n s') have bdy: "\<Gamma> p = Some bdy" by fact from Call have "strip F \<Gamma>\<turnstile>\<langle>bdy,Normal s\<rangle> =n\<Rightarrow> s'" by blast from execn_to_execn_strip_guards [OF this] Call have "strip F \<Gamma>\<turnstile>\<langle>strip_guards F bdy,Normal s\<rangle> =n\<Rightarrow> s'" by simp moreover from bdy have "(strip F \<Gamma>) p = Some (strip_guards F bdy)" by simp ultimately show ?case by (blast intro: execn.intros) next case CallUndefined thus ?case by (auto intro: execn.CallUndefined) qed (auto intro: execn.intros dest: noFaultn_startD' simp add: not_isFault_iff) lemma execn_to_execn_strip': assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" assumes t_not_Fault: "t \<notin> Fault ` F" shows "strip F \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" using exec_c t_not_Fault proof (induct) case (Call p bdy s n s') have bdy: "\<Gamma> p = Some bdy" by fact from Call have "strip F \<Gamma>\<turnstile>\<langle>bdy,Normal s\<rangle> =n\<Rightarrow> s'" by blast from execn_to_execn_strip_guards' [OF this] Call have "strip F \<Gamma>\<turnstile>\<langle>strip_guards F bdy,Normal s\<rangle> =n\<Rightarrow> s'" by simp moreover from bdy have "(strip F \<Gamma>) p = Some (strip_guards F bdy)" by simp ultimately show ?case by (blast intro: execn.intros) next case CallUndefined thus ?case by (auto intro: execn.CallUndefined) next case (Seq c1 s n s' c2 t) show ?case proof (cases "isFault s'") case False with Seq show ?thesis by (auto intro: execn.intros simp add: not_isFault_iff) next case True then obtain f' where s': "s'=Fault f'" by (auto simp add: isFault_def) with Seq obtain "t=Fault f'" and "f' \<notin> F" by (force dest: execn_Fault_end) with Seq s' show ?thesis by (auto intro: execn.intros) qed next case (WhileTrue b c s n s' t) show ?case proof (cases "isFault s'") case False with WhileTrue show ?thesis by (auto intro: execn.intros simp add: not_isFault_iff) next case True then obtain f' where s': "s'=Fault f'" by (auto simp add: isFault_def) with WhileTrue obtain "t=Fault f'" and "f' \<notin> F" by (force dest: execn_Fault_end) with WhileTrue s' show ?thesis by (auto intro: execn.intros) qed qed (auto intro: execn.intros) lemma exec_to_exec_strip: assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" assumes t_not_Fault: "\<not> isFault t" shows "strip F \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" proof - from exec_c obtain n where "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>t" by (auto simp add: exec_iff_execn) from this t_not_Fault have "strip F \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" by (rule execn_to_execn_strip) thus "strip F \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" by (rule execn_to_exec) qed lemma exec_to_exec_strip': assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" assumes t_not_Fault: "t \<notin> Fault ` F" shows "strip F \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" proof - from exec_c obtain n where "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>t" by (auto simp add: exec_iff_execn) from this t_not_Fault have "strip F \<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" by (rule execn_to_execn_strip' ) thus "strip F \<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" by (rule execn_to_exec) qed lemma exec_to_exec_strip_guards_Fault: assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> Fault f" assumes f_notin_F: "f \<notin> F" shows"\<Gamma>\<turnstile>\<langle>strip_guards F c,s\<rangle> \<Rightarrow> Fault f" proof - from exec_c obtain n where "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow>Fault f" by (auto simp add: exec_iff_execn) from execn_to_execn_strip_guards_Fault [OF this _ f_notin_F] have "\<Gamma>\<turnstile>\<langle>strip_guards F c,s\<rangle> =n\<Rightarrow> Fault f" by simp thus "\<Gamma>\<turnstile>\<langle>strip_guards F c,s\<rangle> \<Rightarrow> Fault f" by (rule execn_to_exec) qed (* ************************************************************************* *) subsection \<open>Lemmas about @{term "c\<^sub>1 \<inter>\<^sub>g c\<^sub>2"}\<close> (* ************************************************************************* *) lemma inter_guards_execn_Normal_noFault: "\<And>c c2 s t n. \<lbrakk>(c1 \<inter>\<^sub>g c2) = Some c; \<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> t; \<not> isFault t\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> =n\<Rightarrow> t \<and> \<Gamma>\<turnstile>\<langle>c2,Normal s\<rangle> =n\<Rightarrow> t" proof (induct c1) case Skip have "(Skip \<inter>\<^sub>g c2) = Some c" by fact then obtain c2: "c2=Skip" and c: "c=Skip" by (simp add: inter_guards_Skip) have "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> t" by fact with c have "t=Normal s" by (auto elim: execn_Normal_elim_cases) with Skip c2 show ?case by (auto intro: execn.intros) next case (Basic f) have "(Basic f \<inter>\<^sub>g c2) = Some c" by fact then obtain c2: "c2=Basic f" and c: "c=Basic f" by (simp add: inter_guards_Basic) have "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> t" by fact with c have "t=Normal (f s)" by (auto elim: execn_Normal_elim_cases) with Basic c2 show ?case by (auto intro: execn.intros) next case (Spec r) have "(Spec r \<inter>\<^sub>g c2) = Some c" by fact then obtain c2: "c2=Spec r" and c: "c=Spec r" by (simp add: inter_guards_Spec) have "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> t" by fact with c have "\<Gamma>\<turnstile>\<langle>Spec r,Normal s\<rangle> =n\<Rightarrow> t" by simp from this Spec c2 show ?case by (cases) (auto intro: execn.intros) next case (Seq a1 a2) have noFault: "\<not> isFault t" by fact have "(Seq a1 a2 \<inter>\<^sub>g c2) = Some c" by fact then obtain b1 b2 d1 d2 where c2: "c2=Seq b1 b2" and d1: "(a1 \<inter>\<^sub>g b1) = Some d1" and d2: "(a2 \<inter>\<^sub>g b2) = Some d2" and c: "c=Seq d1 d2" by (auto simp add: inter_guards_Seq) have "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> t" by fact with c obtain s' where exec_d1: "\<Gamma>\<turnstile>\<langle>d1,Normal s\<rangle> =n\<Rightarrow> s'" and exec_d2: "\<Gamma>\<turnstile>\<langle>d2,s'\<rangle> =n\<Rightarrow> t" by (auto elim: execn_Normal_elim_cases) show ?case proof (cases s') case (Fault f') with exec_d2 have "t=Fault f'" by (auto intro: execn_Fault_end) with noFault show ?thesis by simp next case (Normal s'') with d1 exec_d1 Seq.hyps obtain "\<Gamma>\<turnstile>\<langle>a1,Normal s\<rangle> =n\<Rightarrow> Normal s''" and "\<Gamma>\<turnstile>\<langle>b1,Normal s\<rangle> =n\<Rightarrow> Normal s''" by auto moreover from Normal d2 exec_d2 noFault Seq.hyps obtain "\<Gamma>\<turnstile>\<langle>a2,Normal s''\<rangle> =n\<Rightarrow> t" and "\<Gamma>\<turnstile>\<langle>b2,Normal s''\<rangle> =n\<Rightarrow> t" by auto ultimately show ?thesis using Normal c2 by (auto intro: execn.intros) next case (Abrupt s'') with exec_d2 have "t=Abrupt s''" by (auto simp add: execn_Abrupt_end) moreover from Abrupt d1 exec_d1 Seq.hyps obtain "\<Gamma>\<turnstile>\<langle>a1,Normal s\<rangle> =n\<Rightarrow> Abrupt s''" and "\<Gamma>\<turnstile>\<langle>b1,Normal s\<rangle> =n\<Rightarrow> Abrupt s''" by auto moreover obtain "\<Gamma>\<turnstile>\<langle>a2,Abrupt s''\<rangle> =n\<Rightarrow> Abrupt s''" and "\<Gamma>\<turnstile>\<langle>b2,Abrupt s''\<rangle> =n\<Rightarrow> Abrupt s''" by auto ultimately show ?thesis using Abrupt c2 by (auto intro: execn.intros) next case Stuck with exec_d2 have "t=Stuck" by (auto simp add: execn_Stuck_end) moreover from Stuck d1 exec_d1 Seq.hyps obtain "\<Gamma>\<turnstile>\<langle>a1,Normal s\<rangle> =n\<Rightarrow> Stuck" and "\<Gamma>\<turnstile>\<langle>b1,Normal s\<rangle> =n\<Rightarrow> Stuck" by auto moreover obtain "\<Gamma>\<turnstile>\<langle>a2,Stuck\<rangle> =n\<Rightarrow> Stuck" and "\<Gamma>\<turnstile>\<langle>b2,Stuck\<rangle> =n\<Rightarrow> Stuck" by auto ultimately show ?thesis using Stuck c2 by (auto intro: execn.intros) qed next case (Cond b t1 e1) have noFault: "\<not> isFault t" by fact have "(Cond b t1 e1 \<inter>\<^sub>g c2) = Some c" by fact then obtain t2 e2 t3 e3 where c2: "c2=Cond b t2 e2" and t3: "(t1 \<inter>\<^sub>g t2) = Some t3" and e3: "(e1 \<inter>\<^sub>g e2) = Some e3" and c: "c=Cond b t3 e3" by (auto simp add: inter_guards_Cond) have "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> t" by fact with c have "\<Gamma>\<turnstile>\<langle>Cond b t3 e3,Normal s\<rangle> =n\<Rightarrow> t" by simp then show ?case proof (cases) assume s_in_b: "s\<in>b" assume "\<Gamma>\<turnstile>\<langle>t3,Normal s\<rangle> =n\<Rightarrow> t" with Cond.hyps t3 noFault obtain "\<Gamma>\<turnstile>\<langle>t1,Normal s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>t2,Normal s\<rangle> =n\<Rightarrow> t" by auto with s_in_b c2 show ?thesis by (auto intro: execn.intros) next assume s_notin_b: "s\<notin>b" assume "\<Gamma>\<turnstile>\<langle>e3,Normal s\<rangle> =n\<Rightarrow> t" with Cond.hyps e3 noFault obtain "\<Gamma>\<turnstile>\<langle>e1,Normal s\<rangle> =n\<Rightarrow> t" "\<Gamma>\<turnstile>\<langle>e2,Normal s\<rangle> =n\<Rightarrow> t" by auto with s_notin_b c2 show ?thesis by (auto intro: execn.intros) qed next case (While b bdy1) have noFault: "\<not> isFault t" by fact have "(While b bdy1 \<inter>\<^sub>g c2) = Some c" by fact then obtain bdy2 bdy where c2: "c2=While b bdy2" and bdy: "(bdy1 \<inter>\<^sub>g bdy2) = Some bdy" and c: "c=While b bdy" by (auto simp add: inter_guards_While) have exec_c: "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> t" by fact { fix s t n w w1 w2 assume exec_w: "\<Gamma>\<turnstile>\<langle>w,Normal s\<rangle> =n\<Rightarrow> t" assume w: "w=While b bdy" assume noFault: "\<not> isFault t" from exec_w w noFault have "\<Gamma>\<turnstile>\<langle>While b bdy1,Normal s\<rangle> =n\<Rightarrow> t \<and> \<Gamma>\<turnstile>\<langle>While b bdy2,Normal s\<rangle> =n\<Rightarrow> t" proof (induct) prefer 10 case (WhileTrue s b' bdy' n s' s'') have eqs: "While b' bdy' = While b bdy" by fact from WhileTrue have s_in_b: "s \<in> b" by simp have noFault_s'': "\<not> isFault s''" by fact from WhileTrue have exec_bdy: "\<Gamma>\<turnstile>\<langle>bdy,Normal s\<rangle> =n\<Rightarrow> s'" by simp from WhileTrue have exec_w: "\<Gamma>\<turnstile>\<langle>While b bdy,s'\<rangle> =n\<Rightarrow> s''" by simp show ?case proof (cases s') case (Fault f) with exec_w have "s''=Fault f" by (auto intro: execn_Fault_end) with noFault_s'' show ?thesis by simp next case (Normal s''') with exec_bdy bdy While.hyps obtain "\<Gamma>\<turnstile>\<langle>bdy1,Normal s\<rangle> =n\<Rightarrow> Normal s'''" "\<Gamma>\<turnstile>\<langle>bdy2,Normal s\<rangle> =n\<Rightarrow> Normal s'''" by auto moreover from Normal WhileTrue obtain "\<Gamma>\<turnstile>\<langle>While b bdy1,Normal s'''\<rangle> =n\<Rightarrow> s''" "\<Gamma>\<turnstile>\<langle>While b bdy2,Normal s'''\<rangle> =n\<Rightarrow> s''" by simp ultimately show ?thesis using s_in_b Normal by (auto intro: execn.intros) next case (Abrupt s''') with exec_bdy bdy While.hyps obtain "\<Gamma>\<turnstile>\<langle>bdy1,Normal s\<rangle> =n\<Rightarrow> Abrupt s'''" "\<Gamma>\<turnstile>\<langle>bdy2,Normal s\<rangle> =n\<Rightarrow> Abrupt s'''" by auto moreover from Abrupt WhileTrue obtain "\<Gamma>\<turnstile>\<langle>While b bdy1,Abrupt s'''\<rangle> =n\<Rightarrow> s''" "\<Gamma>\<turnstile>\<langle>While b bdy2,Abrupt s'''\<rangle> =n\<Rightarrow> s''" by simp ultimately show ?thesis using s_in_b Abrupt by (auto intro: execn.intros) next case Stuck with exec_bdy bdy While.hyps obtain "\<Gamma>\<turnstile>\<langle>bdy1,Normal s\<rangle> =n\<Rightarrow> Stuck" "\<Gamma>\<turnstile>\<langle>bdy2,Normal s\<rangle> =n\<Rightarrow> Stuck" by auto moreover from Stuck WhileTrue obtain "\<Gamma>\<turnstile>\<langle>While b bdy1,Stuck\<rangle> =n\<Rightarrow> s''" "\<Gamma>\<turnstile>\<langle>While b bdy2,Stuck\<rangle> =n\<Rightarrow> s''" by simp ultimately show ?thesis using s_in_b Stuck by (auto intro: execn.intros) qed next case WhileFalse thus ?case by (auto intro: execn.intros) qed (simp_all) } with this [OF exec_c c noFault] c2 show ?case by auto next case Call thus ?case by (simp add: inter_guards_Call) next case (DynCom f1) have noFault: "\<not> isFault t" by fact have "(DynCom f1 \<inter>\<^sub>g c2) = Some c" by fact then obtain f2 f where c2: "c2=DynCom f2" and f_defined: "\<forall>s. ((f1 s) \<inter>\<^sub>g (f2 s)) \<noteq> None" and c: "c=DynCom (\<lambda>s. the ((f1 s) \<inter>\<^sub>g (f2 s)))" by (auto simp add: inter_guards_DynCom) have "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> t" by fact with c have "\<Gamma>\<turnstile>\<langle>DynCom (\<lambda>s. the ((f1 s) \<inter>\<^sub>g (f2 s))),Normal s\<rangle> =n\<Rightarrow> t" by simp then show ?case proof (cases) assume exec_f: "\<Gamma>\<turnstile>\<langle>the (f1 s \<inter>\<^sub>g f2 s),Normal s\<rangle> =n\<Rightarrow> t" from f_defined obtain f where "(f1 s \<inter>\<^sub>g f2 s) = Some f" by auto with DynCom.hyps this exec_f c2 noFault show ?thesis using execn.DynCom by fastforce qed next case Guard thus ?case by (fastforce elim: execn_Normal_elim_cases intro: execn.intros simp add: inter_guards_Guard) next case Throw thus ?case by (fastforce elim: execn_Normal_elim_cases simp add: inter_guards_Throw) next case (Catch a1 a2) have noFault: "\<not> isFault t" by fact have "(Catch a1 a2 \<inter>\<^sub>g c2) = Some c" by fact then obtain b1 b2 d1 d2 where c2: "c2=Catch b1 b2" and d1: "(a1 \<inter>\<^sub>g b1) = Some d1" and d2: "(a2 \<inter>\<^sub>g b2) = Some d2" and c: "c=Catch d1 d2" by (auto simp add: inter_guards_Catch) have "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> t" by fact with c have "\<Gamma>\<turnstile>\<langle>Catch d1 d2,Normal s\<rangle> =n\<Rightarrow> t" by simp then show ?case proof (cases) fix s' assume "\<Gamma>\<turnstile>\<langle>d1,Normal s\<rangle> =n\<Rightarrow> Abrupt s'" with d1 Catch.hyps obtain "\<Gamma>\<turnstile>\<langle>a1,Normal s\<rangle> =n\<Rightarrow> Abrupt s'" and "\<Gamma>\<turnstile>\<langle>b1,Normal s\<rangle> =n\<Rightarrow> Abrupt s'" by auto moreover assume "\<Gamma>\<turnstile>\<langle>d2,Normal s'\<rangle> =n\<Rightarrow> t" with d2 Catch.hyps noFault obtain "\<Gamma>\<turnstile>\<langle>a2,Normal s'\<rangle> =n\<Rightarrow> t" and "\<Gamma>\<turnstile>\<langle>b2,Normal s'\<rangle> =n\<Rightarrow> t" by auto ultimately show ?thesis using c2 by (auto intro: execn.intros) next assume "\<not> isAbr t" moreover assume "\<Gamma>\<turnstile>\<langle>d1,Normal s\<rangle> =n\<Rightarrow> t" with d1 Catch.hyps noFault obtain "\<Gamma>\<turnstile>\<langle>a1,Normal s\<rangle> =n\<Rightarrow> t" and "\<Gamma>\<turnstile>\<langle>b1,Normal s\<rangle> =n\<Rightarrow> t" by auto ultimately show ?thesis using c2 by (auto intro: execn.intros) qed qed lemma inter_guards_execn_noFault: assumes c: "(c1 \<inter>\<^sub>g c2) = Some c" assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" assumes noFault: "\<not> isFault t" shows "\<Gamma>\<turnstile>\<langle>c1,s\<rangle> =n\<Rightarrow> t \<and> \<Gamma>\<turnstile>\<langle>c2,s\<rangle> =n\<Rightarrow> t" proof (cases s) case (Fault f) with exec_c have "t = Fault f" by (auto intro: execn_Fault_end) with noFault show ?thesis by simp next case (Abrupt s') with exec_c have "t=Abrupt s'" by (simp add: execn_Abrupt_end) with Abrupt show ?thesis by auto next case Stuck with exec_c have "t=Stuck" by (simp add: execn_Stuck_end) with Stuck show ?thesis by auto next case (Normal s') with exec_c noFault inter_guards_execn_Normal_noFault [OF c] show ?thesis by blast qed lemma inter_guards_exec_noFault: assumes c: "(c1 \<inter>\<^sub>g c2) = Some c" assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" assumes noFault: "\<not> isFault t" shows "\<Gamma>\<turnstile>\<langle>c1,s\<rangle> \<Rightarrow> t \<and> \<Gamma>\<turnstile>\<langle>c2,s\<rangle> \<Rightarrow> t" proof - from exec_c obtain n where "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" by (auto simp add: exec_iff_execn) from c this noFault have "\<Gamma>\<turnstile>\<langle>c1,s\<rangle> =n\<Rightarrow> t \<and> \<Gamma>\<turnstile>\<langle>c2,s\<rangle> =n\<Rightarrow> t" by (rule inter_guards_execn_noFault) thus ?thesis by (auto intro: execn_to_exec) qed lemma inter_guards_execn_Normal_Fault: "\<And>c c2 s n. \<lbrakk>(c1 \<inter>\<^sub>g c2) = Some c; \<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> Fault f\<rbrakk> \<Longrightarrow> (\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> =n\<Rightarrow> Fault f \<or> \<Gamma>\<turnstile>\<langle>c2,Normal s\<rangle> =n\<Rightarrow> Fault f)" proof (induct c1) case Skip thus ?case by (fastforce simp add: inter_guards_Skip) next case (Basic f) thus ?case by (fastforce simp add: inter_guards_Basic) next case (Spec r) thus ?case by (fastforce simp add: inter_guards_Spec) next case (Seq a1 a2) have "(Seq a1 a2 \<inter>\<^sub>g c2) = Some c" by fact then obtain b1 b2 d1 d2 where c2: "c2=Seq b1 b2" and d1: "(a1 \<inter>\<^sub>g b1) = Some d1" and d2: "(a2 \<inter>\<^sub>g b2) = Some d2" and c: "c=Seq d1 d2" by (auto simp add: inter_guards_Seq) have "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> Fault f" by fact with c obtain s' where exec_d1: "\<Gamma>\<turnstile>\<langle>d1,Normal s\<rangle> =n\<Rightarrow> s'" and exec_d2: "\<Gamma>\<turnstile>\<langle>d2,s'\<rangle> =n\<Rightarrow> Fault f" by (auto elim: execn_Normal_elim_cases) show ?case proof (cases s') case (Fault f') with exec_d2 have "f'=f" by (auto dest: execn_Fault_end) with Fault d1 exec_d1 have "\<Gamma>\<turnstile>\<langle>a1,Normal s\<rangle> =n\<Rightarrow> Fault f \<or> \<Gamma>\<turnstile>\<langle>b1,Normal s\<rangle> =n\<Rightarrow> Fault f" by (auto dest: Seq.hyps) thus ?thesis proof (cases rule: disjE [consumes 1]) assume "\<Gamma>\<turnstile>\<langle>a1,Normal s\<rangle> =n\<Rightarrow> Fault f" hence "\<Gamma>\<turnstile>\<langle>Seq a1 a2,Normal s\<rangle> =n\<Rightarrow> Fault f" by (auto intro: execn.intros) thus ?thesis by simp next assume "\<Gamma>\<turnstile>\<langle>b1,Normal s\<rangle> =n\<Rightarrow> Fault f" hence "\<Gamma>\<turnstile>\<langle>Seq b1 b2,Normal s\<rangle> =n\<Rightarrow> Fault f" by (auto intro: execn.intros) with c2 show ?thesis by simp qed next case Abrupt with exec_d2 show ?thesis by (auto dest: execn_Abrupt_end) next case Stuck with exec_d2 show ?thesis by (auto dest: execn_Stuck_end) next case (Normal s'') with inter_guards_execn_noFault [OF d1 exec_d1] obtain exec_a1: "\<Gamma>\<turnstile>\<langle>a1,Normal s\<rangle> =n\<Rightarrow> Normal s''" and exec_b1: "\<Gamma>\<turnstile>\<langle>b1,Normal s\<rangle> =n\<Rightarrow> Normal s''" by simp moreover from d2 exec_d2 Normal have "\<Gamma>\<turnstile>\<langle>a2,Normal s''\<rangle> =n\<Rightarrow> Fault f \<or> \<Gamma>\<turnstile>\<langle>b2,Normal s''\<rangle> =n\<Rightarrow> Fault f" by (auto dest: Seq.hyps) ultimately show ?thesis using c2 by (auto intro: execn.intros) qed next case (Cond b t1 e1) have "(Cond b t1 e1 \<inter>\<^sub>g c2) = Some c" by fact then obtain t2 e2 t e where c2: "c2=Cond b t2 e2" and t: "(t1 \<inter>\<^sub>g t2) = Some t" and e: "(e1 \<inter>\<^sub>g e2) = Some e" and c: "c=Cond b t e" by (auto simp add: inter_guards_Cond) have "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> Fault f" by fact with c have "\<Gamma>\<turnstile>\<langle>Cond b t e,Normal s\<rangle> =n\<Rightarrow> Fault f" by simp thus ?case proof (cases) assume "s \<in> b" moreover assume "\<Gamma>\<turnstile>\<langle>t,Normal s\<rangle> =n\<Rightarrow> Fault f" with t have "\<Gamma>\<turnstile>\<langle>t1,Normal s\<rangle> =n\<Rightarrow> Fault f \<or> \<Gamma>\<turnstile>\<langle>t2,Normal s\<rangle> =n\<Rightarrow> Fault f" by (auto dest: Cond.hyps) ultimately show ?thesis using c2 c by (fastforce intro: execn.intros) next assume "s \<notin> b" moreover assume "\<Gamma>\<turnstile>\<langle>e,Normal s\<rangle> =n\<Rightarrow> Fault f" with e have "\<Gamma>\<turnstile>\<langle>e1,Normal s\<rangle> =n\<Rightarrow> Fault f \<or> \<Gamma>\<turnstile>\<langle>e2,Normal s\<rangle> =n\<Rightarrow> Fault f" by (auto dest: Cond.hyps) ultimately show ?thesis using c2 c by (fastforce intro: execn.intros) qed next case (While b bdy1) have "(While b bdy1 \<inter>\<^sub>g c2) = Some c" by fact then obtain bdy2 bdy where c2: "c2=While b bdy2" and bdy: "(bdy1 \<inter>\<^sub>g bdy2) = Some bdy" and c: "c=While b bdy" by (auto simp add: inter_guards_While) have exec_c: "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> Fault f" by fact { fix s t n w w1 w2 assume exec_w: "\<Gamma>\<turnstile>\<langle>w,Normal s\<rangle> =n\<Rightarrow> t" assume w: "w=While b bdy" assume Fault: "t=Fault f" from exec_w w Fault have "\<Gamma>\<turnstile>\<langle>While b bdy1,Normal s\<rangle> =n\<Rightarrow> Fault f\<or> \<Gamma>\<turnstile>\<langle>While b bdy2,Normal s\<rangle> =n\<Rightarrow> Fault f" proof (induct) case (WhileTrue s b' bdy' n s' s'') have eqs: "While b' bdy' = While b bdy" by fact from WhileTrue have s_in_b: "s \<in> b" by simp have Fault_s'': "s''=Fault f" by fact from WhileTrue have exec_bdy: "\<Gamma>\<turnstile>\<langle>bdy,Normal s\<rangle> =n\<Rightarrow> s'" by simp from WhileTrue have exec_w: "\<Gamma>\<turnstile>\<langle>While b bdy,s'\<rangle> =n\<Rightarrow> s''" by simp show ?case proof (cases s') case (Fault f') with exec_w Fault_s'' have "f'=f" by (auto dest: execn_Fault_end) with Fault exec_bdy bdy While.hyps have "\<Gamma>\<turnstile>\<langle>bdy1,Normal s\<rangle> =n\<Rightarrow> Fault f \<or> \<Gamma>\<turnstile>\<langle>bdy2,Normal s\<rangle> =n\<Rightarrow> Fault f" by auto with s_in_b show ?thesis by (fastforce intro: execn.intros) next case (Normal s''') with inter_guards_execn_noFault [OF bdy exec_bdy] obtain "\<Gamma>\<turnstile>\<langle>bdy1,Normal s\<rangle> =n\<Rightarrow> Normal s'''" "\<Gamma>\<turnstile>\<langle>bdy2,Normal s\<rangle> =n\<Rightarrow> Normal s'''" by auto moreover from Normal WhileTrue have "\<Gamma>\<turnstile>\<langle>While b bdy1,Normal s'''\<rangle> =n\<Rightarrow> Fault f \<or> \<Gamma>\<turnstile>\<langle>While b bdy2,Normal s'''\<rangle> =n\<Rightarrow> Fault f" by simp ultimately show ?thesis using s_in_b by (fastforce intro: execn.intros) next case (Abrupt s''') with exec_w Fault_s'' show ?thesis by (fastforce dest: execn_Abrupt_end) next case Stuck with exec_w Fault_s'' show ?thesis by (fastforce dest: execn_Stuck_end) qed next case WhileFalse thus ?case by (auto intro: execn.intros) qed (simp_all) } with this [OF exec_c c] c2 show ?case by auto next case Call thus ?case by (fastforce simp add: inter_guards_Call) next case (DynCom f1) have "(DynCom f1 \<inter>\<^sub>g c2) = Some c" by fact then obtain f2 where c2: "c2=DynCom f2" and F_defined: "\<forall>s. ((f1 s) \<inter>\<^sub>g (f2 s)) \<noteq> None" and c: "c=DynCom (\<lambda>s. the ((f1 s) \<inter>\<^sub>g (f2 s)))" by (auto simp add: inter_guards_DynCom) have "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> Fault f" by fact with c have "\<Gamma>\<turnstile>\<langle>DynCom (\<lambda>s. the ((f1 s) \<inter>\<^sub>g (f2 s))),Normal s\<rangle> =n\<Rightarrow> Fault f" by simp then show ?case proof (cases) assume exec_F: "\<Gamma>\<turnstile>\<langle>the (f1 s \<inter>\<^sub>g f2 s),Normal s\<rangle> =n\<Rightarrow> Fault f" from F_defined obtain F where "(f1 s \<inter>\<^sub>g f2 s) = Some F" by auto with DynCom.hyps this exec_F c2 show ?thesis by (fastforce intro: execn.intros) qed next case (Guard m g1 bdy1) have "(Guard m g1 bdy1 \<inter>\<^sub>g c2) = Some c" by fact then obtain g2 bdy2 bdy where c2: "c2=Guard m g2 bdy2" and bdy: "(bdy1 \<inter>\<^sub>g bdy2) = Some bdy" and c: "c=Guard m (g1 \<inter> g2) bdy" by (auto simp add: inter_guards_Guard) have "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> Fault f" by fact with c have "\<Gamma>\<turnstile>\<langle>Guard m (g1 \<inter> g2) bdy,Normal s\<rangle> =n\<Rightarrow> Fault f" by simp thus ?case proof (cases) assume f_m: "Fault f = Fault m" assume "s \<notin> g1 \<inter> g2" hence "s\<notin>g1 \<or> s\<notin>g2" by blast with c2 f_m show ?thesis by (auto intro: execn.intros) next assume "s \<in> g1 \<inter> g2" moreover assume "\<Gamma>\<turnstile>\<langle>bdy,Normal s\<rangle> =n\<Rightarrow> Fault f" with bdy have "\<Gamma>\<turnstile>\<langle>bdy1,Normal s\<rangle> =n\<Rightarrow> Fault f \<or> \<Gamma>\<turnstile>\<langle>bdy2,Normal s\<rangle> =n\<Rightarrow> Fault f" by (rule Guard.hyps) ultimately show ?thesis using c2 by (auto intro: execn.intros) qed next case Throw thus ?case by (fastforce simp add: inter_guards_Throw) next case (Catch a1 a2) have "(Catch a1 a2 \<inter>\<^sub>g c2) = Some c" by fact then obtain b1 b2 d1 d2 where c2: "c2=Catch b1 b2" and d1: "(a1 \<inter>\<^sub>g b1) = Some d1" and d2: "(a2 \<inter>\<^sub>g b2) = Some d2" and c: "c=Catch d1 d2" by (auto simp add: inter_guards_Catch) have "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> Fault f" by fact with c have "\<Gamma>\<turnstile>\<langle>Catch d1 d2,Normal s\<rangle> =n\<Rightarrow> Fault f" by simp thus ?case proof (cases) fix s' assume "\<Gamma>\<turnstile>\<langle>d1,Normal s\<rangle> =n\<Rightarrow> Abrupt s'" from inter_guards_execn_noFault [OF d1 this] obtain exec_a1: "\<Gamma>\<turnstile>\<langle>a1,Normal s\<rangle> =n\<Rightarrow> Abrupt s'" and exec_b1: "\<Gamma>\<turnstile>\<langle>b1,Normal s\<rangle> =n\<Rightarrow> Abrupt s'" by simp moreover assume "\<Gamma>\<turnstile>\<langle>d2,Normal s'\<rangle> =n\<Rightarrow> Fault f" with d2 have "\<Gamma>\<turnstile>\<langle>a2,Normal s'\<rangle> =n\<Rightarrow> Fault f \<or> \<Gamma>\<turnstile>\<langle>b2,Normal s'\<rangle> =n\<Rightarrow> Fault f" by (auto dest: Catch.hyps) ultimately show ?thesis using c2 by (fastforce intro: execn.intros) next assume "\<Gamma>\<turnstile>\<langle>d1,Normal s\<rangle> =n\<Rightarrow> Fault f" with d1 have "\<Gamma>\<turnstile>\<langle>a1,Normal s\<rangle> =n\<Rightarrow> Fault f \<or> \<Gamma>\<turnstile>\<langle>b1,Normal s\<rangle> =n\<Rightarrow> Fault f" by (auto dest: Catch.hyps) with c2 show ?thesis by (fastforce intro: execn.intros) qed qed lemma inter_guards_execn_Fault: assumes c: "(c1 \<inter>\<^sub>g c2) = Some c" assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> Fault f" shows "\<Gamma>\<turnstile>\<langle>c1,s\<rangle> =n\<Rightarrow> Fault f \<or> \<Gamma>\<turnstile>\<langle>c2,s\<rangle> =n\<Rightarrow> Fault f" proof (cases s) case (Fault f) with exec_c show ?thesis by (auto dest: execn_Fault_end) next case (Abrupt s') with exec_c show ?thesis by (fastforce dest: execn_Abrupt_end) next case Stuck with exec_c show ?thesis by (fastforce dest: execn_Stuck_end) next case (Normal s') with exec_c inter_guards_execn_Normal_Fault [OF c] show ?thesis by blast qed lemma inter_guards_exec_Fault: assumes c: "(c1 \<inter>\<^sub>g c2) = Some c" assumes exec_c: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> Fault f" shows "\<Gamma>\<turnstile>\<langle>c1,s\<rangle> \<Rightarrow> Fault f \<or> \<Gamma>\<turnstile>\<langle>c2,s\<rangle> \<Rightarrow> Fault f" proof - from exec_c obtain n where "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> Fault f" by (auto simp add: exec_iff_execn) from c this have "\<Gamma>\<turnstile>\<langle>c1,s\<rangle> =n\<Rightarrow> Fault f \<or> \<Gamma>\<turnstile>\<langle>c2,s\<rangle> =n\<Rightarrow> Fault f" by (rule inter_guards_execn_Fault) thus ?thesis by (auto intro: execn_to_exec) qed (* ************************************************************************* *) subsection "Restriction of Procedure Environment" (* ************************************************************************* *) lemma restrict_SomeD: "(m|\<^bsub>A\<^esub>) x = Some y \<Longrightarrow> m x = Some y" by (auto simp add: restrict_map_def split: if_split_asm) (* FIXME: To Map *) lemma restrict_dom_same [simp]: "m|\<^bsub>dom m\<^esub> = m" apply (rule ext) apply (clarsimp simp add: restrict_map_def) apply (simp only: not_None_eq [symmetric]) apply rule apply (drule sym) apply blast done lemma restrict_in_dom: "x \<in> A \<Longrightarrow> (m|\<^bsub>A\<^esub>) x = m x" by (auto simp add: restrict_map_def) lemma exec_restrict_to_exec: assumes exec_restrict: "\<Gamma>|\<^bsub>A\<^esub>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" assumes notStuck: "t\<noteq>Stuck" shows "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" using exec_restrict notStuck by (induct) (auto intro: exec.intros dest: restrict_SomeD Stuck_end) lemma execn_restrict_to_execn: assumes exec_restrict: "\<Gamma>|\<^bsub>A\<^esub>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" assumes notStuck: "t\<noteq>Stuck" shows "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" using exec_restrict notStuck by (induct) (auto intro: execn.intros dest: restrict_SomeD execn_Stuck_end) lemma restrict_NoneD: "m x = None \<Longrightarrow> (m|\<^bsub>A\<^esub>) x = None" by (auto simp add: restrict_map_def split: if_split_asm) lemma exec_to_exec_restrict: assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" shows "\<exists>t'. \<Gamma>|\<^bsub>P\<^esub>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t' \<and> (t=Stuck \<longrightarrow> t'=Stuck) \<and> (\<forall>f. t=Fault f\<longrightarrow> t'\<in>{Fault f,Stuck}) \<and> (t'\<noteq>Stuck \<longrightarrow> t'=t)" proof - from exec obtain n where execn_strip: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" by (auto simp add: exec_iff_execn) from execn_to_execn_restrict [where P=P,OF this] obtain t' where "\<Gamma>|\<^bsub>P\<^esub>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t'" "t=Stuck \<longrightarrow> t'=Stuck" "\<forall>f. t=Fault f\<longrightarrow> t'\<in>{Fault f,Stuck}" "t'\<noteq>Stuck \<longrightarrow> t'=t" by blast thus ?thesis by (blast intro: execn_to_exec) qed lemma notStuck_GuardD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>Guard m g c,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}; s \<in> g\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}" by (auto simp add: final_notin_def dest: exec.Guard ) lemma notStuck_SeqD1: "\<lbrakk>\<Gamma>\<turnstile>\<langle>Seq c1 c2,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}" by (auto simp add: final_notin_def dest: exec.Seq ) lemma notStuck_SeqD2: "\<lbrakk>\<Gamma>\<turnstile>\<langle>Seq c1 c2,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}; \<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow>s'\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c2,s'\<rangle> \<Rightarrow>\<notin>{Stuck}" by (auto simp add: final_notin_def dest: exec.Seq ) lemma notStuck_SeqD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>Seq c1 c2,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck} \<and> (\<forall>s'. \<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow>s' \<longrightarrow> \<Gamma>\<turnstile>\<langle>c2,s'\<rangle> \<Rightarrow>\<notin>{Stuck})" by (auto simp add: final_notin_def dest: exec.Seq ) lemma notStuck_CondTrueD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>Cond b c1 c2,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}; s \<in> b\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}" by (auto simp add: final_notin_def dest: exec.CondTrue) lemma notStuck_CondFalseD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>Cond b c1 c2,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}; s \<notin> b\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c2,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}" by (auto simp add: final_notin_def dest: exec.CondFalse) lemma notStuck_WhileTrueD1: "\<lbrakk>\<Gamma>\<turnstile>\<langle>While b c,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}; s \<in> b\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}" by (auto simp add: final_notin_def dest: exec.WhileTrue) lemma notStuck_WhileTrueD2: "\<lbrakk>\<Gamma>\<turnstile>\<langle>While b c,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}; \<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow>s'; s \<in> b\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>While b c,s'\<rangle> \<Rightarrow>\<notin>{Stuck}" by (auto simp add: final_notin_def dest: exec.WhileTrue) lemma notStuck_CallD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>Call p ,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}; \<Gamma> p = Some bdy\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>bdy,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}" by (auto simp add: final_notin_def dest: exec.Call) lemma notStuck_CallDefinedD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}\<rbrakk> \<Longrightarrow> \<Gamma> p \<noteq> None" by (cases "\<Gamma> p") (auto simp add: final_notin_def dest: exec.CallUndefined) lemma notStuck_DynComD: "\<lbrakk>\<Gamma>\<turnstile>\<langle>DynCom c,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>(c s),Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}" by (auto simp add: final_notin_def dest: exec.DynCom) lemma notStuck_CatchD1: "\<lbrakk>\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}" by (auto simp add: final_notin_def dest: exec.CatchMatch exec.CatchMiss ) lemma notStuck_CatchD2: "\<lbrakk>\<Gamma>\<turnstile>\<langle>Catch c1 c2,Normal s\<rangle> \<Rightarrow>\<notin>{Stuck}; \<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> \<Rightarrow>Abrupt s'\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>\<langle>c2,Normal s'\<rangle> \<Rightarrow>\<notin>{Stuck}" by (auto simp add: final_notin_def dest: exec.CatchMatch) (* ************************************************************************* *) subsection "Miscellaneous" (* ************************************************************************* *) lemma execn_noguards_no_Fault: assumes execn: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" assumes noguards_c: "noguards c" assumes noguards_\<Gamma>: "\<forall>p \<in> dom \<Gamma>. noguards (the (\<Gamma> p))" assumes s_no_Fault: "\<not> isFault s" shows "\<not> isFault t" using execn noguards_c s_no_Fault proof (induct) case (Call p bdy n s t) with noguards_\<Gamma> show ?case apply - apply (drule bspec [where x=p]) apply auto done qed (auto) lemma exec_noguards_no_Fault: assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" assumes noguards_c: "noguards c" assumes noguards_\<Gamma>: "\<forall>p \<in> dom \<Gamma>. noguards (the (\<Gamma> p))" assumes s_no_Fault: "\<not> isFault s" shows "\<not> isFault t" using exec noguards_c s_no_Fault proof (induct) case (Call p bdy s t) with noguards_\<Gamma> show ?case apply - apply (drule bspec [where x=p]) apply auto done qed auto lemma execn_nothrows_no_Abrupt: assumes execn: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> =n\<Rightarrow> t" assumes nothrows_c: "nothrows c" assumes nothrows_\<Gamma>: "\<forall>p \<in> dom \<Gamma>. nothrows (the (\<Gamma> p))" assumes s_no_Abrupt: "\<not>(isAbr s)" shows "\<not>(isAbr t)" using execn nothrows_c s_no_Abrupt proof (induct) case (Call p bdy n s t) with nothrows_\<Gamma> show ?case apply - apply (drule bspec [where x=p]) apply auto done qed (auto) lemma exec_nothrows_no_Abrupt: assumes exec: "\<Gamma>\<turnstile>\<langle>c,s\<rangle> \<Rightarrow> t" assumes nothrows_c: "nothrows c" assumes nothrows_\<Gamma>: "\<forall>p \<in> dom \<Gamma>. nothrows (the (\<Gamma> p))" assumes s_no_Abrupt: "\<not>(isAbr s)" shows "\<not>(isAbr t)" using exec nothrows_c s_no_Abrupt proof (induct) case (Call p bdy s t) with nothrows_\<Gamma> show ?case apply - apply (drule bspec [where x=p]) apply auto done qed (auto) end
Require Export ct16. Section DivConq. Variable A : Type. Variable le: A -> A -> Prop. Variable le_dec: forall (x y: A), {le x y} + {~le x y}. Implicit Type l : list A. (* split_pivot:= * takes an input term as pivot and list l and split into two sublists where the * first sublist contains all element/s that is/are le_dec _ pivot and the * second sublist contains the rest of the element/s. *) Fixpoint split_pivot (pivot : A) l : list A * list A := match l with | nil => (nil, nil) | a :: l' => let (l1, l2) := (split_pivot pivot l') in if le_dec a pivot then (a :: l1, l2) else (l1, a :: l2) end. (* split_pivot_wf: * states that for any list ls, each of the sublists generated has length less * than or equal to its original list's. *) Lemma split_pivot_wf1 : forall a l, length (fst (split_pivot a l)) <= length l. Proof. induction l; simpl; auto; destruct (le_dec a0 a); destruct (split_pivot a l); simpl in *; auto; apply le_n_S; auto. Defined. Lemma split_pivot_wf2 : forall a l, length (snd (split_pivot a l)) <= length l. Proof. induction l; simpl; auto; destruct (le_dec a0 a); destruct (split_pivot a l); simpl in *; auto; apply le_n_S; auto. Defined. (* div_conq_pivot: * - another variation of div_conq_split, just that for this, it will use * split_pivot instead. * - To prove some proposition P holds for all lists ls, one needs to prove the * following: * 1. P holds for empty list, nil. * 2. If P hold fst(split_pivot a l) and snd(split_pivot a l), then P must * also hold for (a :: l). *) Theorem div_conq_pivot : forall (P : list A -> Type), P nil -> (forall a l, P (fst (split_pivot a l)) -> P (snd (split_pivot a l)) -> P (a :: l)) -> forall l, P l. Proof. intros; eapply well_founded_induction_type. eapply lengthOrder_wf. destruct x; intros; auto; apply X0; apply X1; apply le_lt_n_Sm. apply split_pivot_wf1. apply split_pivot_wf2. Defined. Hypothesis notle_le: forall x y, ~ le x y -> le y x. (* Forall_snd_split_pivot: * le a x for every element, x, in snd(split_pivot a l). *) Lemma Forall_snd_split_pivot : forall a l, Forall (le a) (snd(split_pivot a l)). Proof. induction l; simpl; auto; destruct (le_dec a0 a); destruct (split_pivot a l); simpl in *; auto. Defined. End DivConq. Ltac div_conq_pivot := eapply div_conq_pivot.
{-# OPTIONS --cubical-compatible #-} open import Agda.Builtin.Equality postulate A : Set B : A → Set data H (@0 A : Set) : Set where con : (@0 x : A) → H A data G : Set where con : (@0 x : A) → (@0 b : B x) → G data D : Set where con : (@0 x : A) → B x → D
/* histogram/get2d.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_histogram2d.h> #include "find.c" double gsl_histogram2d_get (const gsl_histogram2d * h, const size_t i, const size_t j) { const size_t nx = h->nx; const size_t ny = h->ny; if (i >= nx) { GSL_ERROR_VAL ("index i lies outside valid range of 0 .. nx - 1", GSL_EDOM, 0); } if (j >= ny) { GSL_ERROR_VAL ("index j lies outside valid range of 0 .. ny - 1", GSL_EDOM, 0); } return h->bin[i * ny + j]; } int gsl_histogram2d_get_xrange (const gsl_histogram2d * h, const size_t i, double *xlower, double *xupper) { const size_t nx = h->nx; if (i >= nx) { GSL_ERROR ("index i lies outside valid range of 0 .. nx - 1", GSL_EDOM); } *xlower = h->xrange[i]; *xupper = h->xrange[i + 1]; return GSL_SUCCESS; } int gsl_histogram2d_get_yrange (const gsl_histogram2d * h, const size_t j, double *ylower, double *yupper) { const size_t ny = h->ny; if (j >= ny) { GSL_ERROR ("index j lies outside valid range of 0 .. ny - 1", GSL_EDOM); } *ylower = h->yrange[j]; *yupper = h->yrange[j + 1]; return GSL_SUCCESS; } int gsl_histogram2d_find (const gsl_histogram2d * h, const double x, const double y, size_t * i, size_t * j) { int status = find (h->nx, h->xrange, x, i); if (status) { GSL_ERROR ("x not found in range of h", GSL_EDOM); } status = find (h->ny, h->yrange, y, j); if (status) { GSL_ERROR ("y not found in range of h", GSL_EDOM); } return GSL_SUCCESS; }
lemma algebra_single_set: "X \<subseteq> S \<Longrightarrow> algebra S { {}, X, S - X, S }"
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,jl:hydrogen # text_representation: # extension: .jl # format_name: hydrogen # format_version: '1.3' # jupytext_version: 1.10.3 # kernelspec: # display_name: Julia 1.6.4 # language: julia # name: julia-1.6 # --- # %% [markdown] # # Hamiltonian Monte Carlo with leapfrog # # Scalar version: https://github.com/genkuroki/public/blob/main/0018/HMC%20leapfrog.ipynb # %% tags=[] module My using ConcreteStructs: @concrete using Parameters: @unpack using LinearAlgebra: dot using ForwardDiff: gradient using Random: default_rng, randn! using StaticArrays: SVector, MVector @concrete struct LFProblem{dim} ϕ; H; F; dt; nsteps end """Assume ϕ is a potential function.""" function LFProblem(dim, ϕ; dt = 1.0, nsteps = 40) H(x, v, param) = dot(v, v)/2 + ϕ(x, param) F(x, param) = -gradient(x -> ϕ(x, param), x) LFProblem{dim}(ϕ, H, F, dt, nsteps) end """Assume ϕ is a potential function and ∇ϕ its gradient.""" function LFProblem(dim, ϕ, ∇ϕ; dt = 1.0, nsteps = 40) H(x, v, param) = dot(v, v)/2 + ϕ(x, param) F(x, param) = -∇ϕ(x, param) LFProblem{dim}(ϕ, H, F, dt, nsteps) end """Numerically solve Hamilton's equation of motion with leapfrog method""" function solve(lf::LFProblem, x, v, param) @unpack F, dt, nsteps = lf v = v + F(x, param)*dt/2 x = x + v*dt for _ in 2:nsteps v = v + F(x, param)*dt x = x + v*dt end v = v + F(x, param)*dt/2 x, v end @inline function _update!(lf::LFProblem{dim}, x, vtmp, param, rng) where dim @unpack H = lf v = SVector{dim}(randn!(rng, vtmp)) xnew, vnew = solve(lf, x, v, param) dH = H(xnew, vnew, param) - H(x, v, param) rand(rng) ≤ exp(-dH) ? xnew : x end """Hamiltonian Monte Carlo""" function HMC(lf::LFProblem{dim}, param = nothing; niters = 10^5, thin = 1, nwarmups = 0, rng = default_rng(), init = SVector{dim}(randn(rng, dim))) where dim vtmp = MVector{dim}(zeros(eltype(init), dim)) x = init for _ in 1:nwarmups x = _update!(lf, x, vtmp, param, rng) end sample = Vector{typeof(init)}(undef, niters) for i in 1:niters for _ in 1:thin x = _update!(lf, x, vtmp, param, rng) end @inbounds sample[i] = x end sample end end # %% using Plots using BenchmarkTools using StaticArrays using LinearAlgebra using KernelDensity using Statistics using QuadGK using Distributions using Symbolics # %% [markdown] # ## 2-dimensional normal distribution # %% A = @SMatrix [ 1 1/2 1/2 1 ] param = (; A = A) ϕ(x, param) = dot(x, param.A, x)/2 lf = My.LFProblem(2, ϕ) # %% @time sample = My.HMC(lf, param) @time sample = My.HMC(lf, param) @time sample = My.HMC(lf, param); # %% @btime My.HMC($lf, $param); # %% X, Y = first.(sample), last.(sample) d = InterpKDE(kde((X, Y))) x, y = range(extrema(X)...; length=201), range(extrema(Y)...; length=201) heatmap(x, y, (x, y) -> pdf(d, x, y); size=(450, 400), right_margin=3Plots.mm) # %% f(n) = mean(x -> x*x', @view sample[1:n]) n = 1:1000 S = f.(n) S11 = (S -> S[1,1]).(S) S22 = (S -> S[2,2]).(S) S12 = (S -> S[1,2]).(S) ymin = min(-1.5, minimum(S11), minimum(S22), minimum(S12)) ymax = max(2.5, maximum(S11), maximum(S22), maximum(S12)) plot(ylim = (ymin, ymax)) plot!(S11; label="s11", c=1) hline!([inv(A)[1,1]]; label="", c=1, ls=:dash) plot!(S22; label="s22", c=2) hline!([inv(A)[2,2]]; label="", c=2, ls=:dash) plot!(S12; label="s12", c=3) hline!([inv(A)[1,2]]; label="", c=3, ls=:dash) # %% [markdown] # ## φ(x) = a(x² - 1)² # %% ϕ4(x, a) = a * (x[1]^2 - 1)^2 a = [3, 4, 5, 6, 7, 8] XX = Vector{Float64}[] ZZ = Float64[] PP = [] for i in eachindex(a) Z = quadgk(x -> exp(-ϕ4((x,), a[i])), -Inf, Inf)[1] push!(ZZ, Z) lf = My.LFProblem(1, ϕ4; dt = 0.05, nsteps = 100) @time X = first.(My.HMC(lf, a[i])) flush(stdout) push!(XX, X) P = plot() histogram!(X; norm=true, alpha=0.3, label="HMC LF sample", bin=100, c=i) plot!(x -> exp(-ϕ4(x, a[i]))/Z, -2, 2; label="exp(-ϕ2(x))/Z", lw=2, c=i) plot!(; legend=false, xtick=-2:0.5:2) title!("ϕ(x) = a(x² - 1)² for a = $(a[i])", titlefontsize=9) push!(PP, P) end plot(PP...; size=(800, 450), layout=(3, 2)) # %% QQ = [] for i in eachindex(a) Q = plot(XX[i][1:10000]; ylim=(-1.5, 1.5), label="", c=i, lw=0.5) title!("ϕ(x) = a(x² - 1)² for a = $(a[i])", titlefontsize=9) push!(QQ, Q) end plot(QQ...; size=(800, 900), layout=(length(a), 1)) # %% [markdown] # ## Baysian inference for a sample of the standard normal distribution # %% n = 10 sample_normal = randn(n) f(y, m, s) = (y - m)^2/(2s^2) + log(s) negloglik(w, sample) = sum(y -> f(y, w[1], exp(w[2])), sample) lf = My.LFProblem(2, negloglik; dt = 0.1, nsteps = 30) # %% @time sample = My.HMC(lf, sample_normal; init = SVector(0.0, 0.0)) @time sample = My.HMC(lf, sample_normal; init = SVector(0.0, 0.0)) @time sample = My.HMC(lf, sample_normal; init = SVector(0.0, 0.0)) # %% m, logs = first.(sample), last.(sample) d = InterpKDE(kde((m, logs))) x, y = range(extrema(m)...; length=201), range(extrema(logs)...; length=201) heatmap(x, y, (x, y) -> pdf(d, x, y); size=(450, 400), xlabel="μ", ylabel="log(σ)") # %% [markdown] # ## Symbolics.jl example # %% dim = 2 @variables a[1:dim, 1:dim], x[1:dim] aa, xx = collect.((a, x)) # %% phi_sym = dot(xx, aa, xx)/2 |> expand |> simplify # %% dphi_sym = Symbolics.gradient(phi_sym, xx) # %% phi_rgf = build_function(phi_sym, xx, aa; expression = Val(false)) dphi_rgf = build_function(dphi_sym, xx, aa; expression = Val(false))[1] lf = My.LFProblem(dim, phi_rgf, dphi_rgf); # %% param = A = @SMatrix [ 1 1/2 1/2 1 ] # %% @time sample = My.HMC(lf, param) @time sample = My.HMC(lf, param) @time sample = My.HMC(lf, param); # %% @btime My.HMC($lf, $param); # %% X, Y = first.(sample), last.(sample) d = InterpKDE(kde((X, Y))) x, y = range(extrema(X)...; length=201), range(extrema(Y)...; length=201) heatmap(x, y, (x, y) -> pdf(d, x, y); size=(450, 400), right_margin=3Plots.mm) # %% f(n) = mean(x -> x*x', @view sample[1:n]) n = 1:1000 S = f.(n) S11 = (S -> S[1,1]).(S) S22 = (S -> S[2,2]).(S) S12 = (S -> S[1,2]).(S) ymin = min(-1.5, minimum(S11), minimum(S22), minimum(S12)) ymax = max(2.5, maximum(S11), maximum(S22), maximum(S12)) plot(ylim = (ymin, ymax)) plot!(S11; label="s11", c=1) hline!([inv(A)[1,1]]; label="", c=1, ls=:dash) plot!(S22; label="s22", c=2) hline!([inv(A)[2,2]]; label="", c=2, ls=:dash) plot!(S12; label="s12", c=3) hline!([inv(A)[1,2]]; label="", c=3, ls=:dash) # %%
(* Author: Norbert Schirmer Maintainer: Norbert Schirmer, norbert.schirmer at web de License: LGPL *) (* Title: XVcgEx.thy Author: Norbert Schirmer, TU Muenchen Copyright (C) 2006-2008 Norbert Schirmer Some rights reserved, TU Muenchen This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) section "Examples for Parallel Assignments" theory XVcgEx imports "../XVcg" begin record "globals" = "G_'"::"nat" "H_'"::"nat" record 'g vars = "'g state" + A_' :: nat B_' :: nat C_' :: nat I_' :: nat M_' :: nat N_' :: nat R_' :: nat S_' :: nat Arr_' :: "nat list" Abr_':: string term "BASIC \<acute>A :== x, \<acute>B :== y END" term "BASIC \<acute>G :== \<acute>H, \<acute>H :== \<acute>G END" term "BASIC LET (x,y) = (\<acute>A,b); z = \<acute>B IN \<acute>A :== x, \<acute>G :== \<acute>A + y + z END" lemma "\<Gamma>\<turnstile> \<lbrace>\<acute>A = 0\<rbrace> \<lbrace>\<acute>A < 0\<rbrace> \<longmapsto> BASIC LET (a,b,c) = foo \<acute>A IN \<acute>A :== a, \<acute>B :== b, \<acute>C :== c END \<lbrace>\<acute>A = x \<and> \<acute>B = y \<and> \<acute>C = c\<rbrace>" apply vcg oops lemma "\<Gamma>\<turnstile> \<lbrace>\<acute>A = 0\<rbrace> \<lbrace>\<acute>A < 0\<rbrace> \<longmapsto> BASIC LET (a,b,c) = foo \<acute>A IN \<acute>A :== a, \<acute>G :== b + \<acute>B, \<acute>H :== c END \<lbrace>\<acute>A = x \<and> \<acute>G = y \<and> \<acute>H = c\<rbrace>" apply vcg oops definition foo:: "nat \<Rightarrow> (nat \<times> nat \<times> nat)" where "foo n = (n,n+1,n+2)" lemma "\<Gamma>\<turnstile> \<lbrace>\<acute>A = 0\<rbrace> \<lbrace>\<acute>A < 0\<rbrace> \<longmapsto> BASIC LET (a,b,c) = foo \<acute>A IN \<acute>A :== a, \<acute>G :== b + \<acute>B, \<acute>H :== c END \<lbrace>\<acute>A = x \<and> \<acute>G = y \<and> \<acute>H = c\<rbrace>" apply (vcg add: foo_def snd_conv fst_conv) oops end
(* Title: HOL/Auth/Guard/GuardK.thy Author: Frederic Blanqui, University of Cambridge Computer Laboratory Copyright 2002 University of Cambridge Very similar to Guard except: - Guard is replaced by GuardK, guard by guardK, Nonce by Key - some scripts are slightly modified (+ keyset_in, kparts_parts) - the hypothesis Key n ~:G (keyset G) is added *) section\<open>protocol-independent confidentiality theorem on keys\<close> theory GuardK imports Analz Extensions begin (****************************************************************************** messages where all the occurrences of Key n are in a sub-message of the form Crypt (invKey K) X with K:Ks ******************************************************************************) inductive_set guardK :: "nat => key set => msg set" for n :: nat and Ks :: "key set" where No_Key [intro]: "Key n \<notin> parts {X} \<Longrightarrow> X \<in> guardK n Ks" | Guard_Key [intro]: "invKey K \<in> Ks ==> Crypt K X \<in> guardK n Ks" | Crypt [intro]: "X \<in> guardK n Ks \<Longrightarrow> Crypt K X \<in> guardK n Ks" | Pair [intro]: "[| X \<in> guardK n Ks; Y \<in> guardK n Ks |] ==> \<lbrace>X,Y\<rbrace> \<in> guardK n Ks" subsection\<open>basic facts about \<^term>\<open>guardK\<close>\<close> lemma Nonce_is_guardK [iff]: "Nonce p \<in> guardK n Ks" by auto lemma Agent_is_guardK [iff]: "Agent A \<in> guardK n Ks" by auto lemma Number_is_guardK [iff]: "Number r \<in> guardK n Ks" by auto lemma Key_notin_guardK: "X \<in> guardK n Ks \<Longrightarrow> X \<noteq> Key n" by (erule guardK.induct, auto) lemma Key_notin_guardK_iff [iff]: "Key n \<notin> guardK n Ks" by (auto dest: Key_notin_guardK) lemma guardK_has_Crypt [rule_format]: "X \<in> guardK n Ks \<Longrightarrow> Key n \<in> parts {X} \<longrightarrow> (\<exists>K Y. Crypt K Y \<in> kparts {X} \<and> Key n \<in> parts {Y})" by (erule guardK.induct, auto) lemma Key_notin_kparts_msg: "X \<in> guardK n Ks \<Longrightarrow> Key n \<notin> kparts {X}" by (erule guardK.induct, auto dest: kparts_parts) lemma Key_in_kparts_imp_no_guardK: "Key n \<in> kparts H \<Longrightarrow> \<exists>X. X \<in> H \<and> X \<notin> guardK n Ks" apply (drule in_kparts, clarify) apply (rule_tac x=X in exI, clarify) by (auto dest: Key_notin_kparts_msg) lemma guardK_kparts [rule_format]: "X \<in> guardK n Ks \<Longrightarrow> Y \<in> kparts {X} \<longrightarrow> Y \<in> guardK n Ks" by (erule guardK.induct, auto dest: kparts_parts parts_sub) lemma guardK_Crypt: "[| Crypt K Y \<in> guardK n Ks; K \<notin> invKey`Ks |] ==> Y \<in> guardK n Ks" by (ind_cases "Crypt K Y \<in> guardK n Ks") (auto intro!: image_eqI) lemma guardK_MPair [iff]: "(\<lbrace>X,Y\<rbrace> \<in> guardK n Ks) = (X \<in> guardK n Ks \<and> Y \<in> guardK n Ks)" by (auto, (ind_cases "\<lbrace>X,Y\<rbrace> \<in> guardK n Ks", auto)+) lemma guardK_not_guardK [rule_format]: "X \<in>guardK n Ks \<Longrightarrow> Crypt K Y \<in> kparts {X} \<longrightarrow> Key n \<in> kparts {Y} \<longrightarrow> Y \<notin> guardK n Ks" by (erule guardK.induct, auto dest: guardK_kparts) lemma guardK_extand: "[| X \<in> guardK n Ks; Ks \<subseteq> Ks'; [| K \<in> Ks'; K \<notin> Ks |] ==> Key K \<notin> parts {X} |] ==> X \<in> guardK n Ks'" by (erule guardK.induct, auto) subsection\<open>guarded sets\<close> definition GuardK :: "nat \<Rightarrow> key set \<Rightarrow> msg set \<Rightarrow> bool" where "GuardK n Ks H \<equiv> \<forall>X. X \<in> H \<longrightarrow> X \<in> guardK n Ks" subsection\<open>basic facts about \<^term>\<open>GuardK\<close>\<close> lemma GuardK_empty [iff]: "GuardK n Ks {}" by (simp add: GuardK_def) lemma Key_notin_kparts [simplified]: "GuardK n Ks H \<Longrightarrow> Key n \<notin> kparts H" by (auto simp: GuardK_def dest: in_kparts Key_notin_kparts_msg) lemma GuardK_must_decrypt: "[| GuardK n Ks H; Key n \<in> analz H |] ==> \<exists>K Y. Crypt K Y \<in> kparts H \<and> Key (invKey K) \<in> kparts H" apply (drule_tac P="\<lambda>G. Key n \<in> G" in analz_pparts_kparts_substD, simp) by (drule must_decrypt, auto dest: Key_notin_kparts) lemma GuardK_kparts [intro]: "GuardK n Ks H \<Longrightarrow> GuardK n Ks (kparts H)" by (auto simp: GuardK_def dest: in_kparts guardK_kparts) lemma GuardK_mono: "[| GuardK n Ks H; G \<subseteq> H |] ==> GuardK n Ks G" by (auto simp: GuardK_def) lemma GuardK_insert [iff]: "GuardK n Ks (insert X H) = (GuardK n Ks H \<and> X \<in> guardK n Ks)" by (auto simp: GuardK_def) lemma GuardK_Un [iff]: "GuardK n Ks (G Un H) = (GuardK n Ks G & GuardK n Ks H)" by (auto simp: GuardK_def) lemma GuardK_synth [intro]: "GuardK n Ks G \<Longrightarrow> GuardK n Ks (synth G)" by (auto simp: GuardK_def, erule synth.induct, auto) lemma GuardK_analz [intro]: "[| GuardK n Ks G; \<forall>K. K \<in> Ks \<longrightarrow> Key K \<notin> analz G |] ==> GuardK n Ks (analz G)" apply (auto simp: GuardK_def) apply (erule analz.induct, auto) by (ind_cases "Crypt K Xa \<in> guardK n Ks" for K Xa, auto) lemma in_GuardK [dest]: "[| X \<in> G; GuardK n Ks G |] ==> X \<in> guardK n Ks" by (auto simp: GuardK_def) lemma in_synth_GuardK: "[| X \<in> synth G; GuardK n Ks G |] ==> X \<in> guardK n Ks" by (drule GuardK_synth, auto) lemma in_analz_GuardK: "[| X \<in> analz G; GuardK n Ks G; \<forall>K. K \<in> Ks \<longrightarrow> Key K \<notin> analz G |] ==> X \<in> guardK n Ks" by (drule GuardK_analz, auto) lemma GuardK_keyset [simp]: "[| keyset G; Key n \<notin> G |] ==> GuardK n Ks G" by (simp only: GuardK_def, clarify, drule keyset_in, auto) lemma GuardK_Un_keyset: "[| GuardK n Ks G; keyset H; Key n \<notin> H |] ==> GuardK n Ks (G Un H)" by auto lemma in_GuardK_kparts: "[| X \<in> G; GuardK n Ks G; Y \<in> kparts {X} |] ==> Y \<in> guardK n Ks" by blast lemma in_GuardK_kparts_neq: "[| X \<in> G; GuardK n Ks G; Key n' \<in> kparts {X} |] ==> n \<noteq> n'" by (blast dest: in_GuardK_kparts) lemma in_GuardK_kparts_Crypt: "[| X \<in> G; GuardK n Ks G; is_MPair X; Crypt K Y \<in> kparts {X}; Key n \<in> kparts {Y} |] ==> invKey K \<in> Ks" apply (drule in_GuardK, simp) apply (frule guardK_not_guardK, simp+) apply (drule guardK_kparts, simp) by (ind_cases "Crypt K Y \<in> guardK n Ks", auto) lemma GuardK_extand: "[| GuardK n Ks G; Ks \<subseteq> Ks'; [| K \<in> Ks'; K \<notin> Ks |] ==> Key K \<notin> parts G |] ==> GuardK n Ks' G" by (auto simp: GuardK_def dest: guardK_extand parts_sub) subsection\<open>set obtained by decrypting a message\<close> abbreviation (input) decrypt :: "msg set \<Rightarrow> key \<Rightarrow> msg \<Rightarrow> msg set" where "decrypt H K Y \<equiv> insert Y (H - {Crypt K Y})" lemma analz_decrypt: "[| Crypt K Y \<in> H; Key (invKey K) \<in> H; Key n \<in> analz H |] ==> Key n \<in> analz (decrypt H K Y)" apply (drule_tac P="\<lambda>H. Key n \<in> analz H" in ssubst [OF insert_Diff]) apply assumption apply (simp only: analz_Crypt_if, simp) done lemma parts_decrypt: "[| Crypt K Y \<in> H; X \<in> parts (decrypt H K Y) |] ==> X \<in> parts H" by (erule parts.induct, auto intro: parts.Fst parts.Snd parts.Body) subsection\<open>number of Crypt's in a message\<close> fun crypt_nb :: "msg => nat" where "crypt_nb (Crypt K X) = Suc (crypt_nb X)" | "crypt_nb \<lbrace>X,Y\<rbrace> = crypt_nb X + crypt_nb Y" | "crypt_nb X = 0" (* otherwise *) subsection\<open>basic facts about \<^term>\<open>crypt_nb\<close>\<close> lemma non_empty_crypt_msg: "Crypt K Y \<in> parts {X} \<Longrightarrow> crypt_nb X \<noteq> 0" by (induct X, simp_all, safe, simp_all) subsection\<open>number of Crypt's in a message list\<close> primrec cnb :: "msg list => nat" where "cnb [] = 0" | "cnb (X#l) = crypt_nb X + cnb l" subsection\<open>basic facts about \<^term>\<open>cnb\<close>\<close> lemma cnb_app [simp]: "cnb (l @ l') = cnb l + cnb l'" by (induct l, auto) lemma mem_cnb_minus: "x \<in> set l ==> cnb l = crypt_nb x + (cnb l - crypt_nb x)" by (induct l, auto) lemmas mem_cnb_minus_substI = mem_cnb_minus [THEN ssubst] lemma cnb_minus [simp]: "x \<in> set l ==> cnb (remove l x) = cnb l - crypt_nb x" apply (induct l, auto) by (erule_tac l=l and x=x in mem_cnb_minus_substI, simp) lemma parts_cnb: "Z \<in> parts (set l) \<Longrightarrow> cnb l = (cnb l - crypt_nb Z) + crypt_nb Z" by (erule parts.induct, auto simp: in_set_conv_decomp) lemma non_empty_crypt: "Crypt K Y \<in> parts (set l) \<Longrightarrow> cnb l \<noteq> 0" by (induct l, auto dest: non_empty_crypt_msg parts_insert_substD) subsection\<open>list of kparts\<close> lemma kparts_msg_set: "\<exists>l. kparts {X} = set l \<and> cnb l = crypt_nb X" apply (induct X, simp_all) apply (rename_tac agent, rule_tac x="[Agent agent]" in exI, simp) apply (rename_tac nat, rule_tac x="[Number nat]" in exI, simp) apply (rename_tac nat, rule_tac x="[Nonce nat]" in exI, simp) apply (rename_tac nat, rule_tac x="[Key nat]" in exI, simp) apply (rule_tac x="[Hash X]" in exI, simp) apply (clarify, rule_tac x="l@la" in exI, simp) by (clarify, rename_tac nat X y, rule_tac x="[Crypt nat X]" in exI, simp) lemma kparts_set: "\<exists>l'. kparts (set l) = set l' & cnb l' = cnb l" apply (induct l) apply (rule_tac x="[]" in exI, simp, clarsimp) apply (rename_tac a b l') apply (subgoal_tac "\<exists>l''. kparts {a} = set l'' & cnb l'' = crypt_nb a", clarify) apply (rule_tac x="l''@l'" in exI, simp) apply (rule kparts_insert_substI, simp) by (rule kparts_msg_set) subsection\<open>list corresponding to "decrypt"\<close> definition decrypt' :: "msg list => key => msg => msg list" where "decrypt' l K Y == Y # remove l (Crypt K Y)" declare decrypt'_def [simp] subsection\<open>basic facts about \<^term>\<open>decrypt'\<close>\<close> lemma decrypt_minus: "decrypt (set l) K Y <= set (decrypt' l K Y)" by (induct l, auto) text\<open>if the analysis of a finite guarded set gives n then it must also give one of the keys of Ks\<close> lemma GuardK_invKey_by_list [rule_format]: "\<forall>l. cnb l = p \<longrightarrow> GuardK n Ks (set l) \<longrightarrow> Key n \<in> analz (set l) \<longrightarrow> (\<exists>K. K \<in> Ks \<and> Key K \<in> analz (set l))" apply (induct p) (* case p=0 *) apply (clarify, drule GuardK_must_decrypt, simp, clarify) apply (drule kparts_parts, drule non_empty_crypt, simp) (* case p>0 *) apply (clarify, frule GuardK_must_decrypt, simp, clarify) apply (drule_tac P="\<lambda>G. Key n \<in> G" in analz_pparts_kparts_substD, simp) apply (frule analz_decrypt, simp_all) apply (subgoal_tac "\<exists>l'. kparts (set l) = set l' \<and> cnb l' = cnb l", clarsimp) apply (drule_tac G="insert Y (set l' - {Crypt K Y})" and H="set (decrypt' l' K Y)" in analz_sub, rule decrypt_minus) apply (rule_tac analz_pparts_kparts_substI, simp) apply (case_tac "K \<in> invKey`Ks") (* K:invKey`Ks *) apply (clarsimp, blast) (* K ~:invKey`Ks *) apply (subgoal_tac "GuardK n Ks (set (decrypt' l' K Y))") apply (drule_tac x="decrypt' l' K Y" in spec, simp) apply (subgoal_tac "Crypt K Y \<in> parts (set l)") apply (drule parts_cnb, rotate_tac -1, simp) apply (clarify, drule_tac X="Key Ka" and H="insert Y (set l')" in analz_sub) apply (rule insert_mono, rule set_remove) apply (simp add: analz_insertD, blast) (* Crypt K Y:parts (set l) *) apply (blast dest: kparts_parts) (* GuardK n Ks (set (decrypt' l' K Y)) *) apply (rule_tac H="insert Y (set l')" in GuardK_mono) apply (subgoal_tac "GuardK n Ks (set l')", simp) apply (rule_tac K=K in guardK_Crypt, simp add: GuardK_def, simp) apply (drule_tac t="set l'" in sym, simp) apply (rule GuardK_kparts, simp, simp) apply (rule_tac B="set l'" in subset_trans, rule set_remove, blast) by (rule kparts_set) lemma GuardK_invKey_finite: "[| Key n \<in> analz G; GuardK n Ks G; finite G |] ==> \<exists>K. K \<in> Ks \<and> Key K \<in> analz G" apply (drule finite_list, clarify) by (rule GuardK_invKey_by_list, auto) lemma GuardK_invKey: "[| Key n \<in> analz G; GuardK n Ks G |] ==> \<exists>K. K \<in> Ks \<and> Key K \<in> analz G" by (auto dest: analz_needs_only_finite GuardK_invKey_finite) text\<open>if the analyse of a finite guarded set and a (possibly infinite) set of keys gives n then it must also gives Ks\<close> lemma GuardK_invKey_keyset: "[| Key n \<in> analz (G \<union> H); GuardK n Ks G; finite G; keyset H; Key n \<notin> H |] ==> \<exists>K. K \<in> Ks \<and> Key K \<in> analz (G \<union> H)" apply (frule_tac P="\<lambda>G. Key n \<in> G" and G=G in analz_keyset_substD, simp_all) apply (drule_tac G="G Un (H Int keysfor G)" in GuardK_invKey_finite) apply (auto simp: GuardK_def intro: analz_sub) by (drule keyset_in, auto) end
Barker 's sketches , drawings , and paintings of children were given to friends or to the parents of the subjects , donated to charitable institutions and church sponsored events , or exhibited through various art organizations . She illustrated magazine covers , dust jackets , and produced series of postcards for Raphael Tuck and other publishers such as Picturesque Children of the Allies ( 1915 ) , Seaside Holidays ( 1918 ) , and Shakespeare 's Boy and Girl Characters ( 1917 , 1920 ) . Her own Old Rhymes for All Times ( 1928 ) and The Lord of the Rushie River ( 1938 ) , a tale about a girl who lives among swans on a riverbank , were critically well received . Set about 1800 , Groundsel and Necklaces ( 1943 ) tells of a girl named Jenny who rescues her family from poverty through the agency of the fairies . The story features an old Scrooge @-@ like man called Mr. <unk> and tonally suggests a Dickensian social consciousness . Simon the Swan , intended as a sequel to Rushie River was outlined in 1943 with Groundsel , but only developed in 1953 . It was published posthumously in 1988 and is critically considered less successful than Groundsel .
{-# OPTIONS --cubical --no-import-sorts --safe #-} module Cubical.Relation.Unary.Raw where open import Cubical.Core.Everything open import Cubical.Foundations.Prelude using (isProp) open import Cubical.Data.Empty hiding (rec) open import Cubical.Data.Unit.Base using (⊤) open import Cubical.Data.Sigma open import Cubical.Data.Sum.Base using (_⊎_; rec) open import Cubical.Foundations.Function open import Cubical.Relation.Nullary open import Cubical.Relation.Nullary.Decidable using (IsYes) open import Cubical.Relation.Unary using (RawPred) private variable a b c ℓ ℓ₁ ℓ₂ : Level A : Type a B : Type b C : Type c ------------------------------------------------------------------------ -- Special sets -- The empty set. ∅ : RawPred A _ ∅ = λ _ → ⊥ -- The singleton set. {_} : A → RawPred A _ { x } = _≡ x -- The universal set. U : RawPred A _ U = λ _ → ⊤ ------------------------------------------------------------------------ -- Membership infix 6 _∈_ _∉_ _∈_ : A → RawPred A ℓ → Type _ x ∈ P = P x _∉_ : A → RawPred A ℓ → Type _ x ∉ P = ¬ x ∈ P ------------------------------------------------------------------------ -- Subset relations infix 6 _⊆_ _⊇_ _⊈_ _⊉_ _⊂_ _⊃_ _⊄_ _⊅_ _⊆_ : RawPred A ℓ₁ → RawPred A ℓ₂ → Type _ P ⊆ Q = ∀ {x} → x ∈ P → x ∈ Q _⊇_ : RawPred A ℓ₁ → RawPred A ℓ₂ → Type _ P ⊇ Q = Q ⊆ P _⊈_ : RawPred A ℓ₁ → RawPred A ℓ₂ → Type _ P ⊈ Q = ¬ (P ⊆ Q) _⊉_ : RawPred A ℓ₁ → RawPred A ℓ₂ → Type _ P ⊉ Q = ¬ (P ⊇ Q) _⊂_ : RawPred A ℓ₁ → RawPred A ℓ₂ → Type _ P ⊂ Q = P ⊆ Q × Q ⊈ P _⊃_ : RawPred A ℓ₁ → RawPred A ℓ₂ → Type _ P ⊃ Q = Q ⊂ P _⊄_ : RawPred A ℓ₁ → RawPred A ℓ₂ → Type _ P ⊄ Q = ¬ (P ⊂ Q) _⊅_ : RawPred A ℓ₁ → RawPred A ℓ₂ → Type _ P ⊅ Q = ¬ (P ⊃ Q) ------------------------------------------------------------------------ -- Properties of sets infix 10 Satisfiable Universal IUniversal -- Emptiness - no element satisfies P. Empty : RawPred A ℓ → Type _ Empty P = ∀ x → x ∉ P -- Satisfiable - at least one element satisfies P. Satisfiable : RawPred A ℓ → Type _ Satisfiable {A = A} P = ∃[ x ∈ A ] x ∈ P syntax Satisfiable P = ∃⟨ P ⟩ -- Universality - all elements satisfy P. Universal : RawPred A ℓ → Type _ Universal P = ∀ x → x ∈ P syntax Universal P = Π[ P ] -- Implicit universality - all elements satisfy P. IUniversal : RawPred A ℓ → Type _ IUniversal P = ∀ {x} → x ∈ P syntax IUniversal P = ∀[ P ] -- Decidability - it is possible to determine if an arbitrary element -- satisfies P. Decidable : RawPred A ℓ → Type _ Decidable P = ∀ x → Dec (P x) -- Disjointness - Any element satisfying both P and Q is contradictory. _⊃⊂_ : RawPred A ℓ₁ → RawPred A ℓ₂ → Type _ _⊃⊂_ P Q = ∀ {x} → x ∈ P → x ∈ Q → ⊥ -- Positive version of non-disjointness, dual to inclusion. _≬_ : RawPred A ℓ₁ → RawPred A ℓ₂ → Type _ _≬_ {A = A} P Q = ∃[ x ∈ A ] x ∈ P × x ∈ Q ------------------------------------------------------------------------ -- Operations on sets infix 10 ⋃ ⋂ infixr 9 _⊢_ infixr 8 _⇒_ infixr 7 _∩_ infixr 6 _∪_ infix 5 _≬_ -- Complement. ∁ : RawPred A ℓ → RawPred A ℓ ∁ P = λ x → x ∉ P -- Implication. _⇒_ : RawPred A ℓ₁ → RawPred A ℓ₂ → RawPred A _ P ⇒ Q = λ x → x ∈ P → x ∈ Q -- Union. _∪_ : RawPred A ℓ₁ → RawPred A ℓ₂ → RawPred A _ P ∪ Q = λ x → x ∈ P ⊎ x ∈ Q -- Intersection. _∩_ : RawPred A ℓ₁ → RawPred A ℓ₂ → RawPred A _ P ∩ Q = λ x → x ∈ P × x ∈ Q -- Infinitary union. ⋃ : ∀ {i} (I : Type i) → (I → RawPred A ℓ) → RawPred A _ ⋃ I P = λ x → Σ[ i ∈ I ] P i x syntax ⋃ I (λ i → P) = ⋃[ i ∶ I ] P -- Infinitary intersection. ⋂ : ∀ {i} (I : Type i) → (I → RawPred A ℓ) → RawPred A _ ⋂ I P = λ x → (i : I) → P i x syntax ⋂ I (λ i → P) = ⋂[ i ∶ I ] P -- Preimage. _⊢_ : (A → B) → RawPred B ℓ → RawPred A ℓ f ⊢ P = λ x → P (f x) ------------------------------------------------------------------------ -- Preservation under operations _Preserves_⟶_ : (A → B) → RawPred A ℓ₁ → RawPred B ℓ₂ → Type _ f Preserves P ⟶ Q = P ⊆ f ⊢ Q _Preserves_ : (A → A) → RawPred A ℓ → Type _ f Preserves P = f Preserves P ⟶ P -- A binary variant of _Preserves_⟶_. _Preserves₂_⟶_⟶_ : (A → B → C) → RawPred A ℓ₁ → RawPred B ℓ₂ → RawPred C ℓ → Type _ _∙_ Preserves₂ P ⟶ Q ⟶ R = ∀ {x y} → x ∈ P → y ∈ Q → x ∙ y ∈ R _Preserves₂_ : (A → A → A) → RawPred A ℓ → Type _ _∙_ Preserves₂ P = _∙_ Preserves₂ P ⟶ P ⟶ P ------------------------------------------------------------------------ -- Logical equivalence _⇔_ : RawPred A ℓ₁ → RawPred A ℓ₂ → Type _ P ⇔ Q = Π[ P ⇒ Q ∩ Q ⇒ P ] ------------------------------------------------------------------------ -- Predicate combinators -- These differ from the set operations above, as the carrier set of the -- resulting predicates are not the same as the carrier set of the -- component predicates. infixr 2 _⟨×⟩_ infixr 2 _⟨⊙⟩_ infixr 1 _⟨⊎⟩_ infixr 0 _⟨→⟩_ infixl 9 _⟨·⟩_ infix 10 _~ infixr 9 _⟨∘⟩_ infixr 2 _//_ _\\_ -- Product. _⟨×⟩_ : RawPred A ℓ₁ → RawPred B ℓ₂ → RawPred (A × B) _ (P ⟨×⟩ Q) (x , y) = x ∈ P × y ∈ Q -- Sum over one element. _⟨⊎⟩_ : RawPred A ℓ → RawPred B ℓ → RawPred (A ⊎ B) _ P ⟨⊎⟩ Q = rec P Q -- Sum over two elements. _⟨⊙⟩_ : RawPred A ℓ₁ → RawPred B ℓ₂ → RawPred (A × B) _ (P ⟨⊙⟩ Q) (x , y) = x ∈ P ⊎ y ∈ Q -- Implication. _⟨→⟩_ : RawPred A ℓ₁ → RawPred B ℓ₂ → RawPred (A → B) _ (P ⟨→⟩ Q) f = f Preserves P ⟶ Q -- Product. _⟨·⟩_ : (P : RawPred A ℓ₁) (Q : RawPred B ℓ₂) → (P ⟨×⟩ (P ⟨→⟩ Q)) ⊆ Q ∘ uncurry (flip _$_) (P ⟨·⟩ Q) (p , f) = f p -- Converse. _~ : RawPred (A × B) ℓ → RawPred (B × A) ℓ P ~ = P ∘ λ { (x , y) → y , x } -- Composition. _⟨∘⟩_ : RawPred (A × B) ℓ₁ → RawPred (B × C) ℓ₂ → RawPred (A × C) _ _⟨∘⟩_ {B = B} P Q (x , z) = ∃[ y ∈ B ] (x , y) ∈ P × (y , z) ∈ Q -- Post-division. _//_ : RawPred (A × C) ℓ₁ → RawPred (B × C) ℓ₂ → RawPred (A × B) _ (P // Q) (x , y) = Q ∘ (y ,_) ⊆ P ∘ (x ,_) -- Pre-division. _\\_ : RawPred (A × C) ℓ₁ → RawPred (A × B) ℓ₂ → RawPred (B × C) _ P \\ Q = (P ~ // Q ~) ~
from collections import namedtuple import numpy as np import talib from jesse.helpers import slice_candles from jesse.indicators.ma import ma StochasticFast = namedtuple('StochasticFast', ['k', 'd']) def stochf(candles: np.ndarray, fastk_period: int = 5, fastd_period: int = 3, fastd_matype: int = 0, sequential: bool = False) -> StochasticFast: """ Stochastic Fast :param candles: np.ndarray :param fastk_period: int - default=5 :param fastd_period: int - default=3 :param fastd_matype: int - default=0 :param sequential: bool - default=False :return: StochasticFast(k, d) """ candles = slice_candles(candles, sequential) candles_close = candles[:, 2] candles_high = candles[:, 3] candles_low = candles[:, 4] hh = talib.MAX(candles_high, fastk_period) ll = talib.MIN(candles_low, fastk_period) k = 100 * (candles_close - ll) / (hh - ll) d = ma(k, period=fastd_period, matype=fastd_matype, sequential=True) if sequential: return StochasticFast(k, d) else: return StochasticFast(k[-1], d[-1])
__precompile__(true) module CPEG # greet() = print("Hello World!") using LinearAlgebra using StaticArrays using ForwardDiff using SparseArrays using SuiteSparse using Printf include("qp_solver.jl") include("atmosphere.jl") include("scaling.jl") include("gravity.jl") include("aero_forces.jl") include("vehicle.jl") include("dynamics.jl") include("post_process.jl") end # module
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau Dependent functions with finite support (see `data/finsupp.lean`). -/ import data.finset data.set.finite algebra.big_operators algebra.module algebra.pi_instances universes u u₁ u₂ v v₁ v₂ v₃ w x y l variables (ι : Type u) (β : ι → Type v) def decidable_zero_symm {γ : Type w} [has_zero γ] [decidable_pred (eq (0 : γ))] : decidable_pred (λ x, x = (0:γ)) := λ x, decidable_of_iff (0 = x) eq_comm local attribute [instance] decidable_zero_symm namespace dfinsupp variable [Π i, has_zero (β i)] structure pre : Type (max u v) := (to_fun : Π i, β i) (pre_support : multiset ι) (zero : ∀ i, i ∈ pre_support ∨ to_fun i = 0) instance : setoid (pre ι β) := { r := λ x y, ∀ i, x.to_fun i = y.to_fun i, iseqv := ⟨λ f i, rfl, λ f g H i, (H i).symm, λ f g h H1 H2 i, (H1 i).trans (H2 i)⟩ } end dfinsupp variable {ι} @[reducible] def dfinsupp [Π i, has_zero (β i)] : Type* := quotient (dfinsupp.setoid ι β) variable {β} notation `Π₀` binders `, ` r:(scoped f, dfinsupp f) := r infix ` →ₚ `:25 := dfinsupp namespace dfinsupp section basic variables [Π i, has_zero (β i)] variables {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} variables [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] instance : has_coe_to_fun (Π₀ i, β i) := ⟨λ _, Π i, β i, λ f, quotient.lift_on f pre.to_fun $ λ _ _, funext⟩ instance : has_zero (Π₀ i, β i) := ⟨⟦⟨λ i, 0, ∅, λ i, or.inr rfl⟩⟧⟩ instance : inhabited (Π₀ i, β i) := ⟨0⟩ @[simp] lemma zero_apply {i : ι} : (0 : Π₀ i, β i) i = 0 := rfl @[extensionality] lemma ext {f g : Π₀ i, β i} (H : ∀ i, f i = g i) : f = g := quotient.induction_on₂ f g (λ _ _ H, quotient.sound H) H /-- The composition of `f : β₁ → β₂` and `g : Π₀ i, β₁ i` is `map_range f hf g : Π₀ i, β₂ i`, well defined when `f 0 = 0`. -/ def map_range (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (g : Π₀ i, β₁ i) : Π₀ i, β₂ i := quotient.lift_on g (λ x, ⟦(⟨λ i, f i (x.1 i), x.2, λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, hf]⟩ : pre ι β₂)⟧) $ λ x y H, quotient.sound $ λ i, by simp only [H i] @[simp] lemma map_range_apply {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} {i : ι} : map_range f hf g i = f i (g i) := quotient.induction_on g $ λ x, rfl def zip_with (f : Π i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0) (g₁ : Π₀ i, β₁ i) (g₂ : Π₀ i, β₂ i) : (Π₀ i, β i) := begin refine quotient.lift_on₂ g₁ g₂ (λ x y, ⟦(⟨λ i, f i (x.1 i) (y.1 i), x.2 + y.2, λ i, _⟩ : pre ι β)⟧) _, { cases x.3 i with h1 h1, { left, rw multiset.mem_add, left, exact h1 }, cases y.3 i with h2 h2, { left, rw multiset.mem_add, right, exact h2 }, right, rw [h1, h2, hf] }, exact λ x₁ x₂ y₁ y₂ H1 H2, quotient.sound $ λ i, by simp only [H1 i, H2 i] end @[simp] lemma zip_with_apply {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} {i : ι} : zip_with f hf g₁ g₂ i = f i (g₁ i) (g₂ i) := quotient.induction_on₂ g₁ g₂ $ λ _ _, rfl end basic section algebra instance [Π i, add_monoid (β i)] : has_add (Π₀ i, β i) := ⟨zip_with (λ _, (+)) (λ _, add_zero 0)⟩ @[simp] lemma add_apply [Π i, add_monoid (β i)] {g₁ g₂ : Π₀ i, β i} {i : ι} : (g₁ + g₂) i = g₁ i + g₂ i := zip_with_apply instance [Π i, add_monoid (β i)] : add_monoid (Π₀ i, β i) := { add_monoid . zero := 0, add := (+), add_assoc := λ f g h, ext $ λ i, by simp only [add_apply, add_assoc], zero_add := λ f, ext $ λ i, by simp only [add_apply, zero_apply, zero_add], add_zero := λ f, ext $ λ i, by simp only [add_apply, zero_apply, add_zero] } instance [Π i, add_monoid (β i)] {i : ι} : is_add_monoid_hom (λ g : Π₀ i : ι, β i, g i) := by refine_struct {..}; simp instance [Π i, add_group (β i)] : has_neg (Π₀ i, β i) := ⟨λ f, f.map_range (λ _, has_neg.neg) (λ _, neg_zero)⟩ instance [Π i, add_comm_monoid (β i)] : add_comm_monoid (Π₀ i, β i) := { add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm], .. dfinsupp.add_monoid } @[simp] lemma neg_apply [Π i, add_group (β i)] {g : Π₀ i, β i} {i : ι} : (- g) i = - g i := map_range_apply instance [Π i, add_group (β i)] : add_group (Π₀ i, β i) := { add_left_neg := λ f, ext $ λ i, by simp only [add_apply, neg_apply, zero_apply, add_left_neg], .. dfinsupp.add_monoid, .. (infer_instance : has_neg (Π₀ i, β i)) } @[simp] lemma sub_apply [Π i, add_group (β i)] {g₁ g₂ : Π₀ i, β i} {i : ι} : (g₁ - g₂) i = g₁ i - g₂ i := by rw [sub_eq_add_neg]; simp instance [Π i, add_comm_group (β i)] : add_comm_group (Π₀ i, β i) := { add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm], ..dfinsupp.add_group } def to_has_scalar {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] : has_scalar γ (Π₀ i, β i) := ⟨λc v, v.map_range (λ _, (•) c) (λ _, smul_zero _)⟩ local attribute [instance] to_has_scalar @[simp] lemma smul_apply {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] {i : ι} {b : γ} {v : Π₀ i, β i} : (b • v) i = b • (v i) := map_range_apply def to_module {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] : module γ (Π₀ i, β i) := module.of_core { smul_add := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, smul_add], add_smul := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, add_smul], one_smul := λ x, ext $ λ i, by simp only [smul_apply, one_smul], mul_smul := λ r s x, ext $ λ i, by simp only [smul_apply, smul_smul], .. (infer_instance : has_scalar γ (Π₀ i, β i)) } end algebra section filter_and_subtype_domain /-- `filter p f` is the function which is `f i` if `p i` is true and 0 otherwise. -/ def filter [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (f : Π₀ i, β i) : Π₀ i, β i := quotient.lift_on f (λ x, ⟦(⟨λ i, if p i then x.1 i else 0, x.2, λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H, quotient.sound $ λ i, by simp only [H i] @[simp] lemma filter_apply [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {i : ι} {f : Π₀ i, β i} : f.filter p i = if p i then f i else 0 := quotient.induction_on f $ λ x, rfl @[simp] lemma filter_apply_pos [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {f : Π₀ i, β i} {i : ι} (h : p i) : f.filter p i = f i := by simp only [filter_apply, if_pos h] @[simp] lemma filter_apply_neg [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {f : Π₀ i, β i} {i : ι} (h : ¬ p i) : f.filter p i = 0 := by simp only [filter_apply, if_neg h] lemma filter_pos_add_filter_neg [Π i, add_monoid (β i)] {f : Π₀ i, β i} {p : ι → Prop} [decidable_pred p] : f.filter p + f.filter (λi, ¬ p i) = f := ext $ λ i, by simp only [add_apply, filter_apply]; split_ifs; simp only [add_zero, zero_add] /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (f : Π₀ i, β i) : Π₀ i : subtype p, β i.1 := begin fapply quotient.lift_on f, { intro x, refine ⟦⟨λ i, x.1 i.1, (x.2.filter p).attach.map $ λ j, ⟨j.1, (multiset.mem_filter.1 j.2).2⟩, _⟩⟧, refine λ i, or.cases_on (x.3 i.1) (λ H, _) or.inr, left, rw multiset.mem_map, refine ⟨⟨i.1, multiset.mem_filter.2 ⟨H, i.2⟩⟩, _, subtype.eta _ _⟩, apply multiset.mem_attach }, intros x y H, exact quotient.sound (λ i, H i.1) end @[simp] lemma subtype_domain_zero [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] : subtype_domain p (0 : Π₀ i, β i) = 0 := rfl @[simp] lemma subtype_domain_apply [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {i : subtype p} {v : Π₀ i, β i} : (subtype_domain p v) i = v (i.val) := quotient.induction_on v $ λ x, rfl @[simp] lemma subtype_domain_add [Π i, add_monoid (β i)] {p : ι → Prop} [decidable_pred p] {v v' : Π₀ i, β i} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ i, by simp only [add_apply, subtype_domain_apply] instance subtype_domain.is_add_monoid_hom [Π i, add_monoid (β i)] {p : ι → Prop} [decidable_pred p] : is_add_monoid_hom (subtype_domain p : (Π₀ i : ι, β i) → Π₀ i : subtype p, β i) := by refine_struct {..}; simp @[simp] lemma subtype_domain_neg [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p] {v : Π₀ i, β i} : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ i, by simp only [neg_apply, subtype_domain_apply] @[simp] lemma subtype_domain_sub [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p] {v v' : Π₀ i, β i} : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ i, by simp only [sub_apply, subtype_domain_apply] end filter_and_subtype_domain variable [decidable_eq ι] section basic variable [Π i, has_zero (β i)] lemma finite_supp (f : Π₀ i, β i) : set.finite {i | f i ≠ 0} := quotient.induction_on f $ λ x, set.finite_subset (finset.finite_to_set x.2.to_finset) $ λ i H, multiset.mem_to_finset.2 $ (x.3 i).resolve_right H def mk (s : finset ι) (x : Π i : (↑s : set ι), β i.1) : Π₀ i, β i := ⟦⟨λ i, if H : i ∈ s then x ⟨i, H⟩ else 0, s.1, λ i, if H : i ∈ s then or.inl H else or.inr $ dif_neg H⟩⟧ @[simp] lemma mk_apply {s : finset ι} {x : Π i : (↑s : set ι), β i.1} {i : ι} : (mk s x : Π i, β i) i = if H : i ∈ s then x ⟨i, H⟩ else 0 := rfl theorem mk_inj (s : finset ι) : function.injective (@mk ι β _ _ s) := begin intros x y H, ext i, have h1 : (mk s x : Π i, β i) i = (mk s y : Π i, β i) i, {rw H}, cases i with i hi, change i ∈ s at hi, dsimp only [mk_apply, subtype.coe_mk] at h1, simpa only [dif_pos hi] using h1 end def single (i : ι) (b : β i) : Π₀ i, β i := mk (finset.singleton i) $ λ j, eq.rec_on (finset.mem_singleton.1 j.2).symm b @[simp] lemma single_apply {i i' b} : (single i b : Π₀ i, β i) i' = (if h : i = i' then eq.rec_on h b else 0) := begin dsimp only [single], by_cases h : i = i', { have h1 : i' ∈ finset.singleton i, { simp only [h, finset.mem_singleton] }, simp only [mk_apply, dif_pos h, dif_pos h1] }, { have h1 : i' ∉ finset.singleton i, { simp only [ne.symm h, finset.mem_singleton, not_false_iff] }, simp only [mk_apply, dif_neg h, dif_neg h1] } end @[simp] lemma single_zero {i} : (single i 0 : Π₀ i, β i) = 0 := quotient.sound $ λ j, if H : j ∈ finset.singleton i then by dsimp only; rw [dif_pos H]; cases finset.mem_singleton.1 H; refl else dif_neg H @[simp] lemma single_eq_same {i b} : (single i b : Π₀ i, β i) i = b := by simp only [single_apply, dif_pos rfl] @[simp] lemma single_eq_of_ne {i i' b} (h : i ≠ i') : (single i b : Π₀ i, β i) i' = 0 := by simp only [single_apply, dif_neg h] def erase (i : ι) (f : Π₀ i, β i) : Π₀ i, β i := quotient.lift_on f (λ x, ⟦(⟨λ j, if j = i then 0 else x.1 j, x.2, λ j, or.cases_on (x.3 j) or.inl $ λ H, or.inr $ by simp only [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H, quotient.sound $ λ j, if h : j = i then by simp only [if_pos h] else by simp only [if_neg h, H j] @[simp] lemma erase_apply {i j : ι} {f : Π₀ i, β i} : (f.erase i) j = if j = i then 0 else f j := quotient.induction_on f $ λ x, rfl @[simp] lemma erase_same {i : ι} {f : Π₀ i, β i} : (f.erase i) i = 0 := by simp @[simp] lemma erase_ne {i i' : ι} {f : Π₀ i, β i} (h : i' ≠ i) : (f.erase i) i' = f i' := by simp [h] end basic section add_monoid variable [Π i, add_monoid (β i)] @[simp] lemma single_add {i : ι} {b₁ b₂ : β i} : single i (b₁ + b₂) = single i b₁ + single i b₂ := ext $ assume i', begin by_cases h : i = i', { subst h, simp only [add_apply, single_eq_same] }, { simp only [add_apply, single_eq_of_ne h, zero_add] } end lemma single_add_erase {i : ι} {f : Π₀ i, β i} : single i (f i) + f.erase i = f := ext $ λ i', if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, add_zero] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), zero_add] lemma erase_add_single {i : ι} {f : Π₀ i, β i} : f.erase i + single i (f i) = f := ext $ λ i', if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, zero_add] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), add_zero] protected theorem induction {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (single i b + f)) : p f := begin refine quotient.induction_on f (λ x, _), cases x with f s H, revert f H, apply multiset.induction_on s, { intros f H, convert h0, ext i, exact (H i).resolve_left id }, intros i s ih f H, by_cases H1 : i ∈ s, { have H2 : ∀ j, j ∈ s ∨ f j = 0, { intro j, cases H j with H2 H2, { cases multiset.mem_cons.1 H2 with H3 H3, { left, rw H3, exact H1 }, { left, exact H3 } }, right, exact H2 }, have H3 : (⟦{to_fun := f, pre_support := i :: s, zero := H}⟧ : Π₀ i, β i) = ⟦{to_fun := f, pre_support := s, zero := H2}⟧, { exact quotient.sound (λ i, rfl) }, rw H3, apply ih }, have H2 : p (erase i ⟦{to_fun := f, pre_support := i :: s, zero := H}⟧), { dsimp only [erase, quotient.lift_on_beta], have H2 : ∀ j, j ∈ s ∨ ite (j = i) 0 (f j) = 0, { intro j, cases H j with H2 H2, { cases multiset.mem_cons.1 H2 with H3 H3, { right, exact if_pos H3 }, { left, exact H3 } }, right, split_ifs; [refl, exact H2] }, have H3 : (⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j), pre_support := i :: s, zero := _}⟧ : Π₀ i, β i) = ⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j), pre_support := s, zero := H2}⟧ := quotient.sound (λ i, rfl), rw H3, apply ih }, have H3 : single i _ + _ = (⟦{to_fun := f, pre_support := i :: s, zero := H}⟧ : Π₀ i, β i) := single_add_erase, rw ← H3, change p (single i (f i) + _), cases classical.em (f i = 0) with h h, { rw [h, single_zero, zero_add], exact H2 }, refine ha _ _ _ _ h H2, rw erase_same end lemma induction₂ {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (f + single i b)) : p f := dfinsupp.induction f h0 $ λ i b f h1 h2 h3, have h4 : f + single i b = single i b + f, { ext j, by_cases H : i = j, { subst H, simp [h1] }, { simp [H] } }, eq.rec_on h4 $ ha i b f h1 h2 h3 end add_monoid @[simp] lemma mk_add [Π i, add_monoid (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i.1} : mk s (x + y) = mk s x + mk s y := ext $ λ i, by simp only [add_apply, mk_apply]; split_ifs; [refl, rw zero_add] @[simp] lemma mk_zero [Π i, has_zero (β i)] {s : finset ι} : mk s (0 : Π i : (↑s : set ι), β i.1) = 0 := ext $ λ i, by simp only [mk_apply]; split_ifs; refl @[simp] lemma mk_neg [Π i, add_group (β i)] {s : finset ι} {x : Π i : (↑s : set ι), β i.1} : mk s (-x) = -mk s x := ext $ λ i, by simp only [neg_apply, mk_apply]; split_ifs; [refl, rw neg_zero] @[simp] lemma mk_sub [Π i, add_group (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i.1} : mk s (x - y) = mk s x - mk s y := ext $ λ i, by simp only [sub_apply, mk_apply]; split_ifs; [refl, rw sub_zero] instance [Π i, add_group (β i)] {s : finset ι} : is_add_group_hom (@mk ι β _ _ s) := ⟨λ _ _, mk_add⟩ section local attribute [instance] to_module variables (γ : Type w) [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] include γ @[simp] lemma mk_smul {s : finset ι} {c : γ} (x : Π i : (↑s : set ι), β i.1) : mk s (c • x) = c • mk s x := ext $ λ i, by simp only [smul_apply, mk_apply]; split_ifs; [refl, rw smul_zero] @[simp] lemma single_smul {i : ι} {c : γ} {x : β i} : single i (c • x) = c • single i x := ext $ λ i, by simp only [smul_apply, single_apply]; split_ifs; [cases h, rw smul_zero]; refl variable β def lmk (s : finset ι) : (Π i : (↑s : set ι), β i.1) →ₗ[γ] Π₀ i, β i := ⟨mk s, λ _ _, mk_add, λ c x, by rw [mk_smul γ x]⟩ def lsingle (i) : β i →ₗ[γ] Π₀ i, β i := ⟨single i, λ _ _, single_add, λ _ _, single_smul _⟩ variable {β} @[simp] lemma lmk_apply {s : finset ι} {x} : lmk β γ s x = mk s x := rfl @[simp] lemma lsingle_apply {i : ι} {x : β i} : lsingle β γ i x = single i x := rfl end section support_basic variables [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] def support (f : Π₀ i, β i) : finset ι := quotient.lift_on f (λ x, x.2.to_finset.filter $ λ i, x.1 i ≠ 0) $ begin intros x y Hxy, ext i, split, { intro H, rcases finset.mem_filter.1 H with ⟨h1, h2⟩, rw Hxy i at h2, exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (y.3 i).resolve_right h2, h2⟩ }, { intro H, rcases finset.mem_filter.1 H with ⟨h1, h2⟩, rw ← Hxy i at h2, exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (x.3 i).resolve_right h2, h2⟩ }, end @[simp] theorem support_mk_subset {s : finset ι} {x : Π i : (↑s : set ι), β i.1} : (mk s x).support ⊆ s := λ i H, multiset.mem_to_finset.1 (finset.mem_filter.1 H).1 @[simp] theorem mem_support_to_fun (f : Π₀ i, β i) (i) : i ∈ f.support ↔ f i ≠ 0 := begin refine quotient.induction_on f (λ x, _), dsimp only [support, quotient.lift_on_beta], rw [finset.mem_filter, multiset.mem_to_finset], exact and_iff_right_of_imp (x.3 i).resolve_right end theorem eq_mk_support (f : Π₀ i, β i) : f = mk f.support (λ i, f i.1) := by ext i; by_cases h : f i = 0; try {simp at h}; simp [h] @[simp] lemma support_zero : (0 : Π₀ i, β i).support = ∅ := rfl @[simp] lemma mem_support_iff (f : Π₀ i, β i) : ∀i:ι, i ∈ f.support ↔ f i ≠ 0 := f.mem_support_to_fun @[simp] lemma support_eq_empty {f : Π₀ i, β i} : f.support = ∅ ↔ f = 0 := ⟨λ H, ext $ by simpa [finset.ext] using H, by simp {contextual:=tt}⟩ instance decidable_zero : decidable_pred (eq (0 : Π₀ i, β i)) := λ f, decidable_of_iff _ $ support_eq_empty.trans eq_comm lemma support_subset_iff {s : set ι} {f : Π₀ i, β i} : ↑f.support ⊆ s ↔ (∀i∉s, f i = 0) := by simp [set.subset_def]; exact forall_congr (assume i, @not_imp_comm _ _ (classical.dec _) (classical.dec _)) lemma support_single_ne_zero {i : ι} {b : β i} (hb : b ≠ 0) : (single i b).support = {i} := begin ext j, by_cases h : i = j, { subst h, simp [hb] }, simp [ne.symm h, h] end lemma support_single_subset {i : ι} {b : β i} : (single i b).support ⊆ {i} := support_mk_subset section map_range_and_zip_with variables {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} variables [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] variables [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, decidable_pred (eq (0 : β₂ i))] lemma map_range_def {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} : map_range f hf g = mk g.support (λ i, f i.1 (g i.1)) := begin ext i, by_cases h : g i = 0, { simp [h, hf] }, { simp at h, simp [h, hf] } end lemma support_map_range {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} : (map_range f hf g).support ⊆ g.support := by simp [map_range_def] @[simp] lemma map_range_single {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {i : ι} {b : β₁ i} : map_range f hf (single i b) = single i (f i b) := dfinsupp.ext $ λ i', by by_cases i = i'; [{subst i', simp}, simp [h, hf]] lemma zip_with_def {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} : zip_with f hf g₁ g₂ = mk (g₁.support ∪ g₂.support) (λ i, f i.1 (g₁ i.1) (g₂ i.1)) := begin ext i, by_cases h1 : g₁ i = 0; by_cases h2 : g₂ i = 0; try {simp at h1 h2}; simp [h1, h2, hf] end lemma support_zip_with {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by simp [zip_with_def] end map_range_and_zip_with lemma erase_def (i : ι) (f : Π₀ i, β i) : f.erase i = mk (f.support.erase i) (λ j, f j.1) := begin ext j, by_cases h1 : j = i; by_cases h2 : f j = 0; try {simp at h2}; simp [h1, h2] end @[simp] lemma support_erase (i : ι) (f : Π₀ i, β i) : (f.erase i).support = f.support.erase i := begin ext j, by_cases h1 : j = i; by_cases h2 : f j = 0; try {simp at h2}; simp [h1, h2] end section filter_and_subtype_domain variables {p : ι → Prop} [decidable_pred p] lemma filter_def (f : Π₀ i, β i) : f.filter p = mk (f.support.filter p) (λ i, f i.1) := by ext i; by_cases h1 : p i; by_cases h2 : f i = 0; try {simp at h2}; simp [h1, h2] @[simp] lemma support_filter (f : Π₀ i, β i) : (f.filter p).support = f.support.filter p := by ext i; by_cases h : p i; simp [h] lemma subtype_domain_def (f : Π₀ i, β i) : f.subtype_domain p = mk (f.support.subtype p) (λ i, f i.1) := by ext i; cases i with i hi; by_cases h1 : p i; by_cases h2 : f i = 0; try {simp at h2}; dsimp; simp [h1, h2] @[simp] lemma support_subtype_domain {f : Π₀ i, β i} : (subtype_domain p f).support = f.support.subtype p := by ext i; cases i with i hi; by_cases h1 : p i; by_cases h2 : f i = 0; try {simp at h2}; dsimp; simp [h1, h2] end filter_and_subtype_domain end support_basic lemma support_add [Π i, add_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {g₁ g₂ : Π₀ i, β i} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with @[simp] lemma support_neg [Π i, add_group (β i)] [Π i, decidable_pred (eq (0 : β i))] {f : Π₀ i, β i} : support (-f) = support f := by ext i; simp instance [decidable_eq ι] [Π i, has_zero (β i)] [Π i, decidable_eq (β i)] : decidable_eq (Π₀ i, β i) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀i∈f.support, f i = g i)) ⟨assume ⟨h₁, h₂⟩, ext $ assume i, if h : i ∈ f.support then h₂ i h else have hf : f i = 0, by rwa [f.mem_support_iff, not_not] at h, have hg : g i = 0, by rwa [h₁, g.mem_support_iff, not_not] at h, by rw [hf, hg], by intro h; subst h; simp⟩ section prod_and_sum variables {γ : Type w} -- [to_additive dfinsupp.sum] for dfinsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g i (f i)` over the support of `f`. -/ def sum [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_monoid γ] (f : Π₀ i, β i) (g : Π i, β i → γ) : γ := f.support.sum (λi, g i (f i)) /-- `prod f g` is the product of `g i (f i)` over the support of `f`. -/ @[to_additive dfinsupp.sum] def prod [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] (f : Π₀ i, β i) (g : Π i, β i → γ) : γ := f.support.prod (λi, g i (f i)) attribute [to_additive dfinsupp.sum.equations._eqn_1] dfinsupp.prod.equations._eqn_1 @[to_additive dfinsupp.sum_map_range_index] lemma prod_map_range_index {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, decidable_pred (eq (0 : β₂ i))] [comm_monoid γ] {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} {h : Π i, β₂ i → γ} (h0 : ∀i, h i 0 = 1) : (map_range f hf g).prod h = g.prod (λi b, h i (f i b)) := begin rw [map_range_def], refine (finset.prod_subset support_mk_subset _).trans _, { intros i h1 h2, dsimp, simp [h1] at h2, dsimp at h2, simp [h1, h2, h0] }, { refine finset.prod_congr rfl _, intros i h1, simp [h1] } end @[to_additive dfinsupp.sum_zero_index] lemma prod_zero_index [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {h : Π i, β i → γ} : (0 : Π₀ i, β i).prod h = 1 := rfl @[to_additive dfinsupp.sum_single_index] lemma prod_single_index [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {i : ι} {b : β i} {h : Π i, β i → γ} (h_zero : h i 0 = 1) : (single i b).prod h = h i b := begin by_cases h : b = 0, { simp [h, prod_zero_index, h_zero], refl }, { simp [dfinsupp.prod, support_single_ne_zero h] } end @[to_additive dfinsupp.sum_neg_index] lemma prod_neg_index [Π i, add_group (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {g : Π₀ i, β i} {h : Π i, β i → γ} (h0 : ∀i, h i 0 = 1) : (-g).prod h = g.prod (λi b, h i (- b)) := prod_map_range_index h0 @[simp] lemma sum_apply {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, add_comm_monoid (β i)] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} {i₂ : ι} : (f.sum g) i₂ = f.sum (λi₁ b, g i₁ b i₂) := (finset.sum_hom (λf : Π₀ i, β i, f i₂)).symm lemma support_sum {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} : (f.sum g).support ⊆ f.support.bind (λi, (g i (f i)).support) := have ∀i₁ : ι, f.sum (λ (i : ι₁) (b : β₁ i), (g i b) i₁) ≠ 0 → (∃ (i : ι₁), f i ≠ 0 ∧ ¬ (g i (f i)) i₁ = 0), from assume i₁ h, let ⟨i, hi, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨i, (f.mem_support_iff i).mp hi, ne⟩, by simpa [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply] using this @[simp] lemma sum_zero [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_monoid γ] {f : Π₀ i, β i} : f.sum (λi b, (0 : γ)) = 0 := finset.sum_const_zero @[simp] lemma sum_add [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_monoid γ] {f : Π₀ i, β i} {h₁ h₂ : Π i, β i → γ} : f.sum (λi b, h₁ i b + h₂ i b) = f.sum h₁ + f.sum h₂ := finset.sum_add_distrib @[simp] lemma sum_neg [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_group γ] {f : Π₀ i, β i} {h : Π i, β i → γ} : f.sum (λi b, - h i b) = - f.sum h := finset.sum_hom (@has_neg.neg γ _) @[to_additive dfinsupp.sum_add_index] lemma prod_add_index [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {f g : Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : (f + g).prod h = f.prod h * g.prod h := have f_eq : (f.support ∪ g.support).prod (λi, h i (f i)) = f.prod h, from (finset.prod_subset (finset.subset_union_left _ _) $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, have g_eq : (f.support ∪ g.support).prod (λi, h i (g i)) = g.prod h, from (finset.prod_subset (finset.subset_union_right _ _) $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, calc (f + g).support.prod (λi, h i ((f + g) i)) = (f.support ∪ g.support).prod (λi, h i ((f + g) i)) : finset.prod_subset support_add $ by simp [mem_support_iff, h_zero] {contextual := tt} ... = (f.support ∪ g.support).prod (λi, h i (f i)) * (f.support ∪ g.support).prod (λi, h i (g i)) : by simp [h_add, finset.prod_mul_distrib] ... = _ : by rw [f_eq, g_eq] lemma sum_sub_index [Π i, add_comm_group (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_group γ] {f g : Π₀ i, β i} {h : Π i, β i → γ} (h_sub : ∀i b₁ b₂, h i (b₁ - b₂) = h i b₁ - h i b₂) : (f - g).sum h = f.sum h - g.sum h := have h_zero : ∀i, h i 0 = 0, from assume i, have h i (0 - 0) = h i 0 - h i 0, from h_sub i 0 0, by simpa using this, have h_neg : ∀i b, h i (- b) = - h i b, from assume i b, have h i (0 - b) = h i 0 - h i b, from h_sub i 0 b, by simpa [h_zero] using this, have h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ + h i b₂, from assume i b₁ b₂, have h i (b₁ - (- b₂)) = h i b₁ - h i (- b₂), from h_sub i b₁ (-b₂), by simpa [h_neg] using this, by simp [@sum_add_index ι β _ γ _ _ _ f (-g) h h_zero h_add]; simp [@sum_neg_index ι β _ γ _ _ _ g h h_zero, h_neg]; simp [@sum_neg ι β _ γ _ _ _ g h] @[to_additive dfinsupp.sum_finset_sum_index] lemma prod_finset_sum_index {γ : Type w} {α : Type x} [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] [decidable_eq α] {s : finset α} {g : α → Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂): s.prod (λi, (g i).prod h) = (s.sum g).prod h := finset.induction_on s (by simp [prod_zero_index]) (by simp [prod_add_index, h_zero, h_add] {contextual := tt}) @[to_additive dfinsupp.sum_sum_index] lemma prod_sum_index {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂): (f.sum g).prod h = f.prod (λi b, (g i b).prod h) := (prod_finset_sum_index h_zero h_add).symm @[simp] lemma sum_single [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {f : Π₀ i, β i} : f.sum single = f := begin apply dfinsupp.induction f, {rw [sum_zero_index]}, intros i b f H hb ih, rw [sum_add_index, ih, sum_single_index], all_goals { intros, simp } end @[to_additive dfinsupp.sum_subtype_domain_index] lemma prod_subtype_domain_index [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {v : Π₀ i, β i} {p : ι → Prop} [decidable_pred p] {h : Π i, β i → γ} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λi b, h i.1 b) = v.prod h := finset.prod_bij (λp _, p.val) (by simp) (by simp) (assume ⟨a₀, ha₀⟩ ⟨a₁, ha₁⟩, by simp) (λ i hi, ⟨⟨i, hp i hi⟩, by simpa using hi, rfl⟩) lemma subtype_domain_sum [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {s : finset γ} {h : γ → Π₀ i, β i} {p : ι → Prop} [decidable_pred p] : (s.sum h).subtype_domain p = s.sum (λc, (h c).subtype_domain p) := eq.symm (finset.sum_hom _) lemma subtype_domain_finsupp_sum {δ : γ → Type x} [decidable_eq γ] [Π c, has_zero (δ c)] [Π c, decidable_pred (eq (0 : δ c))] [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {p : ι → Prop} [decidable_pred p] {s : Π₀ c, δ c} {h : Π c, δ c → Π₀ i, β i} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum end prod_and_sum end dfinsupp
Will you please share with me the Clerical post exam question papers of previous years of State Bank of India? Directions—(Q. 1–12) Read the following passage carefully and answer the questions given below it. Certain words have been printed in bold to help you locate them while answering some of the questions. Keshava, the washerman had a donkey. They worked together all day, and Keshava would pour out his heart to the doneky. One day, Keshava was walking home with the donkey when he felt tired. He tied the donkey to a tree and sat down to rest for a while, near a school. A window was open, and through it, a teacher could be heard scolding the students. ‘Here I am, trying to turn you donkeys into human beings, but you just won’t study !’ As soon as Keshava heard these words, his ears pricked up. A man who could actually turn donkeys into humans ! This was the answer to his prayers. Impatiently, he waited for school to be over that day. when everyone had gone home, and only the teacher remained behind to check some papers, Keshava entered the classroom. ‘How can I help you ?’ asked the teacher. Keshava scratched his head and said, ‘I heard what you said to the children. This donkey is my companion. If you made it human, we could have such good times together.’ The teacher decided to trick Keshava. He pretended to think for a while and then said, ‘Give me six months and it will cost you a thousand rupees.’ The washerman agreed and rushed home to get the money. He then left the donkey in the teacher’s care. The headman understood someone had played a trick on Keshava. ‘I am not your donkey !’ he said. ‘Go find the sage in the forest.’ Keshava found the sage sitting under a tree with his eyes closed, deep in meditation. He crept up and grabbed the sage’s beard. ‘Come back home now !’ he shouted. The startled sage somehow calmed Keshava. When he heard what had happened, he had a good laugh. Then he told the washerman kindly, ‘The teacher made a fool of you. Your donkey must be still with him. Go and take it back from him. Try to make some real friends, who will talk with you and share your troubles. A donkey will never be able to do that !’ Keshava returned home later that day with his donkey, sadder and wiser. 1. Which of the following can be said about the teacher ? 2. Why did Keshava talk to his donkey while working ? 3. How did Keshava get his donkey back ? 5. Why was Keshava keen to meet the teacher one day ? 6. Why did Keshava interrupt the discussion among the village elders ? 7. What made Keshava pull the sage’s beard ? 8. Why did the teacher ask Keshava to leave the donkey with him for six months ? (b) To reduce Keshava’s dependence on the donkey. Directions—(Q. 9–10) Choose the word which is MOST SIMILAR in MEANING to the word printed in bold as used in the passage. Directions—(Q. 11–12) Choose the word which is MOST OPPOSITE in MEANING to the word printed in bold as used in the passage. Directions—(Q. 13–17) Which of the phrases (A), (B), (C) and (D) given below each sentence should replace the phrase printed in bold in the sentence to make it grammatically correct ? If the sentence is correct as it is given and ‘No Correction is Required’, mark (E) as the answer. 13. The company has set up a foundation which helps students who do not have the necessary funds to study ahead. 14. If this land is used to cultivate crops it will be additionally source of income for the villagers. 15. Belonged to this cadre, you are eligible for facilities such as free air travel and accommodation. 16. The bank has hired a consultant who will look into any issues which arise during the merger. 17. I had severe doubts about if I successfully run a company, but my father encouraged me. Directions—(Q. 18–22) In each question below a sentence with four words printed in bold type is given. These are lettered as (A), (B), (C) and (D). One of these four words printed in bold may be either wrongly spelt or inappropriate in the context of the sentence. Find out the word which is wrongly spelt or inappropriate if any. The letter of that word is your answer. If all the words printed in bold are correctly spelt and also appropriate in the context of the sentence, mark (E) i.e. ‘All Correct’ as your answer. Directions—(Q. 23–27) Rearrange the following six sentences (a), (b), (c), (d), (e) and (f) in the proper sequence to form a meaningful paragraph; then answer the questions given below them. (f) What I saw however when I opened the bags of ‘donations’ they had sent shocked me. 23. Which of the following should be the SECOND sentence after rearrangement ? 24. Which of the following should be the THIRD sentence after rearrangement ? 25. Which of the following should be t h e FOURTH sentence after rearrangement ? 27. Which of the following should be the FIRST sentence after rearrangement ? Directions—(Q. 28–32) Read each sentence to find out whether there is any grammatical error or idiomatic error in it. The error, if any, will be in one part of the sentence. The letter of that part is the answer. If there is no error, the answer is (E). Directions—(Q. 33–40) In the following passage there are blanks, each of which has been numbered. These numbers are printed below the passage and against each, five words are suggested, one of which fits the blank appropriately. Find out the appropriate word in each case. Today, twenty-two years after the bank …(33)…, it has over a thousand branches all over the country and the staff …(34)… about twentythree lakh borrowers. We decided to operate …(35)… from conventional banks who would ask their clients to come to their office. Many people in rural areas found this …(36)…. Our bank is therefore based on the …(37)… that people should not come to the bank but that the bank should go to the people. Our loans are also …(38)… we give them for activities from candle making to tyre repair. We also keep …(39)… checks on the borrower through weekly visits. We do this to make certain that the family of the borrower is …(40)… from the loan.
### fimd8.R ### R code from Van Buuren, S. (2012). ### Flexible Imputation of Missing Data. ### CRC/Chapman & Hall, Boca Raton, FL. ### (c) 2012 Stef van Buuren, www.multiple-imputation.com ### Version 1, 22mar2012 ### Version 2, 4nov2015 tested with mice 2.23 ### Tested with Mac OS X 10.7.3, R2.14-2, mice 2.12 if (packageVersion("mice")<'2.12') stop("This code requires mice 2.12.") library("mice") library("lattice") ### Section 8.1 Correcting for selective drop-out data <- pops pred <- pops.pred if (!is.data.frame(data)) stop("The code for section 8.1 requires access to the POPS data.") ### Section 8.1.4 A degenerate solution (TIME CONSUMING (30 MINUTES)) imp1 <- mice(data, pred=pred, maxit=20, seed=51121) ### Figure 8.2 tp82 <- plot(imp1, c("a10u","a10b","adhd"),col=mdc(5),lty=1:5) print(tp82) ### Section 8.1.5 A better solution ## TIME CONSUMING (30 MINUTES) pred2 <- pred pred2[61:86,61:86] <- 0 imp2 <- mice(data, pred=pred2, maxit=20, seed=51121) ### Figure 8.3 tp83 <- bwplot(imp2, iq+e_tot+l19_sd+b19_sd+coping+seffz~.imp, layout=c(2,3)) print(tp83) ### Section 8.1.6 Results ### Full responders summary(lm(as.numeric(a10u)~1,data,na.action=na.omit)) summary(lm(as.numeric(a10b)~1,data,na.action=na.omit)) summary(lm(as.numeric(adhd)~1,data,na.action=na.omit)) ### All children summary(pool(with(imp2,lm(as.numeric(a10u)~1)))) summary(pool(with(imp2,lm(as.numeric(a10b)~1)))) summary(pool(with(imp2,lm(as.numeric(adhd)~1)))) ### Section 8.2 Correcting for nonresponse library("mice") data <- fdgs ### Section 8.2.4 Augmenting the sample nimp <- c(400, 600, 75, 300, 200, 400) regcat <- c("North","City","North","East","North","City") reg <- rep(regcat, nimp) nimp2 <- floor(rep(nimp, each=2)/2) nimp2[5:6] <- c(38,37) sex <- rep(rep(c("boy","girl"),6), nimp2) minage <- rep(c(0, 0, 10, 10, 14, 14), nimp) maxage <- rep(c(10, 10, 14, 14, 21, 21), nimp) set.seed(42444) age <- runif(length(minage), minage, maxage) id <- 600001:601975 pad <- data.frame(id, reg, age, sex, hgt=NA, wgt=NA, hgt.z=NA, wgt.z=NA) data2 <- rbind(data, pad) ### Figure 8.4 ## inspect the age by region pattern means <- aggregate(data$hgt.z, by=list(reg=data$reg, age=floor(data$age)), mean, na.rm=TRUE) tp84 <- xyplot(x~age, means, group=reg, type=c("g","l"), lty=1:5,col=mdc(4), xlim=c(-1,22), ylim=c(-0.6, 0.8), ylab="Height (SDS)", xlab="Age (years)", key=list( text=list(levels(means$reg)), lines=list(lty=1:5, col=mdc(4)), x=0.1, y=0.98, background="white", columns=3, between.columns=0), scales=list(x=list(tck=c(1,0)), y=list(tck=c(1,0)))) print(tp84) ### Section 8.2.5 Imputation model ## add interaction terms na.opt <- options(na.action=na.pass) int <- model.matrix(~I(age-10)*hgt.z+I(age-10)*wgt.z+age*reg, data=data2)[,-(1:9)] options(na.opt) data3 <- cbind(data2, int) ### define the imputation model ini <- mice(data3, maxit=0) meth <- ini$meth meth["hgt"] <- "" meth["wgt"] <- "" meth["hgt.z"] <- "norm" meth["wgt.z"] <- "norm" meth["I(age - 10):hgt.z"] <- "~I(I(age-10)*hgt.z)" meth["I(age - 10):wgt.z"] <- "~I(I(age-10)*wgt.z)" pred <- ini$pred pred[,c("hgt","wgt")] <- 0 pred["hgt.z", c("id","I(age - 10):hgt.z")] <- 0 pred["wgt.z", c("id","I(age - 10):wgt.z")] <- 0 vis <- ini$vis[c(3,5,4,6)] ### run the imputation model imp <- mice(data3, meth=meth, pred=pred, vis=vis, m=10, maxit=20, seed=28107) ### Figure 8.5 cda <- complete(imp, "long", include=TRUE) means2 <- aggregate(cda$hgt.z, by=list(reg=cda$reg, age=floor(cda$age), imp=cda$.imp), mean, na.rm=TRUE) tp85 <- xyplot(x~age|reg,means2, group=imp, subset=(reg=="North"|reg=="City"), type=c("g","l"),lwd=c(4,rep(1,imp$m)), lty=1:5,col=c(mdc(4),rep(mdc(6),imp$m)), ylab="Height (SDS)", xlab="Age (years)", ylim=c(-0.5,0.8), xlim=c(-2,23), scales=list(x=list(alternating=FALSE, tck=c(1,0)), y=list(tck=c(1,0))), strip = strip.custom(bg="grey95")) print(tp85)
/- This file contains the definition of the "explode" operation, which creates a "powerset" of literals from a list of variables. Associated theorems dealing with the contents of explode are also included. Authors: Cayden Codel, Jeremy Avigad, Marijn Heule Carnegie Mellon University -/ import cnf.literal import cnf.clause import cnf.cnf import data.nat.basic import data.nat.pow -- Represents the parametric type of the variable stored in the literal variables {V : Type*} open literal clause open list function namespace explode variables {v : V} {l : list V} {c : clause V} /-! # Explode -/ -- Produces a list of all possible polarities on a list of variables, maintaining order def explode : list V → list (clause V) | [] := [[]] | (v :: l) := (explode l).map (cons (Pos v)) ++ (explode l).map (cons (Neg v)) @[simp] theorem explode_nil : explode ([] : list V) = [[]] := rfl @[simp] theorem explode_singleton (v : V) : explode [v] = [[Pos v], [Neg v]] := rfl theorem length_explode (l : list V) : length (explode l) = 2^(length l) := begin induction l with v vs ih, { refl }, { simp only [explode, length_cons, length_append, length_map, pow_succ, two_mul, ih] } end theorem length_explode_pos (l : list V) : length (explode l) > 0 := by { rw length_explode, exact pow_pos zero_lt_two _ } theorem exists_mem_explode (l : list V) : ∃ (c : clause V), c ∈ explode l := exists_mem_of_length_pos (length_explode_pos _) theorem length_eq_of_mem_explode : c ∈ explode l → length c = length l := begin induction l with v vs ih generalizing c, { rw [explode_nil, mem_singleton], rintro rfl, refl }, { simp only [explode, mem_append, mem_map], rintros (⟨c, hc, rfl⟩ | ⟨c, hc, rfl⟩); { simp [ih hc, length_cons] } } end theorem cons_mem_explode_cons_of_mem_explode (lit : literal V) : c ∈ explode l → (lit :: c) ∈ explode (lit.var :: l) := assume hc, by { cases lit; simp [explode, literal.var, hc] } variable [decidable_eq V] theorem mem_of_mem_explode_of_mem_vars : c ∈ explode l → v ∈ c.vars → v ∈ l := begin induction l with v vs ih generalizing c, { rw [explode_nil, mem_singleton], rintros rfl hv, rw clause.vars_nil at hv, exact absurd hv (finset.not_mem_empty _) }, { simp only [explode, mem_append, mem_map], rintros (⟨a, ha, rfl⟩ | ⟨a, ha, rfl⟩); { rw [clause.vars, finset.mem_union, mem_cons_iff], rintros (hv | hv), { rw [var, finset.mem_singleton] at hv, exact or.inl hv }, { exact or.inr (ih ha hv) } } } end theorem mem_vars_of_mem_explode_of_mem : c ∈ explode l → v ∈ l → v ∈ c.vars := begin induction l with v vs ih generalizing c, { intros _ hv, exact absurd hv (not_mem_nil v) } , { simp only [explode, mem_append, mem_map], rintros (⟨a, ha, rfl⟩ | ⟨a, ha, rfl⟩) hv; { unfold clause.vars var, rcases eq_or_mem_of_mem_cons hv with rfl | hv, { exact finset.mem_union.mpr (or.inl (mem_singleton_self _)) }, { exact finset.mem_union.mpr (or.inr (ih ha hv)) } } } end theorem not_mem_vars_of_mem_explode_of_not_mem : c ∈ explode l → v ∉ l → v ∉ c.vars := λ h hv, mt (mem_of_mem_explode_of_mem_vars h) hv theorem not_mem_of_mem_explode_of_not_mem_vars : c ∈ explode l → v ∉ c.vars → v ∉ l := λ h hv, mt (mem_vars_of_mem_explode_of_mem h) hv theorem pos_or_neg_of_mem_explode_of_mem : c ∈ explode l → v ∈ l → Pos v ∈ c ∨ Neg v ∈ c := λ h hv, mem_vars_iff_pos_or_neg_mem_clause.mp (mem_vars_of_mem_explode_of_mem h hv) theorem pos_and_neg_not_mem_of_mem_explode_of_not_mem : c ∈ explode l → v ∉ l → Pos v ∉ c ∧ Neg v ∉ c := begin intro h, contrapose, rw not_and_distrib, simp only [not_not], intro hv, exact mem_of_mem_explode_of_mem_vars h (mem_vars_iff_pos_or_neg_mem_clause.mpr hv) end -- If the variables in a clause match the input to explode, then it's in explode theorem map_var_eq_iff_mem_explode : c.map var = l ↔ c ∈ explode l := begin induction l with v vs ih generalizing c, { simp only [map_eq_nil, explode_nil, mem_singleton] }, { split, { intro h, rcases exists_cons_of_map_cons h with ⟨l, ls, rfl, hl, hls⟩, cases l; simp only [explode, mem_append, mem_map], { rw var at hl, subst hl, left, use [ls, ih.mp hls] }, { rw var at hl, subst hl, right, use [ls, ih.mp hls] } }, { simp only [explode, mem_map, mem_append], rintros (⟨a, ha, rfl⟩ | ⟨a, ha, rfl⟩); { simp only [ih.mpr ha, var, map, eq_self_iff_true, and_self] } } } end /-! # nodup properties of explode -/ theorem explode_nodup (l : list V) : nodup (explode l) := begin induction l with v vs ih, { rw explode_nil, exact nodup_singleton nil }, { simp only [explode, nodup_cons, nodup_append, (nodup_map_iff (cons_injective)).mpr ih, true_and], intros x hxp hxn, rcases mem_map.mp hxp with ⟨c, _, rfl⟩, rcases mem_map.mp hxn with ⟨d, _, h⟩, have := head_eq_of_cons_eq h, contradiction } end theorem nodup_of_nodup_of_mem (h : nodup l) : c ∈ explode l → nodup c := begin induction l with n ns ih generalizing c, { rw [explode_nil, mem_singleton], rintro rfl, exact nodup_nil }, { simp only [explode, mem_append, mem_map], rintro (⟨a, ha, rfl⟩ | ⟨a, ha, rfl⟩); rw nodup_cons; have := pos_and_neg_not_mem_of_mem_explode_of_not_mem ha ((nodup_cons.mp h).1), { exact ⟨this.1, ih (nodup_cons.mp h).2 ha⟩ }, { exact ⟨this.2, ih (nodup_cons.mp h).2 ha⟩ } } end theorem xor_pos_neg_mem_clause_of_nodup_of_mem_explode_of_mem (h : nodup l) : c ∈ explode l → v ∈ l → xor (Pos v ∈ c) (Neg v ∈ c) := begin induction l with v vs ih generalizing c, { intros _ h, exact absurd h (not_mem_nil _) }, { simp only [explode, mem_append, mem_map], rintros (⟨a, ha, rfl⟩ | ⟨a, ha, rfl⟩) hc; { rcases eq_or_mem_of_mem_cons hc with (rfl | hv), { simp [pos_and_neg_not_mem_of_mem_explode_of_not_mem ha (nodup_cons.mp h).1] }, { rcases ih (nodup_cons.mp h).2 ha hv with ⟨hp, hn⟩ | ⟨hp, hn⟩; { simp [hp, hn, ne_of_mem_of_not_mem hv (nodup_cons.mp h).1] } } } } end end explode
# Homework 5 ## Due Date: Tuesday, October 3rd at 11:59 PM # Problem 1 We discussed documentation and testing in lecture and also briefly touched on code coverage. You must write tests for your code for your final project (and in life). There is a nice way to automate the testing process called continuous integration (CI). This problem will walk you through the basics of CI and show you how to get up and running with some CI software. ### Continuous Integration The idea behind continuous integration is to automate away the testing of your code. We will be using it for our projects. The basic workflow goes something like this: 1. You work on your part of the code in your own branch or fork 2. On every commit you make and push to GitHub, your code is automatically tested on a fresh machine on Travis CI. This ensures that there are no specific dependencies on the structure of your machine that your code needs to run and also ensures that your changes are sane 3. Now you submit a pull request to `master` in the main repo (the one you're hoping to contribute to). The repo manager creates a branch off `master`. 4. This branch is also set to run tests on Travis. If all tests pass, then the pull request is accepted and your code becomes part of master. We use GitHub to integrate our roots library with Travis CI and Coveralls. Note that this is not the only workflow people use. Google git..github..workflow and feel free to choose another one for your group. ### Part 1: Create a repo Create a public GitHub repo called `cs207test` and clone it to your local machine. **Note:** No need to do this in Jupyter. ### Part 2: Create a roots library Use the example from lecture 7 to create a file called `roots.py`, which contains the `quad_roots` and `linear_roots` functions (along with their documentation). Also create a file called `test_roots.py`, which contains the tests from lecture. All of these files should be in your newly created `cs207test` repo. **Don't push yet!!!** ### Part 3: Create an account on Travis CI and Start Building #### Part A: Create an account on Travis CI and set your `cs207test` repo up for continuous integration once this repo can be seen on Travis. #### Part B: Create an instruction to Travis to make sure that 1. python is installed 2. its python 3.5 3. pytest is installed The file should be called `.travis.yml` and should have the contents: ```yml language: python python: - "3.5" before_install: - pip install pytest pytest-cov script: - pytest ``` You should also create a configuration file called `setup.cfg`: ```cfg [tool:pytest] addopts = --doctest-modules --cov-report term-missing --cov roots ``` #### Part C: Push the new changes to your `cs207test` repo. At this point you should be able to see your build on Travis and if and how your tests pass. ### Part 4: Coveralls Integration In class, we also discussed code coverage. Just like Travis CI runs tests automatically for you, Coveralls automatically checks your code coverage. One minor drawback of Coveralls is that it can only work with public GitHub accounts. However, this isn't too big of a problem since your projects will be public. #### Part A: Create an account on [`Coveralls`](https://coveralls.zendesk.com/hc/en-us), connect your GitHub, and turn Coveralls integration on. #### Part B: Update your the `.travis.yml` file as follows: ```yml language: python python: - "3.5" before_install: - pip install pytest pytest-cov - pip install coveralls script: - py.test after_success: - coveralls ``` Be sure to push the latest changes to your new repo. ### Part 5: Update README.md in repo You can have your GitHub repo reflect the build status on Travis CI and the code coverage status from Coveralls. To do this, you should modify the `README.md` file in your repo to include some badges. Put the following at the top of your `README.md` file: ``` [](https://travis-ci.org/dsondak/cs207testing.svg?branch=master) [](https://coveralls.io/github/dsondak/cs207testing?branch=master) ``` Of course, you need to make sure that the links are to your repo and not mine. You can find embed code on the Coveralls and Travis CI sites. --- # Problem 2 Write a Python module for reaction rate coefficients. Your module should include functions for constant reaction rate coefficients, Arrhenius reaction rate coefficients, and modified Arrhenius reaction rate coefficients. Here are their mathematical forms: \begin{align} &k_{\textrm{const}} = k \tag{constant} \\ &k_{\textrm{arr}} = A \exp\left(-\frac{E}{RT}\right) \tag{Arrhenius} \\ &k_{\textrm{mod arr}} = A T^{b} \exp\left(-\frac{E}{RT}\right) \tag{Modified Arrhenius} \end{align} Test your functions with the following paramters: $A = 10^7$, $b=0.5$, $E=10^3$. Use $T=10^2$. A few additional comments / suggestions: * The Arrhenius prefactor $A$ is strictly positive * The modified Arrhenius parameter $b$ must be real * $R = 8.314$ is the ideal gas constant. It should never be changed (except to convert units) * The temperature $T$ must be positive (assuming a Kelvin scale) * You may assume that units are consistent * Document each function! * You might want to check for overflows and underflows **Recall:** A Python module is a `.py` file which is not part of the main execution script. The module contains several functions which may be related to each other (like in this problem). Your module will be importable via the execution script. For example, suppose you have called your module `reaction_coeffs.py` and your execution script `kinetics.py`. Inside of `kinetics.py` you will write something like: ```python import reaction_coeffs # Some code to do some things # : # : # : # Time to use a reaction rate coefficient: reaction_coeffs.const() # Need appropriate arguments, etc # Continue on... # : # : # : ``` Be sure to include your module in the same directory as your execution script. ```python %%file reaction_coeffs.py import numpy as np R=8.314 def const(k): return k def arr(A, E, T): #Check that A,T,E are numbers if ((type(A) != int and type(A) != float) or (type(T) != int and type(T) != float) or (type(E) != int and type(E) != float)): raise TypeError("All arguments must be numbers!") elif (T<0 or A<0): # A & T must be positive raise ValueError("Temperature and Arrhenius prefactor must be positive!") else: #Calculate karr karr = A*(np.exp(-E/(R*T))) return karr def mod_arr(A,E,b,T): #Check that A,T,E are numbers if ((type(A) != int and type(A) != float) or (type(b) != int and type(b) != float) or (type(E) != int and type(E) != float) or (type(T) != int and type(T) != float)): raise TypeError("All arguments must be numbers!") elif (T<0 or A<0): # A & T must be positive raise ValueError("Temperature and Arrhenius prefactor must be positive!") else: #Calculate karr karr = A*(T**b)*(np.exp(-E/(R*T))) return karr ``` Overwriting reaction_coeffs.py ```python %%file kinetics.py import reaction_coeffs # Time to use a reaction rate coefficient: reaction_coeffs.const(107) reaction_coeffs.arr(107,103,102) reaction_coeffs.mod_arr(107,103,0.5,102) ``` Overwriting kinetics.py ```python %%file kinetics_tests.py import reaction_coeffs #Test k_const def test_const(): assert reaction_coeffs.const(107) == 107 #Test k_arr def test_arr(): assert reaction_coeffs.arr(107,103,102) == 94.762198593430469 def test_arr_values1(): try: reaction_coeffs.arr(-1,103,102) except ValueError as err: assert(type(err) == ValueError) def test_arr_values2(): try: reaction_coeffs.arr(107,103,-2) except ValueError as err: assert(type(err) == ValueError) def test_arr_types1(): try: reaction_coeffs.arr('107',103,102) except TypeError as err: assert(type(err) == TypeError) def test_arr_types2(): try: reaction_coeffs.arr(107,'103',102) except TypeError as err: assert(type(err) == TypeError) def test_arr_types3(): try: reaction_coeffs.arr(107,103,[102]) except TypeError as err: assert(type(err) == TypeError) #Test mod_arr def test_mod_arr(): assert reaction_coeffs.mod_arr(107,103,0.5,102) == 957.05129266439894 def test_mod_arr_values1(): try: reaction_coeffs.mod_arr(-1,103,0.5,102) except ValueError as err: assert(type(err) == ValueError) def test_mod_arr_values2(): try: reaction_coeffs.mod_arr(107,103,0.5,-2) except ValueError as err: assert(type(err) == ValueError) def test_mod_arr_types1(): try: reaction_coeffs.mod_arr('107',103,0.5,102) except TypeError as err: assert(type(err) == TypeError) def test_mod_arr_types2(): try: reaction_coeffs.mod_arr(107,'103',0.5,102) except TypeError as err: assert(type(err) == TypeError) def test_mod_arr_types3(): try: reaction_coeffs.mod_arr(107,103,[0.5],102) except TypeError as err: assert(type(err) == TypeError) def test_mod_arr_types4(): try: reaction_coeffs.mod_arr(107,103,0.5,False) except TypeError as err: assert(type(err) == TypeError) test_const() test_mod_arr() test_arr() test_arr_values1() test_arr_values2() test_arr_types1() test_arr_types2() test_arr_types3() test_mod_arr_values1() test_mod_arr_values2() test_mod_arr_types1() test_mod_arr_types2() test_mod_arr_types3() test_mod_arr_types4() ``` Overwriting kinetics_tests.py --- # Problem 3 Write a function that returns the **progress rate** for a reaction of the following form: \begin{align} \nu_{A} A + \nu_{B} B \longrightarrow \nu_{C} C. \end{align} Order your concentration vector so that \begin{align} \mathbf{x} = \begin{bmatrix} \left[A\right] \\ \left[B\right] \\ \left[C\right] \end{bmatrix} \end{align} Test your function with \begin{align} \nu_{i}^{\prime} = \begin{bmatrix} 2.0 \\ 1.0 \\ 0.0 \end{bmatrix} \qquad \mathbf{x} = \begin{bmatrix} 1.0 \\ 2.0 \\ 3.0 \end{bmatrix} \qquad k = 10. \end{align} You must document your function and write some tests in addition to the one suggested. You choose the additional tests, but you must have at least one doctest in addition to a suite of unit tests. ```python def progress_rate(v1,x,k): """Returns the progress rate of a reaction of the form: v1A + v2B -> v3C. INPUTS ======= v1: list, stoichiometric coefficient of reactants in a reaction(s) x: float, Concentration of A, B, C k: float, reaction rate coefficient RETURNS ======== progress rate: a list of the progress rate of each reaction EXAMPLES ========= >>> progress_rate([2.0,1.0,0.0],[1.0,2.0,3.0],10) [20.0] """ #Check that x and v1 are lists if (type(v1) != list or type(x) != list): raise TypeError("v' & x must be passed in as a list") #Check that x,and k are numbers/list of numbers if (any(type(i) != int and type(i) != float for i in x)): raise TypeError("All elements in x must be numbers!") elif (type(k) != int and type(k) != float and type(k) != list): raise TypeError("k must be a numbers!") else: progress_rates = [] #check for multiple reactions if(type(v1[0]) == list): for v in v1: for reactant in v: if(type(reactant) != int and type(reactant) != float): raise TypeError("All elements in v1 must be numbers!") #Calculate the progress rate of each reaction reactions = len(v1[0]) for j in range(reactions): if (type(k)== list): progress_rate = k[j] else: progress_rate = k for i in range(len(v1)): progress_rate = progress_rate*(x[i]**v1[i][j]) progress_rates.append(progress_rate) else: #Check types of V1 if (any(type(i) != int and type(i) != float for i in v1)): raise TypeError("All elements in v1 must be numbers!") #Calculate the progress rate of each reaction progress_rate = k for i in range(len(v1)): progress_rate = progress_rate*(x[i]**v1[i]) progress_rates.append(progress_rate) return progress_rates ``` ```python progress_rate([2.0,1.0,0.0],[1.0,2.0,3.0],10) ``` [20.0] --- # Problem 4 Write a function that returns the **progress rate** for a system of reactions of the following form: \begin{align} \nu_{11}^{\prime} A + \nu_{21}^{\prime} B \longrightarrow \nu_{31}^{\prime\prime} C \\ \nu_{12}^{\prime} A + \nu_{32}^{\prime} C \longrightarrow \nu_{22}^{\prime\prime} B + \nu_{32}^{\prime\prime} C \end{align} Note that $\nu_{ij}^{\prime}$ represents the stoichiometric coefficient of reactant $i$ in reaction $j$ and $\nu_{ij}^{\prime\prime}$ represents the stoichiometric coefficient of product $i$ in reaction $j$. Therefore, in this convention, I have ordered my vector of concentrations as \begin{align} \mathbf{x} = \begin{bmatrix} \left[A\right] \\ \left[B\right] \\ \left[C\right] \end{bmatrix}. \end{align} Test your function with \begin{align} \nu_{ij}^{\prime} = \begin{bmatrix} 1.0 & 2.0 \\ 2.0 & 0.0 \\ 0.0 & 2.0 \end{bmatrix} \qquad \nu_{ij}^{\prime\prime} = \begin{bmatrix} 0.0 & 0.0 \\ 0.0 & 1.0 \\ 2.0 & 1.0 \end{bmatrix} \qquad \mathbf{x} = \begin{bmatrix} 1.0 \\ 2.0 \\ 1.0 \end{bmatrix} \qquad k_{j} = 10, \quad j=1,2. \end{align} You must document your function and write some tests in addition to the one suggested. You choose the additional tests, but you must have at least one doctest in addition to a suite of unit tests. ```python progress_rate([[1.0,2.0],[2.0,0.0],[0.0,2.0]],[1.0,2.0,1.0],10) ``` [40.0, 10.0] --- # Problem 5 Write a function that returns the **reaction rate** of a system of irreversible reactions of the form: \begin{align} \nu_{11}^{\prime} A + \nu_{21}^{\prime} B &\longrightarrow \nu_{31}^{\prime\prime} C \\ \nu_{32}^{\prime} C &\longrightarrow \nu_{12}^{\prime\prime} A + \nu_{22}^{\prime\prime} B \end{align} Once again $\nu_{ij}^{\prime}$ represents the stoichiometric coefficient of reactant $i$ in reaction $j$ and $\nu_{ij}^{\prime\prime}$ represents the stoichiometric coefficient of product $i$ in reaction $j$. In this convention, I have ordered my vector of concentrations as \begin{align} \mathbf{x} = \begin{bmatrix} \left[A\right] \\ \left[B\right] \\ \left[C\right] \end{bmatrix} \end{align} Test your function with \begin{align} \nu_{ij}^{\prime} = \begin{bmatrix} 1.0 & 0.0 \\ 2.0 & 0.0 \\ 0.0 & 2.0 \end{bmatrix} \qquad \nu_{ij}^{\prime\prime} = \begin{bmatrix} 0.0 & 1.0 \\ 0.0 & 2.0 \\ 1.0 & 0.0 \end{bmatrix} \qquad \mathbf{x} = \begin{bmatrix} 1.0 \\ 2.0 \\ 1.0 \end{bmatrix} \qquad k_{j} = 10, \quad j = 1,2. \end{align} You must document your function and write some tests in addition to the one suggested. You choose the additional tests, but you must have at least one doctest in addition to a suite of unit tests. ```python def reaction_rate(v1,v2,x,k): """Returns the reaction rate of a reaction of the form: v1A + v2B -> v3C. INPUTS ======= v1: 2D list, stoichiometric coefficient of reactants in a reaction(s) v2: 2D list, optional, default value is 2 stoichiometric coefficient of products in a reaction(s) x: float, Concentration of A, B, C k: float, reaction rate coefficient RETURNS ======== reaction rate: a list of the reaction rate of each reactant EXAMPLES ========= >>> reaction_rate([[1.0,0.0],[2.0,0.0],[0.0,2.0]],[[0.0,1.0],[0.0,2.0],[1.0,0.0]],[1.0,2.0,1.0],10) [-30.0, -60.0, 20.0] """ w = progress_rate(v1,x,k) #Check that x,v2 and v1 are lists if (type(v2) != list or type(x) != list or type(v1)!= list): raise TypeError("v' & x must be passed in as a list") if (any(type(i) != int and type(i) != float for i in x)): raise TypeError("All arguments must be numbers!") elif (type(k) != int and type(k) != float and type(k) !=list): raise TypeError("All arguments must be numbers!") else: reaction_rates = [] for i in (range(len(v2))): reaction_rate = 0 for j in (range(len(v2[0]))): reaction_rate = reaction_rate + (v2[i][j]-v1[i][j])*w[j] reaction_rates.append(reaction_rate) return reaction_rates ``` ```python reaction_rate([[1.0,0.0],[2.0,0.0],[0.0,2.0]],[[0.0,1.0],[0.0,2.0],[1.0,0.0]],[1.0,2.0,1.0],10) ``` [-30.0, -60.0, 20.0] --- # Problem 6 Put parts 3, 4, and 5 in a module called `chemkin`. Next, pretend you're a client who needs to compute the reaction rates at three different temperatures ($T = \left\{750, 1500, 2500\right\}$) of the following system of irreversible reactions: \begin{align} 2H_{2} + O_{2} \longrightarrow 2OH + H_{2} \\ OH + HO_{2} \longrightarrow H_{2}O + O_{2} \\ H_{2}O + O_{2} \longrightarrow HO_{2} + OH \end{align} The client also happens to know that reaction 1 is a modified Arrhenius reaction with $A_{1} = 10^{8}$, $b_{1} = 0.5$, $E_{1} = 5\times 10^{4}$, reaction 2 has a constant reaction rate parameter $k = 10^{4}$, and reaction 3 is an Arrhenius reaction with $A_{3} = 10^{7}$ and $E_{3} = 10^{4}$. You should write a script that imports your `chemkin` module and returns the reaction rates of the species at each temperature of interest given the following species concentrations: \begin{align} \mathbf{x} = \begin{bmatrix} H_{2} \\ O_{2} \\ OH \\ HO_{2} \\ H_{2}O \end{bmatrix} = \begin{bmatrix} 2.0 \\ 1.0 \\ 0.5 \\ 1.0 \\ 1.0 \end{bmatrix} \end{align} You may assume that these are elementary reactions. ```python %%file chemkin.py def progress_rate(v1,x,k): """Returns the progress rate of a reaction of the form: v1A + v2B -> v3C. INPUTS ======= v1: list, stoichiometric coefficient of reactants in a reaction(s) x: float, Concentration of A, B, C k: float, reaction rate coefficient RETURNS ======== progress rate: a list of the progress rate of each reaction EXAMPLES ========= >>> progress_rate([2.0,1.0,0.0],[1.0,2.0,3.0],10) [20.0] """ #Check that x and v1 are lists if (type(v1) != list or type(x) != list): raise TypeError("v' & x must be passed in as a list") #Check that x,and k are numbers/list of numbers if (any(type(i) != int and type(i) != float for i in x)): raise TypeError("All elements in x must be numbers!") elif (type(k) != int and type(k) != float and type(k) != list): raise TypeError("k must be a numbers or list!") else: progress_rates = [] #check for multiple reactions if(type(v1[0]) == list): for v in v1: for reactant in v: if(type(reactant) != int and type(reactant) != float): raise TypeError("All elements in v1 must be numbers!") #Calculate the progress rate of each reaction reactions = len(v1[0]) for j in range(reactions): if (type(k) == list): progress_rate = k[j] else: progress_rate = k for i in range(len(v1)): progress_rate = progress_rate*(x[i]**v1[i][j]) progress_rates.append(progress_rate) else: #Check types of V1 if (any(type(i) != int and type(i) != float for i in v1)): raise TypeError("All elements in v1 must be numbers!") #Calculate the progress rate of each reaction progress_rate = k for i in range(len(v1)): progress_rate = progress_rate*(x[i]**v1[i]) progress_rates.append(progress_rate) return progress_rates def reaction_rate(v1,v2,x,k): """Returns the reaction rate of a reaction of the form: v1A + v2B -> v3C. INPUTS ======= v1: 2D list, stoichiometric coefficient of reactants in a reaction(s) v2: 2D list, optional, default value is 2 stoichiometric coefficient of products in a reaction(s) x: float, Concentration of A, B, C k: float, reaction rate coefficient RETURNS ======== reaction rate: a list of the reaction rate of each reactant EXAMPLES ========= >>> reaction_rate([[1.0,0.0],[2.0,0.0],[0.0,2.0]],[[0.0,1.0],[0.0,2.0],[1.0,0.0]],[1.0,2.0,1.0],10) [-30.0, -60.0, 20.0] """ w = progress_rate(v1,x,k) #Check that x,v2 and v1 are lists if (type(v2) != list or type(x) != list or type(v1)!= list): raise TypeError("v' & x must be passed in as a list") if (any(type(i) != int and type(i) != float for i in x)): raise TypeError("All arguments must be numbers!") elif (type(k) != int and type(k) != float and type(k) !=list): raise TypeError("All arguments must be numbers!") else: reaction_rates = [] for i in (range(len(v2))): reaction_rate = 0 for j in (range(len(v2[0]))): reaction_rate = reaction_rate + (v2[i][j]-v1[i][j])*w[j] reaction_rates.append(reaction_rate) return reaction_rates ``` Writing chemkin.py ```python import chemkin import reaction_coeffs v1 = [[2.0,0.0,0.0],[1.0,0.0,1.0],[0.0,1.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]] v2 = [[1.0,0.0,0.0],[0.0,1.0,0.0],[2.0,0.0,1.0],[0.0,0.0,1.0],[0.0,1.0,0.0]] x = [2.0,1.0,0.5,1.0,1.0] k1T1 = reaction_coeffs.mod_arr((10**7),(5*(10**4)),0.5,750) k2T1 = reaction_coeffs.const(10**4) k3T1 = reaction_coeffs.arr((10**8),(10**4),750) k1 = [k1T1,k2T1,k3T1] k2T2 = reaction_coeffs.const(10**4) k3T2 = reaction_coeffs.arr((10**7),(10**4),1500) k1T2 = reaction_coeffs.mod_arr((10**8),(5*(10**4)),0.5,1500) k2 = [k1T2,k2T2,k3T2] k2T3 = reaction_coeffs.const(10**4) k3T3 = reaction_coeffs.arr((10**7),(10**4),2500) k1T3 = reaction_coeffs.mod_arr((10**8),(5*(10**4)),0.5,2500) k3 = [k1T3,k2T3,k3T3] print([chemkin.reaction_rate(v1,v2,x,k1),chemkin.reaction_rate(v1,v2,x,k2), chemkin.reaction_rate(v1,v2,x,k3)]) ``` [[-360707.78728040616, -20470380.895447683, 20831088.682728089, 20109673.108167276, -20109673.108167276], [-281117620.76487017, -285597559.23804539, 566715180.0029155, 4479938.4731752202, -4479938.4731752202], [-1804261425.9632478, -1810437356.938905, 3614698782.902153, 6175930.9756572321, -6175930.9756572321]] ```python %%file test.py import chemkin def test_progress_rate(): assert chemkin.progress_rate([3.0,1.0,1.0],[1.0,2.0,3.0],10) == [60.0] test_progress_rate() def test_reaction_rate(): assert chemkin.reaction_rate([[3.0,1.0,1.0]],[[1.0,2.0,1.0]],[1.0,2.0,3.0],10) == [-10.0] test_reaction_rate() ``` Overwriting test.py ```python !pytest --doctest-modules --cov-report term-missing --cov ``` ============================= test session starts ============================== platform darwin -- Python 3.6.1, pytest-3.2.1, py-1.4.33, pluggy-0.4.0 rootdir: /Users/riddhishah/Documents/cs207/cs207_riddhi_shah/homeworks/HW5, inifile: plugins: cov-2.3.1 collected 0 items  ---------- coverage: platform darwin, python 3.6.1-final-0 ----------- Name Stmts Miss Cover Missing -------------------------------------------------- chemkin.py 43 9 79% 5, 8, 10, 18, 23, 32, 44, 46, 48 kinetics.py 4 0 100% kinetics_tests.py 76 0 100% reaction_coeffs.py 18 0 100% test.py 7 0 100% -------------------------------------------------- TOTAL 148 9 94% ========================= no tests ran in 2.02 seconds ========================= --- # Problem 7 Get together with your project team, form a GitHub organization (with a descriptive team name), and give the teaching staff access. You can have has many repositories as you like within your organization. However, we will grade the repository called **`cs207-FinalProject`**. Within the `cs207-FinalProject` repo, you must set up Travis CI and Coveralls. Make sure your `README.md` file includes badges indicating how many tests are passing and the coverage of your code. ```python '''Done by Hongxiang in our group!''' ``` 'Done by Hongxiang in our group!'
Events, activities and private hires in the Village Hall and Sports Pavilion are shown in the Bookings Diary below. If you are interested in hiring any of the rooms in the Village Hall or the Sports Pavilion it is worth checking availability, even if your preferred date and time appears to clash with one of these events. Please note that some of the events listed below may be private events or restricted to members of particular clubs/groups and may not necessarily be open to the public. Contact details for clubs can be found on the drop down menu on ‘Our Charity’ page and selecting Groups/Clubs or clicking on the diary entry. Cost £7 per session or £35 for 6 weeks. Adults £7.50 Under 14s £3 Bring your own snacks – Full Bar available at the event.
function ellipse_t = fit_ellipse( x,y,axis_handle ) % % fit_ellipse - finds the best fit to an ellipse for the given set of points. % % Format: ellipse_t = fit_ellipse( x,y,axis_handle ) % % Input: x,y - a set of points in 2 column vectors. AT LEAST 5 points are needed ! % axis_handle - optional. a handle to an axis, at which the estimated ellipse % will be drawn along with it's axes % % Output: ellipse_t - structure that defines the best fit to an ellipse % a - sub axis (radius) of the X axis of the non-tilt ellipse % b - sub axis (radius) of the Y axis of the non-tilt ellipse % phi - orientation in radians of the ellipse (tilt) % X0 - center at the X axis of the non-tilt ellipse % Y0 - center at the Y axis of the non-tilt ellipse % X0_in - center at the X axis of the tilted ellipse % Y0_in - center at the Y axis of the tilted ellipse % long_axis - size of the long axis of the ellipse % short_axis - size of the short axis of the ellipse % status - status of detection of an ellipse % % Note: if an ellipse was not detected (but a parabola or hyperbola), then % an empty structure is returned % ===================================================================================== % Ellipse Fit using Least Squares criterion % ===================================================================================== % We will try to fit the best ellipse to the given measurements. the mathematical % representation of use will be the CONIC Equation of the Ellipse which is: % % Ellipse = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f = 0 % % The fit-estimation method of use is the Least Squares method (without any weights) % The estimator is extracted from the following equations: % % g(x,y;A) := a*x^2 + b*x*y + c*y^2 + d*x + e*y = f % % where: % A - is the vector of parameters to be estimated (a,b,c,d,e) % x,y - is a single measurement % % We will define the cost function to be: % % Cost(A) := (g_c(x_c,y_c;A)-f_c)'*(g_c(x_c,y_c;A)-f_c) % = (X*A+f_c)'*(X*A+f_c) % = A'*X'*X*A + 2*f_c'*X*A + N*f^2 % % where: % g_c(x_c,y_c;A) - vector function of ALL the measurements % each element of g_c() is g(x,y;A) % X - a matrix of the form: [x_c.^2, x_c.*y_c, y_c.^2, x_c, y_c ] % f_c - is actually defined as ones(length(f),1)*f % % Derivation of the Cost function with respect to the vector of parameters "A" yields: % % A'*X'*X = -f_c'*X = -f*ones(1,length(f_c))*X = -f*sum(X) % % Which yields the estimator: % % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % | A_least_squares = -f*sum(X)/(X'*X) ->(normalize by -f) = sum(X)/(X'*X) | % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % % (We will normalize the variables by (-f) since "f" is unknown and can be accounted for later on) % % NOW, all that is left to do is to extract the parameters from the Conic Equation. % We will deal the vector A into the variables: (A,B,C,D,E) and assume F = -1; % % Recall the conic representation of an ellipse: % % A*x^2 + B*x*y + C*y^2 + D*x + E*y + F = 0 % % We will check if the ellipse has a tilt (=orientation). The orientation is present % if the coefficient of the term "x*y" is not zero. If so, we first need to remove the % tilt of the ellipse. % % If the parameter "B" is not equal to zero, then we have an orientation (tilt) to the ellipse. % we will remove the tilt of the ellipse so as to remain with a conic representation of an % ellipse without a tilt, for which the math is more simple: % % Non tilt conic rep.: A`*x^2 + C`*y^2 + D`*x + E`*y + F` = 0 % % We will remove the orientation using the following substitution: % % Replace x with cx+sy and y with -sx+cy such that the conic representation is: % % A(cx+sy)^2 + B(cx+sy)(-sx+cy) + C(-sx+cy)^2 + D(cx+sy) + E(-sx+cy) + F = 0 % % where: c = cos(phi) , s = sin(phi) % % and simplify... % % x^2(A*c^2 - Bcs + Cs^2) + xy(2A*cs +(c^2-s^2)B -2Ccs) + ... % y^2(As^2 + Bcs + Cc^2) + x(Dc-Es) + y(Ds+Ec) + F = 0 % % The orientation is easily found by the condition of (B_new=0) which results in: % % 2A*cs +(c^2-s^2)B -2Ccs = 0 ==> phi = 1/2 * atan( b/(c-a) ) % % Now the constants c=cos(phi) and s=sin(phi) can be found, and from them % all the other constants A`,C`,D`,E` can be found. % % A` = A*c^2 - B*c*s + C*s^2 D` = D*c-E*s % B` = 2*A*c*s +(c^2-s^2)*B -2*C*c*s = 0 E` = D*s+E*c % C` = A*s^2 + B*c*s + C*c^2 % % Next, we want the representation of the non-tilted ellipse to be as: % % Ellipse = ( (X-X0)/a )^2 + ( (Y-Y0)/b )^2 = 1 % % where: (X0,Y0) is the center of the ellipse % a,b are the ellipse "radiuses" (or sub-axis) % % Using a square completion method we will define: % % F`` = -F` + (D`^2)/(4*A`) + (E`^2)/(4*C`) % % Such that: a`*(X-X0)^2 = A`(X^2 + X*D`/A` + (D`/(2*A`))^2 ) % c`*(Y-Y0)^2 = C`(Y^2 + Y*E`/C` + (E`/(2*C`))^2 ) % % which yields the transformations: % % X0 = -D`/(2*A`) % Y0 = -E`/(2*C`) % a = sqrt( abs( F``/A` ) ) % b = sqrt( abs( F``/C` ) ) % % And finally we can define the remaining parameters: % % long_axis = 2 * max( a,b ) % short_axis = 2 * min( a,b ) % Orientation = phi % % % initialize orientation_tolerance = 1e-3; % empty warning stack warning( '' ); % prepare vectors, must be column vectors x = x(:); y = y(:); % remove bias of the ellipse - to make matrix inversion more accurate. (will be added later on). mean_x = mean(x); mean_y = mean(y); x = x-mean_x; y = y-mean_y; % the estimation for the conic equation of the ellipse X = [x.^2, x.*y, y.^2, x, y ]; a = sum(X)/(X'*X); % check for warnings if ~isempty( lastwarn ) disp( 'stopped because of a warning regarding matrix inversion' ); ellipse_t = []; return end % extract parameters from the conic equation [a,b,c,d,e] = deal( a(1),a(2),a(3),a(4),a(5) ); % remove the orientation from the ellipse if ( min(abs(b/a),abs(b/c)) > orientation_tolerance ) orientation_rad = 1/2 * atan( b/(c-a) ); cos_phi = cos( orientation_rad ); sin_phi = sin( orientation_rad ); [a,b,c,d,e] = deal(... a*cos_phi^2 - b*cos_phi*sin_phi + c*sin_phi^2,... 0,... a*sin_phi^2 + b*cos_phi*sin_phi + c*cos_phi^2,... d*cos_phi - e*sin_phi,... d*sin_phi + e*cos_phi ); [mean_x,mean_y] = deal( ... cos_phi*mean_x - sin_phi*mean_y,... sin_phi*mean_x + cos_phi*mean_y ); else orientation_rad = 0; cos_phi = cos( orientation_rad ); sin_phi = sin( orientation_rad ); end % check if conic equation represents an ellipse test = a*c; switch (1) case (test>0), status = ''; case (test==0), status = 'Parabola found'; warning( 'fit_ellipse: Did not locate an ellipse' ); case (test<0), status = 'Hyperbola found'; warning( 'fit_ellipse: Did not locate an ellipse' ); end % if we found an ellipse return it's data if (test>0) % make sure coefficients are positive as required if (a<0), [a,c,d,e] = deal( -a,-c,-d,-e ); end % final ellipse parameters X0 = mean_x - d/2/a; Y0 = mean_y - e/2/c; F = 1 + (d^2)/(4*a) + (e^2)/(4*c); [a,b] = deal( sqrt( F/a ),sqrt( F/c ) ); long_axis = 2*max(a,b); short_axis = 2*min(a,b); % rotate the axes backwards to find the center point of the original TILTED ellipse R = [ cos_phi sin_phi; -sin_phi cos_phi ]; P_in = R * [X0;Y0]; X0_in = P_in(1); Y0_in = P_in(2); % pack ellipse into a structure ellipse_t = struct( ... 'a',a,... 'b',b,... 'phi',orientation_rad,... 'X0',X0,... 'Y0',Y0,... 'X0_in',X0_in,... 'Y0_in',Y0_in,... 'long_axis',long_axis,... 'short_axis',short_axis,... 'status','' ); else % report an empty structure ellipse_t = struct( ... 'a',[],... 'b',[],... 'phi',[],... 'X0',[],... 'Y0',[],... 'X0_in',[],... 'Y0_in',[],... 'long_axis',[],... 'short_axis',[],... 'status',status ); end % check if we need to plot an ellipse with it's axes. if (nargin>2) & ~isempty( axis_handle ) & (test>0) % rotation matrix to rotate the axes with respect to an angle phi R = [ cos_phi sin_phi; -sin_phi cos_phi ]; % the axes ver_line = [ [X0 X0]; Y0+b*[-1 1] ]; horz_line = [ X0+a*[-1 1]; [Y0 Y0] ]; new_ver_line = R*ver_line; new_horz_line = R*horz_line; % the ellipse theta_r = linspace(0,2*pi); ellipse_x_r = X0 + a*cos( theta_r ); ellipse_y_r = Y0 + b*sin( theta_r ); rotated_ellipse = R * [ellipse_x_r;ellipse_y_r]; % draw hold_state = get( axis_handle,'NextPlot' ); set( axis_handle,'NextPlot','add' ); plot( new_ver_line(1,:),new_ver_line(2,:),'r' ); plot( new_horz_line(1,:),new_horz_line(2,:),'r' ); plot( rotated_ellipse(1,:),rotated_ellipse(2,:),'r' ); set( axis_handle,'NextPlot',hold_state ); end
""" Copyright (c) Facebook, Inc. and its affiliates. """ import numpy as np import pickle from droidlet.lowlevel.minecraft.iglu_util import IGLU_BLOCK_MAP from droidlet.lowlevel.minecraft.shape_util import ( SHAPE_NAMES, SHAPE_FNS, SHAPE_OPTION_FUNCTION_MAP, ) SL = 17 GROUND_DEPTH = 5 H = 13 HOLE_NAMES = ["RECTANGULOID", "ELLIPSOID", "SPHERE"] # FIXME! better control of distribution and put this in a different file # also no control of cuberite coloring def random_mob_color(mobname): if mobname == "rabbit": return np.random.choice(["brown", "white", "black", "mottled", "gray"]) if mobname == "pig": return np.random.choice(["brown", "white", "black", "mottled", "pink"]) if mobname == "chicken": return np.random.choice(["white", "yellow", "brown"]) if mobname == "sheep": return np.random.choice(["brown", "white", "black", "mottled", "gray"]) if mobname == "cow": return np.random.choice(["brown", "white", "black", "mottled", "gray"]) return "white" def parse_and_execute_mob_config(args): """ mob_config can be a dict of the form {"mobs": [{"mobtype": MOBTYPE, "pose": (x, y, z, pitch, yaw), "color": COLOR}, ...]} or {"mob_generator": CALLABLE} or {"num_mobs": INT, "mob_probs":{MOBNAME:FLOAT_LOGIT, ..., MOBNAME:FLOAT_LOGIT}} if "mob_probs" is not specified, it is uniform over ["rabbit", "cow", "pig", "chicken", "sheep"] or string of the form num_mobs:x;mobname:float;mobname:float;... the floats are the probability of sampling that mob returns a list of [{"mobtype": MOBTYPE, "pose": (x, y, z, pitch, yaw), "color": COLOR}, ...] """ mob_config = args.mob_config if type(mob_config) is str: c = {} o = mob_config.split(";") if len(o) > 0: try: assert o[0].startswith("num_mobs") num_mobs = int(o[0].split(":")[1]) c["num_mobs"] = num_mobs c["mob_probs"] = {} for p in o[1:]: name, prob = p.split(":") c["mob_probs"][name] = float(prob) except: c = {} else: c = mob_config assert type(c) is dict if not c: return [] elif c.get("mobs"): return c["mobs"] elif c.get("mob_generator"): return c["mob_generator"](args) elif c.get("num_mobs"): num_mobs = c.get("num_mobs") if not c["mob_probs"]: md = [("rabbit", "cow", "pig", "chicken", "sheep"), (1.0, 1.0, 1.0, 1.0, 1.0)] else: md = list(zip(*c["mob_probs"].items())) probs = np.array(md[1]) assert probs.min() >= 0.0 probs = probs / probs.sum() mobnames = np.random.choice(md[0], size=num_mobs, p=probs).tolist() mobs = [] for m in mobnames: # mob pose set in collect_scene for now if not specified mobs.append({"mobtype": m, "pose": None, "color": random_mob_color(m)}) return mobs else: raise Exception("malformed mob opts {}".format(c)) def bid(nowhite=True): if nowhite: return (35, np.random.randint(15) + 1) else: return (35, np.random.randint(16)) def red(): return (35, 14) def white(): return (35, 0) def make_pose(args, loc=None, pitchyaw=None, height_map=None): """ make a random pose for player or mob. if loc or pitchyaw is specified, use those if height_map is specified, finds a point close to the loc 1 block higher than the height_map, but less than ENTITY_HEIGHT from args.H TODO option to input object locations and pick pitchyaw to look at one """ ENTITY_HEIGHT = 2 if loc is None: x, y, z = np.random.randint((args.SL, args.H, args.SL)) else: x, y, z = loc if pitchyaw is None: pitch = np.random.uniform(-90, 90) yaw = np.random.uniform(-180, 180) else: pitch, yaw = pitchyaw # put the entity above the current height map. this will break if # there is a big flat slab covering the entire space high, FIXME if height_map is not None: okh = np.array(np.nonzero(height_map < args.H - ENTITY_HEIGHT)) if okh.shape[1] == 0: raise Exception( "no space for entities, height map goes up to args.H-ENTITY_HEIGHT everywhere" ) d = np.linalg.norm((okh - np.array((x, z)).reshape(2, 1)), 2, 0) minidx = np.argmin(d) x = int(okh[0, minidx]) z = int(okh[1, minidx]) y = int(height_map[x, z] + 1) return x, y, z, pitch, yaw def build_base_world(sl, h, g, fence=False): W = {} for i in range(sl): for j in range(g): for k in range(sl): if (i == 0 or i == sl - 1 or k == 0 or k == sl - 1) and j == g - 1 and fence: idm = red() else: idm = white() W[(i, j, k)] = idm return W def shift_list(blocks_list, s): for i in range(len(blocks_list)): b = blocks_list[i] if len(b) == 2: l, idm = b blocks_list[i] = ((l[0] + s[0], l[1] + s[1], l[2] + s[2]), idm) else: assert len(b) == 3 blocks_list[i] = (b[0] + s[0], b[1] + s[1], b[2] + s[2]) return blocks_list def shift_dict(block_dict, s): out = {} for l, idm in block_dict.items(): out[(l[0] + s[0], l[1] + s[1], l[2] + s[2])] = idm return out def in_box_builder(mx, my, mz, Mx, My, Mz): def f(l): lb = l[0] >= mx and l[1] >= my and l[2] >= mz ub = l[0] < Mx and l[1] < My and l[2] < Mz return lb and ub return f def record_shape(S, in_box, offsets, blocks, inst_seg, occupied_by_shapes): for l, idm in S: ln = np.add(l, offsets) if in_box(ln): ln = tuple(ln.tolist()) if not occupied_by_shapes.get(ln): blocks[ln] = idm inst_seg.append(ln) occupied_by_shapes[ln] = True def collect_scene(blocks, inst_segs, args, mobs=[]): J = {} J["inst_seg_tags"] = inst_segs mapped_blocks = [ (int(l[0]), int(l[1]), int(l[2]), int(IGLU_BLOCK_MAP[idm])) for l, idm in blocks.items() ] J["blocks"] = mapped_blocks # FIXME not shifting positions of agents and mobs properly for cuberite # FIXME not using the mob positions in cuberite... height_map = np.zeros((args.SL, args.SL)) for l, idm in blocks.items(): if l[1] > height_map[l[0], l[2]] and idm[0] > 0: height_map[l[0], l[2]] = l[1] J["mobs"] = [] for mob in mobs: if mob.get("pose"): x, y, z, p, yaw = mob["pose"] loc = (x, y, z) pitchyaw = (p, yaw) else: loc = None pitchyaw = None mob["pose"] = make_pose(args, loc=loc, pitchyaw=pitchyaw, height_map=height_map) J["mobs"].append(mob) # FIXME not using the avatar and agent position in cuberite... x, y, z, p, yaw = make_pose(args, height_map=height_map) J["avatarInfo"] = {"pos": (x, y, z), "look": (p, yaw)} x, y, z, p, yaw = make_pose(args, height_map=height_map) J["agentInfo"] = {"pos": (x, y, z), "look": (p, yaw)} o = (0, args.cuberite_y_offset, 0) blocks = shift_dict(blocks, o) J["schematic_for_cuberite"] = [ {"x": int(l[0]), "y": int(l[1]), "z": int(l[2]), "id": int(idm[0]), "meta": int(idm[1])} for l, idm in blocks.items() ] J["offset"] = (args.cuberite_x_offset, args.cuberite_y_offset, args.cuberite_z_offset) return J def build_shape_scene(args): """ Build a scene using basic shapes, outputs a json dict with fields "avatarInfo" = {"pos": (x,y,z), "look": (yaw, pitch)} "agentInfo" = {"pos": (x,y,z), "look": (yaw, pitch)} "blocks" = [(x,y,z,bid) ... (x,y,z,bid)] "schematic_for_cuberite" = [{"x": x, "y":y, "z":z, "id":blockid, "meta": meta} ...] where bid is the output of the BLOCK_MAP applied to a minecraft blockid, meta pair. """ fence = getattr(args, "fence", False) blocks = build_base_world(args.SL, args.H, args.GROUND_DEPTH, fence=fence) if args.iglu_scenes: import pickle with open(args.iglu_scenes, "rb") as f: assets = pickle.load(f) sid = np.random.choice(list(assets.keys())) scene = assets[sid] scene = scene.transpose(1, 0, 2) for i in range(11): for j in range(9): for k in range(11): h = j + args.GROUND_DEPTH if h < args.H: # TODO? fix colors # TODO: assuming this world bigger in xz than iglu c = scene[i, j, k] % 16 if c > 0: blocks[(i + 1, h, k + 1)] = (35, c) num_shapes = np.random.randint(0, args.MAX_NUM_SHAPES + 1) occupied_by_shapes = {} inst_segs = [] for t in range(num_shapes): shape = np.random.choice(SHAPE_NAMES) opts = SHAPE_OPTION_FUNCTION_MAP[shape]() opts["bid"] = bid() S = SHAPE_FNS[shape](**opts) m = np.round(np.mean([l for l, idm in S], axis=0)).astype("int32") offsets = np.random.randint((args.SL, args.H, args.SL)) - m inst_seg = [] in_box = in_box_builder(0, 0, 0, args.SL, args.H, args.SL) record_shape(S, in_box, offsets, blocks, inst_seg, occupied_by_shapes) inst_segs.append({"tags": [shape], "locs": inst_seg}) if args.MAX_NUM_GROUND_HOLES == 0: num_holes = 0 else: num_holes = np.random.randint(0, args.MAX_NUM_GROUND_HOLES) # TODO merge contiguous holes ML = args.SL mL = 0 if args.fence: ML -= 1 mL = 1 for t in range(num_holes): shape = np.random.choice(HOLE_NAMES) opts = SHAPE_OPTION_FUNCTION_MAP[shape]() S = SHAPE_FNS[shape](**opts) S = [(l, (0, 0)) for l, idm in S] m = np.round(np.mean([l for l, idm in S], axis=0)).astype("int32") miny = min([l[1] for l, idm in S]) maxy = max([l[1] for l, idm in S]) offsets = np.random.randint((args.SL, args.H, args.SL)) offsets[0] -= m[0] offsets[2] -= m[2] # offset miny to GROUND_DEPTH - radius of shape offsets[1] = args.GROUND_DEPTH - maxy // 2 - 1 inst_seg = [] in_box = in_box_builder(mL, 0, mL, ML, args.GROUND_DEPTH, ML) record_shape(S, in_box, offsets, blocks, inst_seg, occupied_by_shapes) inst_segs.append({"tags": ["hole"], "locs": inst_seg}) mobs = parse_and_execute_mob_config(args) J = {} # not shifting y for gridworld o = (args.cuberite_x_offset, 0, args.cuberite_z_offset) blocks = shift_dict(blocks, o) for i in inst_segs: i["locs"] = shift_list(i["locs"], o) return collect_scene(blocks, inst_segs, args, mobs=mobs) def build_extra_simple_shape_scene(args): """ Build a scene with a sphere and a cube, non-overlapping. outputs a json dict with fields "avatarInfo" = {"pos": (x,y,z), "look": (yaw, pitch)} "agentInfo" = {"pos": (x,y,z), "look": (yaw, pitch)} "blocks" = [(x,y,z,bid) ... (x,y,z,bid)] "schematic_for_cuberite" = [{"x": x, "y":y, "z":z, "id":blockid, "meta": meta} ...] where bid is the output of the BLOCK_MAP applied to a minecraft blockid, meta pair. """ CUBE_SIZE = 3 SPHERE_RADIUS = 2 fence = getattr(args, "fence", False) blocks = build_base_world(args.SL, args.H, args.GROUND_DEPTH, fence=fence) inst_segs = [] shape_opts = {"SPHERE": {"radius": SPHERE_RADIUS}, "CUBE": {"size": CUBE_SIZE}} shapes = np.random.permutation(["SPHERE", "CUBE"]) occupied_by_shapes = {} old_offset = [-100, -100, -100] for shape in shapes: opts = shape_opts[shape] opts["bid"] = bid() S = SHAPE_FNS[shape](**opts) m = np.round(np.mean([l for l, idm in S], axis=0)).astype("int32") offsets = np.random.randint( (0, args.GROUND_DEPTH, 0), (args.SL - CUBE_SIZE, args.H - CUBE_SIZE, args.SL - CUBE_SIZE), ) count = 0 while ( abs(old_offset[0] - offsets[0]) + abs(old_offset[2] - offsets[2]) < CUBE_SIZE + SPHERE_RADIUS ): offsets = np.random.randint( (0, args.GROUND_DEPTH, 0), (args.SL - CUBE_SIZE, args.H - CUBE_SIZE, args.SL - CUBE_SIZE), ) count += 1 assert count < 100, "Is world too small? can't place shapes" old_offset = offsets inst_seg = [] in_box = in_box_builder(0, 0, 0, args.SL, args.H, args.SL) record_shape(S, in_box, offsets, blocks, inst_seg, occupied_by_shapes) inst_segs.append({"tags": [shape], "locs": inst_seg}) # not shifting y for gridworld o = (args.cuberite_x_offset, 0, args.cuberite_z_offset) blocks = [(l, idm) for l, idm in blocks.items()] blocks = shift(blocks, o) for i in inst_segs: i["locs"] = shift(i["locs"], o) return collect_scene(blocks, inst_segs, args) if __name__ == "__main__": import argparse import json parser = argparse.ArgumentParser() parser.add_argument("--SL", type=int, default=SL) parser.add_argument("--H", type=int, default=H) parser.add_argument("--mob_config", type=str, default="") parser.add_argument("--GROUND_DEPTH", type=int, default=GROUND_DEPTH) parser.add_argument("--MAX_NUM_SHAPES", type=int, default=3) parser.add_argument("--NUM_SCENES", type=int, default=3) parser.add_argument("--MAX_NUM_GROUND_HOLES", type=int, default=0) parser.add_argument("--fence", action="store_true", default=False) parser.add_argument("--cuberite_x_offset", type=int, default=-SL // 2) parser.add_argument("--cuberite_y_offset", type=int, default=63 - GROUND_DEPTH) parser.add_argument("--cuberite_z_offset", type=int, default=-SL // 2) parser.add_argument("--save_data_path", default="") parser.add_argument("--iglu_scenes", default="") parser.add_argument("--extra_simple", action="store_true", default=False) args = parser.parse_args() scenes = [] for i in range(args.NUM_SCENES): if args.extra_simple: scenes.append(build_extra_simple_shape_scene(args)) else: scenes.append(build_shape_scene(args)) if args.save_data_path: with open(args.save_data_path, "w") as f: json.dump(scenes, f)
import numpy as np import scipy.interpolate from mcalf.profiles.gaussian import single_gaussian __all__ = ['reinterpolate_spectrum', 'normalise_spectrum', 'generate_sigma'] def reinterpolate_spectrum(spectrum, original_wavelengths, constant_wavelengths): """Reinterpolate the spectrum. Reinterpolates the spectrum such that intensities at `original_wavelengths` are transformed into intensities at `constant_wavelengths`. Uses :class:`scipy.interpolate.InterpolatedUnivariateSpline` to interpolate. Parameters ---------- spectrum : numpy.ndarray, ndim=1 Spectrum to reinterpolate. original_wavelengths : numpy.ndarray, ndim=1, length=length of `spectrum` Wavelengths of `spectrum`. constant_wavelengths : numpy.ndarray, ndim=1 Wavelengths to cast `spectrum` into. Returns ------- spectrum : numpy.ndarray, length=length of `constant_wavelengths` Reinterpolated spectrum. """ s = scipy.interpolate.InterpolatedUnivariateSpline(original_wavelengths, spectrum) # Fit spline return s(constant_wavelengths) # Evaluate spline at new wavelengths def normalise_spectrum(spectrum, original_wavelengths=None, constant_wavelengths=None, prefilter_response=None, model=None): """Normalise an individual spectrum to have intensities in range [0, 1]. .. warning:: Not recommended for normalising many spectra in a loop. Parameters ---------- spectrum : numpy.ndarray, ndim=1 Spectrum to reinterpolate and normalise. original_wavelengths : numpy.ndarray, ndim=1, length=length of `spectrum`, optional Wavelengths of `spectrum`. constant_wavelengths : numpy.ndarray, ndim=1, optional Wavelengths to cast `spectrum` into. prefilter_response : numpy.ndarray, ndim=1, length=length of `constant_wavelengths`, optional Prefilter response to divide spectrum by. model : child class of mcalf.models.ModelBase, optional Model to extract the above parameters from. Returns ------- spectrum : numpy.ndarray, ndim-1, length=length of `constant_wavelengths` The normalised spectrum. """ from mcalf.models import ModelBase if issubclass(model.__class__, ModelBase): if original_wavelengths is None: original_wavelengths = model.original_wavelengths if constant_wavelengths is None: constant_wavelengths = model.constant_wavelengths if prefilter_response is None: prefilter_response = model.prefilter_response if original_wavelengths is not None or constant_wavelengths is not None: if original_wavelengths is None or constant_wavelengths is None: raise ValueError("original_wavelengths and constant_wavelengths must be provided") spectrum = reinterpolate_spectrum(spectrum, original_wavelengths, constant_wavelengths) if prefilter_response is not None: spectrum /= prefilter_response spectrum -= min(spectrum) spectrum /= max(spectrum) return spectrum def generate_sigma(sigma_type, wavelengths, line_core, a=-0.95, c=0.04, d=1, centre_rad=7, a_peak=0.4): """Generate the default sigma profiles. Parameters ---------- sigma_type : int Type of profile to generate. Should be either `1` or `2`. wavelengths : array_like Wavelengths to use for sigma profile. line_core : float Line core to use as centre of Gaussian sigma profile. a : float, optional, default=-0.95 Amplitude of Gaussian sigma profile. c : float, optional, default=0.04 Sigma of Gaussian sigma profile. d : float, optional, default=1 Background of Gaussian sigma profile. centre_rad : int, optional, default=7 Width of central flattened region. a_peak : float, optional, default=0.4 Amplitude of central 7 pixel section, if `sigma_type` is 2. Returns ------- sigma : numpy.ndarray, length=n_wavelengths The generated sigma profile. """ sigma = single_gaussian(wavelengths, a, line_core, c, d) # Define initial sigma profile centre_i = np.argmin(sigma) # Get central index of sigma sigma[:centre_i - centre_rad] = sigma[centre_rad:centre_i] # Shift left half left sigma[centre_i + centre_rad:] = sigma[centre_i:-centre_rad] # Shift right half right sigma[centre_i - centre_rad:centre_i + centre_rad] = sigma[centre_i] # Connect the two halves with a line if sigma_type == 2: sigma[centre_i - 3:centre_i + 3 + 1] = a_peak # Lessen importance of peak detail return sigma
theory UteProof imports UteDefs "../Majorities" "../Reduction" begin context ute_parameters begin subsection {* Preliminary Lemmas *} text {* Processes can make a vote only at first round of each phase. *} lemma vote_step: assumes nxt: "nextState Ute_M r p (rho r p) \<mu> (rho (Suc r) p)" and "vote (rho (Suc r) p) \<noteq> None" shows "step r = 0" proof (rule ccontr) assume "step r \<noteq> 0" with assms have "vote (rho (Suc r) p) = None" by (auto simp:Ute_SHOMachine_def nextState_def Ute_nextState_def next1_def) with assms show False by auto qed text {* Processes can make a new decision only at second round of each phase. *} lemma decide_step: assumes run: "SHORun Ute_M rho HOs SHOs" and d1: "decide (rho r p) \<noteq> Some v" and d2: "decide (rho (Suc r) p) = Some v" shows "step r \<noteq> 0" proof assume sr:"step r = 0" from run obtain \<mu> where "Ute_nextState r p (rho r p) \<mu> (rho (Suc r) p)" unfolding Ute_SHOMachine_def nextState_def SHORun_eq SHOnextConfig_eq by force with sr have "next0 r p (rho r p) \<mu> (rho (Suc r) p)" unfolding Ute_nextState_def by auto hence "decide (rho r p) = decide (rho (Suc r) p)" by (auto simp:next0_def) with d1 d2 show False by auto qed lemma unique_majority_E: assumes majv: "card {qq::Proc. F qq = Some m} > E" and majw: "card {qq::Proc. F qq = Some m'} > E" shows "m = m'" proof - from majv majw majE have "card {qq::Proc. F qq = Some m} > N div 2" and "card {qq::Proc. F qq = Some m'} > N div 2" by auto then obtain qq where "qq \<in> {qq::Proc. F qq = Some m}" and "qq \<in> {qq::Proc. F qq = Some m'}" by (rule majoritiesE') thus ?thesis by auto qed lemma unique_majority_E_\<alpha>: assumes majv: "card {qq::Proc. F qq = m} > E - \<alpha>" and majw: "card {qq::Proc. F qq = m'} > E - \<alpha>" shows "m = m'" proof - from majE alpha_lt_N majv majw have "card {qq::Proc. F qq = m} > N div 2" and "card {qq::Proc. F qq = m'} > N div 2" by auto then obtain qq where "qq \<in> {qq::Proc. F qq = m}" and "qq \<in> {qq::Proc. F qq = m'}" by (rule majoritiesE') thus ?thesis by auto qed lemma unique_majority_T: assumes majv: "card {qq::Proc. F qq = Some m} > T" and majw: "card {qq::Proc. F qq = Some m'} > T" shows "m = m'" proof - from majT majv majw have "card {qq::Proc. F qq = Some m} > N div 2" and "card {qq::Proc. F qq = Some m'} > N div 2" by auto then obtain qq where "qq \<in> {qq::Proc. F qq = Some m}" and "qq \<in> {qq::Proc. F qq = Some m'}" by (rule majoritiesE') thus ?thesis by auto qed text {* No two processes may vote for different values in the same round. *} lemma common_vote: assumes usafe: "SHOcommPerRd Ute_M HO SHO" and nxtp: "nextState Ute_M r p (rho r p) \<mu>p (rho (Suc r) p)" and mup: "\<mu>p \<in> SHOmsgVectors Ute_M r p (rho r) (HO p) (SHO p)" and nxtq: "nextState Ute_M r q (rho r q) \<mu>q (rho (Suc r) q)" and muq: "\<mu>q \<in> SHOmsgVectors Ute_M r q (rho r) (HO q) (SHO q)" and vp: "vote (rho (Suc r) p) = Some vp" and vq: "vote (rho (Suc r) q) = Some vq" shows "vp = vq" using assms proof - have gtn: "card {qq. sendMsg Ute_M r qq p (rho r qq) = Val vp} + card {qq. sendMsg Ute_M r qq q (rho r qq) = Val vq} > N" proof - have "card {qq. sendMsg Ute_M r qq p (rho r qq) = Val vp} > T - \<alpha> \<and> card {qq. sendMsg Ute_M r qq q (rho r qq) = Val vq} > T - \<alpha>" (is "card ?vsentp > _ \<and> card ?vsentq > _") proof - from nxtp vp have stp:"step r = 0" by (auto simp: vote_step) from mup have "{qq. \<mu>p qq = Some (Val vp)} - (HO p - SHO p) \<subseteq> {qq. sendMsg Ute_M r qq p (rho r qq) = Val vp}" (is "?vrcvdp - ?ahop \<subseteq> ?vsentp") by (auto simp: SHOmsgVectors_def) hence "card (?vrcvdp - ?ahop) \<le> card ?vsentp" and "card (?vrcvdp - ?ahop) \<ge> card ?vrcvdp - card ?ahop" by (auto simp: card_mono diff_card_le_card_Diff) hence "card ?vsentp \<ge> card ?vrcvdp - card ?ahop" by auto moreover from nxtp stp have "next0 r p (rho r p) \<mu>p (rho (Suc r) p)" by (auto simp: Ute_SHOMachine_def nextState_def Ute_nextState_def) with vp have "card ?vrcvdp > T" unfolding next0_def by auto moreover from muq have "{qq. \<mu>q qq = Some (Val vq)} - (HO q - SHO q) \<subseteq> {qq. sendMsg Ute_M r qq q (rho r qq) = Val vq}" (is "?vrcvdq - ?ahoq \<subseteq> ?vsentq") by (auto simp: SHOmsgVectors_def) hence "card (?vrcvdq - ?ahoq) \<le> card ?vsentq" and "card (?vrcvdq - ?ahoq) \<ge> card ?vrcvdq - card ?ahoq" by (auto simp: card_mono diff_card_le_card_Diff) hence "card ?vsentq \<ge> card ?vrcvdq - card ?ahoq" by auto moreover from nxtq stp have "next0 r q (rho r q) \<mu>q (rho (Suc r) q)" by (auto simp: Ute_SHOMachine_def nextState_def Ute_nextState_def) with vq have "card {qq. \<mu>q qq = Some (Val vq)} > T" by (unfold next0_def, auto) moreover from usafe have "card ?ahop \<le> \<alpha>" and "card ?ahoq \<le> \<alpha>" by (auto simp: Ute_SHOMachine_def Ute_commPerRd_def) ultimately show ?thesis using alpha_lt_T by auto qed thus ?thesis using majT by auto qed show ?thesis proof (rule ccontr) assume vpq:"vp \<noteq> vq" have "\<forall>qq. sendMsg Ute_M r qq p (rho r qq) = sendMsg Ute_M r qq q (rho r qq)" by (auto simp: Ute_SHOMachine_def Ute_sendMsg_def step_def send0_def send1_def) with vpq have "{qq. sendMsg Ute_M r qq p (rho r qq) = Val vp} \<inter> {qq. sendMsg Ute_M r qq q (rho r qq) = Val vq} = {}" by auto with gtn have "card ({qq. sendMsg Ute_M r qq p (rho r qq) = Val vp} \<union> {qq. sendMsg Ute_M r qq q (rho r qq) = Val vq}) > N" by (auto simp: card_Un_Int) moreover have "card ({qq. sendMsg Ute_M r qq p (rho r qq) = Val vp} \<union> {qq. sendMsg Ute_M r qq q (rho r qq) = Val vq}) \<le> N" by (auto simp: card_mono) ultimately show "False" by auto qed qed text {* No decision may be taken by a process unless it received enough messages holding the same value. *} (* The proof mainly relies on lemma @{text decide_step} and the @{text Ute_commPerRound} predicate. *) lemma decide_with_threshold_E: assumes run: "SHORun Ute_M rho HOs SHOs" and usafe: "SHOcommPerRd Ute_M (HOs r) (SHOs r)" and d1: "decide (rho r p) \<noteq> Some v" and d2: "decide (rho (Suc r) p) = Some v" shows "card {q. sendMsg Ute_M r q p (rho r q) = Vote (Some v)} > E - \<alpha>" proof - from run obtain \<mu>p where nxt:"nextState Ute_M r p (rho r p) \<mu>p (rho (Suc r) p)" and "\<forall>qq. qq \<in> HOs r p \<longleftrightarrow> \<mu>p qq \<noteq> None" and "\<forall>qq. qq \<in> SHOs r p \<inter> HOs r p \<longrightarrow> \<mu>p qq = Some (sendMsg Ute_M r qq p (rho r qq))" unfolding Ute_SHOMachine_def SHORun_eq SHOnextConfig_eq SHOmsgVectors_def by blast hence "{qq. \<mu>p qq = Some (Vote (Some v))} - (HOs r p - SHOs r p) \<subseteq> {qq. sendMsg Ute_M r qq p (rho r qq) = Vote (Some v)}" (is "?vrcvdp - ?ahop \<subseteq> ?vsentp") by auto hence "card (?vrcvdp - ?ahop) \<le> card ?vsentp" and "card (?vrcvdp - ?ahop) \<ge> card ?vrcvdp - card ?ahop" by (auto simp: card_mono diff_card_le_card_Diff) hence "card ?vsentp \<ge> card ?vrcvdp - card ?ahop" by auto moreover from usafe have "card (HOs r p - SHOs r p) \<le> \<alpha>" by (auto simp: Ute_SHOMachine_def Ute_commPerRd_def) moreover from run d1 d2 have "step r \<noteq> 0" by (rule decide_step) with nxt have "next1 r p (rho r p) \<mu>p (rho (Suc r) p)" by (auto simp: Ute_SHOMachine_def nextState_def Ute_nextState_def) with run d1 d2 have "card {qq. \<mu>p qq = Some (Vote (Some v))} > E" unfolding next1_def by auto ultimately show ?thesis using alpha_lt_E by auto qed subsection {* Proof of Agreement and Validity *} text {* If more than @{text "E - \<alpha>"} messages holding @{text v} are sent to some process @{text p} at round @{text r}, then every process @{text pp} correctly receives more than @{text "\<alpha>"} such messages. *} (* The proof mainly relies on the @{text Ute_commPerRound} predicate. *) lemma common_x_argument_1: assumes usafe:"SHOcommPerRd Ute_M (HOs (Suc r)) (SHOs (Suc r))" and threshold: "card {q. sendMsg Ute_M (Suc r) q p (rho (Suc r) q) = Vote (Some v)} > E - \<alpha>" (is "card (?msgs p v) > _") shows "card (?msgs pp v \<inter> (SHOs (Suc r) pp \<inter> HOs (Suc r) pp)) > \<alpha>" proof - have "card (?msgs pp v) + card (SHOs (Suc r) pp \<inter> HOs (Suc r) pp) > N + \<alpha>" proof - have "\<forall>q. sendMsg Ute_M (Suc r) q p (rho (Suc r) q) = sendMsg Ute_M (Suc r) q pp (rho (Suc r) q)" by (auto simp: Ute_SHOMachine_def Ute_sendMsg_def step_def send0_def send1_def) moreover from usafe have "card (SHOs (Suc r) pp \<inter> HOs (Suc r) pp) > N + 2*\<alpha> - E - 1" by (auto simp: Ute_SHOMachine_def step_def Ute_commPerRd_def) ultimately show ?thesis using threshold by auto qed moreover have "card (?msgs pp v) + card (SHOs (Suc r) pp \<inter> HOs (Suc r) pp) = card (?msgs pp v \<union> (SHOs (Suc r) pp \<inter> HOs (Suc r) pp)) + card (?msgs pp v \<inter> (SHOs (Suc r) pp \<inter> HOs (Suc r) pp))" by (auto intro: card_Un_Int) moreover have "card (?msgs pp v \<union> (SHOs (Suc r) pp \<inter> HOs (Suc r) pp)) \<le> N" by (auto simp: card_mono) ultimately show ?thesis by auto qed text {* If more than @{text "E - \<alpha>"} messages holding @{text v} are sent to @{text p} at some round @{text r}, then any process @{text pp} will set its @{text x} to value @{text v} in @{text r}. *} (* The proof relies on previous lemmas @{text common_x_argument_1} and @{text common_vote} and the @{text Ute_commPerRound} predicate. *) lemma common_x_argument_2: assumes run: "SHORun Ute_M rho HOs SHOs" and usafe: "\<forall>r. SHOcommPerRd Ute_M (HOs r) (SHOs r)" and nxtpp: "nextState Ute_M (Suc r) pp (rho (Suc r) pp) \<mu>pp (rho (Suc (Suc r)) pp)" and mupp: "\<mu>pp \<in> SHOmsgVectors Ute_M (Suc r) pp (rho (Suc r)) (HOs (Suc r) pp) (SHOs (Suc r) pp)" and threshold: "card {q. sendMsg Ute_M (Suc r) q p (rho (Suc r) q) = Vote (Some v)} > E - \<alpha>" (is "card (?sent p v) > _") shows "x (rho (Suc (Suc r)) pp) = v" proof - have stp:"step (Suc r) \<noteq> 0" proof assume sr: "step (Suc r) = 0" hence "\<forall>q. sendMsg Ute_M (Suc r) q p (rho (Suc r) q) = Val (x (rho (Suc r) q))" by (auto simp: Ute_SHOMachine_def Ute_sendMsg_def send0_def) moreover from threshold obtain qq where "sendMsg Ute_M (Suc r) qq p (rho (Suc r) qq) = Vote (Some v)" by force ultimately show False by simp qed have va: "card {qq. \<mu>pp qq = Some (Vote (Some v))} > \<alpha>" (is "card (?msgs v) > \<alpha>") proof - from mupp have "SHOs (Suc r) pp \<inter> HOs (Suc r) pp \<subseteq> {qq. \<mu>pp qq = Some (sendMsg Ute_M (Suc r) qq pp (rho (Suc r) qq))}" unfolding SHOmsgVectors_def by auto moreover hence "(?msgs v) \<supseteq> (?sent pp v) \<inter> (SHOs (Suc r) pp \<inter> HOs (Suc r) pp)" by auto hence "card (?msgs v) \<ge> card ((?sent pp v) \<inter> (SHOs (Suc r) pp \<inter> HOs (Suc r) pp))" by (auto intro: card_mono) moreover from usafe threshold have alph:"card ((?sent pp v) \<inter> (SHOs (Suc r) pp \<inter> HOs (Suc r) pp)) > \<alpha>" by (blast dest: common_x_argument_1) ultimately show ?thesis by auto qed moreover from nxtpp stp have "next1 (Suc r) pp (rho (Suc r) pp) \<mu>pp (rho (Suc (Suc r)) pp)" by (auto simp: Ute_SHOMachine_def nextState_def Ute_nextState_def) ultimately obtain w where wa:"card (?msgs w) > \<alpha>" and xw:"x (rho (Suc (Suc r)) pp) = w" unfolding next1_def by auto have "v = w" proof - note usafe moreover obtain qv where "qv \<in> SHOs (Suc r) pp" and "\<mu>pp qv = Some (Vote (Some v))" proof - have "\<not> (?msgs v \<subseteq> HOs (Suc r) pp - SHOs (Suc r) pp)" proof assume "?msgs v \<subseteq> HOs (Suc r) pp - SHOs (Suc r) pp" hence "card (?msgs v) \<le> card ((HOs (Suc r) pp) - (SHOs (Suc r) pp))" by (auto simp: card_mono) moreover from usafe have "card (HOs (Suc r) pp - SHOs (Suc r) pp) \<le> \<alpha>" by (auto simp: Ute_SHOMachine_def Ute_commPerRd_def) moreover note va ultimately show False by auto qed then obtain qv where "qv \<notin> HOs (Suc r) pp - SHOs (Suc r) pp" and qsv:"\<mu>pp qv = Some (Vote (Some v))" by auto with mupp have "qv \<in> SHOs (Suc r) pp" unfolding SHOmsgVectors_def by auto with qsv that show ?thesis by auto qed with stp mupp have "vote (rho (Suc r) qv) = Some v" by (auto simp: Ute_SHOMachine_def SHOmsgVectors_def Ute_sendMsg_def send1_def) moreover obtain qw where "qw \<in> SHOs (Suc r) pp" and "\<mu>pp qw = Some (Vote (Some w))" proof - have "\<not> (?msgs w \<subseteq> HOs (Suc r) pp - SHOs (Suc r) pp)" proof assume "?msgs w \<subseteq> HOs (Suc r) pp - SHOs (Suc r) pp" hence "card (?msgs w) \<le> card ((HOs (Suc r) pp) - (SHOs (Suc r) pp))" by (auto simp: card_mono) moreover from usafe have "card (HOs (Suc r) pp - SHOs (Suc r) pp) \<le> \<alpha>" by (auto simp: Ute_SHOMachine_def Ute_commPerRd_def) moreover note wa ultimately show False by auto qed then obtain qw where "qw \<notin> HOs (Suc r) pp - SHOs (Suc r) pp" and qsw: "\<mu>pp qw = Some (Vote (Some w))" by auto with mupp have "qw \<in> SHOs (Suc r) pp" unfolding SHOmsgVectors_def by auto with qsw that show ?thesis by auto qed with stp mupp have "vote (rho (Suc r) qw) = Some w" by (auto simp: Ute_SHOMachine_def SHOmsgVectors_def Ute_sendMsg_def send1_def) moreover from run obtain \<mu>qv \<mu>qw where "nextState Ute_M r qv ((rho r) qv) \<mu>qv (rho (Suc r) qv)" and "\<mu>qv \<in> SHOmsgVectors Ute_M r qv (rho r) (HOs r qv) (SHOs r qv)" and "nextState Ute_M r qw ((rho r) qw) \<mu>qw (rho (Suc r) qw)" and "\<mu>qw \<in> SHOmsgVectors Ute_M r qw (rho r) (HOs r qw) (SHOs r qw)" by (auto simp: Ute_SHOMachine_def SHORun_eq SHOnextConfig_eq) blast ultimately show ?thesis using usafe by (auto dest: common_vote) qed with xw show "x (rho (Suc (Suc r)) pp) = v" by auto qed text {* Inductive argument for the agreement and validity theorems. *} (* The proof relies on previous lemmas @{text common_x_argument_2} and @{text unique_majority_T} and the @{text Ute_commPerRound} predicate. *) lemma safety_inductive_argument: assumes run: "SHORun Ute_M rho HOs SHOs" and comm: "\<forall>r. SHOcommPerRd Ute_M (HOs r) (SHOs r)" and ih: "E - \<alpha> < card {q. sendMsg Ute_M r' q p (rho r' q) = Vote (Some v)}" and stp1: "step r' = Suc 0" shows "E - \<alpha> < card {q. sendMsg Ute_M (Suc (Suc r')) q p (rho (Suc (Suc r')) q) = Vote (Some v)}" proof - from stp1 have "r' > 0" by (auto simp: step_def) with stp1 obtain r where rr':"r' = Suc r" and stpr:"step (Suc r) = Suc 0" by (auto dest: gr0_implies_Suc) have "\<forall>pp. x (rho (Suc (Suc r)) pp) = v" proof fix pp from run obtain \<mu>pp where "\<mu>pp \<in> SHOmsgVectors Ute_M r' pp (rho r') (HOs r' pp) (SHOs r' pp)" and "nextState Ute_M r' pp (rho r' pp) \<mu>pp (rho (Suc r') pp)" by (auto simp: Ute_SHOMachine_def SHORun_eq SHOnextConfig_eq) with run comm ih rr' show "x (rho (Suc (Suc r)) pp) = v" by (auto dest: common_x_argument_2) qed with run stpr have "\<forall>pp p. sendMsg Ute_M (Suc (Suc r)) pp p (rho (Suc (Suc r)) pp) = Val v" by (auto simp: Ute_SHOMachine_def SHORun_eq SHOnextConfig_eq Ute_sendMsg_def send0_def mod_Suc step_def) with rr' have "\<And>p \<mu>p'. \<mu>p' \<in> SHOmsgVectors Ute_M (Suc r') p (rho (Suc r')) (HOs (Suc r') p) (SHOs (Suc r') p) \<Longrightarrow> SHOs (Suc r') p \<inter> HOs (Suc r') p \<subseteq> {q. \<mu>p' q = Some (Val v)}" by (auto simp: SHOmsgVectors_def) hence "\<And>p \<mu>p'. \<mu>p' \<in> SHOmsgVectors Ute_M (Suc r') p (rho (Suc r')) (HOs (Suc r') p) (SHOs (Suc r') p) \<Longrightarrow> card (SHOs (Suc r') p \<inter> HOs (Suc r') p) \<le> card {q. \<mu>p' q = Some (Val v)}" by (auto simp: card_mono) moreover from comm have "\<And>p. T < card (SHOs (Suc r') p \<inter> HOs (Suc r') p)" by (auto simp: Ute_SHOMachine_def Ute_commPerRd_def) ultimately have vT:"\<And>p \<mu>p'. \<mu>p' \<in> SHOmsgVectors Ute_M (Suc r') p (rho (Suc r')) (HOs (Suc r') p) (SHOs (Suc r') p) \<Longrightarrow> T < card {q. \<mu>p' q = Some (Val v)}" by (auto dest: less_le_trans) show ?thesis proof - have "\<forall>pp. vote ((rho (Suc (Suc r'))) pp) = Some v" proof fix pp from run obtain \<mu>pp where nxtpp: "nextState Ute_M (Suc r') pp (rho (Suc r') pp) \<mu>pp (rho (Suc (Suc r')) pp)" and mupp: "\<mu>pp \<in> SHOmsgVectors Ute_M (Suc r') pp (rho (Suc r')) (HOs (Suc r') pp) (SHOs (Suc r') pp)" by (auto simp: Ute_SHOMachine_def SHORun_eq SHOnextConfig_eq) with vT have vT':"card {q. \<mu>pp q = Some (Val v)} > T" by auto moreover from stpr rr' have "step (Suc r') = 0" by (auto simp: mod_Suc step_def) with nxtpp have "next0 (Suc r') pp (rho (Suc r') pp) \<mu>pp (rho (Suc (Suc r')) pp)" by (auto simp: Ute_SHOMachine_def nextState_def Ute_nextState_def) ultimately obtain w where wT:"card {q. \<mu>pp q = Some (Val w)} > T" and votew:"vote (rho (Suc (Suc r')) pp) = Some w" by (auto simp: next0_def) from vT' wT have "v = w" by (auto dest: unique_majority_T) with votew show "vote (rho (Suc (Suc r')) pp) = Some v" by simp qed with run stpr rr' have "\<forall>p. N = card {q. sendMsg Ute_M (Suc (Suc (Suc r))) q p ((rho (Suc (Suc (Suc r)))) q) = Vote (Some v)}" by (auto simp: Ute_SHOMachine_def SHORun_eq SHOnextConfig_eq Ute_sendMsg_def send1_def step_def mod_Suc) with rr' majE EltN show ?thesis by auto qed qed text {* A process that holds some decision @{text v} has decided @{text v} sometime in the past. *} lemma decisionNonNullThenDecided: assumes run:"SHORun Ute_M rho HOs SHOs" and dec: "decide (rho n p) = Some v" shows "\<exists>m<n. decide (rho (Suc m) p) \<noteq> decide (rho m p) \<and> decide (rho (Suc m) p) = Some v" proof - let "?dec k" = "decide ((rho k) p)" have "(\<forall>m<n. ?dec (Suc m) \<noteq> ?dec m \<longrightarrow> ?dec (Suc m) \<noteq> Some v) \<longrightarrow> ?dec n \<noteq> Some v" (is "?P n" is "?A n \<longrightarrow> _") proof (induct n) from run show "?P 0" by (auto simp: Ute_SHOMachine_def SHORun_eq HOinitConfig_eq initState_def Ute_initState_def) next fix n assume ih: "?P n" thus "?P (Suc n)" by force qed with dec show ?thesis by auto qed text {* If process @{text "p1"} has decided value @{text "v1"} and process @{text "p2"} later decides, then @{text "p2"} must decide @{text "v1"}. *} (* The proof relies on previous lemmas @{text decide_step}, @{text decide_with_threshold_E}, @{text unique_majority_E_\<alpha>}, @{text decisionNonNullThenDecided} and @{text safety_inductive_argument}. *) lemma laterProcessDecidesSameValue: assumes run:"SHORun Ute_M rho HOs SHOs" and comm:"\<forall>r. SHOcommPerRd Ute_M (HOs r) (SHOs r)" and dv1:"decide (rho (Suc r) p1) = Some v1" and dn2:"decide (rho (r + k) p2) \<noteq> Some v2" and dv2:"decide (rho (Suc (r + k)) p2) = Some v2" shows "v2 = v1" proof - from run dv1 obtain r1 where r1r:"r1 < Suc r" and dn1:"decide (rho r1 p1) \<noteq> Some v1" and dv1':"decide (rho (Suc r1) p1) = Some v1" by (auto dest: decisionNonNullThenDecided) from r1r obtain s where rr1:"Suc r = Suc (r1 + s)" by (auto dest: less_imp_Suc_add) then obtain k' where kk':"r + k = r1 + k'" by auto with dn2 dv2 have dn2': "decide (rho (r1 + k') p2) \<noteq> Some v2" and dv2': "decide (rho (Suc (r1 + k')) p2) = Some v2" by auto from run dn1 dv1' dn2' dv2' have rs0:"step r1 = Suc 0" and rks0:"step (r1 + k') = Suc 0" by (auto simp: mod_Suc step_def dest: decide_step) have "step (r1 + k') = step (step r1 + k')" unfolding step_def by (rule mod_add_left_eq) with rs0 rks0 have "step k' = 0" by (auto simp: step_def mod_Suc) then obtain k'' where "k' = k''*nSteps" by (auto simp: step_def) with dn2' dv2' have dn2'':"decide (rho (r1 + k''*nSteps) p2) \<noteq> Some v2" and dv2'':"decide (rho (Suc (r1 + k''*nSteps)) p2) = Some v2" by auto from rs0 have stp:"step (r1 + k''*nSteps) = Suc 0" unfolding step_def by auto have inv:"card {q. sendMsg Ute_M (r1 + k''*nSteps) q p1 (rho (r1 + k''*nSteps) q) = Vote (Some v1)} > E - \<alpha>" proof (induct k'') from stp have "step (r1 + 0*nSteps) = Suc 0" by (auto simp: step_def) from run comm dn1 dv1' show "card {q. sendMsg Ute_M (r1 + 0*nSteps) q p1 (rho (r1 + 0*nSteps) q) = Vote (Some v1)} > E - \<alpha>" by (intro decide_with_threshold_E) auto next fix k'' assume ih: "E - \<alpha> < card {q. sendMsg Ute_M (r1 + k''*nSteps) q p1 (rho (r1 + k''*nSteps) q) = Vote (Some v1)}" from rs0 have stps: "step (r1 + k''*nSteps) = Suc 0" by (auto simp: step_def) with run comm ih have "E - \<alpha> < card {q. sendMsg Ute_M (Suc (Suc (r1 + k''*nSteps))) q p1 (rho (Suc (Suc (r1 + k''*nSteps))) q) = Vote (Some v1)}" by (rule safety_inductive_argument) thus "E - \<alpha> < card {q. sendMsg Ute_M (r1 + Suc k'' * nSteps) q p1 (rho (r1 + Suc k'' * nSteps) q) = Vote (Some v1)}" by auto qed moreover from run have "\<forall>q. sendMsg Ute_M (r1 + k''*nSteps) q p1 (rho (r1 + k''*nSteps) q) = sendMsg Ute_M (r1 + k''*nSteps) q p2 (rho (r1 + k''*nSteps) q)" by (auto simp: Ute_SHOMachine_def Ute_sendMsg_def step_def send0_def send1_def) moreover from run comm dn2'' dv2'' have "E - \<alpha> < card {q. sendMsg Ute_M (r1 + k''*nSteps) q p2 (rho (r1 + k''*nSteps) q) = Vote (Some v2)}" by (auto dest: decide_with_threshold_E) ultimately show "v2 = v1" by (auto dest: unique_majority_E_\<alpha>) qed text {* The Agreement property is an immediate consequence of the two preceding lemmas. *} theorem ute_agreement: assumes run: "SHORun Ute_M rho HOs SHOs" and comm: "\<forall>r. SHOcommPerRd Ute_M (HOs r) (SHOs r)" and p: "decide (rho m p) = Some v" and q: "decide (rho n q) = Some w" shows "v = w" proof - from run p obtain k where k1: "decide (rho (Suc k) p) \<noteq> decide (rho k p)" and k2: "decide (rho (Suc k) p) = Some v" by (auto dest: decisionNonNullThenDecided) from run q obtain l where l1: "decide (rho (Suc l) q) \<noteq> decide (rho l q)" and l2: "decide (rho (Suc l) q) = Some w" by (auto dest: decisionNonNullThenDecided) show ?thesis proof (cases "k \<le> l") case True then obtain m where m: "l = k+m" by (auto simp add: le_iff_add) from run comm k2 l1 l2 m have "w = v" by (auto elim!: laterProcessDecidesSameValue) thus ?thesis by simp next case False hence "l \<le> k" by simp then obtain m where m: "k = l+m" by (auto simp add: le_iff_add) from run comm l2 k1 k2 m show ?thesis by (auto elim!: laterProcessDecidesSameValue) qed qed text {* Main lemma for the proof of the Validity property. *} (* The proof relies on previous lemmas @{text safety_inductive_argument}, @{text unique_majority_T} and the @{text Ute_commPerRound} predicate. *) from majv majw have "v = w" by (auto dest: unique_majority_T) with votew show "vote ((rho (Suc 0)) pp) = Some v" by simp qed with run have "card {q. sendMsg Ute_M (Suc 0) q p (rho (Suc 0) q) = Vote (Some v)} = N" by (auto simp: Ute_SHOMachine_def SHORun_eq SHOnextConfig_eq Ute_nextState_def step_def Ute_sendMsg_def send1_def) thus "E - \<alpha> < card {q. sendMsg Ute_M (Suc 0 + 0 * nSteps) q p (rho (Suc 0 + 0 * nSteps) q) = Vote (Some v)}" using majE EltN by auto next fix k assume ih:"E - \<alpha> < card {q. sendMsg Ute_M (Suc 0 + k * nSteps) q p (rho (Suc 0 + k * nSteps) q) = Vote (Some v)}" have "step (Suc 0 + k * nSteps) = Suc 0" by (auto simp: mod_Suc step_def) from run comm ih this have "E - \<alpha> < card {q. sendMsg Ute_M (Suc (Suc (Suc 0 + k * nSteps))) q p (rho (Suc (Suc (Suc 0 + k * nSteps))) q) = Vote (Some v)}" by (rule safety_inductive_argument) thus "E - \<alpha> < card {q. sendMsg Ute_M (Suc 0 + Suc k * nSteps) q p (rho (Suc 0 + Suc k * nSteps) q) = Vote (Some v)}" by simp qed ultimately show ?thesis by simp qed text {* The following theorem shows the Validity property of algorithm \ute{}. *} (* The proof relies on previous lemmas @{text decisionNonNullThenDecided}, @{text decide_step}, @{text decide_with_threshold_E}, @{text unique_majority_E_\<alpha>}, and the @{text Validity_argument}. *) theorem ute_validity: assumes run: "SHORun Ute_M rho HOs SHOs" and comm: "\<forall>r. SHOcommPerRd Ute_M (HOs r) (SHOs r)" and init: "\<forall>p. x (rho 0 p) = v" and dw: "decide (rho r p) = Some w" shows "v = w" proof - from run dw obtain r1 where dnr1:"decide ((rho r1) p) \<noteq> Some w" and dwr1:"decide ((rho (Suc r1)) p) = Some w" by (force dest: decisionNonNullThenDecided) with run have "step r1 \<noteq> 0" by (rule decide_step) hence "step r1 = Suc 0" by (simp add: step_def mod_Suc) with assms have "E - \<alpha> < card {q. sendMsg Ute_M r1 q p (rho r1 q) = Vote (Some v)}" by (rule validity_argument) moreover from run comm dnr1 dwr1 have "card {q. sendMsg Ute_M r1 q p (rho r1 q) = Vote (Some w)} > E - \<alpha>" by (auto dest: decide_with_threshold_E) ultimately show "v = w" by (auto dest: unique_majority_E_\<alpha>) qed subsection {* Proof of Termination *} text {* At the second round of a phase that satisfies the conditions expressed in the global communication predicate, processes update their @{text x} variable with the value @{text v} they receive in more than @{text \<alpha>} messages. *} (* The proof relies on @{text common_vote}. *) lemma set_x_from_vote: assumes run: "SHORun Ute_M rho HOs SHOs" and comm: "SHOcommPerRd Ute_M (HOs r) (SHOs r)" and stp: "step (Suc r) = Suc 0" and \<pi>: "\<forall>p. HOs (Suc r) p = SHOs (Suc r) p" and nxt: "nextState Ute_M (Suc r) p (rho (Suc r) p) \<mu> (rho (Suc (Suc r)) p)" and mu: "\<mu> \<in> SHOmsgVectors Ute_M (Suc r) p (rho (Suc r)) (HOs (Suc r) p) (SHOs (Suc r) p)" and vp: "\<alpha> < card {qq. \<mu> qq = Some (Vote (Some v))}" shows "x ((rho (Suc (Suc r))) p) = v" proof - from nxt stp vp obtain wp where xwp:"\<alpha> < card {qq. \<mu> qq = Some (Vote (Some wp))}" and xp:"x (rho (Suc (Suc r)) p) = wp" by (auto simp: Ute_SHOMachine_def nextState_def Ute_nextState_def next1_def) have "wp = v" proof - from xwp obtain pp where smw:"\<mu> pp = Some (Vote (Some wp))" by force have "vote (rho (Suc r) pp) = Some wp" proof - from smw mu \<pi> have "\<mu> pp = Some (sendMsg Ute_M (Suc r) pp p (rho (Suc r) pp))" unfolding SHOmsgVectors_def by force with stp have "\<mu> pp = Some (Vote (vote (rho (Suc r) pp)))" by (auto simp: Ute_SHOMachine_def Ute_sendMsg_def send1_def) with smw show ?thesis by auto qed moreover from vp obtain qq where smv:"\<mu> qq = Some (Vote (Some v))" by force have "vote (rho (Suc r) qq) = Some v" proof - from smv mu \<pi> have "\<mu> qq = Some (sendMsg Ute_M (Suc r) qq p (rho (Suc r) qq))" unfolding SHOmsgVectors_def by force with stp have "\<mu> qq = Some (Vote (vote (rho (Suc r) qq)))" by (auto simp: Ute_SHOMachine_def Ute_sendMsg_def send1_def) with smv show ?thesis by auto qed moreover from run obtain \<mu>pp \<mu>qq where "nextState Ute_M r pp (rho r pp) \<mu>pp (rho (Suc r) pp)" and "\<mu>pp \<in> SHOmsgVectors Ute_M r pp (rho r) (HOs r pp) (SHOs r pp)" and "nextState Ute_M r qq ((rho r) qq) \<mu>qq (rho (Suc r) qq)" and "\<mu>qq \<in> SHOmsgVectors Ute_M r qq (rho r) (HOs r qq) (SHOs r qq)" unfolding Ute_SHOMachine_def SHORun_eq SHOnextConfig_eq by blast ultimately show ?thesis using comm by (auto dest: common_vote) qed with xp show ?thesis by simp qed text {* Assume that HO and SHO sets are uniform at the second step of some phase. Then at the subsequent round there exists some value @{text v} such that any received message which is not corrupted holds @{text v}. *} (* The proof relies on lemma @{text set_x_from_vote}. *) lemma termination_argument_1: assumes run: "SHORun Ute_M rho HOs SHOs" and comm: "SHOcommPerRd Ute_M (HOs r) (SHOs r)" and stp: "step (Suc r) = Suc 0" and \<pi>: "\<forall>p. \<pi>0 = HOs (Suc r) p \<and> \<pi>0 = SHOs (Suc r) p" obtains v where "\<And>p \<mu>p' q. \<lbrakk> q \<in> SHOs (Suc (Suc r)) p \<inter> HOs (Suc (Suc r)) p; \<mu>p' \<in> SHOmsgVectors Ute_M (Suc (Suc r)) p (rho (Suc (Suc r))) (HOs (Suc (Suc r)) p) (SHOs (Suc (Suc r)) p) \<rbrakk> \<Longrightarrow> \<mu>p' q = (Some (Val v))" proof - from \<pi> have hosho:"\<forall>p. SHOs (Suc r) p = SHOs (Suc r) p \<inter> HOs (Suc r) p" by simp have "\<And>p q. x (rho (Suc (Suc r)) p) = x (rho (Suc (Suc r)) q)" proof - fix p q from run obtain \<mu>p where nxt: "nextState Ute_M (Suc r) p (rho (Suc r) p) \<mu>p (rho (Suc (Suc r)) p)" and mu: "\<mu>p \<in> SHOmsgVectors Ute_M (Suc r) p (rho (Suc r)) (HOs (Suc r) p) (SHOs (Suc r) p)" by (auto simp: Ute_SHOMachine_def SHORun_eq SHOnextConfig_eq) from run obtain \<mu>q where nxtq: "nextState Ute_M (Suc r) q (rho (Suc r) q) \<mu>q (rho (Suc (Suc r)) q)" and muq: "\<mu>q \<in> SHOmsgVectors Ute_M (Suc r) q (rho (Suc r)) (HOs (Suc r) q) (SHOs (Suc r) q)" by (auto simp: Ute_SHOMachine_def SHORun_eq SHOnextConfig_eq) have "\<forall>qq. \<mu>p qq = \<mu>q qq" proof fix qq show "\<mu>p qq = \<mu>q qq" proof (cases "\<mu>p qq = None") case False with mu \<pi> have 1:"qq \<in> SHOs (Suc r) p" and 2:"qq \<in> SHOs (Suc r) q" unfolding SHOmsgVectors_def by auto from mu \<pi> 1 have "\<mu>p qq = Some (sendMsg Ute_M (Suc r) qq p (rho (Suc r) qq))" unfolding SHOmsgVectors_def by auto moreover from muq \<pi> 2 have "\<mu>q qq = Some (sendMsg Ute_M (Suc r) qq q (rho (Suc r) qq))" unfolding SHOmsgVectors_def by auto ultimately show ?thesis by (auto simp: Ute_SHOMachine_def Ute_sendMsg_def step_def send0_def send1_def) next case True with mu have "qq \<notin> HOs (Suc r) p" unfolding SHOmsgVectors_def by auto with \<pi> muq have "\<mu>q qq = None" unfolding SHOmsgVectors_def by auto with True show ?thesis by simp qed qed hence vsets:"\<And>v. {qq. \<mu>p qq = Some (Vote (Some v))} = {qq. \<mu>q qq = Some (Vote (Some v))}" by auto (* NB: due to the Global predicate (HO = SHO), we do not need \<alpha> + 1 msgs holding a true vote, only 1. We might also prefer to invoke only the @{text Ute_commPerRound} predicate to obtain qq : since "card (HOs (Suc r) p - SHOs (Suc r) p) < \<alpha>", there should be one "correct" message holding a vote and this vote should be common according to previous (Suc r)esults. *) show "x (rho (Suc (Suc r)) p) = x (rho (Suc (Suc r)) q)" proof (cases "\<exists>v. \<alpha> < card {qq. \<mu>p qq = Some (Vote (Some v))}", clarify) fix v assume vp: "\<alpha> < card {qq. \<mu>p qq = Some (Vote (Some v))}" with run comm stp \<pi> nxt mu have "x (rho (Suc (Suc r)) p) = v" by (auto dest: set_x_from_vote) moreover from vsets vp have "\<alpha> < card {qq. \<mu>q qq = Some (Vote (Some v))}" by auto with run comm stp \<pi> nxtq muq have "x (rho (Suc (Suc r)) q) = v" by (auto dest: set_x_from_vote) ultimately show "x (rho (Suc (Suc r)) p) = x (rho (Suc (Suc r)) q)" by auto next assume nov: "\<not> (\<exists>v. \<alpha> < card {qq. \<mu>p qq = Some (Vote (Some v))})" with nxt stp have "x (rho (Suc (Suc r)) p) = undefined" by (auto simp: Ute_SHOMachine_def nextState_def Ute_nextState_def next1_def) moreover from vsets nov have "\<not> (\<exists>v. \<alpha> < card {qq. \<mu>q qq = Some (Vote (Some v))})" by auto with nxtq stp have "x (rho (Suc (Suc r)) q) = undefined" by (auto simp: Ute_SHOMachine_def nextState_def Ute_nextState_def next1_def) ultimately show ?thesis by simp qed qed then obtain v where "\<And>q. x (rho (Suc (Suc r)) q) = v" by blast moreover from stp have "step (Suc (Suc r)) = 0" by (auto simp: step_def mod_Suc) hence "\<And>p \<mu>p' q. \<lbrakk> q \<in> SHOs (Suc (Suc r)) p \<inter> HOs (Suc (Suc r)) p; \<mu>p' \<in> SHOmsgVectors Ute_M (Suc (Suc r)) p (rho (Suc (Suc r))) (HOs (Suc (Suc r)) p) (SHOs (Suc (Suc r)) p) \<rbrakk> \<Longrightarrow> \<mu>p' q = Some (Val (x (rho (Suc (Suc r)) q)))" by (auto simp: Ute_SHOMachine_def SHOmsgVectors_def Ute_sendMsg_def send0_def) ultimately have "\<And>p \<mu>p' q. \<lbrakk> q \<in> SHOs (Suc (Suc r)) p \<inter> HOs (Suc (Suc r)) p; \<mu>p' \<in> SHOmsgVectors Ute_M (Suc (Suc r)) p (rho (Suc (Suc r))) (HOs (Suc (Suc r)) p) (SHOs (Suc (Suc r)) p) \<rbrakk> \<Longrightarrow> \<mu>p' q = (Some (Val v))" by auto with that show thesis by blast qed text {* If a process @{text p} votes @{text v} at some round @{text r}, then all messages received by @{text p} in @{text r} that are not corrupted hold @{text v}. *} (* immediate from lemma @{text vote_step} and the algorithm definition. *) lemma termination_argument_2: assumes mup: "\<mu>p \<in> SHOmsgVectors Ute_M (Suc r) p (rho (Suc r)) (HOs (Suc r) p) (SHOs (Suc r) p)" and nxtq: "nextState Ute_M r q (rho r q) \<mu>q (rho (Suc r) q)" and vq: "vote (rho (Suc r) q) = Some v" and qsho: "q \<in> SHOs (Suc r) p \<inter> HOs (Suc r) p" shows "\<mu>p q = Some (Vote (Some v))" proof - from nxtq vq have "step r = 0" by (auto simp: vote_step) with mup qsho have "\<mu>p q = Some (Vote (vote (rho (Suc r) q)))" by (auto simp: Ute_SHOMachine_def SHOmsgVectors_def Ute_sendMsg_def step_def send1_def mod_Suc) with vq show "\<mu>p q = Some (Vote (Some v))" by auto qed text{* We now prove the Termination property. *} (* The proof relies on previous lemmas @{text termination_argument_1}, @{text termination_argument_2}, @{text common_vote}, @{text unique_majority_E}, and the @{text Ute_commGlobal} predicate. *) theorem ute_termination: assumes run: "SHORun Ute_M rho HOs SHOs" and commR: "\<forall>r. SHOcommPerRd Ute_M (HOs r) (SHOs r)" and commG: "SHOcommGlobal Ute_M HOs SHOs" shows "\<exists>r v. decide (rho r p) = Some v" proof - from commG obtain \<Phi> \<pi> r0 where rr: "r0 = Suc (nSteps * \<Phi>)" and \<pi>: "\<forall>p. \<pi> = HOs r0 p \<and> \<pi> = SHOs r0 p" and t: "\<forall>p. card (SHOs (Suc r0) p \<inter> HOs (Suc r0) p) > T" and e: "\<forall>p. card (SHOs (Suc (Suc r0)) p \<inter> HOs (Suc (Suc r0)) p) > E" by (auto simp: Ute_SHOMachine_def Ute_commGlobal_def Let_def) from rr have stp:"step r0 = Suc 0" by (auto simp: step_def) obtain w where votew:"\<forall>p. (vote (rho (Suc (Suc r0)) p)) = Some w" proof - have abc:"\<forall>p. \<exists>w. vote (rho (Suc (Suc r0)) p) = Some w" proof fix p from run stp obtain \<mu>p where nxt:"nextState Ute_M (Suc r0) p (rho (Suc r0) p) \<mu>p (rho (Suc (Suc r0)) p)" and mup:"\<mu>p \<in> SHOmsgVectors Ute_M (Suc r0) p (rho (Suc r0)) (HOs (Suc r0) p) (SHOs (Suc r0) p)" by (auto simp: Ute_SHOMachine_def SHORun_eq SHOnextConfig_eq) have "\<exists>v. T < card {qq. \<mu>p qq = Some (Val v)}" proof - from t have "card (SHOs (Suc r0) p \<inter> HOs (Suc r0) p) > T" .. moreover from run commR stp \<pi> rr obtain v where "\<And>p \<mu>p' q. \<lbrakk> q \<in> SHOs (Suc r0) p \<inter> HOs (Suc r0) p; \<mu>p' \<in> SHOmsgVectors Ute_M (Suc r0) p (rho (Suc r0)) (HOs (Suc r0) p) (SHOs (Suc r0) p) \<rbrakk> \<Longrightarrow> \<mu>p' q = Some (Val v)" using termination_argument_1 by blast with mup obtain v where "\<And>qq. qq \<in> SHOs (Suc r0) p \<inter> HOs (Suc r0) p \<Longrightarrow> \<mu>p qq = Some (Val v)" by auto hence "SHOs (Suc r0) p \<inter> HOs (Suc r0) p \<subseteq> {qq. \<mu>p qq = Some (Val v)}" by auto hence "card (SHOs (Suc r0) p \<inter> HOs (Suc r0) p) \<le> card {qq. \<mu>p qq = Some (Val v)}" by (auto intro: card_mono) ultimately have "T < card {qq. \<mu>p qq = Some (Val v)}" by auto thus ?thesis by auto qed with stp nxt show "\<exists>w. vote ((rho (Suc (Suc r0))) p) = Some w" by (auto simp: Ute_SHOMachine_def nextState_def Ute_nextState_def step_def mod_Suc next0_def) qed then obtain qq w where qqw:"vote (rho (Suc (Suc r0)) qq) = Some w" by blast have "\<forall>pp. vote (rho (Suc (Suc r0)) pp) = Some w" proof fix pp from abc obtain wp where pwp:"vote ((rho (Suc (Suc r0))) pp) = Some wp" by blast from run obtain \<mu>pp \<mu>qq where nxtp: "nextState Ute_M (Suc r0) pp (rho (Suc r0) pp) \<mu>pp (rho (Suc (Suc r0)) pp)" and mup: "\<mu>pp \<in> SHOmsgVectors Ute_M (Suc r0) pp (rho (Suc r0)) (HOs (Suc r0) pp) (SHOs (Suc r0) pp)" and nxtq: "nextState Ute_M (Suc r0) qq (rho (Suc r0) qq) \<mu>qq (rho (Suc (Suc r0)) qq)" and muq: "\<mu>qq \<in> SHOmsgVectors Ute_M (Suc r0) qq (rho (Suc r0)) (HOs (Suc r0) qq) (SHOs (Suc r0) qq)" unfolding Ute_SHOMachine_def SHORun_eq SHOnextConfig_eq by blast from commR this pwp qqw have "wp = w" by (auto dest: common_vote) with pwp show "vote ((rho (Suc (Suc r0))) pp) = Some w" by auto qed with that show ?thesis by auto qed from run obtain \<mu>p' where nxtp: "nextState Ute_M (Suc (Suc r0)) p (rho (Suc (Suc r0)) p) \<mu>p' (rho (Suc (Suc (Suc r0))) p)" and mup': "\<mu>p' \<in> SHOmsgVectors Ute_M (Suc (Suc r0)) p (rho (Suc (Suc r0))) (HOs (Suc (Suc r0)) p) (SHOs (Suc (Suc r0)) p)" by (auto simp: Ute_SHOMachine_def SHORun_eq SHOnextConfig_eq) have "\<And>qq. qq \<in> SHOs (Suc (Suc r0)) p \<inter> HOs (Suc (Suc r0)) p \<Longrightarrow> \<mu>p' qq = Some (Vote (Some w))" proof - fix qq assume qqsho:"qq \<in> SHOs (Suc (Suc r0)) p \<inter> HOs (Suc (Suc r0)) p" from run obtain \<mu>qq where nxtqq:"nextState Ute_M (Suc r0) qq (rho (Suc r0) qq) \<mu>qq (rho (Suc (Suc r0)) qq)" by (auto simp: Ute_SHOMachine_def SHORun_eq SHOnextConfig_eq) from commR mup' nxtqq votew qqsho show "\<mu>p' qq = Some (Vote (Some w))" by (auto dest: termination_argument_2) qed hence "SHOs (Suc (Suc r0)) p \<inter> HOs (Suc (Suc r0)) p \<subseteq> {qq. \<mu>p' qq = Some (Vote (Some w))}" by auto hence wsho: "card (SHOs (Suc (Suc r0)) p \<inter> HOs (Suc (Suc r0)) p) \<le> card {qq. \<mu>p' qq = Some (Vote (Some w))}" by (auto simp: card_mono) from stp have "step (Suc (Suc r0)) = Suc 0" unfolding step_def by auto with nxtp have "next1 (Suc (Suc r0)) p (rho (Suc (Suc r0)) p) \<mu>p' (rho (Suc (Suc (Suc r0))) p)" by (auto simp: Ute_SHOMachine_def nextState_def Ute_nextState_def) moreover from e have "E < card (SHOs (Suc (Suc r0)) p \<inter> HOs (Suc (Suc r0)) p)" by auto with wsho have majv:"card {qq. \<mu>p' qq = Some (Vote (Some w))} > E" by auto ultimately show ?thesis by (auto simp: next1_def) qed subsection {* \ute{} Solves Weak Consensus *} text {* Summing up, all (coarse-grained) runs of \ute{} for HO and SHO collections that satisfy the communication predicate satisfy the Weak Consensus property. *} theorem ute_weak_consensus: assumes run: "SHORun Ute_M rho HOs SHOs" and commR: "\<forall>r. SHOcommPerRd Ute_M (HOs r) (SHOs r)" and commG: "SHOcommGlobal Ute_M HOs SHOs" shows "weak_consensus (x \<circ> (rho 0)) decide rho" unfolding weak_consensus_def using ute_validity[OF run commR] ute_agreement[OF run commR] ute_termination[OF run commR commG] by auto text {* By the reduction theorem, the correctness of the algorithm carries over to the fine-grained model of runs. *} theorem ute_weak_consensus_fg: assumes run: "fg_run Ute_M rho HOs SHOs (\<lambda>r q. undefined)" and commR: "\<forall>r. SHOcommPerRd Ute_M (HOs r) (SHOs r)" and commG: "SHOcommGlobal Ute_M HOs SHOs" shows "weak_consensus (\<lambda>p. x (state (rho 0) p)) decide (state \<circ> rho)" (is "weak_consensus ?inits _ _") proof (rule local_property_reduction[OF run weak_consensus_is_local]) fix crun assume crun: "CSHORun Ute_M crun HOs SHOs (\<lambda>r q. undefined)" and init: "crun 0 = state (rho 0)" from crun have "SHORun Ute_M crun HOs SHOs" by (unfold SHORun_def) from this commR commG have "weak_consensus (x \<circ> (crun 0)) decide crun" by (rule ute_weak_consensus) with init show "weak_consensus ?inits decide crun" by (simp add: o_def) qed end -- {* context @{text "ute_parameters"} *} end (* theory UteProof *)
If we have missed anything please feel free to email us so that we can answer your question. Will my personal information be safe if I share it with you? As a family owned business we know our guests trust is of utmost importance. Therefore we want to assure you that any information you choose to share with us on our site will not be sold or shared with additional parties without your express permission. How much is your local sales tax? There is no sales tax in the state of Oregon so there will not be sales tax added to your order. Ainslee’s Homemade Salt Water Taffy is carefully packaged to ensure a secure arrival but please note that it is not recommended to ship our fudge into warm climates as it may melt in the package. Please be sure to check delivery addresses carefully. We cannot extend our guarantee to orders for which we are given incomplete or incorrect addresses. Postal and delivery services will not forward the packages on without the correct address. Please allow 2-3 days to process and ship orders. We will make every effort to expedite orders. We ship orders via USPS priority unless otherwise specified in your order form. See more on our shipping and handling page. How can I recommend you to my friends and family? As a family owned business we rely on word of mouth advertising to increase our sales so that we are able to provide you with the freshest possible product for the most reasonable price we can offer. As you can imagine, the busier we are, the more reasonably priced candies we can offer to you so please spread the word and help us stay around for yet another generation of quality candy making. You can also fill out the "Recommend Us" form on our website. What kind of ingredients do you use? How will I know if something is contained within the product? Wherever we can we make sure to use all natural ingredients in our products. This means no artificial preservatives to lengthen the shelf life of your candy and therefore a more natural product for your body. Although we employ careful sanitation procedures in our cooking process it is important that you know that there is a chance of allergens being introduced into your product so please be cautious if you have a severe allergy. For example we make the peanut butter filled taffy on the same machine as all the rest of the taffy and there is no way to ensure that we have safely eliminated 100% of the peanut contamination before starting the next batch. If you have a specific allergy concern please feel free to email us with questions. What is the best way to store my taffy? What is the best way to store my Caramel Corn? The enemy to freshness here is air and heat. We ship it in a plastic bag to ensure the least amount of air gets to the product. If you would like to keep it longer than a week (after you receive it) you will want to get as much air out of the bag as possible and store it either in Tupperware, or a ziplock bag for maximum freshness. What is the best way to store my Fudge? Fudge will stay fresh for approximately ten days if properly wrapped in plastic wrap or Tupperware. Refrigerating your fudge will dry it out so try to keep it at room temperature. If you would like to keep your fudge for longer than ten days you will need to properly protect it by wrapping it in plastic wrap and then slipping it into a freezer safe bag to store in the freezer. It will keep well in the freezer for up to three months. Do you partner for fundraising? Actually we do. We have several different programs to help you raise money for your cause. Please email or contact our store for specific questions. 15% Discount of homemade salt water taffy to all active duty military personnel with valid military id. Although you would need to present the ID in store to receive the discount we also offer it on mail orders placed to APO addresses in order to encourage you to send goodies to the men and women that are protecting our country. In order to receive the discount on a web orders please send your order by email or snail mail so that we may apply your discount to the final purchase price. We do offer discounts on large orders but please be aware that we will need adequate notice to fulfill larger than typical orders. The timeframe necessary is dependant upon the size of the order. Can I get my candy customized? You used to have a certain flavor, can I still buy that flavor? If you are willing to buy the entire batch we can customize the taffy color of virtually any of our flavors for you. We also have discontinued flavors that we can craft for you if you do not see them on our web site so please do not hesitate to ask. Additionally, sometimes we have recipes for things we do not carry (such as Amaretto fudge, licorice caramel corn or almond brittle) that we can make upon request but please keep in mind that there is a necessary minimum order, contact us to find out more. Do you have a taffy of the month program? Yes, actually we send the recipient a different flavor of taffy every single month. You can choose a three, six month or year long program and either go with the default flavor of the month, mixed or create your own combination for each month. Go to our "Taffy of the month" page on our website to learn more. How do I apply for a job at your store? What could be better than working for a candy store? If you would like to apply for a position with our company please stop by our store for an application. Although we are not always hiring we are always accepting applications. We tend to hire from applications we already have so if you would like to join us it’s very helpful to already have an application on file. Contact us, we would love to hear from you! Copyright © Ainslee's Homemade Salt Water Taffy. All rights reserved.
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import for_mathlib.homological_complex_misc import algebra.homology.homological_complex import algebra.homology.additive import for_mathlib.idempotents.functor_extension2 import category_theory.idempotents.homological_complex noncomputable theory open category_theory open category_theory.category open category_theory.preadditive open category_theory.idempotents variables {C : Type*} [category C] [preadditive C] variables {ι : Type*} {c : complex_shape ι} namespace category_theory namespace idempotents namespace karoubi namespace homological_complex variables {P Q : karoubi (homological_complex C c)} (f : P ⟶ Q) (n : ι) @[simp, reassoc] lemma f_p_comp : P.p.f n ≫ f.f.f n = f.f.f n := homological_complex.congr_hom (p_comp f) n @[simp, reassoc] lemma f_comp_p : f.f.f n ≫ Q.p.f n = f.f.f n := homological_complex.congr_hom (comp_p f) n @[reassoc] lemma f_p_comm : P.p.f n ≫ f.f.f n = f.f.f n ≫ Q.p.f n := homological_complex.congr_hom (p_comm f) n end homological_complex end karoubi namespace karoubi_homological_complex namespace functor @[simps] def obj (P : karoubi (homological_complex C c)) : homological_complex (karoubi C) c := { X := λ n, ⟨P.X.X n, P.p.f n, by simpa only [homological_complex.comp_f] using homological_complex.congr_hom P.idem n⟩, d := λ i j, { f := P.p.f i ≫ P.X.d i j, comm := begin have h := homological_complex.congr_hom P.idem j, simp only [homological_complex.hom.comm_assoc, assoc, homological_complex.hom.comm, homological_complex.comp_f] at h ⊢, simp only [h] end, }, shape' := λ i j hij, by simp only [karoubi.hom_eq_zero_iff, P.X.shape i j hij, limits.comp_zero], d_comp_d' := λ i j k hij hjk, begin simp only [karoubi.hom_eq_zero_iff, karoubi.comp_f, P.p.comm j k], slice_lhs 2 3 { rw P.X.d_comp_d' i j k hij hjk, }, simp only [limits.comp_zero, limits.zero_comp], end, } @[simps] def map {P Q : karoubi (homological_complex C c)} (f : P ⟶ Q) : obj P ⟶ obj Q := { f:= λ n, { f:= f.f.f n, comm := by simpa only [homological_complex.comp_f] using homological_complex.congr_hom f.comm n, }, comm' := λ i j hij, begin ext, simp only [karoubi.comp_f, obj_d_f, assoc, ← f.f.comm], simp only [← assoc], have eq := homological_complex.congr_hom (karoubi.p_comm f) i, simp only [homological_complex.comp_f] at eq, rw eq, end } end functor @[simps] def functor : karoubi (homological_complex C c) ⥤ homological_complex (karoubi C) c := { obj := functor.obj, map := λ P Q f, functor.map f, map_comp' := λ P Q R f f', by { ext n, simpa only [karoubi.comp_f], }, } namespace inverse @[simps] def obj (K : homological_complex (karoubi C) c) : karoubi (homological_complex C c) := { X := { X := λ n, (K.X n).X, d := λ i j, (K.d i j).f, shape' := λ i j hij, karoubi.hom_eq_zero_iff.mp (K.shape' i j hij), d_comp_d' := λ i j k hij hjk, by simpa only [karoubi.comp_f] using karoubi.hom_eq_zero_iff.mp (K.d_comp_d' i j k hij hjk), }, p := { f := λ n, (K.X n).p, comm' := λ i j hij, karoubi.p_comm (K.d i j), }, idem := by { ext n, simpa only [karoubi.comp_f] using (K.X n).idem, }, } @[simps] def map {K L : homological_complex (karoubi C) c} (f : K ⟶ L) : obj K ⟶ obj L := { f:= { f := λ n, (f.f n).f, comm' := λ i j hij, by simpa only [karoubi.comp_f] using karoubi.hom_ext.mp (f.comm' i j hij), }, comm := by { ext n, exact (f.f n).comm, }, } end inverse @[simps] def inverse : homological_complex (karoubi C) c ⥤ karoubi (homological_complex C c) := { obj := inverse.obj, map := λ K L f, inverse.map f, map_comp' := λ K L M f g, by { ext n, simp only [karoubi.comp_f, homological_complex.comp_f, inverse.map_f_f], }, } def counit_eq : inverse ⋙ functor = 𝟭 (homological_complex (karoubi C) c) := begin apply functor.ext, { intros K L f, ext n, dsimp [functor.map, inverse.map], simp only [karoubi.eq_to_hom_f, functor.obj_X_p, homological_complex.eq_to_hom_f, eq_to_hom_refl, comp_id, karoubi.comp_f, inverse.obj_p_f], rw [← karoubi.hom.comm], }, { intro P, apply homological_complex.ext, { intros i j hij, simp [homological_complex.eq_to_hom_f], refl, }, { ext n, { simpa only [id_comp, eq_to_hom_refl, comp_id], }, { refl, }, }, }, end @[simps] def unit_iso : 𝟭 (karoubi (homological_complex C c)) ≅ functor ⋙ inverse := { hom := { app := λ P, { f := { f := λ n, P.p.f n, comm' := λ i j hij, begin dsimp, have h := homological_complex.congr_hom P.idem i, simp only [homological_complex.comp_f] at h, slice_lhs 1 2 { erw h, }, exact P.p.comm' i j hij, end }, comm := begin ext n, have h := homological_complex.congr_hom P.idem n, simp only [homological_complex.comp_f] at h, dsimp, rw [h, h], end }, naturality' := λ X Y f, begin ext n, have h := homological_complex.congr_hom ((karoubi.p_comm f).symm) n, simpa only [functor.map_f_f, homological_complex.comp_f, inverse.map_f_f, karoubi.comp_f] using h, end }, inv := { app := λ P, { f := { f := λ n, P.p.f n, comm' := λ i j hij, begin dsimp, slice_rhs 2 3 { rw ← P.p.comm' i j hij, }, rw ← assoc, have h := homological_complex.congr_hom P.idem i, simp only [homological_complex.comp_f] at h, rw h, end }, comm := begin ext n, have h := homological_complex.congr_hom P.idem n, simp only [homological_complex.comp_f] at h, dsimp, rw [h, h], end }, naturality' := λ P Q f, begin ext n, have h := homological_complex.congr_hom (karoubi.p_comm f).symm n, simpa only [functor_map, functor.map_f_f, functor.id_map, functor.comp_map, homological_complex.comp_f, inverse.map_f_f, inverse_map, karoubi.comp_f] using h, end }, hom_inv_id' := begin ext P n, dsimp, simpa only [homological_complex.comp_f, karoubi.id_eq, karoubi.comp_f] using homological_complex.congr_hom P.idem n, end, inv_hom_id' := begin ext P n, dsimp [inverse.obj, functor.obj], simpa only [homological_complex.comp_f, karoubi.id_eq, karoubi.comp_f] using homological_complex.congr_hom P.idem n, end, } end karoubi_homological_complex variables (C) (c) /-@[simps] def karoubi_homological_complex_equivalence : karoubi (homological_complex C c) ≌ homological_complex (karoubi C) c := { functor := karoubi_homological_complex.functor, inverse := karoubi_homological_complex.inverse, unit_iso := karoubi_homological_complex.unit_iso, counit_iso := eq_to_iso karoubi_homological_complex.counit_eq, functor_unit_iso_comp' := λ P, begin ext n, dsimp, have h := homological_complex.congr_hom P.idem n, simpa only [karoubi_homological_complex.unit_iso_hom_app_f_f, homological_complex.eq_to_hom_f, eq_to_hom_app, karoubi_homological_complex.functor.obj_X_p, karoubi_homological_complex.inverse.obj_p_f, eq_to_hom_refl, karoubi.id_eq, karoubi_homological_complex.functor.map_f_f, karoubi.comp_f] using h, end }-/ lemma functor.map_homological_complex_id {D : Type*} [category D] [preadditive D] : functor.map_homological_complex (𝟭 D) c = 𝟭 _ := begin apply functor.ext, { intros X Y f, ext n, dsimp, simp only [homological_complex.eq_to_hom_f, eq_to_hom_refl], erw [id_comp, comp_id], }, { intro X, apply homological_complex.ext, { intros i j hij, erw [comp_id, id_comp], refl, }, { refl, }, }, end @[simps] def nat_iso.map_homological_complex {D E : Type*} [category D] [category E] [preadditive D] [preadditive E] {F G : D ⥤ E} [F.additive] [G.additive] (e : F ≅ G) : functor.map_homological_complex F c ≅ functor.map_homological_complex G c := { hom := nat_trans.map_homological_complex e.hom c, inv := nat_trans.map_homological_complex e.inv c, hom_inv_id' := by simpa only [← nat_trans.map_homological_complex_comp, e.hom_inv_id], inv_hom_id' := by simpa only [← nat_trans.map_homological_complex_comp, e.inv_hom_id], } def equivalence.map_homological_complex {D E : Type*} [category D] [category E] [preadditive D] [preadditive E] (e : D ≌ E) [e.functor.additive] : homological_complex D c ≌ homological_complex E c := { functor := functor.map_homological_complex e.functor c, inverse := functor.map_homological_complex e.inverse c, unit_iso := eq_to_iso (functor.map_homological_complex_id c).symm ≪≫ nat_iso.map_homological_complex c e.unit_iso, counit_iso := nat_iso.map_homological_complex c e.counit_iso ≪≫ eq_to_iso (functor.map_homological_complex_id c), functor_unit_iso_comp' := λ K, begin ext n, dsimp, simp only [eq_to_hom_app, homological_complex.eq_to_hom_f, eq_to_hom_refl], erw [id_comp, comp_id, e.functor_unit_iso_comp], end, } instance [is_idempotent_complete C] : is_idempotent_complete (homological_complex C c) := begin haveI := (to_karoubi_is_equivalence C), let e := (functor.as_equivalence (to_karoubi C)), let h : (to_karoubi C).additive := by apply_instance, haveI : e.functor.additive := h, rw is_idempotent_complete_iff_of_equivalence (equivalence.map_homological_complex c e), rw ← is_idempotent_complete_iff_of_equivalence (karoubi_homological_complex_equivalence C c), apply_instance, end variables (α : Type*) [add_right_cancel_semigroup α] [has_one α] /-@[simps] def karoubi_chain_complex_equivalence : karoubi (chain_complex C α) ≌ chain_complex (karoubi C) α := karoubi_homological_complex_equivalence C (complex_shape.down α) @[simps] def karoubi_cochain_complex_equivalence : karoubi (cochain_complex C α) ≌ cochain_complex (karoubi C) α := karoubi_homological_complex_equivalence C (complex_shape.up α)-/ end idempotents namespace functor variables {D : Type*} [category D] [preadditive D] @[simps] def map_karoubi_homological_complex (F : C ⥤ D) [F.additive] (c : complex_shape ι) : karoubi (homological_complex C c) ⥤ karoubi (homological_complex D c) := (functor_extension₂ _ _).obj (functor.map_homological_complex F c) lemma map_homological_complex_karoubi_compatibility (F : C ⥤ D) [F.additive] (c : complex_shape ι) : to_karoubi _ ⋙ F.map_karoubi_homological_complex c = F.map_homological_complex c ⋙ to_karoubi _ := begin apply functor.ext, { intros X Y f, ext n, dsimp [to_karoubi], simp only [karoubi.comp_f, karoubi.eq_to_hom_f, eq_to_hom_refl, comp_id, homological_complex.comp_f, map_karoubi_homological_complex_obj_p_f, homological_complex.id_f, map_id, map_homological_complex_map_f], erw id_comp, }, { intro X, ext1, { erw [id_comp, comp_id], ext n, dsimp, simpa only [F.map_id, homological_complex.id_f], }, { refl, }, }, end end functor end category_theory
initialImage = im2single( imread('peppers.png') ); width = size(initialImage, 2); height = size(initialImage, 1); cropPositions = [ 1, 1, height, width; ... % full image 1, 1, height / 2, width / 3; ... % sub patch -height / 2, -width / 2, height / 2, width / 3 ]; ... % sub patch not inside the image crops = cropRectanglesMex( initialImage, cropPositions, [height, width] ); figure(1), imshow( initialImage ); figure(2), imshow( crops(:,:,:,1) ); figure(3), imshow( crops(:,:,:,2) ); figure(4), imshow( crops(:,:,:,3) );
lemma multiplicity_eq_nat: fixes x and y::nat assumes "x > 0" "y > 0" "\<And>p. prime p \<Longrightarrow> multiplicity p x = multiplicity p y" shows "x = y"
SUBROUTINE allreduce_sub( n, comm, a, num ) implicit none include 'mpif.h' integer,intent(IN) :: n, comm, num real(8),intent(INOUT) :: a(n) real(8),allocatable :: b(:) integer :: ierr,i,j,m,nd ierr=0 if ( num <= 1 .or. num > n ) then allocate( b(n) ) ; b=0.0d0 call mpi_allreduce( a, b, n, MPI_REAL8, MPI_SUM, comm, ierr ) a=b else nd = (n+num)/num allocate( b(nd) ) ; b=0.0d0 do i=1,n,nd j=min(i+nd-1,n) m=j-i+1 call mpi_allreduce( a(i), b, m, MPI_REAL8, MPI_SUM, comm, ierr ) a(i:j)=b end do end if deallocate( b ) END SUBROUTINE allreduce_sub
```python from sympy import * import matplotlib.pyplot as plt from sympy.plotting import plot from sympy.matrices import * init_printing() %matplotlib inline ``` # Problem 1 # We have the following system \begin{align} q_D &= b_D - 2p + r \\ q_S &= b_S + 2p - r \\ r &= 2b_r + 4p - 2q \end{align} Convert the system of equations into a linear function of the form $A\mathbf{x} = \mathbf{b}$ \begin{align} q + 2p - r &= b_D \\ 1q - 2p + r &= b_S \\ 1q - 2p + \frac{1}{2}r &= b_r \end{align} and in matrix terms we have \begin{align} \begin{bmatrix} 1 & 2 & -1 \\ 1 & -2 & 1 \\ 1 & -2 & \frac{1}{2} \end{bmatrix} \begin{bmatrix} q \\ p \\ r \end{bmatrix} &= \begin{bmatrix} b_D \\ b_S \\ b_r \end{bmatrix} \end{align} ### Test Solution Existence and Uniqueness with Determinant We want to test the determinant $\det A = 0$. If it is, then we may either have no solution to the system, or an infinite number of solutions. If $\det A \neq 0$ then we know for every vector $\mathbf{b}$ there is a unique solution to the system. ```python A = Matrix([ [1, 2, -1], [1, -2, 1], [1, -2, Rational(1,2)] ]) # We calculate the determinant using A.det() function detA = A.det() A, Eq(Symbol('\det A'),detA) ``` ### Find A^{-1} and Solve the System If $A$ is invertible then $\mathbf{x} = A^{-1}\mathbf{b}$. So calculate the inverse and post multiply $\mathbf{b}$ to find the solution. Assume that $\mathbf{b} = [10,5,1]$. ```python #Instantiate b vector b = Matrix([ [10], [8], [2] ]) #Calculate the inverse of the A matrix. Ainv = A.inv() Ainv, b ``` ```python #Use the inverse of A to find the solution x x = Ainv*b x ``` # Problem 2 Consider the system: \begin{align} q_D &= \frac{b_D}{p^2} \\ q_S &= A_S + \frac{1}{b_S}p^2 \end{align} ```python bD = Symbol('b_D', real=True, positive=True) bS = Symbol('b_S', real=True, positive=True) AS = Symbol('A_S', real=True, positive=True) AD = Symbol('A_D', real=True, positive=True) p = Symbol('p', real=True, positive=True) demand = bD*exp(-p) supply = bS*exp(p) demand, supply ``` ```python #Find the equilibrium price p_eq = solve(demand-supply,p)[0] p_eq ``` ```python grad = Matrix([p_eq.diff(bD), p_eq.diff(bS)]) grad ``` ```python sl = [(bD,5),(bS,1)] gradval = grad.subs(sl) gradval ``` ```python dx = Matrix([Rational(1,9), -Rational(1,7)]) dp = gradval.dot(dx) dp ``` ```python p_eq.subs(sl) + dp ``` ```python plot(5*exp(-p),1*exp(p),(p,0,2)) ``` ```python ```
\documentclass[12pt]{article} \usepackage{alltt,epsfig,html,latexsym,longtable,makeidx,moreverb} \setlength\topmargin{-0.5in} \setlength\textheight{8.5in} \setlength\textwidth{7.0in} \setlength\oddsidemargin{-0.3in} \setlength\evensidemargin{-0.3in} \hyphenation{} \title{{\mlton} SML Style Guide} \author{Stephen Weeks} \date{\today} \include{macros} \makeindex \begin{document} \maketitle \input{abstract} % conventions chosen so that inertia is towards modularity and reuse % not to type fewer characters \sec{High-level structure}{high-level-structure} Code is structured in {\mlton} so that signatures are closed. Thus, in {\mlton}, one would never write the following. \begin{verbatim} signature SIG = sig val f: Foo.t -> int end \end{verbatim} Instead, one would write the following. \begin{verbatim} signature SIG = sig structure Foo: FOO val f: Foo.t -> int end \end{verbatim} The benefit of this approach is that one can first understand the specifications (i.e. signatures) of all of the modules in {\mlton} before having to look at any implementations (i.e. structures or functors). That is, the signatures are self-contained. We deviate from this only in allowing references to top level types (like {\tt int}), basis library modules, and {\mlton} library modules. So, the following signature is fine, because structure {\tt Regexp} is part of the {\mlton} library. \begin{verbatim} signature SIG = sig val f: Regexp.t -> int end \end{verbatim} We also use signatures to express (some of) the dependencies between modules. For every module {\tt Foo}, we write two signatures in a file named {\tt foo.sig}. The signature {\tt FOO} specifies what is implemented by {\tt Foo}. The signature {\tt FOO\_STRUCTS} specifies the modules that are needed in order to specify {\tt Foo}, but that are not implemented by {\tt Foo}. As an example, consider {\mlton}'s closure conversion pass (in {\tt mlton/closure-convert}), which converts from {\tt Sxml}, {\mlton}'s higher-order simply-typed intermediate language, to {\tt Cps}, {\mlton}'s first-order simply-typed intermediate language. The file {\tt closure-convert.sig} contains the following. \begin{verbatim} signature CLOSURE_CONVERT_STRUCTS = sig structure Sxml: SXML structure Cps: CPS sharing Sxml.Atoms = Cps.Atoms end signature CLOSURE_CONVERT = sig include CLOSURE_CONVERT_STRUCTS val closureConvert: Sxml.Program.t -> Cps.Program.t end \end{verbatim} These signatures say that the {\tt ClosureConvert} module implements a function {\tt closureConvert} that transforms an {\tt Sxml} program into a {\tt Cps} program. They also say that {\tt ClosureConvert} does not implement {\tt Sxml} or {\tt Cps}. Rather, it expects some other modules to implement these and for them to be provided to {\tt ClosureConvert}. The sharing constraint expresses that the ILs must share some basic atoms, like constants, variables, and primitives. Given the two signatures that specify a module, the module definition always has the same structure. A module {\tt Foo} is implemented in a file named {\tt foo.fun}, which defines a functor named {\tt Foo} that takes as an argument a structure matching {\tt FOO\_STRUCTS} and returns as a result a structure matching {\tt FOO}. For example, {\tt closure-convert.fun} contains the following. \begin{verbatim} functor ClosureConvert (S: CLOSURE_CONVERT_STRUCTS): CLOSURE_CONVERT = struct open S fun closureConvert ... end \end{verbatim} Although the signatures for {\tt ClosureConvert} express the dependence on the {\tt Sxml} and {\tt Cps} ILs, they do not express the dependence on other modules that are only used internally to closure conversion. For example, closure conversion uses an auxiliary module {\tt AbstractValue} as part of its higher-order control-flow analysis. Because {\tt AbstractValue} is only used internally to closure conversion, it does not appear in the signatures that specify closure conversion. So, helper functors (like {\tt AbstractValue}) are analogous to helper functions in that they are not visible to clients. We do not put helper functors lexically in scope because SML only allows top level functor definitions and, more importantly, because files would become unmanageably large. Instead, helper functors get their own {\tt .sig} and {\tt .fun} file, which follow exactly the convention above. \section{General conventions} \begin{itemize} \item A line of code never exceeds 80 columns. \item Use alphabetical order wherever possible. \begin{itemize} \item record field names \item datatype constructors \item value specs in signatures \item file lists in CM files \item export lists in CM files \end{itemize} \end{itemize} %------------------------------------------------------ % Signature conventions %------------------------------------------------------ \sec{Signatures}{signature-conventions} We now enumerate the conventions we follow in writing signatures. \begin{enumerate} \item Signature identifiers are in all capitals, using ``\_'' to separate words. \item A signature typically contains a single type specification that defines a type constructor {\tt t}, which is the type of interest in the specification. For oexample, here are signature fragments for integers, lists, and maps. \begin{verbatim} signature INTEGER = sig type t val + : t * t -> t ... end signature LIST = sig type 'a t val map: 'a t * ('a -> 'b) -> 'b t ... end signature MAP sig type ('a, 'b) t val extend: ('a, 'b) t * 'a * 'b -> ('a, 'b) t ... end \end{verbatim} Although at first it might appear confusing to name every type {\tt t}, in fact there is never ambiguity, because at any point in the program there is at most one unqualified {\tt t} in scope, and all other types will be named with long identifiers (like {\tt Int.t} or {\tt Int.t List.t}). For example, the code for a function {\tt foo} within the {\tt Map} module might look like the following. \begin{verbatim} fun foo (l: 'a List.t, n: Int.t): ('a, Int.t) t = ... \end{verbatim} In practice, for pervasive types like {\tt int}, {\tt 'a list}, we often use the standard pervasive name instead of the {\tt t} name. \item Signatures should not contain free types or structures, other than pervasives, basis library modules, or {\mlton} library modules. This was explained in \secref{high-level-structure}. \item If additional abstract types (other than pervasive types) are needed to specify operations, they are included as substructures of the signature, and have a signature in their own right. For example, the following signature is good. \begin{verbatim} signature FOO = sig structure Var: VAR type t val fromVar: Var.t -> t val toVar: t -> Var.t end \end{verbatim} \item Signatures do not use substructures or multiple structures to group different operations on the same type. This makes you waste energy remembering where the operations are. For exmample, the following signature is bad. \begin{verbatim} signature REAL = sig type t val + : t * t -> t structure Trig: sig val sin: t -> t val cos: t -> t end end \end{verbatim} \item Signatures usually should not contain datatypes. This exposes the implementation of what should be an abstract type. For example, the following signature is bad. \begin{verbatim} signature COMPLEX = sig datatype t = T of real * real end \end{verbatim} A common exception to this rule is abstract syntax trees. \item Use structure sharing to express type sharing. For example, in {\tt closure-convert.sig}, a single structure sharing equation expresses a number of type sharing equations. \end{enumerate} %------------------------------------------------------ % Value specifications %------------------------------------------------------ \subsec{Value specifications}{val-specs} Here are the conventions that we use for individual value specifications in signatures. Of course, many of these conventions directly impact the way in which we write the core language expressions that implement the specifications. \begin{enumerate} \item In a datatype specification, if there is a single constructor, then that constructor is called {\tt T}. \begin{verbatim} datatype t = T of int \end{verbatim} \item In a datatype specification, if a constructor carries multiple values of the same type, use a record to name them to avoid confusion. \begin{verbatim} datatype t = T of {length: int, start: int} \end{verbatim} \item Identifiers begin with and use small letters, using capital letters to separate words. \begin{verbatim} val helloWorld: unit -> unit \end{verbatim} \item There is no space before the colon, and a single space after it. In the case of operators (like {\tt +}), there is a space before the colon to avoid lexing the colon as part of the operator. \item Pass multiple arguments as tuple, not curried. \begin{verbatim} val eval: Exp.t * Env.t -> Val.t \end{verbatim} \item Currying is only used when there staging of a computation, i.e., if precomputation is done on one of the arguments. \begin{verbatim} val match: Regexp.t -> string -> bool \end{verbatim} \item Functions which take a single element of the abstract type of a signature take the element as the first argument, and auxiliary arguments after. \begin{verbatim} val push: t * int -> unit val map: 'a t * ('a -> 'b) -> 'b t \end{verbatim} \item $n$-ary operations take the $n$ elements first, and auxilary arguments after. \begin{verbatim} val merge: 'a t * 'a t * ('a * 'a -> 'b) -> 'b t \end{verbatim} \item If two arguments to a function are of the same type, and the operation is not commutative, pass them using a record. This names the arguments and ensures they are not confused. Exceptions are the standard numerical and algebraic operators. \begin{verbatim} val fromTo: {start: int, step: int, stop: int} -> int list val substring: t * {length: int, start: int} -> t val - : t * t -> t \end{verbatim} \item Field names in record types are written in alphabetical order. \item Return multiple results as a tuple, or as a record if there is the potential for confusion. \begin{verbatim} val parse: string -> t * string val quotRem: t * t -> t * t val partition: 'a t * ('a -> bool) -> {no: 'a t, yes: 'a t} \end{verbatim} \item If a function returns multiple results, at least two of which are of the same type, and the name of the function does not clearly indicate which result is which, use a record to name the results. \begin{verbatim} val vars: t -> {frees : Vars.t, bound : Vars.t} val partition: 'a t * ('a -> bool) -> {yes : 'a t, no : 'a t} \end{verbatim} \item Use the same names and argument orders for similar functions in different signatures. This is especially common in the {\mlton} library. \begin{verbatim} val < : t * t -> bool val equals: t * t -> bool val forall: 'a t * ('a -> bool) -> bool \end{verbatim} \item Use {\tt is}, {\tt are}, {\tt can}, etc. to name predicates. One exception is {\tt equals}. \begin{verbatim} val isEven: int -> bool val canRead: t -> bool \end{verbatim} \end{enumerate} %------------------------------------------------------ % Signature example %------------------------------------------------------ \subsection{Example} Here is the complete specification of a simple interpreter. This demonstrates the {\tt t}-convention, the closed-signature convention, and the use of sharing constraints. \begin{verbatim} signature VAR = sig type t end signature EXP = sig structure Var: VAR datatype t = Var of Var.t | Lam of Var.t * t | App of t * t end signature VAL = sig structure Var: VAR type t val var: Var.t -> t val lam: Var.t * t -> t val app: t * t -> t end signature INTERP = sig structure Exp: EXP structure Val: VAL sharing Exp.Var = Val.Var val eval: Exp.t -> Val.t end signature ENV = sig structure Var: VAR type 'a t val lookup: 'a t * Var.t -> 'a val extend: 'a t * Var.t * 'a -> 'a t end \end{verbatim} %------------------------------------------------------ % Functors and structures %------------------------------------------------------ \section{Functors and structures} We now enumerate the conventions we follow in writing functors and structures. There is some repetition with \secref{high-level-structure}. \begin{enumerate} \item Functor identifiers begin with capital letters, use mixed case, and use capital letters to separate words. \item Functor definitions look like the following. \begin{verbatim} functor Foo (S: FOO_STRUCTS): FOO = struct open S ... end \end{verbatim} \item The name of the functor is the same as the name of the signature describing the structure it produces. \item The functor result is constrained by a signature. \item A functor takes as arguments any structures that occur in the signature of the result that it does not implement. \item Structure identifiers begin with capital letters, and use capital letters to separate words. \item The name of the structure is the same as the name of the functor that produces it. \item A structure definition looks like one of the following. \begin{verbatim} structure Foo = Foo (S) structure Foo = struct ... end \end{verbatim} \item Avoid the use of {\tt open} except within tightly constrained scopes. The use of {\tt open} makes it hard to look at code later and understand where things come from. \end{enumerate} %------------------------------------------------------ % Core expressions %------------------------------------------------------ \section{Core expressions} We now enumerate the conventions we follow in writing core expressions. We do not repeat the conventions of \secref{val-spec}, although many of them apply here. \begin{enumerate} \item Tuples are written with spaces after commas, like {\tt (a, b, c)}. \item Records are written with spaces on both sides of equals and with spaces after commas, like {\tt \{bar = 1, foo = 2\}}. \item Record field names are written in alphabetical order, both in expressions and types. \item Function application is written with a space between the function and the argument. If there is one untupled argument, it looks like {\tt f x}. If there is a tupleg argument, it looks like {\tt f (x, y, z)}. \item When you want to mix declarations with side-effecting statements, use a declaration like {\tt val \_ = sideEffectingProcedure()}. \item In sequence expressions {\tt (e1; e2)} that span multiple lines, place the semicolon at the beginning of lines. \begin{verbatim} (e1 ; e2 ; e3) \end{verbatim} \item Never write nonexhaustive matches. Always handle the default case and raise an error message. Your error message will be better than the compiler's. Also, if you have lots of uncaught cases, then you are probably not using the type system in a strong enough way - your types are not expressing as much as they could. \item Never use the syntax for declaring functions that repeats the function name. Use {\tt case} or {\tt fn} instead. That is, do not write the following. \begin{verbatim} fun f 0 = 1 | f n = n + 1 \end{verbatim} Instead, write the following. \begin{verbatim} val f = fn 0 => 1 | n => n + 1 \end{verbatim} Or, write the following. \begin{verbatim} fun f n = case n of 0 => 1 | _ => n + 1 \end{verbatim} \end{enumerate} \bibliographystyle{alpha} \bibliography{bib} \end{document}
[STATEMENT] lemma diff_diff_add_mset [simp]: "(M::'a multiset) - N - P = M - (N + P)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. M - N - P = M - (N + P) [PROOF STEP] by (rule diff_diff_add)
section\<open>Kauffman Matrix and Kauffman Bracket- Definitions and Properties\<close> theory Kauffman_Matrix imports Matrix_Tensor.Matrix_Tensor Link_Algebra "HOL-Computational_Algebra.Polynomial" "HOL-Computational_Algebra.Fraction_Field" begin section\<open>Rational Functions\<close> text\<open>intpoly is the type of integer polynomials\<close> type_synonym intpoly = "int poly" (*The following lemma tells us that (pCons 0 1) is an identity function on a given type, if it is a commutative ring*) lemma eval_pCons: "poly (pCons 0 1) x = x" using poly_1 poly_pCons by auto lemma pCons2:" (pCons 0 1) \<noteq> (1::int poly)" using eval_pCons poly_1 zero_neq_one by metis definition var_def: "x = (pCons 0 1)" lemma non_zero:"x \<noteq> 0" using var_def pCons_eq_0_iff zero_neq_one by (metis) text\<open>rat$\_$poly is the fraction field of integer polynomials. In other words, it is the type of rational functions\<close> type_synonym rat_poly = "intpoly fract" text\<open>A is defined to be x/1, while B is defined to be 1/x\<close> definition var_def1:"A = Fract x 1" definition var_def2: "B = Fract 1 x" lemma assumes "b \<noteq> 0" and "d \<noteq> 0" shows "Fract a b = Fract c d \<longleftrightarrow> a * d = c * b" using eq_fract assms by auto lemma A_non_zero:"A \<noteq> (0::rat_poly)" unfolding var_def1 proof(rule ccontr) assume 0:" \<not> (Fract x 1 \<noteq> (0::rat_poly)) " then have "Fract x 1 = (0::rat_poly)" by auto moreover have "(0::rat_poly) = Fract (0::intpoly) (1::intpoly)" by (metis Zero_fract_def) ultimately have "Fract x (1::intpoly) = Fract (0::intpoly) (1::intpoly)" by auto moreover have "(1::intpoly) \<noteq> 0" by auto ultimately have "x*(1::intpoly) = (0::intpoly)*(1::intpoly)" using eq_fract by metis then have "x = (0::intpoly)" by auto then show False using non_zero by auto qed lemma mult_inv_non_zero: assumes "(p::rat_poly) \<noteq> 0" and "p*q = (1::rat_poly)" shows "q \<noteq> 0" using assms by auto abbreviation rat_poly_times::"rat_poly \<Rightarrow> rat_poly \<Rightarrow> rat_poly" where "rat_poly_times p q \<equiv> p*q" abbreviation rat_poly_plus::"rat_poly \<Rightarrow> rat_poly \<Rightarrow> rat_poly" where "rat_poly_plus p q \<equiv> p+q" abbreviation rat_poly_inv::"rat_poly \<Rightarrow> rat_poly" where "rat_poly_inv p \<equiv> (- p)" interpretation rat_poly:semiring_0 "rat_poly_plus" 0 "rat_poly_times" by (unfold_locales) interpretation rat_poly:semiring_1 1 "rat_poly_times" "rat_poly_plus" 0 by (unfold_locales) lemma mat1_equiv:"mat1 (1::nat) = [[(1::rat_poly)]]" by (simp add:mat1I_def vec1I_def) text\<open>rat$\_$poly is an interpretation of the locale plus\_mult\<close> interpretation rat_poly:plus_mult "1" "rat_poly_times" 0 "rat_poly_plus" "rat_poly_inv" apply(unfold_locales) apply(auto) proof- fix p q r show "rat_poly_times p (rat_poly_plus q r) = rat_poly_plus (rat_poly_times p q) (rat_poly_times p r)" by (simp add: distrib_left) show "rat_poly_times (rat_poly_plus p q) r = rat_poly_plus (rat_poly_times p r) (rat_poly_times q r)" by (metis comm_semiring_class.distrib) qed (*using matrix_multiplication *) lemma "rat_poly.matrix_mult [[A,1],[0,A]] [[A,0],[0,A]] = [[A*A,A],[0,A*A]] " apply(simp add:mat_multI_def) apply(simp add:matT_vec_multI_def) apply(auto simp add:replicate_def rat_poly.row_length_def) apply(auto simp add:scalar_prod) done abbreviation rat_polymat_tensor::"rat_poly mat \<Rightarrow> rat_poly mat \<Rightarrow> rat_poly mat" (infixl "\<otimes>" 65) where "rat_polymat_tensor p q \<equiv> rat_poly.Tensor p q" lemma assumes "(j::nat) div a = i div a" and "j mod a = i mod a" shows "j = i" proof- have "a*(j div a) + (j mod a) = j" using mult_div_mod_eq by simp moreover have "a*(i div a) + (i mod a) = i" using mult_div_mod_eq by auto ultimately show ?thesis using assms by metis qed lemma "[[1]] \<otimes> M = M" by (metis rat_poly.Tensor_left_id) lemma " M \<otimes> [[1]] = M" by (metis rat_poly.Tensor_right_id) section\<open>Kauffman matrices\<close> text\<open>We assign every brick to a matrix of rational polynmials\<close> primrec brickmat::"brick \<Rightarrow> rat_poly mat" where "brickmat vert = [[1,0],[0,1]]" |"brickmat cup = [[0],[A],[-B],[0]]" |"brickmat cap = [[0,-A,B,0]]" |"brickmat over = [[A,0,0,0], [0,0,B,0], [0,B,A-(B*B*B),0], [0,0,0,A]]" |"brickmat under = [[B,0,0,0], [0,B-(A*A*A),A,0], [0,A,0,0], [0,0,0,B]]" lemma inverse1:"rat_poly_times A B = 1" using non_zero One_fract_def monoid_mult_class.mult.right_neutral mult_fract mult_fract_cancel var_def1 var_def2 by (metis (hide_lams, no_types)) lemma inverse2:"rat_poly_times B A = 1" using One_fract_def monoid_mult_class.mult.right_neutral mult_fract mult_fract_cancel non_zero var_def1 var_def2 by (metis (hide_lams, no_types)) lemma B_non_zero:"B \<noteq> 0" using A_non_zero mult_inv_non_zero inverse1 divide_fract div_0 fract_collapse(2) monoid_mult_class.mult.left_neutral mult_fract_cancel non_zero var_def2 zero_neq_one by (metis (hide_lams, mono_tags)) lemma "rat_poly_times p (q + r) = (rat_poly_times p q) + (rat_poly_times p r)" by (metis rat_poly.plus_left_distributivity) lemma minus_left_distributivity: "rat_poly_times p (q - r) = (rat_poly_times p q) - (rat_poly_times p r)" using minus_mult_right right_diff_distrib by blast lemma minus_right_distributivity: "rat_poly_times (p - q) r = (rat_poly_times p r) - (rat_poly_times q r)" using minus_left_distributivity rat_poly.comm by metis lemma equation: "rat_poly_plus (rat_poly_times B (B - rat_poly_times (rat_poly_times A A) A)) (rat_poly_times (A - rat_poly_times (rat_poly_times B B) B) A) = 0" proof- have " rat_poly_times (rat_poly_times A A) A = ((A*A)*A)" by auto then have "rat_poly_times B (B - rat_poly_times (rat_poly_times A A) A) = B*B - B*((A*A)*A)" using minus_left_distributivity by auto moreover have "... = B*B - (B*(A*(A*A)))" by auto moreover have "... = B*B - ((B*A)*(A*A))" by auto moreover have "... = B*B - A*A" using inverse2 by auto ultimately have 1: "rat_poly_times B (B - rat_poly_times (rat_poly_times A A) A) = B*B - A*A" by auto have "rat_poly_times (rat_poly_times B B) B = (B*B)*B" by auto then have "(rat_poly_times (A - rat_poly_times (rat_poly_times B B) B) A) = (A*A) - ((B*B)*B)*A" using minus_right_distributivity by auto moreover have "... = (A*A) - ((B*B)*(B*A))" by auto moreover have "... = (A*A) - (B*B)" using inverse2 by auto ultimately have 2: "(rat_poly_times (A - rat_poly_times (rat_poly_times B B) B) A) = (A*A) - (B*B)" by auto have "B*B - A*A + (A*A) - (B*B) = 0" by auto with 1 2 show ?thesis by auto qed lemma "rat_poly.matrix_mult (brickmat over) (brickmat under) = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]] " apply(simp add:mat_multI_def) apply(simp add:matT_vec_multI_def) apply(auto simp add:replicate_def rat_poly.row_length_def) apply(auto simp add:scalar_prod) apply(auto simp add:inverse1 inverse2) apply(auto simp add:equation) done lemma "rat_poly_inv A = -A" by auto lemma vert_dim:"rat_poly.row_length (brickmat vert) = 2 \<and>length (brickmat vert) = 2" using rat_poly.row_length_def by auto lemma cup_dim:"rat_poly.row_length (brickmat cup) = 1" and "length (brickmat cup) = 4" using rat_poly.row_length_def by auto lemma cap_dim:"rat_poly.row_length (brickmat cap) = 4" and "length (brickmat cap) = 1" using rat_poly.row_length_def by auto lemma over_dim:"rat_poly.row_length (brickmat over) = 4" and "length (brickmat over) = 4" using rat_poly.row_length_def by auto lemma under_dim:"rat_poly.row_length (brickmat under) = 4" and "length (brickmat under) = 4" using rat_poly.row_length_def by auto lemma mat_vert:"mat 2 2 (brickmat vert)" unfolding mat_def Ball_def vec_def by auto lemma mat_cup:"mat 1 4 (brickmat cup)" unfolding mat_def Ball_def vec_def by auto lemma mat_cap:"mat 4 1 (brickmat cap)" unfolding mat_def Ball_def vec_def by auto lemma mat_over:"mat 4 4 (brickmat over)" unfolding mat_def Ball_def vec_def by auto lemma mat_under:"mat 4 4 (brickmat under)" unfolding mat_def Ball_def vec_def by auto primrec rowlength::"nat \<Rightarrow> nat" where "rowlength 0 = 1" |"rowlength (Suc k) = 2*(Suc k)" lemma "(rat_poly.row_length (brickmat d)) = (2^(nat (domain d))) " using vert_dim cup_dim cap_dim over_dim under_dim domain.simps by (cases d) (auto) lemma "rat_poly.row_length (brickmat cup) = 1" unfolding rat_poly.row_length_def by auto lemma two:"(Suc (Suc 0)) = 2" by eval text\<open>we assign every block to a matrix of rational function as follows\<close> primrec blockmat::"block \<Rightarrow> rat_poly mat" where "blockmat [] = [[1]]" |"blockmat (l#ls) = (brickmat l) \<otimes> (blockmat ls)" lemma "blockmat [a] = brickmat a" unfolding blockmat.simps rat_poly.Tensor_right_id by auto lemma nat_sum: assumes "a \<ge> 0" and "b \<ge> 0" shows "nat (a+b) = (nat a) + (nat b)" using assms by auto lemma "rat_poly.row_length (blockmat ls) = (2^ (nat ((domain_block ls))))" proof(induct ls) case Nil show ?case unfolding blockmat.simps(1) rat_poly.row_length_def by auto next case (Cons l ls) show ?case proof(cases l) case vert have "rat_poly.row_length (blockmat ls) = 2 ^ nat (domain_block ls)" using Cons by auto then have "rat_poly.row_length (blockmat (l#ls)) = (rat_poly.row_length (brickmat l)) *(rat_poly.row_length (blockmat ls))" using blockmat.simps rat_poly.row_length_mat by auto moreover have "... = 2*(2 ^ nat (domain_block ls))" using rat_poly.row_length_def Cons vert by auto moreover have "... = 2^(1 + nat (domain_block ls))" using domain_block.simps by auto moreover have "... = 2^(nat (domain l) + nat (domain_block ls))" using domain.simps vert by auto moreover have "... = 2^(nat (domain l + domain_block ls))" using Suc_eq_plus1_left Suc_nat_eq_nat_zadd1 calculation(4) domain.simps(1) domain_block_non_negative vert by (metis) moreover have "... = 2^(nat (domain_block (l#ls)))" using domain_block.simps by auto ultimately show ?thesis by metis next case over have "rat_poly.row_length (blockmat ls) = 2 ^ nat (domain_block ls)" using Cons by auto then have "rat_poly.row_length (blockmat (l#ls)) = (rat_poly.row_length (brickmat l)) *(rat_poly.row_length (blockmat ls))" using blockmat.simps rat_poly.row_length_mat by auto also have "... = 4*(2 ^ nat (domain_block ls))" using rat_poly.row_length_def Cons over by auto also have "... = 2^(2 + nat (domain_block ls))" using domain_block.simps by auto also have "... = 2^(nat (domain l) + nat (domain_block ls))" using domain.simps over by auto also have "... = 2^(nat (domain l + domain_block ls))" by (simp add: nat_add_distrib domain_block_nonnegative over) also have "... = 2^(nat (domain_block (l#ls)))" by simp finally show ?thesis . next case under have "rat_poly.row_length (blockmat ls) = 2 ^ nat (domain_block ls)" using Cons by auto then have "rat_poly.row_length (blockmat (l#ls)) = (rat_poly.row_length (brickmat l)) *(rat_poly.row_length (blockmat ls))" using blockmat.simps rat_poly.row_length_mat by auto also have "... = 4*(2 ^ nat (domain_block ls))" using rat_poly.row_length_def Cons under by auto also have "... = 2^(2 + nat (domain_block ls))" using domain_block.simps by auto also have "... = 2^(nat (domain l) + nat (domain_block ls))" using domain.simps under by auto also have "... = 2^(nat (domain l + domain_block ls))" by (simp add: nat_add_distrib domain_block_nonnegative under) also have "... = 2^(nat (domain_block (l#ls)))" using domain_block.simps by auto finally show ?thesis . next case cup have "rat_poly.row_length (blockmat ls) = 2 ^ nat (domain_block ls)" using Cons by auto then have "rat_poly.row_length (blockmat (l#ls)) = (rat_poly.row_length (brickmat l)) *(rat_poly.row_length (blockmat ls))" using blockmat.simps rat_poly.row_length_mat by auto moreover have "... = 1*(2 ^ nat (domain_block ls))" using rat_poly.row_length_def Cons cup by auto moreover have "... = 2^(0 + nat (domain_block ls))" using domain_block.simps by auto moreover have "... = 2^(nat (domain l) + nat (domain_block ls))" using domain.simps cup by auto moreover have "... = 2^(nat (domain l + domain_block ls))" using nat_sum cup domain.simps(2) nat_0 plus_int_code(2) plus_nat.add_0 by (metis) moreover have "... = 2^(nat (domain_block (l#ls)))" using domain_block.simps by auto ultimately show ?thesis by metis next case cap have "rat_poly.row_length (blockmat ls) = 2 ^ nat (domain_block ls)" using Cons by auto then have "rat_poly.row_length (blockmat (l#ls)) = (rat_poly.row_length (brickmat l)) *(rat_poly.row_length (blockmat ls))" using blockmat.simps rat_poly.row_length_mat by auto moreover have "... = 4*(2 ^ nat (domain_block ls))" using rat_poly.row_length_def Cons cap by auto moreover have "... = 2^(2 + nat (domain_block ls))" using domain_block.simps by auto moreover have "... = 2^(nat (domain l) + nat (domain_block ls))" using domain.simps cap by auto moreover have "... = 2^(nat (domain l + domain_block ls))" by (simp add: cap domain_block_nonnegative nat_add_distrib) moreover have "... = 2^(nat (domain_block (l#ls)))" using domain_block.simps by auto ultimately show ?thesis by metis qed qed lemma row_length_domain_block: "rat_poly.row_length (blockmat ls) = (2^ (nat ((domain_block ls))))" proof(induct ls) case Nil show ?case unfolding blockmat.simps(1) rat_poly.row_length_def by auto next case (Cons l ls) show ?case proof(cases l) case vert have "rat_poly.row_length (blockmat ls) = 2 ^ nat (domain_block ls)" using Cons by auto then have "rat_poly.row_length (blockmat (l#ls)) = (rat_poly.row_length (brickmat l)) *(rat_poly.row_length (blockmat ls))" using blockmat.simps rat_poly.row_length_mat by auto moreover have "... = 2*(2 ^ nat (domain_block ls))" using rat_poly.row_length_def Cons vert by auto moreover have "... = 2^(1 + nat (domain_block ls))" using domain_block.simps by auto moreover have "... = 2^(nat (domain l) + nat (domain_block ls))" using domain.simps vert by auto moreover have "... = 2^(nat (domain l + domain_block ls))" using Suc_eq_plus1_left Suc_nat_eq_nat_zadd1 calculation(4) domain.simps(1) domain_block_non_negative vert by metis moreover have "... = 2^(nat (domain_block (l#ls)))" using domain_block.simps by auto ultimately show ?thesis by metis next case over have "rat_poly.row_length (blockmat ls) = 2 ^ nat (domain_block ls)" using Cons by auto then have "rat_poly.row_length (blockmat (l#ls)) = (rat_poly.row_length (brickmat l)) *(rat_poly.row_length (blockmat ls))" using blockmat.simps rat_poly.row_length_mat by auto moreover have "... = 4*(2 ^ nat (domain_block ls))" using rat_poly.row_length_def Cons over by auto moreover have "... = 2^(2 + nat (domain_block ls))" using domain_block.simps by auto moreover have "... = 2^(nat (domain l) + nat (domain_block ls))" using domain.simps over by auto moreover have "... = 2^(nat (domain l + domain_block ls))" by (simp add: over domain_block_nonnegative nat_add_distrib) moreover have "... = 2^(nat (domain_block (l#ls)))" using domain_block.simps by auto ultimately show ?thesis by metis next case under have "rat_poly.row_length (blockmat ls) = 2 ^ nat (domain_block ls)" using Cons by auto then have "rat_poly.row_length (blockmat (l#ls)) = (rat_poly.row_length (brickmat l)) *(rat_poly.row_length (blockmat ls))" using blockmat.simps rat_poly.row_length_mat by auto moreover have "... = 4*(2 ^ nat (domain_block ls))" using rat_poly.row_length_def Cons under by auto moreover have "... = 2^(2 + nat (domain_block ls))" using domain_block.simps by auto moreover have "... = 2^(nat (domain l) + nat (domain_block ls))" using domain.simps under by auto moreover have "... = 2^(nat (domain l + domain_block ls))" by (simp add: under domain_block_nonnegative nat_add_distrib) moreover have "... = 2^(nat (domain_block (l#ls)))" using domain_block.simps by auto ultimately show ?thesis by metis next case cup have "rat_poly.row_length (blockmat ls) = 2 ^ nat (domain_block ls)" using Cons by auto then have "rat_poly.row_length (blockmat (l#ls)) = (rat_poly.row_length (brickmat l)) *(rat_poly.row_length (blockmat ls))" using blockmat.simps rat_poly.row_length_mat by auto moreover have "... = 1*(2 ^ nat (domain_block ls))" using rat_poly.row_length_def Cons cup by auto moreover have "... = 2^(0 + nat (domain_block ls))" using domain_block.simps by auto moreover have "... = 2^(nat (domain l) + nat (domain_block ls))" using domain.simps cup by auto moreover have "... = 2^(nat (domain l + domain_block ls))" using nat_sum cup domain.simps(2) nat_0 plus_int_code(2) plus_nat.add_0 by (metis) moreover have "... = 2^(nat (domain_block (l#ls)))" using domain_block.simps by auto ultimately show ?thesis by metis next case cap have "rat_poly.row_length (blockmat ls) = 2 ^ nat (domain_block ls)" using Cons by auto then have "rat_poly.row_length (blockmat (l#ls)) = (rat_poly.row_length (brickmat l)) *(rat_poly.row_length (blockmat ls))" using blockmat.simps rat_poly.row_length_mat by auto moreover have "... = 4*(2 ^ nat (domain_block ls))" using rat_poly.row_length_def Cons cap by auto moreover have "... = 2^(2 + nat (domain_block ls))" using domain_block.simps by auto moreover have "... = 2^(nat (domain l) + nat (domain_block ls))" using domain.simps cap by auto moreover have "... = 2^(nat (domain l + domain_block ls))" by (simp add: cap domain_block_nonnegative nat_add_distrib) moreover have "... = 2^(nat (domain_block (l#ls)))" using domain_block.simps by auto ultimately show ?thesis by metis qed qed lemma length_codomain_block:"length (blockmat ls) = (2^ (nat ((codomain_block ls))))" proof(induct ls) case Nil show ?case unfolding blockmat.simps(1) rat_poly.row_length_def by auto next case (Cons l ls) show ?case proof(cases l) case vert have "length (blockmat ls) = 2 ^ nat (codomain_block ls)" using Cons by auto then have "length (blockmat (l#ls)) = (length (brickmat l))*(length (blockmat ls))" using blockmat.simps rat_poly.length_Tensor by auto moreover have "... = 2*(2 ^ nat (codomain_block ls))" using Cons vert by auto moreover have "... = 2^(1 + nat (codomain_block ls))" by auto moreover have "... = 2^(nat (codomain l) + nat (codomain_block ls))" using codomain.simps vert by auto moreover have "... = 2^(nat (codomain l + codomain_block ls))" using nat_sum Suc_eq_plus1_left Suc_nat_eq_nat_zadd1 codomain.simps(1) codomain_block_nonnegative nat_numeral numeral_One vert by (metis) moreover have "... = 2^(nat (codomain_block (l#ls)))" by auto ultimately show ?thesis by metis next case over have "length (blockmat ls) = 2 ^ nat (codomain_block ls)" using Cons by auto then have "length (blockmat (l#ls)) = (length (brickmat l))*(length (blockmat ls))" using blockmat.simps rat_poly.length_Tensor by auto moreover have "... = 4*(2 ^ nat (codomain_block ls))" using Cons over by auto moreover have "... = 2^(2 + nat (codomain_block ls))" by auto moreover have "... = 2^(nat (codomain l) + nat (codomain_block ls))" using codomain.simps over by auto moreover have "... = 2^(nat (codomain l + codomain_block ls))" using nat_sum over codomain.simps codomain_block_nonnegative by auto moreover have "... = 2^(nat (codomain_block (l#ls)))" by auto ultimately show ?thesis by metis next case under have "length (blockmat ls) = 2 ^ nat (codomain_block ls)" using Cons by auto then have "length (blockmat (l#ls)) = (length (brickmat l))*(length (blockmat ls))" using blockmat.simps rat_poly.length_Tensor by auto moreover have "... = 4*(2 ^ nat (codomain_block ls))" using Cons under by auto moreover have "... = 2^(2 + nat (codomain_block ls))" by auto moreover have "... = 2^(nat (codomain l) + nat (codomain_block ls))" using codomain.simps under by auto moreover have "... = 2^(nat (codomain l + codomain_block ls))" using nat_sum under codomain.simps codomain_block_nonnegative by auto moreover have "... = 2^(nat (codomain_block (l#ls)))" by auto ultimately show ?thesis by metis next case cup have "length (blockmat ls) = 2 ^ nat (codomain_block ls)" using Cons by auto then have "length (blockmat (l#ls)) = (length (brickmat l))*(length (blockmat ls))" using blockmat.simps rat_poly.length_Tensor by auto moreover have "... = 4*(2 ^ nat (codomain_block ls))" using Cons cup by auto moreover have "... = 2^(2 + nat (codomain_block ls))" by auto moreover have "... = 2^(nat (codomain l) + nat (codomain_block ls))" using codomain.simps cup by auto moreover have "... = 2^(nat (codomain l + codomain_block ls))" using nat_sum cup codomain.simps codomain_block_nonnegative by auto moreover have "... = 2^(nat (codomain_block (l#ls)))" by auto ultimately show ?thesis by metis next case cap have "length (blockmat ls) = 2 ^ nat (codomain_block ls)" using Cons by auto then have "length (blockmat (l#ls)) = (length (brickmat l))*(length (blockmat ls))" using blockmat.simps rat_poly.length_Tensor by auto moreover have "... = 1*(2 ^ nat (codomain_block ls))" using Cons cap by auto moreover have "... = 2^(0 + nat (codomain_block ls))" by auto moreover have "... = 2^(nat (codomain l) + nat (codomain_block ls))" using codomain.simps cap by auto moreover have "... = 2^(nat (codomain l + codomain_block ls))" using nat_sum cap codomain.simps codomain_block_nonnegative by auto moreover have "... = 2^(nat (codomain_block (l#ls)))" by auto ultimately show ?thesis by metis qed qed lemma matrix_blockmat: "mat (rat_poly.row_length (blockmat ls)) (length (blockmat ls)) (blockmat ls)" proof(induct ls) case Nil show ?case using Nil unfolding blockmat.simps(1) rat_poly.row_length_def mat_def vec_def Ball_def by auto next case (Cons a ls) have Cons_1:"mat (rat_poly.row_length (blockmat ls)) (length (blockmat ls)) (blockmat ls)" using Cons by auto have Cons_2:"(blockmat (a#ls)) = (brickmat a)\<otimes>(blockmat ls)" using blockmat.simps by auto moreover have "rat_poly.row_length (blockmat (a#ls)) = (rat_poly.row_length (brickmat a)) *(rat_poly.row_length (blockmat ls))" using calculation rat_poly.row_length_mat by (metis) moreover have "length (blockmat (a#ls)) = (length (brickmat a)) *(length (blockmat ls))" using blockmat.simps(2) rat_poly.length_Tensor by (metis) ultimately have Cons_3:"mat (rat_poly.row_length (brickmat a)) (length (brickmat a)) (brickmat a) \<Longrightarrow> ?case" using rat_poly.well_defined_Tensor Cons by auto then show ?case proof(cases a) case vert have "mat (rat_poly.row_length (brickmat a)) (length (brickmat a)) (brickmat a)" using vert_dim mat_vert rat_poly.matrix_row_length vert by metis thus ?thesis using Cons_3 by auto next case over have "mat (rat_poly.row_length (brickmat a)) (length (brickmat a)) (brickmat a)" using mat_over rat_poly.matrix_row_length over by metis thus ?thesis using Cons_3 by auto next case under have "mat (rat_poly.row_length (brickmat a)) (length (brickmat a)) (brickmat a)" using mat_under rat_poly.matrix_row_length under by metis thus ?thesis using Cons_3 by auto next case cap have "mat (rat_poly.row_length (brickmat a)) (length (brickmat a)) (brickmat a)" using mat_cap rat_poly.matrix_row_length cap by metis thus ?thesis using Cons_3 by auto next case cup have "mat (rat_poly.row_length (brickmat a)) (length (brickmat a)) (brickmat a)" using mat_cup rat_poly.matrix_row_length cup by metis thus ?thesis using Cons_3 by auto qed qed text\<open>The function kauff$\_$mat below associates every wall to a matrix. We call this the kauffman matrix. When the wall represents a well defined tangle diagram, the Kauffman matrix is a 1 $\times$ 1 matrix whose entry is the Kauffman bracket.\<close> primrec kauff_mat::"wall \<Rightarrow> rat_poly mat" where "kauff_mat (basic w) = (blockmat w)" |"kauff_mat (w*ws) = rat_poly.matrix_mult (blockmat w) (kauff_mat ws)" text\<open>The following theorem tells us that if a wall represents a tangle diagram, then its Kauffman matrix is a `valid' matrix.\<close> theorem matrix_kauff_mat: "((is_tangle_diagram ws) \<Longrightarrow> (rat_poly.row_length (kauff_mat ws)) = 2^(nat (domain_wall ws)) \<and> (length (kauff_mat ws)) = 2^(nat (codomain_wall ws)) \<and> (mat (rat_poly.row_length (kauff_mat ws)) (length (kauff_mat ws)) (kauff_mat ws)))" proof(induct ws) case (basic w) show ?case using kauff_mat.simps(1) domain_wall.simps(1) row_length_domain_block matrix_blockmat length_codomain_block basic by auto next case (prod w ws) have "is_tangle_diagram (w*ws)" using prod by auto moreover have prod_1:"is_tangle_diagram ws" using is_tangle_diagram.simps prod.prems by metis ultimately have prod_2:"(codomain_block w) = domain_wall ws" using is_tangle_diagram.simps by auto from prod_1 have prod_3: "mat (rat_poly.row_length (kauff_mat ws)) (length (kauff_mat ws)) (kauff_mat ws)" using prod.hyps by auto moreover have "(rat_poly.row_length (kauff_mat ws)) = 2^(nat (domain_wall ws))" using prod.hyps prod_1 by auto moreover have prod_4:"length (kauff_mat ws) = 2^(nat (codomain_wall ws))" using prod.hyps prod_1 by auto moreover have prod_5: "mat (rat_poly.row_length (blockmat w)) (length (blockmat w)) (blockmat w)" using matrix_blockmat by auto moreover have prod_6: "rat_poly.row_length (blockmat w) = 2^(nat (domain_block w))" and "length (blockmat w) = 2^(nat (codomain_block w))" using row_length_domain_block length_codomain_block by auto ultimately have ad1:"length (blockmat w) = rat_poly.row_length (kauff_mat ws)" using prod_2 by auto then have "mat (rat_poly.row_length (blockmat w)) (length (kauff_mat ws)) (rat_poly.matrix_mult (blockmat w) (kauff_mat ws))" using prod_3 prod_5 mat_mult by auto then have res1:"mat (rat_poly.row_length (blockmat w)) (length (kauff_mat ws)) (kauff_mat (w*ws))" using kauff_mat.simps(2) by auto then have "rat_poly.row_length (kauff_mat (w*ws)) = (rat_poly.row_length (blockmat w))" using ad1 length_0_conv rat_poly.mat_empty_column_length rat_poly.matrix_row_length rat_poly.row_length_def rat_poly.unique_row_col(1) by (metis) moreover have "... = 2^(nat (domain_wall (w*ws)))" using prod_6 domain_wall.simps by auto ultimately have res2: "rat_poly.row_length (kauff_mat (w*ws)) = 2^(nat (domain_wall (w*ws)))" by auto have "length (kauff_mat (w*ws)) = length (kauff_mat ws)" using res1 rat_poly.mat_empty_column_length rat_poly.matrix_row_length rat_poly.unique_row_col(2) by metis moreover have "... = 2^(nat (codomain_wall (w*ws)))" using prod_4 codomain_wall.simps(2) by auto ultimately have res3:"length (kauff_mat (w*ws)) = 2^(nat (codomain_wall (w*ws)))" by auto with res1 res2 show ?case using \<open>length (kauff_mat ws) = 2 ^ nat (codomain_wall (w * ws))\<close> \<open>rat_poly.row_length (blockmat w) = 2 ^ nat (domain_wall (w * ws))\<close> by (metis) qed theorem effective_matrix_kauff_mat: assumes "is_tangle_diagram ws" shows "(rat_poly.row_length (kauff_mat ws)) = 2^(nat (domain_wall ws))" and "length (kauff_mat ws) = 2^(nat (codomain_wall ws))" and "mat (rat_poly.row_length (kauff_mat ws)) (length (kauff_mat ws)) (kauff_mat ws) " apply (auto simp add:matrix_kauff_mat assms ) using assms matrix_kauff_mat by metis lemma mat_mult_equiv: "rat_poly.matrix_mult m1 m2 = mat_mult (rat_poly.row_length m1) m1 m2" by auto theorem associative_rat_poly_mat: assumes "mat (rat_poly.row_length m1) (rat_poly.row_length m2) m1" and "mat (rat_poly.row_length m2) (rat_poly.row_length m3) m2" and "mat (rat_poly.row_length m3) nc m3" shows "rat_poly.matrix_mult m1 (rat_poly.matrix_mult m2 m3) = rat_poly.matrix_mult (rat_poly.matrix_mult m1 m2) m3" proof- have "(rat_poly.matrix_mult m2 m3) = mat_mult (rat_poly.row_length m2) m2 m3" using mat_mult_equiv by auto then have "rat_poly.matrix_mult m1 (rat_poly.matrix_mult m2 m3) = mat_mult (rat_poly.row_length m1) m1 (mat_mult (rat_poly.row_length m2) m2 m3)" using mat_mult_equiv by auto moreover have "... = mat_mult (rat_poly.row_length m1) (mat_mult (rat_poly.row_length m1) m1 m2) m3" using assms mat_mult_assoc by metis moreover have "... = rat_poly.matrix_mult (rat_poly.matrix_mult m1 m2) m3" proof- have "mat (rat_poly.row_length m1) (rat_poly.row_length m3) (rat_poly.matrix_mult m1 m2)" using assms(1) assms(2) mat_mult by (metis) then have "rat_poly.row_length (rat_poly.matrix_mult m1 m2) = (rat_poly.row_length m1)" using assms(1) assms(2) length_0_conv rat_poly.mat_empty_column_length rat_poly.matrix_row_length rat_poly.row_length_Nil rat_poly.unique_row_col(1) rat_poly.unique_row_col(2) by (metis) moreover have "rat_poly.matrix_mult (rat_poly.matrix_mult m1 m2) m3 = mat_mult (rat_poly.row_length (rat_poly.matrix_mult m1 m2)) (rat_poly.matrix_mult m1 m2) m3" using mat_mult_equiv by auto then show ?thesis using mat_mult_equiv by (metis calculation) qed ultimately show ?thesis by auto qed text\<open>It follows from this result that the Kauffman Matrix of a wall representing a link diagram, is a 1 $\times$ 1 matrix. Thus it establishes a correspondence between links and rational functions.\<close> theorem link_diagram_matrix: assumes "is_link_diagram ws" shows "mat 1 1 (kauff_mat ws) " using assms effective_matrix_kauff_mat unfolding is_link_diagram_def by (metis Preliminaries.abs_zero abs_non_negative_sum(1) comm_monoid_add_class.add_0 nat_0 power_0) theorem tangle_compose_matrix: "((is_tangle_diagram ws1) \<and> (is_tangle_diagram ws2) \<and>(domain_wall ws2 = codomain_wall ws1)) \<Longrightarrow> kauff_mat (ws1 \<circ> ws2) = rat_poly.matrix_mult (kauff_mat ws1) (kauff_mat ws2)" proof(induct ws1) case (basic w1) have "(basic w1) \<circ> (ws2) = (w1)*(ws2)" using compose.simps by auto moreover have "kauff_mat ((basic w1) \<circ> ws2) =rat_poly.matrix_mult (blockmat w1) (kauff_mat ws2)" using kauff_mat.simps(2) by auto then show ?case using kauff_mat.simps(1) by auto next case (prod w1 ws1) have 1:"is_tangle_diagram (w1*ws1)" using prod.prems by (rule conjE) then have 2:"(is_tangle_diagram ws1) \<and> (codomain_block w1 = domain_wall ws1)" using is_tangle_diagram.simps(2) by metis then have "mat (2^(nat (domain_wall ws1))) (2^(nat (codomain_wall ws1))) (kauff_mat ws1)" and "mat (2^(nat (domain_block w1))) (2^(nat (codomain_block w1))) (blockmat w1)" using effective_matrix_kauff_mat matrix_blockmat length_codomain_block row_length_domain_block by (auto) (metis) with 2 have 3:"mat (rat_poly.row_length (blockmat w1)) (2^(nat (domain_wall ws1))) (blockmat w1)" and "mat (2^(nat (domain_wall ws1))) (2^(nat (domain_wall ws2))) (kauff_mat ws1)" and "(2^(nat (domain_wall ws1))) = (rat_poly.row_length (kauff_mat ws1))" using effective_matrix_kauff_mat prod.prems matrix_blockmat row_length_domain_block by auto then have "mat (rat_poly.row_length (blockmat w1)) (rat_poly.row_length (kauff_mat ws1)) (blockmat w1)" and "mat (rat_poly.row_length (kauff_mat ws1)) (2^(nat (domain_wall ws2))) (kauff_mat ws1)" by auto moreover have "mat (2^(nat (domain_wall ws2))) (2^(nat (codomain_wall ws2))) (kauff_mat ws2)" and "(2^(nat (domain_wall ws2))) = rat_poly.row_length (kauff_mat ws2)" using prod.prems effective_matrix_kauff_mat effective_matrix_kauff_mat by (auto) (metis prod.prems) ultimately have "mat (rat_poly.row_length (blockmat w1)) (rat_poly.row_length (kauff_mat ws1)) (blockmat w1)" and "mat (rat_poly.row_length (kauff_mat ws1)) (rat_poly.row_length (kauff_mat ws2)) (kauff_mat ws1)" and "mat (rat_poly.row_length (kauff_mat ws2)) (2^(nat (codomain_wall ws2))) (kauff_mat ws2)" by auto with 3 have "rat_poly.matrix_mult (blockmat w1) (rat_poly.matrix_mult (kauff_mat ws1) (kauff_mat ws2)) = rat_poly.matrix_mult (rat_poly.matrix_mult (blockmat w1) (kauff_mat ws1)) (kauff_mat ws2)" using associative_rat_poly_mat by auto then show ?case using "2" codomain_wall.simps(2) compose_Cons prod.hyps prod.prems kauff_mat.simps(2) by (metis) qed theorem left_mat_compose: assumes "is_tangle_diagram ws" and "codomain_wall ws = 0" shows "kauff_mat ws = (kauff_mat (ws \<circ> (basic [])))" proof- have "mat (rat_poly.row_length (kauff_mat ws)) 1 (kauff_mat ws)" using effective_matrix_kauff_mat assms nat_0 power_0 by metis moreover have "(kauff_mat (basic [])) = mat1 1" using kauff_mat.simps(1) blockmat.simps(1) mat1_equiv by auto moreover then have 1:"(kauff_mat (ws \<circ> (basic []))) = rat_poly.matrix_mult (kauff_mat ws) (kauff_mat (basic []))" using tangle_compose_matrix assms is_tangle_diagram.simps by auto ultimately have "rat_poly.matrix_mult (kauff_mat ws) (kauff_mat (basic [])) = (kauff_mat ws)" using mat_mult_equiv mat1_mult_right by auto then show ?thesis using 1 by auto qed theorem right_mat_compose: assumes "is_tangle_diagram ws" and "domain_wall ws = 0" shows "kauff_mat ws = (kauff_mat ((basic []) \<circ>ws))" proof- have "mat 1 (length (kauff_mat ws)) (kauff_mat ws)" using effective_matrix_kauff_mat assms nat_0 power_0 by metis moreover have "(kauff_mat (basic [])) = mat1 1" using kauff_mat.simps(1) blockmat.simps(1) mat1_equiv by auto moreover then have 1:"(kauff_mat ((basic []) \<circ>ws)) = rat_poly.matrix_mult (kauff_mat (basic [])) (kauff_mat ws) " using tangle_compose_matrix assms is_tangle_diagram.simps by auto ultimately have "rat_poly.matrix_mult (kauff_mat (basic [])) (kauff_mat ws) = (kauff_mat ws)" using effective_matrix_kauff_mat(3) is_tangle_diagram.simps(1) mat1 mat1_mult_left one_neq_zero rat_poly.mat_empty_column_length rat_poly.unique_row_col(1) by metis then show ?thesis using 1 by auto qed lemma left_id_blockmat:"blockmat [] \<otimes> blockmat b = blockmat b" unfolding blockmat.simps(1) rat_poly.Tensor_left_id by auto lemma tens_assoc: "\<forall>a xs ys.(brickmat a \<otimes> (blockmat xs \<otimes> blockmat ys) = (brickmat a \<otimes> blockmat xs) \<otimes> blockmat ys)" proof- have "\<forall>a.(mat (rat_poly.row_length (brickmat a)) (length (brickmat a)) (brickmat a))" using brickmat.simps unfolding mat_def rat_poly.row_length_def Ball_def vec_def apply(auto) by (case_tac a) (auto) moreover have "\<forall>xs. (mat (rat_poly.row_length (blockmat xs)) (length (blockmat xs)) (blockmat xs))" using matrix_blockmat by auto moreover have "\<forall>ys. mat (rat_poly.row_length (blockmat ys)) (length (blockmat ys)) (blockmat ys)" using matrix_blockmat by auto ultimately show ?thesis using rat_poly.associativity by auto qed lemma kauff_mat_tensor_distrib: "\<forall>xs.\<forall>ys.(kauff_mat (basic xs \<otimes> basic ys) = kauff_mat (basic xs) \<otimes> kauff_mat (basic ys))" apply(rule allI) apply (rule allI) apply (induct_tac xs) apply(auto) apply (metis rat_poly.vec_mat_Tensor_vector_id) apply (simp add:tens_assoc) done lemma blockmat_tensor_distrib: "(blockmat (a \<otimes> b)) = (blockmat a) \<otimes> (blockmat b)" proof- have "blockmat (a \<otimes> b) = kauff_mat (basic (a \<otimes> b))" using kauff_mat.simps(1) by auto moreover have "... = kauff_mat (basic a) \<otimes> kauff_mat (basic b)" using kauff_mat_tensor_distrib by auto moreover have "... = (blockmat a) \<otimes> (blockmat b)" using kauff_mat.simps(1) by auto ultimately show ?thesis by auto qed lemma blockmat_non_empty:"\<forall>bs.(blockmat bs \<noteq> [])" apply(rule allI) apply(induct_tac bs) apply(auto) apply(case_tac a) apply(auto) apply (metis length_0_conv rat_poly.vec_mat_Tensor_length) apply (metis length_0_conv rat_poly.vec_mat_Tensor_length) apply (metis length_0_conv rat_poly.vec_mat_Tensor_length) apply (metis length_0_conv rat_poly.vec_mat_Tensor_length) apply (metis length_0_conv rat_poly.vec_mat_Tensor_length) done text\<open>The kauffman matrix of a wall representing a tangle diagram is non empty\<close> lemma kauff_mat_non_empty: fixes ws assumes "is_tangle_diagram ws" shows "kauff_mat ws \<noteq> []" proof- have "(length (kauff_mat ws) = 2^(nat (codomain_wall ws)))" using effective_matrix_kauff_mat assms by auto then have "(length (kauff_mat ws)) \<ge> 1" by auto then show ?thesis by auto qed lemma is_tangle_diagram_length_rowlength: assumes "is_tangle_diagram (w*ws)" shows "length (blockmat w) = rat_poly.row_length (kauff_mat ws)" proof- have "(codomain_block w = domain_wall ws)" using assms is_tangle_diagram.simps by metis moreover have "rat_poly.row_length (kauff_mat ws) = 2^(nat (domain_wall ws))" using effective_matrix_kauff_mat by (metis assms is_tangle_diagram.simps(2)) moreover have "length (blockmat w) = 2^(nat (codomain_block w))" using matrix_blockmat length_codomain_block by auto ultimately show ?thesis by auto qed lemma is_tangle_diagram_matrix_match: assumes "is_tangle_diagram (w1*ws1)" and "is_tangle_diagram (w2*ws2)" shows "rat_poly.matrix_match (blockmat w1) (kauff_mat ws1) (blockmat w2) (kauff_mat ws2)" unfolding rat_poly.matrix_match_def apply(auto) proof- show "mat (rat_poly.row_length (blockmat w1)) (length (blockmat w1)) (blockmat w1)" using matrix_blockmat by auto next have "is_tangle_diagram ws1" using assms(1) is_tangle_diagram.simps(2) by metis then show "mat (rat_poly.row_length (kauff_mat ws1)) (length (kauff_mat ws1)) (kauff_mat ws1)" using matrix_kauff_mat by metis next show "mat (rat_poly.row_length (blockmat w2)) (length (blockmat w2)) (blockmat w2)" using matrix_blockmat by auto next have "is_tangle_diagram ws2" using assms(2) is_tangle_diagram.simps(2) by metis then show "mat (rat_poly.row_length (kauff_mat ws2)) (length (kauff_mat ws2)) (kauff_mat ws2)" using matrix_kauff_mat by metis next show "length (blockmat w1) = rat_poly.row_length (kauff_mat ws1)" using is_tangle_diagram_length_rowlength assms(1) by auto next show "length (blockmat w2) = rat_poly.row_length (kauff_mat ws2)" using is_tangle_diagram_length_rowlength assms(2) by auto next assume 0:"blockmat w1 = [] " show False using 0 by (metis blockmat_non_empty) next assume 1:"kauff_mat ws1 = [] " have "is_tangle_diagram ws1" using assms(1) is_tangle_diagram.simps(2) by metis then show False using 1 kauff_mat_non_empty by auto next assume 0:"blockmat w2 = [] " show False using 0 by (metis blockmat_non_empty) next assume 1:"kauff_mat ws2 = [] " have "is_tangle_diagram ws2" using assms(2) is_tangle_diagram.simps(2) by metis then show False using 1 kauff_mat_non_empty by auto qed text\<open>The following function constructs a $2^n \times 2^n$ identity matrix for a given $n$\<close> primrec make_vert_equiv::"nat \<Rightarrow> rat_poly mat" where "make_vert_equiv 0 = [[1]]" |"make_vert_equiv (Suc k) = ((mat1 2)\<otimes>(make_vert_equiv k))" lemma mve1:"make_vert_equiv 1 = (mat1 2)" using make_vert_equiv.simps brickmat.simps(1) One_nat_def rat_poly.Tensor_right_id by (metis) lemma assumes "i<2" and "j<2" shows "(make_vert_equiv 1)!i!j = (if i = j then 1 else 0)" apply(simp add:mve1) apply(simp add:rat_poly.Tensor_right_id) using make_vert_equiv.simps mat1_index assms by (metis) lemma mat1_vert_equiv:"(mat1 2) = (brickmat vert)" (is "?l = ?r") proof- have "?r = [[1,0],[0,1]]" using brickmat.simps by auto then have "rat_poly.row_length ?r = 2" and "length ?r = 2" using rat_poly.row_length_def by auto moreover then have 1:"mat 2 2 ?r" using mat_vert by metis ultimately have 2:"(\<forall> i < 2. \<forall> j < 2. ((?r) ! i ! j = (if i = j then 1 else 0)))" proof- have 1:"(?r ! 0! 0) = 1" by auto moreover have 2:"(?r ! 0! 1) = 0" by auto moreover have 3:"(?r ! 1! 0) = 0" by auto moreover have 5:"(?r ! 1! 1) = 1" by auto ultimately show ?thesis by (auto dest!: less_2_cases) qed have 3:"mat 2 2 (mat1 2)" by (metis mat1) have 4:"(\<forall> i < 2. \<forall> j < 2. ((?l) ! i ! j = (if i = j then 1 else 0)))" by (metis mat1_index) then have "(\<forall> i < 2. \<forall> j < 2. ((?l) ! i ! j = (?r !i !j)))" using 2 by auto with 1 3 have "?l = ?r" by (metis mat_eqI) then show ?thesis by auto qed lemma blockmat_make_vert: "blockmat (make_vert_block n) = (make_vert_equiv n)" apply(induction n) apply(simp) unfolding make_vert_block.simps blockmat.simps make_vert_equiv.simps using mat1_vert_equiv by auto lemma prop_make_vert_equiv: shows "rat_poly.row_length (make_vert_equiv n) = 2^n" and "length (make_vert_equiv n) = 2^n" and "mat (rat_poly.row_length (make_vert_equiv n)) (length (make_vert_equiv n)) (make_vert_equiv n)" proof- have 1:"make_vert_equiv n = (blockmat (make_vert_block n))" using blockmat_make_vert by auto moreover have 2:"domain_block (make_vert_block n) = int n" using domain_make_vert by auto moreover have 3:"codomain_block (make_vert_block n) = int n" using codomain_make_vert by auto ultimately show "rat_poly.row_length (make_vert_equiv n) = 2^n" and "length (make_vert_equiv n) = 2^n" and "mat (rat_poly.row_length (make_vert_equiv n)) (length (make_vert_equiv n)) (make_vert_equiv n)" apply (metis nat_int row_length_domain_block) using 1 2 3 apply (metis length_codomain_block nat_int) using 1 2 3 by (metis matrix_blockmat) qed abbreviation nat_mult::"nat \<Rightarrow> nat \<Rightarrow> nat" (infixl "*n" 65) where "nat_mult a b \<equiv> ((a::nat)*b)" lemma equal_div_mod:assumes "((j::nat) div a) = (i div a)" and "(j mod a) = (i mod a)" shows "j = i" proof- have "j = a*(j div a) + (j mod a)" by auto then have "j = a*(i div a) + (i mod a)" using assms by auto then show ?thesis by auto qed lemma equal_div_mod2:"(((j::nat) div a) = (i div a) \<and> ((j mod a) = (i mod a))) = (j = i)" using equal_div_mod by metis lemma impl_rule: assumes "(\<forall>i < m.\<forall>j < n. (P i) \<and> (Q j))" and "\<forall> i j.(P i) \<and> (Q j) \<longrightarrow> R i j" shows "(\<forall>i < m.\<forall>j < n. R i j)" using assms by metis lemma implic: assumes "\<forall>i j.((P i j) \<longrightarrow> (Q i j))" and "\<forall>i j.((Q i j) \<longrightarrow> (R i j))" shows "\<forall>i j.((P i j) \<longrightarrow> (R i j))" using assms by auto lemma assumes "a < (b*c)" shows "((a::nat) div b) < c" using assms by (metis rat_poly.div_right_ineq) lemma mult_if_then:"((v = (if P then 1 else 0)) \<and> (w = (if Q then 1 else 0))) \<Longrightarrow> (rat_poly_times v w = (if (P\<and>Q) then 1 else 0))" by auto lemma rat_poly_unity:"rat_poly_times 1 1 = 1" by auto lemma "((P \<and> Q) \<longrightarrow> R) \<Longrightarrow> (P \<longrightarrow> Q \<longrightarrow> R)" by auto lemma "length (mat1 2) = 2" apply(simp add:mat1I_def) done theorem make_vert_equiv_mat: "make_vert_equiv n = (mat1 (2^n))" proof(induction n) case 0 show ?case using 0 mat1_equiv by auto next case (Suc k) have 1:"make_vert_equiv k = mat1 (2 ^ k)" using Suc by auto moreover then have "make_vert_equiv (k+1) = (mat1 2)\<otimes>(mat1 (2^k))" using make_vert_equiv.simps(2) by auto then have "(mat1 2) \<otimes> (mat1 (2^k)) = mat1 (2^(k+1))" proof- have 1:"mat (2^(k+1)) (2^(k+1)) (mat1 (2^(k+1)))" using mat1 by auto have 2:"(\<forall> i < 2^(k+1). \<forall> j <2^(k+1). (mat1 (2^(k+1)) ! i ! j = (if i = j then 1 else 0)))" by (metis mat1_index) have 3:"rat_poly.row_length (mat1 2) = 2" by (metis mat1_vert_equiv vert_dim) have 4:"length (mat1 2) = 2" by (simp add:mat1I_def) then have 5:"mat (rat_poly.row_length (mat1 2)) (length (mat1 2)) (mat1 2)" by (metis "4" mat1 mat1_vert_equiv vert_dim) moreover have 6:"rat_poly.row_length (mat1 (2^k)) = 2^k" and 7:"length ((mat1 (2^k))) = 2^k" using Suc by (metis prop_make_vert_equiv(1)) (simp add:mat1I_def) then have 8:"mat (rat_poly.row_length (mat1 (2^k))) (length (mat1 (2^k))) (mat1 (2^k))" using Suc mat1 by (metis) then have 9: "(\<forall>i <(2^(k+1)). \<forall>j < (2^(k+1)). ((rat_poly.Tensor (mat1 2) (mat1 (2^k))!j!i) = rat_poly_times ((mat1 2)!(j div (length (mat1 (2^k)))) !(i div (rat_poly.row_length (mat1 (2^k))))) ((mat1 (2^k))!(j mod length (mat1 (2^k))) !(i mod (rat_poly.row_length (mat1 (2^k)))))))" proof- have "(\<forall>i <((rat_poly.row_length (mat1 2)) *n (rat_poly.row_length (mat1 (2^k)))). \<forall>j < ((length (mat1 2)) *n (length (mat1 (2^k)))). ((rat_poly.Tensor (mat1 2) (mat1 (2^k))!j!i) = rat_poly_times ((mat1 2)!(j div (length (mat1 (2^k)))) !(i div (rat_poly.row_length (mat1 (2^k))))) ((mat1 (2^k))!(j mod length (mat1 (2^k))) !(i mod (rat_poly.row_length (mat1 (2^k)))))))" using 5 8 rat_poly.effective_matrix_Tensor_elements2 by (metis "3" "4" "6" "7" rat_poly.comm) moreover have "(rat_poly.row_length (mat1 2)) *n(rat_poly.row_length (mat1 (2^k))) = 2^(k+1)" using 3 6 by auto moreover have "(length (mat1 2)) *n(length (mat1 (2^k))) = 2^(k+1)" using 4 7 by (metis "3" "6" calculation(2)) ultimately show ?thesis by metis qed have 10:"\<forall>i j.((i div (rat_poly.row_length (mat1 (2^k))) < 2) \<and>(j div length (mat1 (2^k)) < 2) \<longrightarrow> (((mat1 2)!(j div (length (mat1 (2^k)))) !(i div (rat_poly.row_length (mat1 (2^k))))) = (if ((j div (length (mat1 (2^k)))) = (i div (rat_poly.row_length (mat1 (2^k))))) then 1 else 0)))" using mat1_index by (metis "6" "7") have 11:"\<forall>j.(j < (2^(k+1)) \<longrightarrow> j div (length (mat1 (2^k))) < 2)" proof- have "2^(k+1) = (2 *n (2^k))" by auto then show ?thesis using 7 allI Suc.IH prop_make_vert_equiv(1) rat_poly.div_left_ineq by (metis) qed moreover have 12: "\<forall>i.(i < (2^(k+1)) \<longrightarrow> (i div (rat_poly.row_length (mat1 (2^k)))) < 2)" proof- have "2^(k+1) = (2 *n (2^k))" by auto then show ?thesis using 7 allI by (metis Suc.IH prop_make_vert_equiv(1) rat_poly.div_left_ineq) qed ultimately have 13: "\<forall>i j.((i < (2^(k+1)))\<and> j < (2^(k+1)) \<longrightarrow> ((i div (rat_poly.row_length (mat1 (2^k)))) < 2) \<and>((j div (length (mat1 (2^k)))) < 2))" by auto have 14:"\<forall>i j.(i < (2^(k+1)))\<and> (j < (2^(k+1))) \<longrightarrow> (((mat1 2) !(j div (length (mat1 (2^k)))) !(i div (rat_poly.row_length (mat1 (2^k))))) = (if ((j div (length (mat1 (2^k)))) = (i div (rat_poly.row_length (mat1 (2^k))))) then 1 else 0))" apply(rule allI) apply(rule allI) proof fix i j assume 0:"(i::nat) < 2 ^ (k + 1) \<and> (j::nat) < 2 ^ (k + 1)" have "((i div (rat_poly.row_length (mat1 (2^k)))) < 2) \<and>((j div (length (mat1 (2^k)))) < 2)" using 0 13 by auto then show "(((mat1 2) !(j div (length (mat1 (2^k)))) !(i div (rat_poly.row_length (mat1 (2^k))))) = (if ((j div (length (mat1 (2^k)))) = (i div (rat_poly.row_length (mat1 (2^k))))) then 1 else 0))" using 10 by (metis "6") qed have 15:"\<forall>i j.((i mod (rat_poly.row_length (mat1 (2^k))) < 2^k) \<and> (j mod length (mat1 (2^k)) < 2^k) \<longrightarrow> (((mat1 (2^k)) !(j mod (length (mat1 (2^k)))) !(i mod (rat_poly.row_length (mat1 (2^k))))) = (if ((j mod (length (mat1 (2^k)))) = (i mod (rat_poly.row_length (mat1 (2^k))))) then 1 else 0)))" using mat1_index by (metis "6" "7") have 16:"\<forall>j.(j < (2^(k+1)) \<longrightarrow> j mod (length (mat1 (2^k))) < 2^k)" proof- have "2^(k+1) = (2 *n (2^k))" by auto then show ?thesis using 7 allI mod_less_divisor nat_zero_less_power_iff zero_less_numeral by (metis) qed moreover have 17:"\<forall>i.(i < (2^(k+1)) \<longrightarrow> (i mod (rat_poly.row_length (mat1 (2^k)))) < 2^k)" proof- have "2^(k+1) = (2 *n (2^k))" by auto then show ?thesis using 7 allI by (metis "6" calculation) qed ultimately have 18: "\<forall>i j.((i < (2^(k+1)))\<and> j < (2^(k+1)) \<longrightarrow> ((i mod (rat_poly.row_length (mat1 (2^k)))) < 2^k) \<and>((j mod (length (mat1 (2^k)))) < 2^k))" by (metis "7") have 19:"\<forall>i j.(i < (2^(k+1)))\<and> (j < (2^(k+1))) \<longrightarrow> (((mat1 (2^k)) !(j mod (length (mat1 (2^k)))) !(i mod (rat_poly.row_length (mat1 (2^k))))) = (if ((j mod (length (mat1 (2^k)))) = (i mod (rat_poly.row_length (mat1 (2^k))))) then 1 else 0))" apply(rule allI) apply(rule allI) proof fix i j assume 0:"(i::nat) < 2 ^ (k + 1) \<and> (j::nat) < 2 ^ (k + 1)" have "((i mod (rat_poly.row_length (mat1 (2^k)))) < 2^k) \<and>((j mod (length (mat1 (2^k)))) < 2^k)" using 0 18 by auto then show "(((mat1 (2^k)) !(j mod (length (mat1 (2^k)))) !(i mod(rat_poly.row_length (mat1 (2^k))))) = (if ((j mod (length (mat1 (2^k)))) = (i mod (rat_poly.row_length (mat1 (2^k))))) then 1 else 0))" using 15 by (metis "6") qed have "(\<forall>i. \<forall>j. (i <(2^(k+1))) \<and> (j < (2^(k+1))) \<longrightarrow> rat_poly_times ((mat1 2) !(j div (length (mat1 (2^k)))) !(i div (rat_poly.row_length (mat1 (2^k))))) ((mat1 (2^k)) !(j mod length (mat1 (2^k))) !(i mod (rat_poly.row_length (mat1 (2^k))))) = (if (((j div (length (mat1 (2^k)))) = (i div (rat_poly.row_length (mat1 (2^k))))) \<and>((j mod (length (mat1 (2^k)))) = (i mod (rat_poly.row_length (mat1 (2^k)))))) then 1 else 0))" apply(rule allI) apply(rule allI) proof fix i j assume 0: "((i::nat) <(2^(k+1))) \<and> ((j::nat) < (2^(k+1)))" have s1: "((mat1 2) !(j div (length (mat1 (2^k)))) !(i div (rat_poly.row_length (mat1 (2^k))))) = (if ((j div (length (mat1 (2^k)))) = (i div (rat_poly.row_length (mat1 (2^k))))) then 1 else 0)" using 0 14 by metis moreover have s2:"((mat1 (2^k)) !(j mod (length (mat1 (2^k)))) !(i mod (rat_poly.row_length (mat1 (2^k))))) = (if ((j mod (length (mat1 (2^k)))) = (i mod (rat_poly.row_length (mat1 (2^k))))) then 1 else 0)" using 0 19 by metis show "rat_poly_times ((mat1 2) !(j div (length (mat1 (2^k)))) !(i div (rat_poly.row_length (mat1 (2^k))))) ((mat1 (2^k)) !(j mod length (mat1 (2^k))) !(i mod (rat_poly.row_length (mat1 (2^k))))) = (if (((j div (length (mat1 (2^k)))) = (i div (rat_poly.row_length (mat1 (2^k))))) \<and>((j mod (length (mat1 (2^k)))) = (i mod (rat_poly.row_length (mat1 (2^k)))))) then 1 else 0)" apply(simp) apply(rule conjI) proof- show "j div length (mat1 (2 ^ k)) = i div rat_poly.row_length (mat1 (2 ^ k)) \<and> (j mod length (mat1 (2 ^ k)) = i mod rat_poly.row_length (mat1 (2 ^ k))) \<longrightarrow> rat_poly_times (mat1 2 !(j div length (mat1 (2 ^ k))) !(i div rat_poly.row_length (mat1 (2 ^ k)))) (mat1 (2 ^ k) !(j mod length (mat1 (2 ^ k))) !(i mod rat_poly.row_length (mat1 (2 ^ k)))) = 1" proof- have "j div length (mat1 (2 ^ k)) = i div rat_poly.row_length (mat1 (2 ^ k)) \<and> j mod length (mat1 (2 ^ k)) = i mod rat_poly.row_length (mat1 (2 ^ k)) \<Longrightarrow> rat_poly_times (mat1 2 ! (j div length (mat1 (2 ^ k))) ! (i div rat_poly.row_length (mat1 (2 ^ k)))) (mat1 (2 ^ k) ! (j mod length (mat1 (2 ^ k))) ! (i mod rat_poly.row_length (mat1 (2 ^ k)))) = 1" proof- assume local_assms: "j div length (mat1 (2 ^ k)) = i div rat_poly.row_length (mat1 (2 ^ k)) \<and> j mod length (mat1 (2 ^ k)) = i mod rat_poly.row_length (mat1 (2 ^ k)) " have "(mat1 2 ! (j div length (mat1 (2 ^ k))) ! (i div rat_poly.row_length (mat1 (2 ^ k)))) = 1" using s1 local_assms by metis moreover have "(mat1 (2 ^ k) ! (j mod length (mat1 (2 ^ k))) ! (i mod rat_poly.row_length (mat1 (2 ^ k)))) = 1" using s2 local_assms by metis ultimately show ?thesis by (metis "3" "6" "7" Suc.IH local_assms mve1 prop_make_vert_equiv(1) prop_make_vert_equiv(2) rat_poly.right_id) qed then show ?thesis by auto qed show "(j div length (mat1 (2 ^ k)) = i div rat_poly.row_length (mat1 (2 ^ k)) \<longrightarrow> j mod length (mat1 (2 ^ k)) \<noteq> i mod rat_poly.row_length (mat1 (2 ^ k))) \<longrightarrow> mat1 2 ! (j div length (mat1 (2 ^ k))) ! (i div rat_poly.row_length (mat1 (2 ^ k))) = 0 \<or> mat1 (2 ^ k) ! (j mod length (mat1 (2 ^ k))) ! (i mod rat_poly.row_length (mat1 (2 ^ k))) = 0" proof- have "(j div length (mat1 (2 ^ k)) = i div rat_poly.row_length (mat1 (2 ^ k)) \<and> j mod length (mat1 (2 ^ k)) \<noteq> i mod rat_poly.row_length (mat1 (2 ^ k))) \<Longrightarrow> mat1 2 ! (j div length (mat1 (2 ^ k))) ! (i div rat_poly.row_length (mat1 (2 ^ k))) = 0 \<or> mat1 (2 ^ k) ! (j mod length (mat1 (2 ^ k))) ! (i mod rat_poly.row_length (mat1 (2 ^ k))) = 0" proof- assume local_assms: "(j div length (mat1 (2 ^ k)) = i div rat_poly.row_length (mat1 (2 ^ k)) \<and> j mod length (mat1 (2 ^ k)) \<noteq> i mod rat_poly.row_length (mat1 (2 ^ k)))" have "mat1 (2 ^ k) ! (j mod length (mat1 (2 ^ k))) ! (i mod rat_poly.row_length (mat1 (2 ^ k))) = 0" using s2 local_assms by metis then show ?thesis by auto qed then have l: "(j div length (mat1 (2 ^ k)) = i div rat_poly.row_length (mat1 (2 ^ k)) \<and> j mod length (mat1 (2 ^ k)) \<noteq> i mod rat_poly.row_length (mat1 (2 ^ k))) \<longrightarrow> mat1 2 ! (j div length (mat1 (2 ^ k))) ! (i div rat_poly.row_length (mat1 (2 ^ k))) = 0 \<or>mat1 (2 ^ k) ! (j mod length (mat1 (2 ^ k))) ! (i mod rat_poly.row_length (mat1 (2 ^ k))) = 0" by auto show "(j div length (mat1 (2 ^ k)) = i div rat_poly.row_length (mat1 (2 ^ k)) \<longrightarrow> j mod length (mat1 (2 ^ k)) \<noteq> i mod rat_poly.row_length (mat1 (2 ^ k))) \<longrightarrow> mat1 2 ! (j div length (mat1 (2 ^ k))) ! (i div rat_poly.row_length (mat1 (2 ^ k))) = 0 \<or> mat1 (2 ^ k) ! (j mod length (mat1 (2 ^ k))) ! (i mod rat_poly.row_length (mat1 (2 ^ k))) = 0" proof- have "(j div length (mat1 (2 ^ k)) = i div rat_poly.row_length (mat1 (2 ^ k)) \<longrightarrow> j mod length (mat1 (2 ^ k)) \<noteq> i mod rat_poly.row_length (mat1 (2 ^ k))) \<Longrightarrow> mat1 2 ! (j div length (mat1 (2 ^ k))) ! (i div rat_poly.row_length (mat1 (2 ^ k))) = 0 \<or> mat1 (2 ^ k) ! (j mod length (mat1 (2 ^ k))) ! (i mod rat_poly.row_length (mat1 (2 ^ k))) = 0" proof- assume local_assm1: "(j div length (mat1 (2 ^ k)) = i div rat_poly.row_length (mat1 (2 ^ k)) \<longrightarrow> j mod length (mat1 (2 ^ k)) \<noteq> i mod rat_poly.row_length (mat1 (2 ^ k)))" have "(j div length (mat1 (2 ^ k)) = i div rat_poly.row_length (mat1 (2 ^ k))) \<Longrightarrow> mat1 (2 ^ k) ! (j mod length (mat1 (2 ^ k))) ! (i mod rat_poly.row_length (mat1 (2 ^ k))) = 0" using s2 local_assm1 by (metis "7") then have l1:" (j div length (mat1 (2 ^ k)) = i div rat_poly.row_length (mat1 (2 ^ k))) \<Longrightarrow> ?thesis" by auto moreover have "\<not>(j div length (mat1 (2 ^ k)) = i div rat_poly.row_length (mat1 (2 ^ k))) \<Longrightarrow> mat1 2 ! (j div length (mat1 (2^k))) ! (i div rat_poly.row_length (mat1 (2^k))) = 0" using s1 by metis then have "\<not>(j div length (mat1 (2 ^ k)) = i div rat_poly.row_length (mat1 (2 ^ k))) \<Longrightarrow> ?thesis" by auto then show ?thesis using l1 by auto qed then show ?thesis by auto qed qed qed qed then have "(\<forall>i. \<forall>j. (i <(2^(k+1))) \<and> (j < (2^(k+1))) \<longrightarrow> ((rat_poly.Tensor (mat1 2) (mat1 (2^k))!j!i) = (if (((j div (length (mat1 (2^k)))) = (i div (rat_poly.row_length (mat1 (2^k))))) \<and>((j mod (length (mat1 (2^k)))) = (i mod (rat_poly.row_length (mat1 (2^k)))))) then 1 else 0)))" using 9 by metis then have "(\<forall>i. \<forall>j. (i <(2^(k+1))) \<and> (j < (2^(k+1))) \<longrightarrow> ((rat_poly.Tensor (mat1 2) (mat1 (2^k))!j!i) = (if (((j div (2^k))) = (i div (2^k)) \<and>((j mod (2^k)) = (i mod (2^k)))) then 1 else 0)))" by (metis (hide_lams, no_types) "6" "7") then have 20:"(\<forall>i. \<forall>j. (i <(2^(k+1))) \<and> (j < (2^(k+1))) \<longrightarrow> ((rat_poly.Tensor (mat1 2) (mat1 (2^k))!j!i) = (if (j = i) then 1 else 0)))" using equal_div_mod2 by auto with 2 have "(\<forall>i. \<forall>j. (i <(2^(k+1))) \<and> (j < (2^(k+1))) \<longrightarrow> ((rat_poly.Tensor (mat1 2) (mat1 (2^k))!j!i) = (mat1 (2^(k+1)))!j!i))" by metis then have "(\<forall>i <(2^(k+1)).\<forall>j < (2^(k+1)). ((rat_poly.Tensor (mat1 2) (mat1 (2^k))!j!i) = (mat1 (2^(k+1)))!j!i))" by auto moreover have "mat (2^(k+1)) (2^(k+1)) (rat_poly.Tensor (mat1 2) (mat1 (2^k)))" using \<open>make_vert_equiv (k + 1) = mat1 2 \<otimes> mat1 (2 ^ k)\<close> by (metis prop_make_vert_equiv(1) prop_make_vert_equiv(2) prop_make_vert_equiv(3)) ultimately have "(rat_poly.Tensor (mat1 2) (mat1 (2^k))) = (mat1 (2^(k+1)))" using 1 mat_eqI by metis then show ?thesis by auto qed then show ?case using make_vert_equiv.simps using \<open>make_vert_equiv (k + 1) = mat1 2 \<otimes> mat1 (2 ^ k)\<close> by (metis Suc_eq_plus1) qed theorem make_vert_block_map_blockmat: "blockmat (make_vert_block n) = (mat1 (2^n))" by (metis blockmat_make_vert make_vert_equiv_mat) lemma mat1_rt_mult:assumes "mat nr nc m1" shows "rat_poly.matrix_mult m1 (mat1 (nc)) = m1" using assms mat1_mult_right rat_poly.mat_empty_row_length rat_poly.matrix_row_length rat_poly.row_length_def rat_poly.unique_row_col(1) by (metis) lemma mat1_vert_block: "rat_poly.matrix_mult (blockmat b) (blockmat (make_vert_block (nat (codomain_block b)))) = (blockmat b)" proof- have "mat (rat_poly.row_length (blockmat b)) (2^(nat (codomain_block b))) (blockmat b)" using length_codomain_block matrix_blockmat by auto moreover have "(blockmat (make_vert_block (nat (codomain_block b)))) = mat1 (2^(nat (codomain_block b)))" using make_vert_block_map_blockmat by auto ultimately show ?thesis using mat1_rt_mult by auto qed text\<open>The following list of theorems deal with distributivity properties of tensor product of matrices (with entries as rational functions) and composition\<close> definition weak_matrix_match:: "rat_poly mat \<Rightarrow> rat_poly mat \<Rightarrow> rat_poly mat \<Rightarrow> bool" where "weak_matrix_match A1 A2 B1 \<equiv> (mat (rat_poly.row_length A1) (length A1) A1) \<and>(mat (rat_poly.row_length A2) (length A2) A2) \<and>(mat (rat_poly.row_length B1) 1 B1) \<and>(A1 \<noteq> [])\<and>(A2 \<noteq> [])\<and>(B1 \<noteq> []) \<and> (length A1 = rat_poly.row_length A2)" theorem weak_distributivity1: "weak_matrix_match A1 A2 B1 \<Longrightarrow> ((rat_poly.matrix_mult A1 A2)\<otimes> B1) = (rat_poly.matrix_mult (A1 \<otimes> B1) (A2))" proof- assume assms:"weak_matrix_match A1 A2 B1" have 1:"length B1 = 1" using assms weak_matrix_match_def by (metis rat_poly.matrix_row_length rat_poly.unique_row_col(2)) have "[[1]] \<noteq> []" by auto moreover have "mat 1 1 [[1]]" unfolding mat_def Ball_def vec_def by auto moreover have "rat_poly.row_length [[1]] = length B1" unfolding rat_poly.row_length_def 1 by auto ultimately have "rat_poly.matrix_match A1 A2 B1 [[1]]" unfolding rat_poly.matrix_match_def using assms weak_matrix_match_def "1" blockmat.simps(1) matrix_blockmat by (metis (hide_lams, no_types)) then have "((rat_poly.matrix_mult A1 A2)\<otimes>(rat_poly.matrix_mult B1 [[1]])) = (rat_poly.matrix_mult (A1 \<otimes> B1) (A2 \<otimes> [[1]]))" using rat_poly.distributivity by auto moreover have "(rat_poly.matrix_mult B1 [[1]]) = B1" using weak_matrix_match_def assms mat1_equiv mat1_mult_right by (metis) moreover have "(A2 \<otimes> [[1]]) = A2" using rat_poly.Tensor_right_id by (metis) ultimately show ?thesis by auto qed definition weak_matrix_match2:: "rat_poly mat \<Rightarrow> rat_poly mat \<Rightarrow> rat_poly mat \<Rightarrow> bool" where "weak_matrix_match2 A1 B1 B2 \<equiv> (mat (rat_poly.row_length A1) 1 A1) \<and>(mat (rat_poly.row_length B1) (length B1) B1) \<and>(mat (rat_poly.row_length B2) (length B2) B2) \<and>(A1 \<noteq> [])\<and>(B1 \<noteq> [])\<and>(B2 \<noteq> []) \<and> (length B1 = rat_poly.row_length B2)" theorem weak_distributivity2: "weak_matrix_match2 A1 B1 B2 \<Longrightarrow> (A1\<otimes> (rat_poly.matrix_mult B1 B2)) = (rat_poly.matrix_mult (A1 \<otimes> B1) (B2))" proof- assume assms:"weak_matrix_match2 A1 B1 B2" have 1:"length A1 = 1" using assms weak_matrix_match2_def by (metis rat_poly.matrix_row_length rat_poly.unique_row_col(2)) have "[[1]] \<noteq> []" by auto moreover have "mat 1 1 [[1]]" unfolding mat_def Ball_def vec_def by auto moreover have "rat_poly.row_length [[1]] = length A1" unfolding rat_poly.row_length_def 1 by auto ultimately have "rat_poly.matrix_match A1 [[1]] B1 B2" unfolding rat_poly.matrix_match_def using assms weak_matrix_match2_def "1" blockmat.simps(1) matrix_blockmat by (metis (hide_lams, no_types)) then have "((rat_poly.matrix_mult A1 [[1]])\<otimes>(rat_poly.matrix_mult B1 B2)) = (rat_poly.matrix_mult (A1 \<otimes> B1) ([[1]] \<otimes> B2))" using rat_poly.distributivity by auto moreover have "(rat_poly.matrix_mult A1 [[1]]) = A1" using weak_matrix_match2_def assms mat1_equiv mat1_mult_right by (metis) moreover have "([[1]] \<otimes> B2) = B2" by (metis rat_poly.Tensor_left_id) ultimately show ?thesis by auto qed lemma is_tangle_diagram_weak_matrix_match: assumes "is_tangle_diagram (w1*ws1)" and "codomain_block w2 = 0" shows "weak_matrix_match (blockmat w1) (kauff_mat ws1) (blockmat w2)" unfolding weak_matrix_match_def apply(auto) proof- show "mat (rat_poly.row_length (blockmat w1)) (length (blockmat w1)) (blockmat w1)" using matrix_blockmat by auto next have "is_tangle_diagram ws1" using assms(1) is_tangle_diagram.simps(2) by metis then show "mat (rat_poly.row_length (kauff_mat ws1)) (length (kauff_mat ws1)) (kauff_mat ws1)" using matrix_kauff_mat by metis next have "mat (rat_poly.row_length (blockmat w2)) (length (blockmat w2)) (blockmat w2)" using matrix_blockmat by auto then have "mat (rat_poly.row_length (blockmat w2)) 1 (blockmat w2)" using assms(2) length_codomain_block by auto then show "mat (rat_poly.row_length (blockmat w2)) (Suc 0) (blockmat w2)" by auto next show "length (blockmat w1) = rat_poly.row_length (kauff_mat ws1)" using is_tangle_diagram_length_rowlength assms(1) by auto next assume 0:"blockmat w1 = [] " show False using 0 by (metis blockmat_non_empty) next assume 1:"kauff_mat ws1 = [] " have "is_tangle_diagram ws1" using assms(1) is_tangle_diagram.simps(2) by metis then show False using 1 kauff_mat_non_empty by auto next assume 0:"blockmat w2 = [] " show False using 0 by (metis blockmat_non_empty) qed lemma is_tangle_diagram_weak_matrix_match2: assumes "is_tangle_diagram (w2*ws2)" and "codomain_block w1 = 0" shows "weak_matrix_match2 (blockmat w1) (blockmat w2) (kauff_mat ws2)" unfolding weak_matrix_match2_def apply(auto) proof- have "mat (rat_poly.row_length (blockmat w1)) (length (blockmat w1)) (blockmat w1)" using matrix_blockmat by auto then have "mat (rat_poly.row_length (blockmat w1)) 1 (blockmat w1)" using assms(2) length_codomain_block by auto then show "mat (rat_poly.row_length (blockmat w1)) (Suc 0) (blockmat w1)" by auto next have "is_tangle_diagram ws2" using assms(1) is_tangle_diagram.simps(2) by metis then show "mat (rat_poly.row_length (kauff_mat ws2)) (length (kauff_mat ws2)) (kauff_mat ws2)" using matrix_kauff_mat by metis next show "mat (rat_poly.row_length (blockmat w2)) (length (blockmat w2)) (blockmat w2)" by (metis matrix_blockmat) next show "length (blockmat w2) = rat_poly.row_length (kauff_mat ws2)" using is_tangle_diagram_length_rowlength assms(1) by auto next assume 0:"blockmat w1 = [] " show False using 0 by (metis blockmat_non_empty) next assume 1:"kauff_mat ws2 = [] " have "is_tangle_diagram ws2" using assms(1) is_tangle_diagram.simps(2) by metis then show False using 1 kauff_mat_non_empty by auto next assume 0:"blockmat w2 = [] " show False using 0 by (metis blockmat_non_empty) qed lemma is_tangle_diagram_vert_block: "is_tangle_diagram (b*(basic (make_vert_block (nat (codomain_block b)))))" proof- have "domain_wall (basic (make_vert_block (nat (codomain_block b)))) = (codomain_block b)" using domain_wall.simps make_vert_block.simps by (metis codomain_block_nonnegative domain_make_vert int_nat_eq) then show ?thesis using is_tangle_diagram.simps by auto qed text\<open>The following theorem tells us that the the map kauff$\_$mat when restricted to walls representing tangles preserves the tensor product\<close> theorem Tensor_Invariance: "(is_tangle_diagram ws1) \<and> (is_tangle_diagram ws2) \<Longrightarrow> (kauff_mat (ws1 \<otimes> ws2) = (kauff_mat ws1) \<otimes> (kauff_mat ws2))" proof(induction rule:tensor.induct) case 1 show ?case using kauff_mat_tensor_distrib by auto next fix a b as bs assume hyps:" is_tangle_diagram as \<and> is_tangle_diagram bs \<Longrightarrow> (kauff_mat (as \<otimes> bs) = kauff_mat as \<otimes> kauff_mat bs)" assume prems:" is_tangle_diagram (a*as) \<and> is_tangle_diagram (b*bs) " let ?case = "kauff_mat (a * as \<otimes> b * bs) = kauff_mat (a * as) \<otimes> kauff_mat (b * bs)" have 0:"rat_poly.matrix_match (blockmat a) (kauff_mat as) (blockmat b) (kauff_mat bs)" using prems is_tangle_diagram_matrix_match by auto have 1:"is_tangle_diagram as \<and> is_tangle_diagram bs" using prems is_tangle_diagram.simps by metis have "kauff_mat ((a * as) \<otimes> (b * bs)) = kauff_mat ((a \<otimes> b) * (as \<otimes> bs))" using tensor.simps by auto moreover have "... = rat_poly.matrix_mult (blockmat (a \<otimes> b)) (kauff_mat (as \<otimes> bs))" using kauff_mat.simps(2) by auto moreover have "... = rat_poly.matrix_mult ((blockmat a) \<otimes> (blockmat b)) ((kauff_mat as) \<otimes> (kauff_mat bs))" using hyps 1 kauff_mat_tensor_distrib by auto moreover have "... =(rat_poly.matrix_mult (blockmat a) (kauff_mat as)) \<otimes> (rat_poly.matrix_mult (blockmat b) (kauff_mat bs))" using 0 rat_poly.distributivity by auto moreover have "... = kauff_mat (a*as) \<otimes> kauff_mat (b*bs)" by auto ultimately show ?case by metis next fix a b as bs assume hyps:"codomain_block b \<noteq> 0 \<Longrightarrow> is_tangle_diagram as \<and> is_tangle_diagram (basic (make_vert_block (nat (codomain_block b)))) \<Longrightarrow> kauff_mat (as \<otimes> basic (make_vert_block (nat (codomain_block b)))) = kauff_mat as \<otimes> kauff_mat (basic (make_vert_block (nat (codomain_block b))))" assume prems:"is_tangle_diagram (a * as) \<and> is_tangle_diagram (basic b)" let ?case = " kauff_mat (a * as \<otimes> basic b) = kauff_mat (a * as) \<otimes> kauff_mat (basic b)" show ?case proof(cases "codomain_block b = 0") case True have "((a * as) \<otimes> (basic b)) = ((a \<otimes>b) * as)" using tensor.simps True by auto then have "kauff_mat ((a * as) \<otimes> (basic b)) = kauff_mat ((a \<otimes>b) * as)" by auto moreover have "... = rat_poly.matrix_mult (blockmat (a \<otimes> b)) (kauff_mat as)" by auto moreover have "... = rat_poly.matrix_mult ((blockmat a) \<otimes> (blockmat b)) (kauff_mat as)" using blockmat_tensor_distrib by (metis) ultimately have T1: "kauff_mat ((a * as) \<otimes> (basic b)) = rat_poly.matrix_mult ((blockmat a) \<otimes> (blockmat b)) (kauff_mat as)" by auto then have "weak_matrix_match (blockmat a) (kauff_mat as) (blockmat b)" using is_tangle_diagram_weak_matrix_match True prems by auto then have "rat_poly.matrix_mult ((blockmat a) \<otimes> (blockmat b)) (kauff_mat as) = ((rat_poly.matrix_mult (blockmat a) (kauff_mat as)) \<otimes> (blockmat b))" using weak_distributivity1 by auto moreover have "... = (kauff_mat (a*as)) \<otimes> (kauff_mat (basic b))" by auto ultimately show ?thesis using T1 by metis next case False let ?bs = "(basic (make_vert_block (nat (codomain_block b))))" have F0:"rat_poly.matrix_match (blockmat a) (kauff_mat as) (blockmat b) (kauff_mat ?bs)" using prems is_tangle_diagram_vert_block is_tangle_diagram_matrix_match by metis have F1:"codomain_block b \<noteq> 0" using False by auto have F2:" is_tangle_diagram as \<and> is_tangle_diagram ?bs" using is_tangle_diagram.simps prems by metis then have F3:"kauff_mat (as\<otimes>basic (make_vert_block (nat (codomain_block b)))) = kauff_mat as \<otimes> kauff_mat ?bs" using F1 hyps by auto moreover have "((a*as) \<otimes> (basic b)) = (a \<otimes> b) * (as \<otimes> ?bs)" using False tensor.simps by auto moreover then have "kauff_mat ((a*as) \<otimes> (basic b)) = kauff_mat((a \<otimes> b) * (as \<otimes> ?bs))" by auto moreover then have "... = rat_poly.matrix_mult (blockmat (a \<otimes> b)) (kauff_mat (as \<otimes> ?bs))" using kauff_mat.simps by auto moreover then have "... = rat_poly.matrix_mult ((blockmat a)\<otimes>(blockmat b)) ((kauff_mat as)\<otimes>(kauff_mat ?bs))" using F3 blockmat_tensor_distrib by (metis) moreover then have "... = (rat_poly.matrix_mult (blockmat a) (kauff_mat as)) \<otimes> (rat_poly.matrix_mult (blockmat b) (kauff_mat ?bs))" using rat_poly.distributivity F0 by auto moreover then have "... = (rat_poly.matrix_mult (blockmat a) (kauff_mat as)) \<otimes> (blockmat b)" using mat1_vert_block by auto moreover then have "... = (kauff_mat (a*as)) \<otimes> (kauff_mat (basic b))" using kauff_mat.simps by auto ultimately show ?thesis by metis qed next fix a b as bs assume hyps: "codomain_block b \<noteq> 0 \<Longrightarrow> is_tangle_diagram (basic (make_vert_block (nat (codomain_block b)))) \<and>(is_tangle_diagram as) \<Longrightarrow> kauff_mat (basic (make_vert_block (nat (codomain_block b)))\<otimes> as) = kauff_mat (basic (make_vert_block (nat (codomain_block b)))) \<otimes> kauff_mat as " assume prems:"is_tangle_diagram (basic b) \<and> is_tangle_diagram (a * as) " let ?case = " kauff_mat ( (basic b) \<otimes> (a * as)) = kauff_mat (basic b) \<otimes> kauff_mat (a * as)" show ?case proof(cases "codomain_block b = 0") case True have "((basic b) \<otimes> (a * as)) = ((b \<otimes> a) * as)" using tensor.simps True by auto then have "kauff_mat ((basic b) \<otimes> (a * as)) = kauff_mat ((b \<otimes>a ) * as)" by auto moreover have "... = rat_poly.matrix_mult (blockmat (b \<otimes> a)) (kauff_mat as)" by auto moreover have "... = rat_poly.matrix_mult ((blockmat b) \<otimes> (blockmat a)) (kauff_mat as)" using blockmat_tensor_distrib by (metis) ultimately have T1:"kauff_mat ((basic b) \<otimes> (a*as)) = rat_poly.matrix_mult ((blockmat b) \<otimes> (blockmat a)) (kauff_mat as)" by auto then have "weak_matrix_match2 (blockmat b) (blockmat a) (kauff_mat as)" using is_tangle_diagram_weak_matrix_match2 True prems by auto then have "rat_poly.matrix_mult ((blockmat b) \<otimes> (blockmat a)) (kauff_mat as) = (blockmat b) \<otimes> (rat_poly.matrix_mult (blockmat a)(kauff_mat as))" using weak_distributivity2 by auto moreover have "... = (kauff_mat (basic b)) \<otimes> (kauff_mat (a*as)) " by auto ultimately show ?thesis using T1 by metis next case False let ?bs = "(basic (make_vert_block (nat (codomain_block b))))" have F0:"rat_poly.matrix_match (blockmat b) (kauff_mat ?bs) (blockmat a) (kauff_mat as)" using prems is_tangle_diagram_vert_block is_tangle_diagram_matrix_match by metis have F1:"codomain_block b \<noteq> 0" using False by auto have F2:" is_tangle_diagram as \<and> is_tangle_diagram ?bs" using is_tangle_diagram.simps prems by metis then have F3:"kauff_mat (?bs \<otimes> as) = kauff_mat ?bs \<otimes> kauff_mat as" using F1 hyps by auto moreover have "((basic b) \<otimes> (a*as)) = (b \<otimes> a) * (?bs \<otimes> as)" using False tensor.simps by auto moreover then have "kauff_mat ((basic b) \<otimes> (a*as)) = kauff_mat((b \<otimes> a) * (?bs \<otimes> as))" by auto moreover then have "... = rat_poly.matrix_mult (blockmat (b \<otimes> a)) (kauff_mat (?bs \<otimes> as))" using kauff_mat.simps by auto moreover then have "... = rat_poly.matrix_mult ((blockmat b)\<otimes>(blockmat a)) ((kauff_mat ?bs)\<otimes>(kauff_mat as))" using F3 by (metis blockmat_tensor_distrib) moreover then have "... = (rat_poly.matrix_mult (blockmat b) (kauff_mat ?bs)) \<otimes> (rat_poly.matrix_mult (blockmat a) (kauff_mat as))" using rat_poly.distributivity F0 by auto moreover then have "... = (blockmat b) \<otimes> (rat_poly.matrix_mult (blockmat a) (kauff_mat as))" using mat1_vert_block by auto moreover then have "... = (kauff_mat (basic b)) \<otimes> (kauff_mat (a*as))" using kauff_mat.simps by auto ultimately show ?thesis by metis qed qed end
Upon creation , the 766th Unit was designed to vary in size , consisting of a number of smaller units capable of acting alone . Eventually , it was reinforced to the size of a full regiment , with 3 @,@ 000 men equally distributed across six battalions ( numbered 1st through 6th ) . It was made directly subordinate to the KPA Army headquarters and put under the command of Senior Colonel Oh Jin Woo , who would command the unit for its entire existence . All 500 men of the 3rd Battalion were lost just before the war started when their transport was sunk while attacking Pusan harbor by the Republic of Korea Navy . For the remainder of its existence the regiment was whittled down by losses until it numbered no more than 1 @,@ 500 men and could not muster more than three battalions .
SUBROUTINE HROAM ( ityp, x, y, iret ) C************************************************************************ C* HROAM - GN * C* * C* This subroutine roams the window at the specified position on * C* current driver. * C* * C* HROAM ( ITYP, X, Y, IRET ) * C* * C* Input parameters: * C* ITYP INTEGER The base point of roam * C* 0 = upper left screen corner * C* 1 = center of the screen * C* 2 = delta_x, delta_y * C* X REAL Upper left window x coordinates * C* Y REAL Upper left window y coordinates * C* * C* Output parameters: * C* IRET INTEGER Return code * C** * C* Log: * C* C. Lin/EAI 6/97 * C* S. Maxwell/GSC 6/97 Documentation changes * C************************************************************************ INCLUDE 'ERROR.PRM' C------------------------------------------------------------------------ iret = NORMAL C RETURN END
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.set.lattice /-! # Formal concept analysis > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines concept lattices. A concept of a relation `r : α → β → Prop` is a pair of sets `s : set α` and `t : set β` such that `s` is the set of all `a : α` that are related to all elements of `t`, and `t` is the set of all `b : β` that are related to all elements of `s`. Ordering the concepts of a relation `r` by inclusion on the first component gives rise to a *concept lattice*. Every concept lattice is complete and in fact every complete lattice arises as the concept lattice of its `≤`. ## Implementation notes Concept lattices are usually defined from a *context*, that is the triple `(α, β, r)`, but the type of `r` determines `α` and `β` already, so we do not define contexts as a separate object. ## TODO Prove the fundamental theorem of concept lattices. ## References * [Davey, Priestley *Introduction to Lattices and Order*][davey_priestley] ## Tags concept, formal concept analysis, intent, extend, attribute -/ open function order_dual set variables {ι : Sort*} {α β γ : Type*} {κ : ι → Sort*} (r : α → β → Prop) {s s₁ s₂ : set α} {t t₁ t₂ : set β} /-! ### Intent and extent -/ /-- The intent closure of `s : set α` along a relation `r : α → β → Prop` is the set of all elements which `r` relates to all elements of `s`. -/ def intent_closure (s : set α) : set β := {b | ∀ ⦃a⦄, a ∈ s → r a b} /-- The extent closure of `t : set β` along a relation `r : α → β → Prop` is the set of all elements which `r` relates to all elements of `t`. -/ def extent_closure (t : set β) : set α := {a | ∀ ⦃b⦄, b ∈ t → r a b} variables {r} lemma subset_intent_closure_iff_subset_extent_closure : t ⊆ intent_closure r s ↔ s ⊆ extent_closure r t := ⟨λ h a ha b hb, h hb ha, λ h b hb a ha, h ha hb⟩ variables (r) lemma gc_intent_closure_extent_closure : galois_connection (to_dual ∘ intent_closure r) (extent_closure r ∘ of_dual) := λ s t, subset_intent_closure_iff_subset_extent_closure lemma intent_closure_swap (t : set β) : intent_closure (swap r) t = extent_closure r t := rfl lemma extent_closure_swap (s : set α) : extent_closure (swap r) s = intent_closure r s := rfl @[simp] lemma intent_closure_empty : intent_closure r ∅ = univ := eq_univ_of_forall $ λ _ _, false.elim @[simp] lemma extent_closure_empty : extent_closure r ∅ = univ := intent_closure_empty _ @[simp] lemma intent_closure_union (s₁ s₂ : set α) : intent_closure r (s₁ ∪ s₂) = intent_closure r s₁ ∩ intent_closure r s₂ := set.ext $ λ _, ball_or_left_distrib @[simp] lemma extent_closure_union (t₁ t₂ : set β) : extent_closure r (t₁ ∪ t₂) = extent_closure r t₁ ∩ extent_closure r t₂ := intent_closure_union _ _ _ @[simp] lemma intent_closure_Union (f : ι → set α) : intent_closure r (⋃ i, f i) = ⋂ i, intent_closure r (f i) := (gc_intent_closure_extent_closure r).l_supr @[simp] lemma extent_closure_Union (f : ι → set β) : extent_closure r (⋃ i, f i) = ⋂ i, extent_closure r (f i) := intent_closure_Union _ _ @[simp] lemma intent_closure_Union₂ (f : Π i, κ i → set α) : intent_closure r (⋃ i j, f i j) = ⋂ i j, intent_closure r (f i j) := (gc_intent_closure_extent_closure r).l_supr₂ @[simp] lemma extent_closure_Union₂ (f : Π i, κ i → set β) : extent_closure r (⋃ i j, f i j) = ⋂ i j, extent_closure r (f i j) := intent_closure_Union₂ _ _ lemma subset_extent_closure_intent_closure (s : set α) : s ⊆ extent_closure r (intent_closure r s) := (gc_intent_closure_extent_closure r).le_u_l _ lemma subset_intent_closure_extent_closure (t : set β) : t ⊆ intent_closure r (extent_closure r t) := subset_extent_closure_intent_closure _ t @[simp] lemma intent_closure_extent_closure_intent_closure (s : set α) : intent_closure r (extent_closure r $ intent_closure r s) = intent_closure r s := (gc_intent_closure_extent_closure r).l_u_l_eq_l _ @[simp] lemma extent_closure_intent_closure_extent_closure (t : set β) : extent_closure r (intent_closure r $ extent_closure r t) = extent_closure r t := intent_closure_extent_closure_intent_closure _ t lemma intent_closure_anti : antitone (intent_closure r) := (gc_intent_closure_extent_closure r).monotone_l lemma extent_closure_anti : antitone (extent_closure r) := intent_closure_anti _ /-! ### Concepts -/ variables (α β) /-- The formal concepts of a relation. A concept of `r : α → β → Prop` is a pair of sets `s`, `t` such that `s` is the set of all elements that are `r`-related to all of `t` and `t` is the set of all elements that are `r`-related to all of `s`. -/ structure concept extends set α × set β := (closure_fst : intent_closure r fst = snd) (closure_snd : extent_closure r snd = fst) namespace concept variables {r α β} {c d : concept α β r} attribute [simp] closure_fst closure_snd @[ext] lemma ext (h : c.fst = d.fst) : c = d := begin obtain ⟨⟨s₁, t₁⟩, h₁, _⟩ := c, obtain ⟨⟨s₂, t₂⟩, h₂, _⟩ := d, dsimp at h₁ h₂ h, subst h, subst h₁, subst h₂, end lemma ext' (h : c.snd = d.snd) : c = d := begin obtain ⟨⟨s₁, t₁⟩, _, h₁⟩ := c, obtain ⟨⟨s₂, t₂⟩, _, h₂⟩ := d, dsimp at h₁ h₂ h, subst h, subst h₁, subst h₂, end lemma fst_injective : injective (λ c : concept α β r, c.fst) := λ c d, ext lemma snd_injective : injective (λ c : concept α β r, c.snd) := λ c d, ext' instance : has_sup (concept α β r) := ⟨λ c d, { fst := extent_closure r (c.snd ∩ d.snd), snd := c.snd ∩ d.snd, closure_fst := by rw [←c.closure_fst, ←d.closure_fst, ←intent_closure_union, intent_closure_extent_closure_intent_closure], closure_snd := rfl }⟩ instance : has_inf (concept α β r) := ⟨λ c d, { fst := c.fst ∩ d.fst, snd := intent_closure r (c.fst ∩ d.fst), closure_fst := rfl, closure_snd := by rw [←c.closure_snd, ←d.closure_snd, ←extent_closure_union, extent_closure_intent_closure_extent_closure] }⟩ instance : semilattice_inf (concept α β r) := fst_injective.semilattice_inf _ $ λ _ _, rfl @[simp] lemma fst_subset_fst_iff : c.fst ⊆ d.fst ↔ c ≤ d := iff.rfl @[simp] lemma fst_ssubset_fst_iff : c.fst ⊂ d.fst ↔ c < d := iff.rfl @[simp] lemma snd_subset_snd_iff : c.snd ⊆ d.snd ↔ d ≤ c := begin refine ⟨λ h, _, λ h, _⟩, { rw [←fst_subset_fst_iff, ←c.closure_snd, ←d.closure_snd], exact extent_closure_anti _ h }, { rw [←c.closure_fst, ←d.closure_fst], exact intent_closure_anti _ h } end @[simp] lemma snd_ssubset_snd_iff : c.snd ⊂ d.snd ↔ d < c := by rw [ssubset_iff_subset_not_subset, lt_iff_le_not_le, snd_subset_snd_iff, snd_subset_snd_iff] lemma strict_mono_fst : strict_mono (prod.fst ∘ to_prod : concept α β r → set α) := λ c d, fst_ssubset_fst_iff.2 lemma strict_anti_snd : strict_anti (prod.snd ∘ to_prod : concept α β r → set β) := λ c d, snd_ssubset_snd_iff.2 instance : lattice (concept α β r) := { sup := (⊔), le_sup_left := λ c d, snd_subset_snd_iff.1 $ inter_subset_left _ _, le_sup_right := λ c d, snd_subset_snd_iff.1 $ inter_subset_right _ _, sup_le := λ c d e, by { simp_rw ←snd_subset_snd_iff, exact subset_inter }, ..concept.semilattice_inf } instance : bounded_order (concept α β r) := { top := ⟨⟨univ, intent_closure r univ⟩, rfl, eq_univ_of_forall $ λ a b hb, hb trivial⟩, le_top := λ _, subset_univ _, bot := ⟨⟨extent_closure r univ, univ⟩, eq_univ_of_forall $ λ b a ha, ha trivial, rfl⟩, bot_le := λ _, snd_subset_snd_iff.1 $ subset_univ _ } instance : has_Sup (concept α β r) := ⟨λ S, { fst := extent_closure r (⋂ c ∈ S, (c : concept _ _ _).snd), snd := ⋂ c ∈ S, (c : concept _ _ _).snd, closure_fst := by simp_rw [←closure_fst, ←intent_closure_Union₂, intent_closure_extent_closure_intent_closure], closure_snd := rfl }⟩ instance : has_Inf (concept α β r) := ⟨λ S, { fst := ⋂ c ∈ S, (c : concept _ _ _).fst, snd := intent_closure r (⋂ c ∈ S, (c : concept _ _ _).fst), closure_fst := rfl, closure_snd := by simp_rw [←closure_snd, ←extent_closure_Union₂, extent_closure_intent_closure_extent_closure] }⟩ instance : complete_lattice (concept α β r) := { Sup := Sup, le_Sup := λ S c hc, snd_subset_snd_iff.1 $ bInter_subset_of_mem hc, Sup_le := λ S c hc, snd_subset_snd_iff.1 $ subset_Inter₂ $ λ d hd, snd_subset_snd_iff.2 $ hc d hd, Inf := Inf, Inf_le := λ S c, bInter_subset_of_mem, le_Inf := λ S c, subset_Inter₂, ..concept.lattice, ..concept.bounded_order } @[simp] lemma top_fst : (⊤ : concept α β r).fst = univ := rfl @[simp] lemma top_snd : (⊤ : concept α β r).snd = intent_closure r univ := rfl @[simp] lemma bot_fst : (⊥ : concept α β r).fst = extent_closure r univ := rfl @[simp] lemma bot_snd : (⊥ : concept α β r).snd = univ := rfl @[simp] lemma sup_fst (c d : concept α β r) : (c ⊔ d).fst = extent_closure r (c.snd ∩ d.snd) := rfl @[simp] lemma sup_snd (c d : concept α β r) : (c ⊔ d).snd = c.snd ∩ d.snd := rfl @[simp] lemma inf_fst (c d : concept α β r) : (c ⊓ d).fst = c.fst ∩ d.fst := rfl @[simp] lemma inf_snd (c d : concept α β r) : (c ⊓ d).snd = intent_closure r (c.fst ∩ d.fst) := rfl @[simp] lemma Sup_fst (S : set (concept α β r)) : (Sup S).fst = extent_closure r ⋂ c ∈ S, (c : concept _ _ _).snd := rfl @[simp] lemma Sup_snd (S : set (concept α β r)) : (Sup S).snd = ⋂ c ∈ S, (c : concept _ _ _).snd := rfl @[simp] lemma Inf_fst (S : set (concept α β r)) : (Inf S).fst = ⋂ c ∈ S, (c : concept _ _ _).fst := rfl @[simp] lemma Inf_snd (S : set (concept α β r)) : (Inf S).snd = intent_closure r ⋂ c ∈ S, (c : concept _ _ _).fst := rfl instance : inhabited (concept α β r) := ⟨⊥⟩ /-- Swap the sets of a concept to make it a concept of the dual context. -/ @[simps] def swap (c : concept α β r) : concept β α (swap r) := ⟨c.to_prod.swap, c.closure_snd, c.closure_fst⟩ @[simp] lemma swap_swap (c : concept α β r) : c.swap.swap = c := ext rfl @[simp] lemma swap_le_swap_iff : c.swap ≤ d.swap ↔ d ≤ c := snd_subset_snd_iff @[simp] lemma swap_lt_swap_iff : c.swap < d.swap ↔ d < c := snd_ssubset_snd_iff /-- The dual of a concept lattice is isomorphic to the concept lattice of the dual context. -/ @[simps] def swap_equiv : (concept α β r)ᵒᵈ ≃o concept β α (function.swap r) := { to_fun := swap ∘ of_dual, inv_fun := to_dual ∘ swap, left_inv := swap_swap, right_inv := swap_swap, map_rel_iff' := λ c d, swap_le_swap_iff } end concept
This music needs a party and I'm going! that soo set is fire! DJ Soo opens a world of eclectic magic from 7 Samurai's jazz sounds to the Soul Rebels Brass Band to the Empressarios' cumbia and more. Plus Al Green's hard grooving "Waiting For You", singalong soul from The Marvelettes and The Shirelles, and West Coast vibes from Snoop, Ozay Moore and Amin Payne. DJs & GUESTS DJ Static, Professor Groove, DJ Soo / RECORDED April 13, 2018 / HOSTING daduke, PJ, Mike & Oliver. You can help too! ozay moore feat. tony ozier & teeko - w.s.t.c.s.t. tagi & steven beatberg feat. georgia anne muldrow - n.t.
import categoryTheory.thin universes v u u₂ v₂ open category_theory namespace specialCats set_option pp.structure_projections false class FP_cat (C : Type u) extends category C := -- Terminal object (unit : C) (term : ∀ X : C, X ⟶ unit) (unit_η : ∀ (X : C) (f : X ⟶ unit), f = term X) -- Binary products (prod : C → C → C) (pr1 : ∀ {X Y : C}, (prod X Y) ⟶ X) (pr2 : ∀ {X Y : C}, (prod X Y) ⟶ Y) (pair : ∀ {X Y Z : C} (f : Z ⟶ X) (g : Z ⟶ Y), Z ⟶ (prod X Y)) (prod_β1 : ∀ {X Y Z : C} {f : Z ⟶ X} {g : Z ⟶ Y}, (pair f g) ≫ pr1 = f) (prod_β2 : ∀ {X Y Z : C} {f : Z ⟶ X} {g : Z ⟶ Y}, (pair f g) ≫ pr2 = g) (prod_η : ∀ {X Y : C}, pair pr1 pr2 = 𝟙 (prod X Y)) instance {C : Type u} [FP_cat C] : has_one C := { one := FP_cat.unit } instance {C : Type u} [FP_cat C] : has_mul C := { mul := λ X Y, FP_cat.prod X Y } def homprod {C : Type u} [FP_cat C] {W X Y Z : C} (f : W ⟶ X) (g : Y ⟶ Z) : W * Y ⟶ X * Z := FP_cat.pair (FP_cat.pr1 ≫ f) (FP_cat.pr2 ≫ g) notation (name:=homprod) f `***` g := homprod f g -- #check category class CC_cat (C : Type u) extends FP_cat C := (exp : C → C → C) (eval : ∀ {Y Z : C}, (exp Y Z) * Y ⟶ Z) (curry : ∀ {X Y Z : C}, (X * Y ⟶ Z) → (X ⟶ (exp Y Z))) (curry_β : ∀ {X Y Z : C} (u : X * Y ⟶ Z), ((curry u) *** 𝟙 Y) ≫ eval = u) (curry_η : ∀ {X Y Z : C} (v : X ⟶ (exp Y Z)), curry((v *** 𝟙 Y) ≫ eval) = v) notation (name:=exp) X `⟹` Y := CC_cat.exp X Y end specialCats namespace downsetCCC open specialCats class downsets (P : Type) [partial_order P] : Type := (X : set P) (down_closed : ∀ (x x' : P), x ≤ x' → x' ∈ X → x ∈ X) instance {P : Type}[partial_order P] : has_subset (downsets P) := { subset := λ A B, ∀ (x ∈ A.X), x ∈ B.X } theorem downset_ext {P : Type} [partial_order P] : ∀ {A B : downsets P}, A.X = B.X → A=B | ⟨_,_⟩ ⟨_,_⟩ rfl := rfl instance {P : Type}[partial_order P] : has_mem P (downsets P) := { mem := λ x ⟨A,A_down⟩, x ∈ A } def down_closed_external {P : Type}[partial_order P] : ∀ (X : downsets P) (x x' : P), x ≤ x' → x' ∈ X → x ∈ X := begin assume X x x' xlex' x'inX, cases X with A A_down, apply A_down, exact xlex', exact x'inX, end instance {P : Type}[partial_order P] : has_inter (downsets P) := { inter := λ ⟨ A, A_down ⟩ ⟨ B, B_down ⟩, ⟨ A ∩ B , begin assume x x' h x'inboth, cases x'inboth with inA inB, constructor, apply A_down, exact h, exact inA, apply B_down, exact h, exact inB, end ⟩ } #check downset_ext def down {P : Type} (P_struct : partial_order P) : partial_order (downsets P) := { le := (⊆), le_refl := λ A x h, h, le_antisymm := begin assume A B h1 h2, apply downset_ext, apply set.ext, assume x, constructor, apply h1, apply h2, end, le_trans := λ ⟨A,_⟩ ⟨B,_⟩ ⟨C,_⟩ h1 h2 x h, begin apply h2, apply h1, exact h end } def down_pre {P : Type} [P_struct : partial_order P] : preorder (downsets P) := (@partial_order.to_preorder (downsets P) (down P_struct)) instance {P : Type} [partial_order P] : thin_cat (downsets P) := thin_cat.from_preorder down_pre def downset_embed {P : Type} [P_struct : partial_order P]: P → downsets P := λ p, ⟨ { x ∈ set.univ | x ≤ p } , begin assume x x' xlex' h', dsimp, constructor, constructor, dsimp at h', cases h' with _ h, apply le_trans, exact xlex', exact h, end ⟩ def down_exp{P : Type} [P_struct : partial_order P] (X Y : downsets P) : downsets P := ⟨{ x ∈ set.univ | ∀ (z : P), z≤x ∧ z∈X → z∈Y }, begin assume x x' xlex' h', dsimp at h', cases h' with _ h', dsimp, constructor, constructor, assume z h, cases h with zlex zinX, apply h', constructor, apply le_trans, exact zlex, exact xlex', exact zinX, end ⟩ instance {P : Type} [P_struct : partial_order P] : CC_cat (downsets P) := { unit := ⟨ set.univ , λ x x' _ _, true.intro ⟩ , term := begin assume X, induction X with A A_down, apply hom_of_le, assume x, assume h, constructor, end, unit_η := λ X f, by apply thin_cat.K, prod := (∩), pr1 := begin assume X Y, cases X with A A_down, cases Y with B B_down, apply hom_of_le, assume x h, cases h, exact h_left, end, pr2 := begin assume X Y, cases X with A A_down, cases Y with B B_down, apply hom_of_le, assume x h, cases h, exact h_right, end, pair := begin assume X Y Z, assume F G, have k : @partial_order.le (downsets P) (down P_struct) Z X, apply @le_of_hom (downsets P) (down_pre) Z X, exact F, have l : @partial_order.le (downsets P) (down P_struct) Z Y, apply @le_of_hom (downsets P) (down_pre) Z Y, exact G, cases X with A A_down, cases Y with B B_down, cases Z with C C_down, apply hom_of_le, assume z h, constructor, apply k, assumption, apply l, assumption, end, prod_β1 := λ X Y Z f g, by apply thin_cat.K, prod_β2 := λ X Y Z f g, by apply thin_cat.K, prod_η := λ X Y, by apply thin_cat.K, exp := down_exp, eval := begin assume X Y, cases X with A A_down, cases Y with B B_down, apply hom_of_le, assume z h, cases h with zin_exp zin_A, dsimp at zin_exp, cases zin_exp with _ property, apply property, constructor, apply le_refl, exact zin_A, end, curry := begin assume X Y Z XYleZ, suffices betterXYleZ : X ∩ Y ⊆ Z, cases X with A A_down, cases Y with B B_down, cases Z with C C_down, apply hom_of_le, assume z zinA, dsimp[down_exp], constructor, constructor, assume z', assume h, cases h with z'lez z'inB, have z'inA : z'∈A, apply A_down, exact z'lez, exact zinA, suffices ABleC : A ∩ B ⊆ C, apply ABleC, constructor, exact z'inA, exact z'inB, apply betterXYleZ, apply @le_of_hom (downsets P) (down_pre), exact XYleZ, end, curry_β := λ X Y Z u, by apply thin_cat.K, curry_η := λ X Y Z v, by apply thin_cat.K } end downsetCCC
Physiotherapy is an evolving science, as knowledge of the mechanics of the human body change. Bridge 38 maintains an up to date knowledge of the uses and treatments of physiotherapy in sport, pain and injury. We do not believe in prolonged treatments. We do believe in accurate assessments and aim to give you a full and clear explanation of your treatment from the outset, allowing you to manage your own prescription and reduce the number of appointments required overall. With applied physiotherapy, we can help people to stand without pain, to walk freely and to become a more robust athlete in their field. This is the aim of Bridge 38 – the specialist physiotherapy clinic opened by Fiona Campbell in Barton-under-Needwood. Fiona is passionate about using physiotherapy in sport. She worked with Olympic and Paralympic athletes at the EIS (English Institute of Sport), for 10 years. By studying the movement, gait and approach athletes use in training, she uses therapy to address muscle imbalance issues, adjust training and technique errors, reduce recovery times and improve performance. Now contracted through the EIS to the BEF (British Equestrian Federation), Fiona uses a similar approach with riders, demonstrating how better balance and equal use of weight off the horse can improve connection and performance on the horse. Fiona has launched Bridge 38 to bring sports analysis and physiotherapy to the local area. She works with sports enthusiasts, whether professional or hobbyists, to treat injuries and help improve the flow of movement. Fiona also uses physiotherapy to help clients with back pain, arthritis, long term pains and injuries that restrict your daily life. She helps people from all walks of life, professional and retired, young or old, to move freely and get more active. As a triathlete herself, with a sports-loving family, Fiona is personally familiar with the pain from sporting injuries and the frustration of being unable to compete. With her calm and thorough approach, you’ll soon be back on track.
From Equations Require Import Equations. From Coq Require Import Arith Lia List Program.Equality. From Undecidability.FOL Require Import FullSyntax Heyting.Heyting Completeness.HeytingMacNeille. Import ListNotations. Section Lindenbaum. Context {Σ_funcs : funcs_signature}. Context {Σ_preds : preds_signature}. Context {eq_dec_Funcs : EqDec Σ_funcs}. Context {eq_dec_Preds : EqDec Σ_preds}. Section Completeness. (*Context { b : peirce }.*) Notation "A ⊢E phi" := (A ⊢I phi) (at level 30). Instance lb_alg : HeytingAlgebra. Proof. unshelve eapply (@Build_HeytingAlgebra (@form _ _ _ falsity_on)). - intros phi psi. exact ([phi] ⊢E psi). - exact ⊥. - intros phi psi. exact (phi ∧ psi). - intros phi psi. exact (phi ∨ psi). - intros phi psi. exact (phi → psi). - intros phi. apply Ctx. now left. - intros phi psi theta H1 H2. apply IE with (phi:=psi); trivial. apply Weak with (A:=[]); auto. 2: firstorder. econstructor. apply H2. - intros phi. cbn. apply Exp, Ctx. now left. - intros phi psi theta. cbn. split. + intros [H1 H2]. now apply CI. + intros H. split; [apply (CE1 H) | apply (CE2 H)]. - intros phi psi theta. cbn. split. + intros [H1 H2]. eapply DE. apply Ctx; auto. 1: now left. eapply Weak. exact H1. firstorder. eapply Weak. exact H2. firstorder. + intros H; split. * apply (IE (phi := phi ∨ psi)). 2: try apply DI1, Ctx. 2: now left. apply II. eapply Weak; eauto. 1: firstorder. * apply (IE (phi := phi ∨ psi)); try apply DI2, Ctx; try now left. apply II. eapply Weak; eauto. firstorder. - intros phi psi theta. cbn. split. + intros H. apply II. apply (IE (phi := theta ∧ phi)). * apply II. eapply Weak. 1: apply H. firstorder. * apply CI; apply Ctx; firstorder. + intros H. eapply IE. 2: eapply CE2, Ctx; now left. eapply IE. 1: eapply II, Weak. 1: apply H. 2: eapply CE1, Ctx; now left. firstorder. Defined. Lemma lb_alg_iff phi : Top <= phi <-> [] ⊢E phi. Proof. cbn. split; intros H. - apply (IE (phi := ¬ ⊥)); apply II; eauto using Ctx. apply Ctx. now left. - eapply Weak; eauto; firstorder. Qed. Instance lb_calg : CompleteHeytingAlgebra := @completion_calgebra lb_alg. Definition lb_Pr P v : lb_calg := embed (atom P v). Lemma lindenbaum_hsat phi : down phi ≡ proj1_sig (hsat lb_Pr phi). Proof. induction phi as [| |[]|[]] using form_ind_subst; simp hsat in *. - rewrite down_bot. reflexivity. - cbn. reflexivity. - rewrite (@down_meet lb_alg f1 f2), IHphi, IHphi0. now destruct hsat, hsat. - rewrite (@down_join lb_alg f1 f2), IHphi, IHphi0. now destruct hsat, hsat. - rewrite (@down_impl lb_alg f1 f2), IHphi, IHphi0. now destruct hsat, hsat. - cbn. split; intros psi H'. + intros X [HX [t Ht]]. change (psi ∈ proj1_sig (exist normal X HX)). eapply Ht. rewrite <- H. apply AllE, H'. + apply AllI. destruct (@nameless_equiv_all _ _ _ intu ([psi]) f2) as [t Ht]. apply Ht. apply H, H'. exists (proj2_sig (hsat lb_Pr f2[t..])), t. now destruct hsat. - cbn. split; intros psi H'. + intros X [XD HX]. apply XD. intros theta HT. apply (ExE H'). destruct (@nameless_equiv_ex _ _ _ intu ([psi]) f2 theta) as [t Ht]. apply Ht. assert (exists i : term, equiv_HA (hsat lb_Pr f2[t..]) (hsat lb_Pr f2[i..])) by now eexists. specialize (HX (hsat lb_Pr f2[t..]) H0). apply Weak with (A:=[f2[t..]]); auto. 2: now apply ListAutomation.incl_shift. apply HT, HX. rewrite <- H. apply Ctx. now left. + specialize (H' (down (∃ f2))). apply H'. exists (@down_normal lb_alg (∃ f2)). intros X [t ?]. intros ? ?. eapply H0 in H1. revert x H1. fold (hset_sub (proj1_sig (hsat lb_Pr f2[t..])) (down (∃ f2))). rewrite <- H. apply down_mono. eapply ExI, Ctx; eauto. now left. Qed. Lemma lindenbaum_eqH phi : eqH (embed phi) (hsat lb_Pr phi). Proof. unfold eqH. cbn. now rewrite <- lindenbaum_hsat. Qed. Lemma lb_calg_iff phi : Top <= hsat lb_Pr phi <-> nil ⊢E phi. Proof. cbn. rewrite <- lindenbaum_hsat. rewrite <- down_top, <- lb_alg_iff. split. - apply down_inj. - apply down_mono. Qed. End Completeness. (* ** Intuitionistic ND *) Definition hvalid phi := forall (HA : CompleteHeytingAlgebra) HP, Top <= hsat HP phi. Theorem hcompleteness phi : hvalid phi -> nil ⊢I phi. Proof. intros H. specialize (H lb_calg lb_Pr). now eapply lb_calg_iff. Unshelve. Qed. (* ** Generalised Lindenbaum Algebras *) Section Completeness. Variable gprv : list form -> form -> Prop. Notation "A ⊢ phi" := (gprv A phi) (at level 55). Hypothesis gCtx : forall A phi, In phi A -> A ⊢ phi. Hypothesis gIE : forall A phi psi, A ⊢ (phi → psi) -> A ⊢ phi -> A ⊢ psi. Hypothesis gII : forall A phi psi, (phi::A) ⊢ psi -> A ⊢ (phi → psi). Hypothesis gExp : forall A phi, A ⊢ ⊥ -> A ⊢ phi. Hypothesis gCI : forall A phi psi, A ⊢ phi -> A ⊢ psi -> A ⊢ (phi ∧ psi). Hypothesis gCE1 : forall A phi psi, A ⊢ (phi ∧ psi) -> A ⊢ phi. Hypothesis gCE2 : forall A phi psi, A ⊢ (phi ∧ psi) -> A ⊢ psi. Hypothesis gDI1 : forall A phi psi, A ⊢ phi -> A ⊢ (phi ∨ psi). Hypothesis gDI2 : forall A phi psi, A ⊢ psi -> A ⊢ (phi ∨ psi). Hypothesis gDE : forall A phi psi theta, A ⊢ (phi ∨ psi) -> (phi :: A) ⊢ theta -> (psi :: A) ⊢ theta -> A ⊢ theta. Hypothesis gWeak : forall A B phi, A ⊢ phi -> incl A B -> B ⊢ phi. Instance glb_alg : HeytingAlgebra. Proof. unshelve eapply (@Build_HeytingAlgebra (form)). - intros phi psi. exact ([phi] ⊢ psi). - exact ⊥. - intros phi psi. exact (phi ∧ psi). - intros phi psi. exact (phi ∨ psi). - intros phi psi. exact (phi → psi). - intros phi. apply gCtx. now left. - intros phi psi theta H1 H2. apply gIE with (phi:=psi); trivial. apply gWeak with (A:=[]); auto. firstorder. - intros phi. cbn. apply gExp, gCtx. now left. - intros phi psi theta. cbn. split. + intros [H1 H2]. now apply gCI. + intros H. split; [apply (gCE1 H) | apply (gCE2 H)]. - intros phi psi theta. cbn. split. + intros [H1 H2]. eapply gDE. apply gCtx; auto. 1: now left. eapply gWeak. exact H1. firstorder. eapply gWeak. exact H2. firstorder. + intros H; split. * apply (gIE (phi := phi ∨ psi)); try apply gDI1, gCtx. apply gII. eapply gWeak; eauto. 1: firstorder. now left. * apply (gIE (phi := phi ∨ psi)); try apply gDI2, gCtx. apply gII. eapply gWeak; eauto. 1: firstorder. now left. - intros phi psi theta. cbn. split. + intros H. apply gII. apply (gIE (phi := theta ∧ phi)). * apply gII. eapply gWeak; eauto. firstorder. * apply gCI; apply gCtx; auto. 1: right; now left. now left. + intros H. apply (gIE (phi:=phi)). 2: eapply gCE2, gCtx; now left. eapply gIE. 1: eapply gII, gWeak. 1: apply H. 2: eapply gCE1, gCtx; now left. firstorder. Defined. Lemma glb_alg_iff phi : Top <= phi <-> [] ⊢ phi. Proof. cbn. split; intros H. - apply (gIE (phi := ¬ ⊥)); apply gII. 2: apply gCtx; now left. apply H. - eapply gWeak; eauto. firstorder. Qed. Instance glb_calg : CompleteHeytingAlgebra := @completion_calgebra glb_alg. Definition glb_Pr P v : glb_calg := embed (atom P v). Hypothesis gAllI : forall A phi, map (subst_form ↑) A ⊢ phi -> A ⊢ (∀ phi). Hypothesis gAllE : forall A t phi, A ⊢ (∀ phi) -> A ⊢ phi[t..]. Hypothesis gExI : forall A t phi, A ⊢ phi[t..] -> A ⊢ (∃ phi). Hypothesis gExE : forall A phi psi, A ⊢ (∃ phi) -> (phi :: map (subst_form ↑) A) ⊢ psi[↑] -> A ⊢ psi. Hypothesis gnameless_equiv_all' : forall A phi, exists t, A ⊢ phi[t..] <-> map (subst_form ↑) A ⊢ phi. Hypothesis gnameless_equiv_ex' : forall A phi psi, exists t, (psi[t..] :: A) ⊢ phi <-> (psi :: map (subst_form ↑) A) ⊢ phi[↑]. Lemma glindenbaum_hsat phi : down phi ≡ proj1_sig (hsat glb_Pr phi). Proof. induction phi as [| |[]phi ? psi ?|[] phi ?] using form_ind_subst; simp hsat in *. - rewrite down_bot. reflexivity. - cbn. reflexivity. - rewrite (@down_meet glb_alg phi psi), IHphi, IHphi0. now destruct hsat, hsat. - rewrite (@down_join glb_alg phi psi), IHphi, IHphi0. now destruct hsat, hsat. - rewrite (@down_impl glb_alg phi psi), IHphi, IHphi0. now destruct hsat, hsat. - cbn. split; intros psi H'. + intros X [HX [t Ht]]. change (psi ∈ proj1_sig (exist normal X HX)). eapply Ht. rewrite <- H. apply gAllE, H'. + apply gAllI. destruct (@gnameless_equiv_all' ([psi]) phi) as [t <-]. apply H, H'. exists (proj2_sig (hsat glb_Pr phi[t..])), t. now destruct hsat. - cbn. split; intros psi H'. + intros X [XD HX]. apply XD. intros theta HT. apply (gExE H'). destruct (@gnameless_equiv_ex' ([psi]) theta phi) as [t <-]. assert (exists i : term, equiv_HA (hsat glb_Pr phi[t..]) (hsat glb_Pr phi[i..])) by now eexists. specialize (HX (hsat glb_Pr phi[t..]) H0). apply gWeak with (A:=[phi[t..]]); auto. apply HT, HX. rewrite <- H. apply gCtx. now left. apply ListAutomation.incl_shift. easy. + specialize (H' (down (∃ phi))). apply H'. exists (@down_normal glb_alg (∃ phi)). intros X [t ?]. intros ? ?. eapply H0 in H1. revert x H1. fold (hset_sub (proj1_sig (hsat glb_Pr phi[t..])) (down (∃ phi))). rewrite <- H. apply down_mono. eapply gExI, gCtx; eauto. now left. Qed. Lemma glindenbaum_eqH phi : eqH (embed phi) (hsat glb_Pr phi). Proof. unfold eqH. cbn. now rewrite <- glindenbaum_hsat. Qed. Lemma glb_calg_iff phi : Top <= hsat glb_Pr phi <-> nil ⊢ phi. Proof. cbn. rewrite <- glindenbaum_hsat. rewrite <- down_top, <- glb_alg_iff. split. - apply down_inj. - apply down_mono. Qed. End Completeness. #[local] Hint Constructors prv : core. Instance clb_alg : HeytingAlgebra. Proof. apply (@glb_alg (@prv _ _ _ class)); eauto 2. apply Weak. Defined. Instance clb_calg : CompleteHeytingAlgebra. Proof. apply (@glb_calg (@prv _ _ _ class)); eauto 2. apply Weak. Defined. Definition clb_Pr P (v : Vector.t term (ar_preds P)) : clb_calg. Proof. apply glb_Pr with P. exact v. Defined. Lemma clb_alg_boolean : boolean clb_alg. Proof. intros phi psi. cbn. eapply IE; try apply Pc. apply Ctx. now left. Qed. Lemma boolean_completion HA : boolean HA -> boolean (@completion_calgebra HA). Proof. intros H. intros [X HX] [Y HY]; cbn. intros a Ha. unfold hset_impl in Ha. apply HX. intros b Hb. specialize (Ha (Impl b Bot)). eapply Rtra; try apply H. apply Impl1, Hb, Ha. intros c Hc. apply HY. intros d Hd. apply Rtra with Bot; try apply Bot1. assert (H' : Meet (Impl b Bot) c <= Impl b Bot) by apply Meet2. apply Impl1 in H'. eapply Rtra; try eassumption. repeat rewrite <- Meet1. repeat split; auto. eapply Rtra; try apply Meet3. now apply Hb. Qed. Definition bvalid phi := forall (HA : CompleteHeytingAlgebra) HP, boolean HA -> Top <= hsat HP phi. Theorem bcompleteness phi : bvalid phi -> nil ⊢C phi. Proof. intros H. specialize (H clb_calg clb_Pr (boolean_completion clb_alg_boolean)). apply glb_calg_iff in H; eauto 2; clear H0. - intros A psi. edestruct (nameless_equiv_all (p:=class) A psi) as (x & Hx). exists x. now rewrite Hx. - intros A psi chi. edestruct (nameless_equiv_ex (p:=class) A chi psi) as (x & Hx). exists x. now rewrite Hx. Qed. End Lindenbaum.
print(paste0(Sys.time(), " --- Histogram of PTEs total spp described")) # Tabulate statistics of years active tax <- df_describers[spp_N_1st_auth_s>=1] highlight_auth <- tax[ns_spp_N>750]$full.name.of.describer.n tax_highlight <- tax[full.name.of.describer.n %in% highlight_auth][,c("ns_spp_N", "last.name")] x_axis <- seq(0, max(tax$ns_spp_N), 1000) x_axis_minor <- seq(0, max(tax$ns_spp_N), 100) hist_tl_spp <- ggplot(tax, aes(x=ns_spp_N)) + geom_histogram(mapping=aes(y=..count../sum(..count..) * 100), fill='grey30', binwidth=100) + geom_vline(xintercept=median(tax$ns_spp_N), color='grey', size=.5) + xlab("\nTotal number of valid species described, by PTE") + ylab("Proportion of PTEs (%)\n") + geom_label_repel(data=tax_highlight, aes(x=ns_spp_N, y=.1, label=last.name), size=2, nudge_x=10, nudge_y=30, fontface='bold', color='black', segment.color='grey80', force=1, box.padding = unit(0.001, 'lines')) + scale_x_continuous(breaks=x_axis, minor_breaks=x_axis_minor) + # scale_y_continuous(breaks= seq(0, 12, 1), limits=c(0, 12)) + theme ggsave(paste0(dir_plot, 'fig-4a.png'), hist_tl_spp, units="cm", width=7, height=6, dpi=300) # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ # Section - Histogram of PTEs mean sp described per year # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ print(paste0(Sys.time(), " --- Histogram of PTEs mean sp described per year")) # Tabulate statistics of years active tax <- df_describers[spp_N_1st_auth_s>=1] # Highlight auths from previous section tax_highlight <- tax[full.name.of.describer.n %in% highlight_auth][,c("ns_species_per_year_active", "last.name")] hist_mean_spp <- ggplot(tax, aes(x=ns_species_per_year_active)) + geom_histogram(mapping=aes(y=..count../sum(..count..) * 100), fill='grey30', binwidth=1) + geom_vline(xintercept=median(tax$ns_species_per_year_active), color='grey', size=.5) + xlab("\nMean number of species described per year, by PTE") + ylab("Proportion of PTEs (%)\n") + scale_x_continuous(breaks= seq(0, max(tax$ns_species_per_year_active), 10)) + geom_label_repel(data=tax_highlight, aes(x=ns_species_per_year_active, y=.1, label=paste0(last.name, " (", round(ns_species_per_year_active, 0),")")), size=2, nudge_x=20, nudge_y=30, fontface='bold', color='black', segment.color='grey80', force=5, box.padding = unit(0.001, 'lines')) + theme ggsave(paste0(dir_plot, 'fig-4b.png'), hist_mean_spp, units="cm", width=7, height=6, dpi=300)
(* Title: HOL/Auth/n_flash_lemma_on_inv__19.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_flash Protocol Case Study*} theory n_flash_lemma_on_inv__19 imports n_flash_base begin section{*All lemmas on causal relation between inv__19 and some rule r*} lemma n_PI_Remote_PutXVsinv__19: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_PI_Remote_PutX dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__19 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_PI_Remote_ReplaceVsinv__19: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Replace src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__19 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_Get_Nak_HomeVsinv__19: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__19 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_Get_PutVsinv__19: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__19 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_Get_Put_HomeVsinv__19: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__19 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') dst) ''CacheState'')) (Const CACHE_E))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_GetX_Nak_HomeVsinv__19: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__19 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_GetX_PutXVsinv__19: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__19 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_GetX_PutX_HomeVsinv__19: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__19 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_PutVsinv__19: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__19 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "((formEval (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true))) s))" by auto moreover { assume c1: "((formEval (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true)) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume c1: "((formEval (neg (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true))) s))" have "?P1 s" proof(cut_tac a1 a2 b1 c1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately have "invHoldForRule s f r (invariants N)" by satx } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_PutXVsinv__19: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__19 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_InvVsinv__19: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Inv dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__19 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_PI_Local_Get_GetVsinv__19: assumes a1: "(r=n_PI_Local_Get_Get )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__19 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_GetX__part__0Vsinv__19: assumes a1: "(r=n_PI_Local_GetX_GetX__part__0 )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__19 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_GetX__part__1Vsinv__19: assumes a1: "(r=n_PI_Local_GetX_GetX__part__1 )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__19 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Nak_HomeVsinv__19: assumes a1: "(r=n_NI_Nak_Home )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__19 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_PutVsinv__19: assumes a1: "(r=n_NI_Local_Put )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__19 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_PutXAcksDoneVsinv__19: assumes a1: "(r=n_NI_Local_PutXAcksDone )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__19 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_Get_Get__part__1Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Remote_GetVsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_PutX__part__0Vsinv__19: assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_WbVsinv__19: assumes a1: "r=n_NI_Wb " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_StoreVsinv__19: assumes a1: "\<exists> src data. src\<le>N\<and>data\<le>N\<and>r=n_Store src data" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_5Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_GetX__part__1Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_3Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_1Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_Store_HomeVsinv__19: assumes a1: "\<exists> data. data\<le>N\<and>r=n_Store_Home data" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_3Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_ReplaceVsinv__19: assumes a1: "r=n_PI_Local_Replace " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_Nak__part__1Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_Nak__part__1Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_Get__part__0Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_existsVsinv__19: assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_Nak__part__2Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_Put_HeadVsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_PutXVsinv__19: assumes a1: "r=n_PI_Local_PutX " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_Nak__part__2Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_GetX__part__0Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_6Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_Get_PutVsinv__19: assumes a1: "r=n_PI_Local_Get_Put " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_ShWbVsinv__19: assumes a1: "r=n_NI_ShWb N " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__19: assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__0 N " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_11Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_ReplaceVsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Replace src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_1Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_8_HomeVsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_GetX_NakVsinv__19: assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_NakVsinv__19: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Remote_GetXVsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_PutX__part__1Vsinv__19: assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_10Vsinv__19: assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_8Vsinv__19: assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_PutVsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__19: assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_2Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_Nak__part__0Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_exists_HomeVsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Replace_HomeVsinv__19: assumes a1: "r=n_NI_Replace_Home " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_Get_NakVsinv__19: assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Nak_ClearVsinv__19: assumes a1: "r=n_NI_Nak_Clear " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_Put_DirtyVsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_Get_Nak__part__0Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_10_HomeVsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_2Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__19: assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__1 N " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_FAckVsinv__19: assumes a1: "r=n_NI_FAck " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_4Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__19: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__19 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
For any two positive real numbers $d$ and $e$, the open balls of radius $d$ and $e$ are homeomorphic. The same is true for closed balls.
.b = import('../../base') #' Function to normalize expression objects #' #' @param rawData A raw data object, or a list thereof #' @param method Method to use for normalization: rma, gcrma, frma #' @return The normalized data normalize = function(rawData, ...) { UseMethod("normalize") } normalize.list = function(rawData, ...) { re = lapply(rawData, function(x) normalize(x, ...) %catch% NA) if (any(is.na(re))) warning("dropping ", names(re)[is.na(re)]) if (all(is.na(re))) stop("all normalizations failed") re[!is.na(re)] } normalize.FeatureSet = function(rawData, method="rma") { if (method == "rma") oligo::rma(rawData) else stop("invalid method") } normalize.AffyBatch = function(rawData, method="rma") { if (method == "rma") affy::rma(rawData) else if (method == "gcrma") gcrma::gcrma(rawData) else if (method == "frma") frma::frma(rawData, target="core") else stop("invalid method") } normalize.EListRaw = function(rawData, method="quantile") { rawData %>% limma::backgroundCorrect(method="normexp") %>% limma::normalizeBetweenArrays(method=method) } normalize.RGList = function(rawData, method="loess") { rawData %>% limma::backgroundCorrect(method="normexp") %>% limma::normalizeWithinArrays(method=method) } normalize.NChannelSet = function(rawData, ...) { ad = as.list(Biobase::assayData(rawData)) ad$genes = Biobase::fData(rawData) if ("E" %in% names(ad)) { # one-color norm = normalize.EListRaw(new("EListRaw", ad), ...) ad = with(norm, Biobase::assayDataNew(E = E)) } else { # two-color norm = normalize.RGList(new("RGList", ad), ...) ad = with(norm, Biobase::assayDataNew(R = R, G = G)) } features = new("AnnotatedDataFrame", norm$genes) normeset = new("NChannelSet", assayData = ad) featureData(normeset) = features phenoData(normeset) = phenoData(rawData) normeset }
(* Title: HOL/Auth/n_germanSimp_lemma_on_inv__46.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_germanSimp Protocol Case Study*} theory n_germanSimp_lemma_on_inv__46 imports n_germanSimp_base begin section{*All lemmas on causal relation between inv__46 and some rule r*} lemma n_RecvReqSVsinv__46: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__46 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvReqS N i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__46 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv4) ''Cmd'')) (Const InvAck)) (eqn (IVar (Ident ''CurCmd'')) (Const Empty))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv4) ''Cmd'')) (Const InvAck)) (eqn (IVar (Ident ''CurCmd'')) (Const Empty))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvReqE__part__0Vsinv__46: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__0 N i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__46 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvReqE__part__0 N i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__46 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv4) ''Cmd'')) (Const InvAck)) (eqn (IVar (Ident ''CurCmd'')) (Const Empty))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv4) ''Cmd'')) (Const InvAck)) (eqn (IVar (Ident ''CurCmd'')) (Const Empty))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvReqE__part__1Vsinv__46: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__1 N i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__46 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvReqE__part__1 N i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__46 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (neg (eqn (IVar (Field (Para (Ident ''Cache'') p__Inv4) ''State'')) (Const I))) (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv4) ''Cmd'')) (Const InvAck))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Chan3'') p__Inv4) ''Cmd'')) (Const InvAck)) (eqn (IVar (Ident ''CurCmd'')) (Const Empty))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInv__part__0Vsinv__46: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__46 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInv__part__0 i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__46 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInv__part__1Vsinv__46: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__46 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInv__part__1 i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__46 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInvAckVsinv__46: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__46 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInvAck i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__46 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Ident ''InvSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv4) ''Cmd'')) (Const Inv))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvInvAckVsinv__46: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__46 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvInvAck i" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__46 p__Inv4" apply fastforce done have "(i=p__Inv4)\<or>(i~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_StoreVsinv__46: assumes a1: "\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__46 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvGntSVsinv__46: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvGntS i" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__46 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendGntSVsinv__46: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendGntS i" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__46 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvGntEVsinv__46: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvGntE i" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__46 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendGntEVsinv__46: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendGntE N i" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__46 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
module MRIQuant include("Constants.jl") include("Relaxation.jl") include("ExtendedPhaseGraphs.jl") end
c c ================================================= function stream(x,y) c ================================================= c c # Stream function in physical space (x,y). c # Clockwise rotation, rotates fully in time 1. implicit double precision (a-h,o-z) stream = 3.1415926535897931d0 *(x**2 + y**2) c return end
(** * RIS.nominalsetoid : Nominal sets up-to equivalence. *) Require Import tools atoms PeanoNat Nat bijection. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. (** * Definitions *) Section s. (** We fix a decidable set of atoms. *) Context {atom : Set}{A : Atom atom}. (** We use the notation [π ⊙ x] for the group action of a nominal setoid, and [⌈x⌉] for its support. *) Class ActionSetoid (X : Set) := actoid : perm -> X -> X. Infix " ⊙ " := actoid (at level 50). Class SupportSetoid {A : Atom atom} (X : Set) := suppoid : X -> list atom. Notation " ⌈ x ⌉ " := (suppoid x). (** A nominal setoid is a set [X] equipped with a relation [≃], an action [⊙] and a support function [⌈_⌉] satisfying the following axioms: *) Class NominalSetoid (X : Set) (equiv : SemEquiv X) (act : ActionSetoid X) (supp : SupportSetoid X) := { (** [≃] is an equivalence relation; *) eq_equivalence :> Equivalence sequiv; (** equivalent elements have equivalent support : if [x≃y], then [a∈⌈x⌉ <-> a∈⌈y⌉]; *) eq_support :> Proper (sequiv ==> (@equivalent atom)) suppoid; (** the action in compatible with the equivalence relation ; *) eq_act_proper π :> Proper (sequiv ==> sequiv) (actoid π); (** the remaining axioms are the same as for nominal sets, except that equality of elements in [X] has been substituted with [≃]. *) action_invariant_eq : forall (x : X) π, (π ∙ ⌈x⌉ = ⌈x⌉) -> (π ⊙ x) ≃ x; support_action_eq : forall x π, ⌈π ⊙ x⌉ ≈ π∙⌈x⌉; action_compose_eq : forall x π π', π ⊙ (π' ⊙ x) ≃ (π++π') ⊙ x }. (** The following observations are straightforward to check directly from the axioms we just listed. *) Remark actoid_pinv_p {X : Set} `{NominalSetoid X}: forall π x, π∗ ⊙ (π ⊙ x) ≃ x. Proof. intros;rewrite action_compose_eq;apply action_invariant_eq. rewrite perm_pinv_p_eq_nil,act_nil;reflexivity. Qed. Remark actoid_p_pinv {X : Set} `{NominalSetoid X}: forall π x, π ⊙ (π∗ ⊙ x) ≃ x. Proof. intros;rewrite action_compose_eq;apply action_invariant_eq. rewrite perm_p_pinv_eq_nil,act_nil;reflexivity. Qed. (** Permutations that are equivalent as functions yield the same action (even if they are syntactically different): if for every atom [a] we have [π ∙ a = π' ∙ a] and if [x≃y], then [π⊙x≃π'⊙y]. *) Global Instance eq_act {X : Set} `{NominalSetoid X} : Proper (sequiv ==> sequiv ==> sequiv) actoid. Proof. intros π π' Eπ x y <- ;clear y. transitivity (π'⊙(π'∗ ⊙ (π ⊙ x))). - rewrite actoid_p_pinv;reflexivity. - apply eq_act_proper. rewrite action_compose_eq;apply action_invariant_eq. rewrite <- action_compose. rewrite Eπ,act_pinv_p;reflexivity. Qed. Lemma minimal_support_eq {X: Set} `{NominalSetoid X} l x : (forall π, (forall a, a ∈ l -> π ∙ a = a) -> π ⊙ x ≃ x) -> ⌈x⌉ ⊆ l. Proof. intros s a Ia. case_in a l;[tauto|exfalso]. destruct (exists_fresh (a::l++⌈x⌉)) as (b&hb). simpl_In in hb. assert (E: [(a,b)]⊙x≃x). - apply s;intros c Ic. apply elements_inv_act_atom;simpl. intros [->|[->|F]];tauto. - pose proof (support_action_eq x [(a,b)]) as E'. rewrite E in E';revert Ia. rewrite E',In_act_lists. unfold act,act_atom;simpl;simpl_beq. tauto. Qed. Remark ActionSetoid_ext_In {X:Set} `{NominalSetoid X}: forall π π' x, (forall a, a ∈ ⌈x⌉ -> π ∙ a = π' ∙ a) -> π ⊙ x ≃ π' ⊙ x. Proof. intros p q x h. cut (x ≃ q∗ ⊙ (p ⊙ x)). - intros e ;rewrite e at 2;rewrite actoid_p_pinv;reflexivity. - symmetry;rewrite action_compose_eq. apply action_invariant_eq,map_eq_id. intros a Ia;rewrite <- action_compose,h,act_pinv_p;reflexivity||assumption. Qed. End s. (* begin hide *) Infix " ⊙ " := actoid (at level 50). Notation " ⌈ x ⌉ " := (suppoid x). (* Arguments NominalSetoid : clear implicits. *) Arguments NominalSetoid {atom} A X {equiv act supp}. Arguments ActionSetoid _ A X : clear implicits. Arguments SupportSetoid _ A X : clear implicits. (* end hide *) (** * Lifting the structure to lists *) Section list. (** Let us fix a nominal setoid [S] over a set of atoms [Atom]. *) Context {atom : Set}{A: Atom atom}. Context {S : Set} {eqS : SemEquiv S} {actS : ActionSetoid _ A S} {suppS : SupportSetoid _ A S}. Context {N: NominalSetoid A S}. (** We define the action of [π] on a list by apply [π] pointwise. *) Global Instance actoid_lists : ActionSetoid _ A (list S):= fun π l => map (fun x => π⊙x) l. (* begin hide *) Remark actoid_lists_app π (l m : list S) : π⊙(l++m) = π⊙l++π⊙m. Proof. apply map_app. Qed. Remark actoid_lists_cons π (a :S) l : π⊙(a::l) = π⊙a::π⊙l. Proof. reflexivity. Qed. Remark actoid_lists_length π (l : list S) : ⎢π⊙l⎥ = ⎢l⎥. Proof. apply map_length. Qed. (* end hide *) (** To compute the support of a list, we compute the support of each element, take the union of those, and remove duplicates. *) Global Instance SupportSetoidList : SupportSetoid _ A (list S) := fun l => {{flat_map suppoid l}}. (** Two lists are equivalent if they have the same length, and if their elements are pointwise equivalent. For instance if [l=l1...ln] and [m=m1...mn], then [l≃m] if and only if [forall 1<=i<=n, li≃mi]. *) Fixpoint semeq_list (l1 l2 : list S) := match (l1,l2) with | ([],[]) => True | (a::l1,b::l2) => (a≃b) /\ semeq_list l1 l2 | (_::_,[]) | ([],_::_) => False end. Instance SemEquiv_listS : SemEquiv (list S) := semeq_list. (* begin hide *) Global Instance cons_sequiv : Proper (sequiv ==> sequiv ==> sequiv) cons. Proof. intros x y E l m E'. unfold sequiv,SemEquiv_listS in *;simpl;tauto. Qed. Global Instance app_sequiv : Proper (sequiv ==> sequiv ==> sequiv) (@app S). Proof. intros x y E l m E'. unfold sequiv,SemEquiv_listS in *. revert y E;induction x as [|a x];intros [|b y];simpl;try tauto. intros (h1&h2);split;[tauto|apply IHx,h2]. Qed. Global Instance length_sequiv : Proper (sequiv ==> eq) (@length S). Proof. intros x y E. unfold sequiv,SemEquiv_listS in *. revert y E;induction x as [|a x];intros [|b y];simpl;try tauto. intros (h1&h2);rewrite (IHx y);reflexivity||assumption. Qed. (* end hide *) (** It is a simple matter to check that the operations we have defined indeed define a nominal setoid structure over [list S]. *) Global Instance NominalSetoid_list : NominalSetoid A (list S). Proof. split. - unfold sequiv,SemEquiv_listS;split. + intros l;induction l as [|a l];simpl. * tauto. * split;[reflexivity|assumption]. + intros l1;induction l1 as [|a l1];intros [|b l2];simpl;try tauto. intros (->&h);intuition. + intros l1;induction l1 as [|a l1];intros [|b l2] [|c l3];simpl;try tauto. intros (->&h1) (->&h2);split;[reflexivity|]. apply (IHl1 l2 l3);assumption. - unfold sequiv,SemEquiv_listS;intros l1;induction l1 as [|a l1];intros [|b l2];simpl; try tauto||reflexivity. intros (e&h);apply IHl1 in h;revert h. unfold suppoid,SupportSetoidList;simpl. repeat rewrite undup_equivalent;intros ->. rewrite (eq_support e);reflexivity. - intros π l1;unfold sequiv,SemEquiv_listS;induction l1 as [|a l1];intros [|b l2];simpl; try tauto. intros (->&e);split;[reflexivity|]. apply IHl1,e. - unfold sequiv,SemEquiv_listS;unfold suppoid,SupportSetoidList in *;simpl. intros x p h; unfold actoid,actoid_lists in *. unfold act,act_lists in h;rewrite <- map_undup_id in h. induction x as [|x l];auto. + reflexivity. + revert h;simpl;rewrite map_app;intro E;apply length_app in E as (E1&E2). * split;[|apply IHl,E2]. apply action_invariant_eq,E1. * apply map_length. - unfold act,act_lists,actoid,actoid_lists,suppoid,SupportSetoidList,sequiv,SemEquiv_listS in *. intros x p;symmetry;simpl in *. rewrite map_undup_inj;eauto using perm_inj. repeat rewrite flat_map_concat_map. rewrite concat_map,map_map,map_map,undup_equivalent,undup_equivalent. intros a;repeat rewrite <- flat_map_concat_map,in_flat_map. setoid_rewrite support_action_eq;unfold act at 2,act_lists;tauto. - intros;unfold actoid,actoid_lists. rewrite map_map. unfold sequiv,SemEquiv_listS;induction x as [|a x];simpl;[tauto|split;[|apply IHx]]. apply action_compose_eq. Qed. (* begin hide *) Remark suppoid_cons b w : ⌈b::w⌉ ≈ ⌈b⌉ ++ ⌈w⌉. Proof. intro a;unfold suppoid,SupportSetoidList. repeat rewrite undup_equivalent. simpl;simpl_In;tauto. Qed. Remark suppoid_app w1 w2 : ⌈w1++w2⌉ ≈ ⌈w1⌉ ++ ⌈w2⌉. Proof. intro a;unfold suppoid,SupportSetoidList. repeat rewrite undup_equivalent. rewrite flat_map_concat_map,map_app,concat_app,<-flat_map_concat_map,<-flat_map_concat_map. reflexivity. Qed. (* end hide *) End list.
TQC Machu Scratching Tool to perform a Machu test (corrosion test) with. Each tool is provided with a 1mm width cutter to cut the coating down to the metal, complying with ISO 17872. The TQC Machu Scratching Tool Basic is based on the CC2000 model. with a self positioning knife bracket to expose the substrate with a perpendicular cut through the coating. The TQC Machu Scratching Tool Professional is based on the CC3000 model with adjustable cutting depth and two ball bearings to guide the cut. This guarantees reproducible results. Mandatory test in Qualicoat and QIB accredited laboratories.
[STATEMENT] lemma parts_insert_subset_impl: "\<lbrakk>x \<in> parts (insert a G); x \<in> parts G \<Longrightarrow> x \<in> synth (parts H); a \<in> synth (parts H)\<rbrakk> \<Longrightarrow> x \<in> synth (parts H)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>x \<in> parts (insert a G); x \<in> parts G \<Longrightarrow> x \<in> synth (parts H); a \<in> synth (parts H)\<rbrakk> \<Longrightarrow> x \<in> synth (parts H) [PROOF STEP] using Fake_parts_sing in_parts_UnE insert_is_Un parts_idem parts_synth subsetCE sup.absorb2 synth_idem synth_increasing [PROOF STATE] proof (prove) using this: ?X \<in> synth (analz ?H) \<Longrightarrow> parts {?X} \<subseteq> synth (analz ?H) \<union> parts ?H \<lbrakk>?c \<in> parts (?G \<union> ?H); ?c \<in> parts ?G \<Longrightarrow> ?P; ?c \<in> parts ?H \<Longrightarrow> ?P\<rbrakk> \<Longrightarrow> ?P insert ?a ?A = {?a} \<union> ?A parts (parts ?H) = parts ?H parts (synth ?H) = parts ?H \<union> synth ?H \<lbrakk>?A \<subseteq> ?B; ?c \<notin> ?A \<Longrightarrow> ?P; ?c \<in> ?B \<Longrightarrow> ?P\<rbrakk> \<Longrightarrow> ?P ?a \<le> ?b \<Longrightarrow> sup ?a ?b = ?b synth (synth ?H) = synth ?H ?H \<subseteq> synth ?H goal (1 subgoal): 1. \<lbrakk>x \<in> parts (insert a G); x \<in> parts G \<Longrightarrow> x \<in> synth (parts H); a \<in> synth (parts H)\<rbrakk> \<Longrightarrow> x \<in> synth (parts H) [PROOF STEP] by (metis (no_types, lifting) analz_parts)
#redirect Filmmakers Ambitions (No longer active)
module BBHeap.Properties {A : Set}(_≤_ : A → A → Set) where open import BBHeap _≤_ open import BBHeap.Perfect _≤_ open import Bound.Lower A open import Bound.Lower.Order _≤_ open import Data.Empty sym≃ : {b b' : Bound}{h : BBHeap b}{h' : BBHeap b'} → h ≃ h' → h' ≃ h sym≃ ≃lf = ≃lf sym≃ (≃nd b≤x b'≤x' l⋘r l'⋘r' l≃r l'≃r' l≃l') = ≃nd b'≤x' b≤x l'⋘r' l⋘r l'≃r' l≃r (sym≃ l≃l') trans≃ : {b b' b'' : Bound}{h : BBHeap b}{h' : BBHeap b'}{h'' : BBHeap b''} → h ≃ h' → h' ≃ h'' → h ≃ h'' trans≃ ≃lf ≃lf = ≃lf trans≃ (≃nd b≤x b'≤x' l⋘r l'⋘r' l≃r _ l≃l') (≃nd .b'≤x' b''≤x'' .l'⋘r' l''⋘r'' _ l''≃r'' l'≃l'') = ≃nd b≤x b''≤x'' l⋘r l''⋘r'' l≃r l''≃r'' (trans≃ l≃l' l'≃l'') lemma≃ : {b b' : Bound}{h : BBHeap b}{h' : BBHeap b'} → h ≃ h' → h ⋘ h' lemma≃ ≃lf = lf⋘ lemma≃ (≃nd b≤x b'≤x' l⋘r l'⋘r' l≃r l'≃r' l≃l') = ll⋘ b≤x b'≤x' l⋘r l'⋘r' l'≃r' (trans≃ (sym≃ l≃r) l≃l') lemma⋗≃ : {b b' b'' : Bound}{h : BBHeap b}{h' : BBHeap b'}{h'' : BBHeap b''} → h ⋗ h' → h' ≃ h'' → h ⋗ h'' lemma⋗≃ (⋗lf b≤x) ≃lf = ⋗lf b≤x lemma⋗≃ (⋗nd b≤x b'≤x' l⋘r l'⋘r' l≃r _ l⋗l') (≃nd .b'≤x' b''≤x'' .l'⋘r' l''⋘r'' _ l''≃r'' l'≃l'') = ⋗nd b≤x b''≤x'' l⋘r l''⋘r'' l≃r l''≃r'' (lemma⋗≃ l⋗l' l'≃l'') lemma⋗ : {b b' : Bound}{h : BBHeap b}{h' : BBHeap b'} → h ⋗ h' → h ⋙ h' lemma⋗ (⋗lf b≤x) = ⋙lf b≤x lemma⋗ (⋗nd b≤x b'≤x' l⋘r l'⋘r' l≃r l'≃r' l⋗l') = ⋙rl b≤x b'≤x' l⋘r l≃r l'⋘r' (lemma⋗≃ l⋗l' l'≃r') lemma⋗⋗ : {b b' b'' : Bound}{h : BBHeap b}{h' : BBHeap b'}{h'' : BBHeap b''} → h ⋗ h' → h'' ⋗ h' → h ≃ h'' lemma⋗⋗ (⋗lf b≤x) (⋗lf b''≤x'') = ≃nd b≤x b''≤x'' lf⋘ lf⋘ ≃lf ≃lf ≃lf lemma⋗⋗ (⋗nd b≤x b'≤x' l⋘r l'⋘r' l≃r _ l⋗l') (⋗nd b''≤x'' .b'≤x' l''⋘r'' .l'⋘r' l''≃r'' _ l''⋗l') = ≃nd b≤x b''≤x'' l⋘r l''⋘r'' l≃r l''≃r'' (lemma⋗⋗ l⋗l' l''⋗l') lemma⋗⋗' : {b b' b'' : Bound}{h : BBHeap b}{h' : BBHeap b'}{h'' : BBHeap b''} → h ⋗ h' → h ⋗ h'' → h' ≃ h'' lemma⋗⋗' (⋗lf b≤x) (⋗nd .b≤x _ .lf⋘ _ _ _ ()) lemma⋗⋗' (⋗nd .b≤x _ .lf⋘ _ _ _ ()) (⋗lf b≤x) lemma⋗⋗' (⋗lf b≤x) (⋗lf .b≤x) = ≃lf lemma⋗⋗' (⋗nd b≤x b'≤x' l⋘r l'⋘r' _ l'≃r' l⋗l') (⋗nd .b≤x b''≤x'' .l⋘r l''⋘r'' _ l''≃r'' l⋗l'') = ≃nd b'≤x' b''≤x'' l'⋘r' l''⋘r'' l'≃r' l''≃r'' (lemma⋗⋗' l⋗l' l⋗l'') lemma≃⋗ : {b b' b'' : Bound}{h : BBHeap b}{h' : BBHeap b'}{h'' : BBHeap b''} → h ≃ h' → h' ⋗ h'' → h ⋗ h'' lemma≃⋗ (≃nd b≤x b'≤x' l⋘r l'⋘r' l≃r _ l≃l') (⋗nd .b'≤x' b''≤x'' .l'⋘r' l''⋘r'' _ l''≃r'' l'⋗l'') = ⋗nd b≤x b''≤x'' l⋘r l''⋘r'' l≃r l''≃r'' (lemma≃⋗ l≃l' l'⋗l'') lemma≃⋗ (≃nd b≤x b'≤x' lf⋘ lf⋘ ≃lf ≃lf ≃lf) (⋗lf .b'≤x') = ⋗lf b≤x lemma-⋘-≃ : {b b' b'' : Bound}{h : BBHeap b}{h' : BBHeap b'}{h'' : BBHeap b''} → h ⋘ h' → h' ≃ h'' → h ⋘ h'' lemma-⋘-≃ lf⋘ ≃lf = lf⋘ lemma-⋘-≃ (ll⋘ b≤x b'≤x' l⋘r l'⋘r' _ r≃l') (≃nd .b'≤x' b''≤x'' .l'⋘r' l''⋘r'' _ l''≃r'' l'≃l'') = ll⋘ b≤x b''≤x'' l⋘r l''⋘r'' l''≃r'' (trans≃ r≃l' l'≃l'') lemma-⋘-≃ (lr⋘ b≤x b'≤x' l⋙r l'⋘r' _ l⋗l') (≃nd .b'≤x' b''≤x'' .l'⋘r' l''⋘r'' _ l''≃r'' l'≃l'') = lr⋘ b≤x b''≤x'' l⋙r l''⋘r'' l''≃r'' (lemma⋗≃ l⋗l' l'≃l'') lemma-≃-⋙ : {b b' b'' : Bound}{h : BBHeap b}{h' : BBHeap b'}{h'' : BBHeap b''} → h ≃ h' → h' ⋙ h'' → h ⋙ h'' lemma-≃-⋙ (≃nd b≤x b'≤x' lf⋘ lf⋘ ≃lf ≃lf ≃lf) (⋙lf .b'≤x') = ⋙lf b≤x lemma-≃-⋙ (≃nd b≤x b'≤x' l⋘r l'⋘r' l≃r _ l≃l') (⋙rl .b'≤x' b''≤x'' .l'⋘r' _ l''⋘r'' l'⋗r'') = ⋙rl b≤x b''≤x'' l⋘r l≃r l''⋘r'' (lemma≃⋗ l≃l' l'⋗r'') lemma-≃-⋙ (≃nd b≤x b'≤x' l⋘r l'⋘r' l≃r _ l≃l') (⋙rr .b'≤x' b''≤x'' .l'⋘r' _ l''⋙r'' l'≃l'') = ⋙rr b≤x b''≤x'' l⋘r l≃r l''⋙r'' (trans≃ l≃l' l'≃l'') lemma-⋘-⋗ : {b b' b'' : Bound}{h : BBHeap b}{h' : BBHeap b'}{h'' : BBHeap b''} → h ⋘ h' → h'' ⋗ h' → h'' ⋙ h lemma-⋘-⋗ lf⋘ (⋗lf b≤x) = ⋙lf b≤x lemma-⋘-⋗ (ll⋘ b≤x b'≤x' l⋘r l'⋘r' _ r≃l') (⋗nd b''≤x'' .b'≤x' l''⋘r'' .l'⋘r' l''≃r'' _ l''⋗l') = ⋙rl b''≤x'' b≤x l''⋘r'' l''≃r'' l⋘r (lemma⋗≃ l''⋗l' (sym≃ r≃l')) lemma-⋘-⋗ (lr⋘ b≤x b'≤x' l⋙r l'⋘r' _ l⋗l') (⋗nd b''≤x'' .b'≤x' l''⋘r'' .l'⋘r' l''≃r'' _ l''⋗l') = ⋙rr b''≤x'' b≤x l''⋘r'' l''≃r'' l⋙r (lemma⋗⋗ l''⋗l' l⋗l') lemma-≃-⊥ : {b b' : Bound}{h : BBHeap b}{h' : BBHeap b'} → h ≃ h' → h ⋗ h' → ⊥ lemma-≃-⊥ () (⋗lf _) lemma-≃-⊥ (≃nd .b≤x .b'≤x' .l⋘r .l'⋘r' _ _ l≃l') (⋗nd b≤x b'≤x' l⋘r l'⋘r' l≃r l'≃r' l⋗l') with lemma-≃-⊥ l≃l' l⋗l' ... | () lemma-⋘-⊥ : {b b' : Bound}{x x' : A}{l r : BBHeap (val x)}{l' r' : BBHeap (val x')}(b≤x : LeB b (val x))(b'≤x' : LeB b' (val x'))(l⋙r : l ⋙ r)(l'⋘r' : l' ⋘ r') → l ≃ l' → right b≤x l⋙r ⋘ left b'≤x' l'⋘r' → ⊥ lemma-⋘-⊥ b≤x b'≤x' l⋙r l'⋘r' l≃l' (lr⋘ .b≤x .b'≤x' .l⋙r .l'⋘r' _ l⋗l') with lemma-≃-⊥ l≃l' l⋗l' ... | () lemma-perfect : {b b' : Bound}{h : BBHeap b}{h' : BBHeap b'} → h ⋘ h' → Perfect h' lemma-perfect lf⋘ = plf lemma-perfect (ll⋘ b≤x b'≤x' l⋘l l'⋘l' l'≃r' r≃l') = pnd b'≤x' l'⋘l' l'≃r' lemma-perfect (lr⋘ b≤x b'≤x' l⋙r l'⋘l' l'≃r' l⋗l') = pnd b'≤x' l'⋘l' l'≃r'
State Before: G : Type u_2 M : Type ?u.82889 α : Type u_1 s : Set α m : MeasurableSpace α inst✝⁴ : Group G inst✝³ : MulAction G α inst✝² : MeasurableSpace G inst✝¹ : MeasurableSMul G α c : G μ : Measure α inst✝ : SMulInvariantMeasure G α μ x y : G hs : x • s =ᶠ[ae μ] s hy : y ∈ Subgroup.zpowers x ⊢ y • s =ᶠ[ae μ] s State After: case intro G : Type u_2 M : Type ?u.82889 α : Type u_1 s : Set α m : MeasurableSpace α inst✝⁴ : Group G inst✝³ : MulAction G α inst✝² : MeasurableSpace G inst✝¹ : MeasurableSMul G α c : G μ : Measure α inst✝ : SMulInvariantMeasure G α μ x : G hs : x • s =ᶠ[ae μ] s k : ℤ hy : x ^ k ∈ Subgroup.zpowers x ⊢ x ^ k • s =ᶠ[ae μ] s Tactic: obtain ⟨k, rfl⟩ := Subgroup.mem_zpowers_iff.mp hy State Before: case intro G : Type u_2 M : Type ?u.82889 α : Type u_1 s : Set α m : MeasurableSpace α inst✝⁴ : Group G inst✝³ : MulAction G α inst✝² : MeasurableSpace G inst✝¹ : MeasurableSMul G α c : G μ : Measure α inst✝ : SMulInvariantMeasure G α μ x : G hs : x • s =ᶠ[ae μ] s k : ℤ hy : x ^ k ∈ Subgroup.zpowers x ⊢ x ^ k • s =ᶠ[ae μ] s State After: case intro G : Type u_2 M : Type ?u.82889 α : Type u_1 s : Set α m : MeasurableSpace α inst✝⁴ : Group G inst✝³ : MulAction G α inst✝² : MeasurableSpace G inst✝¹ : MeasurableSMul G α c : G μ : Measure α inst✝ : SMulInvariantMeasure G α μ x : G hs : x • s =ᶠ[ae μ] s k : ℤ hy : x ^ k ∈ Subgroup.zpowers x e : α ≃ α := ↑(MulAction.toPermHom G α) x ⊢ x ^ k • s =ᶠ[ae μ] s Tactic: let e : α ≃ α := MulAction.toPermHom G α x State Before: case intro G : Type u_2 M : Type ?u.82889 α : Type u_1 s : Set α m : MeasurableSpace α inst✝⁴ : Group G inst✝³ : MulAction G α inst✝² : MeasurableSpace G inst✝¹ : MeasurableSMul G α c : G μ : Measure α inst✝ : SMulInvariantMeasure G α μ x : G hs : x • s =ᶠ[ae μ] s k : ℤ hy : x ^ k ∈ Subgroup.zpowers x e : α ≃ α := ↑(MulAction.toPermHom G α) x ⊢ x ^ k • s =ᶠ[ae μ] s State After: case intro G : Type u_2 M : Type ?u.82889 α : Type u_1 s : Set α m : MeasurableSpace α inst✝⁴ : Group G inst✝³ : MulAction G α inst✝² : MeasurableSpace G inst✝¹ : MeasurableSMul G α c : G μ : Measure α inst✝ : SMulInvariantMeasure G α μ x : G hs : x • s =ᶠ[ae μ] s k : ℤ hy : x ^ k ∈ Subgroup.zpowers x e : α ≃ α := ↑(MulAction.toPermHom G α) x he : QuasiMeasurePreserving ↑e ⊢ x ^ k • s =ᶠ[ae μ] s Tactic: have he : QuasiMeasurePreserving e μ μ := (measurePreserving_smul x μ).quasiMeasurePreserving State Before: case intro G : Type u_2 M : Type ?u.82889 α : Type u_1 s : Set α m : MeasurableSpace α inst✝⁴ : Group G inst✝³ : MulAction G α inst✝² : MeasurableSpace G inst✝¹ : MeasurableSMul G α c : G μ : Measure α inst✝ : SMulInvariantMeasure G α μ x : G hs : x • s =ᶠ[ae μ] s k : ℤ hy : x ^ k ∈ Subgroup.zpowers x e : α ≃ α := ↑(MulAction.toPermHom G α) x he : QuasiMeasurePreserving ↑e ⊢ x ^ k • s =ᶠ[ae μ] s State After: case intro G : Type u_2 M : Type ?u.82889 α : Type u_1 s : Set α m : MeasurableSpace α inst✝⁴ : Group G inst✝³ : MulAction G α inst✝² : MeasurableSpace G inst✝¹ : MeasurableSMul G α c : G μ : Measure α inst✝ : SMulInvariantMeasure G α μ x : G hs : x • s =ᶠ[ae μ] s k : ℤ hy : x ^ k ∈ Subgroup.zpowers x e : α ≃ α := ↑(MulAction.toPermHom G α) x he : QuasiMeasurePreserving ↑e he' : QuasiMeasurePreserving ↑e.symm ⊢ x ^ k • s =ᶠ[ae μ] s Tactic: have he' : QuasiMeasurePreserving e.symm μ μ := (measurePreserving_smul x⁻¹ μ).quasiMeasurePreserving State Before: case intro G : Type u_2 M : Type ?u.82889 α : Type u_1 s : Set α m : MeasurableSpace α inst✝⁴ : Group G inst✝³ : MulAction G α inst✝² : MeasurableSpace G inst✝¹ : MeasurableSMul G α c : G μ : Measure α inst✝ : SMulInvariantMeasure G α μ x : G hs : x • s =ᶠ[ae μ] s k : ℤ hy : x ^ k ∈ Subgroup.zpowers x e : α ≃ α := ↑(MulAction.toPermHom G α) x he : QuasiMeasurePreserving ↑e he' : QuasiMeasurePreserving ↑e.symm ⊢ x ^ k • s =ᶠ[ae μ] s State After: case intro G : Type u_2 M : Type ?u.82889 α : Type u_1 s : Set α m : MeasurableSpace α inst✝⁴ : Group G inst✝³ : MulAction G α inst✝² : MeasurableSpace G inst✝¹ : MeasurableSMul G α c : G μ : Measure α inst✝ : SMulInvariantMeasure G α μ x : G hs : x • s =ᶠ[ae μ] s k : ℤ hy : x ^ k ∈ Subgroup.zpowers x e : α ≃ α := ↑(MulAction.toPermHom G α) x he : QuasiMeasurePreserving ↑e he' : QuasiMeasurePreserving ↑e.symm h : ↑(e ^ k) '' s =ᶠ[ae μ] s ⊢ x ^ k • s =ᶠ[ae μ] s Tactic: have h := he.image_zpow_ae_eq he' k hs State Before: case intro G : Type u_2 M : Type ?u.82889 α : Type u_1 s : Set α m : MeasurableSpace α inst✝⁴ : Group G inst✝³ : MulAction G α inst✝² : MeasurableSpace G inst✝¹ : MeasurableSMul G α c : G μ : Measure α inst✝ : SMulInvariantMeasure G α μ x : G hs : x • s =ᶠ[ae μ] s k : ℤ hy : x ^ k ∈ Subgroup.zpowers x e : α ≃ α := ↑(MulAction.toPermHom G α) x he : QuasiMeasurePreserving ↑e he' : QuasiMeasurePreserving ↑e.symm h : ↑(e ^ k) '' s =ᶠ[ae μ] s ⊢ x ^ k • s =ᶠ[ae μ] s State After: case intro G : Type u_2 M : Type ?u.82889 α : Type u_1 s : Set α m : MeasurableSpace α inst✝⁴ : Group G inst✝³ : MulAction G α inst✝² : MeasurableSpace G inst✝¹ : MeasurableSMul G α c : G μ : Measure α inst✝ : SMulInvariantMeasure G α μ x : G hs : x • s =ᶠ[ae μ] s k : ℤ hy : x ^ k ∈ Subgroup.zpowers x e : α ≃ α := ↑(MulAction.toPermHom G α) x he : QuasiMeasurePreserving ↑e he' : QuasiMeasurePreserving ↑e.symm h : (fun a => ↑(↑(MulAction.toPermHom G α) (x ^ k)) a) '' s =ᶠ[ae μ] s ⊢ x ^ k • s =ᶠ[ae μ] s Tactic: simp only [← MonoidHom.map_zpow] at h State Before: case intro G : Type u_2 M : Type ?u.82889 α : Type u_1 s : Set α m : MeasurableSpace α inst✝⁴ : Group G inst✝³ : MulAction G α inst✝² : MeasurableSpace G inst✝¹ : MeasurableSMul G α c : G μ : Measure α inst✝ : SMulInvariantMeasure G α μ x : G hs : x • s =ᶠ[ae μ] s k : ℤ hy : x ^ k ∈ Subgroup.zpowers x e : α ≃ α := ↑(MulAction.toPermHom G α) x he : QuasiMeasurePreserving ↑e he' : QuasiMeasurePreserving ↑e.symm h : (fun a => ↑(↑(MulAction.toPermHom G α) (x ^ k)) a) '' s =ᶠ[ae μ] s ⊢ x ^ k • s =ᶠ[ae μ] s State After: no goals Tactic: simpa only [MulAction.toPermHom_apply, MulAction.toPerm_apply, image_smul] using h