Datasets:
AI4M
/

text
stringlengths
0
3.34M
### INSTRUCTIONS ## ## ## Run this script with ## On Windows ## source('~/Engineering/GitHub_repos/R-setup/setup.r') ## On Chromebook ## source('~/GitHub_repos/R-setup/setup.r') ## On Colab ## Not sure yet. Likely need to run under Python to access Google Drive. ## GitHub repo with setup.r file is here: ## /content/gdrive/MyDrive/Colab Notebooks/github_dhjelmar/R-setup/modules ## ## What it does ## ## Load libraries, but first need to install packages (more details below) ## In terminal, install packages with following if using conda ## conda install r-essentials ## conda install r-plotly ## ## Source local .r and .R scripts ## Some of these are R packages that wold not install with conda ## Some of these are R functions I wrote #---------------------------------------------------------------------------- ## identify operating system os <- .Platform$OS.type ### INSTALL PACKAGES ## Two options ## Install from terminal if using conda (this made installing rstudio easy but all packages not supported) ## Install inside R using (may be faster in R than rstudio), e.g.: ## install.packages("r-plotly") ### INSTALL PACKAGES WITH CONDA ## input following into terminal (or Anaconda Prompt) ## conda install r-essentials # not sure if this is needed ## conda install r-readxl ## conda install r-ggplot2 ## conda install r-plotly ## conda install r-RColorBrewer ## conda install r-dplyr ## conda install r-reticulate ## conda install r-matlib <-- worked on chromebook but windows required conda install -c conda-forge r-matlib ## conda install r-qualityTools <-- may have needed conda install -c conda-forge r-qualityTools ## ## Following list would not install so will source r functions instead ## conda install r-rgl ## conda install r-tolerance # finally available on ChromeOS in 8/2021 ## conda install r-IAPWS95 ## ## Following not tried with Conda but installed inside JL ## install.packages("DT") ## install.packages('tolerance') # worked on Windows in Rstudio ##---------------------------------------------------------------------------- #### LOAD LIBRARIES ## load packages ## following packages do not load on conda ## tolerance ## qualityTools ## plotly ## IAPWS95 ## rgl ## ## of the above, only would load inside R ## install.packages("qualityTools") ## may also have installed plotly inside R library(qualityTools) library(matlib) library(tibble) library(readxl) library(ggplot2) # alternative to base plots (used by plotly) library(plotly) # interactive plots library(RColorBrewer) # need if use brewer.pal color pallettes library(dplyr) # need for left_join(df1,df2,by="byvar") ## alternate to be more directly like match/index in Excel would be to use: ## parent_dataset[sub_dataset$ID,'column_name_of_value_you_want'] library(reticulate) # interface with Python (see https://datascienceplus.com/how-to-make-seaborn-pairplot-and-heatmap-in-r-write-python-in-r/) library(superml) ## library(FrF2) # fractional factorial design of experiments; will not install on chrome library(DT) library(stringi) # need for stri_split_fixed function library(stringr) # need for str_extract function library(tolerance) (.packages()) # shows packages that are loaded ##search() # little different from above but not sure how (includes more) ###---------------------------------------------------------------------------- ### Load local .R and .r files ## Source R packages that would not install with conda ## Instead, source for each of following was copied to ~/ProgramFiles/R_packages and using source to pull in .r and .R files ## library(qualityTools) # rnorm, dnorm, rweibull, dweibull, qqPlot (different from qqplot) ## library(rgl) # plot3d ## library(tolerance) # need for fitdistr ## library(IAPWS95) # water properties: hfT(T)=saturated liq enthalpy,h, in kJ/kg for temperature,T, in K ## hgT(T)=saturated steam enthalpy ## hTp(T,P) = enthalpy for given T and pressure, P ## TSatp(P) ## Tph(P,h) = Temperature for given P and h ## Note: Only qualityTools would install with intall.packages("qualityTools") but kept having to reinstall because library kept failing ## ## Source my own .r files in ~/RSTUDIO/modules ## source all files in specified folders herein if (os == "windows") { setup.path <- c("~/Programs/GitHub_home/R-setup/modules") } else if (os == 'unix') { setup.path <- c("~/GitHub_repos/R-setup/modules", ##"~/ProgramFiles/R_packages/tolerance/R", # now available on ChromeOS "~/ProgramFiles/R_packages/rgl/R" ) } else { # assume Colab (.Platform returns NULL) setup.path <- c("/content/gdrive/MyDrive/Colab Notebooks/github_dhjelmar/R-setup/modules") } r_files <- list.files(setup.path, pattern="*.[rR]$", full.names=TRUE) for (f in r_files) { ## cat("f =",f,"\n") source(f) }
#pragma once #include <bitset> #include <type_traits> #include <thrust/execution_policy.h> #include <thrust/gather.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/scatter.h> #include <cuda/define_specifiers.hpp> #include <gsl-lite/gsl-lite.hpp> #include <thrustshift/bit.h> #include <thrustshift/gather.h> #include <thrustshift/managed-vector.h> #include <thrustshift/not-a-vector.h> #include <thrustshift/scatter.h> namespace thrustshift { namespace permutation { /*! \brief Return \f$ P_b P_a^T \f$ * * \param result `result[i]` is the index of element \f$ a_i \f$ * after permutation \f$ P_b \f$ is applied to the natural order. */ template <class PermutationA, class PermutationB, class ResultPermutation, class MemoryResource> void multiply(PermutationA&& a, PermutationB&& b, ResultPermutation&& result, MemoryResource& memory_resource) { gsl_Expects(a.size() == b.size()); gsl_Expects(result.size() == a.size()); using ResultIndex = typename std::remove_reference<ResultPermutation>::type::value_type; auto [__, tmp] = make_not_a_vector_and_span<ResultIndex>(result.size(), memory_resource); auto cit_begin = thrust::make_counting_iterator(ResultIndex(0)); auto cit_end = thrust::make_counting_iterator( gsl_lite::narrow<ResultIndex>(result.size())); // Rather use `.data()` in case the iterator class is not defined // in device code thrust::scatter(thrust::device, cit_begin, cit_end, b.data(), tmp.data()); thrust::gather(thrust::device, a.data(), a.data() + a.size(), tmp.data(), result.data()); } /*! \brief Multiply successive permutations * * Assume you have \f$N\f$ permutations \f$P_{N-1},...,P_0\f$ * and \f$N\f$ linear maps \f$M_{N-1},...,M_0\f$ where each * linear map \f$M_i\f$ operates on the new order described by * \f$P_i\f$ relatively to the natural order. If every * linear map is applied to a vector \f$x\f$ in natural order * it yields to: * * \f[ * P_{N-1}^T M_{N-1} P_{N-1} P_{N-2}^T M^{N-2} ... P_0^T M_0 P_0 x * \f] * * The \f$P_i\f$ permutation matrices are given in vectorial form \f$p_i\f$ * such that \f$(P_i)_mn = 1\f$ if \f$(p_i)_m = n\f$. * * \param input_permutations Range of size N with ranges of length L each * \param merged_permutations Range of size N - 1 with ranges of length L each. * merged_permutations[i] = \f$P_{i+1} P_{i}^T\f$ */ template <class InputPermutations, class MergedPermutations, class MemoryResource> void multiply_successive(InputPermutations&& input_permutations, MergedPermutations&& multiplied_permutations, MemoryResource& memory_resource) { const auto N = input_permutations.size(); if (N == 0) { return; } gsl_Expects(N > 0); gsl_Expects(N == multiplied_permutations.size() + 1); for (size_t i = 0; i < input_permutations.size() - 1; ++i) { multiply(input_permutations[i], input_permutations[i + 1], multiplied_permutations[i], memory_resource); } } /*! \brief Bitoptimized successive pairwise permutation * * This class saves a permutation of `I = {0,...,N-1}`, which * is created by successive pairwise swaps of the sequence `I`: * * ```cpp * for (int j = 1; j < N; ++j) { * if (do_swap[j - 1]) { * swap(I[j - 1], I[j]); * } * } * ``` * * The array `do_swap[]` saves if two values are swapped and is saved in * a bit pattern within this class. * This can also be seen as a path in a binary tree with `N` levels because * the internal representation is a bit pattern, which sets the bit if the * swap is not done. `N` is limited by the amount of Bits in `BitPatternT`. * If `operator[]` is called once, no function to change the `do_swap` * array should be called by the user. The state of the class is then a * read-only mode. Moreover the array `I` can only be read successively * by the `operator[]`. Thus reading the pattern starts with the last element * `i = N - 1` and in the next call `i = i - 1` must be used as a function argument. * This is an highly unsafe class design, which is chosen to avoid the * usage of additional registers. E.g. the safety of the class can be * greatly improved if one register is added, which is avoided here * due to performance reasons. * * \note When `std::bitset` is supported for device code. This should be * used to save the bit pattern * \note When compiled for device code CUDA currently supports built-in * function to count leading zeros `clz` for `int` and `long long int`, which * then must be used for `BitPatternT`. */ template <class BitPatternT> class bit_successive_permutation_t { public: CUDA_FHD bit_successive_permutation_t(int N) : bit_pattern_(BitPatternT(1) << (N - 1)) { gsl_Expects(N <= sizeof(BitPatternT) * 8); #ifndef NDEBUG N_ = N; #endif } CUDA_FHD void do_swap(int j) { gsl_Expects(j < sizeof(BitPatternT) * 8); #ifndef NDEBUG gsl_Expects(!read_only_mode_); gsl_Expects(j < N_ - 1); #endif bit_pattern_ &= ~(BitPatternT(1) << j); } CUDA_FHD void do_not_swap(int j) { gsl_Expects(j < sizeof(BitPatternT) * 8); #ifndef NDEBUG gsl_Expects(!read_only_mode_); gsl_Expects(j < N_ - 1); #endif bit_pattern_ |= (BitPatternT(1) << j); } CUDA_FHD void set(int j, bool do_swap_) { if (do_swap_) { do_swap(j); } else { do_not_swap(j); } } CUDA_FHD int operator[](int i) { gsl_Expects(i < sizeof(BitPatternT) * 8); #ifndef NDEBUG gsl_Expects(i < N_); if (!read_only_mode_) { read_only_mode_ = true; last_i_ = N_; } gsl_Expects(i == last_i_ - 1); last_i_ = i; #endif gsl_Expects(i >= 0); const bool flag = (1ll << i) & bit_pattern_; bit_pattern_ &= ~(1ll << i); if (flag) { const int lz = count_leading_zeros(bit_pattern_); return sizeof(BitPatternT) * 8 - lz; } else { return i + 1; } } private: #ifndef NDEBUG bool read_only_mode_ = false; int N_; int last_i_; #endif BitPatternT bit_pattern_; }; } // namespace permutation } // namespace thrustshift
module Category.Functor.Lawful where open import Agda.Primitive using (lsuc; _⊔_) open import Category.Functor open import Category.Applicative open import Function using (id; _∘_) open import Relation.Binary.PropositionalEquality using (_≡_; module ≡-Reasoning; sym; cong) record LawfulFunctorImp {l₁ l₂} {F : Set l₁ → Set l₂} (FFunc : RawFunctor F) : Set (lsuc l₁ ⊔ l₂) where open RawFunctor FFunc field <$>-identity : ∀ {a} {x : F a} → (id <$> x) ≡ x <$>-compose : ∀ {a b c} {f : a → b} {g : b → c} {x : F a} → ((g ∘ f) <$> x) ≡ (g <$> (f <$> x)) module LawfulFunctor {l₁ l₂} {F : Set l₁ → Set l₂} {FFunc : RawFunctor F} (FLawful : LawfulFunctorImp FFunc) where open RawFunctor FFunc public open LawfulFunctorImp FLawful public record LawfulApplicativeImp {l} {F : Set l → Set l} (FAppl : RawApplicative F) : Set (lsuc l) where open RawApplicative FAppl field ⊛-identity : ∀ {A} {u : F A} → (pure id ⊛ u) ≡ u ⊛-homomorphism : ∀ {A B} {u : A → B } {v : A} → (pure u ⊛ pure v) ≡ pure (u v) ⊛-interchange : ∀ {A B} {u : F (A → B)} {v : A} → (u ⊛ pure v) ≡ (pure (λ uᵢ → uᵢ v) ⊛ u) ⊛-composition : ∀ {A B C} {u : F (B → C)} {v : F (A → B)} {w : F A} → (pure (λ f g a → f (g a)) ⊛ u ⊛ v ⊛ w) ≡ (u ⊛ (v ⊛ w)) open ≡-Reasoning private composelemma : ∀ {a b c} {f : a → b} {g : b → c} {x : F a} → ((g ∘ f) <$> x) ≡ (g <$> (f <$> x)) composelemma {_} {_} {_} {f} {g} {x} = pure (λ x₁ → g (f x₁)) ⊛ x ≡⟨ cong (_⊛ x) (sym ⊛-homomorphism) ⟩ pure (λ f x → g (f x)) ⊛ pure f ⊛ x ≡⟨ cong ((_⊛ x) ∘ (_⊛ pure f)) (sym ⊛-homomorphism) ⟩ pure (λ g f x → g (f x)) ⊛ pure g ⊛ pure f ⊛ x ≡⟨ ⊛-composition ⟩ pure g ⊛ (pure f ⊛ x) ∎ isLawfulFunctor : LawfulFunctorImp rawFunctor isLawfulFunctor = record { <$>-identity = ⊛-identity ; <$>-compose = composelemma } module LawfulApplicative {l} {F : Set l → Set l} (FAppl : RawApplicative F) (FLawful : LawfulApplicativeImp FAppl) where open RawApplicative FAppl public open LawfulApplicativeImp FLawful public open LawfulFunctorImp isLawfulFunctor public
# Using built-in functions Incr := s -> String(Int(s) + 1); # Implementing addition # (but here 9...9 + 1 = 0...0 since the string length is fixed) Increment := function(s) local c, n, carry, digits; digits := "0123456789"; n := Length(s); carry := true; while n > 0 and carry do c := Position(digits, s[n]) - 1; if carry then c := c + 1; fi; if c > 9 then carry := true; c := c - 10; else carry := false; fi; s[n] := digits[c + 1]; n := n - 1; od; end; s := "2399"; Increment(s); s; # "2400"
(** Sharpened ADT for an expression grammar with parentheses *) Require Import Coq.Init.Wf Coq.Arith.Wf_nat. Require Import Coq.omega.Omega. Require Import Coq.Lists.List Coq.Strings.String. Require Import Coq.Numbers.Natural.Peano.NPeano. Require Import Fiat.Parsers.ContextFreeGrammar.Core. Require Import Fiat.Parsers.ContextFreeGrammar.PreNotations. Require Import Fiat.Parsers.ContextFreeGrammar.Equality. Require Import Coq.Program.Equality. Require Import Coq.MSets.MSetPositive. Require Import Fiat.Common. Require Import Fiat.Common.Equality. Require Import Fiat.Common.Wf. Require Import Fiat.Common.Enumerable. Require Import Fiat.Common.LogicFacts. Require Import Fiat.Parsers.Splitters.RDPList. Require Import Fiat.Parsers.Splitters.BruteForce. Require Import Fiat.Parsers.ParserInterface. Require Import Fiat.Parsers.BaseTypes. Require Import Fiat.Parsers.CorrectnessBaseTypes. Require Import Fiat.Parsers.BooleanRecognizerFull. Require Import Fiat.Parsers.BooleanRecognizerCorrect. Require Import Fiat.Common.List.Operations. Require Import Fiat.Parsers.StringLike.Core. Require Import Fiat.Parsers.StringLike.ForallChars. Require Import Fiat.Parsers.StringLike.FirstChar. Require Import Fiat.Parsers.StringLike.FirstCharSuchThat. Require Import Fiat.Parsers.StringLike.LastChar. Require Import Fiat.Parsers.StringLike.LastCharSuchThat. Require Import Fiat.Parsers.StringLike.Properties. Require Import Fiat.Parsers.MinimalParseOfParse. Require Import Fiat.Parsers.ContextFreeGrammar.Properties. Require Import Fiat.Parsers.ContextFreeGrammar.Fold. Require Import Fiat.Parsers.BaseTypesLemmas. Require Import Fiat.Parsers.ContextFreeGrammar.Valid. Require Import Fiat.Parsers.ContextFreeGrammar.ValidProperties. Require Import Fiat.Parsers.ContextFreeGrammar.ValidReflective. Require Import Fiat.Parsers.Refinement.DisjointLemmasEarlyDeclarations. Require Import Fiat.Parsers.Refinement.PossibleTerminalsSets. Require Import Fiat.Common.BoolFacts. Require Fiat.Parsers.Reachable.All.MinimalReachable. Require Fiat.Parsers.Reachable.All.MinimalReachableOfReachable. Require Fiat.Parsers.Reachable.All.ReachableParse. Require Fiat.Parsers.Reachable.OnlyFirst.MinimalReachable. Require Fiat.Parsers.Reachable.OnlyFirst.MinimalReachableOfReachable. Require Fiat.Parsers.Reachable.OnlyFirst.ReachableParse. Require Fiat.Parsers.Reachable.OnlyLast.MinimalReachable. Require Fiat.Parsers.Reachable.OnlyLast.MinimalReachableOfReachable. Require Fiat.Parsers.Reachable.OnlyLast.ReachableParse. Require Fiat.Parsers.Reachable.MaybeEmpty.Core. Require Fiat.Parsers.Reachable.MaybeEmpty.MinimalOfCore. Require Fiat.Parsers.Reachable.MaybeEmpty.OfParse. Set Implicit Arguments. Local Open Scope string_like_scope. Local Arguments string_beq : simpl never. Section search_forward. Context {G : pregrammar' Ascii.ascii} {HSLM : StringLikeMin Ascii.ascii} {HSL : StringLike Ascii.ascii} {HSI : StringIso Ascii.ascii} {HSLP : StringLikeProperties Ascii.ascii} {HSIP : StringIsoProperties Ascii.ascii} (pdata : possible_data G). Local Notation possible_terminals_of nt := (@all_possible_ascii_of_nt G pdata nt). Local Notation possible_first_terminals_of_production its := (@possible_first_ascii_of_production G pdata its). Local Notation might_be_empty_of_production its := (@might_be_empty_of_pr_production G pdata its). Lemma terminals_disjoint_search_for_not' (str : @String Ascii.ascii HSLM) {nt its} (H_disjoint : disjoint ascii_beq (possible_terminals_of nt) (possible_first_terminals_of_production its)) {n} (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt)) (pits : parse_of_production G (StringLike.drop n str) its) (H_reachable : production_is_reachable G (NonTerminal nt :: its)) : forall_chars__char_in (take n str) (possible_terminals_of nt) /\ ((length str <= n /\ might_be_empty_of_production its) \/ (for_first_char (drop n str) (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of nt))) /\ n < length str)). Proof. destruct H_reachable as [ nt' [ prefix [ HinV HinL ] ] ]. pose proof HinV as HinV'; rewrite <- (@initial_nonterminals_correct _ G (@rdp_list_predata _ G) (@rdp_list_rdata' _ G)) in HinV'. apply and_comm; split. { destruct (Compare_dec.le_dec (length str) n); [ left | right ]. { split; trivial. pose proof (drop_length str n) as H. rewrite (proj2 (Nat.sub_0_le (length str) n)) in H by assumption. generalize dependent (drop n str); clear -pit HinV' HinL HSLP HSIP. intros. eapply might_be_empty_pr_parse_of_production; eassumption. } { split; try omega; []. eapply first_char_in__impl__for_first_char; [ | apply possible_first_ascii_parse_of_production; eassumption ]. intros ch H'. apply Bool.negb_true_iff, Bool.not_true_iff_false. intro H''. apply list_in_bl in H''; [ | apply (@ascii_bl) ]. eapply fold_right_andb_map_in in H_disjoint; [ | eassumption ]. apply Bool.negb_true_iff, Bool.not_true_iff_false in H_disjoint. apply H_disjoint. apply list_in_lb; [ apply (@ascii_lb) | assumption ]. } } { apply (all_possible_ascii_of_item_nt pit). } Qed. Lemma terminals_disjoint_search_for_not (str : @String Ascii.ascii HSLM) {nt its} (H_disjoint : disjoint ascii_beq (possible_terminals_of nt) (possible_first_terminals_of_production its)) {n} (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt)) (pits : parse_of_production G (StringLike.drop n str) its) (H_reachable : production_is_reachable G (NonTerminal nt :: its)) : is_first_char_such_that (might_be_empty_of_production its) str n (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of nt))). Proof. pose proof (terminals_disjoint_search_for_not' _ H_disjoint pit pits H_reachable) as H. split; [ destruct H as [H0 H1] | destruct H as [H0 [[H1 H2] | H1]]; solve [ left; eauto | right; eauto ] ]. revert H0. apply forall_chars__char_in__impl__forall_chars. intros ch H' H''. apply Bool.negb_true_iff, Bool.not_true_iff_false in H''. apply H''. apply list_in_lb; [ apply (@ascii_lb) | ]; assumption. Qed. Lemma terminals_disjoint_search_for' (str : @String Ascii.ascii HSLM) {nt its} (H_disjoint : disjoint ascii_beq (possible_terminals_of nt) (possible_first_terminals_of_production its)) {n} (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt)) (pits : parse_of_production G (StringLike.drop n str) its) (H_reachable : production_is_reachable G (NonTerminal nt :: its)) : forall_chars (take n str) (fun ch => negb (list_bin ascii_beq ch (possible_first_terminals_of_production its))) /\ ((length str <= n /\ might_be_empty_of_production its) \/ (first_char_in (drop n str) (possible_first_terminals_of_production its) /\ n < length str)). Proof. destruct H_reachable as [ nt' [ prefix [ HinV HinL ] ] ]. pose proof HinV as HinV'; rewrite <- (@initial_nonterminals_correct _ G (@rdp_list_predata _ G) (@rdp_list_rdata' _ G)) in HinV'. apply and_comm; split. { destruct (Compare_dec.le_dec (length str) n); [ left | right ]. { split; trivial. pose proof (drop_length str n) as H. rewrite (proj2 (Nat.sub_0_le (length str) n)) in H by assumption. generalize dependent (drop n str); clear -pit HinV' HinL HSLP HSIP. intros. eapply might_be_empty_pr_parse_of_production; eassumption. } { split; try omega; try assumption. apply possible_first_ascii_parse_of_production; assumption. } } { eapply forall_chars__char_in__impl__forall_chars. { intros ch H'. apply Bool.negb_true_iff, Bool.not_true_iff_false. intro H''. apply list_in_bl in H''; [ | apply (@ascii_bl) ]. eapply fold_right_andb_map_in in H_disjoint; [ | eassumption ]. apply Bool.negb_true_iff, Bool.not_true_iff_false in H_disjoint. apply H_disjoint. apply list_in_lb; [ apply (@ascii_lb) | assumption ]. } { apply all_possible_ascii_of_item_nt; assumption. } } Qed. Lemma terminals_disjoint_search_for (str : @String Ascii.ascii HSLM) {nt its} (H_disjoint : disjoint ascii_beq (possible_terminals_of nt) (possible_first_terminals_of_production its)) {n} (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt)) (pits : parse_of_production G (StringLike.drop n str) its) (H_reachable : production_is_reachable G (NonTerminal nt :: its)) : is_first_char_such_that (might_be_empty_of_production its) str n (fun ch => list_bin ascii_beq ch (possible_first_terminals_of_production its)). Proof. pose proof (terminals_disjoint_search_for' _ H_disjoint pit pits H_reachable) as H. split; [ destruct H as [H0 H1] | destruct H as [H0 [[H1 H2] | [H1 ?]]]; [ right | left; split ]; eauto ]. { revert H0. apply forall_chars_Proper; [ reflexivity | ]. intros ch H' H''. apply Bool.negb_true_iff, Bool.not_true_iff_false in H'. apply H'. assumption. } { revert H1. apply first_char_in__impl__for_first_char. intros ch H'. apply list_in_lb; [ apply (@ascii_lb) | ]; assumption. } Qed. End search_forward. Section search_backward. Context {G : pregrammar' Ascii.ascii} {HSLM : StringLikeMin Ascii.ascii} {HSL : StringLike Ascii.ascii} {HSI : StringIso Ascii.ascii} {HSLP : StringLikeProperties Ascii.ascii} {HSIP : StringIsoProperties Ascii.ascii} (pdata : possible_data G). Local Notation possible_terminals_of_production its := (@all_possible_ascii_of_production G pdata its). Local Notation possible_last_terminals_of nt := (@possible_last_ascii_of_nt G pdata nt). Local Notation might_be_empty_of nt := (@might_be_empty_of_pr_nt G pdata nt). Lemma terminals_disjoint_rev_search_for_not' (str : @String Ascii.ascii HSLM) {nt its} (H_disjoint : disjoint ascii_beq (possible_last_terminals_of nt) (possible_terminals_of_production its)) {n} (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt)) (pits : parse_of_production G (StringLike.drop n str) its) (H_reachable : production_is_reachable G (NonTerminal nt :: its)) : forall_chars__char_in (drop n str) (possible_terminals_of_production its) /\ ((n = 0 /\ might_be_empty_of nt) \/ (for_last_char (take n str) (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of_production its))) /\ n > 0)). Proof. destruct H_reachable as [ nt' [ prefix [ HinV HinL ] ] ]. pose proof HinV as HinV'; rewrite <- (@initial_nonterminals_correct _ G (@rdp_list_predata _ G) (@rdp_list_rdata' _ G)) in HinV'. apply and_comm; split. { destruct (Compare_dec.zerop n); [ left | right ]. { split; trivial; []; subst. eapply might_be_empty_pr_parse_of_item_nt; try eassumption. rewrite take_length; reflexivity. } { split; try omega; []. eapply last_char_in__impl__for_last_char; [ | apply possible_last_ascii_parse_of_item_nt; eassumption ]. intros ch H'. apply Bool.negb_true_iff, Bool.not_true_iff_false. intro H''. apply list_in_bl in H''; [ | apply (@ascii_bl) ]. eapply fold_right_andb_map_in in H_disjoint; [ | eassumption ]. apply Bool.negb_true_iff, Bool.not_true_iff_false in H_disjoint. apply H_disjoint. apply list_in_lb; [ apply (@ascii_lb) | assumption ]. } } { apply all_possible_ascii_of_parse_of_production; assumption. } Qed. Lemma terminals_disjoint_rev_search_for_not (str : @String Ascii.ascii HSLM) {nt its} (H_disjoint : disjoint ascii_beq (possible_last_terminals_of nt) (possible_terminals_of_production its)) {n} (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt)) (pits : parse_of_production G (StringLike.drop n str) its) (H_reachable : production_is_reachable G (NonTerminal nt :: its)) : is_after_last_char_such_that str n (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of_production its))). Proof. pose proof (terminals_disjoint_rev_search_for_not' _ H_disjoint pit pits H_reachable) as H. split; [ destruct H as [H0 H1] | destruct H as [H0 [[H1 H2] | H1]]; destruct_head and; try solve [ left; eauto | right; eauto | assumption | apply for_last_char_nil; rewrite ?take_length; apply Min.min_case_strong; omega ] ]. revert H0. apply forall_chars__char_in__impl__forall_chars. intros ch H' H''. apply Bool.negb_true_iff, Bool.not_true_iff_false in H''. apply H''; clear H''. apply list_in_lb; [ apply (@ascii_lb) | ]; assumption. Qed. Lemma terminals_disjoint_rev_search_for' (str : @String Ascii.ascii HSLM) {nt its} (H_disjoint : disjoint ascii_beq (possible_last_terminals_of nt) (possible_terminals_of_production its)) {n} (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt)) (pits : parse_of_production G (StringLike.drop n str) its) (H_reachable : production_is_reachable G (NonTerminal nt :: its)) : forall_chars (drop n str) (fun ch => negb (list_bin ascii_beq ch (possible_last_terminals_of nt))) /\ ((n = 0 /\ might_be_empty_of nt) \/ (last_char_in (take n str) (possible_last_terminals_of nt) /\ n > 0)). Proof. destruct H_reachable as [ nt' [ prefix [ HinV HinL ] ] ]. pose proof HinV as HinV'; rewrite <- (@initial_nonterminals_correct _ G (@rdp_list_predata _ G) (@rdp_list_rdata' _ G)) in HinV'. apply and_comm; split. { destruct (Compare_dec.zerop n); [ left | right ]. { split; trivial; []. eapply might_be_empty_pr_parse_of_item_nt; try eassumption. rewrite take_length; subst; reflexivity. } { split; try omega; try assumption; []. apply possible_last_ascii_parse_of_item_nt; assumption. } } { eapply forall_chars__char_in__impl__forall_chars. { intros ch H'. apply Bool.negb_true_iff, Bool.not_true_iff_false. intro H''. apply list_in_bl in H''; [ | apply (@ascii_bl) ]. eapply fold_right_andb_map_in in H_disjoint; [ | eassumption ]. apply Bool.negb_true_iff, Bool.not_true_iff_false in H_disjoint. apply H_disjoint. apply list_in_lb; [ apply (@ascii_lb) | eassumption ]. } { apply all_possible_ascii_of_parse_of_production; assumption. } } Qed. Lemma terminals_disjoint_rev_search_for (str : @String Ascii.ascii HSLM) {nt its} (H_disjoint : disjoint ascii_beq (possible_last_terminals_of nt) (possible_terminals_of_production its)) {n} (pit : parse_of_item G (StringLike.take n str) (NonTerminal nt)) (pits : parse_of_production G (StringLike.drop n str) its) (H_reachable : production_is_reachable G (NonTerminal nt :: its)) : is_after_last_char_such_that str n (fun ch => list_bin ascii_beq ch (possible_last_terminals_of nt)). Proof. pose proof (terminals_disjoint_rev_search_for' _ H_disjoint pit pits H_reachable) as H. split; [ destruct H as [H0 H1] | destruct H as [H0 [[H1 H2] | [H1 ?]]]; try solve [ right; eauto | left; split; eauto | assumption | apply for_last_char_nil; rewrite ?take_length; apply Min.min_case_strong; omega ] ]. { revert H0. apply forall_chars_Proper; [ reflexivity | ]. intros ch H' H''. apply Bool.negb_true_iff, Bool.not_true_iff_false in H'. apply H'. assumption. } { revert H1. apply last_char_in__impl__for_last_char. intros ch H'. apply list_in_lb; [ apply (@ascii_lb) | ]; assumption. } Qed. End search_backward. Ltac get_grammar := lazymatch goal with | [ |- context[ParserInterface.split_list_is_complete_idx ?G] ] => G end. (*Ltac pose_rvalid_for G := lazymatch goal with | [ H : is_true (grammar_rvalid G) |- _ ] => idtac | _ => let Hvalid := fresh "Hvalid" in assert (Hvalid : is_true (grammar_rvalid G)) by (vm_compute; reflexivity) end. Ltac pose_rvalid := let G := get_grammar in pose_rvalid_for G.*) Module Export Exports. Export DisjointLemmasEarlyDeclarations. (** hide the arguments to Build_disjoint_search_data *) Local Arguments FromAbstractInterpretation.Build_fold_grammar_data' {_ _ _ _ _} _ _ : assert. Notation precomputed_search_data := (FromAbstractInterpretation.Build_fold_grammar_data' _ _). Ltac do_disjoint_precomputations _ ::= let G := get_grammar in lazymatch goal with | [ |- context[@ParserInterface.split_list_is_complete_idx _ G ?HSLM ?HSL] ] => pose (_ : @StringLikeProperties _ HSLM HSL) end; pose_possible_data_for G. End Exports.
# Decision Lens API # # No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # # OpenAPI spec version: 1.0 # # Generated by: https://github.com/swagger-api/swagger-codegen.git #' DataUpdatedMessagePayload Class #' #' @field message #' #' @importFrom R6 R6Class #' @importFrom jsonlite fromJSON toJSON #' @export DataUpdatedMessagePayload <- R6::R6Class( 'DataUpdatedMessagePayload', public = list( `message` = NULL, initialize = function(`message`){ if (!missing(`message`)) { stopifnot(is.character(`message`), length(`message`) == 1) self$`message` <- `message` } }, toJSON = function() { DataUpdatedMessagePayloadObject <- list() if (!is.null(self$`message`)) { DataUpdatedMessagePayloadObject[['message']] <- self$`message` } DataUpdatedMessagePayloadObject }, fromJSON = function(DataUpdatedMessagePayloadJson) { DataUpdatedMessagePayloadObject <- dlensFromJSON(DataUpdatedMessagePayloadJson) if (!is.null(DataUpdatedMessagePayloadObject$`message`)) { self$`message` <- DataUpdatedMessagePayloadObject$`message` } }, toJSONString = function() { sprintf( '{ "message": %s }', self$`message` ) }, fromJSONString = function(DataUpdatedMessagePayloadJson) { DataUpdatedMessagePayloadObject <- dlensFromJSON(DataUpdatedMessagePayloadJson) self$`message` <- DataUpdatedMessagePayloadObject$`message` } ) )
module filenames_mod implicit none character(len=20), parameter :: load_param_file_name = 'load_param.txt' character(len=20), parameter :: uel_stiffness_file_name = 'uel_stiffness.txt' character(len=20), parameter :: rp_node_coords_file_name = 'rp_coord.txt' end module filenames_mod
# Spectrum calculator for AtmosLES struct AtmosLESSpectraDiagnosticsParams <: DiagnosticsGroupParams nor::Float64 end """ setup_atmos_spectra_diagnostics( ::AtmosLESConfigType, interval::String, out_prefix::String; writer = NetCDFWriter(), interpol = nothing, nor = Inf, ) Create the "AtmosLESSpectra" `DiagnosticsGroup` which contains the following diagnostic variable: - spectrum: power spectrum from 3D velocity fields This variable is output with the `k` dimension (wave number) on an interpolated grid (`interpol` _must_ be specified) as well as a (unlimited) `time` dimension at the specified `interval`. """ function setup_atmos_spectra_diagnostics( ::AtmosLESConfigType, interval::String, out_prefix::String, nor::Float64; writer = NetCDFWriter(), interpol = nothing, ) @assert !isnothing(interpol) return DiagnosticsGroup( "AtmosLESSpectra", Diagnostics.atmos_les_spectra_init, Diagnostics.atmos_les_spectra_fini, Diagnostics.atmos_les_spectra_collect, interval, out_prefix, writer, interpol, AtmosLESSpectraDiagnosticsParams(nor), ) end function get_spectrum(mpicomm, mpirank, Q, bl, interpol, nor) FT = eltype(Q) istate = similar(Q.data, interpol.Npl, number_states(bl, Prognostic(), FT)) interpolate_local!(interpol, Q.data, istate) all_state_data = accumulate_interpolated_data(mpicomm, interpol, istate) if mpirank == 0 u = all_state_data[:, :, :, 2] ./ all_state_data[:, :, :, 1] v = all_state_data[:, :, :, 3] ./ all_state_data[:, :, :, 1] w = all_state_data[:, :, :, 4] ./ all_state_data[:, :, :, 1] x1 = Array(interpol.x1g) d = length(x1) s, k = power_spectrum_3d( AtmosLESConfigType(), u, v, w, x1[d] - x1[1], d, nor, ) return s, k end return nothing, nothing end function atmos_les_spectra_init(dgngrp, currtime) Q = Settings.Q bl = Settings.dg.balance_law mpicomm = Settings.mpicomm mpirank = MPI.Comm_rank(mpicomm) FT = eltype(Q) interpol = dgngrp.interpol nor = dgngrp.params.nor spectrum, wavenumber = get_spectrum(mpicomm, mpirank, Q, bl, interpol, nor) if mpirank == 0 dims = OrderedDict("k" => (wavenumber, Dict())) vars = OrderedDict("spectrum" => (("k",), FT, Dict())) dprefix = @sprintf("%s_%s", dgngrp.out_prefix, dgngrp.name) dfilename = joinpath(Settings.output_dir, dprefix) noov = Settings.no_overwrite init_data(dgngrp.writer, dfilename, noov, dims, vars) end return nothing end function atmos_les_spectra_collect(dgngrp, currtime) Q = Settings.Q bl = Settings.dg.balance_law mpicomm = Settings.mpicomm mpirank = MPI.Comm_rank(mpicomm) FT = eltype(Q) interpol = dgngrp.interpol nor = dgngrp.params.nor spectrum, _ = get_spectrum(mpicomm, mpirank, Q, bl, interpol, nor) if mpirank == 0 varvals = OrderedDict("spectrum" => spectrum) append_data(dgngrp.writer, varvals, currtime) end MPI.Barrier(mpicomm) return nothing end function atmos_les_spectra_fini(dgngrp, currtime) end
Inductive listn : nat -> Set := | niln : listn 0 | consn : forall n : nat, nat -> listn n -> listn (S n). Axiom ax : forall (n n' : nat) (l : listn (n + n')) (l' : listn (n' + n)), existS _ (n + n') l = existS _ (n' + n) l'. Lemma lem : forall (n n' : nat) (l : listn (n + n')) (l' : listn (n' + n)), n + n' = n' + n /\ existT _ (n + n') l = existT _ (n' + n) l'. Proof. intros n n' l l'. dependent rewrite (ax n n' l l'). split; reflexivity. Qed.
%CODEGENERATOR.GENSLBLOCKFKINE Generate Simulink block for forward kinematics % % cGen.genslblockfkine() generates a robot-specific Simulink block to compute % forward kinematics. % % Notes:: % - Is called by CodeGenerator.genfkine if cGen has active flag genslblock. % - The Simulink blocks are generated and stored in a robot specific block % library cGen.slib in the directory cGen.basepath. % - Blocks are created for intermediate transforms T0, T1 etc. as well. % % Author:: % Joern Malzahn, ([email protected]) % % See also CodeGenerator.CodeGenerator, CodeGenerator.genfkine. % Copyright (C) 2012-2014, by Joern Malzahn % % This file is part of The Robotics Toolbox for Matlab (RTB). % % RTB is free software: you can redistribute it and/or modify % it under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % RTB is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU Lesser General Public License for more details. % % You should have received a copy of the GNU Leser General Public License % along with RTB. If not, see <http://www.gnu.org/licenses/>. % % http://www.petercorke.com % % The code generation module emerged during the work on a project funded by % the German Research Foundation (DFG, BE1569/7-1). The authors gratefully % acknowledge the financial support. function genslblockfkine(CGen) %% Open or create block library bdclose('all') % avoid problems with previously loaded libraries load_system('simulink'); if ~(exist([CGen.slibpath,simulinkext]) == 2) % Create new block library if none exists CGen.createnewblocklibrary; end open_system(CGen.slibpath); set_param(CGen.slib,'lock','off'); q = CGen.rob.gencoords; %% Forward kinematics up to tool center point CGen.logmsg([datestr(now),'\tGenerating forward kinematics Simulink block up to the end-effector frame']); symname = 'fkine'; fname = fullfile(CGen.sympath,[symname,'.mat']); if exist(fname,'file') tmpStruct = load(fname); else error ('genslblockfkine:SymbolicsNotFound','Save symbolic expressions to disk first!') end blockaddress = [CGen.slib,'/',symname]; % treat intermediate transformations separately if ~isempty(find_system(CGen.slib,'SearchDepth',1,'Name',symname)) % Delete previously generated block delete_block(blockaddress); save_system; end symexpr2slblock(blockaddress,tmpStruct.(symname).T,'vars',{q}); CGen.logmsg('\t%s\n',' done!'); %% Individual joint forward kinematics CGen.logmsg([datestr(now),'\tGenerating forward kinematics Simulink block up to joint']); for iJoints=1:CGen.rob.n CGen.logmsg(' %i ',iJoints); symname = ['T0_',num2str(iJoints)]; fname = fullfile(CGen.sympath,[symname,'.mat']); tmpStruct = struct; tmpStruct = load(fname); funFileName = fullfile(CGen.robjpath,[symname,'.m']); q = CGen.rob.gencoords; blockaddress = [CGen.slib,'/',symname]; % treat intermediate transformations separately if doesblockexist(CGen.slib,symname) delete_block(blockaddress); save_system; end symexpr2slblock(blockaddress,tmpStruct.(symname).T,'vars',{q}); end CGen.logmsg('\t%s\n',' done!'); %% Cleanup % Arrange blocks distributeblocks(CGen.slib); % Lock, save and close library set_param(CGen.slib,'lock','on'); save_system(CGen.slib,CGen.slibpath); close_system(CGen.slib); end
%% Copyright (C) 2014-2016, 2022 Colin B. Macdonald %% %% This file is part of OctSymPy. %% %% OctSymPy is free software; you can redistribute it and/or modify %% it under the terms of the GNU General Public License as published %% by the Free Software Foundation; either version 3 of the License, %% or (at your option) any later version. %% %% This software 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 software; see the file COPYING. %% If not, see <http://www.gnu.org/licenses/>. %% -*- texinfo -*- %% @documentencoding UTF-8 %% @defmethod @@sym limit (@var{expr}, @var{x}, @var{a}, @var{dir}) %% @defmethodx @@sym limit (@var{expr}, @var{x}, @var{a}) %% @defmethodx @@sym limit (@var{expr}, @var{a}) %% @defmethodx @@sym limit (@var{expr}) %% Evaluate symbolic limits. %% %% The limit of @var{expr} as @var{x} tends to @var{a} from %% @var{dir}. @var{dir} can be @code{left} or @code{right}. %% %% Examples: %% @example %% @group %% syms x %% L = limit(sin(x)/x, x, 0) %% @result{} L = (sym) 1 %% L = limit(1/x, x, sym(inf)) %% @result{} L = (sym) 0 %% L = limit(1/x, x, 0, 'left') %% @result{} L = (sym) -∞ %% L = limit(1/x, x, 0, 'right') %% @result{} L = (sym) ∞ %% @end group %% @end example %% %% If @var{x} is omitted, @code{symvar} is used to determine the %% variable. If @var{a} is omitted, it defaults to 0. %% %% @var{dir} defaults to @code{right}. Note this is different from %% Matlab's Symbolic Math Toolbox which returns @code{NaN} for %% @code{limit(1/x, x, 0)} %% (and @code{+/-inf} if you specify @code{left/right}). I'm not %% sure how to get this nicer behaviour from SymPy. %% FIXME: this is https://github.com/cbm755/octsympy/issues/74 %% %% @seealso{@@sym/diff} %% @end defmethod function L = limit(f, x, a, dir) if (nargin > 4 || nargin < 1) print_usage (); end f = sym(f); if (nargin < 4) dir= 'right'; end if (nargin == 2) a = x; x = symvar(f, 1); end if (nargin == 1) x = symvar(f, 1); a = 0; end switch (lower (dir)) case {'left' '-'} pdir = '-'; case {'right' '+'} pdir = '+'; otherwise print_usage (); end if (isempty (x)) L = f; return end L = elementwise_op ('lambda f, x, a, dir: f.limit(x, a, dir=dir)', ... sym(f), sym(x), sym(a), pdir); end %!error limit (sym(1), 2, 3, 4, 5) %!shared x, oo %! syms x %! oo = sym(inf); %!assert (isa (limit(x, x, pi), 'sym')) %!assert (isequal (limit(x, x, pi), sym(pi))) %!assert (isequal (limit(sin(x)/x, x, 0), 1)) %!test %! % left/right-hand limit %! assert (isequal (limit(1/x, x, 0, 'right'), oo)) %! assert (isequal (limit(1/x, x, 0), oo)) %! assert (isequal (limit(1/x, x, 0, 'left'), -oo)) %! assert (isequal (limit(1/x, x, oo), 0)) %! assert (isequal (limit(sign(x), x, 0, 'left'), -1)) %! assert (isequal (limit(sign(x), x, 0, 'right'), 1)) %! assert (isequal (limit(sign(x), x, 0, '-'), -1)) %! assert (isequal (limit(sign(x), x, 0, '+'), 1)) %!test %! % matrix %! syms y %! A = [x 1/x x*y]; %! B = sym([3 sym(1)/3 3*y]); %! assert (isequal (limit(A, x, 3), B)) %!test %! % omitting arguments %! syms a %! assert (isequal (limit(a), 0)) %! assert (isequal (limit(a*x+a+2), a+2)) %! assert (isequal (limit(a*x+a+2, 6), 7*a+2)) %!test %! % constants %! assert (isequal (limit(sym(6)), 6)) %! assert (isequal (limit(sym(6), 7), 6)) %! assert (isequal (limit([sym(6) sym(2)], 7), [6 2])) %!test %! % double constant, with sym limit %! a = limit (6, sym(0)); %! assert (isa (a, 'sym')) %! assert (isequal (a, sym(6)))
/* * File: ralc.r * Contents: allocation routines */ /* * Prototypes. */ #ifdef Concurrent static struct region *findgap(struct region *curr_private, word nbytes, int region); #define INIT_SHARED(blk) blk->shared = 0 #else /* Concurrent */ static struct region *findgap (struct region *curr, word nbytes); #define INIT_SHARED(blk) #endif /* Concurrent */ extern word alcnum; #ifndef MultiProgram word coexp_ser = 2; /* serial numbers for co-expressions; &main is 1 */ word list_ser = 1; /* serial numbers for lists */ word intern_list_ser=-1;/* serial numbers for lists used internally by the RT system */ #ifdef PatternType word pat_ser = 1; /* serial numbers for patterns */ #endif /* PatternType */ word set_ser = 1; /* serial numbers for sets */ word table_ser = 1; /* serial numbers for tables */ #endif /* MultiProgram */ /* * AlcBlk - allocate a block. */ #begdef AlcBlk(var, struct_nm, t_code, nbytes) { /* * Ensure that there is enough room in the block region. */ if (DiffPtrs(blkend,blkfree) < nbytes && !reserve(Blocks, nbytes)) return NULL; /* * Decrement the free space in the block region by the number of bytes * allocated and return the address of the first byte of the allocated * block. */ blktotal += nbytes; var = (struct struct_nm *)blkfree; blkfree += nbytes; var->title = t_code; } #enddef /* * AlcFixBlk - allocate a fixed length block. */ #define AlcFixBlk(var, struct_nm, t_code)\ AlcBlk(var, struct_nm, t_code, sizeof(struct struct_nm)) /* * AlcVarBlk - allocate a variable-length block. */ #begdef AlcVarBlk(var, struct_nm, t_code, n_desc) { uword size; /* * Variable size blocks are declared with one descriptor, thus * we need add in only n_desc - 1 descriptors. */ size = sizeof(struct struct_nm) + (n_desc - 1) * sizeof(struct descrip); AlcBlk(var, struct_nm, t_code, size) var->blksize = size; } #enddef /* * alcactiv - allocate a co-expression activation block. */ struct astkblk *alcactiv() { struct astkblk *abp; CURTSTATE(); abp = (struct astkblk *)malloc((msize)sizeof(struct astkblk)); /* * If malloc failed, attempt to free some co-expression blocks and retry. */ if (abp == NULL) { DO_COLLECT(Static); abp = (struct astkblk *)malloc((msize)sizeof(struct astkblk)); } if (abp == NULL) ReturnErrNum(305, NULL); abp->nactivators = 0; abp->astk_nxt = NULL; abp->arec[0].activator = NULL; return abp; } #ifdef LargeInts #begdef alcbignum_macro(f,e_lrgint) /* * alcbignum - allocate an n-digit bignum in the block region */ struct b_bignum *f(word n) { register struct b_bignum *blk; register uword size; CURTSTATE(); size = LrgNeed(n); EVVal((word)size, e_lrgint); AlcBlk(blk, b_bignum, T_Lrgint, size); blk->blksize = size; blk->msd = blk->sign = 0; blk->lsd = n - 1; return blk; } #enddef #ifdef MultiProgram alcbignum_macro(alcbignum_0,0) alcbignum_macro(alcbignum_1,E_Lrgint) #else /* MultiProgram */ alcbignum_macro(alcbignum,0) #endif /* MultiProgram */ #endif /* LargeInts */ #ifdef Concurrent int alcce_q(dptr q, int size){ struct b_list *hp; if((hp = alclist(-1, size)) == NULL) return Failed; MUTEX_INITBLK(hp); BlkLoc(*q) = (union block *) hp; (*q).dword = D_List; hp->max = size; CV_INITBLK(hp); return Succeeded; } int alcce_queues(struct b_coexpr *ep){ ep->inbox = nulldesc; ep->outbox = nulldesc; ep->cequeue = nulldesc; ep->handdata = NULL; /* * Initialize sender/receiver queues. * * Make sure we have enough memory for all queues all at once to avoid * multiple GC if we are at the end of a region. */ if (!reserve(Blocks, (word)( sizeof(struct b_list) * 3 + sizeof(struct b_lelem) * 3 + (CE_INBOX_SIZE + CE_OUTBOX_SIZE + CE_CEQUEUE_SIZE) * sizeof(struct descrip))) ) return Failed; if (alcce_q(&(ep->outbox), 1024) == Failed) return Failed; if (alcce_q(&(ep->inbox), 1024) == Failed) return Failed; if (alcce_q(&(ep->cequeue), 64) == Failed) return Failed; ep->handdata = NULL; INIT_SHARED(ep); return Succeeded; } #endif /* Concurrent */ /* * alccoexp - allocate a co-expression stack block. */ #if COMPILER struct b_coexpr *alccoexp() { struct b_coexpr *ep; /* * If there have been too many co-expression allocations * since a collection, attempt to free some co-expression blocks. */ CURTSTATE(); MUTEX_LOCKID_CONTROLLED(MTX_ALCNUM); if (alcnum > AlcMax) DO_COLLECT(Static); ep = (struct b_coexpr *)malloc((msize)stksize); /* * If malloc failed, attempt to free some co-expression blocks and retry. */ if (ep == NULL) { DO_COLLECT(Static); ep = (struct b_coexpr *)malloc((msize)stksize); } if (ep == NULL){ MUTEX_UNLOCKID(MTX_ALCNUM); ReturnErrNum(305, NULL); } alcnum++; /* increment allocation count since last g.c. */ MUTEX_UNLOCKID(MTX_ALCNUM); ep->title = T_Coexpr; ep->size = 0; ep->es_actstk = NULL; MUTEX_LOCKID(MTX_COEXP_SER); ep->id = coexp_ser++; MUTEX_UNLOCKID(MTX_COEXP_SER); ep->es_tend = NULL; ep->file_name = ""; ep->line_num = 0; ep->freshblk = nulldesc; ep->es_actstk = NULL; #ifdef NativeCoswitch ep->status = 0; #else /* NativeCoswitch */ ep->status = Ts_Posix; #endif /* NativeCoswitch */ /* need to look at concurrent initialization for COMPILER and !COMPILER * cases and see if we should make a common function that can serve both. */ #ifdef Concurrent if (alcce_queues(ep) == Failed) ReturnErrNum(307, NULL); ep->ini_blksize = rootblock.size/100; if (ep->ini_blksize < MinAbrSize) ep->ini_blksize = MinAbrSize; ep->ini_ssize = rootstring.size/100; if (ep->ini_ssize < MinStrSpace) ep->ini_ssize = MinStrSpace; #endif /* Concurrent */ ep->es_tend = NULL; #ifdef PthreadCoswitch { makesem(ep); ep->tmplevel = 0; ep->have_thread = 0; ep->alive = 0; } #endif /* PthreadCoswitch */ MUTEX_LOCKID(MTX_STKLIST); ep->nextstk = stklist; stklist = ep; MUTEX_UNLOCKID(MTX_STKLIST); INIT_SHARED(ep); return ep; } #else /* COMPILER */ #ifdef MultiProgram /* * If this is a new program being loaded, an icodesize>0 gives the * hdr.hsize and a stacksize to use; allocate * sizeof(progstate) + icodesize + mstksize * Otherwise (icodesize==0), allocate a normal stksize... */ struct b_coexpr *alccoexp(icodesize, stacksize) long icodesize, stacksize; #else /* MultiProgram */ struct b_coexpr *alccoexp() #endif /* MultiProgram */ { struct b_coexpr *ep = NULL; CURTSTATE(); /* * If there have been too many co-expression allocations * since a collection, attempt to free some co-expression blocks. */ MUTEX_LOCKID_CONTROLLED(MTX_ALCNUM); if (alcnum > AlcMax) DO_COLLECT(Static); #ifdef MultiProgram if (icodesize > 0) { ep = (struct b_coexpr *) calloc(1, (msize)(stacksize + icodesize + sizeof(struct progstate) + sizeof(struct b_coexpr))); } else #endif /* MultiProgram */ ep = (struct b_coexpr *)malloc((msize)stksize); /* * If malloc failed, attempt to free some co-expression blocks and retry. */ if (ep == NULL) { DO_COLLECT(Static); #ifdef MultiProgram if (icodesize>0) { ep = (struct b_coexpr *) malloc((msize)(mstksize+icodesize+sizeof(struct progstate))); } else #endif /* MultiProgram */ ep = (struct b_coexpr *)malloc((msize)stksize); } if (ep == NULL){ MUTEX_UNLOCKID(MTX_ALCNUM); ReturnErrNum(305, NULL); } alcnum++; /* increment allocation count since last g.c. */ MUTEX_UNLOCKID(MTX_ALCNUM); ep->title = T_Coexpr; ep->es_actstk = NULL; ep->size = 0; #ifdef MultiProgram ep->es_pfp = NULL; ep->es_gfp = NULL; ep->es_argp = NULL; ep->tvalloc = NULL; #ifdef NativeCoswitch ep->status = 0; #else /* NativeCoswitch */ ep->status = Ts_Posix; #endif /* NativeCoswitch */ if (icodesize > 0) ep->id = 1; else{ #endif /* MultiProgram */ MUTEX_LOCKID(MTX_COEXP_SER); ep->id = coexp_ser++; MUTEX_UNLOCKID(MTX_COEXP_SER); #ifdef MultiProgram } #endif /* MultiProgram */ #ifdef Concurrent ep->Lastop = 0; if (alcce_queues(ep) == Failed) ReturnErrNum(307, NULL); { unsigned long available = memorysize(1); word size; if (NARthreads <= 32) size = available * 0.005; else if (NARthreads <= 96) size = available * 0.004; else if (NARthreads <= 224) size = available * 0.003; else if (NARthreads <= 480) size = available * 0.002; else size = available * 0.001; ep->ini_blksize = ep->ini_ssize = size; } if (ep->ini_blksize < MinAbrSize) ep->ini_blksize = MinAbrSize; if (ep->ini_ssize < MinStrSpace) ep->ini_ssize = MinStrSpace; #endif /* Concurrent */ ep->es_tend = NULL; #ifdef MultiProgram /* * Initialize program state to self for &main; curpstate for others. */ if(icodesize>0){ ep->program = (struct progstate *)(ep+1); ep->program->tstate = &ep->program->maintstate; } else ep->program = curpstate; #endif /* MultiProgram */ #ifdef PthreadCoswitch { makesem(ep); ep->tmplevel = 0; ep->have_thread = 0; ep->alive = 0; #ifdef Concurrent #ifdef MultiProgram if(icodesize>0){ ep->isProghead = 1; ep->tstate = ep->program->tstate; } else #endif /* MultiProgram */ { ep->tstate = NULL; ep->isProghead = 0; } #endif /* Concurrent */ } #endif /* PthreadCoswitch */ MUTEX_LOCKID(MTX_STKLIST); ep->nextstk = stklist; stklist = ep; MUTEX_UNLOCKID(MTX_STKLIST); return ep; } #endif /* COMPILER */ #begdef alccset_macro(f, e_cset) /* * alccset - allocate a cset in the block region. */ struct b_cset *f() { register struct b_cset *blk; register int i; CURTSTATE(); EVVal(sizeof (struct b_cset), e_cset); AlcFixBlk(blk, b_cset, T_Cset) blk->size = -1; /* flag size as not yet computed */ /* * Zero the bit array. */ for (i = 0; i < CsetSize; i++) blk->bits[i] = 0; return blk; } #enddef #ifdef MultiProgram alccset_macro(alccset_0,0) alccset_macro(alccset_1,E_Cset) #else /* MultiProgram */ alccset_macro(alccset,0) #endif /* MultiProgram */ #begdef alcfile_macro(f, e_file) /* * alcfile - allocate a file block in the block region. */ struct b_file *f(FILE *fd, int status, dptr name) { tended struct descrip tname = *name; register struct b_file *blk; EVVal(sizeof (struct b_file), e_file); AlcFixBlk(blk, b_file, T_File) blk->fd.fp = fd; blk->status = status; blk->fname = tname; #ifdef Concurrent blk->mutexid = get_mutex(&rmtx_attr); #endif /* Concurrent */ return blk; } #enddef #ifdef MultiProgram #passthru #undef alcfile alcfile_macro(alcfile,0) alcfile_macro(alcfile_1,E_File) #else /* MultiProgram */ alcfile_macro(alcfile,0) #endif /* MultiProgram */ #begdef alchash_macro(f, e_table, e_set) /* * alchash - allocate a hashed structure (set or table header) in the block * region. */ union block *f(int tcode) { register int i; register struct b_set *ps; register struct b_table *pt; CURTSTATE(); if (tcode == T_Table) { EVVal(sizeof(struct b_table), e_table); AlcFixBlk(pt, b_table, T_Table); ps = (struct b_set *)pt; MUTEX_LOCKID(MTX_TABLE_SER); ps->id = table_ser++; MUTEX_UNLOCKID(MTX_TABLE_SER); } else { /* tcode == T_Set */ EVVal(sizeof(struct b_set), e_set); AlcFixBlk(ps, b_set, T_Set); MUTEX_LOCKID(MTX_SET_SER); ps->id = set_ser++; MUTEX_UNLOCKID(MTX_SET_SER); } ps->size = 0; ps->mask = 0; INIT_SHARED(ps); for (i = 0; i < HSegs; i++) ps->hdir[i] = NULL; return (union block *)ps; } #enddef #ifdef MultiProgram alchash_macro(alchash_0,0,0) alchash_macro(alchash_1,E_Table,E_Set) #else /* MultiProgram */ alchash_macro(alchash,0,0) #endif /* MultiProgram */ #begdef alcsegment_macro(f,e_slots) /* * alcsegment - allocate a slot block in the block region. */ struct b_slots *f(word nslots) { uword size; register struct b_slots *blk; CURTSTATE(); size = sizeof(struct b_slots) + WordSize * (nslots - HSlots); EVVal(size, e_slots); AlcBlk(blk, b_slots, T_Slots, size); blk->blksize = size; while (--nslots >= 0) blk->hslots[nslots] = NULL; return blk; } #enddef #ifdef MultiProgram alcsegment_macro(alcsegment_0,0) alcsegment_macro(alcsegment_1,E_Slots) #else /* MultiProgram */ alcsegment_macro(alcsegment,0) #endif /* MultiProgram */ #ifdef PatternType #begdef alcpattern_macro(f, e_pattern, e_pelem) struct b_pattern *f(word stck_size) { register struct b_pattern *pheader; CURTSTATE(); EVVal(sizeof (struct b_pattern), e_pattern); AlcFixBlk(pheader, b_pattern, T_Pattern) pheader->stck_size = stck_size; MUTEX_LOCKID(MTX_PAT_SER); pheader->id = pat_ser++; MUTEX_UNLOCKID(MTX_PAT_SER); pheader->pe = NULL; return pheader; } #enddef #ifdef MultiProgram alcpattern_macro(alcpattern_0,0,0) alcpattern_macro(alcpattern_1,E_Pattern,E_Pelem) #else /* MultiProgram */ alcpattern_macro(alcpattern,0,0) #endif /* MultiProgram */ #begdef alcpelem_macro(f, e_pelem) #if COMPILER struct b_pelem *f( word patterncode) #else /* COMPILER */ struct b_pelem *f( word patterncode, word *o_ipc) #endif /* COMPILER */ { register struct b_pelem *pelem; CURTSTATE(); EVVal(sizeof (struct b_pelem), e_pelem); AlcFixBlk(pelem, b_pelem, T_Pelem) pelem->pcode = patterncode; pelem->pthen = NULL; #if !COMPILER pelem->origin_ipc = o_ipc; #endif /* COMPILER */ pelem->parameter = nulldesc; return pelem; } #enddef #ifdef MultiProgram alcpelem_macro(alcpelem_0,0) alcpelem_macro(alcpelem_1,E_Pelem) #else /* MultiProgram */ alcpelem_macro(alcpelem,0) #endif /* MultiProgram */ #endif /* PatternType */ struct b_cons *alccons(union block *data) { struct b_cons *rv; CURTSTATE(); AlcFixBlk(rv, b_cons, T_Cons); rv->data = data; rv->next = NULL; return rv; } /* * allocate just a list header block. internal use only (alc*array family). */ struct b_list *alclisthdr(uword size, union block *bptr) { register struct b_list *blk; CURTSTATE(); AlcFixBlk(blk, b_list, T_List) blk->size = size; MUTEX_LOCKID(MTX_LIST_SER); blk->id = list_ser++; MUTEX_UNLOCKID(MTX_LIST_SER); blk->listhead = bptr; blk->listtail = NULL; INIT_SHARED(blk); #ifdef Arrays ( (struct b_realarray *) bptr)->listp = (union block *)blk; #endif /* Arrays */ return blk; } /* * alclist_raw(), followed by alclist(). * * alclist - allocate a list header block and attach a * corresponding list element block in the block region. * Forces a g.c. if there's not enough room for the whole list. * The "alclstb" code is inlined to avoid duplicated initialization. * * alclist_raw() - as per alclist(), except initialization is left to * the caller, who promises to initialize first n==size slots w/o allocating. */ #begdef alclist_raw_macro(f, e_list, e_lelem) struct b_list *f(uword size, uword nslots) { register struct b_list *blk; register struct b_lelem *lblk; register word i; CURTSTATE(); if (!reserve(Blocks, (word)(sizeof(struct b_list) + sizeof (struct b_lelem) + (nslots - 1) * sizeof(struct descrip)))) return NULL; EVVal(sizeof (struct b_list), e_list); EVVal(sizeof (struct b_lelem) + (nslots-1) * sizeof(struct descrip), e_lelem); AlcFixBlk(blk, b_list, T_List) AlcVarBlk(lblk, b_lelem, T_Lelem, nslots) MUTEX_LOCKID(MTX_LIST_SER); if (size != -1) blk->id = list_ser++; else{ /* * size -1 is used to indicate an RT list, * reset size to 0 and use the "special" serial number */ size = 0; blk->id = intern_list_ser--; } MUTEX_UNLOCKID(MTX_LIST_SER); blk->size = size; INIT_SHARED(blk); blk->listhead = blk->listtail = (union block *)lblk; lblk->nslots = nslots; lblk->first = 0; lblk->nused = size; lblk->listprev = lblk->listnext = (union block *)blk; /* * Set all elements beyond size to &null. */ for (i = size; i < nslots; i++) lblk->lslots[i] = nulldesc; return blk; } #enddef #ifdef MultiProgram #passthru #undef alclist_raw alclist_raw_macro(alclist_raw,0,0) alclist_raw_macro(alclist_raw_1,E_List,E_Lelem) #else /* MultiProgram */ alclist_raw_macro(alclist_raw,0,0) #endif /* MultiProgram */ #begdef alclist_macro(f,e_list,e_lelem) struct b_list *f(uword size, uword nslots) { register word i = sizeof(struct b_lelem)+(nslots-1)*sizeof(struct descrip); register struct b_list *blk; register struct b_lelem *lblk; CURTSTATE(); if (!reserve(Blocks, (word)(sizeof(struct b_list) + i))) return NULL; EVVal(sizeof (struct b_list), e_list); EVVal(i, e_lelem); AlcFixBlk(blk, b_list, T_List) AlcBlk(lblk, b_lelem, T_Lelem, i) MUTEX_LOCKID(MTX_LIST_SER); if (size != -1) blk->id = list_ser++; else{ /* * size -1 is used to indicate an RT list, * reset size to 0 and use the "special" serial number */ size = 0; blk->id = intern_list_ser--; } MUTEX_UNLOCKID(MTX_LIST_SER); blk->size = size; blk->listhead = blk->listtail = (union block *)lblk; INIT_SHARED(blk); lblk->blksize = i; lblk->nslots = nslots; lblk->first = 0; lblk->nused = size; lblk->listprev = lblk->listnext = (union block *)blk; /* * Set all elements to &null. */ for (i = 0; i < nslots; i++) lblk->lslots[i] = nulldesc; return blk; } #enddef #ifdef MultiProgram alclist_macro(alclist_0,0,0) alclist_macro(alclist_1,E_List,E_Lelem) #else /* MultiProgram */ alclist_macro(alclist,0,0) #endif /* MultiProgram */ #begdef alclstb_macro(f,t_lelem) /* * alclstb - allocate a list element block in the block region. */ struct b_lelem *f(uword nslots, uword first, uword nused) { register struct b_lelem *blk; register word i; CURTSTATE(); AlcVarBlk(blk, b_lelem, T_Lelem, nslots) blk->nslots = nslots; blk->first = first; blk->nused = nused; blk->listprev = NULL; blk->listnext = NULL; /* * Set all elements to &null. */ for (i = 0; i < nslots; i++) blk->lslots[i] = nulldesc; return blk; } #enddef #ifdef MultiProgram alclstb_macro(alclstb_0,0) alclstb_macro(alclstb_1,E_Lelem) #else /* MultiProgram */ alclstb_macro(alclstb,0) #endif /* MultiProgram */ #begdef alcreal_macro(f,e_real) /* * alcreal - allocate a real value in the block region. */ struct b_real *f(double val) { register struct b_real *blk; CURTSTATE(); EVVal(sizeof (struct b_real), e_real); AlcFixBlk(blk, b_real, T_Real) #ifdef Double /* store real value one word at a time into possibly unaligned slot */ { int *rp, *rq; rp = (int *) &(blk->realval); rq = (int *) &val; *rp++ = *rq++; *rp = *rq; } #else /* Double */ blk->realval = val; #endif /* Double */ return blk; } #enddef #ifndef DescriptorDouble #ifdef MultiProgram #passthru #undef alcreal alcreal_macro(alcreal,0) alcreal_macro(alcreal_1,E_Real) #else /* MultiProgram */ alcreal_macro(alcreal,0) #endif /* MultiProgram */ #endif /* DescriptorDouble */ #begdef alcrecd_macro(f,e_record) /* * alcrecd - allocate record with nflds fields in the block region. */ struct b_record *f(int nflds, union block *recptr) { tended union block *trecptr = recptr; register struct b_record *blk; EVVal(sizeof(struct b_record) + (nflds-1)*sizeof(struct descrip),e_record); AlcVarBlk(blk, b_record, T_Record, nflds) blk->recdesc = trecptr; MUTEX_LOCKID(MTX_RECID); blk->id = (((struct b_proc *)recptr)->recid)++; MUTEX_UNLOCKID(MTX_RECID); INIT_SHARED(blk); return blk; } #enddef #ifdef MultiProgram alcrecd_macro(alcrecd_0,0) alcrecd_macro(alcrecd_1,E_Record) #else /* MultiProgram */ alcrecd_macro(alcrecd,0) #endif /* MultiProgram */ /* * alcrefresh - allocate a co-expression refresh block. */ #if COMPILER struct b_refresh *alcrefresh(na, nl, nt, wrk_sz) int na; int nl; int nt; int wrk_sz; { struct b_refresh *blk; CURTSTATE(); AlcVarBlk(blk, b_refresh, T_Refresh, na + nl) blk->nlocals = nl; blk->nargs = na; blk->ntemps = nt; blk->wrk_size = wrk_sz; return blk; } #else /* COMPILER */ #begdef alcrefresh_macro(f,e_refresh) struct b_refresh *f(word *entryx, int na, int nl) { struct b_refresh *blk; CURTSTATE(); AlcVarBlk(blk, b_refresh, T_Refresh, na + nl); blk->ep = entryx; blk->nlocals = nl; return blk; } #enddef #ifdef MultiProgram alcrefresh_macro(alcrefresh_0,0) alcrefresh_macro(alcrefresh_1,E_Refresh) #else /* MultiProgram */ alcrefresh_macro(alcrefresh,0) #endif /* MultiProgram */ #endif /* COMPILER */ #begdef alcselem_macro(f,e_selem) /* * alcselem - allocate a set element block. */ struct b_selem *f(dptr mbr,uword hn) { tended struct descrip tmbr = *mbr; register struct b_selem *blk; EVVal(sizeof(struct b_selem), e_selem); AlcFixBlk(blk, b_selem, T_Selem) blk->clink = NULL; blk->setmem = tmbr; blk->hashnum = hn; return blk; } #enddef #ifdef MultiProgram alcselem_macro(alcselem_0,0) alcselem_macro(alcselem_1,E_Selem) #else /* MultiProgram */ alcselem_macro(alcselem,0) #endif /* MultiProgram */ #begdef alcstr_macro(f,e_string) /* * alcstr - allocate a string in the string space. */ char *f(register char *s, register word slen) { tended struct descrip ts; register char *d; char *ofree; #if e_string if (!noMTevents){ StrLen(ts) = slen; StrLoc(ts) = s; EVVal(slen, e_string); s = StrLoc(ts); } #endif /* e_string */ /* * Make sure there is enough room in the string space. */ if (DiffPtrs(strend,strfree) < slen) { StrLen(ts) = slen; StrLoc(ts) = s; if (!reserve(Strings, slen)){ return NULL; } s = StrLoc(ts); } strtotal += slen; /* * Copy the string into the string space, saving a pointer to its * beginning. Note that s may be null, in which case the space * is still allocated but nothing is to be copied into it. * memcpy() is slower for slen < 4 but faster for slen >> 4. */ ofree = d = strfree; if (s) { if (slen >= 4) { memcpy(d, s, slen); d+= slen; } else while (slen-- > 0) *d++ = *s++; } else d += slen; strfree = d; return ofree; } #enddef #ifdef MultiProgram #passthru #undef alcstr alcstr_macro(alcstr,0) alcstr_macro(alcstr_1,E_String) #else /* MultiProgram */ alcstr_macro(alcstr,0) #endif /* MultiProgram */ #begdef alcsubs_macro(f, e_tvsubs) /* * alcsubs - allocate a substring trapped variable in the block region. */ struct b_tvsubs *f(word len, word pos, dptr var) { tended struct descrip tvar = *var; register struct b_tvsubs *blk; EVVal(sizeof(struct b_tvsubs), e_tvsubs); AlcFixBlk(blk, b_tvsubs, T_Tvsubs) blk->sslen = len; blk->sspos = pos; blk->ssvar = tvar; return blk; } #enddef #ifdef MultiProgram alcsubs_macro(alcsubs_0,0) alcsubs_macro(alcsubs_1,E_Tvsubs) #else /* MultiProgram */ alcsubs_macro(alcsubs,0) #endif /* MultiProgram */ #begdef alctelem_macro(f, e_telem) /* * alctelem - allocate a table element block in the block region. */ struct b_telem *f() { register struct b_telem *blk; CURTSTATE(); EVVal(sizeof (struct b_telem), e_telem); AlcFixBlk(blk, b_telem, T_Telem) blk->hashnum = 0; blk->clink = NULL; blk->tref = nulldesc; return blk; } #enddef #ifdef MultiProgram alctelem_macro(alctelem_0,0) alctelem_macro(alctelem_1,E_Telem) #else /* MultiProgram */ alctelem_macro(alctelem,0) #endif /* MultiProgram */ #begdef alctvtbl_macro(f,e_tvtbl) /* * alctvtbl - allocate a table element trapped variable block in the block * region. */ struct b_tvtbl *f(register dptr tbl, register dptr ref, uword hashnum) { tended struct descrip ttbl = *tbl; tended struct descrip tref = *ref; register struct b_tvtbl *blk; EVVal(sizeof (struct b_tvtbl), e_tvtbl); AlcFixBlk(blk, b_tvtbl, T_Tvtbl) blk->hashnum = hashnum; blk->clink = BlkLoc(ttbl); blk->tref = tref; return blk; } #enddef #ifdef MultiProgram alctvtbl_macro(alctvtbl_0,0) alctvtbl_macro(alctvtbl_1,E_Tvtbl) #else /* MultiProgram */ alctvtbl_macro(alctvtbl,0) #endif /* MultiProgram */ #ifdef EventMon #begdef alctvmonitored_macro(f) /* * alctvmonitored - allocate a trapped monitored variable block in the block * region. no need for event, unless the Monitor is a TP for another Monitor. */ struct b_tvmonitored *f(register dptr tv, word count) { tended struct descrip vref = *tv; register struct b_tvmonitored *blk; AlcFixBlk(blk, b_tvmonitored,T_Tvmonitored); blk->tv = vref; blk->cur_actv = count; return blk; } #enddef alctvmonitored_macro(alctvmonitored) #endif /* EventMon */ #begdef deallocate_macro(f,e_blkdealc) /* * deallocate - return a block to the heap. * * The block must be the one that is at the very end of a block region. */ void f (union block *bp) { word nbytes; struct region *rp; CURTSTATE(); #ifdef Concurrent /* DO WE NEED THIS ? WE HAVE PRIVATE HEAPS NOW */ return; #endif /* Concurrent */ nbytes = BlkSize(bp); for (rp = curblock; rp; rp = rp->next) if ((char *)bp + nbytes == rp->free) break; if (!rp) for (rp = curblock->prev; rp; rp = rp->prev) if ((char *)bp + nbytes == rp->free) break; if (!rp) syserr ("deallocation botch"); rp->free = (char *)bp; blktotal -= nbytes; EVVal(nbytes, e_blkdealc); } #enddef #ifdef MultiProgram deallocate_macro(deallocate_0,0) deallocate_macro(deallocate_1,E_BlkDeAlc) #else /* MultiProgram */ deallocate_macro(deallocate,0) #endif /* MultiProgram */ #begdef reserve_macro(f,e_tenurestring,e_tenureblock) /* * reserve -- ensure space in either string or block region. * * 1. check for space in current region. * 2. check for space in older regions. * 3. check for space in newer regions. * 4. set goal of 10% of size of newest region. * 5. collect regions, newest to oldest, until goal met. * 6. allocate new region at 200% the size of newest existing. * 7. reset goal back to original request. * 8. collect regions that were too small to bother with before. * 9. search regions, newest to oldest. * 10. give up and signal error. */ char *f(int region, word nbytes) { struct region **pcurr, *curr_private, *rp; word want, newsize; extern int qualfail; #ifdef Concurrent int mtx_heap; struct region **p_publicheap; CURTSTATE(); if (region == Strings) pcurr = &curtstring; else pcurr = &curtblock; #else /* Concurrent */ if (region == Strings) pcurr = &curstring; else pcurr = &curblock; #endif /* Concurrent */ curr_private = *pcurr; /* * Check for space available now. */ if (DiffPtrs(curr_private->end, curr_private->free) >= nbytes) return curr_private->free; /* quick return: current region is OK */ /* check all regions on chain */ #ifdef Concurrent if ((rp = findgap(curr_private, nbytes, region)) != 0) #else /* Concurrent */ if ((rp = findgap(curr_private, nbytes)) != 0) #endif /* Concurrent */ { *pcurr = rp; /* switch regions */ return rp->free; } #ifndef Concurrent /* * Set "curr_private" to point to newest region. */ while (curr_private->next) curr_private = curr_private->next; /* * Need to collect garbage. To reduce thrashing, set a minimum requirement * of 10% of the size of the newest region, and collect regions until that * amount of free space appears in one of them. */ want = (curr_private->size / 100) * memcushion; if (want < nbytes) want = nbytes; for (rp = curr_private; rp; rp = rp->prev) if (rp->size >= want) { /* if large enough to possibly succeed */ *pcurr = rp; collect(region); if (DiffPtrs(rp->end,rp->free) >= want) return rp->free; } #else /* Concurrent */ want = (curr_private->size / 100) * memcushion; if (want < nbytes) want = nbytes; SUSPEND_THREADS(); collect(region); /* try to collect the private region first */ if (DiffPtrs(curr_private->end,curr_private->free) >= want) { RESUME_THREADS(); return curr_private->free; } /* Only the GC is running */ if (region == Strings) { mtx_heap=MTX_STRHEAP; p_publicheap = &public_stringregion; } else{ mtx_heap=MTX_BLKHEAP; p_publicheap = &public_blockregion; } /* look in the public heaps, */ for (rp = *p_publicheap; rp; rp = rp->Tnext) /* if large enough to possibly succeed */ if (rp->size >= want && rp->size>=curr_private->size/2) { curr_private = swap2publicheap(curr_private, rp, p_publicheap); *pcurr = curr_private; collect(region); if (DiffPtrs( curr_private->end, curr_private->free) >= want){ RESUME_THREADS(); return curr_private->free; } } /* * GC has failed so far to free enough memory, wake up all threads for now. */ RESUME_THREADS(); #endif /* Concurrent */ /* * That didn't work. Allocate a new region with a size based on the * newest previous region. memgrowth is a percentile number (defaulting * to 200, meaning "double each time"), so divide by 100. */ newsize = (curr_private->size / 100) * memgrowth; if (newsize < (nbytes + memcushion)) newsize = nbytes + memcushion; if (newsize < MinAbrSize) newsize = MinAbrSize; if ((rp = newregion(nbytes, newsize)) != 0) { #ifdef Concurrent /* a new region is allocated, swap the current private * region out to the public list. */ if (region == Strings){ MUTEX_LOCKID_CONTROLLED(MTX_PUBLICSTRHEAP); swap2publicheap(curr_private, NULL, &public_stringregion); MUTEX_UNLOCKID(MTX_PUBLICSTRHEAP); } else{ MUTEX_LOCKID_CONTROLLED(MTX_PUBLICBLKHEAP); swap2publicheap(curr_private, NULL, &public_blockregion); MUTEX_UNLOCKID(MTX_PUBLICBLKHEAP); } /* * Set "curr_private" to point to newest region. */ MUTEX_LOCKID(mtx_heap); while (curr_private->next) curr_private = curr_private->next; #endif /* Concurrent */ rp->prev = curr_private; rp->next = NULL; curr_private->next = rp; rp->Gnext = curr_private; rp->Gprev = curr_private->Gprev; if (curr_private->Gprev) curr_private->Gprev->Gnext = rp; curr_private->Gprev = rp; MUTEX_UNLOCKID(mtx_heap); *pcurr = rp; #if e_tenurestring || e_tenureblock { int tmp_noMTevents; MUTEX_LOCKID(MTX_NOMTEVENTS); tmp_noMTevents = noMTevents; MUTEX_UNLOCKID(MTX_NOMTEVENTS); if (!tmp_noMTevents) { if (region == Strings) { EVVal(rp->size, e_tenurestring); } else { EVVal(rp->size, e_tenureblock); } } } #endif /* e_tenurestring || e_tenureblock */ return rp->free; } /* * Allocation failed. Try to continue, probably thrashing all the way. * Collect the regions that weren't collected before and see if any * region has enough to satisfy the original request. */ #ifdef Concurrent // fprintf(stderr, " !!! Low memory!! Trying all options !!!\n "); /* look in the public heaps, */ SUSPEND_THREADS(); /* public heaps might have got updated, resync, no need to lock! */ if (region == Strings) p_publicheap = &public_stringregion; else p_publicheap = &public_blockregion; for (rp = *p_publicheap; rp; rp = rp->Tnext) if (rp->size >= want) { /* if not collected earlier */ curr_private = swap2publicheap(curr_private, rp, p_publicheap); *pcurr = curr_private; collect(region); if (DiffPtrs(curr_private->end,curr_private->free) >= want){ RESUME_THREADS(); return curr_private->free; } } RESUME_THREADS(); if ((rp = findgap(curr_private, nbytes, region)) != 0) /* check all regions on chain */ #else /* Concurrent */ for (rp = curr_private; rp; rp = rp->prev) if (rp->size >= want) { /* if not collected earlier */ *pcurr = rp; collect(region); if (DiffPtrs(rp->end,rp->free) >= want) return rp->free; } if ((rp = findgap(curr_private, nbytes)) != 0) #endif /* Concurrent */ { *pcurr = rp; return rp->free; } /* * All attempts failed. */ if (region == Blocks) ReturnErrNum(307, NULL); else if (qualfail) ReturnErrNum(304, NULL); else ReturnErrNum(306, NULL); } #enddef #ifdef MultiProgram reserve_macro(reserve_0,0,0) reserve_macro(reserve_1,E_TenureString,E_TenureBlock) #else /* MultiProgram */ reserve_macro(reserve,0,0) #endif /* MultiProgram */ #ifdef Concurrent /* * swap the thread current region (curr_private) with curr_public from the * public heaps. The switch is done in the chain and a pointer to the new private * region is returned. * IMPORTANT: This function assumes that the public heap in use is locked. */ struct region *swap2publicheap( curr_private, curr_public, p_public) struct region *curr_private; struct region *curr_public; struct region **p_public; /* pointer to the head of the list*/ { if (curr_public){ curr_private->Tnext = curr_public->Tnext; curr_private->Tprev = curr_public->Tprev; if (curr_public->Tnext){ curr_private->Tnext->Tprev = curr_private; curr_public->Tnext = NULL; if (curr_public->Tprev){ /* middle node*/ curr_private->Tprev->Tnext = curr_private; curr_public->Tprev = NULL; } else *p_public = curr_private; } else if (curr_public->Tprev){ curr_private->Tprev->Tnext = curr_private; curr_public->Tprev = NULL; } else *p_public = curr_private; } else { /* NO SWAP: some thread is giving up his heap. Just insert curr_private into the public heap. */ curr_private->Tprev=NULL; if (*p_public==NULL) curr_private->Tnext=NULL; else{ curr_private->Tnext=*p_public; curr_private->Tnext->Tprev=curr_private; } *p_public=curr_private; return NULL; } return curr_public; } #endif /* Concurrent */ /* * findgap - search region chain for a region having at least nbytes available */ #ifdef Concurrent static struct region *findgap(curr_private, nbytes, region) struct region *curr_private; word nbytes; int region; #else /* Concurrent */ static struct region *findgap(curr, nbytes) struct region *curr; word nbytes; #endif /* Concurrent */ { struct region *rp; #ifdef Concurrent if (region == Strings){ MUTEX_LOCKID_CONTROLLED(MTX_PUBLICSTRHEAP); for (rp = public_stringregion; rp; rp = rp->Tnext) if (DiffPtrs(rp->end, rp->free) >= nbytes && rp->size>=curr_private->size/2) break; if (rp) rp=swap2publicheap(curr_private, rp, &public_stringregion); MUTEX_UNLOCKID(MTX_PUBLICSTRHEAP); } else{ MUTEX_LOCKID_CONTROLLED(MTX_PUBLICBLKHEAP); for (rp = public_blockregion; rp; rp = rp->Tnext) if (DiffPtrs(rp->end, rp->free) >= nbytes && rp->size>=curr_private->size/2) break; if (rp) rp=swap2publicheap(curr_private, rp, &public_blockregion); MUTEX_UNLOCKID(MTX_PUBLICBLKHEAP); } return rp; #else /* Concurrent */ /* With ThreadHeap, skip this, we know we are at the front of the list */ for (rp = curr; rp; rp = rp->prev) if (DiffPtrs(rp->end, rp->free) >= nbytes) return rp; for (rp = curr->next; rp; rp = rp->next) if (DiffPtrs(rp->end, rp->free) >= nbytes) return rp; return NULL; #endif /* Concurrent */ } /* * newregion - try to malloc a new region and tenure the old one, * backing off if the requested size fails. */ struct region *newregion(nbytes,stdsize) word nbytes,stdsize; { uword minSize = MinAbrSize; struct region *rp; #if IntBits == 16 if ((uword)nbytes > (uword)MaxBlock) return NULL; if ((uword)stdsize > (uword)MaxBlock) stdsize = (uword)MaxBlock; #endif /* IntBits == 16 */ if ((uword)nbytes > minSize) minSize = (uword)nbytes; rp = (struct region *)malloc(sizeof(struct region)); if (rp) { rp->size = stdsize; #if IntBits == 16 if ((rp->size < nbytes) && (nbytes < (unsigned int)MaxBlock)) rp->size = Min(nbytes+stdsize,(unsigned int)MaxBlock); #else /* IntBits == 16 */ if (rp->size < nbytes) rp->size = Max(nbytes+stdsize, nbytes); #endif /* IntBits == 16 */ do { rp->free = rp->base = (char *)AllocReg(rp->size); if (rp->free != NULL) { rp->end = rp->base + rp->size; rp->next = rp->prev = NULL; #ifdef Concurrent rp->Tnext=NULL; rp->Tprev=NULL; #endif /* Concurrent */ return rp; } rp->size = (rp->size + nbytes)/2 - 1; } while (rp->size >= minSize); free((char *)rp); } return NULL; } #ifdef Arrays struct b_intarray *alcintarray(uword n) { int bsize = sizeof(struct b_intarray) + (n-1) * sizeof(word); register struct b_intarray *blk; CURTSTATE(); AlcBlk(blk, b_intarray, T_Intarray, bsize); blk->blksize = bsize; blk->dims = NULL; blk->listp = NULL; return blk; } struct b_realarray *alcrealarray(uword n) { int bsize = sizeof(struct b_realarray) + (n-1) * sizeof(double); register struct b_realarray *blk; CURTSTATE(); AlcBlk(blk, b_realarray, T_Realarray, bsize); blk->blksize = bsize; blk->dims = NULL; blk->listp = NULL; return blk; } #endif /* Arrays */
#include <gsl/gsl_errno.h> #include <gsl/matrix/gsl_matrix.h> #define BASE_DOUBLE #include <gsl/templates_on.h> #include <gsl/matrix/matrix_source.c> #include <gsl/templates_off.h> #undef BASE_DOUBLE
State Before: a : ℕ a1 : 1 < a ⊢ yn a1 0 ≡ 0 [MOD a - 1] State After: no goals Tactic: simp [Nat.ModEq.refl] State Before: a : ℕ a1 : 1 < a ⊢ yn a1 1 ≡ 1 [MOD a - 1] State After: no goals Tactic: simp [Nat.ModEq.refl] State Before: a : ℕ a1 : 1 < a n : ℕ ⊢ yn a1 (n + 2) + yn a1 n ≡ n + 2 + n [MOD a - 1] State After: a : ℕ a1 : 1 < a n : ℕ ⊢ 2 * a * yn a1 (n + 1) ≡ 2 * (n + 1) [MOD a - 1] Tactic: rw [yn_succ_succ, (by ring : n + 2 + n = 2 * (n + 1))] State Before: a : ℕ a1 : 1 < a n : ℕ ⊢ 2 * a * yn a1 (n + 1) ≡ 2 * (n + 1) [MOD a - 1] State After: no goals Tactic: exact ((modEq_sub a1.le).mul_left 2).mul (yn_modEq_a_sub_one (n + 1)) State Before: a : ℕ a1 : 1 < a n : ℕ ⊢ n + 2 + n = 2 * (n + 1) State After: no goals Tactic: ring
Require ClassicalEpsilon. Require Import Reals Psatz. From stdpp Require Import tactics. From mathcomp Require Import ssrfun ssreflect eqtype ssrbool seq fintype choice bigop. From discprob.basic Require Import base sval order monad bigop_ext nify. From discprob.idxval Require Import pival_dist pival ival_dist ival ival_pair pidist_singleton idist_pidist_pair extrema. From discprob.prob Require Import prob countable finite stochastic_order. Import Lub. (* This is an inductive characterization of eq_ivd_prob, as is proved later *) Inductive irrel_ivd : ∀ X, ivdist X → ivdist X → Prop := | irrel_ivd_refl X : ∀ (I: ivdist X), irrel_ivd X I I | irrel_ivd_sym X : ∀ I1 I2, irrel_ivd X I1 I2 → irrel_ivd X I2 I1 | irrel_ivd_trans X : ∀ I1 I2 I3, irrel_ivd X I1 I2 → irrel_ivd X I2 I3 → irrel_ivd X I1 I3 | irrel_ivd_proper X : ∀ I1 I1' I2 I2', eq_ivd I1 I1' → eq_ivd I2 I2' → irrel_ivd X I1 I2 → irrel_ivd X I1' I2' | irrel_ivd_irrel X : ∀ {Y} I1 (I0: ivdist Y), irrel_ivd X I1 (x ← I0; I1) | irrel_ivd_bind X Y: ∀ (I1 I2: ivdist X) (f1 f2: X → ivdist Y), irrel_ivd X I1 I2 → (∀ x, irrel_ivd Y (f1 x) (f2 x)) → irrel_ivd Y (x ← I1; f1 x) (x ← I2; f2 x). Arguments irrel_ivd {_}. Definition le_pidist_irrel := λ {X : Type} (Is1 Is2 : pidist X), ∀ I : ivdist X, In (I: ival X) Is1 → ∃ I' : ivdist X, irrel_ivd I I' ∧ In (I': ival X) Is2. Lemma le_pidist_irrel_refl {X: Type} (Is1: pidist X): le_pidist_irrel Is1 Is1. Proof. intros I Hin. exists I; split; eauto. apply irrel_ivd_refl. Qed. Lemma irrel_ivd_support_coerce {X} (I1 I2: ivdist X) : irrel_ivd I1 I2 → ∀ x, (∃ i2, ind I2 i2 = x ∧ val I2 i2 > 0) ↔ (∃ i1, ind I1 i1 = x ∧ val I1 i1 > 0). Proof. induction 1. - split; intros; auto. - intros. by rewrite (IHirrel_ivd x). - intros. by rewrite (IHirrel_ivd2 x). - intros. rewrite (eq_ival_support_coerce I1 I1'); eauto. rewrite (eq_ival_support_coerce I2 I2'); eauto. - intros. * split. ** intros ((i0&i1)&Heq&Hgt). exists i1. rewrite //= in Heq Hgt. split; auto. specialize (val_nonneg I0 i0); nra. ** intros (i1&Heq&Hgt). edestruct (ivd_support_idx I0) as (i0&Hgt'). exists (existT i0 i1); split => //=; nra. - intros x. split. * intros ((i2&if2)&Hind&Hval). rewrite //= in Hind. edestruct (IHirrel_ivd (ind I2 i2)) as (HI2&_). edestruct (HI2) as (i1&Hindeq&?). { eexists. split; eauto. rewrite //= in Hval. specialize (val_nonneg (f2 (ind I2 i2)) if2). nra. } edestruct (H1 (ind I2 i2)) as (Hf2&_). edestruct Hf2 as (if1&?&?). { eexists. split; eauto. rewrite //= in Hval. specialize (val_nonneg I2 i2); nra. } unshelve (eexists). { exists i1. rewrite Hindeq; exact if1. } split => //=; destruct Hindeq. ** rewrite /eq_rect_r//=. ** rewrite /eq_rect_r//=. nra. * intros ((i2&if2)&Hind&Hval). rewrite //= in Hind. edestruct (IHirrel_ivd (ind I1 i2)) as (_&HI2). edestruct (HI2) as (i1&Hindeq&?). { eexists. split; eauto. rewrite //= in Hval. specialize (val_nonneg (f1 (ind I1 i2)) if2). nra. } edestruct (H1 (ind I1 i2)) as (_&Hf2). edestruct Hf2 as (if1&?&?). { eexists. split; eauto. rewrite //= in Hval. specialize (val_nonneg I1 i2); nra. } unshelve (eexists). { exists i1. rewrite Hindeq; exact if1. } split => //=; destruct Hindeq. ** rewrite /eq_rect_r//=. ** rewrite /eq_rect_r//=. nra. Qed. Lemma le_pidist_irrel_support_coerce_aux {X} (Is1 Is2: pidist X) : le_pidist_irrel Is2 Is1 → ∀ x, In_psupport x Is2 → In_psupport x Is1. Proof. intros Hle x (I2&i2&Hin2&?&Hval). destruct (Hle {| ivd_ival := I2; val_sum1 := all_sum1 Is2 _ Hin2|}) as (I1&Heq&Hin1); eauto. exists I1. edestruct (irrel_ivd_support_coerce _ _ Heq) as (i1&?&?). { eauto. } eexists; split; eauto. Qed. Global Instance irrel_ivd_proper_instance : Proper (@eq_ivd X ==> @eq_ivd X ==> iff) (@irrel_ivd X). Proof. intros ? I1 I1' Heq1 I2 I2' Heq2. split; intros; eapply irrel_ivd_proper; eauto; try by symmetry. Qed. Global Instance irrel_ivd_Transitivite {X}: Transitive (@irrel_ivd X). Proof. intros ???. apply irrel_ivd_trans. Qed. Global Instance irrel_ivd_Reflexive {X}: Reflexive (@irrel_ivd X). Proof. intros ?. apply irrel_ivd_refl. Qed. Global Instance irrel_ivd_Symmetry {X}: Symmetric (@irrel_ivd X). Proof. intros ??. apply irrel_ivd_sym. Qed. Lemma is_Ex_ival_irrel_proper_bind {X Y} f (f1 f2: X → ivdist Y) (I1 I2: ivdist X) v (Hirrel_ivd : irrel_ivd I1 I2) (Hall_irrel : ∀ x : X, irrel_ivd (f1 x) (f2 x)) (IHinner : ∀ (x : X) (f : Y → R) (v : R), is_Ex_ival f (f1 x) v ↔ is_Ex_ival f (f2 x) v) (IHirrel_ivd : ∀ (f : X → R) (v : R), is_Ex_ival f I1 v ↔ is_Ex_ival f I2 v): is_Ex_ival f (ivd_bind _ _ f1 I1) v → is_Ex_ival f (ivd_bind _ _ f2 I2) v. Proof. intros His. assert (ex_Ex_ival f (ivd_bind _ _ f1 I1)). { eapply is_Ex_ival_ex; eauto. } rewrite -(is_Ex_ival_unique _ _ _ His). feed pose proof (ex_Ex_ival_bind_post (λ x, Rabs (f x)) I1 f1) as Hex_I1. { eapply ex_Ex_ival_to_Rabs, is_Ex_ival_ex. eauto. } feed pose proof (ex_Ex_ival_bind_post f I1 f1) as Hex_I1'. { eapply is_Ex_ival_ex. eauto. } rewrite Ex_ival_bind_post //=. assert (ex_Ex_ival f (ivd_bind _ _ f2 I2)). { apply ex_Ex_ival_from_Rabs, ex_Ex_ival_bind_post_inv; eauto using Rabs_pos, Rle_ge. ** intros. apply is_Ex_ival_ex, ex_Ex_ival_to_Rabs in His. edestruct (irrel_ivd_support_coerce I1 I2) as (Hlr&Hrl); eauto. edestruct Hlr as (i1&Heqi1&Hvali1); eauto. eapply ex_Ex_ival_bind_inv in His; eauto. eapply ex_Ex_ival_is in His as (v'&His). rewrite -Heqi1. eapply is_Ex_ival_ex. eapply IHinner; eauto. ** apply ex_Ex_ival_is in Hex_I1 as (v'&His'). eapply is_Ex_ival_ex; eapply IHirrel_ivd. eapply is_Ex_ival_proper_fun_support; eauto. intros x Hsupport => //=. symmetry. apply is_Ex_ival_unique. eapply IHinner. eapply Ex_ival_correct. eapply (ex_Ex_ival_bind_inv (λ x, Rabs (f x)) f1 I1); eauto. apply ex_Ex_ival_to_Rabs. eapply is_Ex_ival_ex; eauto. } cut (Ex_ival f (ivd_bind _ _ f2 I2) = (Ex_ival (λ x, Ex_ival f (f1 x)) I1)). { intros HEx. rewrite -HEx. apply Ex_ival_correct; eauto. } rewrite Ex_ival_bind_post //=. apply is_Ex_ival_unique. eapply IHirrel_ivd. eapply is_Ex_ival_proper_fun_support; last first. { eapply Ex_ival_correct. eauto. } intros => //=. symmetry. apply is_Ex_ival_unique. eapply IHinner. eapply Ex_ival_correct. eapply (ex_Ex_ival_bind_inv f f1 I1); eauto. Qed. Lemma is_Ex_ival_irrel_proper {A} f (I I': ivdist A) v : irrel_ivd I I' → is_Ex_ival f I v ↔ is_Ex_ival f I' v. Proof. intros irrel_ivd. revert v. induction irrel_ivd; auto; intros. - symmetry. eapply IHirrel_ivd. - rewrite IHirrel_ivd1. auto. - rewrite /eq_ivd in H. etransitivity; first etransitivity; try eapply IHirrel_ivd. { split; apply is_Ex_ival_proper; eauto. by symmetry. } { split; apply is_Ex_ival_proper; eauto. by symmetry. } - split. apply is_Ex_ival_bind_irrel, val_sum1. intros His. cut (ex_Ex_ival f I1). { intros Hex. apply Ex_ival_correct in Hex. cut (Ex_ival f I1 = v); intros; subst; eauto. eapply is_Ex_ival_unique'; last eassumption. apply is_Ex_ivd_bind_irrel; eauto. } apply is_Ex_ival_ex in His. unshelve (eapply ex_Ex_ival_bind_inv in His; eauto). { exact (sval (ivd_support_idx I0)). } destruct (ivd_support_idx _) => //=. - split; eapply is_Ex_ival_irrel_proper_bind; eauto; try (intros; by symmetry). Qed. Lemma ex_Ex_ival_irrel_proper {A} f (I I': ivdist A) : irrel_ivd I I' → ex_Ex_ival f I → ex_Ex_ival f I'. Proof. intros Hirrel (v&His)%ex_Ex_ival_is. eapply is_Ex_ival_ex. eapply is_Ex_ival_irrel_proper; eauto. by symmetry. Qed. Lemma Ex_ival_irrel_proper {A} f (I I': ivdist A) : irrel_ivd I I' → ex_Ex_ival f I → Ex_ival f I = Ex_ival f I'. Proof. intros. symmetry. apply is_Ex_ival_unique. eapply is_Ex_ival_irrel_proper; eauto. * symmetry. eauto. * apply Ex_ival_correct; eauto. Qed. Lemma irrel_ivd_to_eq_ivd_prob {X} (I1 I2: ivdist X): irrel_ivd I1 I2 → eq_ivd_prob I1 I2. Proof. intros Hirrel. apply eq_ivd_prob_alt. intros x. transitivity ((Pr (λ v, v = x) I1)). { rewrite /Ex_ival/idx_eq_ind//=. eapply SeriesC_ext; intros. destruct ClassicalEpsilon.excluded_middle_informative => //=; nra. } transitivity ((Pr (λ v, v = x) I2)); last first. { rewrite /Ex_ival/idx_eq_ind//=. eapply SeriesC_ext; intros. destruct ClassicalEpsilon.excluded_middle_informative => //=; nra. } apply Ex_ival_irrel_proper; eauto. apply ex_Pr. Qed. Lemma In_isupport_pr_gt_0 {X: Type} (I: ivdist X) (x: X): In_isupport x I → 0 < Pr (eq ^~ x) I. Proof. rewrite /Pr/Ex_ival => Hin. destruct Hin as (i&?&?). eapply (Series_strict_pos _ (pickle i)). { intros. rewrite /countable_sum/oapp. destruct pickle_inv; try nra. destruct ClassicalEpsilon.excluded_middle_informative => //=; try nra. rewrite Rmult_1_l. apply val_nonneg. } { intros. rewrite /countable_sum/oapp. rewrite pickleK_inv. destruct ClassicalEpsilon.excluded_middle_informative => //=; try nra. } feed pose proof (ex_Pr (eq^~ x) I). apply ex_Ex_ival_is in H1 as (v&?). rewrite /is_Ex_ival in H1. destruct H1 as (Hex&His). eexists. eauto. Qed. Lemma pr_gt_0_In_isupport {X: Type} (I: ivdist X) (x: X): 0 < Pr (eq ^~ x) I → In_isupport x I. Proof. rewrite /Pr/Ex_ival => Hin. eapply (Series_strict_pos_inv) in Hin as (n&?). { destruct (pickle_inv (idx I) n) as [i|] eqn:Heq. - exists i. rewrite //=/countable_sum//= Heq //= in H. destruct ClassicalEpsilon.excluded_middle_informative => //=; try nra. * rewrite //= in H. split; eauto. nra. * rewrite //= in H. nra. - rewrite //=/countable_sum//= Heq //= in H ; nra. } intros n. rewrite /countable_sum. destruct pickle_inv => //=; last nra. destruct ClassicalEpsilon.excluded_middle_informative => //=; try nra. rewrite Rmult_1_l. apply val_nonneg. Qed. (* This is a kind of conditional distribution *) Lemma ival_slice_proof1 (X : Type) (I : ivdist X) (x : X): ∀ i : idx I, (if ClassicalEpsilon.excluded_middle_informative (In_isupport x I) then (if ClassicalEpsilon.excluded_middle_informative (ind I i = x) then val I i else 0) / Pr (eq^~ x) I else val I i) ≥ 0. Proof. intros i. destruct ClassicalEpsilon.excluded_middle_informative; eauto; last apply val_nonneg. apply Rle_ge, Rdiv_le_0_compat. { destruct ClassicalEpsilon.excluded_middle_informative; eauto; try nra. apply Rge_le, val_nonneg. } { apply In_isupport_pr_gt_0; eauto. } Qed. Definition ival_slice {X} (I: ivdist X) (x: X) : ival X. refine {| idx := idx I; ind := ind I; val := λ i, if ClassicalEpsilon.excluded_middle_informative (In_isupport x I) then (if ClassicalEpsilon.excluded_middle_informative (ind I i = x) then val I i else 0) / Pr (λ i, i = x) I else val I i|}. apply ival_slice_proof1. Defined. Lemma ival_slice_proof2 (X : Type) (I : ivdist X) (x : X): is_series (countable_sum (val (ival_slice I x))) 1. Proof. rewrite //=. destruct ClassicalEpsilon.excluded_middle_informative; last apply val_sum1. replace 1 with (Pr (eq^~ x) I */ Pr (eq^~ x) I); last first. { field. apply Rgt_not_eq, In_isupport_pr_gt_0; auto. } apply is_seriesC_scal_r. rewrite /Pr/Ex_ival. apply (is_seriesC_ext _ (λ i0 : idx I, (if is_left (ClassicalEpsilon.excluded_middle_informative (ind I i0 = x)) then 1 else 0) * val I i0)). { intros. destruct ClassicalEpsilon.excluded_middle_informative => //=; try nra. } { feed pose proof (ex_Pr (eq^~ x) I) as Hpr. apply ex_Ex_ival_is in Hpr as (v&Hpr). rewrite /is_Ex_ival in Hpr. destruct Hpr as (Hex&His). eapply Series_correct; eexists; eauto. } Qed. Definition ivdist_slice {X} (I: ivdist X) (x: X) : ivdist X. Proof. exists (ival_slice I x). apply ival_slice_proof2. Defined. Lemma eq_ivd_prob_Pr_eq {X} (I1 I2: ivdist X) x: eq_ivd_prob I1 I2 → Pr (eq^~ x) I1 = Pr (eq^~ x) I2. Proof. rewrite /Pr/Ex_ival => Heq. unshelve (eapply eq_ivd_prob_alt in Heq); first exact x. rewrite /idx_eq_ind in Heq. setoid_rewrite Rmult_if_distrib. setoid_rewrite Rmult_0_l. setoid_rewrite Rmult_1_l. eauto. Qed. Lemma eq_ivd_prob_In_isupport {X: Type} I1 I2 (x: X): eq_ivd_prob I1 I2 → In_isupport x I1 → In_isupport x I2. Proof. intros Heq Hin%In_isupport_pr_gt_0. apply pr_gt_0_In_isupport. erewrite <-eq_ivd_prob_Pr_eq; last eassumption. eauto. Qed. Lemma eq_ivd_prob_to_irrel_ivd {X} (I1 I2: ivdist X): eq_ivd_prob I1 I2 → irrel_ivd I1 I2. Proof. intros Heq. transitivity (x ← I1; _ ← ivdist_slice I2 x; mret x). { transitivity (x ← I1; mret x). { rewrite ivd_right_id. reflexivity. } apply irrel_ivd_bind; first reflexivity. intros x. apply irrel_ivd_irrel. } transitivity (x ← I2; _ ← ivdist_slice I1 x; mret x); last first. { symmetry. transitivity (x ← I2; mret x). { rewrite ivd_right_id. reflexivity. } apply irrel_ivd_bind; first reflexivity. intros x. apply irrel_ivd_irrel. } cut (eq_ivd (I1 ≫= (λ x : X, ivdist_slice I2 x ≫= (λ _ : X, mret x))) (I2 ≫= (λ x : X, ivdist_slice I1 x ≫= (λ _ : X, mret x)))). { intros ->. reflexivity. } apply eq_ival_nondep_inj_surj_suffice. apply eq_ival_nondep_inj_surj'_helper. unshelve eexists. { intros (i1&i2&?). exists i2. exists i1. exact tt. } rewrite //=. split_and!. * intros (i1&i2&[]) (i1'&i2'&[]) _ _ => //=. inversion 1; subst. auto. * intros (i2&i1&[]). unshelve (eexists). { exists i1. exists i2. exact tt. } split_and!; eauto => //=. repeat destruct ClassicalEpsilon.excluded_middle_informative; try nra; try congruence. ** intros Hgt. eapply Rge_gt_trans; last eassumption. right. rewrite //=. cut (Pr (eq^~ (ind I2 i2)) I1 = Pr (eq^~ (ind I1 i1)) I2). { intros ->. nra. } rewrite e0; eapply eq_ivd_prob_Pr_eq; eauto. ** intros; exfalso. eapply n. rewrite e. eapply eq_ivd_prob_In_isupport; eauto. ** intros; exfalso. eapply n. rewrite e. eapply eq_ivd_prob_In_isupport; eauto. by symmetry. ** cut (val I2 i2 = 0). { intros ->. nra. } destruct (val_nonneg I2 i2); last auto. exfalso. eapply n. eapply eq_ivd_prob_In_isupport; eauto. { by symmetry. } eexists; eauto. * intros (i1&i2&[]) => //=. repeat destruct ClassicalEpsilon.excluded_middle_informative; try nra; try congruence. cut (val I1 i1 = 0). { intros ->. nra. } destruct (val_nonneg I1 i1); last auto. exfalso. eapply n. eapply eq_ivd_prob_In_isupport; eauto. eexists; eauto. * intros (i1&i2&[]) => //=. repeat destruct ClassicalEpsilon.excluded_middle_informative => //=; try nra; try congruence. ** intros Hgt. cut (Pr (eq^~ (ind I2 i2)) I1 = Pr (eq^~ (ind I1 i1)) I2). { intros ->. nra. } rewrite e0; eapply eq_ivd_prob_Pr_eq; eauto. ** intros; exfalso. eapply n. rewrite e. eapply eq_ivd_prob_In_isupport; eauto. by symmetry. ** intros; exfalso. eapply n. rewrite e. eapply eq_ivd_prob_In_isupport; eauto. ** cut (val I1 i1 = 0). { intros ->. nra. } destruct (val_nonneg I1 i1); last auto. exfalso. eapply n. eapply eq_ivd_prob_In_isupport; eauto. eexists; eauto. Qed. Lemma irrel_ivd_choice {X} (I1 I1' I2 I2': ivdist X) p Hpf Hpf': irrel_ivd I1 I2 → irrel_ivd I1' I2' → irrel_ivd (ivdplus p Hpf I1 I1') (ivdplus p Hpf' I2 I2'). Proof. intros Hirrel1 Hirrel2. transitivity (b ← ivdplus p Hpf (mret true) (mret false); if (b: bool) then I1 else I1'). { rewrite ivd_plus_bind ?ivd_left_id. reflexivity. } transitivity (b ← ivdplus p Hpf' (mret true) (mret false); if (b: bool) then I2 else I2'); last first. { rewrite ivd_plus_bind ?ivd_left_id. reflexivity. } apply irrel_ivd_bind. { cut (eq_ivd (ivdplus p Hpf (mret true) (mret false)) (ivdplus p Hpf' (mret true) (mret false))). { intros ->; reflexivity. } apply ivdist_plus_proper; reflexivity. } intros [|]; eauto. Qed. Definition irrel_pidist {X: Type} (Is1 Is2: pidist X) := ∀ f, bounded_fun f → Rbar_le (Ex_min f Is2) (Ex_min f Is1). Lemma irrel_pidist_Ex_max {X: Type} (Is1 Is2: pidist X) : irrel_pidist Is1 Is2 → ∀ f, bounded_fun f → Rbar_le (Ex_max f Is1) (Ex_max f Is2). Proof. intros Hirrel f Hb. rewrite ?Ex_max_neg_min. apply Rbar_opp_le. apply Hirrel. destruct Hb as (c&?). exists c => x. rewrite Rabs_Ropp; eauto. Qed. Lemma Ex_max_irrel_pidist {X: Type} (Is1 Is2: pidist X) : (∀ f, bounded_fun f → Rbar_le (Ex_max f Is1) (Ex_max f Is2)) → irrel_pidist Is1 Is2. Proof. intros Hirrel f Hb. specialize (Hirrel (λ x, (- f x))). rewrite ?Ex_max_neg_min in Hirrel. apply Rbar_opp_le. setoid_rewrite Ropp_involutive in Hirrel. eapply Hirrel. destruct Hb as (c&?). exists c. intros x. rewrite Rabs_Ropp; eauto. Qed. Lemma irrel_pidist_refl {X} : ∀ I, @irrel_pidist X I I. Proof. intros f Hb; reflexivity. Qed. Lemma irrel_pidist_trans {X} : ∀ I1 I2 I3, @irrel_pidist X I1 I2 → @irrel_pidist X I2 I3 → @irrel_pidist X I1 I3. Proof. intros I1 I2 I3 Hi1 Hi2 f Hb. specialize (Hi1 f Hb). specialize (Hi2 f Hb). etransitivity; eauto. Qed. Lemma bounded_supp_fun_le_pidist {A} f (Is Is': pidist A): le_pidist Is Is' → bounded_fun_on f (λ x, In_psupport x Is') → bounded_fun_on f (λ x, In_psupport x Is). Proof. intros Hle Hbf. eapply bounded_fun_on_anti; try eassumption. intros a. eapply le_pidist_support_coerce_aux; eauto. Qed. Lemma Ex_min_le_pidist_irrel {X} (f: X → R) Is1 Is2: le_pidist_irrel Is1 Is2 → Rbar_le (Ex_min f Is2) (Ex_min f Is1). Proof. intros Hle. rewrite /Ex_min. destruct (Glb_Rbar_correct (Ex_pidist f Is1)) as (Hlb&Hglb). apply Hglb. intros r Hex. destruct Hex as (I&Hin&Hex). edestruct (Hle {| ivd_ival := I; val_sum1 := all_sum1 Is1 _ Hin |}) as (I2&Heq&Hin2). { rewrite //=. } { eapply (is_Ex_ival_irrel_proper f) in Heq; last eauto. destruct (Glb_Rbar_correct (Ex_pidist f Is2)) as (Hlb2&Hglb2). eapply Hlb2. eexists; split; eauto. eapply Heq => //=. } Qed. Lemma Ex_max_le_pidist_irrel {X} (f: X → R) Is1 Is2: le_pidist_irrel Is1 Is2 → Rbar_le (Ex_max f Is1) (Ex_max f Is2). Proof. rewrite ?Ex_max_neg_min. intros Hle. apply Rbar_opp_le. apply Ex_min_le_pidist_irrel; eauto. Qed. Lemma irrel_pidist_proper_irrel {X} : ∀ I1 I1' I2 I2', le_pidist_irrel I1' I1 → le_pidist_irrel I2 I2' → @irrel_pidist X I1 I2 → @irrel_pidist X I1' I2'. Proof. intros I1 I1' I2 I2' Hle1 Hle2 Hirrel12. intros f Hb. etransitivity. { apply Ex_min_le_pidist_irrel; eauto. } etransitivity. { eapply Hirrel12; eauto. } { apply Ex_min_le_pidist_irrel; eauto. } Qed. Lemma irrel_pidist_bind1 {X Y}: ∀ (I1 I2: pidist X) (f: X → pidist Y), @irrel_pidist X I1 I2 → @irrel_pidist Y (x ← I1; f x) (x ← I2; f x). Proof. intros I1 I2 f Hirrel. intros g Hb. rewrite ?Ex_min_bind_post; eauto using Ex_min_bounded_is_bounded, ex_Ex_extrema_bounded_fun, Ex_min_bounded_fun_finite. Qed. Lemma irrel_pidist_bind {X Y}: ∀ (I1 I2: pidist X) (f1 f2: X → pidist Y), @irrel_pidist X I1 I2 → (∀ x, @irrel_pidist Y (f1 x) (f2 x)) → @irrel_pidist Y (x ← I1; f1 x) (x ← I2; f2 x). Proof. intros I1 I2 f1 f2 Hirrel Hirrelfun. eapply irrel_pidist_trans. { eapply irrel_pidist_bind1; eauto. } intros f Hb. eapply Ex_min_bind_le; eauto using Ex_min_bounded_is_bounded, ex_Ex_extrema_bounded_fun, Ex_min_bounded_fun_finite. intros a ?. eapply Hirrelfun; eauto. Qed. Lemma irrel_pidist_proper X : ∀ (I1 I1' I2 I2': pidist X), le_pidist I1' I1 → le_pidist I2 I2' → irrel_pidist I1 I2 → irrel_pidist I1' I2'. Proof. intros ???? Hle1 Hle2. eapply irrel_pidist_proper_irrel. { intros x Hin. edestruct (Hle1 x) as (x'&Heq&Hin'); eauto. exists {| ivd_ival := x'; val_sum1 := all_sum1 I1 _ Hin'|}; split; auto. eapply irrel_ivd_proper; eauto; last apply irrel_ivd_refl. reflexivity. } { intros x Hin. edestruct (Hle2 x) as (x'&Heq&Hin'); eauto. exists {| ivd_ival := x'; val_sum1 := all_sum1 I2' _ Hin'|}; split; auto. eapply irrel_ivd_proper; eauto; last apply irrel_ivd_refl. reflexivity. } Qed. Global Instance irrel_pidist_mono_instance : Proper (@le_pidist X --> @le_pidist X ==> Coq.Program.Basics.impl) (@irrel_pidist X). Proof. intros X I1 I1' Heq1 I2 I2' Heq2. intros Hirrel. eapply irrel_pidist_proper; eauto. Qed. Global Instance irrel_pidist_proper_instance : Proper (@eq_pidist X ==> @eq_pidist X ==> iff) (@irrel_pidist X). Proof. intros X I1 I1' Heq1 I2 I2' Heq2. split; intros Hirrel; eapply irrel_pidist_proper; eauto; try (setoid_rewrite Heq1; reflexivity); try (setoid_rewrite Heq2; reflexivity). Qed. Global Instance irrel_pidist_Transitivite {X}: Transitive (@irrel_pidist X). Proof. intros ???. apply irrel_pidist_trans. Qed. Global Instance irrel_pidist_Reflexive {X}: Reflexive (@irrel_pidist X). Proof. intros ?. apply irrel_pidist_refl. Qed. Record irrel_couplingP {A1 A2} (I1: ivdist A1) (Is2: pidist A2) (P: A1 → A2 → Prop) : Type := { irrel_I : ivdist A1; irrel_Is : pidist A2; irrel_rel_I : irrel_ivd I1 irrel_I; irrel_rel_Is : irrel_pidist irrel_Is Is2; irrel_couple_wit :> idist_pidist_couplingP irrel_I irrel_Is P }. Definition lsupport {A1 A2 Is1 Is2 P} (Icouple: irrel_couplingP Is1 Is2 P) (y: A2) := { x : A1 | ∃ i Hpf, ival.ind Icouple i = (exist _ (x, y) Hpf) ∧ ival.val Icouple i > 0 }. Definition rsupport {A1 A2 Is1 Is2 P} (Icouple: irrel_couplingP Is1 Is2 P) (x: A1) := { y : A2 | ∃ i Hpf, ival.ind Icouple i = (exist _ (x, y) Hpf) ∧ ival.val Icouple i > 0 }. Definition irrel_coupling_propP {A1 A2} (I1: ivdist A1) (Is2: pidist A2) P : Prop := ∃ (ic: irrel_couplingP I1 Is2 P), True. Lemma ic_wit_to_prop {A1 A2} (I1 : ivdist A1) (Is2: pidist A2) P : irrel_couplingP I1 Is2 P → irrel_coupling_propP I1 Is2 P. Proof. intros; eexists; eauto. Qed. Lemma ic_prop_to_wit {A1 A2} (I1 : ivdist A1) (Is2: pidist A2) P : irrel_coupling_propP I1 Is2 P → irrel_couplingP I1 Is2 P. Proof. intros (?&_)%ClassicalEpsilon.constructive_indefinite_description; auto. Qed. Lemma irrel_pidist_support_coerce {X} (I1 I2: pidist X) : irrel_pidist I2 I1 → ∀ x, In_psupport x I2 → In_psupport x I1. Proof. intros Hirrel x Hin. destruct Hin as (I&i&Hin&Hind&Hval). assert (0 < Pr (eq ^~ x) {| ivd_ival := I; val_sum1 := all_sum1 _ _ Hin|}). { eapply In_isupport_pr_gt_0. eexists; eauto. } assert (Rbar_lt 0 (Pr_max (eq^~ x) I1)) as Hmax. { apply (Rbar_lt_le_trans _ (Pr_max (eq^~ x) I2)); last first. { eapply irrel_pidist_Ex_max; eauto. exists 1. intros. destruct (is_left); rewrite Rabs_right; nra. } apply (Rbar_lt_le_trans _ (Pr (eq^~ x) {| ivd_ival := I; val_sum1 := all_sum1 I2 I Hin |})); first done. apply Ex_max_spec1' => //=. eapply (ex_Pr (eq^~x) {| ivd_ival := I; val_sum1 := all_sum1 I2 I Hin |}). } assert (∃ I' : ivdist X, In (I': ival X) I1 ∧ 0 < Pr (eq^~x) I') as (I'&Hin'&Hpr'). { apply Classical_Pred_Type.not_all_not_ex. intros Hneg. apply Rbar_lt_not_le in Hmax. apply Hmax. apply Ex_max_spec2. intros r' (I'&Hin'&Heq). apply Rbar_not_lt_le. intros Hlt. exfalso; eapply (Hneg {| ivd_ival := I'; val_sum1 := all_sum1 _ _ Hin'|}). split; first done. rewrite /Pr. erewrite is_Ex_ival_unique; last eassumption. auto. } exists I'. apply pr_gt_0_In_isupport in Hpr'. destruct Hpr' as (?&?&?). eexists; split_and!; eauto. Qed. Lemma irrel_pidist_choice {X} (I1 I1' I2 I2': pidist X) p Hpf Hpf': irrel_pidist I1 I2 → irrel_pidist I1' I2' → irrel_pidist (pidist_plus p Hpf I1 I1') (pidist_plus p Hpf' I2 I2'). Proof. intros Hirrel1 Hirrel2. transitivity (b ← pidist_plus p Hpf (mret true) (mret false); if (b: bool) then I1 else I1'). { rewrite pidist_plus_bind ?pidist_left_id. reflexivity. } transitivity (b ← pidist_plus p Hpf' (mret true) (mret false); if (b: bool) then I2 else I2'); last first. { rewrite pidist_plus_bind ?pidist_left_id. reflexivity. } apply irrel_pidist_bind. { cut (eq_pidist (pidist_plus p Hpf (mret true) (mret false)) (pidist_plus p Hpf' (mret true) (mret false))). { intros ->; reflexivity. } apply pidist_plus_proper; reflexivity. } intros [|]; eauto. Qed. Lemma irrel_pidist_irrel {X Y}: ∀ I1 (I0: pidist Y), @irrel_pidist X (x ← I0; I1) I1. Proof. intros. intros f Hbounded. rewrite Ex_min_bind_irrel //=; try reflexivity; eauto using Ex_min_bounded_is_bounded, ex_Ex_extrema_bounded_fun, Ex_min_bounded_fun_finite. Qed. Lemma irrel_coupling_proper {A1 A2} (I1 I2 : ivdist A1) (Is1 Is2: pidist A2) P: eq_ivd I1 I2 → eq_pidist Is1 Is2 → irrel_couplingP I1 Is1 P → irrel_couplingP I2 Is2 P. Proof. intros HeqI HeqIs [I1' Is1' HeqI1 HeqIs1 Hcouple]. exists I1' Is1'. - setoid_rewrite <-HeqI. done. - setoid_rewrite <-HeqIs. done. - done. Qed. Lemma irrel_coupling_mono {A1 A2} (I1 I2 : ivdist A1) (Is1 Is2: pidist A2) P: eq_ivd I1 I2 → le_pidist Is1 Is2 → irrel_couplingP I1 Is1 P → irrel_couplingP I2 Is2 P. Proof. intros HeqI HeqIs [I1' Is1' HeqI1 HeqIs1 Hcouple]. exists I1' Is1'. - setoid_rewrite <-HeqI. done. - setoid_rewrite <-HeqIs. done. - done. Qed. Lemma irrel_coupling_mono_irrel {A1 A2} (I1 I2 : ivdist A1) (Is1 Is2: pidist A2) P: eq_ivd I1 I2 → irrel_pidist Is1 Is2 → irrel_couplingP I1 Is1 P → irrel_couplingP I2 Is2 P. Proof. intros HeqI HeqIs [I1' Is1' HeqI1 HeqIs1 Hcouple]. exists I1' Is1'. - setoid_rewrite <-HeqI. done. - setoid_rewrite <-HeqIs. done. - done. Qed. Lemma irrel_coupling_mono_irrel' {A1 A2} (I1 I2 : ivdist A1) (Is1 Is2: pidist A2) P: irrel_ivd I1 I2 → irrel_pidist Is1 Is2 → irrel_couplingP I1 Is1 P → irrel_couplingP I2 Is2 P. Proof. intros HeqI HeqIs [I1' Is1' HeqI1 HeqIs1 Hcouple]. exists I1' Is1'. - setoid_rewrite <-HeqI. done. - setoid_rewrite <-HeqIs. done. - done. Qed. Global Instance irrel_coupling_prop_Proper {A1 A2}: Proper (@eq_ivd A1 ==> @le_pidist A2 ==> eq ==> impl) irrel_coupling_propP. Proof. intros ?? Heq ?? Hle ?? ->. intros H%ic_prop_to_wit. apply ic_wit_to_prop. eapply irrel_coupling_mono; eauto. Qed. Global Instance irrel_coupling_prop_irrel_Proper {A1 A2}: Proper (@eq_ivd A1 ==> @irrel_pidist A2 ==> eq ==> impl) irrel_coupling_propP. Proof. intros ?? Heq ?? Hle ?? ->. intros H%ic_prop_to_wit. apply ic_wit_to_prop. eapply irrel_coupling_mono_irrel; eauto. Qed. Lemma irrel_coupling_mret {A1 A2} (P: A1 → A2 → Prop) x y: P x y → irrel_couplingP (mret x) (mret y) P. Proof. intros HP. exists (mret x) (mret y); try reflexivity. by apply ip_coupling_mret. Qed. Lemma irrel_coupling_prop_mret {A1 A2} (P: A1 → A2 → Prop) x y: P x y → irrel_coupling_propP (mret x) (mret y) P. Proof. intros; apply ic_wit_to_prop, irrel_coupling_mret; auto. Qed. Lemma irrel_coupling_bind {A1 A2 B1 B2} P (f1: A1 → ivdist B1) (f2: A2 → pidist B2) I1 Is2 Q (Ic: irrel_couplingP I1 Is2 P): (∀ x y, P x y → irrel_couplingP (f1 x) (f2 y) Q) → irrel_couplingP (mbind f1 I1) (mbind f2 Is2) Q. Proof. intros Hfc. destruct Ic as [I1' Is2' HeqI HeqIs Hcouple]. destruct Hcouple as [I2' ? [Ic ? ?]%ic_coupling_to_id]. unshelve (eexists). - refine (xy ← Ic; _). destruct xy as ((x&y)&HP). destruct (Hfc _ _ HP). exact irrel_I0. - refine (xy ← singleton Ic; _). destruct xy as ((x&y)&HP). destruct (Hfc x y HP). exact irrel_Is0. - etransitivity. { eapply irrel_ivd_bind. eauto. reflexivity. } etransitivity. { eapply irrel_ivd_bind. setoid_rewrite idc_proj1. reflexivity. reflexivity. } setoid_rewrite ivd_assoc. eapply irrel_ivd_bind; first reflexivity. intros ((x&y)&HP). destruct (Hfc _ _ _) as [? ? ?]. rewrite /irrel_I. rewrite /sval. setoid_rewrite ivd_left_id. done. - etransitivity; last first. { eapply irrel_pidist_bind. - etransitivity; last by eauto. eapply irrel_pidist_proper; first by eauto. reflexivity. reflexivity. - intros; reflexivity. } setoid_rewrite idc_proj2. setoid_rewrite singleton_bind. setoid_rewrite pidist_assoc. eapply irrel_pidist_bind; first reflexivity. intros ((x&y)&HP). destruct (Hfc _ _ _) as [? ? ?]. rewrite /irrel_I. rewrite /sval. setoid_rewrite singleton_mret. setoid_rewrite pidist_left_id. eauto. - eapply (ip_coupling_bind _ _ _ _ (λ x y, x = y)). * apply ip_coupling_singleton. * intros ((?&?)&HP1) ((x&y)&HP2). inversion 1; subst. rewrite //=. assert (HP1 = HP2). { apply classical_proof_irrelevance. } subst. destruct (Hfc x y HP2). eauto. Qed. Lemma irrel_coupling_prop_bind {A1 A2 B1 B2} P (f1: A1 → ivdist B1) (f2: A2 → pidist B2) I1 Is2 Q (Ic: irrel_coupling_propP I1 Is2 P): (∀ x y, P x y → irrel_coupling_propP (f1 x) (f2 y) Q) → irrel_coupling_propP (mbind f1 I1) (mbind f2 Is2) Q. Proof. intros; eapply ic_wit_to_prop, irrel_coupling_bind; intros; apply ic_prop_to_wit; eauto. Qed. Lemma irrel_coupling_trivial {A1 A2} (I: ivdist A1) (Is: pidist A2): irrel_couplingP I Is (λ x y, True). Proof. assert ({ I' : ivdist A2 | In (I': ival A2) Is}) as (I'&Hin). { destruct Is as [(Is&Hne) Hall] => //=. rewrite //= in Hall. apply ClassicalEpsilon.constructive_indefinite_description in Hne as (I'&His). exists {| ivd_ival := I'; val_sum1 := Hall _ His |}. auto. } exists (x ← I'; I) (singleton (x ← I; I')). { eapply irrel_ivd_irrel. } { eapply irrel_pidist_proper_irrel; [| apply le_pidist_irrel_refl | reflexivity ]. intros I0 Hin'. inversion Hin' as [Heq]. exists I'; split; auto. eapply (irrel_ivd_proper _ (x ← I; I')). { rewrite /eq_ivd. rewrite -Heq //=. } { reflexivity. } symmetry. apply irrel_ivd_irrel. } exists (x ← I; I'). { intros ?. eapply In_pidist_le_singleton. eexists; split; first reflexivity. rewrite /In/singleton//=. } unshelve (eexists). { refine (ivd_ival (x ← I; y ← I'; mret _)). exists (x, y); done. } - setoid_rewrite ival_bind_comm. setoid_rewrite ival_assoc. eapply ival_bind_congr; first reflexivity. intros. setoid_rewrite ival_bind_mret_mret. setoid_rewrite ival_right_id. reflexivity. - setoid_rewrite ival_assoc. eapply ival_bind_congr; first reflexivity. intros. setoid_rewrite ival_bind_mret_mret. setoid_rewrite ival_right_id. reflexivity. Qed. Lemma irrel_coupling_prop_trivial {A1 A2} (I: ivdist A1) (Is: pidist A2): irrel_coupling_propP I Is (λ x y, True). Proof. apply ic_wit_to_prop, irrel_coupling_trivial. Qed. Lemma irrel_coupling_conseq {A1 A2} (P1 P2: A1 → A2 → Prop) (I: ivdist A1) (Is: pidist A2): (∀ x y, P1 x y → P2 x y) → irrel_couplingP I Is P1 → irrel_couplingP I Is P2. Proof. intros HP Hirrel. destruct Hirrel as [I0 Is0 ? ? ?]. exists I0 Is0; auto. eapply ip_coupling_conseq; eauto. Qed. Lemma irrel_coupling_plus {A1 A2} p Hpf p' Hpf' (P : A1 → A2 → Prop) (Is1 Is1': ivdist A1) (Is2 Is2': pidist A2) : p = p' → irrel_couplingP Is1 Is2 P → irrel_couplingP Is1' Is2' P → irrel_couplingP (ivdplus p Hpf Is1 Is1') (pidist_plus p' Hpf' Is2 Is2') P. Proof. intros Hpeq Hic Hic'. subst. destruct Hic as [I1i Is2i Hirrel1i Hirrel2i Hwit]. destruct Hic' as [I1i' Is2i' Hirrel1i' Hirrel2i' Hwit']. exists (ivdplus p' Hpf I1i I1i') (pidist_plus p' Hpf' Is2i Is2i'). { eapply irrel_ivd_choice; eauto. } { eapply irrel_pidist_choice; eauto. } apply ip_coupling_plus; eauto. Qed. Lemma irrel_coupling_bind_condition {A1 B1 B2} (f1: A1 → ivdist B1) (f2: A1 → pidist B2) I Is Q x: (le_pidist (singleton I) Is ) → (irrel_couplingP (f1 x) (f2 x) Q) → irrel_couplingP (x ← I; y ← f1 x; mret (x, y)) (x ← Is; y ← f2 x; mret (x, y)) (λ xy1 xy2, fst xy1 = x → fst xy2 = x → Q (snd xy1) (snd xy2)). Proof. intros Hle Hc. eapply (irrel_coupling_bind (λ x y, x = y)). { exists I Is; try reflexivity. exists I; eauto. apply ival_coupling_refl. } intros ? y ?; subst. destruct (ClassicalEpsilon.excluded_middle_informative (x = y)). - intros; subst. eapply irrel_coupling_bind; eauto. intros. apply irrel_coupling_mret => ? //=. - intros. eapply irrel_coupling_bind. * apply irrel_coupling_trivial. * intros. apply irrel_coupling_mret => ? //=. intros. congruence. Qed. Lemma irrel_coupling_support {X Y} I1 I2 (P: X → Y → Prop): ∀ (Ic: irrel_couplingP I1 I2 P), irrel_couplingP I1 I2 (λ x y, ∃ Hpf: P x y, In_isupport x I1 ∧ In_psupport y I2 ∧ In_isupport (exist _ (x, y) Hpf) Ic). Proof. intros [? ? Heq1 Heq2 Ic]. specialize (ip_coupling_support _ _ _ Ic). eexists; eauto. eapply ip_coupling_conseq; eauto. intros x y (Hpf&Hin1&Hin2&?); exists Hpf; repeat split; auto. - edestruct Hin1 as (i&?&?). edestruct (irrel_ivd_support_coerce _ _ Heq1) as (Hcoerce&_). apply Hcoerce; eauto. - eapply irrel_pidist_support_coerce; eauto. Qed. Lemma irrel_coupling_support_wit {X Y} I1 I2 (P: X → Y → Prop): ∀ (Ic: irrel_couplingP I1 I2 P), { xy : X * Y | ∃ Hpf : P (fst xy) (snd xy), In_isupport (fst xy) I1 ∧ In_psupport (snd xy) I2 ∧ In_isupport (exist _ xy Hpf) Ic }. Proof. intros [? ? Heq1 Heq2 Ic]. specialize (ip_coupling_support_wit _ _ _ Ic). rewrite //=. intros ((x&y)&Hpf). exists (x, y). destruct Hpf as (Hpf&Hin1&Hin2&?). exists Hpf; repeat split; auto. - edestruct Hin1 as (i&?&?). edestruct (irrel_ivd_support_coerce _ _ Heq1) as (Hcoerce&_). apply Hcoerce; eauto. - eapply irrel_pidist_support_coerce; eauto. Qed. Lemma rsupport_support_right {X Y} (Ix: ivdist X) (x: X) Is (P: X → Y → Prop) (Ic: irrel_couplingP Ix Is P) (c: rsupport Ic x) : In_psupport (proj1_sig c) Is. Proof. destruct c as (y'&ic&HP&Hind&Hgt). rewrite //=. destruct Ic as [Ix' Is' Hirrel_ivd Hirrel_pidist Ic]. eapply irrel_pidist_support_coerce; eauto. destruct Ic as [Iy Hle Ic]. rewrite //= in ic Hind Hgt. clear Hirrel_pidist. destruct (irrel_ivd_support_coerce _ _ Hirrel_ivd x) as (Hcoerce&_). destruct (Hle Iy) as (Iy'&Heq&Hin); first by auto. destruct Ic as [Ic Hproj1 Hproj2]. rewrite //= in ic Hind Hgt. symmetry in Hproj2. setoid_rewrite Heq in Hproj2. destruct Hproj2 as (h1&h2&?&?&Hindic&Hvalic). assert (val (x0 ← Ic; mret (sval x0).2) (existT ic tt) > 0) as Hgt'. { rewrite //= Rmult_1_r //=. } specialize (Hindic (coerce_supp _ _ Hgt')). specialize (Hvalic (coerce_supp _ _ Hgt')). rewrite //= in Hindic Hvalic. exists Iy'. exists (sval (h1 (coerce_supp _ _ Hgt'))). repeat split; auto. - rewrite Hindic Hind //=. - rewrite Hvalic //=. Qed. Lemma rsupport_post {X Y} (Ix: ivdist X) (x: X) Is (P: X → Y → Prop) (Ic: irrel_couplingP Ix Is P) (c: rsupport Ic x) : P x (proj1_sig c). Proof. destruct c as (y&I&i&Hind&?). rewrite //=. Qed. Transparent pidist_ret. Lemma rsupport_mret_right {X Y} (Ix: ivdist X) (x: X) (y: Y) (P: X → Y → Prop) (Ic: irrel_couplingP Ix (mret y) P) (c: rsupport Ic x) : proj1_sig c = y. Proof. edestruct (rsupport_support_right _ _ _ _ Ic c) as (Iy&iy&Hin&Hind&?). subst; rewrite -Hind //=. rewrite /In/mret/base.mret//= in Hin. subst. destruct iy => //=. Qed. Opaque pidist_ret. Lemma ip_irrel_coupling {A1 A2} (I: ivdist A1) (Is: pidist A2) (P: A1 → A2 → Prop): idist_pidist_couplingP I Is P → irrel_couplingP I Is P. Proof. intros. exists I Is; try reflexivity; eauto. Qed. Lemma irrel_bounded_supp_fun {A} f (Is Is': pidist A): irrel_pidist Is Is' → bounded_fun_on f (λ x, In_psupport x Is') → bounded_fun_on f (λ x, In_psupport x Is). Proof. intros Hle Hbf. eapply bounded_fun_on_anti; try eassumption. eapply irrel_pidist_support_coerce; eauto. Qed. Lemma irrel_pidist_bounded_supp_Ex_max {A} f (Is Is': pidist A): irrel_pidist Is Is' → bounded_fun_on f (λ x, In_psupport x Is') → Rbar_le (Ex_max f Is) (Ex_max f Is'). Proof. intros Hi Hb1. feed pose proof (irrel_bounded_supp_fun f Is Is') as Hb2; eauto. assert (bounded_fun_on f (λ x, In_psupport x Is ∨ In_psupport x Is')) as Hb. { destruct Hb1 as (c1&?). destruct Hb2 as (c2&?). exists (Rmax c1 c2). intros x [Hin1|Hin2]; rewrite Rmax_Rle; intuition. } clear Hb1. clear Hb2. edestruct (bounded_fun_on_to_bounded f) as (g'&Hb'&Heq); eauto. feed pose proof (irrel_pidist_Ex_max Is Is' Hi g' Hb'); eauto. erewrite (Ex_max_eq_ext_supp f g' Is'); eauto. etransitivity; eauto. erewrite (Ex_max_eq_ext_supp f g' Is); eauto; first reflexivity. Qed. Lemma Ex_min_irrel_anti {A} f (Is Is': pidist A) : irrel_pidist Is Is' → bounded_fun f → Rbar_le (Ex_min f Is') (Ex_min f Is). Proof. eauto. Qed. Lemma irrel_coupling_eq_ex_Ex {A1 A2} f g (I: ivdist A1) (Is: pidist A2) : irrel_couplingP I Is (λ x y, f x = g y) → bounded_fun g → ex_Ex_ival f I. Proof. intros [Is1_irrel Is2_irrel Hirrel_ivd Hirrel_pidst Ic] Hex. assert (idist_pidist_couplingP (x ← Is1_irrel; mret (f x)) (x ← Is2_irrel; mret (g x)) (λ x y, x = y)) as Ic'. { eapply ip_coupling_bind; eauto => ???. apply ip_coupling_mret; auto. } destruct Ic' as [I2 Hmem Ic']. apply ival_coupling_eq in Ic'. eapply ex_Ex_ival_irrel_proper. { symmetry; eauto. } rewrite (ex_Ex_ival_fmap id f). setoid_rewrite Ic'. cut (ex_Ex_extrema id (x ← Is2_irrel; mret (g x))). { intros Hex'. edestruct (Hmem I2) as (I2'&Heq'&?); first done. rewrite Heq'. eapply Hex'; eauto. } rewrite -ex_Ex_extrema_fmap. eauto. eapply ex_Ex_extrema_bounded_fun. eauto. Qed. Lemma irrel_coupling_eq_Ex_min {A1 A2} f g (I: ivdist A1) (Is: pidist A2) : irrel_couplingP I Is (λ x y, f x = g y) → bounded_fun g → Rbar_le (Ex_min g Is) (Ex_ival f I). Proof. intros Hirrel Hb. feed pose proof (irrel_coupling_eq_ex_Ex f g I Is) as Hex; eauto. destruct Hirrel as [Is1_irrel Is2_irrel Hirrel_ivd Hirrel_pidst Ic]. assert (idist_pidist_couplingP (x ← Is1_irrel; mret (f x)) (x ← Is2_irrel; mret (g x)) (λ x y, x = y)) as Ic'. { eapply ip_coupling_bind; eauto => ???. apply ip_coupling_mret; auto. } destruct Ic' as [I2 Hmem Ic']. apply ival_coupling_eq in Ic'. etransitivity; first apply Ex_min_irrel_anti; eauto. erewrite Ex_ival_irrel_proper; eauto. transitivity (Ex_min (λ x, Ex_min id (mret (g x))) Is2_irrel). { apply Ex_min_le_ext. * intros. rewrite Ex_min_mret. reflexivity. * eapply ex_Ex_extrema_bounded_fun; eauto. } assert (ex_Ex_ival f Is1_irrel). { eapply ex_Ex_ival_irrel_proper; eauto. } etransitivity; first eapply Ex_min_bind_post_aux2; last first. - transitivity (Ex_ival (λ x, Ex_ival id (mret (f x))) Is1_irrel); last first. { apply Ex_ival_mono. * intros. rewrite Ex_ival_mret. reflexivity. * setoid_rewrite Ex_ival_mret. eapply ex_Ex_ival_irrel_proper; eauto. * eapply ex_Ex_ival_irrel_proper; eauto. } rewrite -Ex_ival_bind_post; last first. { rewrite -ex_Ex_ival_fmap. eauto. } transitivity (Ex_ival id I2); last first. { refl_right. f_equal. symmetry. eapply Ex_ival_proper; eauto. rewrite -ex_Ex_ival_fmap. eauto. } apply In_pidist_le_singleton in Hmem. destruct Hmem as (I2'&Heq22'&?). transitivity (Ex_ival id I2'); last first. { refl_right. f_equal. symmetry. eapply Ex_ival_proper; eauto. eapply ex_Ex_ival_proper; eauto. rewrite -ex_Ex_ival_fmap. eauto. } apply Ex_min_spec1'; auto. eapply ex_Ex_ival_proper; eauto. eapply ex_Ex_ival_proper; eauto. rewrite -ex_Ex_ival_fmap. eauto. - setoid_rewrite Ex_min_mret. apply ex_Ex_extrema_bounded_fun; eauto. - intros. setoid_rewrite Ex_min_mret. rewrite //=. - apply Ex_min_bounded_fun_finite. setoid_rewrite Ex_min_mret. eauto. Qed. Lemma irrel_coupling_eq_Ex_min' {A1 A2 A3} f g (h : A3 → R) (I: ivdist A1) (Is: pidist A2) : irrel_couplingP I Is (λ x y, f x = g y) → bounded_fun (λ x, h (g x)) → Rbar_le (Ex_min (λ x, h (g x)) Is) (Ex_ival (λ x, h (f x)) I). Proof. intros Hic Hb. eapply irrel_coupling_eq_Ex_min; eauto. eapply irrel_coupling_conseq; eauto. rewrite //=. intros x y ->. done. Qed. Lemma irrel_coupling_eq_Ex_max {A1 A2} f g (I: ivdist A1) (Is: pidist A2): irrel_couplingP I Is (λ x y, f x = g y) → bounded_fun g → Rbar_le (Ex_ival f I) (Ex_max g Is). Proof. intros HIc Hb. apply Rbar_opp_le. rewrite Ex_max_neg_min Rbar_opp_involutive. rewrite /Rbar_opp//=. rewrite -Ex_ival_negate. apply irrel_coupling_eq_Ex_min; eauto. - eapply irrel_coupling_conseq; eauto => x y ?. nra. - destruct Hb as (c&Hb). exists c; intros x. specialize (Hb x). move: Hb. do 2 apply Rabs_case; nra. Qed. Lemma irrel_coupling_eq_ex_Ex_supp {A1 A2} f g (I: ivdist A1) (Is: pidist A2) : irrel_couplingP I Is (λ x y, f x = g y) → bounded_fun_on g (λ x, In_psupport x Is) → ex_Ex_ival f I. Proof. intros Hi Hex. edestruct (bounded_fun_on_to_bounded g) as (g'&?Hb&Heq); eauto. feed pose proof (irrel_coupling_eq_ex_Ex f g' I Is); eauto. eapply irrel_coupling_conseq; last first. { unshelve (eapply @irrel_coupling_support); last eapply Hi. } rewrite //=. intros x y (Hpf&Hin&Hinp&?). rewrite -Heq; eauto. Qed. Lemma irrel_coupling_eq_Ex_min_supp {A1 A2} f g (I: ivdist A1) (Is: pidist A2) : irrel_couplingP I Is (λ x y, f x = g y) → bounded_fun_on g (λ x, In_psupport x Is) → Rbar_le (Ex_min g Is) (Ex_ival f I). Proof. intros Hi Hex. edestruct (bounded_fun_on_to_bounded g) as (g'&?Hb&Heq); eauto. feed pose proof (irrel_coupling_eq_Ex_min f g' I Is); eauto. eapply irrel_coupling_conseq; last first. { unshelve (eapply @irrel_coupling_support); last eapply Hi. } rewrite //=. intros x y (Hpf&Hin&Hinp&?). rewrite -Heq; eauto. etransitivity; last eassumption. refl_right. eapply Ex_min_eq_ext_supp. eauto. Qed. Lemma irrel_coupling_eq_Ex_max_supp {A1 A2} f g (I: ivdist A1) (Is: pidist A2): irrel_couplingP I Is (λ x y, f x = g y) → bounded_fun_on g (λ x, In_psupport x Is) → Rbar_le (Ex_ival f I) (Ex_max g Is). Proof. intros HIc Hb. apply Rbar_opp_le. rewrite Ex_max_neg_min Rbar_opp_involutive. rewrite /Rbar_opp//=. rewrite -Ex_ival_negate. apply irrel_coupling_eq_Ex_min_supp; eauto. - eapply irrel_coupling_conseq; eauto => x y ?. nra. - destruct Hb as (c&Hb). exists c; intros x Hin. specialize (Hb x Hin). move: Hb. do 2 apply Rabs_case; nra. Qed.
The Moorish Revival synagogue , designed after the <unk> Tempel in Vienna , was located on modern @-@ day Praška Street . It has been the only purpose @-@ built Jewish house of worship in the history of the city . It was one of the city 's most prominent public buildings , as well as one of the most esteemed examples of synagogue architecture in the region .
function varargout = exp(varargin) %EXP (overloaded) switch class(varargin{1}) case 'double' % What is the numerical value of this argument (needed for displays etc) % SHOULD NEVER HAPPEN, THIS SHOULD BE CAUGHT BY BUILT-IN error('Overloaded SDPVAR/NORM CALLED WITH DOUBLE. Report error') case 'sdpvar' % Overloaded operator for SDPVAR objects. Pass on args and save them. if length(varargin{1}) == 1 varargout{1} = yalmip('addEvalVariable',mfilename,varargin{1}); else y = []; for i = 1:length(varargin{1}) y = [y;yalmip('addEvalVariable',mfilename,extsubsref(varargin{1},i))]; end varargout{1} = y; end case 'char' % YALMIP sends 'model' when it wants the epigraph or hypograph switch varargin{1} case 'graph' t = varargin{2}; X = varargin{3}; % This is different from so called extended operators % Just do it! F = SetupEvaluationVariable(varargin{:}); % Now add your own code, such as domain constraints. % Exponential does not need any domain constraint. % Let YALMIP know about convexity etc varargout{1} = F; varargout{2} = struct('convexity','convex','monotonicity','increasing','definiteness','positive'); varargout{3} = X; case 'milp' varargout{1} = []; varargout{2} = []; varargout{3} = []; otherwise error('SDPVAR/EXP called with CHAR argument?'); end otherwise error('SDPVAR/EXP called with CHAR argument?'); end
function mori = parents(mori) % variants of an orientation relationship % % Syntax % % ori_parents = ori_child * inv(mori.parents) % % Input % mori - child to parent @orientation relationship % ori_child - child orientation % % Output % ori_parents - all possible parent @orientation % % Example % % parent symmetry % cs_fcc = crystalSymmetry('m-3m', [3.6599 3.6599 3.6599], 'mineral', 'Iron fcc'); % % % child symmetry % cs_bcc = crystalSymmetry('m-3m', [2.866 2.866 2.866], 'mineral', 'Iron bcc') % % % define a bcc child orientation % ori_bcc = orientation.goss(cs_bcc) % % % define Nishiyama Wassermann fcc to bcc orientation relation ship % NW = orientation.NishiyamaWassermann (cs_fcc,cs_bcc) % % % compute a fcc parent orientation related to the bcc child orientation % ori_fcc = ori_bcc * NW % % % compute all symmetrically possible parent orientations % ori_fcc = unique(ori_bcc.symmetrise * NW) % % % same using the function parents % ori_fcc2 = ori_bcc * NW.parents % % See also % orientation/variants % % store child symmetry CS_child = mori.SS; % symmetrise only with respect to child symmetry mori = CS_child * mori; % ignore all variants symmetrically equivalent % with respect to the parent symmetry mori.SS = crystalSymmetry('1'); mori = unique(mori); mori.SS = CS_child;
{-# LANGUAGE ScopedTypeVariables #-} module Math.Probably.NelderMead where import Math.Probably.FoldingStats import Data.Ord import Data.List import Data.Maybe import Debug.Trace import Foreign.Storable import qualified Data.Vector.Storable as V import qualified Numeric.LinearAlgebra as L {-mean, m2 :: V.Vector Double mean = fromList [45.1,10.3] cov :: Matrix Double cov = (2><2) $ [5.0, 1, 1, 1.5] invCov = inv cov lndet = log $ det cov pdf = multiNormalByInv lndet invCov mean m2 = fromList [55.1,20.3] main = runRIO $ do io $ print $ pdf mean ap <- nmAdaMet (defaultAM {nsam =1000000}) pdf (fromList [3.0,0.8]) {-iniampar <- sample $ initialAdaMet 500 5e-3 (pdf) $ fromList [30.0,8.0] io $ print iniampar froampar <- runAndDiscard 5000 (show . ampPar) iniampar $ adaMet False (pdf) io $ print froampar io $ print $ realToFrac (count_accept froampar) / (realToFrac $ count froampar) -} let iniSim = genInitial (negate . pdf) 0.1 $ fromList [3.0,0.5] io $ mapM_ print iniSim let finalSim = goNm (negate . pdf) 1 iniSim io $ print $ finalSim io $ print $ hessianFromSimplex (negate . pdf) finalSim -} type Simplex = [(V.Vector Double, Double)] {-instance (Storable a, Num a) => Num (V.Vector a) where (+) = V.zipWith (+) (-) = V.zipWith (-) (*) = V.zipWith (*) -} scale x = V.map (*x) centroid :: Simplex -> V.Vector Double centroid points = scale (recip l) $ sum $ map fst points where l = fromIntegral $ length points nmAlpha = 1 nmGamma = 2 nmRho = 0.5 nmSigma = 0.5 secondLast (x:y:[]) = x secondLast (_:xs) = secondLast xs replaceLast xs x = init xs ++ [x] {-hessianFromSimplex :: (V.Vector Double -> Double) -> [Int] -> [((Int, Int), Double)] -> Simplex -> (V.Vector Double, Matrix Double) hessianFromSimplex f isInt fixed sim = let mat :: [V.Vector Double] mat = toRows $ fromColumns $ map fst sim fsw ((y0, ymin),ymax) = (y0, max (ymax-y0) (y0-ymin)) swings = flip map mat $ runStat (fmap fsw $ meanF `both` minFrom 1e80 `both` maxFrom (-1e80)) . toList n = length swings xv = fromList $ map fst swings fxv = f xv fixedpts = map fst fixed iswings i | i `elem` isInt = atLeastOne $snd $ swings!!i | otherwise = snd $ swings!!i funits d i | d/=i = 0 | i `elem` isInt = atLeastOne $ snd $ swings!!i | otherwise = snd $ swings!!i units = flip map [0..n-1] $ \d -> V.generate n $ funits d --http://www.caspur.it/risorse/softappl/doc/sas_docs/ormp/chap5/sect28.htm fhess ij@ (i,j) | ij `elem` fixedpts = fromJust $ lookup ij fixed | i>=j = ((f $ xv + units!!i + units!!j) - (f $ xv + units!!i - units!!j) - (f $ xv - units!!i + units!!j) + (f $ xv - units!!i - units!!j) ) / (4*(iswings i) * (iswings j)) | otherwise = 0.0 hess1= buildMatrix n n fhess hess2 = buildMatrix n n $ \(i,j) ->if i>=j then hess1@@>(i,j) else hess1@@>(j,i) -- we probably ought to make pos-definite -- http://www.mathworks.com/matlabcentral/newsreader/view_thread/103174 -- posdefify in R etc in (fromList (map (fst) swings), hess2) -} atLeastOne :: Double -> Double atLeastOne x | isNaN x || isInfinite x = 1.0 | x < -1.0 || x > 1.0 = realToFrac $ round x | x < 0 = -1.0 | otherwise = 1.0 genInitial :: (V.Vector Double -> Double) -> [Int] -> (Int -> Double) -> V.Vector Double -> Simplex genInitial f isInt h x0 = sim where n = length $ V.toList x0 unit d = V.generate n $ \j -> if j /=d then 0.0 else if d `elem` isInt then atLeastOne $ h j*(x0!d) else h j*(x0!d) mkv d = with f $ x0 + unit d sim = (x0, f x0) : map mkv [0..n-1] (!) = (V.!) goNm :: (V.Vector Double -> Double) -> [Int] -> Double -> Int -> Int -> Simplex -> Simplex goNm f' isInt tol nmin nmax sim' = go f' 0 $ sortBy (comparing snd) sim' where go f i sim = let nsim = sortBy (comparing snd) $ (nmStep f isInt sim) fdiff = abs $ snd (last nsim) - snd (head nsim) in case () of _ | (fdiff < tol && i>nmin) || i>nmax -> nsim | all (<0) (map snd sim) && any (>0) (map snd nsim) -> sim | any (isNaN) (map snd nsim) -> sim | otherwise -> go f (i+1) nsim goNmVerbose :: (V.Vector Double -> Double) -> [Int] -> Double -> Int -> Int -> Simplex -> Simplex goNmVerbose f' isInt tol nmin nmax sim' = go f' 0 $ sortBy (comparing snd) sim' where go f i sim = let nsim = sortBy (comparing snd) $ (nmStep f isInt sim) fdiff = trace ("1: "++ show (fst (head nsim)) ++ "\nlast: "++ show (fst (last nsim)) ++ "\n#"++show i++": "++ show (map snd nsim)) abs $ snd (last nsim) - snd (head nsim) in case () of _ | (fdiff < tol && i>nmin) || i>nmax -> nsim | all (<0) (map snd sim) && any (>0) (map snd nsim) -> sim | any (isNaN) (map snd nsim) -> sim | otherwise -> go f (i+1) nsim nmStep :: (V.Vector Double -> Double) -> [Int] -> Simplex -> Simplex nmStep f isInt s0 = snext where x0 = centroid $ init s0 xnp1 = fst (last s0) fxnp1 = snd (last s0) xr = x0 + nmAlpha * (x0 - xnp1) fxr = f xr fx1 = snd $ head s0 snext = if fx1 <= fxr && fxr <= (snd $ secondLast s0) then replaceLast s0 (xr,fxr) else sexpand xe = x0 + nmGamma * (x0-xnp1) fxe = f xe sexpand = if fxr > fx1 then scontract else if fxe < fxr then replaceLast s0 (xe,fxe) else replaceLast s0 (xr,fxr) xc = xnp1 + scale nmRho (x0-xnp1) fxc = f xc scontract = if fxc < fxnp1 then replaceLast s0 (xc,fxc) else sreduce sreduce = case s0 of p0@(x1,_):rest -> p0 : (flip map rest $ \(xi,_) -> with f $ x1+ scale nmRho (xi-x1)) with f x = (x, f x)
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE Strict #-} module FourierPinwheel.GaussianEnvelopePinwheel where import Data.Array.Repa as R import Data.Complex import Data.Vector.Generic as VG import Data.Vector.Unboxed as VU import FourierPinwheel.Hypergeo1F1 import Math.Gamma import Pinwheel.FourierSeries2D import Utils.Distribution import Utils.Parallel -- The Fourier coefficients of e^{-a^2 r^2} r^\mu {-# INLINE gaussianPinwheelFourierCoefficients #-} gaussianPinwheelFourierCoefficients :: (RealFloat a, Gamma (Complex a), Enum a) => Int -> a -> a -> a -> Int -> Int -> a -> a -> a -> Complex a gaussianPinwheelFourierCoefficients numR2Freqs periodR2 a sigma angularFreq radialFreq periodEnv phi rho = let periodConst = (-2) * pi / log periodEnv piRhoPConst = pi * rho / periodR2 real = pi / periodR2 ^ 2 * piRhoPConst ^ abs angularFreq mu = (2 + sigma + fromIntegral (abs angularFreq)) :+ (periodConst * fromIntegral radialFreq) alpha = mu / 2 beta = fromIntegral (1 + abs angularFreq) :+ 0 z = ((-1) * (piRhoPConst / a) ^ 2) :+ 0 img = (0 :+ (-1)) ^ abs angularFreq * cis (fromIntegral (-angularFreq) * phi) * gamma alpha / gamma beta * (a :+ 0) ** (-mu) * hypergeom alpha beta z in (real :+ 0) * img gaussianPinwheel :: ( RealFloat a , Gamma (Complex a) , Enum a , Unbox a , VG.Vector vector (Complex a) , NFData (vector (Complex a)) ) => Int -> a -> a -> a -> Int -> Int -> a -> a -> a -> vector (Complex a) gaussianPinwheel numR2Freqs periodR2 stdR2 sigma thetaFreq rFreq periodEnv stdTheta stdR = let zeroVec = VG.replicate (numR2Freqs ^ 2) 0 a = 1 / (stdR2 * sqrt 2) in VG.concat . parMap rdeepseq (\(radialFreq, angularFreq) -> if angularFreq == 0 then let pinwheel = centerHollowArray numR2Freqs $ createFrequencyArray numR2Freqs (gaussianPinwheelFourierCoefficients numR2Freqs periodR2 a sigma angularFreq radialFreq periodEnv) arr = R.map (* ((gaussian1DFourierCoefficients (fromIntegral radialFreq) (log periodEnv) stdR) :+ 0)) $ centerHollowArray numR2Freqs pinwheel in VG.convert . toUnboxed . computeS $ arr else zeroVec) $ [ (radialFreq, angularFreq) | radialFreq <- [-rFreq .. rFreq] , angularFreq <- [-thetaFreq .. thetaFreq] ] -- This one has a orientation preference at 0 degree. It is used for Koffka cross problem. gaussianPinwheel1 :: ( RealFloat a , Gamma (Complex a) , Enum a , Unbox a , VG.Vector vector (Complex a) , NFData (vector (Complex a)) ) => Int -> a -> a -> a -> Int -> Int -> a -> a -> a -> vector (Complex a) gaussianPinwheel1 numR2Freqs periodR2 stdR2 sigma thetaFreq rFreq periodEnv stdTheta stdR = let a = 1 / (stdR2 * sqrt 2) in VG.concat . parMap rdeepseq (\(radialFreq, angularFreq) -> let pinwheel = centerHollowArray numR2Freqs $ createFrequencyArray numR2Freqs (gaussianPinwheelFourierCoefficients numR2Freqs periodR2 a sigma 0 radialFreq periodEnv) arr = R.map (* ((gaussian1DFreq (fromIntegral angularFreq) stdTheta * gaussian1DFourierCoefficients (fromIntegral radialFreq) (log periodEnv) stdR) :+ 0)) $ centerHollowArray numR2Freqs pinwheel in VG.convert . toUnboxed . computeS $ arr) $ [ (radialFreq, angularFreq) | radialFreq <- [-rFreq .. rFreq] , angularFreq <- [-thetaFreq .. thetaFreq] ]
State Before: n m k : ℕ ⊢ lor' (lor' n m) k = lor' n (lor' m k) State After: no goals Tactic: bitwise_assoc_tac
section "Frequency Moments" theory Frequency_Moments imports Frequency_Moments_Preliminary_Results Universal_Hash_Families.Field Interpolation_Polynomials_HOL_Algebra.Interpolation_Polynomial_Cardinalities begin text \<open>This section contains a definition of the frequency moments of a stream and a few general results about frequency moments..\<close> definition F where "F k xs = (\<Sum> x \<in> set xs. (rat_of_nat (count_list xs x)^k))" lemma F_ge_0: "F k as \<ge> 0" unfolding F_def by (rule sum_nonneg, simp) lemma F_gr_0: assumes "as \<noteq> []" shows "F k as > 0" proof - have "rat_of_nat 1 \<le> rat_of_nat (card (set as))" using assms card_0_eq[where A="set as"] by (intro of_nat_mono) (metis List.finite_set One_nat_def Suc_leI neq0_conv set_empty) also have "... = (\<Sum>x\<in>set as. 1)" by simp also have "... \<le> (\<Sum>x\<in>set as. rat_of_nat (count_list as x) ^ k)" by (intro sum_mono one_le_power) (metis count_list_gr_1 of_nat_1 of_nat_le_iff) also have "... \<le> F k as" by (simp add:F_def) finally show ?thesis by simp qed definition P\<^sub>e :: "nat \<Rightarrow> nat \<Rightarrow> nat list \<Rightarrow> bool list option" where "P\<^sub>e p n f = (if p > 1 \<and> f \<in> bounded_degree_polynomials (Field.mod_ring p) n then ([0..<n] \<rightarrow>\<^sub>e Nb\<^sub>e p) (\<lambda>i \<in> {..<n}. ring.coeff (Field.mod_ring p) f i) else None)" lemma poly_encoding: "is_encoding (P\<^sub>e p n)" proof (cases "p > 1") case True interpret cring "Field.mod_ring p" using mod_ring_is_cring True by blast have a:"inj_on (\<lambda>x. (\<lambda>i \<in> {..<n}. (coeff x i))) (bounded_degree_polynomials (mod_ring p) n)" proof (rule inj_onI) fix x y assume b:"x \<in> bounded_degree_polynomials (mod_ring p) n" assume c:"y \<in> bounded_degree_polynomials (mod_ring p) n" assume d:"restrict (coeff x) {..<n} = restrict (coeff y) {..<n}" have "coeff x i = coeff y i" for i proof (cases "i < n") case True then show ?thesis by (metis lessThan_iff restrict_apply d) next case False hence e: "i \<ge> n" by linarith have "coeff x i = \<zero>\<^bsub>mod_ring p\<^esub>" using b e by (subst coeff_length, auto simp:bounded_degree_polynomials_length) also have "... = coeff y i" using c e by (subst coeff_length, auto simp:bounded_degree_polynomials_length) finally show ?thesis by simp qed then show "x = y" using b c univ_poly_carrier by (subst coeff_iff_polynomial_cond) (auto simp:bounded_degree_polynomials_length) qed have "is_encoding (\<lambda>f. P\<^sub>e p n f)" unfolding P\<^sub>e_def using a True by (intro encoding_compose[where f="([0..<n] \<rightarrow>\<^sub>e Nb\<^sub>e p)"] fun_encoding bounded_nat_encoding) auto thus ?thesis by simp next case False hence "is_encoding (\<lambda>f. P\<^sub>e p n f)" unfolding P\<^sub>e_def using encoding_triv by simp then show ?thesis by simp qed lemma bounded_degree_polynomial_bit_count: assumes "p > 1" assumes "x \<in> bounded_degree_polynomials (Field.mod_ring p) n" shows "bit_count (P\<^sub>e p n x) \<le> ereal (real n * (log 2 p + 1))" proof - interpret cring "Field.mod_ring p" using mod_ring_is_cring assms by blast have a: "x \<in> carrier (poly_ring (mod_ring p))" using assms(2) by (simp add:bounded_degree_polynomials_def) have "real_of_int \<lfloor>log 2 (p-1)\<rfloor>+1 \<le> log 2 (p-1) + 1" using floor_eq_iff by (intro add_mono, auto) also have "... \<le> log 2 p + 1" using assms by (intro add_mono, auto) finally have b: "\<lfloor>log 2 (p-1)\<rfloor>+1 \<le> log 2 p + 1" by simp have "bit_count (P\<^sub>e p n x) = (\<Sum> k \<leftarrow> [0..<n]. bit_count (Nb\<^sub>e p (coeff x k)))" using assms restrict_extensional by (auto intro!:arg_cong[where f="sum_list"] simp add:P\<^sub>e_def fun_bit_count lessThan_atLeast0) also have "... = (\<Sum> k \<leftarrow> [0..<n]. ereal (floorlog 2 (p-1)))" using coeff_in_carrier[OF a] mod_ring_carr by (subst bounded_nat_bit_count_2, auto) also have "... = n * ereal (floorlog 2 (p-1))" by (simp add: sum_list_triv) also have "... = n * real_of_int (\<lfloor>log 2 (p-1)\<rfloor>+1)" using assms(1) by (simp add:floorlog_def) also have "... \<le> ereal (real n * (log 2 p + 1))" by (subst ereal_less_eq, intro mult_left_mono b, auto) finally show ?thesis by simp qed end
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang ! This file was ported from Lean 3 source module ring_theory.ring_hom.finite_type ! leanprover-community/mathlib commit 64fc7238fb41b1a4f12ff05e3d5edfa360dd768c ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.RingTheory.LocalProperties import Mathbin.RingTheory.Localization.InvSubmonoid /-! # The meta properties of finite-type ring homomorphisms. The main result is `ring_hom.finite_is_local`. -/ namespace RingHom open Pointwise theorem finiteType_stableUnderComposition : StableUnderComposition @FiniteType := by introv R hf hg exact hg.comp hf #align ring_hom.finite_type_stable_under_composition RingHom.finiteType_stableUnderComposition theorem finiteType_holdsForLocalizationAway : HoldsForLocalizationAway @FiniteType := by introv R _ skip suffices Algebra.FiniteType R S by change Algebra.FiniteType _ _ convert this ext rw [Algebra.smul_def] rfl exact IsLocalization.finiteType_of_monoid_fg (Submonoid.powers r) S #align ring_hom.finite_type_holds_for_localization_away RingHom.finiteType_holdsForLocalizationAway theorem finiteType_ofLocalizationSpanTarget : OfLocalizationSpanTarget @FiniteType := by -- Setup algebra intances. rw [of_localization_span_target_iff_finite] introv R hs H skip classical letI := f.to_algebra replace H : ∀ r : s, Algebra.FiniteType R (Localization.Away (r : S)) · intro r convert H r ext rw [Algebra.smul_def] rfl replace H := fun r => (H r).1 constructor -- Suppose `s : finset S` spans `S`, and each `Sᵣ` is finitely generated as an `R`-algebra. -- Say `t r : finset Sᵣ` generates `Sᵣ`. By assumption, we may find `lᵢ` such that -- `∑ lᵢ * sᵢ = 1`. I claim that all `s` and `l` and the numerators of `t` and generates `S`. choose t ht using H obtain ⟨l, hl⟩ := (Finsupp.mem_span_iff_total S (s : Set S) 1).mp (show (1 : S) ∈ Ideal.span (s : Set S) by rw [hs] trivial) let sf := fun x : s => IsLocalization.finsetIntegerMultiple (Submonoid.powers (x : S)) (t x) use s.attach.bUnion sf ∪ s ∪ l.support.image l rw [eq_top_iff] -- We need to show that every `x` falls in the subalgebra generated by those elements. -- Since all `s` and `l` are in the subalgebra, it suffices to check that `sᵢ ^ nᵢ • x` falls in -- the algebra for each `sᵢ` and some `nᵢ`. rintro x - apply Subalgebra.mem_of_span_eq_top_of_smul_pow_mem _ (s : Set S) l hl _ _ x _ · intro x hx apply Algebra.subset_adjoin rw [Finset.coe_union, Finset.coe_union] exact Or.inl (Or.inr hx) · intro i by_cases h : l i = 0 · rw [h] exact zero_mem _ apply Algebra.subset_adjoin rw [Finset.coe_union, Finset.coe_image] exact Or.inr (Set.mem_image_of_mem _ (finsupp.mem_support_iff.mpr h)) · intro r rw [Finset.coe_union, Finset.coe_union, Finset.coe_bunionᵢ] -- Since all `sᵢ` and numerators of `t r` are in the algebra, it suffices to show that the -- image of `x` in `Sᵣ` falls in the `R`-adjoin of `t r`, which is of course true. obtain ⟨⟨_, n₂, rfl⟩, hn₂⟩ := IsLocalization.exists_smul_mem_of_mem_adjoin (Submonoid.powers (r : S)) x (t r) (Algebra.adjoin R _) _ _ _ · exact ⟨n₂, hn₂⟩ · intro x hx apply Algebra.subset_adjoin refine' Or.inl (Or.inl ⟨_, ⟨r, rfl⟩, _, ⟨s.mem_attach r, rfl⟩, hx⟩) · rw [Submonoid.powers_eq_closure, Submonoid.closure_le, Set.singleton_subset_iff] apply Algebra.subset_adjoin exact Or.inl (Or.inr r.2) · rw [ht] trivial #align ring_hom.finite_type_of_localization_span_target RingHom.finiteType_ofLocalizationSpanTarget theorem finiteType_is_local : PropertyIsLocal @FiniteType := ⟨localization_finiteType, finiteType_ofLocalizationSpanTarget, finiteType_stableUnderComposition, finiteType_holdsForLocalizationAway⟩ #align ring_hom.finite_type_is_local RingHom.finiteType_is_local theorem finiteType_respectsIso : RingHom.RespectsIso @RingHom.FiniteType := RingHom.finiteType_is_local.RespectsIso #align ring_hom.finite_type_respects_iso RingHom.finiteType_respectsIso end RingHom
------------------------------------------------------------------------ -- A partial order ------------------------------------------------------------------------ {-# OPTIONS --cubical --sized-types #-} open import Prelude hiding (⊥; module W) module Partiality-monad.Coinductive.Partial-order {a} {A : Type a} where open import Equality.Propositional.Cubical open import Logical-equivalence using (_⇔_) open import Prelude.Size open import Bijection equality-with-J using (_↔_) open import Equality.Path.Isomorphisms.Univalence equality-with-paths open import H-level equality-with-J open import H-level.Closure equality-with-J open import H-level.Truncation.Propositional equality-with-paths as Trunc open import Quotient equality-with-paths as Quotient open import Univalence-axiom equality-with-J open import Delay-monad open import Delay-monad.Bisimilarity as B using (_≈_) import Delay-monad.Partial-order as PO open import Partiality-monad.Coinductive -- An ordering relation. LE : A ⊥ → A ⊥ → Proposition a LE x y = Quotient.rec (λ where .[]ʳ x → LE″ x y .[]-respects-relationʳ → left-lemma″-∥∥ y .is-setʳ → is-set) x where LE′ : Delay A ∞ → Delay A ∞ → Proposition a LE′ x y = ∥ x PO.⊑ y ∥ , truncation-is-proposition abstract is-set : Is-set (∃ λ (A : Type a) → Is-proposition A) is-set = Is-set-∃-Is-proposition ext prop-ext right-lemma : ∀ {x y z} → x ≈ y → LE′ z x ≡ LE′ z y right-lemma x≈y = _↔_.to (⇔↔≡″ ext prop-ext) (record { to = ∥∥-map (flip PO.transitive-⊑≈ x≈y) ; from = ∥∥-map (flip PO.transitive-⊑≈ (B.symmetric x≈y)) }) right-lemma-∥∥ : ∀ {x y z} → ∥ x ≈ y ∥ → LE′ z x ≡ LE′ z y right-lemma-∥∥ = Trunc.rec is-set right-lemma LE″ : Delay A ∞ → A ⊥ → Proposition a LE″ x y = Quotient.rec (λ where .[]ʳ → LE′ x .[]-respects-relationʳ → right-lemma-∥∥ .is-setʳ → is-set) y abstract left-lemma : ∀ {x y z} → x ≈ y → LE′ x z ≡ LE′ y z left-lemma x≈y = _↔_.to (⇔↔≡″ ext prop-ext) (record { to = ∥∥-map (PO.transitive-≈⊑ (B.symmetric x≈y)) ; from = ∥∥-map (PO.transitive-≈⊑ x≈y) }) left-lemma″ : ∀ {x y} z → x ≈ y → LE″ x z ≡ LE″ y z left-lemma″ {x} {y} z x≈y = Quotient.elim-prop {P = λ z → LE″ x z ≡ LE″ y z} (λ where .[]ʳ _ → left-lemma x≈y .is-propositionʳ _ → Is-set-∃-Is-proposition ext prop-ext) z left-lemma″-∥∥ : ∀ {x y} z → ∥ x ≈ y ∥ → LE″ x z ≡ LE″ y z left-lemma″-∥∥ z = Trunc.rec is-set (left-lemma″ z) infix 4 _⊑_ _⊑_ : A ⊥ → A ⊥ → Type a x ⊑ y = proj₁ (LE x y) -- _⊑_ is propositional. ⊑-propositional : ∀ x y → Is-proposition (x ⊑ y) ⊑-propositional x y = proj₂ (LE x y) -- _⊑_ is reflexive. reflexive : ∀ x → x ⊑ x reflexive = Quotient.elim-prop λ where .[]ʳ x → ∣ PO.reflexive x ∣ .is-propositionʳ x → ⊑-propositional [ x ] [ x ] -- _⊑_ is antisymmetric. antisymmetric : ∀ x y → x ⊑ y → y ⊑ x → x ≡ y antisymmetric = Quotient.elim-prop λ where .[]ʳ x → Quotient.elim-prop (λ where .[]ʳ y ∥x⊑y∥ ∥y⊑x∥ → []-respects-relation $ Trunc.rec truncation-is-proposition (λ x⊑y → ∥∥-map (PO.antisymmetric x⊑y) ∥y⊑x∥) ∥x⊑y∥ .is-propositionʳ _ → Π-closure ext 1 λ _ → Π-closure ext 1 λ _ → ⊥-is-set) .is-propositionʳ _ → Π-closure ext 1 λ _ → Π-closure ext 1 λ _ → Π-closure ext 1 λ _ → ⊥-is-set -- _⊑_ is transitive. transitive : ∀ x y z → x ⊑ y → y ⊑ z → x ⊑ z transitive = Quotient.elim-prop λ where .[]ʳ x → Quotient.elim-prop λ where .[]ʳ y → Quotient.elim-prop λ where .[]ʳ z ∥x⊑y∥ → Trunc.rec truncation-is-proposition (λ y⊑z → ∥∥-map (λ x⊑y → PO.transitive x⊑y y⊑z) ∥x⊑y∥) .is-propositionʳ _ → Π-closure ext 1 λ _ → Π-closure ext 1 λ _ → ⊑-propositional [ _ ] [ _ ] .is-propositionʳ _ → Π-closure ext 1 λ z → Π-closure ext 1 λ _ → Π-closure ext 1 λ _ → ⊑-propositional [ _ ] z .is-propositionʳ _ → Π-closure ext 1 λ _ → Π-closure ext 1 λ z → Π-closure ext 1 λ _ → Π-closure ext 1 λ _ → ⊑-propositional [ _ ] z
import sys import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt import matplotlib.patches as mpatch from matplotlib.ticker import AutoMinorLocator, MultipleLocator import seaborn sys.path.append("../analysis") from fffit.utils import values_real_to_scaled from utils.ap import APConstants from matplotlib import ticker AP = APConstants() matplotlib.rc("font", family="sans-serif") matplotlib.rc("font", serif="Arial") NM_TO_ANGSTROM = 10 K_B = 0.008314 # J/MOL K KJMOL_TO_K = 1.0 / K_B def main(): df = pd.read_csv("../analysis/csv/uc-lattice-iter4-results.csv", index_col=0) seaborn.set_palette(None, n_colors=6) fig, ax = plt.subplots() ax.scatter( range(len(df.loc[df["temperature"] == 10])), df.loc[df["temperature"] == 10].sort_values("uc_mean_distance")["uc_mean_distance_Cl"], label="UCMD Cl", alpha=0.4, s=20, marker="v", ) ax.scatter( range(len(df.loc[df["temperature"] == 10])), df.loc[df["temperature"] == 10].sort_values("uc_mean_distance")["uc_mean_distance_O"], label="UCMD O", alpha=0.4, s=16, marker="s", ) ax.scatter( range(len(df.loc[df["temperature"] == 10])), df.loc[df["temperature"] == 10].sort_values("uc_mean_distance")["uc_mean_distance_N"], label="UCMD N", alpha=0.4, marker="P", s=16, ) ax.scatter( range(len(df.loc[df["temperature"] == 10])), df.loc[df["temperature"] == 10].sort_values("uc_mean_distance")["uc_mean_distance_H"], label="UCMD H", alpha=0.4, s=20, marker="*", ) ax.plot( range(len(df.loc[df["temperature"] == 10])), df.loc[df["temperature"] == 10].sort_values("uc_mean_distance")["uc_mean_distance"], label="UCMD", linewidth=4, alpha=0.8, color="gray", ) ax2 = ax.twinx() ax2.scatter( range(len(df.loc[df["temperature"] == 10])), df.loc[df["temperature"] == 10].sort_values("uc_mean_distance")["abs(HB3-HB4)"], label=r"abs$(\Delta_\mathrm{hbond})$", color="black", alpha=0.4, s=20, ) ax.set_xlabel("Sorted parameter index", fontsize=16, labelpad=15) ax.set_ylabel(r"UCMD [$\mathrm{\AA}$]", fontsize=16, labelpad=15) ax2.set_ylabel(r"abs$(\Delta_\mathrm{hbond})$ $[\mathrm{\AA}]$", fontsize=16, labelpad=15) ax2.set_ylim(0.0,0.004) ax.tick_params("both", direction="in", which="both", length=4, labelsize=14, pad=5) ax2.tick_params("both", direction="in", which="both", length=4, labelsize=14, pad=5) ax.tick_params("both", which="major", length=8) ax2.tick_params("both", which="major", length=8) ax.xaxis.set_ticks_position("both") ax.xaxis.set_major_locator(MultipleLocator(50)) ax.xaxis.set_minor_locator(AutoMinorLocator(5)) ax.yaxis.set_minor_locator(AutoMinorLocator(5)) ax.set_ylim(0.0, 0.4) fig.subplots_adjust(left=0.2, bottom=0.2, top=0.8, right=0.8) fig.legend(fontsize=12, loc="lower right", bbox_to_anchor=(0.9,1), bbox_transform=ax.transAxes, ncol=2) fig.savefig("pdfs/fig8-ap-tradeoffs.pdf") if __name__ == "__main__": main()
theory Common_Primitive_Lemmas imports Common_Primitive_Matcher "../Semantics_Ternary/Primitive_Normalization" "../Semantics_Ternary/MatchExpr_Fold" begin section\<open>Further Lemmas about the Common Matcher\<close> lemma has_unknowns_common_matcher: fixes m::"'i::len common_primitive match_expr" shows "has_unknowns common_matcher m \<longleftrightarrow> has_disc is_Extra m" proof - { fix A and p :: "('i, 'a) tagged_packet_scheme" have "common_matcher A p = TernaryUnknown \<longleftrightarrow> is_Extra A" by(induction A p rule: common_matcher.induct) (simp_all add: bool_to_ternary_Unknown) } hence "\<beta> = (common_matcher::('i::len common_primitive, ('i, 'a) tagged_packet_scheme) exact_match_tac) \<Longrightarrow> has_unknowns \<beta> m = has_disc is_Extra m" for \<beta> by(induction \<beta> m rule: has_unknowns.induct) (simp_all) thus ?thesis by simp qed end
/** * Copyright (c) 2018, University Osnabrück * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University Osnabrück nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL University Osnabrück BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @file PLYIO.hpp * @brief I/O support for PLY files (implementation). * @details I/O support for PLY files: Reading and writing meshes and * pointclouds, including color information, confidence, intensity * and normals. * @author Lars Kiesow (lkiesow), [email protected] * @author Thomas Wiemann * @version 110929 * @date Created: 2011-09-16 17:28:28 * @date Last modified: 2011-09-29 14:23:36 */ #include <lvr2/io/PLYIO.hpp> #include <lvr2/io/Timestamp.hpp> #include <cstring> #include <ctime> #include <sstream> #include <fstream> #include <boost/filesystem.hpp> #include <opencv2/opencv.hpp> namespace lvr2 { void PLYIO::save( string filename ) { if ( !m_model ) { std::cerr << timestamp << "No data to save." << std::endl; return; } /* Handle options. */ e_ply_storage_mode mode( PLY_LITTLE_ENDIAN ); // Local buffer shortcuts floatArr m_vertices; floatArr m_vertexConfidence; floatArr m_vertexIntensity; floatArr m_vertexNormals; floatArr m_points; floatArr m_pointConfidences; floatArr m_pointIntensities; floatArr m_pointNormals; unsigned dummy = 0; unsigned w_point_color = 0; unsigned w_vertex_color = 0; size_t m_numVertices = 0; size_t m_numVertexColors = 0; size_t m_numVertexConfidences = 0; size_t m_numVertexIntensities = 0; size_t m_numVertexNormals = 0; size_t m_numPoints = 0; size_t m_numPointColors = 0; size_t m_numPointConfidence = 0; size_t m_numPointIntensities = 0; size_t m_numPointNormals = 0; size_t m_numFaces = 0; ucharArr m_vertexColors; ucharArr m_pointColors; uintArr m_faceIndices; // Get buffers if ( m_model->m_pointCloud ) { PointBufferPtr pc( m_model->m_pointCloud ); m_numPoints = pc->numPoints(); m_numPointNormals = m_numPoints; m_numPointColors = m_numPoints; m_points = pc->getPointArray(); m_pointConfidences = pc->getFloatArray("confidences", m_numPointConfidence, dummy); m_pointColors = pc->getColorArray(w_point_color); m_pointIntensities = pc->getFloatArray("intensities", m_numPointIntensities, dummy); m_pointNormals = pc->getNormalArray(); } if ( m_model->m_mesh ) { MeshBufferPtr mesh( m_model->m_mesh ); m_numVertices = mesh->numVertices(); m_numFaces = mesh->numFaces(); m_numVertexColors = m_numVertices; m_numVertexNormals = m_numVertices; m_vertices = mesh->getVertices(); m_vertexColors = mesh->getVertexColors(w_vertex_color); m_vertexConfidence = mesh->getFloatArray("vertex_confidences", m_numVertexConfidences, dummy); m_vertexIntensity = mesh->getFloatArray("vertex_intensities", m_numVertexIntensities, dummy); m_vertexNormals = mesh->getVertexNormals(); m_faceIndices = mesh->getFaceIndices(); } p_ply oply = ply_create( filename.c_str(), mode, NULL, 0, NULL ); if ( !oply ) { std::cerr << timestamp << "Could not create »" << filename << "«" << std::endl; return; } /* Check if we have vertex information. */ if ( !( m_vertices || m_points ) ) { std::cout << timestamp << "Neither vertices nor points to write." << std::endl; if ( !ply_close( oply ) ) { std::cerr << timestamp << "Could not close file." << std::endl; } return; } /* First: Write Header information according to data. */ bool vertex_color = false; bool vertex_intensity = false; bool vertex_confidence = false; bool vertex_normal = false; bool point_color = false; bool point_intensity = false; bool point_confidence = false; bool point_normal = false; /* Add vertex element. */ if ( m_vertices ) { ply_add_element( oply, "vertex", m_numVertices ); /* Add vertex properties: x, y, z, (r, g, b) */ ply_add_scalar_property( oply, "x", PLY_FLOAT ); ply_add_scalar_property( oply, "y", PLY_FLOAT ); ply_add_scalar_property( oply, "z", PLY_FLOAT ); /* Add color information if there is any. */ if ( m_vertexColors ) { if ( m_numVertexColors != m_numVertices ) { std::cerr << timestamp << "Amount of vertices and color information is" << " not equal. Color information won't be written." << std::endl; } else { ply_add_scalar_property( oply, "red", PLY_UCHAR ); ply_add_scalar_property( oply, "green", PLY_UCHAR ); ply_add_scalar_property( oply, "blue", PLY_UCHAR ); vertex_color = true; } } /* Add intensity. */ if ( m_vertexIntensity ) { if ( m_numVertexIntensities != m_numVertices ) { std::cout << timestamp << "Amount of vertices and intensity" << " information is not equal. Intensity information won't be" << " written." << std::endl; } else { ply_add_scalar_property( oply, "intensity", PLY_FLOAT ); vertex_intensity = true; } } /* Add confidence. */ if ( m_vertexConfidence ) { if ( m_numVertexConfidences != m_numVertices ) { std::cout << timestamp << "Amount of vertices and confidence" << " information is not equal. Confidence information won't be" << " written." << std::endl; } else { ply_add_scalar_property( oply, "confidence", PLY_FLOAT ); vertex_confidence = true; } } /* Add normals if there are any. */ if ( m_vertexNormals ) { if ( m_numVertexNormals != m_numVertices ) { std::cout << timestamp << "Amount of vertices and normals" << " does not match. Normals won't be written." << std::endl; } else { ply_add_scalar_property( oply, "nx", PLY_FLOAT ); ply_add_scalar_property( oply, "ny", PLY_FLOAT ); ply_add_scalar_property( oply, "nz", PLY_FLOAT ); vertex_normal = true; } } /* Add faces. */ if ( m_faceIndices ) { ply_add_element( oply, "face", m_numFaces ); ply_add_list_property( oply, "vertex_indices", PLY_UCHAR, PLY_INT ); } } /* Add point element */ if ( m_points ) { ply_add_element( oply, "point", m_numPoints ); /* Add point properties: x, y, z, (r, g, b) */ ply_add_scalar_property( oply, "x", PLY_FLOAT ); ply_add_scalar_property( oply, "y", PLY_FLOAT ); ply_add_scalar_property( oply, "z", PLY_FLOAT ); /* Add color information if there is any. */ if ( m_pointColors ) { if ( m_numPointColors != m_numPoints ) { std::cout << timestamp << "Amount of points and color information is" << " not equal. Color information won't be written." << std::endl; } else { ply_add_scalar_property( oply, "red", PLY_UCHAR ); ply_add_scalar_property( oply, "green", PLY_UCHAR ); ply_add_scalar_property( oply, "blue", PLY_UCHAR ); point_color = true; } } /* Add intensity. */ if ( m_pointIntensities ) { if ( m_numPointIntensities != m_numPoints ) { std::cout << timestamp << "Amount of points and intensity" << " information is not equal. Intensity information won't be" << " written." << std::endl; } else { ply_add_scalar_property( oply, "intensity", PLY_FLOAT ); point_intensity = true; } } /* Add confidence. */ if ( m_pointConfidences ) { if ( m_numPointConfidence != m_numPoints ) { std::cout << timestamp << "Amount of point and confidence" << " information is not equal. Confidence information won't be" << " written." << std::endl; } else { ply_add_scalar_property( oply, "confidence", PLY_FLOAT ); point_confidence = true; } } /* Add normals if there are any. */ if ( m_pointNormals ) { if ( m_numPointNormals != m_numPoints ) { std::cout << timestamp << "Amount of point and normals does" << " not match. Normals won't be written." << std::endl; } else { ply_add_scalar_property( oply, "nx", PLY_FLOAT ); ply_add_scalar_property( oply, "ny", PLY_FLOAT ); ply_add_scalar_property( oply, "nz", PLY_FLOAT ); point_normal = true; } } } /* Write header to file. */ if ( !ply_write_header( oply ) ) { std::cerr << timestamp << "Could not write header." << std::endl; return; } /* Second: Write data. */ for (size_t i = 0; i < m_numVertices; i++ ) { ply_write( oply, (double) m_vertices[ i * 3 ] ); /* x */ ply_write( oply, (double) m_vertices[ i * 3 + 1 ] ); /* y */ ply_write( oply, (double) m_vertices[ i * 3 + 2 ] ); /* z */ if ( vertex_color ) { ply_write( oply, m_vertexColors[ i * w_vertex_color ] ); /* red */ ply_write( oply, m_vertexColors[ i * w_vertex_color + 1 ] ); /* green */ ply_write( oply, m_vertexColors[ i * w_vertex_color + 2 ] ); /* blue */ } if ( vertex_intensity ) { ply_write( oply, m_vertexIntensity[ i ] ); } if ( vertex_confidence ) { ply_write( oply, m_vertexConfidence[ i ] ); } if ( vertex_normal ) { ply_write( oply, (double) m_vertexNormals[ i * 3 ] ); /* nx */ ply_write( oply, (double) m_vertexNormals[ i * 3 + 1 ] ); /* ny */ ply_write( oply, (double) m_vertexNormals[ i * 3 + 2 ] ); /* nz */ } } /* Write faces (Only if we also have vertices). */ if ( m_vertices ) { for ( size_t i = 0; i < m_numFaces; i++ ) { ply_write( oply, 3.0 ); /* Indices per face. */ ply_write( oply, (double) m_faceIndices[ i * 3 ] ); ply_write( oply, (double) m_faceIndices[ i * 3 + 1 ] ); ply_write( oply, (double) m_faceIndices[ i * 3 + 2 ] ); } } for ( size_t i = 0; i < m_numPoints; i++ ) { ply_write( oply, (double) m_points[ i * 3 ] ); /* x */ ply_write( oply, (double) m_points[ i * 3 + 1 ] ); /* y */ ply_write( oply, (double) m_points[ i * 3 + 2 ] ); /* z */ if ( point_color ) { ply_write( oply, m_pointColors[ i * w_point_color ] ); /* red */ ply_write( oply, m_pointColors[ i * w_point_color + 1 ] ); /* green */ ply_write( oply, m_pointColors[ i * w_point_color + 2 ] ); /* blue */ } if ( point_intensity ) { ply_write( oply, m_pointIntensities[ i ] ); } if ( point_confidence ) { ply_write( oply, m_pointConfidences[ i ] ); } if ( point_normal ) { ply_write( oply, (double) m_pointNormals[ i * 3 ] ); /* nx */ ply_write( oply, (double) m_pointNormals[ i * 3 + 1 ] ); /* ny */ ply_write( oply, (double) m_pointNormals[ i * 3 + 2 ] ); /* nz */ } } if ( !ply_close( oply ) ) { std::cerr << timestamp << "Could not close file." << std::endl; } } ModelPtr PLYIO::read( string filename ) { return read( filename, true ); } /** * swaps n elements from index i1 in arr with n elements from index i2 in arr */ template <typename T> void swap(T*& arr, size_t i1, size_t i2, size_t n) { std::swap_ranges(arr + i1, arr + i1 + n, arr + i2); } ModelPtr PLYIO::read( string filename, bool readColor, bool readConfidence, bool readIntensity, bool readNormals, bool readFaces, bool readPanoramaCoords ) { /* Start reading new PLY */ p_ply ply = ply_open( filename.c_str(), NULL, 0, NULL ); if ( !ply ) { std::cerr << timestamp << "Could not open »" << filename << "«." << std::endl; return ModelPtr(); } if ( !ply_read_header( ply ) ) { std::cerr << timestamp << "Could not read header." << std::endl; return ModelPtr(); } //std::cout << timestamp << "Loading »" << filename << "«." << std::endl; /* Check if there are vertices and get the amount of vertices. */ char buf[256] = ""; const char * name = buf; long int n; p_ply_element elem = NULL; // Buffer count variables size_t numVertices = 0; size_t numVertexColors = 0; size_t numVertexConfidences = 0; size_t numVertexIntensities = 0; size_t numVertexNormals = 0; size_t numVertexPanoramaCoords = 0; size_t numPoints = 0; size_t numPointColors = 0; size_t numPointConfidence = 0; size_t numPointIntensities = 0; size_t numPointNormals = 0; size_t numPointPanoramaCoords = 0; size_t numPointSpectralChannels = 0; size_t numFaces = 0; size_t n_channels = 0; // Number of spectral channels while ( ( elem = ply_get_next_element( ply, elem ) ) ) { ply_get_element_info( elem, &name, &n ); if ( !strcmp( name, "vertex" ) ) { numVertices = n; p_ply_property prop = NULL; while ( ( prop = ply_get_next_property( elem, prop ) ) ) { ply_get_property_info( prop, &name, NULL, NULL, NULL ); if ( !strcmp( name, "red" ) && readColor ) { /* We have color information */ numVertexColors = n; } else if ( !strcmp( name, "confidence" ) && readConfidence ) { /* We have confidence information */ numVertexConfidences = n; } else if ( !strcmp( name, "intensity" ) && readIntensity ) { /* We have intensity information */ numVertexIntensities = n; } else if ( !strcmp( name, "nx" ) && readNormals ) { /* We have normals */ numVertexNormals = n; } else if ( !strcmp( name, "x_coords" ) && readPanoramaCoords ) { /* We have panorama coordinates */ numVertexPanoramaCoords = n; } } } else if ( !strcmp( name, "point" ) ) { numPoints = n; p_ply_property prop = NULL; while ( ( prop = ply_get_next_property( elem, prop ) ) ) { ply_get_property_info( prop, &name, NULL, NULL, NULL ); if ( !strcmp( name, "red" ) && readColor ) { /* We have color information */ numPointColors = n; } else if ( !strcmp( name, "confidence" ) && readConfidence ) { /* We have confidence information */ numPointConfidence = n; } else if ( !strcmp( name, "intensity" ) && readIntensity ) { /* We have intensity information */ numPointIntensities = n; } else if ( !strcmp( name, "nx" ) && readNormals ) { /* We have normals */ numPointNormals = n; } else if ( !strcmp( name, "x_coords" ) && readPanoramaCoords ) { /* We have panorama coordinates */ numPointPanoramaCoords = n; } } } else if ( !strcmp( name, "face" ) && readFaces ) { numFaces = n; } } if ( !( numVertices || numPoints ) ) { std::cout << timestamp << "Neither vertices nor points in ply." << std::endl; return ModelPtr(); } // Buffers floatArr vertices; floatArr vertexConfidence; floatArr vertexIntensity; floatArr vertexNormals; floatArr points; floatArr pointConfidences; floatArr pointIntensities; floatArr pointNormals; ucharArr pointSpectralChannels; ucharArr vertexColors; ucharArr pointColors; shortArr vertexPanoramaCoords; shortArr pointPanoramaCoords; uintArr faceIndices; /* Allocate memory. */ if ( numVertices ) { vertices = floatArr( new float[ numVertices * 3 ] ); } if ( numVertexColors ) { vertexColors = ucharArr( new unsigned char[ numVertices * 3 ] ); } if ( numVertexConfidences ) { vertexConfidence = floatArr( new float[ numVertices ] ); } if ( numVertexIntensities ) { vertexIntensity = floatArr( new float[ numVertices ] ); } if ( numVertexNormals ) { vertexNormals = floatArr( new float[ numVertices * 3 ] ); } if ( numVertexPanoramaCoords ) { vertexPanoramaCoords = shortArr( new short[ numVertices * 2 ] ); } if ( numFaces ) { faceIndices = indexArray( new unsigned int[ numFaces * 3 ] ); } if ( numPoints ) { points = floatArr( new float[ numPoints * 3 ] ); } if ( numPointColors ) { pointColors = ucharArr( new unsigned char[ numPoints * 3 ] ); } if ( numPointConfidence ) { pointConfidences = floatArr( new float[numPoints] ); } if ( numPointIntensities ) { pointIntensities = floatArr( new float[numPoints] ); } if ( numPointNormals ) { pointNormals = floatArr( new float[ numPoints * 3 ] ); } if ( numPointPanoramaCoords ) { pointPanoramaCoords = shortArr( new short[ numPoints * 2 ] ); } float* vertex = vertices.get(); uint8_t* vertex_color = vertexColors.get(); float* vertex_confidence = vertexConfidence.get(); float* vertex_intensity = vertexIntensity.get(); float* vertex_normal = vertexNormals.get(); short* vertex_panorama_coords = vertexPanoramaCoords.get(); unsigned int* face = faceIndices.get(); float* point = points.get(); uint8_t* point_color = pointColors.get(); float* point_confidence = pointConfidences.get(); float* point_intensity = pointIntensities.get(); float* point_normal = pointNormals.get(); short* point_panorama_coords = pointPanoramaCoords.get(); /* Set callbacks. */ if ( vertex ) { ply_set_read_cb( ply, "vertex", "x", readVertexCb, &vertex, 0 ); ply_set_read_cb( ply, "vertex", "y", readVertexCb, &vertex, 0 ); ply_set_read_cb( ply, "vertex", "z", readVertexCb, &vertex, 1 ); } if ( vertex_color ) { ply_set_read_cb( ply, "vertex", "red", readColorCb, &vertex_color, 0 ); ply_set_read_cb( ply, "vertex", "green", readColorCb, &vertex_color, 0 ); ply_set_read_cb( ply, "vertex", "blue", readColorCb, &vertex_color, 1 ); } if ( vertex_confidence ) { ply_set_read_cb( ply, "vertex", "confidence", readVertexCb, &vertex_confidence, 1 ); } if ( vertex_intensity ) { ply_set_read_cb( ply, "vertex", "intensity", readVertexCb, &vertex_intensity, 1 ); } if ( vertex_normal ) { ply_set_read_cb( ply, "vertex", "nx", readVertexCb, &vertex_normal, 0 ); ply_set_read_cb( ply, "vertex", "ny", readVertexCb, &vertex_normal, 0 ); ply_set_read_cb( ply, "vertex", "nz", readVertexCb, &vertex_normal, 1 ); } if ( vertex_panorama_coords ) { ply_set_read_cb( ply, "vertex", "x_coords", readPanoramaCoordCB, &vertex_panorama_coords, 0 ); ply_set_read_cb( ply, "vertex", "y_coords", readPanoramaCoordCB, &vertex_panorama_coords, 1 ); } if ( face ) { ply_set_read_cb( ply, "face", "vertex_indices", readFaceCb, &face, 0 ); ply_set_read_cb( ply, "face", "vertex_index", readFaceCb, &face, 0 ); } if ( point ) { ply_set_read_cb( ply, "point", "x", readVertexCb, &point, 0 ); ply_set_read_cb( ply, "point", "y", readVertexCb, &point, 0 ); ply_set_read_cb( ply, "point", "z", readVertexCb, &point, 1 ); } if ( point_color ) { ply_set_read_cb( ply, "point", "red", readColorCb, &point_color, 0 ); ply_set_read_cb( ply, "point", "green", readColorCb, &point_color, 0 ); ply_set_read_cb( ply, "point", "blue", readColorCb, &point_color, 1 ); } if ( point_confidence ) { ply_set_read_cb( ply, "point", "confidence", readVertexCb, &point_confidence, 1 ); } if ( point_intensity ) { ply_set_read_cb( ply, "point", "intensity", readVertexCb, &point_intensity, 1 ); } if ( point_normal ) { ply_set_read_cb( ply, "point", "nx", readVertexCb, &point_normal, 0 ); ply_set_read_cb( ply, "point", "ny", readVertexCb, &point_normal, 0 ); ply_set_read_cb( ply, "point", "nz", readVertexCb, &point_normal, 1 ); } if ( point_panorama_coords ) { ply_set_read_cb( ply, "point", "x_coords", readPanoramaCoordCB, &point_panorama_coords, 0 ); ply_set_read_cb( ply, "point", "y_coords", readPanoramaCoordCB, &point_panorama_coords, 1 ); } /* Read ply file. */ if ( !ply_read( ply ) ) { std::cerr << timestamp << "Could not read »" << filename << "«." << std::endl; } /* Check if we got only vertices and neither points nor faces. If that is * the case then use the vertices as points. */ if ( vertices && !points && !faceIndices ) { std::cout << timestamp << "PLY contains neither faces nor points. " << "Assuming that vertices are meant to be points." << std::endl; points = vertices; pointColors = vertexColors; pointConfidences = vertexConfidence; pointIntensities = vertexIntensity; pointNormals = vertexNormals; pointPanoramaCoords = vertexPanoramaCoords; point = points.get(); point_color = pointColors.get(); point_confidence = pointConfidences.get(); point_intensity = pointIntensities.get(); point_normal = pointNormals.get(); point_panorama_coords = pointPanoramaCoords.get(); numPoints = numVertices; numPointColors = numVertexColors; numPointConfidence = numVertexConfidences; numPointIntensities = numVertexIntensities; numPointNormals = numVertexNormals; numPointPanoramaCoords = numVertexPanoramaCoords; numVertices = 0; numVertexColors = 0; numVertexConfidences = 0; numVertexIntensities = 0; numVertexNormals = 0; numVertexPanoramaCoords = 0; vertices.reset(); vertexColors.reset(); vertexConfidence.reset(); vertexIntensity.reset(); vertexNormals.reset(); vertexPanoramaCoords.reset(); } ply_close( ply ); // read Panorama Images if we have annotated data if (numPointPanoramaCoords) { // move all the Points that don't have spectral information to the end for (int i = 0; i < numPointPanoramaCoords; i++) { if (point_panorama_coords[2 * i] == -1) { // swap with last element numPointPanoramaCoords--; const int n = numPointPanoramaCoords; swap(point_panorama_coords, 2 * i, 2 * numPointPanoramaCoords, 2); swap(point, 3 * i, 3 * numPointPanoramaCoords, 3); if (numPointColors) swap(point_color, 3*i, 3*numPointPanoramaCoords, 3); if (numPointConfidence) swap(point_confidence, i, numPointPanoramaCoords, 1); if (numPointIntensities) swap(point_intensity, i, numPointPanoramaCoords, 1); if (numPointNormals) swap(point_normal, 3*i, 3*numPointPanoramaCoords, 3); i--; } } std::cout << timestamp << numPoints << "Found " << (numPoints - numPointPanoramaCoords) << " without spectral data. Reodering..." << std::endl; size_t pos_underscore = filename.find_last_of("_"); size_t pos_extension = filename.find_last_of("."); string scanNr = filename.substr(pos_underscore + 1, pos_extension - pos_underscore - 1); string channelDirName = string("panorama_channels_") + scanNr; boost::filesystem::path dir(filename); dir = dir.parent_path() / "panoramas_fixed" / channelDirName; if (!boost::filesystem::exists(dir / "channel0.png")) { std::cerr << timestamp << "Annotated Data given, but " + dir.string() + " does not contain channel files" << std::endl; } else { std::cout << timestamp << "Found Annotated Data. Loading spectral channel images from: " << dir.string() << "/" << std::endl; std::cout << timestamp << "This may take a while depending on data size" << std::endl; std::vector<cv::Mat> imgs; std::vector<unsigned char*> pixels; cv::VideoCapture images(dir.string() + "/channel%d.png"); cv::Mat img, imgFlipped; while (images.read(img)) { imgs.push_back(cv::Mat()); cv::flip(img, imgFlipped, 0); // TODO: FIXME: Data is currently stored mirrored and offset cv::cvtColor(imgFlipped, imgs.back(), cv::COLOR_RGB2GRAY); pixels.push_back(imgs.back().data); } n_channels = imgs.size(); int width = imgs[0].cols; int height = imgs[0].rows; numPointSpectralChannels = numPointPanoramaCoords; pointSpectralChannels = ucharArr(new unsigned char[numPointPanoramaCoords * n_channels]); unsigned char* point_spectral_channels = pointSpectralChannels.get(); std::cout << timestamp << "Finished loading " << n_channels << " channel images" << std::endl; #pragma omp parallel for for (int i = 0; i < numPointPanoramaCoords; i++) { int pc_index = 2 * i; // x_coords, y_coords short x = point_panorama_coords[pc_index]; short y = point_panorama_coords[pc_index + 1]; x = (x + width / 2) % width; // TODO: FIXME: Data is currently stored mirrored and offset int panoramaPosition = y * width + x; unsigned char* pixel = point_spectral_channels + n_channels * i; for (int channel = 0; channel < n_channels; channel++) { pixel[channel] = pixels[channel][panoramaPosition]; } } std::cout << timestamp << "Finished extracting channel information" << std::endl; } } // Save buffers in model PointBufferPtr pc; MeshBufferPtr mesh; if(points) { pc = PointBufferPtr( new PointBuffer ); pc->setPointArray(points, numPoints); if (pointColors) { pc->setColorArray(pointColors, numPointColors); } if (pointIntensities) { pc->addFloatChannel(pointIntensities, "intensities", numPointIntensities, 1); } if (pointConfidences) { pc->addFloatChannel(pointConfidences, "confidences", numPointConfidence, 1); } if (pointNormals) { pc->setNormalArray(pointNormals, numPointNormals); } // only add spectral data if we really have some... if (pointSpectralChannels) { pc->addUCharChannel(pointSpectralChannels, "spectral_channels", numPointSpectralChannels, n_channels); // there is no way to read min-, maxchannel from ply file => assume default 400-1000nm pc->addIntAtomic(400, "spectral_wavelength_min"); pc->addIntAtomic(400 + 4 * n_channels, "spectral_wavelength_max"); pc->addIntAtomic(n_channels, "num_spectral_channels"); } } if(vertices) { mesh = MeshBufferPtr( new MeshBuffer ); mesh->setVertices(vertices, numVertices ); if (faceIndices) { mesh->setFaceIndices(faceIndices, numFaces); } if (vertexNormals) { mesh->setVertexNormals(vertexNormals); } if (vertexColors) { mesh->setVertexColors(vertexColors); } if (vertexIntensity) { mesh->addFloatChannel(vertexIntensity, "vertex_intensities", numVertexIntensities, 1); } if (vertexConfidence) { mesh->addFloatChannel(vertexConfidence, "vertex_confidences", numVertexConfidences, 1); } } ModelPtr m( new Model( mesh, pc ) ); m_model = m; return m; } int PLYIO::readVertexCb( p_ply_argument argument ) { float ** ptr; ply_get_argument_user_data( argument, (void **) &ptr, NULL ); **ptr = ply_get_argument_value( argument ); (*ptr)++; return 1; } int PLYIO::readColorCb( p_ply_argument argument ) { uint8_t ** color; ply_get_argument_user_data( argument, (void **) &color, NULL ); **color = ply_get_argument_value( argument ); (*color)++; return 1; } int PLYIO::readFaceCb( p_ply_argument argument ) { unsigned int ** face; long int length, value_index; ply_get_argument_user_data( argument, (void **) &face, NULL ); ply_get_argument_property( argument, NULL, &length, &value_index ); if ( value_index < 0 ) { /* We got info about amount of face vertices. */ if ( ply_get_argument_value( argument ) == 3 ) { return 1; } std::cerr << timestamp << "Mesh is not a triangle mesh." << std::endl; return 0; } **face = ply_get_argument_value( argument ); (*face)++; return 1; } int PLYIO::readPanoramaCoordCB( p_ply_argument argument ) { short ** ptr; ply_get_argument_user_data( argument, (void **) &ptr, NULL ); **ptr = ply_get_argument_value( argument ); (*ptr)++; return 1; } } // namespace lvr2
# Article submitted # Fusion of Evidences in Intensities Channels for Edge Detection in PolSAR Images # GRSL - IEEE Geoscience and Remote Sensing Letters # Anderson A. de Borba, Maurı́cio Marengoni, and Alejandro C Frery # Despriction (function) # Finds the l(L, mu) using log-likelihood, (internal side) # Input: L, mu > 0 # # Output: l(L, mu) - log-likelihood loglike <- function(param){ L <- param[1] mu <- param[2] aux1 <- L * log(L) aux2 <- L * sum(log(z[1: j])) / j aux3 <- L * log(mu) aux4 <- log(gamma(L)) aux5 <- (L / mu) * sum(z[1: j]) / j ll <- aux1 + aux2 - aux3 - aux4 - aux5 return(ll) }
theory leftpad imports Main "~~/src/HOL/Library/Code_Target_Nat" begin section \<open>define leftpad\<close> (* left pad. Takes a padding character, a string, and a total length, returns the string padded to that length with that character. If length is less than the length of the string, does nothing. inspired by https://www.hillelwayne.com/post/theorem-prover-showdown/ *) fun rightPad :: "'a => 'a list => nat => 'a list" where "rightPad p [] 0 = []" | "rightPad p [] (Suc n) = p # (rightPad p [] n)" | "rightPad p (x # xs) 0 = (x # xs)" | "rightPad p (x # xs) (Suc n) = x # (rightPad p xs n)" fun leftPad :: "'a => 'a list => nat => 'a list" where "leftPad p xs n = rev (rightPad p (rev xs) n)" value "leftPad 0 [1,2] 1 :: nat list" value "leftPad 0 [1,2] 4 :: nat list" value "leftPad 9 [1,1] 3 :: nat list" (* Prove: You have to specify it’s the right length, that the added characters are all the padding character, and that the suffix is the original string. *) section \<open>Proofs\<close> subsection \<open>right pad\<close> lemma rightpad_empty_is_replicate:"\<lbrakk>padTo = n\<rbrakk> \<Longrightarrow> rightPad p [] padTo = replicate n p" proof(induction padTo arbitrary: n) case 0 then show ?case by simp next case (Suc padTo) then show ?case by auto qed text "additional characters are padding" lemma right_pad_adds_padding_character: fixes lst :: "'a list" and p :: "'a" and padTo :: nat assumes "length lst < padTo" and "length lst + n = padTo" shows "\<lbrakk>length lst < padTo; length lst + n = padTo\<rbrakk> \<Longrightarrow> drop (length lst) (rightPad p lst padTo) = replicate n p" proof(induction lst arbitrary: padTo) case Nil then show ?case proof(induction padTo) case 0 then show ?case by simp next case (Suc padTo) then show ?case by (simp add: rightpad_empty_is_replicate) qed next case (Cons l ls) then show ?case proof(induction padTo) case 0 then show ?case by simp next case (Suc padT) then show ?case by simp qed qed text "prefix of result is the list" lemma right_pad_prefix_is_list: fixes lst :: "'a list" and p :: "'a" and padTo :: nat shows "take (length lst) (rightPad p lst padTo) = lst" proof(induction lst arbitrary: padTo) case Nil then show ?case by simp next case (Cons a lst) then show ?case proof(induction padTo) case 0 then show ?case by simp next case (Suc padTo) then show ?case by simp qed qed text "length is correct" lemma right_pad_length_is_correct: shows "length (rightPad p lst padTo) = max (length lst) padTo" proof(induction lst arbitrary: padTo) case Nil then show ?case by (simp add: rightpad_empty_is_replicate) next case (Cons a lst) then show ?case proof(induction padTo) case 0 then show ?case by simp next case (Suc padTo) then show ?case by simp qed qed subsection \<open>left pad\<close> text "length is correct" theorem left_pad_length_is_correct: shows "length (leftPad p lst padTo) = max (length lst) padTo" by (simp add: right_pad_length_is_correct) text "suffix of result is the list" theorem left_pad_suffix_is_list: fixes lst :: "'a list" and p :: "'a" and padTo :: nat assumes "length lst < padTo" and "length lst + n = padTo" shows "\<lbrakk>length lst + n = padTo\<rbrakk> \<Longrightarrow> drop n (leftPad p lst padTo) = lst" proof(induction lst) case Nil then show ?case by (simp add: rightpad_empty_is_replicate) next case (Cons l ls) then show ?case proof(induction padTo) case 0 then show ?case by simp next case (Suc padTo\<^sub>p) have "drop n (leftPad p ls padTo\<^sub>p) = ls" apply auto proof - have "length ls \<le> padTo\<^sub>p" by (metis (no_types) Suc.prems(2) Suc_inject add.commute add_Suc_right le_add1 length_Cons) then have "length (rightPad p (rev ls) padTo\<^sub>p) = padTo\<^sub>p" by (simp add: right_pad_length_is_correct) then have "length (rightPad p (rev ls) padTo\<^sub>p) - n = length ls" by (metis (no_types) Suc.prems(2) add.commute add_Suc_right add_diff_cancel_left' length_Cons) then show "drop n (rev (rightPad p (rev ls) padTo\<^sub>p)) = ls" by (metis (no_types) drop_rev length_rev rev_rev_ident right_pad_prefix_is_list) qed then show ?case apply auto proof - have "length (rightPad p (rev ls @ [l]) (Suc padTo\<^sub>p)) - n = length (l # ls)" by (metis Suc.prems(2) add_diff_cancel_right' le_add1 length_rev max_def_raw rev.simps(2) right_pad_length_is_correct) then show "drop n (rev (rightPad p (rev ls @ [l]) (Suc padTo\<^sub>p))) = l # ls" by (metis drop_rev length_rev rev.simps(2) rev_swap right_pad_prefix_is_list) qed qed qed text "additional characters are padding" theorem left_pad_adds_padding_character: fixes lst :: "'a list" and p :: "'a" and padTo :: nat and n :: nat assumes "length lst < padTo" and "length lst + n = padTo" shows "\<lbrakk>length lst < padTo; length lst + n = padTo\<rbrakk> \<Longrightarrow> take n (leftPad p lst padTo) = replicate n p" proof(induction lst arbitrary: padTo) case Nil then show ?case proof(induction padTo) case 0 then show ?case by simp next case (Suc padTo) then show ?case apply auto by (simp add: replicate_append_same rightpad_empty_is_replicate) qed next case (Cons l ls) then show ?case proof(induction padTo) case 0 then show ?case by simp next case (Suc padTo\<^sub>p) then show ?case apply auto proof - assume a1: "padTo\<^sub>p = length ls + n" have f2: "length (rightPad p (rev ls @ [l]) (Suc (length ls + n))) = length (l # ls) + n" by (simp add: right_pad_length_is_correct) have f3: "length (rev ls @ [l]) + n = Suc padTo\<^sub>p" using Suc.prems(3) by auto have "length (rev ls @ [l]) < Suc padTo\<^sub>p" using Suc.prems(2) by force then have "drop (length (rev ls @ [l])) (rightPad p (rev ls @ [l]) (Suc padTo\<^sub>p)) = replicate n p" using f3 by (metis (full_types) right_pad_adds_padding_character) then show "take n (rev (rightPad p (rev ls @ [l]) (Suc (length ls + n)))) = replicate n p" using f2 a1 by (simp add: take_rev) qed qed qed
"""" __Predicates__ are functions that ask "yes or no" questions of their argument[s]. You can ask of a number "Is this zero?" or "Is this one?" and these predicates (`iszero`, `isone`) will work as expected with almost all numerical types. The built-in numerical types let you query finiteness (`isfinite`, `isinf`). These are the predicates made available for use with DoubleFloats: > iszero, isnonzero, isone # value == 0, value != 0, value == 1 ispositive, isnegative, # value > 0, value < 0 isnonnegative, isnonpositive, # value >= 0, value <= 0 isfinite, isinf, # abs(value) != Inf, abs(value) == Inf isposinf, isneginf, # value == Inf, value == -Inf isnan, # value is not a number (eg 0/0) issubnormal, # value contains a subnormal part isnormal, # value is finite and not subnormal isinteger, isfractional # value == round(value) iseven, isodd, # isinteger(value/2.0), !isinteger(value/2.0) """ predicates """ isnonzero(x) Return `!iszero(x)` """ isnonzero(x::T) where {T<:AbstractFloat} = !iszero(x) """ ispositive(x) Returns `true` if `!isnegative(x)` and `isnonzero(x)`. """ ispositive(x::T) where {T<:AbstractFloat} = !isnegative(x) && isnonzero(x) """ isnonnegative(x) Returns `true` if `!isnegative(x)`. """ isnonnegative(x::T) where {T<:AbstractFloat} = !isnegative(x) """ isnonpositive(x) Returns `true` if `isnegative(x)` or `iszero(x)`. """ isnonpositive(x::T) where {T<:AbstractFloat} = isnegative(x) || iszero(x) """ isfractional(x) Returns `true` if `abs(x) < one(x)`. """ isfractional(x::T) where {T<:AbstractFloat} = abs(x) < one(T) iszero(x::DoubleFloat{T}) where {T<:IEEEFloat} = iszero(HI(x)) # && iszero(LO(x)) isnonzero(x::DoubleFloat{T}) where {T<:IEEEFloat} = !iszero(HI(x)) # || !iszero(LO(x)) isone(x::DoubleFloat{T}) where {T<:IEEEFloat} = isone(HI(x)) && iszero(LO(x)) ispositive(x::DoubleFloat{T}) where {T<:IEEEFloat} = !signbit(HI(x)) && !iszero(HI(x)) """ isnegative(x) Return `true` if `signbit(HI(x))` is `true`. """ isnegative(x::DoubleFloat{T}) where {T<:IEEEFloat} = signbit(HI(x)) isnonnegative(x::DoubleFloat{T}) where {T<:IEEEFloat} = !signbit(HI(x)) isnonpositive(x::DoubleFloat{T}) where {T<:IEEEFloat} = signbit(HI(x)) || iszero(HI(x)) isfinite(x::DoubleFloat{T}) where {T<:IEEEFloat} = isfinite(HI(x)) isinf(x::DoubleFloat{T}) where {T<:IEEEFloat} = isinf(HI(x)) """ isposinf(x) Tests whether a number positive and infinite. """ isposinf(x::DoubleFloat{T}) where {T<:IEEEFloat} = isinf(HI(x)) """ isneginf(x) Tests whether a number is negative and infinite. """ isneginf(x::DoubleFloat{T}) where {T<:IEEEFloat} = isinf(HI(x)) && signbit(HI(x)) isnan(x::DoubleFloat{T}) where {T<:IEEEFloat} = isnan(HI(x)) issubnormal(x::DoubleFloat{T}) where {T<:IEEEFloat} = issubnormal(LO(x)) || issubnormal(HI(x)) """ isnormal(x) Tests whether a floating point number is normal. """ isnormal(x::DoubleFloat{T}) where {T<:IEEEFloat} = isfinite(HI(x)) && !iszero(x) && (abs(x) >= floatmin(T)) @inline isinteger(x::DoubleFloat{T}) where {T<:IEEEFloat} = isinteger(HI(x)) && isinteger(LO(x)) isfractional(x::DoubleFloat{T}) where {T<:IEEEFloat} = !isinteger(LO(x)) || !isinteger(HI(x)) isodd(x::DoubleFloat{T}) where {T<:IEEEFloat} = if isinteger(x) (iszero(LO(x)) && isodd(HI(x))) || isodd(LO(x)) else false end iseven(x::DoubleFloat{T}) where {T<:IEEEFloat} = if isinteger(x) (iszero(LO(x)) && iseven(HI(x))) || iseven(LO(x)) else false end iseven(x::T) where {T<:IEEEFloat} = isinteger(x) && iseven(BigInt(x)) isodd(x::T) where {T<:IEEEFloat} = isinteger(x) && isodd(BigInt(x))
qqplot_nwj <- function(x, type='nw') { ## creates side by side, normal and Weibull qq plots if (type == 'nw') { par(mfrow=c(1,2)) qualityTools::qqPlot(x, "normal", col='black') qualityTools::qqPlot(x, "Weibull", col='black') } else { par(mfrow=c(1,3)) qualityTools::qqPlot(x, "normal", col='black') qualityTools::qqPlot(x, "Weibull", col='black') library(SuppDists) # need for Johnson distribution jparms <- JohnsonFit(x) quantiles_john <- qJohnson(ppoints(length(x)), jparms) stats::qqplot( x = x, xlab = "Data", y = quantiles_john, ylab = 'Quantiles from "Johnson" Distribution', main = expression('Q-Q plot for "Johnson" Distribution'), col='black') qqline(x, distribution = function(p) qJohnson(p, jparms), col=2) } } ## qqplot_nwj(mtcars$mpg) ## ## comparisons for normal qq plot ## par(mfrow=c(1,2)) ## qualityTools::qqPlot(x, "normal", col='black') ## quantiles_norm <- qnorm(ppoints(length(x)), mean = mean(x), sd = sd(x)) ## stats::qqplot( ## x = x, ## xlab = "Data", ## y = quantiles_norm, ## ylab = 'Quantiles from Normal Distribution', ## main = expression('Q-Q plot for Normal Distribution'), ## col='black') ## qqline(x, distribution = function(p) qnorm(p, mean=mean(x), sd=sd(x)), col=2) ## ## ## comparisons for Weibull qq plot ## par(mfrow=c(1,2)) ## qualityTools::qqPlot(x, "Weibull", col='black') ## tol_out <- exttol.int(x, alpha =0.1, P=0.99, side=1) ## shape <- tol_out$'shape.1' ## scale <- tol_out$'shape.2' ## quantiles_weib <- qweibull(ppoints(length(x)), shape = shape, scale = scale) ## stats::qqplot( ## x = x, ## xlab = "Data", ## y = quantiles_weib, ## ylab = 'Quantiles from Weibull Distribution', ## main = expression('Q-Q plot for Weibull Distribution'), ## col='black') ## qqline(x, distribution = function(p) qweibull(p, shape = shape, scale = scale), col=2)
function ob = ctranspose(ob) %function ob = ctranspose(ob) % "ctranspose" method for Gtomo2 class % transpose base object base = ob.base; ob.base = base';
import os from collections import namedtuple from functools import reduce from operator import mul import numpy as np from sandbox import misc as sbmisc def insert_to_dict(dictionary, elmt, indexes): depth = len(indexes) key = indexes[0] if depth > 1: indexes = indexes[1:] if key not in dictionary.keys(): dictionary[key] = {} insert_to_dict(dictionary[key], elmt, indexes) else: dictionary[key] = elmt def has_key(nested_dict, keys): ''' search through nested dictionary to fine the elements ''' if not type(keys) is tuple: keys = (keys,) if not type(nested_dict) == dict: return False if (len(keys) > 1): has_it = keys[0] in nested_dict return has_key(nested_dict[keys[0]], keys[1:]) if has_it else False else: return keys[0] in nested_dict def get_from_dict(nested_dict, keys, safe=True): if not type(keys) is tuple: keys = (keys,) if safe and not has_key(nested_dict, keys): return None if len(keys) > 1: return get_from_dict(nested_dict[keys[0]], keys[1:], False) else: return nested_dict[keys[0]] def nested_dict_values(dictionary): for v in dictionary.values(): if isinstance(v, dict): yield from nested_dict_values(v) else: yield v def progress(count, total, status=''): # adoped from https://gist.github.com/vladignatyev/06860ec2040cb497f0f3 bar_len = 60 percents = 0 filled_len = int(round(bar_len * count / float(total))) percents = round(100.0 * count / float(total), 1) bar = '=' * filled_len + '-' * (bar_len - filled_len) print('[%s] %s%s ...%s\r' % (bar, percents, '%', status)) def join_char_array(arrays, seperator='_'): sep_array = np.array([seperator] * len(arrays[0])) ret = arrays[0] for array in arrays[1:]: ret = np.core.defchararray.add(ret, sep_array) ret = np.core.defchararray.add(ret, array) return ret ## # some io stuff def create_dir(path2dir, safe=True): if safe: assert (not os.path.exists(path2dir)) os.mkdir(path2dir) return 0 ## # Find the largest bound area. Based on the solution on https://stackoverflow.com/questions/2478447 RectangleGeo = namedtuple('RectangleGeo', 'start height') def max_size(mat, value=1, verbose=False): """Find height, width, and idxes of the largest rectangle constraining all Based on the solution on https://stackoverflow.com/questions/247844 """ it = iter(mat) hist = [(el == value) for el in next(it, [])] def _box_idxes(yidxes, xidxes): return yidxes + xidxes max_size, xidxes = max_rectangle_size(hist) max_idxes = _box_idxes((0, 0), xidxes) nrow = mat.shape[0] nstep = int(nrow / 50) for i, row in enumerate(it, start=1): if verbose and i % nstep == 0: print("[%d/%d] processed" % (i, nrow)) hist = [(1 + h) if el == value else 0 for h, el in zip(hist, row)] cur_size, xidxes = max_rectangle_size(hist) cur_size = max(max_size, cur_size, key=area) if max_size != cur_size: max_size, max_idxes = (cur_size, _box_idxes((i - hist[xidxes[0]] + 1, i), xidxes)) return np.array(max_size).astype(int), max_idxes def max_rectangle_size(histogram): """Find height, width, idxes of the largest rectangle that fits entirely under the histogram. Based on the solution on https://stackoverflow.com/questions/247844 """ stack = [] top = lambda: stack[-1] max_size = (0, 0) # height, width of the largest rectangle pos = 0 # current position in the histogram xidxes = (0, 0) # xidxes of the rectangle def _update(max_size, xidxes, height, start, end): cur_size = max(max_size, (height, (end - start)), key=area) if max_size != cur_size: max_size, xidxes = cur_size, (start, end - 1) return max_size, xidxes for pos, height in enumerate(histogram): start = pos # position where rectangle starts while True: if not stack or height > top().height: stack.append(RectangleGeo(start, height)) # push elif stack and height < top().height: max_size, xidxes = _update(max_size, xidxes, top().height, top().start, pos) start, _ = stack.pop() continue break # height == top().height goes here # processing the last element in the stack pos += 1 for start, height in stack: max_size, xidxes = _update(max_size, xidxes, height, start, pos) return max_size, xidxes def area(size): return reduce(mul, size)
Are you looking for an apartment painting contractor in Cary, North Carolina? Whether you're searching for a painting contractor to paint the interior or exterior of your apartment building or just a single apartment, look no further. Since 1980, Exceptional Painting has provided quality, affordable Cary apartment painting services. We work on all projects, no matter how big or small. Whether you're a resident looking to have your apartment painted, or a building manager looking to have the building painted, Exceptional Painting is the right choice for you. Is the paint on your Cary apartment building chipped or just looking dull? Does it need to be rejuvenated? How about fresh new coat of paint? There's no better way to freshen up a worn out looking building than to apply a fresh coat of paint. Allow your tenants to take pride in their apartment building, or better yet, attract new potential tenants by giving your building a brand new look with a fresh coat of paint. Call the painting experts at (919) 435-2997. Whether you're a resident looking to have your Cary apartment painted, or you a building manager looking to have the interior of the apartment building painted, call the Cary painting pros at (919) 435-2997. Having 39 years of painting experience, the painters at Exceptional Painting are the best fit for you. Whether you're a resident looking to have your apartment or condominium painted, or a building manager looking to have the whole building or individual units painted, Exceptional Painting of Cary, North Carolina is the right choice for you. Call us today at (919) 435-2997 for your free estimates.
import numpy as np import random from Req import LeakyReLUSoftmaxCCE def cuckoo_search(X, Y, N, generations, p, l, in_shape, out_shape, layer_sizes): agents = [LeakyReLUSoftmaxCCE(in_shape, out_shape, layer_sizes) for _ in range(N)] generation_best = [] generation_best.append(max(agents, key=lambda agent: agent.loss(X, Y))) for _ in range(generations): agents = sorted(agents, key=lambda agent: agent.loss(X, Y))[:int(p*len(agents))] generation_best.append(agents[0]) return generation_best
function sVF = approximation(v, y, varargin) % % Syntax % sVF = S2VectorField.quadrature(v, value) % sVF = S2VectorField.quadrature(v, value, 'bandwidth', bw) % % Input % value - @vector3d % v - @vector3d % % Output % sVF - @S2VectorFieldHarmonic % % Options % bw - degree of the spherical harmonic (default: 128) % y = y.xyz; sF = S2FunHarmonic.quadrature(v, y, varargin{:}); sVF = S2VectorFieldHarmonic(sF); end
theory System imports Main begin datatype ('proc, 'msg, 'val) event = Receive (msg_sender: 'proc) (recv_msg: 'msg) | Request 'val | Timeout type_synonym ('proc, 'state, 'msg, 'val) step_func = \<open>'proc \<Rightarrow> 'state \<Rightarrow> ('proc, 'msg, 'val) event \<Rightarrow> ('state \<times> ('proc \<times> 'msg) set)\<close> fun valid_event :: \<open>('proc, 'msg, 'val) event \<Rightarrow> 'proc \<Rightarrow> ('proc \<times> 'proc \<times> 'msg) set \<Rightarrow> bool\<close> where \<open>valid_event (Receive sender msg) recpt msgs = ((sender, recpt, msg) \<in> msgs)\<close> | \<open>valid_event (Request _) _ _ = True\<close> | \<open>valid_event Timeout _ _ = True\<close> inductive execute :: \<open>('proc, 'state, 'msg, 'val) step_func \<Rightarrow> ('proc \<Rightarrow> 'state) \<Rightarrow> 'proc set \<Rightarrow> ('proc \<times> ('proc, 'msg, 'val) event) list \<Rightarrow> ('proc \<times> 'proc \<times> 'msg) set \<Rightarrow> ('proc \<Rightarrow> 'state) \<Rightarrow> bool\<close> where \<open>execute step init procs [] {} init\<close> | \<open>\<lbrakk>execute step init procs events msgs states; proc \<in> procs; valid_event event proc msgs; step proc (states proc) event = (new_state, sent); events' = events @ [(proc, event)]; msgs' = msgs \<union> {m. \<exists>(recpt, msg) \<in> sent. m = (proc, recpt, msg)}; states' = states (proc := new_state) \<rbrakk> \<Longrightarrow> execute step init procs events' msgs' states'\<close> theorem prove_invariant: assumes \<open>execute step init procs events msgs states\<close> shows \<open>some_invariant states\<close> using assms proof (induction events arbitrary: msgs states rule: List.rev_induct) case Nil then show \<open>some_invariant states\<close> sorry next case (snoc event events) then show ?case sorry qed end
module RecordDoc record A (a : Type) where anA : a record Tuple (a, b : Type) where proj1 : a proj2 : b record Singleton {0 a : Type} (v : a) where value : a 0 equal : value = v
Require Import ClassicalRealizability.Kbase. (**********************************) (** * Primitive pairs and sums **) (**********************************) (** ** Hypotheses: new instructions and their evaluation rules **) Parameter cpl : Λ -> Λ -> Λ. Parameter ι₁ ι₂ : Λ -> Λ. Parameter pair proj1 proj2 inj1 inj2 case : instruction. Notation "<| t , u |>" := (cpl t u). Axiom red_pair : forall t u k π e, pair↓e ★ t·u·k·π ≻ k ★ <|t, u|>·π. Axiom red_proj1 : forall t u k π e, proj1↓e ★ <|t, u|>·k·π ≻ k ★ t·π. Axiom red_proj2 : forall t u k π e, proj2↓e ★ <|t, u|>·k·π ≻ k ★ u·π. Axiom red_inj1 : forall t k π e, inj1↓e ★ t·k·π ≻ k ★ ι₁ t·π. Axiom red_inj2 : forall u k π e, inj2↓e ★ u·k·π ≻ k ★ ι₂ u·π. Axiom red_case1 : forall t k₁ k₂ π e, case↓e ★ ι₁ t·k₁·k₂·π ≻ k₁ ★ t·π. Axiom red_case2 : forall u k₁ k₂ π e, case↓e ★ ι₂ u·k₁·k₂·π ≻ k₂ ★ u·π. Definition prod A B F := fun π => exists t, exists u, exists π', π = <|t, u|>·π' /\ t ⊩ A /\ u ⊩ B /\ π' ∈ ‖F‖. Notation "A ** B ⇒ F" := (prod A B F) (at level 40). Definition sum A B F := fun π => exists t, exists π', ((π = ι₁ t·π' /\ t ⊩ A) \/ (π = ι₂ t·π' /\ t ⊩ B)) /\ π' ∈ ‖F‖. Notation "A ++ B ⇒ F" := (sum A B F) (at level 40). (** ** Tactics **) Global Ltac pair_sum_Keval tac := lazymatch goal with | [ |- Cst pair↓ _ ★ ?t·?u·?k·?π ∈ ⫫] => Debug "Keval_pair"; apply anti_evaluation with (k ★ <|t, u|>·π); [now apply red_pair |] | [ |- Cst proj1↓ _ ★ <|?t, ?u|>·?k·?π ∈ ⫫] => Debug "Keval_proj1"; apply anti_evaluation with (k ★ t·π); [now apply red_proj1 |] | [ |- Cst proj2↓ _ ★ <|?t, ?u|>·?k·?π ∈ ⫫] => Debug "Keval_proj2"; apply anti_evaluation with (k ★ u·π); [now apply red_proj2 |] | [ |- Cst inj1↓ _ ★ ?t·?k·?π ∈ ⫫] => Debug "Keval_inj1"; apply anti_evaluation with (k ★ ι₁ t·π); [now apply red_inj1 |] | [ |- Cst inj2↓ _ ★ ?u·?k·?π ∈ ⫫] => Debug "Keval_inj2"; apply anti_evaluation with (k ★ ι₂ u·π); [now apply red_inj2 |] | [ |- Cst case↓ _ ★ ι₁ ?t·?k₁·?k₂·?π ∈ ⫫] => Debug "Keval_case1"; apply anti_evaluation with (k₁ ★ t·π); [now apply red_case1 |] | [ |- Cst case↓ _ ★ ι₂ ?u·?k₁·?k₂·?π ∈ ⫫] => Debug "Keval_case2"; apply anti_evaluation with (k₂ ★ u·π); [now apply red_case2 |] | _ => Debug "Keval_next"; tac end. Ltac Keval ::= basic_Keval ltac:(idtac; pair_sum_Keval fail). Global Ltac pair_sum_dstack tac Hπ := lazymatch type of Hπ with | ?π ∈ ‖?A ** ?B ⇒ ?F‖ => let t := fresh "t" in let Ht := fresh "Ht" in let u := fresh "u" in let Hu := fresh "Hu" in let π' := fresh "π" in let t' := fresh "t" in let u' := fresh "u" in let Heq := fresh "Heq" in destruct Hπ as [t' [u' [π' [Heq [Ht [Hu Hπ]]]]]]; destruct π as [| t π]; inversion Heq | ?π ∈ ‖?A ++ ?B ⇒ ?F‖ => let t := fresh "t" in let t' := fresh "t" in let π' := fresh "π" in let Ht := fresh "Ht" in let Heq := fresh "Heq" in destruct Hπ as [t [π' [Hcase Hπ]]]; destruct π as [| t' π]; (destruct Hcase as [[Heq Ht] | [Heq Ht]]; inversion Heq; subst π' t'; clear Heq) | _ => tac Hπ end. Ltac dstack ::= basic_dstack ltac:(pair_sum_dstack fail). (** ** Specifications **) Theorem pair_realizer : forall e, pair↓e ⊩ ∀A B, A → B → ∀Z, (A ** B ⇒ Z) → Z. Proof. Ksolve. Qed. Theorem proj1_realizer : forall e, proj1↓e ⊩ ∀A B Z, (A ** B ⇒ ((A → Z) → Z)). Proof. Ksolve. Qed. Theorem proj2_realizer : forall e, proj2↓e ⊩ ∀A B Z, (A ** B ⇒ ((B → Z) → Z)). Proof. Ksolve. Qed. Theorem inj1_realizer : forall e, inj1↓e ⊩ ∀A B, A → ∀Z, (A ++ B ⇒ Z) → Z. Proof. Ksolve. intuition. Qed. Theorem inj2_realizer : forall e, inj2↓e ⊩ ∀A B, B → ∀Z, (A ++ B ⇒ Z) → Z. Proof. Ksolve. intuition. Qed. Theorem case_realizer : forall e, case↓e ⊩ ∀A B, A ++ B ⇒ ∀Z, (A → Z) → (B → Z) → Z. Proof. Ksolve. Qed. (*********************************************************) (** * Equivalence between e₁ = e₂ ⇒ A and e₁ = e₂ ↦ A **) (*********************************************************) Lemma eq_equiv1 : forall T (a a' : T) A e, λ"x" λ"e" "e" @ "x"↓e ⊩ (a = a' ↦ A) → prop (a = a') → A. Proof. Ksolve. elim (Classical_Prop.classic (a = a')); intro H. left. find. right. find. Qed. Lemma eq_equiv2 : forall T (a a' : T) A e, λ"x" "x" @ Id↓e ⊩ (prop (a = a') → A) → a = a' ↦ A. Proof. Ksolve. start. destruct Hπ as [[] | []]. now apply Id_realizer. contradiction. Qed. (****************************************************) (** * Equivalence between e₁ ≠ e₂ and ¬(e₁ = e₂) **) (****************************************************) Notation "a ≠ a'" := (if Peano_dec.eq_nat_dec a a' then ⊥ else ⊤) (at level 10). (*Definition neq_equiv1 := λ"x" "x" @ Id. Definition neq_equiv2 := λ"x" λ"y" "y" @ "x".*) Transparent prop. Lemma neq_equiv1 : forall e, λ"x" "x" @ Id↓e ⊩ ∀a a', ¬(prop (a = a')) → a ≠ a'. Proof. Ksolve. destruct (Peano_dec.eq_nat_dec a a'). unfold prop in *. start. destruct Hπ as [[_ Hπ] | [Hc _]]. unfold one in *. Ksolve. contradiction. elim Hπ. Qed. Lemma neq_equiv2 : forall e, λ"x" λ"y" "y" @ "x"↓e ⊩ ∀a a', a ≠ a' → ¬(prop (a = a')). Proof. Ksolve. unfold prop. destruct (Peano_dec.eq_nat_dec a a'). left. split. ok. find. right. repeat split; ok. Qed. Opaque prop. (***********************************) (** * Weak Recurrence Principle **) (***********************************) Notation "x == 0" := (∀y, x ≠ (S y)) (at level 11). Lemma S_wf : well_founded (fun y x => S y = x). Proof. intros n. induction n; constructor; intros m Hm. discriminate Hm. now inversion Hm. Qed. Lemma Y_wra : forall e, Y↓e ⊩ ∀P, (∀x, (∀y, S y = x ↦ P y) → P x) → ∀x, P x. Proof. intros ? ? ?. apply (Y_realizer S_wf). exact H. Qed. Definition WRA := λ"x" λ"y" Y @ (λ"z" callcc @ (λ"k" "x" @ ("k" @ ("y" @ "z")))). Theorem WRA_realizer : forall e, WRA↓e ⊩ ∀P, (∀x, x == 0 → P x) → (∀y, P y → P (S y)) → ∀x, P x. Proof. Ksolve. apply Y_wra. do 2 Ksolve. Ksolve. destruct (Peano_dec.eq_nat_dec (S y) x0) as [Heq | Heq]. Ksolve. destruct (Peano_dec.eq_nat_dec x0 (S y)) as [Heq2 | Heq2]. subst. now elim Heq. ok. destruct (Peano_dec.eq_nat_dec x0 (S y)). now subst. ok. Qed.
State Before: J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H : IsPushout f g h i ⊢ IsVanKampen H ↔ IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) State After: case mp J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H : IsPushout f g h i ⊢ IsVanKampen H → IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) case mpr J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H : IsPushout f g h i ⊢ IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) → IsVanKampen H Tactic: constructor State Before: case mp J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H : IsPushout f g h i ⊢ IsVanKampen H → IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) State After: case mp J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ Nonempty (IsColimit c') ↔ ∀ (j : WalkingSpan), IsPullback (c'.ι.app j) (α.app j) fα ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app j) Tactic: intro H F' c' α fα eα hα State Before: case mp J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ Nonempty (IsColimit c') ↔ ∀ (j : WalkingSpan), IsPullback (c'.ι.app j) (α.app j) fα ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app j) State After: case mp.refine'_1 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ Nonempty (IsColimit c') ↔ IsPushout (F'.map WalkingSpan.Hom.fst) (F'.map WalkingSpan.Hom.snd) (c'.ι.app WalkingSpan.left) (c'.ι.app WalkingSpan.right) case mp.refine'_2 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ CommSq (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h case mp.refine'_3 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ CommSq (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i case mp.refine'_4 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ CommSq (F'.map WalkingSpan.Hom.fst) (F'.map WalkingSpan.Hom.snd) (c'.ι.app WalkingSpan.left) (c'.ι.app WalkingSpan.right) case mp.refine'_5 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ IsPullback (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h ∧ IsPullback (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i ↔ ∀ (j : WalkingSpan), IsPullback (c'.ι.app j) (α.app j) fα ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app j) Tactic: refine' Iff.trans _ ((H (F'.map WalkingSpan.Hom.fst) (F'.map WalkingSpan.Hom.snd) (c'.ι.app _) (c'.ι.app _) (α.app _) (α.app _) (α.app _) fα (by convert hα WalkingSpan.Hom.fst) (by convert hα WalkingSpan.Hom.snd) _ _ _).trans _) State Before: case mp.refine'_5 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ IsPullback (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h ∧ IsPullback (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i ↔ ∀ (j : WalkingSpan), IsPullback (c'.ι.app j) (α.app j) fα ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app j) State After: case mp.refine'_5.mp J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ IsPullback (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h ∧ IsPullback (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i → ∀ (j : WalkingSpan), IsPullback (c'.ι.app j) (α.app j) fα ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app j) case mp.refine'_5.mpr J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ (∀ (j : WalkingSpan), IsPullback (c'.ι.app j) (α.app j) fα ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app j)) → IsPullback (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h ∧ IsPullback (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i Tactic: constructor State Before: J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ IsPullback (F'.map WalkingSpan.Hom.fst) (α.app WalkingSpan.zero) (α.app WalkingSpan.left) f State After: no goals Tactic: convert hα WalkingSpan.Hom.fst State Before: J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ IsPullback (F'.map WalkingSpan.Hom.snd) (α.app WalkingSpan.zero) (α.app WalkingSpan.right) g State After: no goals Tactic: convert hα WalkingSpan.Hom.snd State Before: case mp.refine'_1 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ Nonempty (IsColimit c') ↔ IsPushout (F'.map WalkingSpan.Hom.fst) (F'.map WalkingSpan.Hom.snd) (c'.ι.app WalkingSpan.left) (c'.ι.app WalkingSpan.right) State After: case mp.refine'_1 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α this : F'.map WalkingSpan.Hom.fst ≫ c'.ι.app WalkingSpan.left = F'.map WalkingSpan.Hom.snd ≫ c'.ι.app WalkingSpan.right ⊢ Nonempty (IsColimit c') ↔ IsPushout (F'.map WalkingSpan.Hom.fst) (F'.map WalkingSpan.Hom.snd) (c'.ι.app WalkingSpan.left) (c'.ι.app WalkingSpan.right) Tactic: have : F'.map WalkingSpan.Hom.fst ≫ c'.ι.app WalkingSpan.left = F'.map WalkingSpan.Hom.snd ≫ c'.ι.app WalkingSpan.right := by simp only [Cocone.w] State Before: case mp.refine'_1 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α this : F'.map WalkingSpan.Hom.fst ≫ c'.ι.app WalkingSpan.left = F'.map WalkingSpan.Hom.snd ≫ c'.ι.app WalkingSpan.right ⊢ Nonempty (IsColimit c') ↔ IsPushout (F'.map WalkingSpan.Hom.fst) (F'.map WalkingSpan.Hom.snd) (c'.ι.app WalkingSpan.left) (c'.ι.app WalkingSpan.right) State After: case mp.refine'_1 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α this : F'.map WalkingSpan.Hom.fst ≫ c'.ι.app WalkingSpan.left = F'.map WalkingSpan.Hom.snd ≫ c'.ι.app WalkingSpan.right ⊢ Nonempty (IsColimit (PushoutCocone.mk (c'.ι.app WalkingSpan.left) (c'.ι.app WalkingSpan.right) this)) ↔ IsPushout (F'.map WalkingSpan.Hom.fst) (F'.map WalkingSpan.Hom.snd) (c'.ι.app WalkingSpan.left) (c'.ι.app WalkingSpan.right) J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α this : F'.map WalkingSpan.Hom.fst ≫ c'.ι.app WalkingSpan.left = F'.map WalkingSpan.Hom.snd ≫ c'.ι.app WalkingSpan.right ⊢ (Cocones.precompose (diagramIsoSpan F').inv).obj c' ≅ PushoutCocone.mk (c'.ι.app WalkingSpan.left) (c'.ι.app WalkingSpan.right) this Tactic: rw [(IsColimit.equivOfNatIsoOfIso (diagramIsoSpan F') c' (PushoutCocone.mk _ _ this) _).nonempty_congr] State Before: J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ F'.map WalkingSpan.Hom.fst ≫ c'.ι.app WalkingSpan.left = F'.map WalkingSpan.Hom.snd ≫ c'.ι.app WalkingSpan.right State After: no goals Tactic: simp only [Cocone.w] State Before: case mp.refine'_1 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α this : F'.map WalkingSpan.Hom.fst ≫ c'.ι.app WalkingSpan.left = F'.map WalkingSpan.Hom.snd ≫ c'.ι.app WalkingSpan.right ⊢ Nonempty (IsColimit (PushoutCocone.mk (c'.ι.app WalkingSpan.left) (c'.ι.app WalkingSpan.right) this)) ↔ IsPushout (F'.map WalkingSpan.Hom.fst) (F'.map WalkingSpan.Hom.snd) (c'.ι.app WalkingSpan.left) (c'.ι.app WalkingSpan.right) State After: no goals Tactic: exact ⟨fun h => ⟨⟨this⟩, h⟩, fun h => h.2⟩ State Before: J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α this : F'.map WalkingSpan.Hom.fst ≫ c'.ι.app WalkingSpan.left = F'.map WalkingSpan.Hom.snd ≫ c'.ι.app WalkingSpan.right ⊢ (Cocones.precompose (diagramIsoSpan F').inv).obj c' ≅ PushoutCocone.mk (c'.ι.app WalkingSpan.left) (c'.ι.app WalkingSpan.right) this State After: J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α this : F'.map WalkingSpan.Hom.fst ≫ c'.ι.app WalkingSpan.left = F'.map WalkingSpan.Hom.snd ≫ c'.ι.app WalkingSpan.right ⊢ ∀ (j : WalkingSpan), ((Cocones.precompose (diagramIsoSpan F').inv).obj c').ι.app j ≫ (Iso.refl c'.pt).hom = (PushoutCocone.mk (c'.ι.app WalkingSpan.left) (c'.ι.app WalkingSpan.right) this).ι.app j Tactic: refine' Cocones.ext (Iso.refl c'.pt) _ State Before: J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α this : F'.map WalkingSpan.Hom.fst ≫ c'.ι.app WalkingSpan.left = F'.map WalkingSpan.Hom.snd ≫ c'.ι.app WalkingSpan.right ⊢ ∀ (j : WalkingSpan), ((Cocones.precompose (diagramIsoSpan F').inv).obj c').ι.app j ≫ (Iso.refl c'.pt).hom = (PushoutCocone.mk (c'.ι.app WalkingSpan.left) (c'.ι.app WalkingSpan.right) this).ι.app j State After: no goals Tactic: rintro (_ | _ | _) <;> dsimp <;> simp only [c'.w, Category.assoc, Category.id_comp, Category.comp_id] State Before: case mp.refine'_2 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ CommSq (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h State After: no goals Tactic: exact ⟨NatTrans.congr_app eα.symm _⟩ State Before: case mp.refine'_3 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ CommSq (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i State After: no goals Tactic: exact ⟨NatTrans.congr_app eα.symm _⟩ State Before: case mp.refine'_4 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ CommSq (F'.map WalkingSpan.Hom.fst) (F'.map WalkingSpan.Hom.snd) (c'.ι.app WalkingSpan.left) (c'.ι.app WalkingSpan.right) State After: no goals Tactic: exact ⟨by simp⟩ State Before: J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ F'.map WalkingSpan.Hom.fst ≫ c'.ι.app WalkingSpan.left = F'.map WalkingSpan.Hom.snd ≫ c'.ι.app WalkingSpan.right State After: no goals Tactic: simp State Before: case mp.refine'_5.mp J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ IsPullback (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h ∧ IsPullback (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i → ∀ (j : WalkingSpan), IsPullback (c'.ι.app j) (α.app j) fα ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app j) State After: case mp.refine'_5.mp.intro.none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α h₁ : IsPullback (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h h₂ : IsPullback (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i ⊢ IsPullback (c'.ι.app none) (α.app none) fα ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app none) case mp.refine'_5.mp.intro.some.left J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α h₁ : IsPullback (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h h₂ : IsPullback (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i ⊢ IsPullback (c'.ι.app (some WalkingPair.left)) (α.app (some WalkingPair.left)) fα ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app (some WalkingPair.left)) case mp.refine'_5.mp.intro.some.right J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α h₁ : IsPullback (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h h₂ : IsPullback (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i ⊢ IsPullback (c'.ι.app (some WalkingPair.right)) (α.app (some WalkingPair.right)) fα ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app (some WalkingPair.right)) Tactic: rintro ⟨h₁, h₂⟩ (_ | _ | _) State Before: case mp.refine'_5.mp.intro.some.left J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α h₁ : IsPullback (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h h₂ : IsPullback (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i ⊢ IsPullback (c'.ι.app (some WalkingPair.left)) (α.app (some WalkingPair.left)) fα ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app (some WalkingPair.left)) case mp.refine'_5.mp.intro.some.right J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α h₁ : IsPullback (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h h₂ : IsPullback (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i ⊢ IsPullback (c'.ι.app (some WalkingPair.right)) (α.app (some WalkingPair.right)) fα ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app (some WalkingPair.right)) State After: no goals Tactic: exacts [h₁, h₂] State Before: case mp.refine'_5.mp.intro.none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α h₁ : IsPullback (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h h₂ : IsPullback (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i ⊢ IsPullback (c'.ι.app none) (α.app none) fα ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app none) State After: case mp.refine'_5.mp.intro.none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α h₁ : IsPullback (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h h₂ : IsPullback (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i ⊢ IsPullback (F'.map WalkingSpan.Hom.fst ≫ c'.ι.app WalkingSpan.left) (α.app none) fα ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app none) Tactic: rw [← c'.w WalkingSpan.Hom.fst] State Before: case mp.refine'_5.mp.intro.none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α h₁ : IsPullback (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h h₂ : IsPullback (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i ⊢ IsPullback (F'.map WalkingSpan.Hom.fst ≫ c'.ι.app WalkingSpan.left) (α.app none) fα ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app none) State After: no goals Tactic: exact (hα WalkingSpan.Hom.fst).paste_horiz h₁ State Before: case mp.refine'_5.mpr J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α ⊢ (∀ (j : WalkingSpan), IsPullback (c'.ι.app j) (α.app j) fα ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app j)) → IsPullback (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h ∧ IsPullback (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i State After: case mp.refine'_5.mpr J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h✝ : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h✝ i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h✝ i (_ : f ≫ h✝ = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h✝ i (_ : f ≫ h✝ = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α h : ∀ (j : WalkingSpan), IsPullback (c'.ι.app j) (α.app j) fα ((PushoutCocone.mk h✝ i (_ : f ≫ h✝ = g ≫ i)).ι.app j) ⊢ IsPullback (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h✝ ∧ IsPullback (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i Tactic: intro h State Before: case mp.refine'_5.mpr J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h✝ : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h✝ i H : IsVanKampen H✝ F' : WalkingSpan ⥤ C c' : Cocone F' α : F' ⟶ span f g fα : c'.pt ⟶ (PushoutCocone.mk h✝ i (_ : f ≫ h✝ = g ≫ i)).pt eα : α ≫ (PushoutCocone.mk h✝ i (_ : f ≫ h✝ = g ≫ i)).ι = c'.ι ≫ (Functor.const WalkingSpan).map fα hα : NatTrans.Equifibered α h : ∀ (j : WalkingSpan), IsPullback (c'.ι.app j) (α.app j) fα ((PushoutCocone.mk h✝ i (_ : f ≫ h✝ = g ≫ i)).ι.app j) ⊢ IsPullback (c'.ι.app WalkingSpan.left) (α.app WalkingSpan.left) fα h✝ ∧ IsPullback (c'.ι.app WalkingSpan.right) (α.app WalkingSpan.right) fα i State After: no goals Tactic: exact ⟨h _, h _⟩ State Before: case mpr J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H : IsPushout f g h i ⊢ IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) → IsVanKampen H State After: case mpr J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ IsPushout f' g' h' i' ↔ IsPullback h' αX αZ h ∧ IsPullback i' αY αZ i Tactic: introv H W' hf hg hh hi w State Before: case mpr J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ IsPushout f' g' h' i' ↔ IsPullback h' αX αZ h ∧ IsPullback i' αY αZ i State After: case mpr.refine'_1 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ IsPushout f' g' h' i' ↔ Nonempty (IsColimit (CommSq.cocone w)) case mpr.refine'_2 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ ∀ ⦃X_1 Y_1 : WalkingSpan⦄ (f_1 : X_1 ⟶ Y_1), ((span f' g').map f_1 ≫ Option.casesOn Y_1 αW fun val => WalkingPair.casesOn val αX αY) = (Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) ≫ (span f g).map f_1 case mpr.refine'_3 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ (NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = (CommSq.cocone w).ι ≫ (Functor.const WalkingSpan).map αZ case mpr.refine'_4 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ NatTrans.Equifibered (NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) case mpr.refine'_5 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ (∀ (j : WalkingSpan), IsPullback ((CommSq.cocone w).ι.app j) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app j) αZ ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app j)) ↔ IsPullback h' αX αZ h ∧ IsPullback i' αY αZ i Tactic: refine' Iff.trans _ ((H w.cocone ⟨by rintro (_ | _ | _); exacts [αW, αX, αY], _⟩ αZ _ _).trans _) State Before: case mpr.refine'_1 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ IsPushout f' g' h' i' ↔ Nonempty (IsColimit (CommSq.cocone w)) case mpr.refine'_2 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ ∀ ⦃X_1 Y_1 : WalkingSpan⦄ (f_1 : X_1 ⟶ Y_1), ((span f' g').map f_1 ≫ Option.casesOn Y_1 αW fun val => WalkingPair.casesOn val αX αY) = (Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) ≫ (span f g).map f_1 case mpr.refine'_3 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ (NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = (CommSq.cocone w).ι ≫ (Functor.const WalkingSpan).map αZ case mpr.refine'_4 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ NatTrans.Equifibered (NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) case mpr.refine'_5 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ (∀ (j : WalkingSpan), IsPullback ((CommSq.cocone w).ι.app j) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app j) αZ ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app j)) ↔ IsPullback h' αX αZ h ∧ IsPullback i' αY αZ i State After: case mpr.refine'_2 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ ∀ ⦃X_1 Y_1 : WalkingSpan⦄ (f_1 : X_1 ⟶ Y_1), ((span f' g').map f_1 ≫ Option.casesOn Y_1 αW fun val => WalkingPair.casesOn val αX αY) = (Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) ≫ (span f g).map f_1 case mpr.refine'_3 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ (NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = (CommSq.cocone w).ι ≫ (Functor.const WalkingSpan).map αZ case mpr.refine'_4 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ NatTrans.Equifibered (NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) case mpr.refine'_5 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ (∀ (j : WalkingSpan), IsPullback ((CommSq.cocone w).ι.app j) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app j) αZ ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app j)) ↔ IsPullback h' αX αZ h ∧ IsPullback i' αY αZ i case mpr.refine'_1 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ IsPushout f' g' h' i' ↔ Nonempty (IsColimit (CommSq.cocone w)) Tactic: rotate_left State Before: J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ (X_1 : WalkingSpan) → (span f' g').obj X_1 ⟶ (span f g).obj X_1 State After: case none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ (span f' g').obj none ⟶ (span f g).obj none case some.left J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ (span f' g').obj (some WalkingPair.left) ⟶ (span f g).obj (some WalkingPair.left) case some.right J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ (span f' g').obj (some WalkingPair.right) ⟶ (span f g).obj (some WalkingPair.right) Tactic: rintro (_ | _ | _) State Before: case none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ (span f' g').obj none ⟶ (span f g).obj none case some.left J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ (span f' g').obj (some WalkingPair.left) ⟶ (span f g).obj (some WalkingPair.left) case some.right J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ (span f' g').obj (some WalkingPair.right) ⟶ (span f g).obj (some WalkingPair.right) State After: no goals Tactic: exacts [αW, αX, αY] State Before: case mpr.refine'_2 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ ∀ ⦃X_1 Y_1 : WalkingSpan⦄ (f_1 : X_1 ⟶ Y_1), ((span f' g').map f_1 ≫ Option.casesOn Y_1 αW fun val => WalkingPair.casesOn val αX αY) = (Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) ≫ (span f g).map f_1 State After: case mpr.refine'_2.id J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i✝ : Y ⟶ Z H✝ : IsPushout f g h i✝ H : IsVanKampenColimit (PushoutCocone.mk h i✝ (_ : f ≫ h = g ≫ i✝)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i✝ w : CommSq f' g' h' i' i : WalkingSpan ⊢ ((span f' g').map (WidePushoutShape.Hom.id i) ≫ Option.casesOn i αW fun val => WalkingPair.casesOn val αX αY) = (Option.casesOn i αW fun val => WalkingPair.casesOn val αX αY) ≫ (span f g).map (WidePushoutShape.Hom.id i) case mpr.refine'_2.init.left J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ ((span f' g').map (WidePushoutShape.Hom.init WalkingPair.left) ≫ Option.casesOn (some WalkingPair.left) αW fun val => WalkingPair.casesOn val αX αY) = (Option.casesOn none αW fun val => WalkingPair.casesOn val αX αY) ≫ (span f g).map (WidePushoutShape.Hom.init WalkingPair.left) case mpr.refine'_2.init.right J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ ((span f' g').map (WidePushoutShape.Hom.init WalkingPair.right) ≫ Option.casesOn (some WalkingPair.right) αW fun val => WalkingPair.casesOn val αX αY) = (Option.casesOn none αW fun val => WalkingPair.casesOn val αX αY) ≫ (span f g).map (WidePushoutShape.Hom.init WalkingPair.right) Tactic: rintro i _ (_ | _ | _) State Before: case mpr.refine'_2.init.left J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ ((span f' g').map (WidePushoutShape.Hom.init WalkingPair.left) ≫ Option.casesOn (some WalkingPair.left) αW fun val => WalkingPair.casesOn val αX αY) = (Option.casesOn none αW fun val => WalkingPair.casesOn val αX αY) ≫ (span f g).map (WidePushoutShape.Hom.init WalkingPair.left) case mpr.refine'_2.init.right J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ ((span f' g').map (WidePushoutShape.Hom.init WalkingPair.right) ≫ Option.casesOn (some WalkingPair.right) αW fun val => WalkingPair.casesOn val αX αY) = (Option.casesOn none αW fun val => WalkingPair.casesOn val αX αY) ≫ (span f g).map (WidePushoutShape.Hom.init WalkingPair.right) State After: no goals Tactic: exacts [hf.w, hg.w] State Before: case mpr.refine'_2.id J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i✝ : Y ⟶ Z H✝ : IsPushout f g h i✝ H : IsVanKampenColimit (PushoutCocone.mk h i✝ (_ : f ≫ h = g ≫ i✝)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i✝ w : CommSq f' g' h' i' i : WalkingSpan ⊢ ((span f' g').map (WidePushoutShape.Hom.id i) ≫ Option.casesOn i αW fun val => WalkingPair.casesOn val αX αY) = (Option.casesOn i αW fun val => WalkingPair.casesOn val αX αY) ≫ (span f g).map (WidePushoutShape.Hom.id i) State After: case mpr.refine'_2.id J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i✝ : Y ⟶ Z H✝ : IsPushout f g h i✝ H : IsVanKampenColimit (PushoutCocone.mk h i✝ (_ : f ≫ h = g ≫ i✝)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i✝ w : CommSq f' g' h' i' i : WalkingSpan ⊢ (span f' g').map (𝟙 i) ≫ Option.rec αW (fun val => WalkingPair.rec αX αY val) i = Option.rec αW (fun val => WalkingPair.rec αX αY val) i ≫ (span f g).map (𝟙 i) Tactic: dsimp State Before: case mpr.refine'_2.id J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i✝ : Y ⟶ Z H✝ : IsPushout f g h i✝ H : IsVanKampenColimit (PushoutCocone.mk h i✝ (_ : f ≫ h = g ≫ i✝)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i✝ w : CommSq f' g' h' i' i : WalkingSpan ⊢ (span f' g').map (𝟙 i) ≫ Option.rec αW (fun val => WalkingPair.rec αX αY val) i = Option.rec αW (fun val => WalkingPair.rec αX αY val) i ≫ (span f g).map (𝟙 i) State After: no goals Tactic: simp only [Functor.map_id, Category.comp_id, Category.id_comp] State Before: case mpr.refine'_3 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ (NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι = (CommSq.cocone w).ι ≫ (Functor.const WalkingSpan).map αZ State After: case mpr.refine'_3.w.h.none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι).app none = ((CommSq.cocone w).ι ≫ (Functor.const WalkingSpan).map αZ).app none case mpr.refine'_3.w.h.some.left J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι).app (some WalkingPair.left) = ((CommSq.cocone w).ι ≫ (Functor.const WalkingSpan).map αZ).app (some WalkingPair.left) case mpr.refine'_3.w.h.some.right J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι).app (some WalkingPair.right) = ((CommSq.cocone w).ι ≫ (Functor.const WalkingSpan).map αZ).app (some WalkingPair.right) Tactic: ext (_ | _ | _) State Before: case mpr.refine'_3.w.h.some.left J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι).app (some WalkingPair.left) = ((CommSq.cocone w).ι ≫ (Functor.const WalkingSpan).map αZ).app (some WalkingPair.left) case mpr.refine'_3.w.h.some.right J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι).app (some WalkingPair.right) = ((CommSq.cocone w).ι ≫ (Functor.const WalkingSpan).map αZ).app (some WalkingPair.right) State After: no goals Tactic: exacts [hh.w.symm, hi.w.symm] State Before: case mpr.refine'_3.w.h.none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) ≫ (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι).app none = ((CommSq.cocone w).ι ≫ (Functor.const WalkingSpan).map αZ).app none State After: case mpr.refine'_3.w.h.none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ αW ≫ f ≫ h = (CommSq.cocone w).ι.app none ≫ αZ Tactic: dsimp State Before: case mpr.refine'_3.w.h.none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ αW ≫ f ≫ h = (CommSq.cocone w).ι.app none ≫ αZ State After: case mpr.refine'_3.w.h.none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ αW ≫ f ≫ h = (f' ≫ PushoutCocone.inl (CommSq.cocone w)) ≫ αZ Tactic: rw [PushoutCocone.condition_zero] State Before: case mpr.refine'_3.w.h.none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ αW ≫ f ≫ h = (f' ≫ PushoutCocone.inl (CommSq.cocone w)) ≫ αZ State After: no goals Tactic: erw [Category.assoc, hh.w, hf.w_assoc] State Before: case mpr.refine'_4 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ NatTrans.Equifibered (NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY) State After: case mpr.refine'_4.id J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i✝ : Y ⟶ Z H✝ : IsPushout f g h i✝ H : IsVanKampenColimit (PushoutCocone.mk h i✝ (_ : f ≫ h = g ≫ i✝)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i✝ w : CommSq f' g' h' i' i : WalkingSpan ⊢ IsPullback ((span f' g').map (WidePushoutShape.Hom.id i)) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app i) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app i) ((span f g).map (WidePushoutShape.Hom.id i)) case mpr.refine'_4.init.left J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ IsPullback ((span f' g').map (WidePushoutShape.Hom.init WalkingPair.left)) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app none) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app (some WalkingPair.left)) ((span f g).map (WidePushoutShape.Hom.init WalkingPair.left)) case mpr.refine'_4.init.right J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ IsPullback ((span f' g').map (WidePushoutShape.Hom.init WalkingPair.right)) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app none) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app (some WalkingPair.right)) ((span f g).map (WidePushoutShape.Hom.init WalkingPair.right)) Tactic: rintro i _ (_ | _ | _) State Before: case mpr.refine'_4.init.left J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ IsPullback ((span f' g').map (WidePushoutShape.Hom.init WalkingPair.left)) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app none) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app (some WalkingPair.left)) ((span f g).map (WidePushoutShape.Hom.init WalkingPair.left)) case mpr.refine'_4.init.right J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ IsPullback ((span f' g').map (WidePushoutShape.Hom.init WalkingPair.right)) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app none) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app (some WalkingPair.right)) ((span f g).map (WidePushoutShape.Hom.init WalkingPair.right)) State After: no goals Tactic: exacts [hf, hg] State Before: case mpr.refine'_4.id J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i✝ : Y ⟶ Z H✝ : IsPushout f g h i✝ H : IsVanKampenColimit (PushoutCocone.mk h i✝ (_ : f ≫ h = g ≫ i✝)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i✝ w : CommSq f' g' h' i' i : WalkingSpan ⊢ IsPullback ((span f' g').map (WidePushoutShape.Hom.id i)) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app i) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app i) ((span f g).map (WidePushoutShape.Hom.id i)) State After: case mpr.refine'_4.id J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i✝ : Y ⟶ Z H✝ : IsPushout f g h i✝ H : IsVanKampenColimit (PushoutCocone.mk h i✝ (_ : f ≫ h = g ≫ i✝)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i✝ w : CommSq f' g' h' i' i : WalkingSpan ⊢ IsPullback ((span f' g').map (𝟙 i)) (Option.rec αW (fun val => WalkingPair.rec αX αY val) i) (Option.rec αW (fun val => WalkingPair.rec αX αY val) i) ((span f g).map (𝟙 i)) Tactic: dsimp State Before: case mpr.refine'_4.id J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i✝ : Y ⟶ Z H✝ : IsPushout f g h i✝ H : IsVanKampenColimit (PushoutCocone.mk h i✝ (_ : f ≫ h = g ≫ i✝)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i✝ w : CommSq f' g' h' i' i : WalkingSpan ⊢ IsPullback ((span f' g').map (𝟙 i)) (Option.rec αW (fun val => WalkingPair.rec αX αY val) i) (Option.rec αW (fun val => WalkingPair.rec αX αY val) i) ((span f g).map (𝟙 i)) State After: case mpr.refine'_4.id J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i✝ : Y ⟶ Z H✝ : IsPushout f g h i✝ H : IsVanKampenColimit (PushoutCocone.mk h i✝ (_ : f ≫ h = g ≫ i✝)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i✝ w : CommSq f' g' h' i' i : WalkingSpan ⊢ IsPullback (𝟙 ((span f' g').obj i)) (Option.rec αW (fun val => WalkingPair.rec αX αY val) i) (Option.rec αW (fun val => WalkingPair.rec αX αY val) i) (𝟙 ((span f g).obj i)) Tactic: simp_rw [Functor.map_id] State Before: case mpr.refine'_4.id J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i✝ : Y ⟶ Z H✝ : IsPushout f g h i✝ H : IsVanKampenColimit (PushoutCocone.mk h i✝ (_ : f ≫ h = g ≫ i✝)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i✝ w : CommSq f' g' h' i' i : WalkingSpan ⊢ IsPullback (𝟙 ((span f' g').obj i)) (Option.rec αW (fun val => WalkingPair.rec αX αY val) i) (Option.rec αW (fun val => WalkingPair.rec αX αY val) i) (𝟙 ((span f g).obj i)) State After: no goals Tactic: exact IsPullback.of_horiz_isIso ⟨by rw [Category.comp_id, Category.id_comp]⟩ State Before: J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i✝ : Y ⟶ Z H✝ : IsPushout f g h i✝ H : IsVanKampenColimit (PushoutCocone.mk h i✝ (_ : f ≫ h = g ≫ i✝)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i✝ w : CommSq f' g' h' i' i : WalkingSpan ⊢ 𝟙 ((span f' g').obj i) ≫ Option.rec αW (fun val => WalkingPair.rec αX αY val) i = Option.rec αW (fun val => WalkingPair.rec αX αY val) i ≫ 𝟙 ((span f g).obj i) State After: no goals Tactic: rw [Category.comp_id, Category.id_comp] State Before: case mpr.refine'_5 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ (∀ (j : WalkingSpan), IsPullback ((CommSq.cocone w).ι.app j) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app j) αZ ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app j)) ↔ IsPullback h' αX αZ h ∧ IsPullback i' αY αZ i State After: case mpr.refine'_5.mp J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ (∀ (j : WalkingSpan), IsPullback ((CommSq.cocone w).ι.app j) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app j) αZ ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app j)) → IsPullback h' αX αZ h ∧ IsPullback i' αY αZ i case mpr.refine'_5.mpr J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ IsPullback h' αX αZ h ∧ IsPullback i' αY αZ i → ∀ (j : WalkingSpan), IsPullback ((CommSq.cocone w).ι.app j) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app j) αZ ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app j) Tactic: constructor State Before: case mpr.refine'_5.mp J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ (∀ (j : WalkingSpan), IsPullback ((CommSq.cocone w).ι.app j) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app j) αZ ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app j)) → IsPullback h' αX αZ h ∧ IsPullback i' αY αZ i State After: case mpr.refine'_5.mp J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h✝ : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h✝ i H : IsVanKampenColimit (PushoutCocone.mk h✝ i (_ : f ≫ h✝ = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h✝ hi : CommSq i' αY αZ i w : CommSq f' g' h' i' h : ∀ (j : WalkingSpan), IsPullback ((CommSq.cocone w).ι.app j) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app j) αZ ((PushoutCocone.mk h✝ i (_ : f ≫ h✝ = g ≫ i)).ι.app j) ⊢ IsPullback h' αX αZ h✝ ∧ IsPullback i' αY αZ i Tactic: intro h State Before: case mpr.refine'_5.mp J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h✝ : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h✝ i H : IsVanKampenColimit (PushoutCocone.mk h✝ i (_ : f ≫ h✝ = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h✝ hi : CommSq i' αY αZ i w : CommSq f' g' h' i' h : ∀ (j : WalkingSpan), IsPullback ((CommSq.cocone w).ι.app j) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app j) αZ ((PushoutCocone.mk h✝ i (_ : f ≫ h✝ = g ≫ i)).ι.app j) ⊢ IsPullback h' αX αZ h✝ ∧ IsPullback i' αY αZ i State After: no goals Tactic: exact ⟨h WalkingCospan.left, h WalkingCospan.right⟩ State Before: case mpr.refine'_5.mpr J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ IsPullback h' αX αZ h ∧ IsPullback i' αY αZ i → ∀ (j : WalkingSpan), IsPullback ((CommSq.cocone w).ι.app j) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app j) αZ ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app j) State After: case mpr.refine'_5.mpr.intro.none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' h₁ : IsPullback h' αX αZ h h₂ : IsPullback i' αY αZ i ⊢ IsPullback ((CommSq.cocone w).ι.app none) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app none) αZ ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app none) case mpr.refine'_5.mpr.intro.some.left J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' h₁ : IsPullback h' αX αZ h h₂ : IsPullback i' αY αZ i ⊢ IsPullback ((CommSq.cocone w).ι.app (some WalkingPair.left)) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app (some WalkingPair.left)) αZ ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app (some WalkingPair.left)) case mpr.refine'_5.mpr.intro.some.right J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' h₁ : IsPullback h' αX αZ h h₂ : IsPullback i' αY αZ i ⊢ IsPullback ((CommSq.cocone w).ι.app (some WalkingPair.right)) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app (some WalkingPair.right)) αZ ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app (some WalkingPair.right)) Tactic: rintro ⟨h₁, h₂⟩ (_ | _ | _) State Before: case mpr.refine'_5.mpr.intro.some.left J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' h₁ : IsPullback h' αX αZ h h₂ : IsPullback i' αY αZ i ⊢ IsPullback ((CommSq.cocone w).ι.app (some WalkingPair.left)) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app (some WalkingPair.left)) αZ ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app (some WalkingPair.left)) case mpr.refine'_5.mpr.intro.some.right J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' h₁ : IsPullback h' αX αZ h h₂ : IsPullback i' αY αZ i ⊢ IsPullback ((CommSq.cocone w).ι.app (some WalkingPair.right)) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app (some WalkingPair.right)) αZ ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app (some WalkingPair.right)) State After: no goals Tactic: exacts [h₁, h₂] State Before: case mpr.refine'_5.mpr.intro.none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' h₁ : IsPullback h' αX αZ h h₂ : IsPullback i' αY αZ i ⊢ IsPullback ((CommSq.cocone w).ι.app none) ((NatTrans.mk fun X_1 => Option.casesOn X_1 αW fun val => WalkingPair.casesOn val αX αY).app none) αZ ((PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)).ι.app none) State After: case mpr.refine'_5.mpr.intro.none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' h₁ : IsPullback h' αX αZ h h₂ : IsPullback i' αY αZ i ⊢ IsPullback ((CommSq.cocone w).ι.app none) αW αZ (f ≫ h) Tactic: dsimp State Before: case mpr.refine'_5.mpr.intro.none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' h₁ : IsPullback h' αX αZ h h₂ : IsPullback i' αY αZ i ⊢ IsPullback ((CommSq.cocone w).ι.app none) αW αZ (f ≫ h) State After: case mpr.refine'_5.mpr.intro.none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' h₁ : IsPullback h' αX αZ h h₂ : IsPullback i' αY αZ i ⊢ IsPullback (f' ≫ PushoutCocone.inl (CommSq.cocone w)) αW αZ (f ≫ h) Tactic: rw [PushoutCocone.condition_zero] State Before: case mpr.refine'_5.mpr.intro.none J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' h₁ : IsPullback h' αX αZ h h₂ : IsPullback i' αY αZ i ⊢ IsPullback (f' ≫ PushoutCocone.inl (CommSq.cocone w)) αW αZ (f ≫ h) State After: no goals Tactic: exact hf.paste_horiz h₁ State Before: case mpr.refine'_1 J : Type v' inst✝¹ : Category J C : Type u inst✝ : Category C W X Y Z : C f : W ⟶ X g : W ⟶ Y h : X ⟶ Z i : Y ⟶ Z H✝ : IsPushout f g h i H : IsVanKampenColimit (PushoutCocone.mk h i (_ : f ≫ h = g ≫ i)) W' X' Y' Z' : C f' : W' ⟶ X' g' : W' ⟶ Y' h' : X' ⟶ Z' i' : Y' ⟶ Z' αW : W' ⟶ W αX : X' ⟶ X αY : Y' ⟶ Y αZ : Z' ⟶ Z hf : IsPullback f' αW αX f hg : IsPullback g' αW αY g hh : CommSq h' αX αZ h hi : CommSq i' αY αZ i w : CommSq f' g' h' i' ⊢ IsPushout f' g' h' i' ↔ Nonempty (IsColimit (CommSq.cocone w)) State After: no goals Tactic: exact ⟨fun h => h.2, fun h => ⟨w, h⟩⟩
! ! Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. ! ! 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. ! ! C1413 (R1416) If a submodule-name appears in the end-submodule-stmt, it shall ! be identical to the one in the submodule-stmt. ! C1412 (R1418) The ancestor-module-name shall be the name of a nonintrinsic ! module that declares a separate module procedure; the parent-submodule-name ! shall be the name of a descendant of that module. ! C1411 (R1416) A submodule specification-part shall not contain a format-stmt !C1412 ancestor-module is nonintrinsic, declares a module procedure module ancestor interface module subroutine hello end subroutine module subroutine hello2 end subroutine end interface end module ancestor ! C1411 - submodule specification-part does not contain a format-stmt ! C1413 - test that matching submodule-name is accepted submodule (ancestor) descendant contains module procedure hello ! print *, "hello world" write(*,"(a)",advance="no")" PA" end procedure end submodule descendant ! C1411 - submodule specification-part does not contain a format-stmt ! C1412 - parent-submodule-name (descendant) is a descendant of ancestor ! C1413 - test that end-submodule-stmt without submodule-name is accepted submodule (ancestor:descendant) descendant2 contains module procedure hello2 write(*,"(a)",advance="no") "SS " print *, "" ! print *, "hello again, world" end procedure end submodule program main use ancestor call hello call hello2 end program main
[STATEMENT] lemma of_rat_lec_zero: "of_rat_lec 0 = 0" [PROOF STATE] proof (prove) goal (1 subgoal): 1. of_rat_lec 0 = 0 [PROOF STEP] unfolding zero_le_constraint_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. of_rat_lec (Le_Constraint Leq_Rel 0 0) = Le_Constraint Leq_Rel 0 0 [PROOF STEP] by simp
#! /usr/bin/env python # encoding: utf-8 import click import numpy as np from .download_input import get_input # @refactor: Both solution functions could be easily put into one def solve_captcha_puzzle_1(captcha): # @documentation: All or parts of the documentation is missing! if isinstance(captcha, str): captcha = list(captcha) if len(captcha) == 0: return 0 cap = np.asarray(captcha, dtype=int) mask = cap == np.roll(cap, 1) selection = cap[mask] return np.sum(selection) def solve_captcha_puzzle_2(captcha): # @documentation: All or parts of the documentation is missing! if isinstance(captcha, str): captcha = list(captcha) if len(captcha) == 0: return 0 cap = np.asarray(captcha, dtype=int) mask = cap == np.roll(cap, np.floor_divide(cap.size, 2)) selection = cap[mask] return np.sum(selection) @click.command() def main(): test_input_puzzle_1 = get_input(1) print(f"Solution for test input: {solve_captcha_puzzle_1(test_input_puzzle_1)}") test_input_puzzle_2 = get_input(1) print(f"Solution for test input: {solve_captcha_puzzle_2(test_input_puzzle_2)}") if __name__ == '__main__': main()
\<^marker>\<open>creator "Alexander Krauss"\<close> \<^marker>\<open>creator "Josh Chen"\<close> \<^marker>\<open>creator "Kevin Kappelmann"\<close> section \<open>Soft-Types for Sets\<close> theory Sets imports Soft_Types.Soft_Types_HOL HOTG.Pairs begin subsection \<open>Sets, Elements, and Subsets\<close> abbreviation Set :: "set type" where "Set \<equiv> Any" definition Element :: "set \<Rightarrow> set type" where [typedef]: "Element A \<equiv> type (\<lambda>x. x \<in> A)" lemma Element_covariant: "a : Element A \<Longrightarrow> A \<subseteq> B \<Longrightarrow> a : Element B" by unfold_types auto definition Subset :: "set \<Rightarrow> set type" where [typedef, type_simp]: "Subset A \<equiv> Element (powerset A)" lemma Subset_covariant: "a : Subset A \<Longrightarrow> A \<subseteq> B \<Longrightarrow> a : Subset B" by unfold_types auto lemma mem_iff_Element: "a \<in> A \<longleftrightarrow> a : Element A" by unfold_types corollary ElementI: "a \<in> A \<Longrightarrow> a : Element A" and ElementD: "a : Element A \<Longrightarrow> a \<in> A" by (auto iff: mem_iff_Element) lemma Subset_iff: "A \<subseteq> B \<longleftrightarrow> A : Subset B" by unfold_types auto corollary SubsetI: "A \<subseteq> B \<Longrightarrow> A : Subset B" and SubsetD: "A : Subset B \<Longrightarrow> A \<subseteq> B" by (auto iff: Subset_iff) lemma subset_self [derive]: "A : Subset A" by unfold_types auto text \<open>Declare basic soft type translations.\<close> (*Note: soft type translations go on the right of the "\<rightleftharpoons>". This should either be documented, or else made unnecessary.*) soft_type_translation "a \<in> A" \<rightleftharpoons> "a : Element A" by unfold_types soft_type_translation "A \<subseteq> B" \<rightleftharpoons> "A : Subset B" by unfold_types auto soft_type_translation "\<forall>x \<in> A. P x" \<rightleftharpoons> "\<forall>x : Element A. P x" by unfold_types auto soft_type_translation "\<exists>x \<in> A. P x" \<rightleftharpoons> "\<exists>x : Element A. P x" by unfold_types auto (* Note Kevin: Think about removing collections all together? *) subsection \<open>Collections\<close> definition Collection :: "set type \<Rightarrow> set type" where [typedef]: "Collection T \<equiv> type (\<lambda>x. \<forall>y \<in> x. y : T)" lemma CollectionI: "(\<And>x. x \<in> C \<Longrightarrow> x : T) \<Longrightarrow> C : Collection T" by unfold_types auto lemma Collection_memD: "C : Collection T \<Longrightarrow> x \<in> C \<Longrightarrow> x : T" by unfold_types auto lemma Collection_covariant: assumes "C : Collection T" and "\<And>x. x : T \<Longrightarrow> x \<in> C \<Longrightarrow> x : T'" shows "C : Collection T'" using assms by (intro CollectionI) (auto dest: Collection_memD) lemma Collection_covariant': assumes "C : Collection T" and "\<And>x. x : T \<Longrightarrow> x : T'" shows "C : Collection T'" using assms Collection_covariant by auto lemma Subset_if_Collecten_Element [derive]: "A : Collection (Element B) \<Longrightarrow> A : Subset B" by unfold_types blast lemma Collection_Element_if_Subset: "A : Subset B \<Longrightarrow> A : Collection (Element B)" by unfold_types blast subsection \<open>Basic Constant Types\<close> text \<open> The following typing rules are less general than what could be proved, since the \<^term>\<open>Bool\<close> soft type is trivial. But the rules also determine the behavior of type inference. The rule for \<^term>\<open>HOL.All\<close> currently needs to be restricted due to a deficiency in the elaboration algorithm. \<close> lemma [type]: "(\<in>) : (Element A) \<Rightarrow> (Subset A) \<Rightarrow> Bool" and [type]: "powerset : Collection T \<Rightarrow> Collection (Collection T)" and [type]: "union : Collection (Collection T) \<Rightarrow> Collection T" and [type]: "repl : Collection T \<Rightarrow> (T \<Rightarrow> S) \<Rightarrow> Collection S" and [type]: "HOL.All : ((T :: set type) \<Rightarrow> Bool) \<Rightarrow> Bool" and [type]: "{} : Subset A" and [type]: "(\<subseteq>) : Subset A \<Rightarrow> Subset A \<Rightarrow> Bool" and [type]: "insert : Element A \<Rightarrow> Subset A \<Rightarrow> Subset A" and [type]: "(\<union>) : Subset A \<Rightarrow> Subset A \<Rightarrow> Subset A" and [type]: "(\<inter>) : Subset A \<Rightarrow> Subset A \<Rightarrow> Subset A" and [type]: "collect : Subset A \<Rightarrow> (Element A \<Rightarrow> Bool) \<Rightarrow> Subset A" and [type]: "(\<times>) : Subset A \<Rightarrow> Subset B \<Rightarrow> Subset (A \<times> B)" by unfold_types auto end
module Data.OrderedVect import Decidable.Order %default total mutual public export data OrderedVect : Nat -> (constraint : Ordered ty to) -> Type where Nil : .{auto constraint : Ordered ty to} -> OrderedVect Z constraint (::) : .{constraint : Ordered ty to} -> (x : ty) -> (v : OrderedVect n constraint) -> .{auto prf : Fits x v} -> OrderedVect (S n) constraint public export Fits : {constraint : Ordered ty to} -> ty -> OrderedVect n constraint -> Type Fits _ Nil = () Fits n (m :: _) = to n m %name OrderedVect xs,ys,zs export head : .{constraint : Ordered ty to} -> OrderedVect (S _) constraint -> ty head (x :: _) = x fitsTrans : (Fits {constraint} x ys) -> Fits {constraint} (head ys) zs -> Fits {constraint} x zs fitsTrans {zs = []} _ _ = () fitsTrans {x} {ys = y' :: _} {zs = z' :: _} rel1 rel2 = transitive x y' z' rel1 rel2 mutual merge' : .{constraint : Ordered ty to} -> {n : Nat} -> (v1 : OrderedVect (S n) constraint) -> {m : Nat} -> (v2 : OrderedVect (S m) constraint) -> (ret : OrderedVect ((S n) + (S m)) constraint ** Either (Fits (head v1) ret) (Fits (head v2) ret)) merge' [] _ impossible merge' _ [] impossible merge' {to} [x] [y] = case order {to} x y of Left prf => ([x, y] ** Left (reflexive x)) Right prf => ([y, x] ** Right (reflexive y)) merge' {m} [x] (y :: ys) = rewrite sym $ plusZeroRightNeutral m in rewrite plusSuccRightSucc m Z in case assert_total $ merge' (y :: ys) [x] of (ref ** Left prf) => (ref ** Right prf) (ref ** Right prf) => (ref ** Left prf) merge' {n = S cntX} (x :: xs) [y] = case order {to} x y of Left prf => case mergeHelper xs [y] x of (zs ** fitsPrf) => (zs ** Left fitsPrf) Right prf => rewrite sym $ plusSuccRightSucc cntX Z in rewrite plusZeroRightNeutral cntX in ((y :: x :: xs) ** Right (reflexive y)) merge' ((::) {n = S cntX} x (x' :: xs')) ((::) {n = S cntY} y (y' :: ys')) = case order {to} x y of Left prf => case mergeHelper (x' :: xs') (y :: y' :: ys') x of (zs ** fitsPrf) => (zs ** Left fitsPrf) Right prf => case mergeHelper (y' :: ys') (x :: x' :: xs') y of (zs ** fitsPrf) => rewrite plusCommutative cntX (S $ S $ cntY) in rewrite plusSuccRightSucc (S $ S cntY) cntX in rewrite plusSuccRightSucc (S cntY) (S cntX) in (zs ** Right fitsPrf) mergeHelper : .{constraint : Ordered ty to} -> {n : Nat} -> (xs : OrderedVect (S n) constraint) -> {m : Nat} -> (ys : OrderedVect (S m) constraint) -> (x : ty) -> .{auto prfXs : Fits x xs} -> .{auto prfYs : Fits x ys} -> (ret : OrderedVect (S $ (S n) + (S m)) constraint ** Fits x ret) mergeHelper xs ys x {prfXs} {prfYs} = case assert_total $ merge' xs ys of (zs ** Left fitsPrf) => let _ = fitsTrans prfXs fitsPrf in (x :: zs ** reflexive x) (zs ** Right fitsPrf) => let _ = fitsTrans prfYs fitsPrf in (x :: zs ** reflexive x) export merge : {constraint : Ordered ty to} -> (n : Nat) -> OrderedVect n constraint -> (m : Nat) -> OrderedVect m constraint -> OrderedVect (n + m) constraint merge Z [] Z [] = Nil merge n v1 Z [] = rewrite plusZeroRightNeutral n in v1 merge Z [] _ v2 = v2 merge (S _) v1 (S _) v2 = fst $ merge' v1 v2 export tail : OrderedVect (S n) constraint -> OrderedVect n constraint tail (_ :: v) = v export orderedVectToList : .{constraint : Ordered ty _} -> OrderedVect n constraint -> List ty orderedVectToList [] = [] orderedVectToList {n = S _} (x :: xs) = x :: (orderedVectToList xs)
[STATEMENT] lemma eval_length: "length [] = 0" "length (x # xs) = Suc (length xs)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. length [] = 0 &&& length (x # xs) = Suc (length xs) [PROOF STEP] by simp_all
module Data.ZZ.ZZModulo import Control.Algebra import Classes.Verified import Data.ZZ import Control.Algebra.NumericInstances import Data.Fin.FinOrdering import Data.Fin.Structural import Control.Algebra.ZZDivisors import Data.ZZ.ModuloVerification {- Table of contents * Modulo for naturals * Lemmas for applying (modNatFnIsRemainder) * Derived modulo for ZZ -} {- Modulo for naturals -} ||| A manually verifiably total modulo for naturals: ||| It recurses precisely when ||| ( Not (x `LT` m) ) & ( m, x > 0 ). ||| Not (x `LT` m) -> Either (x = m) (m `LT` x), ||| in former case ((x `minus` m) `modNat` m) is defined, ||| & latter case cannot hold indefinitely since ||| m > 0 ||| ==> ||| the iterates of (`minus` m) are decreasing. %reflection modNatT : Nat -> Nat -> Nat modNatT Z _ = Z modNatT x Z = x modNatT (S predx) (S predm) with (decLT (S predx) (S predm)) | No notlt = ((S predx) `minus` (S predm)) `modNatT` (S predm) | Yes prlt = S predx {- Lemmas for applying (modNatFnIsRemainder) -} total modNatTIdModZero : (x : Nat) -> x `modNatT` Z = x modNatTIdModZero Z = Refl modNatTIdModZero (S predx) = Refl -- The LT implies subtracting m is reversible total modNatTCharizLT : (x, m : Nat) -> (x `LT` m) -> x `modNatT` m = x modNatTCharizLT Z _ _ = Refl modNatTCharizLT x Z ltpr = void $ succNotLTEzero ltpr modNatTCharizLT (S predx) (S predm) ltpr with (decLT (S predx) (S predm)) | No notlt = void $ notlt ltpr | Yes prlt = Refl total modNatTCharizEq : (m : Nat) -> m `modNatT` m = Z modNatTCharizEq Z = Refl modNatTCharizEq (S predm) with (decLT (S predm) (S predm)) | No notlt = rewrite sym $ minusZeroN predm in Refl | Yes prlt = void $ notLTSelf prlt total modNatTCharizGTE : (x, m : Nat) -> (m `plus` x) `modNatT` m = x `modNatT` m modNatTCharizGTE Z m = trans (rewrite plusZeroRightNeutral m in Refl) $ modNatTCharizEq m modNatTCharizGTE x Z = Refl modNatTCharizGTE (S predx) (S predm) with (decLT (S predm `plus` S predx) (S predm)) | No notlt = rewrite natPlusInvertibleL (S predx) predm in Refl | Yes prlt = void $ notLTSelf $ lteUnsumLeftSummandLeft {y=S predx} prlt total modNatTIsRemainder : (x, m : Nat) -> (d : Nat ** (d `mult` m) `plus` (x `modNatT` m) = x) modNatTIsRemainder = modNatFnIsRemainder modNatT modNatTIdModZero modNatTCharizLT modNatTCharizGTE {- -- Totally superfluous modNatTCharizSucc : (x, m : Nat) -> S x `modNatT` m = (S $ x `modNatT` m) `modNatT` m modNatTCharizSucc Z _ = ?modNatTCharizSucc_rhs_1 modNatTCharizSucc (S predx) m = ?modNatTCharizSucc_rhs_2 -} {- Derived modulo for ZZ -} total modZT : ZZ -> ZZ -> ZZ modZT = modZGenFn modNatT modNatTIsRemainder quotientPartModZT : (x, m : ZZ) -> (x <-> (x `modZT` m)) `quotientOverZZ` m quotientPartModZT = modZGenQuot modNatT modNatTIsRemainder
postulate A : Set f : (B : Set) → B → A f A a = a -- Expected error: -- A !=< A of type Set -- (because one is a variable and one a defined identifier) -- when checking that the expression a has type A
I'm a lover of nature, specially I love mountain landscapes. Would France been good to live and work in? I would travel alone and my stay would be indefinite. Hi, It's pretty difficult to get a working visa for France but if you can get one, it's a good place to live and work. Beautiful landscapes, and historical monument to visit, everything is full of history, more than 2000 years of history to endurstand, Paris was created 58BC. Some country services will be picked up directly from your salary, like health insurance, retirement allocations, unemployed allocation, familly allocation etc. If you negociate a salary of 40k€/year (called brut salary) you will really have in your pocket 30k€/year (called net salary). You have to know that every salary is negociate as "brut" salary. You will have to had on the previous taxes salary taxes wich correspond to one salary per year so it's gonna be 30k€ / 12. Then you will have a job in France congrat. If you want moutain and live cheap, you can try to get a job in Pau You have to know that if you want to get a working visa, it can be easier to get it in a company based in Paris. After almost two years living in US, I feel like France is a way better because of health insurance and you do not need a car to go everywhere but that's my personal opinion. I hope all those infos helped you. I lived in Dijon for a while and loved it. Because Paris is such a monster city in size, we tend to not realize that the other cities in France are quite large too. Lyon, Dijon, Orleans (Centre), Lille, Nantes are all truly lovely cities-full of culture, wonderful people and great food...and surrounded by beautiful landscapes. I would be happy to live in any of them! Getting a work permit will prove difficult, as well as getting a job. The social taxes are astronomic, so most employers are not hiring right now. France is a great place to work, IF you can secure a job. And for this, you will need a work permit. Unless you have a EU passport, or come from North Africa, this is not easy.
#include <boost/hana/cartesian_product.hpp>
[STATEMENT] lemma Hausdorff_space_subtopology: assumes "Hausdorff_space X" shows "Hausdorff_space(subtopology X S)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Hausdorff_space (subtopology X S) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. Hausdorff_space (subtopology X S) [PROOF STEP] have *: "disjnt U V \<Longrightarrow> disjnt (S \<inter> U) (S \<inter> V)" for U V [PROOF STATE] proof (prove) goal (1 subgoal): 1. disjnt U V \<Longrightarrow> disjnt (S \<inter> U) (S \<inter> V) [PROOF STEP] by (simp add: disjnt_iff) [PROOF STATE] proof (state) this: disjnt ?U ?V \<Longrightarrow> disjnt (S \<inter> ?U) (S \<inter> ?V) goal (1 subgoal): 1. Hausdorff_space (subtopology X S) [PROOF STEP] from assms [PROOF STATE] proof (chain) picking this: Hausdorff_space X [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: Hausdorff_space X goal (1 subgoal): 1. Hausdorff_space (subtopology X S) [PROOF STEP] apply (simp add: Hausdorff_space_def openin_subtopology_alt) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<forall>x y. x \<in> topspace X \<and> y \<in> topspace X \<and> x \<noteq> y \<longrightarrow> (\<exists>U. openin X U \<and> (\<exists>V. openin X V \<and> x \<in> U \<and> y \<in> V \<and> disjnt U V)) \<Longrightarrow> \<forall>x y. x \<in> topspace X \<and> x \<in> S \<and> y \<in> topspace X \<and> y \<in> S \<and> x \<noteq> y \<longrightarrow> (\<exists>U. openin X U \<and> x \<in> U \<and> (\<exists>V. openin X V \<and> y \<in> V \<and> disjnt (S \<inter> U) (S \<inter> V))) [PROOF STEP] apply (fast intro: * elim!: all_forward) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done [PROOF STATE] proof (state) this: Hausdorff_space (subtopology X S) goal: No subgoals! [PROOF STEP] qed
lemma holomorphic_on_id [simp, holomorphic_intros]: "id holomorphic_on s"
Autodesk Animator files explanation (.FLI only excerpted). I believe that the original programmer wrote up this doc. It's correct, as I've used the info to realtime playback stock .FLIs on a 680x0 machine. All numbers in a .FLI file are in Intel format, so you may have to compensate for that, of course. - kevin 8.1 Flic Files (.FLI) The details of a FLI file are moderately complex, but the idea behind it is simple: don't bother storing the parts of a frame that are the same as the last frame. Not only does this save space, but it's very quick. It's faster to leave a pixel alone than to set it. A FLI file has a 128-byte header followed by a sequence of frames. The first frame is compressed using a bytewise run-length compression scheme. Subsequent frames are stored as the difference from the previous frame. (Occasionally the first frame and/or subsequent frames are uncompressed.) There is one extra frame at the end of a FLI which contains the difference between the last frame and the first frame. The FLI header: byte size name meaning offset 0 4 size Length of file, for programs that want to read the FLI all at once if possible. 4 2 magic Set to hex AF11. Please use another value here if you change format (even to a different resolution) so Autodesk Animator won't crash trying to read it. 6 2 frames Number of frames in FLI. FLI files have a maxium length of 4000 frames. 8 2 width Screen width (320). 10 2 height Screen height (200). 12 14 2 flags Must be 0. 16 2 speed Number of video ticks between frames. 18 4 next Set to 0. 22 4 frit Set to 0. 26 102 expand All zeroes -- for future enhancement. Next are the frames, each of which has a header: byte size name meaning offset 0 4 size Bytes in this frame. Autodesk Animator demands that this be less than 64K. 4 2 magic Always hexadecimal F1FA 6 2 chunks Number of 'chunks' in frame. 8 8 expand Space for future enhancements. All zeros. After the frame header come the chunks that make up the frame. First comes a color chunk if the color map has changed from the last frame. Then comes a pixel chunk if the pixels have changed. If the frame is absolutely identical to the last frame there will be no chunks at all. A chunk itself has a header, followed by the data. The chunk header is: byte size name meaning offset 0 4 size Bytes in this chunk. 4 2 type Type of chunk (see below). There are currently five types of chunks you'll see in a FLI file: number name meaning 11 FLI_COLOR Compressed color map 12 FLI_LC Line compressed -- the most common type of compression for any but the first frame. Describes the pixel difference from the previous frame. 13 FLI_BLACK Set whole screen to color 0 (only occurs on the first frame). 15 FLI_BRUN Bytewise run-length compression -- first frame only 16 FLI_COPY Indicates uncompressed 64000 bytes soon to follow. For those times when compression just doesn't work! The compression schemes are all byte-oriented. If the compressed data ends up being an odd length a single pad byte is inserted so that the FLI_COPY's always start at an even address for faster DMA. FLI_COLOR Chunks The first word is the number of packets in this chunk. This is followed directly by the packets. The first byte of a packet says how many colors to skip. The next byte says how many colors to change. If this byte is zero it is interpreted to mean 256. Next follows 3 bytes for each color to change (one each for red, green and blue). FLI_LC Chunks This is the most common, and alas, most complex chunk. The first word (16 bits) is the number of lines starting from the top of the screen that are the same as the previous frame. (For example, if there is motion only on the bottom line of screen you'd have a 199 here.) The next word is the number of lines that do change. Next there is the data for the changing lines themselves. Each line is compressed individually; among other things this makes it much easier to play back the FLI at a reduced size. The first byte of a compressed line is the number of packets in this line. If the line is unchanged from the last frame this is zero. The format of an individual packet is: skip_count size_count data The skip count is a single byte. If more than 255 pixels are to be skipped it must be broken into 2 packets. The size count is also a byte. If it is positive, that many bytes of data follow and are to be copied to the screen. If it's negative a single byte follows, and is repeated -skip_count times. In the worst case a FLI_LC frame can be about 70K. If it comes out to be 60000 bytes or more Autodesk Animator decides compression isn't worthwhile and saves the frame as FLI_COPY. FLI_BLACK Chunks These are very simple. There is no data associated with them at all. In fact they are only generated for the first frame in Autodesk Animator after the user selects NEW under the FLIC menu. FLI_BRUN Chunks These are much like FLI_LC chunks without the skips. They start immediately with the data for the first line, and go line- by-line from there. The first byte contains the number of packets in that line. The format for a packet is: size_count data If size_count is positive the data consists of a single byte which is repeated size_count times. If size_count is negative there are -size_count bytes of data which are copied to the screen. In Autodesk Animator if the "compressed" data shows signs of exceeding 60000 bytes the frame is stored as FLI_COPY instead. FLI_COPY Chunks These are 64000 bytes of data for direct reading onto the screen. -eof- Notes: Since these are animations, the last frame will delta into a copy of the first one (which was usually a large BRUN chunk). Therefore, looping should go back to the _second_ frame chunk (usually a LC or COLOR chunk) instead of all the way back to the file beginning, to avoid a "stutter" caused by unnecessarily redecoding the original frame. Also, a very few files may have palette animation, so write your code so that COLOR chunks can be found at any time. - kevin
\section{Introduction} System safety analysis techniques are well established and are a required activity in the development of commercial aircraft and safety-critical ground systems. However, these techniques are based on informal system descriptions that are separate from the actual system design artifacts, and are highly dependent on the skill and intuition of a safety analyst. The lack of precise models of the system architecture and its failure modes often forces safety analysts to devote significant effort to gathering architectural details about the system behavior from multiple sources and embedding this information in safety artifacts, such as fault trees. While model-based development (MBD) methods are widely used in the aerospace industry, they are generally disconnected from the safety analysis process itself. Formal model-based systems engineering (MBSE) methods and tools now permit system-level requirements to be specified and analyzed early in the development process~\cite{QFCS15:backes,hilt2013,NFM2012:CoGaMiWhLaLu,DBLP:journals/scp/CimattiT15,Pajic2012,DBLP:conf/adaEurope/SokolskyLC09}. These tools can also be used to perform safety analysis based on the system architecture and initial functional decomposition. Design models from which aircraft systems are developed can be integrated into the safety analysis process to help guarantee accurate and consistent results. This integration is especially important as the amount of safety-critical hardware and software in domains such as aerospace, automotive, and medical devices has dramatically increased due to desire for greater autonomy, capability, and connectedness. Architecture description languages, such as SysML~\cite{SysML} and the Architecture Analysis and Design Language (AADL)~\cite{AADL} are appropriate for capturing system safety information. There are several tools that currently support reasoning about faults in architecture description languages, such as the AADL error annex~\cite{Larson:2013:IAE:2527269.2527271} and HiP-HOPS for EAST-ADL~\cite{CHEN201391}. However, these approaches primarily use {\em qualitative} reasoning, in which faults are enumerated and their propagations through system components must be explicitly described. Given many possible faults, these propagation relationships become complex and it is also difficult to describe temporal properties of faults that evolve over time (e.g., leaky valve or slow divergence of sensor values). This is likewise the case with tools like SAML that incorporate both \textit{qualitative} and \textit{quantitative} reasoning \cite{Gudemann:2010:FQQ:1909626.1909813}. Due to the complexity of propagation relationships, interactions may also be overlooked by the analyst and thus may not be explicitly described within the fault model. In earlier work, University of Minnesota and Rockwell Collins developed and demonstrated an approach to model-based safety analysis (MBSA) \cite {Joshi05:Dasc,Joshi05:SafeComp,NasaRep:MBSA-Aug05} using the Simulink notation \cite{MathWorks}. In this approach, a behavioral model of (sometimes simplified) system dynamics was used to reason about the effect of faults. We believe that this approach allows a natural and implicit notion of fault propagation through the changes in pressure, mode, etc. that describe the system's behavior. Unlike qualitative approaches, this approach allows uniform reasoning about system functionality and failure behavior, and can describe complex temporal fault behaviors. On the other hand, Simulink is not an architecture description language, and several system engineering aspects, such as hardware devices and non-functional aspects cannot be easily captured in models. \iffalse Over the last five years, several research groups have focused on formal reasoning at the system architecture level, resulting in MBSE tools that incorporate assume-guarantee compositional reasoning techniques~\cite{Trento and Rockwell and UMN}. These tools allow behavioral reasoning about complex system models, but with substantially greater scalability than previous approaches. \fi This paper describes our initial work towards a behavioral approach to MBSA using AADL. Using assume-guarantee compositional reasoning techniques, we hope to support system safety objectives of ARP4754A and ARP4761. To make these capabilities accessible to practicing safety engineers, it is necessary to extend modeling notations to better describe failure conditions, interactions, and mitigations, and provide improvements to compositional reasoning approaches focused on the specific needs of system safety analysis. These extensions involve creating models of fault effects and weaving them into the analysis process. To a large extent, our work has been an adaptation of the work of Joshi et. al in \cite {Joshi05:Dasc,Joshi05:SafeComp,NasaRep:MBSA-Aug05} to the AADL modeling language. \iffalse This paper describes our initial work towards a behavioral approach to MBSA using AADL. In previous work we have extended the AADL language to add formal assume-guarantee contracts to specify behavioral requirements and compositional reasoning about system behavior. Compared to the existing AADL Error Model Annex, these contracts provide a better, more natural, and more effective way to describe fault propagation and system behavior in the presence of failures. To make these capabilities accessible to practicing safety engineers, it is necessary to extend modeling notations to better describe failure conditions, interactions, and mitigations, and provide improvements to compositional reasoning approaches focused on the specific needs of system safety analysis. These extensions involve creating models of fault effects and weaving them into the analysis process. To a large extent, our work has been an adaptation of the work of Joshi et. al to the AADL modeling language. \fi To evaluate the effectiveness and practicality of our approach, we developed an architectural model of the Wheel Braking System model in SAE AIR6110. Starting from a reference AADL model constructed by the SEI instrumented with qualitative safety analysis information~\cite{SEI:AADL}, we added behavioral contracts to the model. In so doing, we determine that there are errors related to (manually constructed) propagations across components, and also an architecture that contains single points of failure. We use our analyses to find these errors.
Robert A. Kloner, MD, Ph.D., is Chief Science Officer and Director of Cardiovascular Research at Huntington Medical Research Institutes (HMRI). He serves as Professor of Medicine (Clinical Scholar) at Keck School of Medicine at the University of Southern California and is an attending cardiologist at LAC+USC. Prior to accepting an appointment at HMRI, Dr. Kloner served as Director of Research of the Heart Institute of Good Samaritan Hospital in Los Angeles from 1987 to December 2014. He has run nationally and internationally known cardiovascular research programs for over 40 years, training dozens of medical scientists and collaborating with scores of physician-scientists, numerous research institutions, and medical industries worldwide. During his administrative tenure at both Wayne State University and The Heart Institute of Good Samaritan Hospital, he built successful research facilities from the ground-up, creating centers recognized for scientific excellence and innovation. In the mid-1970s Dr. Kloner received his MD in the Honors Program in Medical Education and Ph.D. (Experimental Pathology) degrees from Northwestern University Medical School in Chicago where he trained in the laboratory of Dr. Robert Jennings. Dr. Kloner is a member of the Alpha Omega Alpha honor society. He completed internship and residency in internal medicine at Peter Bent Brigham Hospital and Harvard Medical School in Boston, Massachusetts (1975-1978). Additional training included clinical and research fellowships in medicine and cardiology (with Drs. Eugene Braunwald and Peter Maroko) at Harvard Medical School and Brigham and Women’s Hospital. He served as Assistant and then Associate Professor of Medicine at Harvard Medical School and was an attending cardiologist at Brigham and Women’s Hospital (1979-1984). He was the recipient of an Established Investigator Award of the American Heart Association (AHA), is a fellow of the American College of Cardiology, an Inaugural Fellow of the Council on Basic Cardiovascular Sciences of the AHA, and was elected to the American Society of Clinical Investigation. In 2015 he was elected a Fellow of the Cardiovascular Section of the American Physiology Society. Dr. Kloner has made major contributions to the understanding and treatment of heart disease, receiving funding from the National Institutes of Health (NIH), American Heart Association (AHA), Environmental Protection Agency (EPA), Department of Defense (DOD) and numerous corporations and private foundations. He has made major contributions in the following areas: the pathophysiology of heart attack; treatments for heart attack; triggers of cardiovascular events; studies on high blood pressure and heart failure; the effect of toxins like alcohol, cocaine, and pollution on the heart; stem cell therapy for the heart; the intersection between sexual dysfunction and cardiovascular disease. His current work at HMRI, funded by the DOD, assesses new therapies for hemorrhagic shock; additional current work funded by the NIH and Tobacco-Related Disease Research Program studies the effects of e-cigarettes on the cardiovascular system. Throughout his career, Dr. Kloner has participated in several large multi-center studies. This experience has enabled Dr. Kloner to actively facilitate cross-disciplinary research initiatives within HMRI, advising and collaborating with the bio-technology group (cell phone app for assessing heart function), neuro-science, stem cell biology, and imaging scientists. A frequent contributor to the medical and scientific press, Dr. Kloner has authored or co-authored over 720 original papers in peer-reviewed journals, 219 chapters or monographs, and 518 abstracts (as of 2019). Dr. Kloner is the author and editor of 18 medical texts including Cardiovascular Trials Reviews (10 editions); The Guide to Cardiology (3 editions); Stunned Myocardium; Ischemic Preconditioning; VIAGRA; and Heart Disease and Erectile Dysfunction. In addition, he has written and published three medical science fiction novels. Among his editorial responsibilities, Dr. Kloner served as editor-in-chief of the Journal of Cardiovascular Pharmacology and Therapeutics (2009-2019). He has served as Guest Editor of Circulation. He is on the editorial boards of American Journal of Cardiology, Basic Research in Cardiology, International Journal of Impotence Research, Journal of Cardiovascular Pharmacology and Therapeutics, Regenerative Medicine, and Life Sciences. Among his many career distinctions, Dr. Kloner has been listed in Who’s Who in America, The Best Doctors in America and in 2002 was cited by the Institute for Scientific Information as one of the most highly cited scientific authors. He has an H-index of 99 and is cited over 41,830 times as per the Web of Science. Dr. Kloner is a frequent lecturer at major scientific symposia including the Scientific Sessions of the American Heart Association, American College of Cardiology, and Transcatheter Cardiovascular Therapeutics Meetings, and he has lectured at most major academic medical centers in the United States. He has taught at both the Keck School of Medicine at USC and lectured at Caltech.
import field_definition import field_results import numbers import roots import quadratic lemma multiply_out_cubed (f : Type) [myfld f] (x a : f) : (cubed f (x .+ a)) = ((cubed f x) .+ (((three f) .* ((square f x) .* a)) .+ (((three f) .* ((x .* a) .* a)) .+ (cubed f a)))) := begin unfold cubed, unfold three, unfold square, repeat {rw distrib_simp f _ _ _}, repeat {rw distrib_simp_alt f _ _ _}, rw one_mul_simp f _, rw myfld.mul_assoc _ _ _, rw myfld.mul_comm a x, rw myfld.mul_assoc a x a, rw myfld.mul_comm a x, rw myfld.mul_assoc _ _ _, rw myfld.mul_assoc a x x, rw myfld.mul_comm a x, rw <- myfld.mul_assoc x a x, rw myfld.mul_comm a x, repeat {rw myfld.mul_assoc _ _ _}, repeat {rw <- myfld.add_assoc _ _ _}, rw myfld.add_assoc ((x .* a) .* a) ((x .* x) .* a) _, rw myfld.add_comm ((x .* a) .* a) ((x .* x) .* a), repeat {rw <- myfld.add_assoc _ _ _}, rw one_mul_simp f _, end def cardano_intermediate_val (f : Type) [myfld f] [fld_with_sqrt f] [fld_not_char_two f] [fld_not_char_three f] (c d : f) : f := sqroot (((square f d) .* (myfld.reciprocal (four f) (four_ne_zero f))) .+ ((cubed f c) .* (myfld.reciprocal (twenty_seven f) (twenty_seven_ne_zero f)))) def cardano_other_int_val (f : Type) [myfld f] [fld_not_char_two f] (d : f) : f := .- (d .* (myfld.reciprocal (two f) fld_not_char_two.not_char_two)) /- Prove that (if c ≠ 0) the fraction in the Cardano formula is a legal fraction. We do actually need a couple of versions of this for different purposes, so the formula is split over a few different lemmae.-/ lemma cardano_den_not_zero_general (f : Type) [myfld f] [fld_with_sqrt f] [fld_not_char_two f] [fld_not_char_three f] (c d : f) (c_ne_zero : c ≠ myfld.zero) : (square f (cardano_intermediate_val f c d)) .+ (.- (square f (cardano_other_int_val f d))) ≠ myfld.zero := begin intro h, unfold square at h, unfold cardano_other_int_val at h, unfold cardano_intermediate_val at h, rw fld_with_sqrt.sqrt_mul_sqrt _ at h, rw mul_negate f _ at h, rw <- mul_negate_alt f _ at h, rw double_negative f _ at h, rw <- myfld.mul_assoc d _ _ at h, rw myfld.mul_comm d (myfld.reciprocal (two f) _) at h, rw myfld.mul_assoc (myfld.reciprocal (two f) _) (myfld.reciprocal (two f) _) _ at h, rw mul_two_reciprocals f (two f) (two f) _ _ at h, rw myfld.mul_comm _ d at h, rw myfld.mul_assoc d d _ at h, unfold square at h, unfold four at h, rw reciprocal_rewrite f ((two f) .+ (two f)) ((two f) .* (two f)) (two_plus_two f) _ at h, rw myfld.add_comm (_ .* _) _ at h, rw <- myfld.add_assoc _ _ _ at h, rw only_one_reciprocal f ((two f) .* (two f)) _ (mul_nonzero f (two f) (two f) fld_not_char_two.not_char_two fld_not_char_two.not_char_two) at h, rw myfld.add_negate _ at h, rw zero_simp at h, have h1 : (cubed f c) ≠ myfld.zero, unfold cubed, exact mul_nonzero f c (c .* c) c_ne_zero (mul_nonzero f c c c_ne_zero c_ne_zero), exact (mul_nonzero f (cubed f c) (myfld.reciprocal (twenty_seven f) _) h1 (reciprocal_ne_zero f (twenty_seven f) _)) h, end lemma cardano_den_not_zero_int (f : Type) [myfld f] [fld_with_sqrt f] [fld_not_char_two f] [fld_not_char_three f] (c d : f) (c_ne_zero : c ≠ myfld.zero) : (cardano_intermediate_val f c d) .+ (cardano_other_int_val f d) ≠ myfld.zero := begin intro h, have h1 : (((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d)) .* ((cardano_intermediate_val f c d) .+ (.- (cardano_other_int_val f d)))) = myfld.zero, rw h, rw mul_zero f _, clear h, rename h1 h, rw difference_of_squares f _ _ at h, exact cardano_den_not_zero_general f c d c_ne_zero h, end lemma cardano_den_not_zero_int_alt (f : Type) [myfld f] [fld_with_sqrt f] [fld_not_char_two f] [fld_not_char_three f] (c d : f) (c_ne_zero : c ≠ myfld.zero) : (cardano_intermediate_val f c d) .+ (.- (cardano_other_int_val f d)) ≠ myfld.zero := begin intro h, have h1 : (((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d)) .* ((cardano_intermediate_val f c d) .+ (.- (cardano_other_int_val f d)))) = myfld.zero, rw h, rw zero_mul f _, clear h, rename h1 h, rw difference_of_squares f _ _ at h, exact cardano_den_not_zero_general f c d c_ne_zero h, end lemma cardano_denominator_not_zero (f : Type) [myfld f] [fld_with_sqrt f] [fld_not_char_two f] [fld_not_char_three f] [fld_with_cube_root f] (c d : f) (c_ne_zero : c ≠ myfld.zero) (cubrt_func : f -> f) (cubrt_func_nonzero : ∀ (x : f), x ≠ myfld.zero -> (cubrt_func x ≠ myfld.zero)) : (cubrt_func ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d))) .* (three f) ≠ myfld.zero := begin exact mul_nonzero f _ (three f) (cubrt_func_nonzero _ (cardano_den_not_zero_int f c d c_ne_zero)) fld_not_char_three.not_char_three, end /- This is the formula, finally. Note that we are intentionally vague about the cube root - any function that gives a cube root can be provided. This is so that we can easily create a proof that covers all three cube roots at the same time.-/ def cardano_formula (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d : f) (c_ne_zero : c ≠ myfld.zero) (cubrt_func : f -> f) (cubrt_func_nonzero : ∀ (x : f), x ≠ myfld.zero -> (cubrt_func x ≠ myfld.zero)) (cubrt_func_correct : ∀ (x : f), (cubed f (cubrt_func x)) = x) : f := ((cubrt_func ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d))) .+ (.- (c .* (myfld.reciprocal ((cubrt_func ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d))) .* (three f)) (cardano_denominator_not_zero f c d c_ne_zero cubrt_func cubrt_func_nonzero))))) def depressed_cubic_subst (f : Type) [myfld f] (c d x : f) : f := (cubed f x) .+ ((c .* x) .+ d) /- This is now the proof that all depressed cubics can be solved by the above formula. We're not doing uniqueness yet.-/ lemma cardano_works (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d : f) (c_ne_zero : c ≠ myfld.zero) (cubrt_func : f -> f) (cubrt_func_nonzero : ∀ (x : f), x ≠ myfld.zero -> (cubrt_func x ≠ myfld.zero)) (cubrt_func_correct : ∀ (x : f), (cubed f (cubrt_func x)) = x) : depressed_cubic_subst f c d (cardano_formula f c d c_ne_zero cubrt_func cubrt_func_nonzero cubrt_func_correct) = myfld.zero := begin /- First multiply out the brackets.-/ unfold depressed_cubic_subst, unfold cardano_formula, rw distrib_simp_alt f c _ _, rw multiply_out_cubed f _ _, unfold square, rw cubrt_func_correct _, rw cube_of_negative f _, simp only [mul_negate, mul_negate_alt_simp, double_negative], /- Now simplify two terms where we have 3 * 1/3.-/ rw split_reciprocal f _ (three f) _, rw myfld.mul_comm (myfld.reciprocal _ _) (myfld.reciprocal (three f) _), rw myfld.mul_assoc c (myfld.reciprocal (three f) _) _, rw myfld.mul_comm c (myfld.reciprocal (three f) _), rw myfld.mul_comm _ (((myfld.reciprocal (three f) _) .* c) .* (myfld.reciprocal _ _)), rw myfld.mul_comm _ (((myfld.reciprocal (three f) _) .* c) .* (myfld.reciprocal _ _)), repeat {rw myfld.mul_assoc _ _ _}, rw myfld.mul_reciprocal (three f) _, rw one_mul_simp f _, /- There are also some points where we have cubrt (stuff) * reciprocal (cubrt (stuff)) . So these also simplify.-/ rw <- myfld.mul_assoc c (myfld.reciprocal (cubrt_func _) _) (cubrt_func _), rw myfld.mul_comm (myfld.reciprocal (cubrt_func _) _) (cubrt_func _), rw myfld.mul_reciprocal _ _, rw simp_mul_one f _, /- We can now cancel some of the terms by moving them next to their negations. -/ rw myfld.add_comm (c .* _) (.- _), rw myfld.add_comm (((c .* _) .* c) .* _) (.- (cubed f _)), repeat {rw <- myfld.add_assoc _ _ _}, rw myfld.add_assoc (((c .* _) .* c) .* _) (.- _) _, rw myfld.add_negate _, rw simp_zero f _, rw myfld.add_comm (.- _) _, rw myfld.add_comm _ d, repeat {rw <- myfld.add_assoc _ _ _}, rw myfld.add_negate _, rw zero_simp f _, /- One of our remaining terms has two reciprocals multiplied together. Also, it is the cube of some stuff multiplied by a cube root, so we can remove the cube root from the expression.-/ rw myfld.mul_comm (myfld.reciprocal _ _) c, rw <- myfld.mul_assoc c (myfld.reciprocal _ _) (myfld.reciprocal _ _), repeat {rw cube_of_product f _ _}, rw cube_of_reciprocal f (cubrt_func _), rw reciprocal_rewrite f (cubed f (cubrt_func _)) _ (cubrt_func_correct _) _, rw cube_of_reciprocal f _, /- We now have the reciprocal of (cardano_intermediate_val + cardano_other_int_val) . cardano_intermediate_val is a square root, so in the interest of rationalising denominators we can multiply this by (int_val - other_int_val) / (int_val - other_int_val) . -/ rw only_one_reciprocal f ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d)) _ (cardano_den_not_zero_int f c d c_ne_zero), have tmp : (((cardano_intermediate_val f c d) .+ (.- (cardano_other_int_val f d))) .* (myfld.reciprocal ((cardano_intermediate_val f c d) .+ (.- (cardano_other_int_val f d))) (cardano_den_not_zero_int_alt f c d c_ne_zero))) = myfld.one, rw myfld.mul_reciprocal _ _, have tmp2 : (myfld.reciprocal ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d)) (cardano_den_not_zero_int f c d c_ne_zero)) = ((myfld.reciprocal ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d)) (cardano_den_not_zero_int f c d c_ne_zero)) .* myfld.one), exact myfld.mul_one _, rw <- tmp at tmp2, clear tmp, rename tmp2 tmp, rw myfld.mul_comm _ (myfld.reciprocal _ _) at tmp, rw myfld.mul_assoc (myfld.reciprocal _ _) (myfld.reciprocal _ _) _ at tmp, rw mul_two_reciprocals f _ _ _ _ at tmp, rw reciprocal_rewrite f _ _ (difference_of_squares f _ _) _ at tmp, rw tmp, clear tmp, /- Now that we've pre-rationalized the denominator, it's finally time to unfold these intermediate values.-/ unfold cardano_intermediate_val, unfold cardano_other_int_val, /- Our fraction now has an expression on the bottom that simplifies to p^3/27. Because reciprocals need to have a proof that the denominator isn't zero, it's easier to do this in a sub-proof so that the reciprocal only needs to be rewritten once.-/ have denominator_sub_proof : ((square f (sqroot (((square f d) .* (myfld.reciprocal (four f) _)) .+ ((cubed f c) .* (myfld.reciprocal (twenty_seven f) _))))) .+ (.- (square f (.- (d .* (myfld.reciprocal (two f) fld_not_char_two.not_char_two)))))) = ((cubed f c) .* (myfld.reciprocal (twenty_seven f) (twenty_seven_ne_zero f))), rw sqrt_squared f _, unfold square, rw mul_negate f _ _, rw double_negative f _, rw mul_negate_alt_simp f _ _, rw <- myfld.mul_assoc d (myfld.reciprocal _ _) (_ .* _), rw myfld.mul_comm d (myfld.reciprocal _ _), rw myfld.mul_assoc (myfld.reciprocal _ _) (myfld.reciprocal _ _) d, rw mul_two_reciprocals f (two f) (two f) _ _, rw myfld.mul_comm (myfld.reciprocal _ _) d, rw myfld.mul_assoc d d _, rw myfld.add_comm _ (.- _), rw myfld.add_assoc _ _ _, unfold four, rw reciprocal_rewrite f ((two f) .+ (two f)) ((two f) .* (two f)) (two_plus_two _) _, rw only_one_reciprocal f ((two f) .* (two f)) _ (mul_nonzero f (two f) (two f) fld_not_char_two.not_char_two fld_not_char_two.not_char_two), rw myfld.add_comm (.- _) _, rw myfld.add_negate _, rw simp_zero f _, /- And now we can do the rewrite in the main proof.-/ rw reciprocal_rewrite f _ _ denominator_sub_proof _, /- The big fraction is now reduced to p^3 (stuff) / (27 (p^3/27)) . A bit of cancellation will reduce that to the part abbreviated "stuff" in that equation.-/ rw myfld.mul_assoc (myfld.reciprocal _ _) (myfld.reciprocal _ _) (_ .+ _), rw myfld.mul_comm (myfld.reciprocal (cubed f (three f)) _) (myfld.reciprocal (_ .* _) _), repeat {rw <- myfld.mul_assoc _ _ _}, repeat {rw myfld.mul_assoc _ _ _}, rw split_reciprocal f (cubed f c) _ _, rw myfld.mul_assoc (cubed f c) (myfld.reciprocal (cubed f c) _) _, rw myfld.mul_reciprocal (cubed f c), rw one_mul_simp f _, rw double_reciprocal f _, rw reciprocal_rewrite f (cubed f (three f)) (twenty_seven f) (three_cubed f) _, rw myfld.mul_reciprocal (twenty_seven f) _, rw one_mul_simp f _, /- And now one of the big square roots is positive and one is negative, so they cancel.-/ clear denominator_sub_proof, repeat {rw add_negate f _ _}, rw double_negative f _, rw <- myfld.add_assoc (.- (sqroot _)) _ _, rw myfld.add_assoc _ (.- (sqroot _)) _, rw myfld.add_comm _ (.- (sqroot _)), repeat {rw <- myfld.add_assoc _ _ _}, repeat {rw myfld.add_assoc _ _ _}, /- TODO: improve this line-/ rw myfld.add_negate _, rw simp_zero f _, /- And finally we have (-d/2) + (-d/2) + d, which is obviously zero.-/ rw <- add_negate f (d .* _) (d .* _), rw <- distrib_simp_alt f d _ _, rw only_one_reciprocal f (two f) _ (two_ne_zero f), rw add_two_halves f, rw <- myfld.mul_one d, rw myfld.add_comm (.- d) d, exact myfld.add_negate d, end def cardano_formula_a (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d : f) (c_ne_zero : c ≠ myfld.zero) : f := cardano_formula f c d c_ne_zero fld_with_cube_root.cubrt (cubrt_nonzero f) (cubrt_cubed f) def cardano_formula_b (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d : f) (c_ne_zero : c ≠ myfld.zero) : f := cardano_formula f c d c_ne_zero (alt_cubrt_a f) (alt_cubrt_a_nonzero f) (alt_cubrt_a_correct f) def cardano_formula_c (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d : f) (c_ne_zero : c ≠ myfld.zero) : f := cardano_formula f c d c_ne_zero (alt_cubrt_b f) (alt_cubrt_b_nonzero f) (alt_cubrt_b_correct f) /- And as we have proven that all versions of the cardano_formula are correct when substituted into the equation, all three of the above formulae are solutions to a depressed cubic equation.-/ def depressed_cubic_solution_c_zero (f : Type) [myfld f] (c d : f) (c_eq_zero : c = myfld.zero) (cubrt_func : f -> f) (cubrt_func_correct : ∀ (x : f), (cubed f (cubrt_func x)) = x) : f := .- (cubrt_func (d)) lemma depressed_cubic_solution_c_zero_correct (f : Type) [myfld f] (c d : f) (c_eq_zero : c = myfld.zero) (cubrt_func : f -> f) (cubrt_func_correct : ∀ (x : f), (cubed f (cubrt_func x)) = x) : depressed_cubic_subst f c d (depressed_cubic_solution_c_zero f c d c_eq_zero cubrt_func cubrt_func_correct) = myfld.zero := begin unfold depressed_cubic_solution_c_zero, unfold depressed_cubic_subst, rw c_eq_zero, rw mul_zero f _, rw simp_zero f _, unfold cubed, repeat {rw mul_negate f _ _}, repeat {rw mul_negate_alt_simp f _ _}, rw double_negative f _, rw myfld.mul_assoc _ _ _, unfold cubed at cubrt_func_correct, rw <- myfld.mul_assoc, rw cubrt_func_correct _, rw myfld.add_comm, rw myfld.add_negate d, end def depressed_cubic_solution_c_zero_a (f : Type) [myfld f] [fld_with_cube_root f] (c d : f) (c_eq_zero : c = myfld.zero) : f := depressed_cubic_solution_c_zero f c d c_eq_zero fld_with_cube_root.cubrt (cubrt_cubed f) def depressed_cubic_solution_c_zero_b (f : Type) [myfld f] [fld_with_cube_root f] [fld_with_sqrt f] [fld_not_char_two f] (c d : f) (c_eq_zero : c = myfld.zero) : f := depressed_cubic_solution_c_zero f c d c_eq_zero (alt_cubrt_a f) (alt_cubrt_a_correct f) def depressed_cubic_solution_c_zero_c (f : Type) [myfld f] [fld_with_cube_root f] [fld_with_sqrt f] [fld_not_char_two f] (c d : f) (c_eq_zero : c = myfld.zero) : f := depressed_cubic_solution_c_zero f c d c_eq_zero (alt_cubrt_b f) (alt_cubrt_b_correct f) /- This is a bit lame, I will admit. We have a formula that is proven to be correct when c is zero, and a formula that is proven to be correct when c is not zero. I don't right now see that we can merge them into one formula, however, because while Lean does have a "cond" operator that functions like the ternary operator in most languages, it doesn't seem to allow for accessing a proof of the proposition that has been evaluated. Ergo, we can't use it here because calling the "c is not zero" version of the formula requires that we have a proof that c is not zero.-/ def cubic_subst (f : Type) [myfld f] (a b c d x : f) : f := (a .* (cubed f x)) .+ ((b .* (square f x)) .+ ((c .* x) .+ d)) /- This is a fairly trivial result, but it enables us to create a simplified version of the formula with no x^3 coefficient.-/ lemma divide_cubic_through (f : Type) [myfld f] (a b c d x : f) (a_ne_zero : a ≠ myfld.zero) : (cubic_subst f a b c d x) = myfld.zero <-> (cubic_subst f myfld.one (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) x) = myfld.zero := begin unfold cubic_subst, split, intros h, have h1 : (((a .* (cubed f x)) .+ ((b .* (square f x)) .+ ((c .* x) .+ d))) .* (myfld.reciprocal a a_ne_zero)) = myfld.zero, rw h, exact mul_zero f _, clear h, rename h1 h, repeat {rw distrib_simp f _ _ _ at h}, repeat {rw <- myfld.mul_assoc _ _ (myfld.reciprocal a a_ne_zero) at h}, repeat {rw myfld.mul_comm _ (myfld.reciprocal a a_ne_zero) at h}, rw myfld.mul_assoc a (myfld.reciprocal a a_ne_zero) _ at h, rw myfld.mul_reciprocal a a_ne_zero at h, rw myfld.mul_comm d (myfld.reciprocal a a_ne_zero), repeat {rw myfld.mul_assoc _ _ _ at h}, repeat {rw myfld.mul_assoc _ _ _}, exact h, intros h, have h1 : (((myfld.one .* (cubed f x)) .+ (((b .* (myfld.reciprocal a a_ne_zero)) .* (square f x)) .+ (((c .* (myfld.reciprocal a a_ne_zero)) .* x) .+ (d .* (myfld.reciprocal a a_ne_zero))))) .* a) = myfld.zero, rw h, exact mul_zero f _, clear h, rename h1 h, repeat {rw distrib_simp f _ _ _ at h}, rw <- myfld.mul_assoc _ (myfld.reciprocal a a_ne_zero) a at h, rw myfld.mul_comm (myfld.reciprocal a a_ne_zero) a at h, rw myfld.mul_reciprocal a a_ne_zero at h, rw simp_mul_one at h, repeat {rw <- myfld.mul_assoc _ _ a at h}, repeat {rw myfld.mul_comm _ a at h}, repeat {rw myfld.mul_assoc _ a _ at h}, repeat {rw <- myfld.mul_assoc _ _ a at h}, repeat {rw myfld.mul_comm (myfld.reciprocal a a_ne_zero) a at h}, rw myfld.mul_reciprocal a a_ne_zero at h, repeat {rw simp_mul_one at h}, rw one_mul_simp at h, exact h, end def third (f : Type) [myfld f] [fld_not_char_three f] : f := (myfld.reciprocal (three f) fld_not_char_three.not_char_three) def twenty_seventh (f : Type) [myfld f] [fld_not_char_three f] : f := (myfld.reciprocal (twenty_seven f) (twenty_seven_ne_zero f)) /- This looks weird and pointless but it simplifies a proof later.-/ lemma depressed_cubic_equal_split (f : Type) [myfld f] (c1 d1 c2 d2 x : f) : (c1 = c2) /\ (d1 = d2) -> (depressed_cubic_subst f c1 d1 x) = (depressed_cubic_subst f c2 d2 x) := begin intros h, cases h with h1 h2, rw h1, rw h2, end /- This is used in the next proof (reduce_cubic_to_depressed) . It could have been done with a "have", but the next proof is long enough that my computer was struggling with it, so it seemed worth moving this bit out.-/ lemma helper_bcubed (f : Type) [myfld f] [fld_not_char_three f] (b : f) : (b .* ((third f) .* (b .* ((third f) .* b)))) = ((three f) .* ((myfld.reciprocal (twenty_seven f) (twenty_seven_ne_zero f)) .* ((b .* b) .* b))) := begin unfold third, unfold twenty_seven, unfold nine, rw split_reciprocal f _ _ _, rw <- myfld.mul_assoc (myfld.reciprocal (three f) _), rw myfld.mul_assoc (three f) (myfld.reciprocal (three f) _) _, rw myfld.mul_reciprocal (three f) _, rw one_mul_simp f _, repeat {rw myfld.mul_comm b (_ .* _) }, repeat {rw myfld.mul_assoc _ _ _}, rw mul_two_reciprocals f _ _ _ _, end /- Ditto.-/ lemma helper_twothirds (f : Type) [myfld f] [fld_not_char_three f] : ((.- (third f)) .+ myfld.one) = (third f) .+ (third f) := begin have h : myfld.one = (third f) .* (three f) , unfold third, rw myfld.mul_comm, symmetry, exact myfld.mul_reciprocal (three f) _, rw h, clear h, have h : (.- (third f)) = (third f) .* (.- myfld.one) , rw <- mul_negate_alt f _ _, rw simp_mul_one f _, rw h, clear h, rw <- distrib_simp_alt f _ _ _, unfold third, unfold three, rw myfld.add_assoc (.- myfld.one) myfld.one _, rw myfld.add_comm (.- myfld.one) myfld.one, rw myfld.add_negate myfld.one, rw simp_zero f _, rw distrib_simp_alt f _ _ _, rw simp_mul_one f _, end lemma reduce_cubic_to_depressed (f : Type) [myfld f] [fld_not_char_three f] (b c d x y : f) : x = y .+ (.- (b .* (third f))) -> (cubic_subst f myfld.one b c d x) = (depressed_cubic_subst f (((square f b) .* (.- (third f))) .+ c) ((twenty_seventh f) .* ((((two f) .* (cubed f b)) .+ (.- ((nine f) .* (b .* c)))) .+ ((twenty_seven f) .* d))) y) := begin intros h, rw h, clear h, unfold cubic_subst, rw multiply_out_cubed f y _, rw multiply_out_squared f _ _, rw one_mul_simp f _, repeat {rw distrib_simp_alt f _ _ _}, rw mul_negate f _ _, repeat {rw mul_negate_alt_simp f _ _}, repeat {rw mul_negate f _ _}, rw mul_negate_alt_simp f _ _, rw double_negative f _, /- First job is to cancel the terms that have 3 * (1/3) in them.-/ have third_three : (three f) .* (third f) = myfld.one, unfold third, rw myfld.mul_reciprocal (three f) _, rw myfld.mul_comm b (third f), rw myfld.mul_assoc _ (third f) _, rw myfld.mul_comm _ (third f), rw <- myfld.mul_assoc (third f) _ _, rw myfld.mul_assoc y (third f) b, rw myfld.mul_comm y (third f), rw <- myfld.mul_assoc (third f) y b, rw <- myfld.mul_assoc (third f) (y .* b) _, repeat {rw myfld.mul_assoc (three f) (third f) _}, rw third_three, clear third_three, repeat {rw one_mul_simp f _}, /- Now we have a term for by^2 and -by^2, so these cancel.-/ unfold square, rw myfld.mul_comm b (y .* y), rw myfld.add_comm (.- ((y .* y) .* b)) _, repeat {rw <- myfld.add_assoc}, rw myfld.add_assoc (.- ((y .* y) .* b)) ((y .* y) .* b) _, rw myfld.add_comm (.- ((y .* y) .* b)) ((y .* y) .* b), rw myfld.add_negate ((y .* y) .* b), rw simp_zero, /- This ultimately needs to be made equivalent to the depressed cubic formula, so we gather all the terms that are multiplied by y together.-/ rw myfld.mul_comm _ y, repeat {rw myfld.mul_assoc _ y _, rw myfld.mul_comm _ y}, rw <- myfld.mul_assoc y (two f) _, rw myfld.mul_assoc _ y _, rw myfld.mul_comm b y, repeat {rw <- myfld.mul_assoc y b _}, rw mul_negate_alt f y _, rw myfld.mul_comm c y, rw myfld.add_assoc (cubed f (.- ((third f) .* b))) (y .* _) _, rw myfld.add_comm _ (y .* (.- (b .* ((two f) .* ((third f) .* b))))), rw <- myfld.add_assoc (y .* (.- (b .* ((two f) .* ((third f) .* b))))) _ _, rw myfld.add_assoc (y .* _) (y .* _), rw <- distrib_simp_alt f y _ _, rw myfld.add_assoc _ (y .* c) _, rw myfld.add_comm _ (y .* c), rw <- myfld.add_assoc (y .* c) _ _, rw myfld.add_assoc _ (y .* c) _, rw myfld.add_comm _ (y .* c), rw <- myfld.add_assoc (y .* c) _ _, rw myfld.add_assoc _ (y .* c) _, rw <- distrib_simp_alt f y _ c, /- We can now fold this back into the depressed cubic formula, which will make the remaining algebra slightly easier to follow.-/ rw myfld.mul_comm y _, /- The following line is ugly, but it's just a copy-paste of the algebra in the sidebar.-/ have tmp : (cubed f y) .+ (((((b .* ((third f) .* b)) .+ (.- (b .* ((two f) .* ((third f) .* b))))) .+ c) .* y) .+ ((cubed f (.- ((third f) .* b))) .+ ((b .* ((.- ((third f) .* b)) .* (.- ((third f) .* b)))) .+ ((.- (c .* ((third f) .* b))) .+ d)))) = depressed_cubic_subst f (((b .* ((third f) .* b)) .+ (.- (b .* ((two f) .* ((third f) .* b))))) .+ c) ((cubed f (.- ((third f) .* b))) .+ ((b .* ((.- ((third f) .* b)) .* (.- ((third f) .* b)))) .+ ((.- (c .* ((third f) .* b))) .+ d))) y, unfold depressed_cubic_subst, rw tmp, clear tmp, /- This enables us to break down into two goals (one for the y term and one for the constant.) -/ apply depressed_cubic_equal_split f _ _ _ _ y, split, /- (b^2) /3 - 2 (b/^2) 3 = - (b^2) /3, which solves the y term goal.-/ rw myfld.mul_comm _ b, rw myfld.mul_comm _ (b .* _), rw myfld.mul_assoc _ b _, rw myfld.mul_comm (two f) b, rw <- myfld.mul_assoc b (two f) _, rw myfld.mul_comm (b .* (third f)) b, repeat {rw myfld.mul_assoc b b _}, rw mul_negate_alt f (b .* b) _, rw <- distrib_simp_alt f (b .* b) _ _, rw myfld.mul_comm (two f) (third f), have tmp : (third f) = ((third f) .* myfld.one), exact myfld.mul_one (third f), rewrite [tmp] {occs := occurrences.pos [1]}, clear tmp, rw mul_negate_alt f (third f) (two f), rw <- distrib_simp_alt f (third f) _ _, have tmp : myfld.one .+ (.- (two f)) = .- (myfld.one), unfold two, rw add_negate f myfld.one myfld.one, rw myfld.add_assoc myfld.one (.- myfld.one) (.- myfld.one), rw myfld.add_negate myfld.one, rw <- zero_add f (.- myfld.one), rw tmp, clear tmp, rw <- mul_negate_alt f (third f) myfld.one, rw simp_mul_one f _, rw <- mul_negate_alt f (b .* b) (third f), /- The constant goal is a bit more complicated, but all it really involves is collecting together the b^3 terms and reducing the coefficient of each term to a single power of three.-/ unfold cubed, repeat {rw mul_negate f _ _}, repeat {rw mul_negate_alt_simp f _ _}, repeat {rw double_negative f _}, rw myfld.mul_assoc (twenty_seventh f) (twenty_seven f) _, rw myfld.mul_comm (twenty_seventh f) (twenty_seven f), unfold twenty_seventh, rw myfld.mul_reciprocal (twenty_seven f) _, rw one_mul_simp f _, rw myfld.mul_assoc (myfld.reciprocal (twenty_seven f) _) (nine f), rw only_one_reciprocal f (twenty_seven f) _ (twenty_seven_ne_zero f), have tmp : ((myfld.reciprocal (twenty_seven f) (twenty_seven_ne_zero f)) .* (nine f)) = (myfld.reciprocal (three f) fld_not_char_three.not_char_three), unfold twenty_seven, unfold nine, rw split_reciprocal f _ _ _, rw split_reciprocal f _ _ _, repeat {rw <- myfld.mul_assoc _ _ _}, rw myfld.mul_assoc (myfld.reciprocal _ _) (three f) _, rw myfld.mul_comm (myfld.reciprocal (three f) _) (three f), rw myfld.mul_reciprocal (three f) _, rw one_mul_simp f _, rw myfld.mul_comm (myfld.reciprocal (three f) _) (three f), rw myfld.mul_reciprocal (three f) _, rw simp_mul_one f _, rw myfld.mul_assoc (myfld.reciprocal (twenty_seven f) _) (nine f) _, rw tmp, clear tmp, rw myfld.mul_assoc _ (two f) _, rw myfld.mul_comm _ (two f), rw <- myfld.mul_assoc (two f) _ _, unfold two, rw distrib_simp f myfld.one myfld.one _, rw one_mul_simp f _, rw myfld.add_assoc _ (b .* ((third f) .* (b .* ((third f) .* b)))) _, rw helper_bcubed f b, have tmp : ((three f) .* ((myfld.reciprocal (twenty_seven f) _) .* ((b .* b) .* b))) = (myfld.one .* ((three f) .* ((myfld.reciprocal (twenty_seven f) _) .* ((b .* b) .* b)))), rw one_mul_simp f _, rewrite [tmp] {occs := occurrences.pos [2]}, clear tmp, rw <- mul_negate f (third f) _, rw <- distrib_simp f _ _ _, rw helper_twothirds f, rw distrib_simp f (third f) (third f) _, rw myfld.mul_assoc (third f) (three f) _, have tmp : (third f) .* (three f) = myfld.one, unfold third, rw myfld.mul_comm _ _, rw myfld.mul_reciprocal (three f) _, rw tmp, rw one_mul_simp f _, clear tmp, rw myfld.mul_assoc c (third f) b, rw myfld.mul_comm c (third f), rw <- myfld.mul_assoc (third f) c b, rw myfld.mul_comm c b, rw myfld.mul_assoc b b b, unfold third, end /- We have now proven that every cubic equation can be reduced to a cubic equation where the x^3 coefficient is 1, that every such cubic can be reduced to a depressed cubic, and that every depressed cubic can be solved with Cardano's formula. This is therefore enough for a solution to any general cubic. The one wrinkle in this is that the Cardano formula only works if the x term is not equal to zero. If the x term is equal to zero then the solution is trivial (x just equals zero minus the cube root of the constant), but this cannot be represented as part of the same formula using our notion of reciprocals. Ergo, to get a general cubic formula we need to assume that it is always decidable whether a value is zero or not.-/ lemma int_quantity_ne_zero_simp (f : Type) [myfld f] [fld_not_char_three f] (a1 b c : f) (a_ne_zero : a1 ≠ myfld.zero) : ((three f) .* (a1 .* c)) .+ (.- (square f b)) ≠ myfld.zero -> (((square f (b .* (myfld.reciprocal a1 a_ne_zero))) .* (.- (third f))) .+ (c .* (myfld.reciprocal a1 a_ne_zero))) ≠ myfld.zero := begin intros h1 h2, unfold square at h2, rw myfld.mul_comm _ (.- _) at h2, repeat {rw myfld.mul_assoc _ _ (myfld.reciprocal a1 a_ne_zero) at h2}, rw <- distrib_simp f _ _ _ at h2, rw <- mul_zero_by_reciprocal f a1 _ _ at h2, rw mul_both_sides f _ _ (three f) at h2, rw mul_zero at h2, rw distrib_simp at h2, repeat {rw mul_negate at h2}, rw myfld.mul_comm (_ .* _) (three f) at h2, rw myfld.mul_assoc (three f) (third f) _ at h2, unfold third at h2, rw myfld.mul_reciprocal (three f) _ at h2, rw one_mul_simp at h2, rw mul_both_sides f _ _ a1 at h2, rw distrib_simp at h2, rw mul_zero at h2, rw mul_negate at h2, rw myfld.mul_comm _ b at h2, repeat {rw <- myfld.mul_assoc at h2}, rw myfld.mul_comm _ a1 at h2, rw myfld.mul_reciprocal a1 _ at h2, rw simp_mul_one at h2, unfold square at h1, rw myfld.mul_comm c _ at h2, rw myfld.mul_assoc at h1, rw myfld.add_comm at h1, cc, cc, exact fld_not_char_three.not_char_three, end def cubic_formula_a (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_ne_zero : ((three f) .* (a .* c)) .+ (.- (square f b)) ≠ myfld.zero) : f := ((cardano_formula_a f (((square f (b .* (myfld.reciprocal a a_ne_zero))) .* (.- (third f))) .+ (c .* (myfld.reciprocal a a_ne_zero))) ((twenty_seventh f) .* ((((two f) .* (cubed f (b .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((nine f) .* ((b .* (myfld.reciprocal a a_ne_zero)) .* (c .* (myfld.reciprocal a a_ne_zero)))))) .+ ((twenty_seven f) .* (d .* (myfld.reciprocal a a_ne_zero))))) (int_quantity_ne_zero_simp f a b c a_ne_zero int_quantity_ne_zero)) .+ (.- ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f)))) lemma cubic_formula_a_correct (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_ne_zero : ((three f) .* (a .* c)) .+ (.- (square f b)) ≠ myfld.zero) : cubic_subst f a b c d (cubic_formula_a f a b c d a_ne_zero int_quantity_ne_zero) = myfld.zero := begin rw divide_cubic_through f a b c d _ a_ne_zero, have tmp : (cubic_formula_a f a b c d a_ne_zero int_quantity_ne_zero) = (((cubic_formula_a f a b c d a_ne_zero int_quantity_ne_zero) .+ ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f))) .+ (.- ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f)))), simp, rw reduce_cubic_to_depressed f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (cubic_formula_a f a b c d a_ne_zero int_quantity_ne_zero) ((cubic_formula_a f a b c d a_ne_zero int_quantity_ne_zero) .+ ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f))) tmp, clear tmp, unfold cubic_formula_a, unfold cardano_formula_a, rw <- myfld.add_assoc (cardano_formula f _ _ _ _ _ _) (.- _) _, rw myfld.add_comm (.- _) _, rw myfld.add_negate _, rw zero_simp f _, exact cardano_works f _ _ _ _ _ _, end def cubic_formula_b (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_ne_zero : ((three f) .* (a .* c)) .+ (.- (square f b)) ≠ myfld.zero) : f := ((cardano_formula_b f (((square f (b .* (myfld.reciprocal a a_ne_zero))) .* (.- (third f))) .+ (c .* (myfld.reciprocal a a_ne_zero))) ((twenty_seventh f) .* ((((two f) .* (cubed f (b .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((nine f) .* ((b .* (myfld.reciprocal a a_ne_zero)) .* (c .* (myfld.reciprocal a a_ne_zero)))))) .+ ((twenty_seven f) .* (d .* (myfld.reciprocal a a_ne_zero))))) (int_quantity_ne_zero_simp f a b c a_ne_zero int_quantity_ne_zero)) .+ (.- ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f)))) lemma cubic_formula_b_correct (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_ne_zero : ((three f) .* (a .* c)) .+ (.- (square f b)) ≠ myfld.zero) : cubic_subst f a b c d (cubic_formula_b f a b c d a_ne_zero int_quantity_ne_zero) = myfld.zero := begin rw divide_cubic_through f a b c d _ a_ne_zero, have tmp : (cubic_formula_b f a b c d a_ne_zero int_quantity_ne_zero) = (((cubic_formula_b f a b c d a_ne_zero int_quantity_ne_zero) .+ ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f))) .+ (.- ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f)))), simp, rw reduce_cubic_to_depressed f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (cubic_formula_b f a b c d a_ne_zero int_quantity_ne_zero) ((cubic_formula_b f a b c d a_ne_zero int_quantity_ne_zero) .+ ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f))) tmp, clear tmp, unfold cubic_formula_b, unfold cardano_formula_b, rw <- myfld.add_assoc (cardano_formula f _ _ _ _ _ _) (.- _) _, rw myfld.add_comm (.- _) _, rw myfld.add_negate _, rw zero_simp f _, exact cardano_works f _ _ _ _ _ _, end def cubic_formula_c (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_ne_zero : ((three f) .* (a .* c)) .+ (.- (square f b)) ≠ myfld.zero) : f := ((cardano_formula_c f (((square f (b .* (myfld.reciprocal a a_ne_zero))) .* (.- (third f))) .+ (c .* (myfld.reciprocal a a_ne_zero))) ((twenty_seventh f) .* ((((two f) .* (cubed f (b .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((nine f) .* ((b .* (myfld.reciprocal a a_ne_zero)) .* (c .* (myfld.reciprocal a a_ne_zero)))))) .+ ((twenty_seven f) .* (d .* (myfld.reciprocal a a_ne_zero))))) (int_quantity_ne_zero_simp f a b c a_ne_zero int_quantity_ne_zero)) .+ (.- ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f)))) lemma cubic_formula_c_correct (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_ne_zero : ((three f) .* (a .* c)) .+ (.- (square f b)) ≠ myfld.zero) : cubic_subst f a b c d (cubic_formula_c f a b c d a_ne_zero int_quantity_ne_zero) = myfld.zero := begin rw divide_cubic_through f a b c d _ a_ne_zero, have tmp : (cubic_formula_c f a b c d a_ne_zero int_quantity_ne_zero) = (((cubic_formula_c f a b c d a_ne_zero int_quantity_ne_zero) .+ ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f))) .+ (.- ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f)))), simp, rw reduce_cubic_to_depressed f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (cubic_formula_c f a b c d a_ne_zero int_quantity_ne_zero) ((cubic_formula_c f a b c d a_ne_zero int_quantity_ne_zero) .+ ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f))) tmp, clear tmp, unfold cubic_formula_c, unfold cardano_formula_c, rw <- myfld.add_assoc (cardano_formula f _ _ _ _ _ _) (.- _) _, rw myfld.add_comm (.- _) _, rw myfld.add_negate _, rw zero_simp f _, exact cardano_works f _ _ _ _ _ _, end lemma int_quantity_eq_zero_simp (f : Type) [myfld f] [fld_not_char_three f] (a1 b c : f) (a_ne_zero : a1 ≠ myfld.zero) : ((three f) .* (a1 .* c)) .+ (.- (square f b)) = myfld.zero -> (((square f (b .* (myfld.reciprocal a1 a_ne_zero))) .* (.- (third f))) .+ (c .* (myfld.reciprocal a1 a_ne_zero))) = myfld.zero := begin intros h, unfold square, rw myfld.mul_comm _ (.- _), repeat {rw myfld.mul_assoc _ _ (myfld.reciprocal a1 a_ne_zero) }, rw <- distrib_simp f _ _ _, rw <- mul_zero_by_reciprocal f a1 _ _, rw mul_both_sides f _ _ (three f), rw mul_zero, rw distrib_simp, repeat {rw mul_negate}, rw myfld.mul_comm (_ .* _) (three f), rw myfld.mul_assoc (three f) (third f) _, unfold third, rw myfld.mul_reciprocal (three f) _, rw one_mul_simp, rw mul_both_sides f _ _ a1, rw distrib_simp, rw mul_zero, rw mul_negate, rw myfld.mul_comm _ b, repeat {rw <- myfld.mul_assoc}, rw myfld.mul_comm _ a1, rw myfld.mul_reciprocal a1 _, rw simp_mul_one, unfold square at h, rw myfld.mul_comm c _, rw myfld.mul_assoc at h, rw myfld.add_comm at h, cc, cc, exact fld_not_char_three.not_char_three, end def cubic_formula_a_alt (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_eq_zero : ((three f) .* (a .* c)) .+ (.- (square f b)) = myfld.zero) : f := ((depressed_cubic_solution_c_zero_a f (((square f (b .* (myfld.reciprocal a a_ne_zero))) .* (.- (third f))) .+ (c .* (myfld.reciprocal a a_ne_zero))) ((twenty_seventh f) .* ((((two f) .* (cubed f (b .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((nine f) .* ((b .* (myfld.reciprocal a a_ne_zero)) .* (c .* (myfld.reciprocal a a_ne_zero)))))) .+ ((twenty_seven f) .* (d .* (myfld.reciprocal a a_ne_zero))))) (int_quantity_eq_zero_simp f a b c a_ne_zero int_quantity_eq_zero)) .+ (.- ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f)))) lemma cubic_formula_a_alt_correct (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_eq_zero : ((three f) .* (a .* c)) .+ (.- (square f b)) = myfld.zero) : cubic_subst f a b c d (cubic_formula_a_alt f a b c d a_ne_zero int_quantity_eq_zero) = myfld.zero := begin rw divide_cubic_through f a b c d _ a_ne_zero, have tmp : (cubic_formula_a_alt f a b c d a_ne_zero int_quantity_eq_zero) = (((cubic_formula_a_alt f a b c d a_ne_zero int_quantity_eq_zero) .+ ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f))) .+ (.- ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f)))), simp, rw reduce_cubic_to_depressed f (b .* (myfld.reciprocal a a_ne_zero)) (c .* (myfld.reciprocal a a_ne_zero)) (d .* (myfld.reciprocal a a_ne_zero)) (cubic_formula_a_alt f a b c d a_ne_zero int_quantity_eq_zero) ((cubic_formula_a_alt f a b c d a_ne_zero int_quantity_eq_zero) .+ ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f))) tmp, clear tmp, unfold cubic_formula_a_alt, unfold depressed_cubic_solution_c_zero_a, rw <- myfld.add_assoc (depressed_cubic_solution_c_zero f _ _ _ _ _) (.- _) _, rw myfld.add_comm (.- _) _, rw myfld.add_negate _, rw zero_simp f _, exact depressed_cubic_solution_c_zero_correct f _ _ _ fld_with_cube_root.cubrt (cubrt_cubed f), end def cubic_formula_b_alt (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_eq_zero : ((three f) .* (a .* c)) .+ (.- (square f b)) = myfld.zero) : f := ((depressed_cubic_solution_c_zero_b f (((square f (b .* (myfld.reciprocal a a_ne_zero))) .* (.- (third f))) .+ (c .* (myfld.reciprocal a a_ne_zero))) ((twenty_seventh f) .* ((((two f) .* (cubed f (b .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((nine f) .* ((b .* (myfld.reciprocal a a_ne_zero)) .* (c .* (myfld.reciprocal a a_ne_zero)))))) .+ ((twenty_seven f) .* (d .* (myfld.reciprocal a a_ne_zero))))) (int_quantity_eq_zero_simp f a b c a_ne_zero int_quantity_eq_zero)) .+ (.- ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f)))) def cubic_formula_c_alt (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a b c d : f) (a_ne_zero : a ≠ myfld.zero) (int_quantity_eq_zero : ((three f) .* (a .* c)) .+ (.- (square f b)) = myfld.zero) : f := ((depressed_cubic_solution_c_zero_c f (((square f (b .* (myfld.reciprocal a a_ne_zero))) .* (.- (third f))) .+ (c .* (myfld.reciprocal a a_ne_zero))) ((twenty_seventh f) .* ((((two f) .* (cubed f (b .* (myfld.reciprocal a a_ne_zero)))) .+ (.- ((nine f) .* ((b .* (myfld.reciprocal a a_ne_zero)) .* (c .* (myfld.reciprocal a a_ne_zero)))))) .+ ((twenty_seven f) .* (d .* (myfld.reciprocal a a_ne_zero))))) (int_quantity_eq_zero_simp f a b c a_ne_zero int_quantity_eq_zero)) .+ (.- ((b .* (myfld.reciprocal a a_ne_zero)) .* (third f)))) /- And so, as long as it is decidable whether a quantity is equal to zero or not, we have a viable solution to any cubic.-/ /- The next goal is to prove uniqueness of those solutions. As thie is going to involve the cardano formula and the cube roots of unity, we can start with some intermediate lemmae.-/ lemma cube_roots_sum_zero (f : Type) [myfld f] [fld_with_sqrt f] [fld_not_char_two f] [fld_with_cube_root f] (x : f) : (fld_with_cube_root.cubrt x) .+ ((alt_cubrt_a f x) .+ (alt_cubrt_b f x)) = myfld.zero := begin unfold alt_cubrt_a, unfold alt_cubrt_b, unfold cube_root_of_unity, rw <- distrib_simp f _ _ (fld_with_cube_root.cubrt x), have tmp : (fld_with_cube_root.cubrt x) = myfld.one .* (fld_with_cube_root.cubrt x) , rw myfld.mul_comm, exact myfld.mul_one (fld_with_cube_root.cubrt x), rw [tmp] {occs := occurrences.pos [1]}, clear tmp, rw <- distrib_simp f _ _ (fld_with_cube_root.cubrt x), have h : (myfld.one .+ (( .- myfld.one .+ sqroot .- (three f)) .* (myfld.reciprocal (two f) _) .+ ( .- myfld.one .+ .- sqroot .- (three f)) .* (myfld.reciprocal (two f) _))) = myfld.zero, rw myfld.add_comm _ (.- (sqroot _)), rw distrib_simp f _ _ _, rw distrib_simp f _ _ _, repeat {rw mul_negate f _ _}, rw one_mul_simp f _, repeat {rw <- myfld.add_assoc _ _ _}, rw myfld.add_assoc (_ .* _) (.- _) _, rw myfld.add_negate _, rw simp_zero f _, rw <- add_negate f _ _, rw only_one_reciprocal f (two f) _ (two_ne_zero f), rw add_two_halves f, exact myfld.add_negate myfld.one, rw h, exact mul_zero f _, end /- Proving uniqueness will involve expalnding the cubic (x - solution_a) (x - solution_b) (x - solution_c) . This is the x^2 term (0) in the resulting cubic.-/ lemma cardano_formulae_sum_zero (f : Type) [myfld f] [fld_with_sqrt f] [fld_not_char_two f] [fld_with_cube_root f] [fld_not_char_three f] (c d : f) (c_ne_zero : c ≠ myfld.zero) : (cardano_formula_a f c d c_ne_zero) .+ ((cardano_formula_b f c d c_ne_zero) .+ (cardano_formula_c f c d c_ne_zero)) = myfld.zero := begin have mul_zero_by_anything : ∀(x y : f), (x = myfld.zero) -> x .* y = myfld.zero, intros x y hx, rw hx, rw mul_zero, unfold cardano_formula_a, unfold cardano_formula_b, unfold cardano_formula_c, unfold cardano_formula, /- First move all the cube root terms to the start - they must sum to zero by the previous lemma.-/ rw <- myfld.add_assoc (alt_cubrt_a f _) _ _, rw myfld.add_assoc _ (alt_cubrt_b f _) _, rw myfld.add_comm _ (alt_cubrt_b f _), rw <- myfld.add_assoc (alt_cubrt_b f _) _ _, rw myfld.add_assoc (alt_cubrt_a f _) (alt_cubrt_b f _) _, rw myfld.add_assoc (_ .+ _) (_ .+ _) (_ .+ _), rw <- myfld.add_assoc (fld_with_cube_root.cubrt _) (.- _) (_ .+ _), rw myfld.add_comm (.- _) ((alt_cubrt_a f _) .+ (alt_cubrt_b f _)), rw myfld.add_assoc (fld_with_cube_root.cubrt _) (_ .+ _) (.- _), rw cube_roots_sum_zero f _, rw simp_zero f _, /- The three remaining terms are all -c/3x, where x is one of the three cube roots. We can first use distributivity to make this into the sum of the reciprocals of the cube roots.-/ rw <- add_negate f _ _, rw <- add_negate f _ _, apply negate_zero_a f _, rw <- distrib_simp_alt f c _ _, rw <- distrib_simp_alt f c _ _, rw myfld.mul_comm c _, apply mul_zero_by_anything _ c, repeat {rw <- mul_two_reciprocals f _ (three f) _ _}, rw only_one_reciprocal f (three f) _ fld_not_char_three.not_char_three, rw <- distrib_simp f _ _ (myfld.reciprocal (three f) fld_not_char_three.not_char_three), rw <- distrib_simp f _ _ (myfld.reciprocal (three f) fld_not_char_three.not_char_three), apply mul_zero_by_anything _ (myfld.reciprocal (three f) fld_not_char_three.not_char_three), unfold alt_cubrt_a, unfold alt_cubrt_b, rw split_reciprocal f _ (fld_with_cube_root.cubrt ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d))), rw split_reciprocal f _ (fld_with_cube_root.cubrt ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d))), rw only_one_reciprocal f _ _ (cubrt_nonzero f _ (cardano_den_not_zero_int f c d c_ne_zero)), rw <- distrib_simp f _ _ _, have tmp : (myfld.reciprocal (fld_with_cube_root.cubrt ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d))) _) = myfld.one .* (myfld.reciprocal (fld_with_cube_root.cubrt ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d))) _) , rw myfld.mul_comm myfld.one _, exact myfld.mul_one _, exact cubrt_nonzero f _ (cardano_den_not_zero_int f c d c_ne_zero), rw [tmp] {occs := occurrences.pos [1]}, clear tmp, rw only_one_reciprocal f _ _ (cubrt_nonzero f _ (cardano_den_not_zero_int f c d c_ne_zero)), rw <- distrib_simp f _ _ _, apply mul_zero_by_anything _ _, /- And now we just prove that the reciprocals of the cube roots of unity add to zero. -/ unfold cube_root_of_unity, repeat {rw split_reciprocal f _ _ _}, rw double_reciprocal f _ _, rw <- distrib_simp f _ _ (two f), rw add_two_reciprocals f _ _ _ _, rw <- myfld.add_assoc (.- myfld.one) _ (_ .+ _), have tmp : (.- myfld.one) .+ (.- (sqroot (.- (three f)))) = (.- (sqroot (.- (three f)))) .+ (.- myfld.one) , exact myfld.add_comm (.- myfld.one) (.- (sqroot (.- (three f)))), rw [tmp] {occs := occurrences.pos [1]}, clear tmp, rw myfld.add_assoc (sqroot _) (.- (sqroot _)) _, rw myfld.add_negate (sqroot (.- (three f))), rw simp_zero f _, rw <- add_negate f myfld.one myfld.one, rw reciprocal_rewrite f _ _ (difference_of_squares f (.- myfld.one) (sqroot (.- (three f)))) _, have simp_den : ((square f (.- myfld.one)) .+ (.- (square f (sqroot (.- (three f)))))) = (two f) .* (two f) , unfold square, rw mul_negate f _ _, rw <- mul_negate_alt f _ _, rw double_negative f _, rw simp_mul_one f _, rw fld_with_sqrt.sqrt_mul_sqrt _, rw double_negative f _, unfold three, unfold two, simp, rw reciprocal_rewrite f _ ((two f) .* (two f)) simp_den _, rw <- myfld.mul_assoc _ _ _, rw split_reciprocal f (two f) (two f) _, rw <- myfld.mul_assoc (myfld.reciprocal (two f) _) (myfld.reciprocal (two f) _) (two f), rw myfld.mul_comm (myfld.reciprocal (two f) _) (two f), rw myfld.mul_reciprocal (two f) _, rw simp_mul_one f _, rw mul_negate f _ _, unfold two, rw myfld.mul_reciprocal (myfld.one .+ myfld.one) _, exact myfld.add_negate myfld.one, /- And now we just do some of the leftover detritus from the "applies" earlier.-/ apply alt_cubrt_b_nonzero f _, exact cardano_den_not_zero_int f c d c_ne_zero, exact fld_not_char_three.not_char_three, apply alt_cubrt_a_nonzero f _, exact cardano_den_not_zero_int f c d c_ne_zero, end lemma cardano_products (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d x : f) (c_ne_zero : c ≠ myfld.zero) : ((((cardano_formula_a f c d c_ne_zero) .* (cardano_formula_b f c d c_ne_zero)) .+ ((cardano_formula_a f c d c_ne_zero) .* (cardano_formula_c f c d c_ne_zero))) .+ ((cardano_formula_b f c d c_ne_zero) .* (cardano_formula_c f c d c_ne_zero))) = c := begin /- I'm so sorry about this line. What it does is simplify the proof by reducing it to solving the same goal where some of the more complex recurring expressions have been folded down. However, the only nice way to do that is with mathlib, and there are reasons why I *really* didn't want to use that.-/ have folded_version : ∀ (cubrt root_unity_a root_unity_b : f), ∀ (cubrt_ne_zero : cubrt ≠ myfld.zero), ∀ (root_unity_a_ne_zero : root_unity_a ≠ myfld.zero), ∀ (root_unity_b_ne_zero : root_unity_b ≠ myfld.zero), (cubrt = (fld_with_cube_root.cubrt ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d))) -> root_unity_a = (cube_root_of_unity f (sqroot (.- (three f))) (fld_with_sqrt.sqrt_mul_sqrt (.- (three f)))) -> root_unity_b = (cube_root_of_unity f (.- (sqroot (.- (three f)))) (negative_sqrt f (.- (three f)))) -> (((cubrt .+ (.- (c .* (myfld.reciprocal (cubrt .* (three f)) (mul_nonzero f cubrt (three f) cubrt_ne_zero fld_not_char_three.not_char_three))))) .* ((root_unity_a .* cubrt) .+ (.- (c .* (myfld.reciprocal ((root_unity_a .* cubrt) .* (three f)) (mul_nonzero f (root_unity_a .* cubrt) (three f) (mul_nonzero f root_unity_a cubrt root_unity_a_ne_zero cubrt_ne_zero) fld_not_char_three.not_char_three)))))) .+ ((cubrt .+ (.- (c .* (myfld.reciprocal (cubrt .* (three f)) (mul_nonzero f cubrt (three f) cubrt_ne_zero fld_not_char_three.not_char_three))))) .* ((root_unity_b .* cubrt) .+ (.- (c .* (myfld.reciprocal ((root_unity_b .* cubrt) .* (three f)) (mul_nonzero f (root_unity_b .* cubrt) (three f) (mul_nonzero f root_unity_b cubrt root_unity_b_ne_zero cubrt_ne_zero) fld_not_char_three.not_char_three))))))) .+ (((root_unity_a .* cubrt) .+ (.- (c .* (myfld.reciprocal ((root_unity_a .* cubrt) .* (three f)) (mul_nonzero f (root_unity_a .* cubrt) (three f) (mul_nonzero f root_unity_a cubrt root_unity_a_ne_zero cubrt_ne_zero) fld_not_char_three.not_char_three))))) .* ((root_unity_b .* cubrt) .+ (.- (c .* (myfld.reciprocal ((root_unity_b .* cubrt) .* (three f)) (mul_nonzero f (root_unity_b .* cubrt) (three f) (mul_nonzero f root_unity_b cubrt root_unity_b_ne_zero cubrt_ne_zero) fld_not_char_three.not_char_three)))))) = c), intros cubrt root_unity_a root_unity_b cubrt_n_zero rta_n_zero rtb_n_zero cubrt_h root_unity_a_h root_unity_b_h, /- OK, so that hideous line means that the proof in the sidebar looks much less hideous, but we can still use it to solve the main proof once we finish.-/ /- First take a moment to restate some of the properties of roots.-/ have sum_roots_zero : myfld.one .+ (root_unity_a .+ root_unity_b) = myfld.zero, rw root_unity_a_h, rw root_unity_b_h, have tmp : myfld.one .+ ((cubrt_unity_a f) .+ (cubrt_unity_b f)) = myfld.zero, exact cubrts_unity_sum_zero f, unfold cubrt_unity_a at tmp, unfold cubrt_unity_b at tmp, unfold cube_root_of_unity, exact tmp, have product_roots_one : root_unity_a .* root_unity_b = myfld.one, rw root_unity_a_h, rw root_unity_b_h, unfold cube_root_of_unity, rw <- myfld.mul_assoc _ (myfld.reciprocal (two f) _) _, rw myfld.mul_comm (myfld.reciprocal (two f) _) _, rw <- myfld.mul_assoc _ (myfld.reciprocal (two f) _) (myfld.reciprocal (two f) _), rw mul_two_reciprocals f (two f) (two f) _ _, rw myfld.mul_assoc _ _ (myfld.reciprocal _ _), rw difference_of_squares f (.- (myfld.one)) _, rw sqrt_squared f _, unfold square, rw mul_negate f _ _, rw mul_negate_alt_simp f _ _, repeat {rw double_negative f _}, rw one_mul_simp f _, unfold two, unfold three, simp, have root_a_reciprocal : ∀ (rta_prf : root_unity_a ≠ myfld.zero), myfld.reciprocal root_unity_a rta_prf = root_unity_b, intros prf, symmetry, exact only_one_reciprocal_alt f root_unity_a root_unity_b _ product_roots_one, have root_b_reciprocal : ∀ (rtb_prf : root_unity_b ≠ myfld.zero), myfld.reciprocal root_unity_b rtb_prf = root_unity_a, intros prf, symmetry, rw myfld.mul_comm at product_roots_one, exact only_one_reciprocal_alt f root_unity_b root_unity_a _ product_roots_one, have sum_alt_roots_minusone : root_unity_a .+ root_unity_b = .- myfld.one, have tmp : (myfld.one .+ (root_unity_a .+ root_unity_b)) .+ (.- myfld.one) = .- myfld.one, rw sum_roots_zero, rw simp_zero f _, rw <- myfld.add_assoc myfld.one (_ .+ _) (.- _) at tmp, rw myfld.add_comm (_ .+ _) (.- myfld.one) at tmp, rw myfld.add_assoc myfld.one (.- myfld.one) _ at tmp, rw myfld.add_negate myfld.one at tmp, rw simp_zero f _ at tmp, exact tmp, have root_a_squ : root_unity_a .* root_unity_a = root_unity_b, have tmp : root_unity_a .+ (myfld.reciprocal root_unity_a rta_n_zero) = .- (myfld.one), rw root_a_reciprocal rta_n_zero, exact sum_alt_roots_minusone, have tmp2 : (root_unity_a .+ (myfld.reciprocal root_unity_a rta_n_zero)) .* root_unity_a = .- root_unity_a, rw tmp, rw mul_negate f _ _, rw one_mul_simp f root_unity_a, clear tmp, rw distrib_simp f _ _ _ at tmp2, rw carry_term_across f (root_unity_a .* root_unity_a) (.- root_unity_a) ((myfld.reciprocal root_unity_a rta_n_zero) .* root_unity_a) at tmp2, rw myfld.mul_comm (myfld.reciprocal _ _) root_unity_a at tmp2, rw myfld.mul_reciprocal root_unity_a _ at tmp2, rw myfld.add_assoc at sum_roots_zero, rw myfld.add_comm (_ .+ _) root_unity_b at sum_roots_zero, rw carry_term_across f _ _ _ at sum_roots_zero, rw <- add_negate _ _ at tmp2, rw simp_zero _ at sum_roots_zero, rw myfld.add_comm root_unity_a myfld.one at tmp2, rw <- sum_roots_zero at tmp2, exact tmp2, have root_b_squ : root_unity_b .* root_unity_b = root_unity_a, rw <- root_a_squ, rw [root_a_squ] {occs := occurrences.pos [2]}, rw <- myfld.mul_assoc, rw product_roots_one, rw <- myfld.mul_one root_unity_a, /-have a_squared_b : root_unity_a .* root_unity_a = root_unity_b, rw root_unity_a_h, rw root_unity_b_h, -/ /- Start by multiplying out all the brackets and cancelling in terms with cubrt * reciprocal (cubrt) .-/ repeat {rw distrib_simp f _ _ _}, repeat {rw distrib_simp_alt f _ _ _}, repeat {rw mul_negate f _ _}, repeat {rw mul_negate_alt_simp f _ _}, repeat {rw double_negative f _}, have tmp : ∀ (x : f), ((x .* cubrt) .* (three f)) = cubrt .* (x .* (three f)) , intro x, simp, rw reciprocal_rewrite f _ _ (tmp root_unity_a) _, rw reciprocal_rewrite f _ _ (tmp root_unity_b) _, /- Some sensible-looking stuff now doesn't work because it's rewriting inside the proofs that are keeping the reciprocals legal. -/ /- To make it work we're gonna need to do a massive only_one_reciprocal.-/ rw only_one_reciprocal f (cubrt .* (root_unity_a .* (three f))) _ (mul_nonzero f cubrt (root_unity_a .* (three f)) cubrt_n_zero (mul_nonzero f root_unity_a (three f) rta_n_zero fld_not_char_three.not_char_three)), rw only_one_reciprocal f (cubrt .* (root_unity_b .* (three f))) _ (mul_nonzero f cubrt (root_unity_b .* (three f)) cubrt_n_zero (mul_nonzero f root_unity_b (three f) rtb_n_zero fld_not_char_three.not_char_three)), repeat {rw myfld.mul_comm _ cubrt}, repeat {rw myfld.mul_assoc cubrt c (myfld.reciprocal _ _) }, repeat {rw myfld.mul_comm cubrt c}, repeat {rw <- myfld.mul_assoc c cubrt (myfld.reciprocal _ _) }, repeat {rw cancel_from_reciprocal_alt f cubrt _ _}, repeat {rw myfld.mul_assoc (c .* _) cubrt _}, repeat {rw <- myfld.mul_assoc c (myfld.reciprocal _ _) cubrt}, repeat {rw cancel_from_reciprocal f cubrt _ _}, /- Now we gather all of the (cubrt^2) terms together, and they cancel out as there is one for each of the cube roots of unity.-/ rw myfld.mul_assoc (cubrt .* root_unity_a) cubrt root_unity_b, rw myfld.mul_comm (cubrt .* root_unity_a) cubrt, repeat {rw myfld.mul_assoc cubrt cubrt _}, repeat {rw <- myfld.mul_assoc (cubrt .* cubrt) _ _}, repeat {rw <- myfld.add_assoc ((cubrt .* cubrt) .* _) _ _}, repeat {rw myfld.add_assoc _ ((cubrt .* cubrt) .* _) _}, repeat {rw myfld.add_comm _ ((cubrt .* cubrt) .* _) }, repeat {rw <- myfld.add_assoc ((cubrt .* cubrt) .* _) _ _}, rw myfld.add_assoc ((cubrt .* cubrt) .* _) ((cubrt .* cubrt) .* _) _, rw <- distrib_simp_alt f (cubrt .* cubrt) _ _, rw myfld.add_assoc ((cubrt .* cubrt) .* _) ((cubrt .* cubrt) .* _) _, rw <- distrib_simp_alt f (cubrt .* cubrt) _ _, rw product_roots_one, rw myfld.add_comm root_unity_a myfld.one, rw <- myfld.add_assoc myfld.one root_unity_a root_unity_b, rw sum_roots_zero, rw zero_mul f _, rw simp_zero f _, /- Now we can do the same with the terms containing a factor of c^2/cubrt^2-/ have tmp2 : ∀ (x y : f), (c .* x) .* (c .* y) = (c .* c) .* (x .* y) , intros x y, rw myfld.mul_assoc (c .* x) c y, rw <- myfld.mul_assoc c x c, rw myfld.mul_comm x c, rw myfld.mul_assoc _ _ _, rw myfld.mul_assoc _ _ _, repeat {rw tmp2 _ _}, clear tmp2, clear tmp, repeat {rw mul_two_reciprocals f _ _ _ _}, /- We now have some convoluted reciprocals that need to be simplified. This needs to be done in sub-proofs so that it can be done in a single step with reciprocal_rewrite.-/ have reciprocal_1 : ((cubrt .* (three f)) .* (cubrt .* (root_unity_a .* (three f)))) = (square f (cubrt .* (three f))) .* root_unity_a, unfold square, simp, rw reciprocal_rewrite f _ _ reciprocal_1 _, have reciprocal_2 : ((cubrt .* (three f)) .* (cubrt .* (root_unity_b .* (three f)))) = (square f (cubrt .* (three f))) .* root_unity_b, unfold square, simp, rw reciprocal_rewrite f _ _ reciprocal_2 _, have reciprocal_3 : ((cubrt .* (root_unity_a .* (three f))) .* (cubrt .* (root_unity_b .* (three f)))) = (square f (cubrt .* (three f))) .* (root_unity_a .* root_unity_b) , unfold square, exact mul_complex f _ _ _ _, rw product_roots_one at reciprocal_3, rw reciprocal_rewrite f _ _ reciprocal_3 _, repeat {rw split_reciprocal f (square f (cubrt .* (three f))) _ _}, repeat {rw myfld.mul_assoc (c .* c) (myfld.reciprocal (square f _) _) (myfld.reciprocal _ _) }, repeat {rw myfld.add_comm _ (((c .* c) .* (myfld.reciprocal _ _)) .* (myfld.reciprocal _ _)) }, repeat {rw myfld.add_assoc _ (((c .* c) .* (myfld.reciprocal _ _)) .* (myfld.reciprocal _ _)) _}, repeat {rw myfld.add_comm _ (((c .* c) .* (myfld.reciprocal _ _)) .* (myfld.reciprocal _ _)) }, repeat {rw <- myfld.add_assoc (((c .* c) .* (myfld.reciprocal _ _)) .* (myfld.reciprocal _ _)) _ _}, repeat {rw myfld.add_assoc _ (((c .* c) .* (myfld.reciprocal _ _)) .* (myfld.reciprocal _ _)) _}, repeat {rw myfld.add_comm _ (((c .* c) .* (myfld.reciprocal _ _)) .* (myfld.reciprocal _ _)) }, rw <- myfld.add_assoc (((c .* c) .* (myfld.reciprocal _ _)) .* (myfld.reciprocal _ _)) _ _, rw myfld.add_assoc (((c .* c) .* (myfld.reciprocal _ _)) .* (myfld.reciprocal _ _)) (((c .* c) .* (myfld.reciprocal _ _)) .* (myfld.reciprocal _ _)) _, rw <- distrib_simp_alt f ((c .* c) .* (myfld.reciprocal _ _)) _ _, repeat {rw <- myfld.add_assoc (((c .* c) .* (myfld.reciprocal _ _)) .* (myfld.reciprocal _ _)) _ _}, rw myfld.add_assoc (((c .* c) .* (myfld.reciprocal _ _)) .* _) (((c .* c) .* (myfld.reciprocal _ _)) .* _) _, rw <- distrib_simp_alt f ((c .* c) .* (myfld.reciprocal _ _)) _ _, rw root_a_reciprocal _, rw root_b_reciprocal _, rw recip_one_one f _, rw myfld.add_comm root_unity_b myfld.one, rw <- myfld.add_assoc myfld.one root_unity_b root_unity_a, rw myfld.add_comm root_unity_b root_unity_a, rw sum_roots_zero, rw zero_mul f _, rw simp_zero f _, clear reciprocal_1, clear reciprocal_2, clear reciprocal_3, /- Some minor cancellation that should maybe have been done earlier but wasn't...-/ rw myfld.mul_comm cubrt root_unity_a, repeat {rw <- myfld.mul_assoc root_unity_a cubrt (_ .* _) }, rw myfld.mul_assoc cubrt c (myfld.reciprocal _ _), rw myfld.mul_comm cubrt c, rw <- myfld.mul_assoc c cubrt (myfld.reciprocal _ _), rw cancel_from_reciprocal_alt f cubrt _ _, clear cubrt_h, /- This also lets us get rid of the cubrt variable entirely, which is nice.-/ repeat {rw split_reciprocal f _ _ _}, rw only_one_reciprocal f root_unity_a _ rta_n_zero, rw only_one_reciprocal f root_unity_b _ rtb_n_zero, rw only_one_reciprocal f (three f) _ fld_not_char_three.not_char_three, clear cubrt_n_zero, clear cubrt, repeat {rw <- add_negate f _ _}, repeat {rw root_a_reciprocal _}, repeat {rw root_b_reciprocal _}, clear root_a_reciprocal, clear root_b_reciprocal, clear rta_n_zero, clear rtb_n_zero, clear root_unity_a_h, clear root_unity_b_h, /- Every remainining term is a factor of c/3, so we can pull that out.-/ rw myfld.mul_assoc root_unity_a c (_ .* _), rw myfld.mul_comm root_unity_a c, repeat {rw <- myfld.mul_assoc c _ _}, repeat {rw <- distrib_simp_alt f c _ _}, rw myfld.mul_assoc root_unity_a root_unity_a _, rw root_a_squ, clear root_a_squ, rw myfld.mul_comm (root_unity_b .* _) root_unity_b, rw myfld.mul_assoc root_unity_b root_unity_b _, rw root_b_squ, clear root_b_squ, repeat {rw myfld.mul_comm _ (myfld.reciprocal (three f) _) }, repeat {rw <- distrib_simp_alt f (myfld.reciprocal (three f) _) _ _}, /- And now we have -c * 1/3 * -3, so c.-/ rw myfld.add_comm root_unity_b root_unity_a, rw sum_alt_roots_minusone, repeat {rw <- add_negate f _ _}, rw <- mul_negate_alt f (myfld.reciprocal (three f) _) (_ .+ _), rw <- mul_negate_alt f _ _, rw double_negative f _, rw myfld.mul_comm (myfld.reciprocal _ _) (_ .+ _), unfold three, rw <- myfld.add_assoc myfld.one myfld.one myfld.one, rw myfld.mul_reciprocal (myfld.one .+ (myfld.one .+ myfld.one)) _, symmetry, exact myfld.mul_one c, unfold cardano_formula_a, unfold cardano_formula_b, unfold cardano_formula_c, unfold cardano_formula, unfold alt_cubrt_a, unfold alt_cubrt_b, have tmp1 : (fld_with_cube_root.cubrt ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d))) = (fld_with_cube_root.cubrt ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d))), refl, have tmp2 : (cube_root_of_unity f (sqroot (.- (three f))) (fld_with_sqrt.sqrt_mul_sqrt (.- (three f)))) = (cube_root_of_unity f (sqroot (.- (three f))) (fld_with_sqrt.sqrt_mul_sqrt (.- (three f)))), refl, have tmp3 : (cube_root_of_unity f (.- (sqroot (.- (three f)))) (negative_sqrt f (.- (three f)))) = (cube_root_of_unity f (.- (sqroot (.- (three f)))) (negative_sqrt f (.- (three f)))), refl, exact folded_version (fld_with_cube_root.cubrt ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d))) (cube_root_of_unity f (sqroot (.- (three f))) (fld_with_sqrt.sqrt_mul_sqrt (.- (three f)))) (cube_root_of_unity f (.- (sqroot (.- (three f)))) (negative_sqrt f (.- (three f)))) (cubrt_nonzero f ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d)) (cardano_den_not_zero_int f c d c_ne_zero)) (cubrt_unity_nonzero f (sqroot (.- (three f))) (fld_with_sqrt.sqrt_mul_sqrt (.- (three f)))) (cubrt_unity_nonzero f (.- (sqroot (.- (three f)))) (negative_sqrt f (.- (three f)))) tmp1 tmp2 tmp3, /- You tried to do this bit with mathlib, which would have made it prettier. However, the display bugs and over-aggressive rewriter made it impractical.-/ /-set cubrt := (fld_with_cube_root.cubrt ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d))), set root_unity_a := (cube_root_of_unity f (sqroot (.- (three f))) (fld_with_sqrt.sqrt_mul_sqrt (.- (three f)))) with rt_unity_a_h, repeat {rw split_reciprocal f _ _ _}, have tmp : (cube_root_of_unity f (sqroot (.- (three f))) (fld_with_sqrt.sqrt_mul_sqrt (.- (three f)))) = root_unity_a, rw rt_unity_a_h, rw reciprocal_rewrite f (cube_root_of_unity f (sqroot (.- (three f))) (fld_with_sqrt.sqrt_mul_sqrt (.- (three f)))) root_unity_a tmp _, rw reciprocal_rewrite f (cube_root_of_unity f (sqroot (.- (three f))) (fld_with_sqrt.sqrt_mul_sqrt (.- (three f)))) root_unity_a tmp _, -/ end /- This is used to end the next proof, because that's long enough that it's starting to lag visual studio, so moving part of it out to somewhere else seems smart.-/ lemma cardano_product_helper (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d : f) (c_ne_zero : c ≠ myfld.zero) : (((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d)) .+ (.- ((((myfld.reciprocal ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d)) (cardano_den_not_zero_int f c d c_ne_zero)) .* (myfld.reciprocal ((three f) .* ((three f) .* (three f))) (mul_nonzero f (three f) ((three f) .* (three f)) fld_not_char_three.not_char_three (mul_nonzero f (three f) (three f) fld_not_char_three.not_char_three fld_not_char_three.not_char_three)))) .* (c .* c)) .* c))) = .- d := begin /- Start by rationalising the denominator.-/ have tmp_rat_den : (myfld.reciprocal ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d)) (cardano_den_not_zero_int f c d c_ne_zero)) = ((myfld.reciprocal ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d)) (cardano_den_not_zero_int f c d c_ne_zero)) .* ((myfld.reciprocal ((cardano_intermediate_val f c d) .+ (.- (cardano_other_int_val f d))) (cardano_den_not_zero_int_alt f c d c_ne_zero)) .* ((cardano_intermediate_val f c d) .+ (.- (cardano_other_int_val f d))))), rw myfld.mul_comm (myfld.reciprocal _ _) (_ .+ _), rw myfld.mul_reciprocal _ _, rw simp_mul_one f _, rw tmp_rat_den, clear tmp_rat_den, rw myfld.mul_assoc (myfld.reciprocal _ _) (myfld.reciprocal _ _) _, rw mul_two_reciprocals f _ _ _ _, rw reciprocal_rewrite f _ _ (difference_of_squares f _ _) _, /- Now we can simplify the denominator.-/ rw myfld.mul_comm _ (myfld.reciprocal (_ .* _) _), rw myfld.mul_assoc (myfld.reciprocal _ _) (myfld.reciprocal _ _) _, rw mul_two_reciprocals f _ _ _ _, have denom_simp : (((three f) .* ((three f) .* (three f))) .* ((square f (cardano_intermediate_val f c d)) .+ (.- (square f (cardano_other_int_val f d))))) = c .* (c .* c) , unfold cardano_intermediate_val, unfold cardano_other_int_val, rw sqrt_squared f _, unfold square, repeat {rw mul_negate_alt_simp f _ _}, rw double_negative f _, rw [ (myfld.mul_comm d (myfld.reciprocal _ _)) ] {occs := occurrences.pos [2]}, rw mul_negate f _ _, rw myfld.mul_assoc (d .* _) _ d, rw <- myfld.mul_assoc d (myfld.reciprocal _ _) (myfld.reciprocal _ _), rw mul_two_reciprocals f (two f) (two f) _ _, rw myfld.mul_comm (_ .* _) d, rw myfld.mul_assoc d d _, rw myfld.add_comm _ (.- (_ .* _)), rw myfld.add_assoc (.- _) (_ .* _), unfold four, rw myfld.add_comm (.- _) _, rw reciprocal_rewrite f _ _ (two_plus_two f) _, rw only_one_reciprocal f ((two f) .* (two f)) _ (mul_nonzero f (two f) (two f) fld_not_char_two.not_char_two fld_not_char_two.not_char_two), rw myfld.add_negate _, rw simp_zero f _, rw myfld.mul_assoc ((three f) .* _) (cubed f c) _, rw myfld.mul_comm _ (cubed f c), unfold twenty_seven, unfold nine, rw <- myfld.mul_assoc (cubed f c) ((three f) .* _) (myfld.reciprocal _ _), rw myfld.mul_reciprocal _ _, unfold cubed, simp, rw reciprocal_rewrite f _ _ denom_simp _, /- The c^3 on the numerator now cancels with the denominator.-/ repeat {rw <- myfld.mul_assoc}, rw myfld.mul_comm _ ((c .* c) .* c), rw myfld.mul_assoc (myfld.reciprocal _ _) ((c .* c) .* c) _, rw <- myfld.mul_assoc c c c, rw myfld.mul_comm (myfld.reciprocal _ _) (c .* (c .* c)), rw myfld.mul_reciprocal (c .* (c .* c)) _, rw one_mul_simp f _, clear denom_simp, /- The positive intermediate_val cancels with the negative...-/ rw add_negate f _ _, rw double_negative f _, rw myfld.add_assoc (_ .+ _) (.- _) _, rw <- myfld.add_assoc _ _ (.- _), rw myfld.add_comm _ (.- _), rw myfld.add_assoc _ (.- _) _, rw myfld.add_negate _, rw simp_zero f _, /- And ifnally we have to copies of other_int_value added to each other. Each of these is just -d/2, so they add to -d.-/ unfold cardano_other_int_val, rw <- add_negate f _ _, rw <- distrib_simp_alt f d _ _, rw only_one_reciprocal f (two f) _ (two_ne_zero f), rw add_two_halves f, rw simp_mul_one f _, end lemma cardano_product (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d : f) (c_ne_zero : c ≠ myfld.zero) : ((cardano_formula_a f c d c_ne_zero) .* ((cardano_formula_b f c d c_ne_zero) .* (cardano_formula_c f c d c_ne_zero))) = .- (d) := begin /- Again, this line is hideous but actually makes the proof easier to follow in the long run.-/ have folded_version : ∀ (cubrt root_unity_a root_unity_b : f), ∀ (cubrt_ne_zero : cubrt ≠ myfld.zero), ∀ (root_unity_a_ne_zero : root_unity_a ≠ myfld.zero), ∀ (root_unity_b_ne_zero : root_unity_b ≠ myfld.zero), (cubrt = (fld_with_cube_root.cubrt ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d))) -> root_unity_a = (cube_root_of_unity f (sqroot (.- (three f))) (fld_with_sqrt.sqrt_mul_sqrt (.- (three f)))) -> root_unity_b = (cube_root_of_unity f (.- (sqroot (.- (three f)))) (negative_sqrt f (.- (three f)))) -> (cubrt .+ (.- (c .* (myfld.reciprocal (cubrt .* (three f)) (mul_nonzero f cubrt (three f) cubrt_ne_zero fld_not_char_three.not_char_three))))) .* (((root_unity_a .* cubrt) .+ (.- (c .* (myfld.reciprocal ((root_unity_a .* cubrt) .* (three f)) (mul_nonzero f (root_unity_a .* cubrt) (three f) (mul_nonzero f root_unity_a cubrt root_unity_a_ne_zero cubrt_ne_zero) fld_not_char_three.not_char_three))))) .* ((root_unity_b .* cubrt) .+ (.- (c .* (myfld.reciprocal ((root_unity_b .* cubrt) .* (three f)) (mul_nonzero f (root_unity_b .* cubrt) (three f) (mul_nonzero f root_unity_b cubrt root_unity_b_ne_zero cubrt_ne_zero) fld_not_char_three.not_char_three)))))) = (.- d)), intros cubrt root_unity_a root_unity_b cubrt_ne_zero rta_n_zero rtb_n_zero cubrt_h root_unity_a_h root_unity_b_h, /- TODO: Move all of this crap to somewhere where both sub-proofs can refer to it rather than having all this duplication.-/ have product_roots_one : root_unity_a .* root_unity_b = myfld.one, rw root_unity_a_h, rw root_unity_b_h, unfold cube_root_of_unity, rw <- myfld.mul_assoc _ (myfld.reciprocal (two f) _) _, rw myfld.mul_comm (myfld.reciprocal (two f) _) _, rw <- myfld.mul_assoc _ (myfld.reciprocal (two f) _) (myfld.reciprocal (two f) _), rw mul_two_reciprocals f (two f) (two f) _ _, rw myfld.mul_assoc _ _ (myfld.reciprocal _ _), rw difference_of_squares f (.- (myfld.one)) _, rw sqrt_squared f _, unfold square, rw mul_negate f _ _, rw mul_negate_alt_simp f _ _, repeat {rw double_negative f _}, rw one_mul_simp f _, unfold two, unfold three, simp, have sum_roots_zero : myfld.one .+ (root_unity_a .+ root_unity_b) = myfld.zero, rw root_unity_a_h, rw root_unity_b_h, have tmp : myfld.one .+ ((cubrt_unity_a f) .+ (cubrt_unity_b f)) = myfld.zero, exact cubrts_unity_sum_zero f, unfold cubrt_unity_a at tmp, unfold cubrt_unity_b at tmp, unfold cube_root_of_unity, exact tmp, have root_a_reciprocal : ∀ (rta_prf : root_unity_a ≠ myfld.zero), myfld.reciprocal root_unity_a rta_prf = root_unity_b, intros prf, symmetry, exact only_one_reciprocal_alt f root_unity_a root_unity_b _ product_roots_one, have root_b_reciprocal : ∀ (rtb_prf : root_unity_b ≠ myfld.zero), myfld.reciprocal root_unity_b rtb_prf = root_unity_a, intros prf, symmetry, rw myfld.mul_comm at product_roots_one, exact only_one_reciprocal_alt f root_unity_b root_unity_a _ product_roots_one, have sum_alt_roots_minusone : root_unity_a .+ root_unity_b = .- myfld.one, have tmp : (myfld.one .+ (root_unity_a .+ root_unity_b)) .+ (.- myfld.one) = .- myfld.one, rw sum_roots_zero, rw simp_zero f _, rw <- myfld.add_assoc myfld.one (_ .+ _) (.- _) at tmp, rw myfld.add_comm (_ .+ _) (.- myfld.one) at tmp, rw myfld.add_assoc myfld.one (.- myfld.one) _ at tmp, rw myfld.add_negate myfld.one at tmp, rw simp_zero f _ at tmp, exact tmp, have root_a_squ : root_unity_a .* root_unity_a = root_unity_b, have tmp : root_unity_a .+ (myfld.reciprocal root_unity_a rta_n_zero) = .- (myfld.one), rw root_a_reciprocal rta_n_zero, exact sum_alt_roots_minusone, have tmp2 : (root_unity_a .+ (myfld.reciprocal root_unity_a rta_n_zero)) .* root_unity_a = .- root_unity_a, rw tmp, rw mul_negate f _ _, rw one_mul_simp f root_unity_a, clear tmp, rw distrib_simp f _ _ _ at tmp2, rw carry_term_across f (root_unity_a .* root_unity_a) (.- root_unity_a) ((myfld.reciprocal root_unity_a rta_n_zero) .* root_unity_a) at tmp2, rw myfld.mul_comm (myfld.reciprocal _ _) root_unity_a at tmp2, rw myfld.mul_reciprocal root_unity_a _ at tmp2, rw myfld.add_assoc at sum_roots_zero, rw myfld.add_comm (_ .+ _) root_unity_b at sum_roots_zero, rw carry_term_across f _ _ _ at sum_roots_zero, rw <- add_negate _ _ at tmp2, rw simp_zero _ at sum_roots_zero, rw myfld.add_comm root_unity_a myfld.one at tmp2, rw <- sum_roots_zero at tmp2, exact tmp2, have root_b_squ : root_unity_b .* root_unity_b = root_unity_a, rw <- root_a_squ, rw [root_a_squ] {occs := occurrences.pos [2]}, rw <- myfld.mul_assoc, rw product_roots_one, rw <- myfld.mul_one root_unity_a, repeat {rw distrib_simp f _ _ _}, repeat {rw distrib_simp_alt f _ _ _}, /- First cancel cubrt and 1/cubrt in some terms.-/ repeat {rw mul_negate f _ _}, repeat {rw mul_negate_alt_simp f _ _}, repeat {rw double_negative f _}, repeat {rw myfld.mul_comm c (myfld.reciprocal _ _) }, repeat {rw <- myfld.mul_assoc (myfld.reciprocal _ _) c _}, repeat {rw myfld.mul_assoc cubrt (myfld.reciprocal _ _) _}, rw myfld.mul_assoc (_ .* cubrt) (myfld.reciprocal _ _) _, rw <- myfld.mul_assoc _ cubrt (myfld.reciprocal _ _), have tmp : ∀ (rt : f), ((rt .* cubrt) .* (three f)) = cubrt .* (rt .* (three f)) , simp, repeat {rw reciprocal_rewrite f _ _ (tmp _) _}, repeat {rw cancel_from_reciprocal_alt f cubrt _ _}, /- Some of this bit is slightly more convoluted than you'd expect so as to avoid making the result type-incorrect by rewriting in a reciprocal as collateral damage.-/ rw myfld.mul_assoc c (root_unity_a .* cubrt) (root_unity_b .* cubrt), rw myfld.mul_assoc c root_unity_a cubrt, rw myfld.mul_comm (c .* root_unity_a) cubrt, rw <- myfld.mul_assoc cubrt (c .* root_unity_a) _, rw myfld.mul_assoc (myfld.reciprocal _ _) cubrt _, rw myfld.mul_assoc c root_unity_b cubrt, rw myfld.mul_comm (c .* root_unity_b) cubrt, repeat {rw myfld.mul_assoc (myfld.reciprocal _ _) cubrt _}, repeat {rw cancel_from_reciprocal f cubrt _ _}, /- We can now collect like terms together, as three terms have a factor of cubrt and three terms have a factor of 1/cubrt.-/ repeat {rw myfld.mul_comm (myfld.reciprocal _ _) cubrt}, rw <- myfld.add_assoc (.- _) _ _, rw myfld.add_assoc _ (.- _) _, repeat {rw myfld.add_comm _ (.- _) }, rw <- myfld.add_assoc (.- _) _ _, rw myfld.add_assoc _ (.- _) _, repeat {rw myfld.add_comm _ (.- _) }, rw myfld.add_assoc (.- _) (.- _) _, rw <- add_negate f _ _, repeat {rw <- myfld.add_assoc (.- _) _ _}, rw myfld.add_assoc (.- _) (.- _) _, rw <- add_negate f _ _, rw myfld.mul_assoc (c .* root_unity_a) root_unity_b cubrt, rw myfld.mul_assoc (myfld.reciprocal (three f) _) (_ .* _) cubrt, rw myfld.mul_comm (_ .* _) cubrt, rw <- myfld.mul_assoc cubrt _ _, rw <- distrib_simp_alt f cubrt _ _, rw <- distrib_simp_alt f cubrt _ _, /- cubrt term done, now 1/cubrt term-/ have tmp2 : (cubrt .* (root_unity_b .* (three f))) = ((cubrt .* (three f)) .* root_unity_b), simp, rw reciprocal_rewrite f _ _ tmp2 _, rw split_reciprocal f (cubrt .* (three f)) _ _, rw <- myfld.mul_assoc (myfld.reciprocal (cubrt .* (three f)) _) _ _, rw myfld.mul_assoc _ (myfld.reciprocal (cubrt .* (three f)) _) _, rw myfld.mul_comm _ (myfld.reciprocal (cubrt .* (three f)) _), rw <- myfld.mul_assoc (myfld.reciprocal (cubrt .* (three f)) _) _ _, rw myfld.mul_assoc _ (myfld.reciprocal (cubrt .* (three f)) _) _, rw myfld.mul_comm _ (myfld.reciprocal (cubrt .* (three f)) _), rw <- myfld.mul_assoc (myfld.reciprocal (cubrt .* (three f)) _) _ _, rw only_one_reciprocal f (cubrt .* (three f)) _ (mul_nonzero f cubrt (three f) cubrt_ne_zero fld_not_char_three.not_char_three), rw myfld.add_comm (.- _) ((myfld.reciprocal (cubrt .* (three f)) _) .* _), rw myfld.add_assoc ((myfld.reciprocal (cubrt .* (three f)) _) .* _) ((myfld.reciprocal (cubrt .* (three f)) _) .* _) (.- _), rw <- distrib_simp_alt f (myfld.reciprocal (cubrt .* (three f)) _) _ _, repeat {rw <- myfld.add_assoc _ _ _}, rw myfld.add_assoc ((myfld.reciprocal (cubrt .* (three f)) _) .* _) ((myfld.reciprocal (cubrt .* (three f)) _) .* _) (.- _), rw <- distrib_simp_alt f (myfld.reciprocal (cubrt .* (three f)) _) _ _, /- The cubrt terms do in fact sum to zero.-/ repeat {rw myfld.mul_comm _ c}, repeat {rw myfld.mul_assoc _ c _}, repeat {rw <- myfld.mul_assoc c _ _}, repeat {rw myfld.mul_assoc _ c _}, repeat {rw myfld.mul_comm (myfld.reciprocal _ _) c}, repeat {rw <- myfld.mul_assoc c _ _}, rw <- distrib_simp_alt f c _ _, rw <- distrib_simp_alt f c _ _, repeat {rw reciprocal_rewrite f (_ .* (three f)) ((three f) .* _) (myfld.mul_comm _ (three f)) }, rw myfld.mul_comm root_unity_a (myfld.reciprocal _ _), rw split_reciprocal f (three f) _ _, rw split_reciprocal f (three f) _ _, repeat {rw <- myfld.mul_assoc (myfld.reciprocal (three f) _) _ _}, rw only_one_reciprocal f (three f) _ fld_not_char_three.not_char_three, rw <- distrib_simp_alt f (myfld.reciprocal (three f) _) _ _, rw <- distrib_simp_alt f (myfld.reciprocal (three f) _) _ _, rw product_roots_one, rw root_a_reciprocal _, rw root_b_reciprocal _, rw root_a_squ, rw root_b_squ, rw sum_roots_zero, repeat {rw zero_mul f _}, rw negate_zero_zero f, rw simp_zero f _, /- And so do the 1/cubrt terms.-/ rw myfld.mul_comm root_unity_b c, rw <- myfld.mul_assoc c root_unity_b root_unity_a, rw myfld.mul_assoc (myfld.reciprocal _ _) c (root_unity_b .* root_unity_a), rw myfld.mul_comm (myfld.reciprocal (three f) _) c, rw <- myfld.mul_assoc c (myfld.reciprocal (three f) _) (root_unity_b .* root_unity_a), repeat {rw myfld.mul_assoc c c _}, repeat {rw myfld.mul_assoc (c .* c) (myfld.reciprocal (three f) _) _}, rw <- distrib_simp_alt f ((c .* c) .* (myfld.reciprocal (three f) _)) _ _, rw <- distrib_simp_alt f ((c .* c) .* (myfld.reciprocal (three f) _)) _ _, rw myfld.mul_comm root_unity_b root_unity_a, rw product_roots_one, rw myfld.add_comm root_unity_b root_unity_a, rw sum_roots_zero, repeat {rw zero_mul f _}, rw simp_zero f _, /- Minor simplifications that should maybe have been done earlier.-/ rw myfld.mul_assoc (root_unity_a .* cubrt) root_unity_b cubrt, rw [ (myfld.mul_comm root_unity_a cubrt) ] {occs := occurrences.pos [1]}, rw <- myfld.mul_assoc cubrt root_unity_a root_unity_b, rw product_roots_one, rw simp_mul_one f _, rw myfld.mul_comm c ((_ .* _) .* _), repeat {rw myfld.mul_assoc _ _ _}, repeat {rw <- myfld.mul_assoc _ _ _}, rw myfld.mul_assoc (myfld.reciprocal _ _) (myfld.reciprocal _ _), rw mul_two_reciprocals f _ _ _ _, rw myfld.mul_assoc (myfld.reciprocal _ _) (myfld.reciprocal _ _), rw mul_two_reciprocals f _ _ _ _, have den_reorder : ((((three f) .* cubrt) .* (cubrt .* (root_unity_a .* (three f)))) .* ((three f) .* cubrt)) = (((cubrt .* (cubrt .* cubrt)) .* ((three f) .* ((three f) .* (three f)))) .* root_unity_a), rw myfld.mul_comm root_unity_a (three f), rw myfld.mul_assoc cubrt (three f) root_unity_a, repeat {rw myfld.mul_comm (three f) cubrt}, rw <- myfld.mul_assoc (cubrt .* (three f)) _ (cubrt .* (three f)), rw myfld.mul_comm (_ .* root_unity_a) _, repeat {rw <- myfld.mul_assoc cubrt _ _}, repeat {rw myfld.mul_assoc _ cubrt _}, rw myfld.mul_comm (three f) cubrt, repeat {rw <- myfld.mul_assoc cubrt _ _}, repeat {rw myfld.mul_assoc _ cubrt _}, rw myfld.mul_comm (three f) cubrt, repeat {rw myfld.mul_assoc}, rw reciprocal_rewrite f _ _ den_reorder _, rw split_reciprocal f _ root_unity_a _, rw root_a_reciprocal _, repeat {rw <- myfld.mul_assoc}, rw myfld.mul_comm c (root_unity_a .* c), rw myfld.mul_assoc root_unity_b (_ .* _) c, rw myfld.mul_assoc root_unity_b root_unity_a c, rw myfld.mul_comm root_unity_b root_unity_a, rw product_roots_one, rw one_mul f c, /- Now that we only have two fractions left, simplifying the proofs that enable those reciprocals to exist will allow us to throw away all the lemmae about roots, as they are no longer relevant.-/ rw split_reciprocal f (_ .* (_ .* _)) (_ .* (_ .* _)) _, rw only_one_reciprocal f (cubrt .* (cubrt .* cubrt)) _ (mul_nonzero f cubrt (cubrt .* cubrt) cubrt_ne_zero (mul_nonzero f cubrt cubrt cubrt_ne_zero cubrt_ne_zero)), rw only_one_reciprocal f ((three f) .* ((three f) .* (three f))) _ (mul_nonzero f (three f) ((three f) .* (three f)) fld_not_char_three.not_char_three (mul_nonzero f (three f) (three f) fld_not_char_three.not_char_three fld_not_char_three.not_char_three)), clear tmp tmp2 den_reorder root_a_squ root_b_squ sum_alt_roots_minusone root_a_reciprocal root_b_reciprocal sum_roots_zero product_roots_one root_unity_a_h root_unity_b_h rta_n_zero rtb_n_zero root_unity_a root_unity_b, rw myfld.mul_comm c (_ .* _), /- We now have cubrt * (cubrt * cubrt) in some places. As cubrt is a cube root this can be rewritten according to the definition of the cube root.-/ have cubrt_cubed : (cubrt .* (cubrt .* cubrt)) = (cardano_intermediate_val f c d) .+ (cardano_other_int_val f d) , rw myfld.mul_assoc, rw cubrt_h, rw fld_with_cube_root.cubrt_cubed, rw reciprocal_rewrite f _ _ cubrt_cubed _, rw [cubrt_cubed] {occs := occurrences.pos [1]}, rw only_one_reciprocal f _ _ (cardano_den_not_zero_int f c d c_ne_zero), clear cubrt_cubed cubrt_h cubrt_ne_zero cubrt, /- The remaining simplification is outsourced to a separate lemma, as this one is already large enough to lag VS.-/ exact cardano_product_helper f c d c_ne_zero, unfold cardano_formula_a, unfold cardano_formula_b, unfold cardano_formula_c, unfold cardano_formula, unfold alt_cubrt_a, unfold alt_cubrt_b, have tmp1 : (fld_with_cube_root.cubrt ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d))) = (fld_with_cube_root.cubrt ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d))), refl, have tmp2 : (cube_root_of_unity f (sqroot (.- (three f))) (fld_with_sqrt.sqrt_mul_sqrt (.- (three f)))) = (cube_root_of_unity f (sqroot (.- (three f))) (fld_with_sqrt.sqrt_mul_sqrt (.- (three f)))), refl, have tmp3 : (cube_root_of_unity f (.- (sqroot (.- (three f)))) (negative_sqrt f (.- (three f)))) = (cube_root_of_unity f (.- (sqroot (.- (three f)))) (negative_sqrt f (.- (three f)))), refl, exact folded_version (fld_with_cube_root.cubrt ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d))) (cube_root_of_unity f (sqroot (.- (three f))) (fld_with_sqrt.sqrt_mul_sqrt (.- (three f)))) (cube_root_of_unity f (.- (sqroot (.- (three f)))) (negative_sqrt f (.- (three f)))) (cubrt_nonzero f ((cardano_intermediate_val f c d) .+ (cardano_other_int_val f d)) (cardano_den_not_zero_int f c d c_ne_zero)) (cubrt_unity_nonzero f (sqroot (.- (three f))) (fld_with_sqrt.sqrt_mul_sqrt (.- (three f)))) (cubrt_unity_nonzero f (.- (sqroot (.- (three f)))) (negative_sqrt f (.- (three f)))) tmp1 tmp2 tmp3, end /- Now we do uniqueness. As every cubic is equivalent to a depressed cubic, it is sufficient to prove this for the general depressed cubic.-/ lemma depressed_cubic_factorize (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d x : f) (c_ne_zero : c ≠ myfld.zero) : (depressed_cubic_subst f c d x) = (factorized_cubic_expression f x (cardano_formula_a f c d c_ne_zero) (cardano_formula_b f c d c_ne_zero) (cardano_formula_c f c d c_ne_zero)) := begin rw multiply_out_cubic f x _ _ _, rw cardano_formulae_sum_zero f, rw mul_zero f (x .* x), rw negate_zero_zero f, rw simp_zero f, rw cardano_products f c d x c_ne_zero, rw cardano_product f, rw double_negative f d, unfold depressed_cubic_subst, rw myfld.mul_comm x c, end lemma cardano_formula_uniqueness (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (c d x : f) (c_ne_zero : c ≠ myfld.zero) : (x ≠ (cardano_formula_a f c d c_ne_zero)) -> (x ≠ (cardano_formula_b f c d c_ne_zero)) -> (x ≠ (cardano_formula_c f c d c_ne_zero)) -> ((depressed_cubic_subst f c d x) ≠ myfld.zero) := begin have h : factorized_cubic_expression f x (cardano_formula_a f c d c_ne_zero) (cardano_formula_b f c d c_ne_zero) (cardano_formula_c f c d c_ne_zero) = depressed_cubic_subst f c d x, symmetry, exact depressed_cubic_factorize f c d x c_ne_zero, intros not_formula_a not_formula_b not_formula_c solution, unfold factorized_cubic_expression at h, rw solution at h, have ne_zero_a : (x .+ (.- (cardano_formula_a f c d c_ne_zero))) ≠ myfld.zero, exact subtract_ne f x (cardano_formula_a f c d c_ne_zero) not_formula_a, have ne_zero_b : (x .+ (.- (cardano_formula_b f c d c_ne_zero))) ≠ myfld.zero, exact subtract_ne f x (cardano_formula_b f c d c_ne_zero) not_formula_b, have ne_zero_c : (x .+ (.- (cardano_formula_c f c d c_ne_zero))) ≠ myfld.zero, exact subtract_ne f x (cardano_formula_c f c d c_ne_zero) not_formula_c, exact (mul_nonzero f ((x .+ (.- (cardano_formula_a f c d c_ne_zero))) .* (x .+ (.- (cardano_formula_b f c d c_ne_zero)))) (x .+ (.- (cardano_formula_c f c d c_ne_zero))) (mul_nonzero f (x .+ (.- (cardano_formula_a f c d c_ne_zero))) (x .+ (.- (cardano_formula_b f c d c_ne_zero))) ne_zero_a ne_zero_b) ne_zero_c) h, end lemma cubic_formula_uniqueness (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a1 b c d x : f) (a_ne_zero : a1 ≠ myfld.zero) (int_quantity_ne_zero : ((three f) .* (a1 .* c)) .+ (.- (square f b)) ≠ myfld.zero) : (x ≠ (cubic_formula_a f a1 b c d a_ne_zero int_quantity_ne_zero)) -> (x ≠ (cubic_formula_b f a1 b c d a_ne_zero int_quantity_ne_zero)) -> (x ≠ (cubic_formula_c f a1 b c d a_ne_zero int_quantity_ne_zero)) -> ((cubic_subst f a1 b c d x) ≠ myfld.zero) := begin intros ha hb hc, have move_term : ∀ (q : f), x ≠ q .+ (.- ((b .* (myfld.reciprocal a1 a_ne_zero)) .* (third f))) <-> (x .+ ((b .* (myfld.reciprocal a1 a_ne_zero)) .* (third f))) ≠ q, intros q, split, intros h1 h2, rw <- h2 at h1, clear h2, rw <- myfld.add_assoc at h1, rw myfld.add_negate at h1, rw zero_simp f x at h1, cc, intros h1 h2, rw h2 at h1, clear h2, rw <- myfld.add_assoc at h1, rw myfld.add_comm (.- _) _ at h1, rw myfld.add_negate at h1, rw zero_simp f q at h1, cc, unfold cubic_formula_a at ha, rw move_term _ at ha, unfold cubic_formula_b at hb, rw move_term _ at hb, unfold cubic_formula_c at hc, rw move_term _ at hc, intros is_solution, rw divide_cubic_through f a1 b c d _ a_ne_zero at is_solution, have tmp : x = (x .+ ((b .* (myfld.reciprocal a1 a_ne_zero)) .* (third f))) .+ (.- ((b .* (myfld.reciprocal a1 a_ne_zero)) .* (third f))) , rw <- myfld.add_assoc, rw myfld.add_negate, exact myfld.add_zero x, rw (reduce_cubic_to_depressed f (b .* (myfld.reciprocal a1 a_ne_zero)) (c .* (myfld.reciprocal a1 a_ne_zero)) (d .* (myfld.reciprocal a1 a_ne_zero)) x (x .+ ((b .* (myfld.reciprocal a1 a_ne_zero)) .* (third f))) tmp) at is_solution, exact cardano_formula_uniqueness f _ _ _ (int_quantity_ne_zero_simp f a1 b c a_ne_zero int_quantity_ne_zero) ha hb hc is_solution, end lemma cubic_formula_alt_uniqueness (f : Type) [myfld f] [fld_with_sqrt f] [fld_with_cube_root f] [fld_not_char_two f] [fld_not_char_three f] (a1 b c d x : f) (a_ne_zero : a1 ≠ myfld.zero) (int_quantity_eq_zero : ((three f) .* (a1 .* c)) .+ (.- (square f b)) = myfld.zero) : (x ≠ (cubic_formula_a_alt f a1 b c d a_ne_zero int_quantity_eq_zero)) -> (x ≠ (cubic_formula_b_alt f a1 b c d a_ne_zero int_quantity_eq_zero)) -> (x ≠ (cubic_formula_c_alt f a1 b c d a_ne_zero int_quantity_eq_zero)) -> ((cubic_subst f a1 b c d x) ≠ myfld.zero) := begin intros ha hb hc is_solution, rw divide_cubic_through f a1 b c d _ a_ne_zero at is_solution, have tmp : x = (x .+ ((b .* (myfld.reciprocal a1 a_ne_zero)) .* (third f))) .+ (.- ((b .* (myfld.reciprocal a1 a_ne_zero)) .* (third f))) , rw <- myfld.add_assoc, rw myfld.add_negate, exact myfld.add_zero x, rw (reduce_cubic_to_depressed f (b .* (myfld.reciprocal a1 a_ne_zero)) (c .* (myfld.reciprocal a1 a_ne_zero)) (d .* (myfld.reciprocal a1 a_ne_zero)) x (x .+ ((b .* (myfld.reciprocal a1 a_ne_zero)) .* (third f))) tmp) at is_solution, rw (int_quantity_eq_zero_simp f a1 b c a_ne_zero int_quantity_eq_zero) at is_solution, unfold depressed_cubic_subst at is_solution, rw mul_zero at is_solution, rw simp_zero at is_solution, have move_term : ∀ (q : f), x ≠ q .+ (.- ((b .* (myfld.reciprocal a1 a_ne_zero)) .* (third f))) <-> (x .+ ((b .* (myfld.reciprocal a1 a_ne_zero)) .* (third f))) ≠ q, intros q, split, intros h1 h2, rw <- h2 at h1, clear h2, rw <- myfld.add_assoc at h1, rw myfld.add_negate at h1, rw zero_simp f x at h1, cc, intros h1 h2, rw h2 at h1, clear h2, rw <- myfld.add_assoc at h1, rw myfld.add_comm (.- _) _ at h1, rw myfld.add_negate at h1, rw zero_simp f q at h1, cc, unfold cubic_formula_a_alt at ha, rw move_term _ at ha, unfold depressed_cubic_solution_c_zero_a at ha, unfold depressed_cubic_solution_c_zero at ha, rw move_negation_ne f _ _ at ha, unfold cubic_formula_b_alt at hb, rw move_term _ at hb, unfold depressed_cubic_solution_c_zero_b at hb, unfold depressed_cubic_solution_c_zero at hb, rw move_negation_ne f _ _ at hb, unfold cubic_formula_c_alt at hc, rw move_term _ at hc, unfold depressed_cubic_solution_c_zero_c at hc, unfold depressed_cubic_solution_c_zero at hc, rw move_negation_ne f _ _ at hc, clear move_term, clear tmp, rw move_across at is_solution, have tmp : ∀ (x : f), .- (cubed f x) = cubed f (.- x), intros q, unfold cubed, simp, rw tmp _ at is_solution, exact (no_other_cubrts_simple f _ _ ha hb hc) is_solution, end
From discprob.basic Require Import base order. From discprob.prob Require Import prob countable finite stochastic_order. From discprob.monad Require Import monad monad_par par_quicksort monad_par_hoare. From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq div choice fintype. From mathcomp Require Import tuple finfun bigop prime binomial finset. From mathcomp Require Import path. Require Import Coq.omega.Omega Coq.Program.Wf. Lemma perm_eq_cat {A: eqType} (l1a l1b l2a l2b: seq A) : perm_eq l1a l2a → perm_eq l1b l2b → perm_eq (l1a ++ l1b) (l2a ++ l2b). Proof. move /perm_eqP => Hpa. move /perm_eqP => Hpb. apply /perm_eqP. intros x. rewrite ?count_cat. rewrite (Hpa x) (Hpb x). done. Qed. Lemma sorted_cat {A: eqType} (l1 l2: seq A) (R: rel A): sorted R l1 → sorted R l2 → (∀ n1 n2, n1 \in l1 → n2 \in l2 → R n1 n2) → sorted R (l1 ++ l2). Proof. revert l2. induction l1 => //=. intros l2 HP Hsorted Hle. rewrite cat_path. apply /andP; split; auto. induction l2 => //=. apply /andP; split; auto. apply Hle. - apply mem_last. - rewrite in_cons eq_refl //. Qed. Lemma quicksort_correct (l: list nat): mspec (qs l) (λ l', (sorted leq l' && perm_eq l l'):Prop). Proof. remember (size l) as k eqn:Heq. revert l Heq. induction k as [k IH] using (well_founded_induction lt_wf) => l Heq. destruct l as [| a l]. - rewrite //= => b. rewrite mem_seq1. move /eqP => -> //=. - destruct l as [| b0 l0]. { rewrite //= => b. rewrite mem_seq1. move /eqP => -> //=. } rewrite qs_unfold. remember (b0 :: l0) as l eqn:Hl0. clear l0 Hl0. tbind (λ x, sval x \in a :: l). { intros (?&?) => //. } intros (pv&Hin) _. tbind (λ x, lower (sval x) = [ seq n <- (a :: l) | ltn n pv] ∧ middle (sval x) = [ seq n <- (a :: l) | n == pv] ∧ upper (sval x) = [ seq n <- (a :: l) | ltn pv n]). { remember (a :: l) as l0 eqn:Heql0. apply mspec_mret => //=. clear. induction l0 as [|a l]; first by rewrite //=. rewrite //=; case (ltngtP a pv) => //= ?; destruct (IHl) as (?&?&?); repeat split; auto; f_equal; done. } remember (a :: l) as l0 eqn:Heql0. intros (spl&Hin'). intros (Hl&Hm&Hu). rewrite //= in Hl, Hm, Hu. tbind (λ x, (sorted leq (fst x) && perm_eq (lower spl) (fst x)) ∧ (sorted leq (snd x) && perm_eq (upper spl) (snd x))). { rewrite //=. eapply (mspec_rpar2 _ _ (λ x, (sorted leq x && perm_eq (lower spl) x)) (λ x, (sorted leq x && perm_eq (upper spl) x))). - eapply (IH (size (lower spl))); auto. rewrite Heq. move /andP in Hin'. destruct Hin' as (pf1&pf2); move /implyP in pf2. rewrite -(perm_eq_size pf1) //= ?size_cat -?plusE //; assert (Hlt: (lt O (size (middle spl)))) by ( apply /ltP; apply pf2 => //=; destruct p; eauto; subst; rewrite //=). rewrite //= in Hlt. omega. - eapply (IH (size (upper spl))); auto. rewrite Heq. move /andP in Hin'. destruct Hin' as (pf1&pf2); move /implyP in pf2. rewrite -(perm_eq_size pf1) //= ?size_cat -?plusE //; assert (Hlt: (lt O (size (middle spl)))) by ( apply /ltP; apply pf2 => //=; destruct p; eauto; subst; rewrite //=). rewrite //= in Hlt. omega. } intros (ll&lu) (Hll&Hlu). move /andP in Hll. destruct Hll as (Hllsorted&Hllperm). move /andP in Hlu. destruct Hlu as (Hlusorted&Hluperm). apply mspec_mret => //=. apply /andP; split. * apply sorted_cat; [| apply sorted_cat |]; auto. ** rewrite Hm. clear. induction l0 => //=. case: ifP; auto. move /eqP => ->. rewrite //=. clear IHl0. induction l0 => //=. case: ifP; auto. move /eqP => -> //=. rewrite leqnn IHl0 //. ** rewrite Hm => a' b'; rewrite mem_filter. move /andP => [Heqpv Hin1 Hin2]. move /eqP in Heqpv. move: Hin2. rewrite -(perm_eq_mem Hluperm) Hu mem_filter. move /andP => [Hgtpv ?]. move /ltP in Hgtpv. rewrite Heqpv. apply /leP. omega. ** intros a' b'. rewrite -(perm_eq_mem Hllperm) Hl mem_filter. move /andP => [Hgtpv ?]. move /ltP in Hgtpv. rewrite mem_cat. move /orP => []. *** rewrite Hm; rewrite mem_filter. move /andP => [Heqpv ?]. move /eqP in Heqpv. rewrite Heqpv. apply /leP. omega. *** rewrite -(perm_eq_mem Hluperm) Hu mem_filter. move /andP => [Hltpv ?]. move /ltP in Hltpv. apply /leP. omega. * move /andP in Hin'. destruct Hin' as (Hperm&_). rewrite perm_eq_sym in Hperm. rewrite (perm_eq_trans Hperm) //. repeat apply perm_eq_cat; auto. Qed.
module Main import Data.Fin import Data.Vect import Data.Vect.Quantifiers import Decidable.Equality Cell : Nat -> Type Cell n = Maybe (Fin n) data Board : Nat -> Type where MkBoard : {n : Nat} -> Vect n (Vect n (Cell n)) -> Board n emptyBoard : {n : Nat} -> Board n emptyBoard {n=n} = MkBoard (replicate n (replicate n Nothing)) Empty : Cell n -> Type Empty {n=n} x = (the (Cell n) Nothing) = x Filled : Cell n -> Type Filled {n=n} = (\x => Not (Empty x)) FullBoard : Board n -> Type FullBoard (MkBoard b) = All (All Filled) b indexStep : {i : Fin n} -> {xs : Vect n a} -> {x : a} -> index i xs = index (FS i) (x::xs) indexStep = Refl find : {p : a -> Type} -> ((x : a) -> Dec (p x)) -> (xs : Vect n a) -> Either (All (\x => Not (p x)) xs) (y : a ** (p y, (i : Fin n ** y = index i xs))) find _ Nil = Left Nil find {p} d (x::xs) with (d x) | Yes prf = Right (x ** (prf, (FZ ** Refl))) | No prf = case find {p} d xs of Right (y ** (prf', (i ** prf''))) => Right (y ** (prf', (FS i ** replace {P=(\x => y = x)} (indexStep {x=x}) prf''))) Left prf' => Left (prf::prf') empty : (cell : Cell n) -> Dec (Empty cell) empty Nothing = Yes Refl empty (Just _) = No nothingNotJust findEmptyInRow : (xs : Vect n (Cell n)) -> Either (All Filled xs) (i : Fin n ** Empty (index i xs)) findEmptyInRow xs = case find {p=Empty} empty xs of Right (_ ** (pempty, (i ** pidx))) => Right (i ** trans pempty pidx) Left p => Left p getCell : Board n -> (Fin n, Fin n) -> Cell n getCell (MkBoard b) (x, y) = index x (index y b) emptyCell : {n : Nat} -> (b : Board n) -> Either (FullBoard b) (c : (Fin n, Fin n) ** Empty (getCell b c)) emptyCell (MkBoard rs) = case helper rs of Left p => Left p Right (ri ** (ci ** pf2)) => Right ((ci, ri) ** pf2) where helper : (rs : Vect m (Vect n (Cell n))) -> Either (All (All Filled) rs) (r : Fin m ** (c : Fin n ** Empty (index c (index r rs)))) helper Nil = Left Nil helper (r::rs) = case findEmptyInRow r of Right (ci ** pf3) => Right (FZ ** (ci ** pf3)) Left prf => case helper rs of Left prf' => Left (prf::prf') Right (ri ** (ci ** pf4)) => Right (FS ri ** (ci ** pf4)) main : IO () main = case emptyCell (emptyBoard {n=0}) of Left _ => putStrLn "l" Right _ => putStrLn "r"
(** Copyright (c) 2015 Bill White **) (** Distributed under the MIT/X11 software license **) (** See http://www.opensource.org/licenses/mit-license.php **) (** CTreeGrafting: A cgraft describes how to extend a ctree to a better approximation. The purpose is so that a small ctree can be given in the block header and the graft to extend it to a larger ctree can be given in the block delta without repeating the ctree information in the header. **) Require Export CTrees. (*** A "cgraft" can be used to extend a ctree to be a better approximation without repeating the part that is known. The idea is to use this to put just what's needed in the block header (enough of an approx to support the coinstake tx) and then a graft of the extra part that's needed in the block delta. ***) Definition cgraft : Type := list (prod hashval (sigT ctree)). Fixpoint cgraft_valid (G:cgraft) : Prop := match G with | nil => True | (h,existT n T)::G' => ctree_hashroot T = h /\ cgraft_valid G' end. (*** Coercion needed due to dependent types ***) Definition eqnat_coerce_ctree (m n:nat) (E:m = n) (T:ctree m) : ctree n := eq_rect m ctree T n E. (*** The dependent types here are a little tricky. I could omit m from the input return (existT n T) where T, leaving the caller of the function to check if m = n (which it should). Instead I decided to do it here. Either way a coercion using the proof of the equation seems to be needed. ***) Fixpoint cgraft_assoc (G:cgraft) (k:hashval) (m:nat) : ctree m := match G with | nil => ctreeH m k | (h,existT n T)::G' => if hashval_eq_dec h k then match eq_nat_dec n m with | left E => eqnat_coerce_ctree n m E T | _ => ctreeH m k end else cgraft_assoc G' k m end. Lemma cgraft_assoc_hashroot (G:cgraft) (k:hashval) (m:nat) : cgraft_valid G -> ctree_hashroot (cgraft_assoc G k m) = k. induction G as [|[h [n T]] G' IH]. - intros _. destruct m; reflexivity. - simpl. intros [H1 H2]. destruct (hashval_eq_dec h k) as [E1|E1]. + destruct (eq_nat_dec n m) as [E2|E2]. * destruct E2. simpl. (*** tricky ***) rewrite <- E1. exact H1. * destruct m; reflexivity. (*** even though this is impossible (since if ctree m and ctree n have the same hashroot, m should equal n) the proof goes through. ***) + exact (IH H2). Qed. Lemma cgraft_assoc_subqc (G:cgraft) (k:hashval) (m:nat) : cgraft_valid G -> subqc (ctreeH m k) (cgraft_assoc G k m). intros H1. generalize (cgraft_assoc_hashroot G k m H1). intros H2. destruct m as [|m]. - simpl. unfold subqc. unfold subqm. apply subqhH. change (mtree_hashroot (ctree_mtree (cgraft_assoc G k 0)) = Some k). rewrite mtree_hashroot_ctree_hashroot. congruence. - unfold subqc. change (subqm (mtreeH m (Some k)) (ctree_mtree (cgraft_assoc G k (S m)))). change (mtree_hashroot (ctree_mtree (cgraft_assoc G k (S m))) = mtree_hashroot (mtreeH m (Some k))). change (mtree_hashroot (ctree_mtree (cgraft_assoc G k (S m))) = Some k). rewrite mtree_hashroot_ctree_hashroot. congruence. Qed. Fixpoint ctree_cgraft (G:cgraft) {n} : ctree n -> ctree n := match n with | O => fun T:ctree 0 => match T with | inl h => cgraft_assoc G h 0 | _ => T end | S n => fun T:ctree (S n) => match T with | inr (inl h) => cgraft_assoc G h (S n) | inr (inr (inl Tl)) => ctreeBL (ctree_cgraft G Tl) | inr (inr (inr (inl Tr))) => ctreeBR (ctree_cgraft G Tr) | inr (inr (inr (inr (Tl,Tr)))) => ctreeB (ctree_cgraft G Tl) (ctree_cgraft G Tr) | _ => T end end. Theorem ctree_cgraft_subqc (G:cgraft) {n} (T:ctree n) : cgraft_valid G -> subqc T (ctree_cgraft G T). intros H1. induction n as [|n IH]. - destruct T as [h|[a hl]]. + simpl. change (subqc (ctreeH 0 h) (cgraft_assoc G h 0)). now apply cgraft_assoc_subqc. + apply subqm_ref. - destruct T as [[gamma hl]|[h|[Tl|[Tr|[Tl Tr]]]]]. + apply subqm_ref. + change (subqc (ctreeH (S n) h) (cgraft_assoc G h (S n))). now apply cgraft_assoc_subqc. + split. * apply IH. * apply subqm_ref. + split. * apply subqm_ref. * apply IH. + split. * apply IH. * apply IH. Qed. Transparent ctree_mtree. Theorem ctree_approx_fun_cgraft_valid (G:cgraft) {n} (T:ctree n) (f:bitseq n -> list asset) : cgraft_valid G -> octree_approx_fun_p (Some T) f -> octree_approx_fun_p (Some (ctree_cgraft G T)) f. intros HG. induction n as [|n IH]. - destruct T as [h|[h hl]]. + unfold octree_approx_fun_p. simpl. intros H1. rewrite H1. generalize (cgraft_assoc_hashroot G h 0 HG). destruct (cgraft_assoc G h 0) as [k|[k kl]]. * simpl. congruence. * simpl. destruct (hlist_hashroot kl); congruence. + simpl. tauto. - destruct T as [[gamma hl]|[h|[Tl|[Tr|[Tl Tr]]]]]. + simpl. tauto. + unfold octree_approx_fun_p. intros [Tl [Tr [H1 [H2 H3]]]]. unfold ctree_cgraft. generalize (cgraft_assoc_hashroot G h (S n) HG). intros H4. destruct (cgraft_assoc G h (S n)) as [[[[|] delta] kl]|[k|[Tl'|[Tr'|[Tl' Tr']]]]]. * { simpl. simpl in H4. destruct (mtree_hashroot Tl) as [hl|] eqn:E1; destruct (mtree_hashroot Tr) as [hr|] eqn:E2; simpl in H1. - exfalso. inversion H1. rewrite H0 in H4. apply hashpairinj in H4. destruct H4 as [H4 _]. apply hashnatinj in H4. omega. - exfalso. inversion H1. rewrite H0 in H4. apply hashpairinj in H4. destruct H4 as [H4 _]. apply hashnatinj in H4. omega. - inversion H1. rewrite H0 in H4. apply hashpairinj in H4. destruct H4 as [_ H4]. split. + apply (mtree_hashroot_mtree_approx_fun_p Tl). * rewrite mtree_hashroot_empty. exact E1. * exact H2. + apply (mtree_hashroot_mtree_approx_fun_p Tr). * assert (L1: mtree_hashroot Tr = mtree_hashroot (ctree_mtree (ctreeL kl delta))). { rewrite mtree_hashroot_ctree_hashroot. congruence. } destruct n; exact L1. * exact H3. - discriminate H1. } * { simpl. simpl in H4. destruct (mtree_hashroot Tl) as [hl|] eqn:E1; destruct (mtree_hashroot Tr) as [hr|] eqn:E2; simpl in H1. - exfalso. inversion H1. rewrite H0 in H4. apply hashpairinj in H4. destruct H4 as [H4 _]. apply hashnatinj in H4. omega. - inversion H1. rewrite H0 in H4. apply hashpairinj in H4. destruct H4 as [_ H4]. split. + apply (mtree_hashroot_mtree_approx_fun_p Tl). * assert (L1: mtree_hashroot Tl = mtree_hashroot (ctree_mtree (ctreeL kl delta))). { rewrite mtree_hashroot_ctree_hashroot. congruence. } destruct n; exact L1. * exact H2. + apply (mtree_hashroot_mtree_approx_fun_p Tr). * rewrite mtree_hashroot_empty. exact E2. * exact H3. - exfalso. inversion H1. rewrite H0 in H4. apply hashpairinj in H4. destruct H4 as [H4 _]. apply hashnatinj in H4. omega. - discriminate H1. } * { simpl. exists Tl. exists Tr. simpl in H4. subst k. repeat split. - exact H1. - exact H2. - exact H3. } * { simpl. simpl in H4. destruct (mtree_hashroot Tl) as [hl|] eqn:E1; destruct (mtree_hashroot Tr) as [hr|] eqn:E2; simpl in H1. - exfalso. inversion H1. rewrite H0 in H4. apply hashpairinj in H4. destruct H4 as [H4 _]. apply hashnatinj in H4. omega. - inversion H1. rewrite H0 in H4. apply hashpairinj in H4. destruct H4 as [_ H4]. split. + apply (mtree_hashroot_mtree_approx_fun_p Tl). * rewrite mtree_hashroot_ctree_hashroot. congruence. * exact H2. + apply (mtree_hashroot_mtree_approx_fun_p Tr). * rewrite mtree_hashroot_empty. exact E2. * exact H3. - exfalso. inversion H1. rewrite H0 in H4. apply hashpairinj in H4. destruct H4 as [H4 _]. apply hashnatinj in H4. omega. - exfalso. discriminate H1. } * { simpl. simpl in H4. destruct (mtree_hashroot Tl) as [hl|] eqn:E1; destruct (mtree_hashroot Tr) as [hr|] eqn:E2; simpl in H1. - exfalso. inversion H1. rewrite H0 in H4. apply hashpairinj in H4. destruct H4 as [H4 _]. apply hashnatinj in H4. omega. - exfalso. inversion H1. rewrite H0 in H4. apply hashpairinj in H4. destruct H4 as [H4 _]. apply hashnatinj in H4. omega. - inversion H1. rewrite H0 in H4. apply hashpairinj in H4. destruct H4 as [_ H4]. split. + apply (mtree_hashroot_mtree_approx_fun_p Tl). * rewrite mtree_hashroot_empty. exact E1. * exact H2. + apply (mtree_hashroot_mtree_approx_fun_p Tr). * rewrite mtree_hashroot_ctree_hashroot. congruence. * exact H3. - discriminate H1. } * { simpl. simpl in H4. destruct (mtree_hashroot Tl) as [hl|] eqn:E1; destruct (mtree_hashroot Tr) as [hr|] eqn:E2; simpl in H1. - inversion H1. rewrite H0 in H4. apply hashpairinj in H4. destruct H4 as [_ H4]. apply hashpairinj in H4. destruct H4 as [H4a H4]. apply hashpairinj in H4. destruct H4 as [H4b _]. split. + apply (mtree_hashroot_mtree_approx_fun_p Tl). * rewrite mtree_hashroot_ctree_hashroot. congruence. * exact H2. + apply (mtree_hashroot_mtree_approx_fun_p Tr). * rewrite mtree_hashroot_ctree_hashroot. congruence. * exact H3. - exfalso. inversion H1. rewrite H0 in H4. apply hashpairinj in H4. destruct H4 as [H4 _]. apply hashnatinj in H4. omega. - exfalso. inversion H1. rewrite H0 in H4. apply hashpairinj in H4. destruct H4 as [H4 _]. apply hashnatinj in H4. omega. - discriminate H1. } + intros [H1 H2]. split. * apply IH. exact H1. * exact H2. + intros [H1 H2]. split. * exact H1. * apply IH. exact H2. + intros [H1 H2]. split. * apply IH. exact H1. * apply IH. exact H2. Qed. Opaque ctree_cgraft. Opaque cgraft_valid. Opaque ctree_mtree. Opaque mtree_approx_fun_p. Theorem ctree_valid_cgraft_valid (G:cgraft) (T:ctree 160) : ctree_valid T -> cgraft_valid G -> ctree_valid (ctree_cgraft G T). intros [f [H1 H2]] HG. exists f. split. - exact H1. - assert (L1: octree_approx_fun_p (Some (ctree_cgraft G T)) f). { apply ctree_approx_fun_cgraft_valid. - exact HG. - unfold octree_approx_fun_p. unfold octree_mtree. exact H2. } unfold octree_approx_fun_p in L1. unfold octree_mtree in L1. exact L1. Qed.
The corn crake is solitary on the wintering grounds , where each bird occupies 4 @.@ 2 – 4 @.@ 9 ha ( 10 – 12 acres ) at one time , although the total area used may be double that , since an individual may move locally due to flooding , plant growth , or grass cutting . Flocks of up to 40 birds may form on migration , sometimes associating with common quails . Migration takes place at night , and flocks resting during the day may aggregate to hundreds of birds at favoured sites . The ability to migrate is innate , not learned from adults . Chicks raised from birds kept in captivity for ten generations were able to migrate to Africa and return with similar success to wild @-@ bred young .
# 02 Data Structures and Libraries ## CLASS MATERIAL <br> <a href='#DataStructures'>1. Data Structures</a> <br> <a href='#Libraries__'>2. Libraries</a> <br> <a href='#InstallingPygame'>3. Installing Pygame</a> <br> <a href='#ReviewExercises'>4. Review Exercises</a> # Update the new class notes. __Navigate to the directory where your files are stored.__ __Update the course notes by downloading the changes__ ##### Windows Search for __Git Bash__ in the programs menu. Select __Git Bash__, a terminal will open. Use `cd` to navigate to *inside* the __ILAS_PyEv2019__ repository you downloaded. Run the command: >`./automerge` ##### Mac Open a terminal. Use `cd` to navigate to *inside* the __ILAS_PyEv2019__ repository you downloaded. Run the command: >`sudo ./automerge` Enter your password when prompted. <a id='Summary'></a> # Primer Summary For more information refer to the primer notebook for this class 02_DataStructures_Libraries__Primer.ipynb ###### Data Structures - A data structure is used to assign a collection of values to a single collection name. - A Python list can store multiple items of data in sequentially numbered elements (numbering starts at zero) - Data stored in a list element can be referenced using the list name can be referenced using the list name followed by an index number in [] square brackets. - The `len()` function returns the length of a specified list. ###### Libraries - Python has an extensive __standard library__ of built-in functions. - More specialised libraries of functions and constants are available. We call these __packages__. - Packages are imported using the keyword `import` - The function documentation tells is what it does and how to use it. - When calling a library function it must be prefixed with a __namespace__ is used to show from which package it should be called. ## Lesson Goal - Build a guessing game. - Build the game 0 and Xs or tic-tac-toe. <p align="center"> </p> ## Fundamental programming concepts - Importing existing libraries of code to use in your program - Storing and representing data e.g. a grid with 0 and X in each grid cell <a id='DataStructures'></a> # 1. Data Structures In the last seminar we learnt to generate a range of numbers for use in control flow of a program, using the function `range()`: for j in range(20): ... Often we want to manipulate data that is more meaningful than ranges of numbers. These collections of variables might include: - the results of an experiment - a list of names - the components of a vector - a telephone directory with names and associated numbers. Python has different __data structures__ that can be used to store and manipulate these values. Like variable types (`string`, `int`,`float`...) different data structures behave in different ways. Today we will learn to use `list`s A list is a container with compartments in which we can store data: <p align="center"> </p> Example If we want to store the names of students in a laboratory group, rather than representing each students using an individual string variable, we could use a list of names. ```python lab_group0 = ["Yukari", "Sajid", "Hemma", "Ayako"] lab_group1 = ["Sara", "Mari", "Quang", "Sam", "Ryo", "Nao", "Takashi"] print(lab_group0) print(lab_group1) ``` ['Yukari', 'Sajid', 'Hemma', 'Ayako'] ['Sara', 'Mari', 'Quang', 'Sam', 'Ryo', 'Nao', 'Takashi'] This is useful because we can perform operations on lists such as: - checking its length (number of students in a lab group) - sorting the names in the list into alphabetical order - making a list of lists (we call this a *nested list*): ```python lab_groups = [lab_group0, lab_group1] print(lab_groups) ``` [['Yukari', 'Sajid', 'Hemma', 'Ayako'], ['Sara', 'Mari', 'Quang', 'Sam', 'Ryo', 'Nao', 'Takashi']] <a id='ExampleChangePosition'></a> ### Example: Change in Position: (Representing Vectors using Lists) __Vector:__ A quantity with magnitude and direction. The position of a point in 2D space (e.g. the position of a character in a game), can be expressed in terms of horizontal (x) and vertical (y) conrdinates. The movement to a new position can be expressed as a change in x and y. [Daniel Schiffman, The Nature of Code] We can conveniently express the position $\mathbf{r}$ in matrix (or basis vector) form using the coefficients $x$ and $y$: $$ \mathbf{r} = [r_x, r_y] $$ __...which looks a lot like a Python list!__ When we move a character in a game, we change it's position. The change in position with each time-step is the __velocity__ of the character. __Velocity__ : the magnitude and direction of a change in position per time increment. $$ \mathbf{v} = [v_x, v_y] $$ To get the position at the next time step we simply add the x and y component of the veclocity to the x and y component of the initial position vector: \begin{align} {\displaystyle {\begin{aligned}\ \mathbf{w} &=\mathbf{u} + \mathbf{u}\\ &=[(u_x+v_x),\;\; (u_y+v_y)] \\ \end{aligned}}} \end{align} For example, let's find the position at the next timestep where: - initial position, $\mathbf{u} = [5, 2]$ - velocity, $\mathbf{v} = [3, 4]$ [Daniel Schiffman, The Nature of Code] ```python # Example: Change in Position ``` ```python # Example Solution: Change in Position u = [5, 2] v = [3, 4] u = [u[0] + v[0], u[1] + v[1]] print(u) ``` [8, 6] Arranging the code on seperate lines: - makes the code more readable - does not effect how the code works Line breaks can only be used within code that is enclosed by at elast one set of brackets (), []. __Check Your Solution:__ $ \mathbf{u} = [5, 2]$ <br> $ \mathbf{v} = [3, 4]$ \begin{align} {\displaystyle {\begin{aligned}\ \mathbf{u} + \mathbf{v} &=[5, 2]+ [3, 4]\\ &=[(5+3), \quad (2+4)] \\ & = [8, 6] \end{aligned}}} \end{align} <a id='Libraries__'></a> # 2. Libraries <br> &emsp;&emsp; <a href='#StandardLibrary'>__2.1 The Standard Library__</a> <br> &emsp;&emsp; <a href='#Packages'>__2.2 Packages__ </a> <br> &emsp;&emsp; <a href='#FunctionDocumentation'>__2.3 Function Documentation__</a> <br> &emsp;&emsp; <a href='#Optimise'>__2.4 Using Package Functions to Optimise your Code__</a> One of the most important concepts in good programming is to reuse code and avoid repetitions. Python, like other modern programming languages, has an extensive *library* of built-in functions. These functions are designed, tested and optimised by the developers of the Python langauge. We can use these functions to make our code shorter, faster and more reliable. <a id='StandardLibrary'></a> ## 2.1 The Standard Library Python has a large standard library. e.g. `print()` takes the __input__ in the parentheses and __outputs__ a visible representation. They are listed on the Python website: https://docs.python.org/3/library/functions.html We could write our own code to find the minimum of a group of numbers ```python x0 = 1 x1 = 2 x2 = 4 x_min = x0 if x1 < x_min: x_min = x1 if x2 < x_min: x_min = x2 print(x_min) ``` 1 However, it is much faster to use the build in function: ```python print(min(1,2,4)) ``` 1 The built-in functions can be found in (.py) files called 'modules'. The files are neatly arranged into a system of __sub-packages__ (sub-folders) and __modules__ (files). These files are stored on the computer you are using. A quick google search for "python function to sum all the numbers in a list"... https://www.google.co.jp/search?q=python+function+to+sum+all+the+numbers+in+a+list&rlz=1C5CHFA_enJP751JP751&oq=python+function+to+sum+&aqs=chrome.0.0j69i57j0l4.7962j0j7&sourceid=chrome&ie=UTF-8 ...returns the function `sum()`. `sum()` finds the sum of the values in a data structure. ```python print(sum([1,2,3,4,5])) print(sum((1,2,3,4,5))) a = [1,2,3,4,5] print(sum(a)) ``` 15 15 15 The function `max()` finds the maximum value in data structure. <a id='Packages'></a> ## 2.2 Packages The standard library tools are available in any Python environment. More specialised libraries, called packages, are available for more specific tasks <br>e.g. solving trigonometric functions. Packages contain functions and constants. We install the packages to use them. __Pygame__ <br>For a large part of this course we will use functions from a package called `Pygame`. <br>`Pygame` is a set of Python modules designed for writing computer games, graphics and sound projects. <br>Instructions for how install pygame will be given later in today's seminar. __math__ <br>`math` is already installed and allows you to use convenient mathematical functions and operators. A package is a collection of Python modules: - a __module__ is a single Python file - a __package__ is a directory of Python modules.<br>(It contains an __init__.py file, to distinguish it from folders that are not libraries). The files that are stored on your computer when Pygame is installed: <br>https://github.com/pygame/pygame <a id='ImportingPackage'></a> ## Importing a Package To use an installed package, we simply `import` it. We only need to import the package once. <br>The `import` statement must appear before the use of the package in the code so all packages are usually imported at the start of the program. import math We can then use variable and functions defined within that package by prefixing them with the name of the package: ```python import math ``` After this, any constant, variable or function from the package can be used by prefixing it with the name of the package: Any constant in `math` can be called as: `math.constant`. Any function in `numpy` can be called as: `math.function()` ```python # pi print(math.pi) x = 1 # Trigonometric functions e.g. cosine y = math.cos(x) print(y) ``` 3.141592653589793 0.5403023058681398 <a id='UsingPackageFunctions'></a> ## Using Package Functions. Let's learn to use `math` functions in our programs... ```python # Some examples math functions with their definitions (as given in the documentation) x = 1 # Return the sine of x radians. print(math.sin(x)) # Return the tangent of x radians. print(math.tan(x)) # Return the inverse hyperbolic tangent of x. print(math.atan(x)) ``` 0.8414709848078965 1.557407724654902 0.7853981633974483 ```python x = 1 # Convert angle x from radians to degrees. degrees = math.degrees(x) print(degrees) # Convert angle x from degrees to radians. radians = math.radians(degrees) print(radians) ``` 57.29577951308232 1.0 <a id='FunctionDocumentation'></a> ## 2.3 Function Documentation Online documentation can be used to find out: - what to include in the () parentheses - allowable data types to use as arguments - the order in which arguments should be given A google search for 'python math documentation' returns: https://docs.python.org/3/library/math.html (this list is not exhaustive). ### Try it yourself: <br> Find a function in the Python math documentation (https://docs.python.org/3/library/math.html) that can be used to solve the following problem: ##### Return, $\left| x \right|$, the absolute value of x Write your answer in the cell below: ```python # Return the absolute value of x. ``` <a id='Examplemathpow'></a> ### Example : math.pow ($x^y$) Documentation : https://docs.python.org/3/library/math.html#hyperbolic-functions The documentation tells us the following information... ##### What arguments to input: "math.pow(x, y)" ##### What the function returns: "Return x raised to the power y." ##### The format of the returned argument: math.pow() converts both its arguments to type float <a id='Optimise'></a> ## 2.4 Using Package Functions to Optimise your Code One purpose of using imported functions is to make your code shorter and neater. <br>For example, when designing a game it can be very useful to generate (pseudo) random numbers so that the challenges and problems for the user to solve are not identical every time the game is played. Writing your own algorithm to generate random numbers is unecessarily time-consuming. `random` is a python module that implements pseudo-random number generators for various distributions. The documentation of the functions in this package can be found here: <br>https://docs.python.org/3/library/random.html# Import random to use functions from this package: ```python import random ``` Here are some examples of functions from `random`... ```python # random.randint(a, b) # Return a random integer N such that a <= N <= b. random.randint(1, 15) ``` 14 ```python # random.sample(population, k) # Return a k length list of unique elements chosen from the population sequence or set. # Used for random sampling without replacement. random.sample([1,2,3,4,5,6,7,8], 4) ``` [4, 7, 8, 1] Random numbers can be used to introduce an element of uncertainty to your programs. This makes a game more intersting as the outcome may be different every time it is played. For example, an adventure game may have a different outcome depending on a random variable. ```python print("Inside the castle you see a giant spider.") answer = input("Do you fight the spider? (Yes/No) ") if answer == 'Yes': print("you defeat the spider. \nYou win!") else: print("The spider eats you. \nYou lose!") ``` Inside the castle you see a giant spider. Do you fight the spider? (Yes/No) Yes you defeat the spider. You win! An adventure game where the outcome is random can be more interesting. ```python print("Inside the castle you see a giant spider.") answer = input("Do you fight the spider? (Yes/No) ") if answer == 'Yes': number = int(random.randint(0, 2)) if number < 2: print("The spider defeats you. \nYou lose!") else: print("you defeat the spider. \nYou win!") else: print("The spider eats you. \nYou lose!") ``` Inside the castle you see a giant spider. Do you fight the spider? (Yes/No) The spider eats you. You lose! Random, computer generated values can also be used to build a game of rock, paper scissors where the user plays against the computer. The code section below shows the case that the player choses *rock*. ```python computer = int(random.randint(0, 2)) if computer == 0: c_choice = "rock" elif computer == 1: c_choice = "paper" else: c_choice = "scissors" ``` The full version of the code is given in example program: Examples/02_RockPaperScissors.py Try running this from the terminal by typing `python3 02_RockPaperScissors.py` from within the __PyEv2019/Examples__ directory. <a id='InstallingPygame'></a> ## 3. Installing Pygame Install Pygame now. We will begin using this package in next week's class. ##### Windows 1. Open the Anaconda Prompt from the terminal. <p align="center"> </p> 1. The window that opens will look like the command line. In the window type the following code then press 'Enter': >`conda install -c anaconda pip` 1. When the installation completes type the following code then press 'Enter': >`pip install pygame` ##### Mac 1. Open a terminal. 1. Type the following code then press 'Enter': >`conda install -c anaconda pip` 1. When the installation completes type the following code then press 'Enter': >`pip install pygame` To check the installation has worked type: >`import pygame` in a Jupyter notebook cell and run the cell. If no error is generated you have installed pygame successfully. <a id='ReviewExercises'></a> # 4. Review Exercises Compete the exercise below. Save your answers as .py files and email them to: <br>[email protected] ## Review Exercise 1 : Guessing Game __(A)__ <br> Write a game that: - chooses a random number between 1 and 10 - asks the user to guess what it is - exits when the user guesses the right number Use: - a while loop - a break statement (to break out of the while loop) - a random number generator (from the package, `random`) <br> Example : The output from your game might look like this: ``` I'm thinking of a random number between 1 and 10. Can you guess what it is? Guess what number I am thinking of: 5 Guess what number I am thinking of: 2 Guess what number I am thinking of: 1 Guess what number I am thinking of: 9 You win! I was thinking of 9. ``` *Hint: Remember that the function `input` returns a string even when a numerical value is entered.* ```python # Review Exercise A: Guessing Game ``` I'm thinking of a random number between 1 and 10. Can you guess what it is? Guess what number I am thinking of: 4 Guess what number I am thinking of: 5 Guess what number I am thinking of: 6 You win! I was thinking of 6 ```python # Review Exercise : Guessing Game # Example Solution import random import math num = random.randint(1, 10) print("I'm thinking of a random number between 1 and 10.") print("Can you guess what it is?") while(1): guess = int(input("Guess what number I am thinking of: ")) if guess == num: print(f"You win! I was thinking of {num}") break ``` __(B)__ <br>Use `if` and `else` to generate a __clue__ for the player gets the answer wrong <br> The output from your game might look like this: ``` I'm thinking of a random number between 1 and 10. Can you guess what it is? Guess what number I am thinking of: 1 Too low. Guess what number I am thinking of: 5 Too low. Guess what number I am thinking of: 9 You win! I was thinking of 9. ``` ```python # Review Exercise B: Guessing Game with Clues ``` ```python # Review Exercise : Guessing Game with Clues # Example Solution import random import math num = random.randint(1, 10) print("I'm thinking of a random number between 1 and 10.") print("Can you guess what it is?") while(1): guess = int(input("Guess what number I am thinking of: ")) if guess == num: print(f"You win! I was thinking of {num}") break elif guess < num: print("Too low") else: print("Too high") ``` I'm thinking of a random number between 1 and 10. Can you guess what it is? Guess what number I am thinking of: 2 Too low Guess what number I am thinking of: 5 Too high Guess what number I am thinking of: 3 Too low Guess what number I am thinking of: 4 You win! I was thinking of 4 __(C)__ <br>Use `break` to quit the game if the user makes three consecutive wrong guesses. <br> The output from your game might look something like this: I'm thinking of a random number between 1 and 10. Can you guess what it is? You have 3 guesses... Guess what number I am thinking of: 1 Too low. Guess what number I am thinking of: 2 Too low. Guess what number I am thinking of: 5 You used all your lives! You lose! I was thinking of 9. ```python # Review Exercise C: Guessing game with maximum number of tries ``` ```python # Review Exercise : Guessing game with maximum number of tries # Example Solution import random import math num = random.randint(1, 10) print("I'm thinking of a random number between 1 and 10.") print("Can you guess what it is?") for i in range(3): guess = int(input("Guess what number I am thinking of: ")) if guess == num: print(f"You win! I was thinking of {num}") break elif guess < num: print("Too low") else: print("Too high") print(f"You used all your lives! You lose! I was thinking of {num}.") ``` I'm thinking of a random number between 1 and 10. Can you guess what it is? Guess what number I am thinking of: 3 Too low Guess what number I am thinking of: 4 Too low Guess what number I am thinking of: 5 Too low You used all your lives! You lose! I was thinking of 7. ## Review Exercise 2: List with `for` loop. In the cell below, use a `for` loop to print the first letter of each month in the list. ```python # Print the first letter of each month in the list months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] ``` ```python # Review Exercise: List with for loop # Example Solution ``` <a id='ExampleTicTacToe'></a> ## Review Exercise 3 : Tic-tac-toe A list of lists can be used to represent a discrete set of positions the a player can occupy. We can write a program that plays the the game tic-tac-toe, using a list of list. The program is shown in the cell below. <p align="center"> </p> __(A)__ The program decides whether to quit the game based on user input after each turn taken. Copy and paste the program into the cell provided below. Edit the program to quit the game if either: - one of the players places three marks in a row. - all positions have been marked but noone has won. <br>*Hints:* - Use: - `if` and `else` - the boolean operators `and`, `or`, `not` - If the value of three colinear places is equal, the game has finished/been won. ```python # tic-tac-toe # # Board positions: # # 00 01 02 # 10 11 12 # 20 21 22 # Example solution # # use a for loop to set-up the 3x3 grid board = [] for row in range(3): #board.append(['_', '_', '_']) board.append(['_']*3) # print the output nicely for row in board: for column in row: print(column, end='\t') # new line at end of row print() # choose who goes first, X or 0 player = 'X' # keep playing the game until told to quit while(1): # use if and else to take turns at adding input from each player to the board if player == 'X': position = input('Player X, choose position: ') board[int(position[0])][int(position[1])] = 'X' player = '0' else: position = input('Player 0, choose position: ') board[int(position[0])][int(position[1])] = '0' player = 'X' #board[int(position[0])][int(position[1])] = player # print the output nicely for row in board: for column in row: print(column, end='\t') # new line at end of row print() print('\nnext turn \n') game_over = input('Game over?(Y/N): ') if game_over == 'Y': break ``` __(B)__ <br>Edit the program to prevent a player from choosing a place that is already occupied. <br>For example, the program might ask the player to choose again. <br>e.g. position already occupied, Player X choose a different position ```python # Review Exercise: Tic-tac-toe ``` ```python # Review Exercise: Tic-tac-toe # Example Solution # use a for loop to set-up the board board = [] for row in range(3): #board.append(['_', '_', '_']) board.append(['_']*3) # display the output nicely for lists in board: for i in lists: print(i,end='\t') # leave gap before next row print() # choose who goes first, X or 0 player = 'X' # keep playing the game until told to quit while(1): # use if and else to take turns at adding input from each player to the board if player == 'X': position = input('Player X, choose position: ') while(board[int(position[0])][int(position[1])] != '_'): position = input('Position taken, Player X, choose again: ') board[int(position[0])][int(position[1])] = 'X' player = '0' else: position = input('Player 0, choose position: ') while(board[int(position[0])][int(position[1])] != '_'): position = input('Position taken, Player 0, choose again: ') board[int(position[0])][int(position[1])] = '0' player = 'X' #board[int(position[0])][int(position[1])] = player # display the output nicely for lists in board: for i in lists: print(i,end='\t') print() # game over : one player gets 3 in a row if((board[0][0] == board[1][1] == board[2][2]== 'X')or (board[2][0] == board[1][1] == board[0][2]== 'X')or (board[0][0] == board[1][0] == board[2][0]== 'X')or (board[0][1] == board[1][1] == board[2][1]== 'X')or (board[0][2] == board[1][2] == board[2][2]== 'X')or (board[0][0] == board[0][1] == board[0][2]== 'X')or (board[1][0] == board[1][1] == board[1][2]== 'X')or (board[2][0] == board[2][1] == board[2][2]== 'X')or (board[0][0] == board[1][1] == board[2][2]== '0')or (board[2][0] == board[1][1] == board[0][2]== '0')or (board[0][0] == board[1][0] == board[2][0]== '0')or (board[0][1] == board[1][1] == board[2][1]== '0')or (board[0][2] == board[1][2] == board[2][2]== '0')or (board[0][0] == board[0][1] == board[0][2]== '0')or (board[1][0] == board[1][1] == board[1][2]== '0')or (board[2][0] == board[2][1] == board[2][2]== '0')): print("Game over! Player " + player + " wins!") break # game over : no empty sapces remain gameover = True for lists in board: for i in lists: if i=='_': gameover = False if gameover: print("Game over! No winner.") ``` _ _ _ _ _ _ _ _ _ Player X, choose position: 20 _ _ _ _ _ _ X _ _ Player 0, choose position: 11 _ _ _ _ 0 _ X _ _ Player X, choose position: 20 Position taken, Player X, choose again: 00 X _ _ _ 0 _ X _ _ Player 0, choose position: 11 Position taken, Player 0, choose again: 21 X _ _ _ 0 _ X 0 _ ```python # tic-tac-toe ```
############################################################################# ## #W example.gd ## ## This file contains a sample of a GAP implementation file. ## ############################################################################# ## #M SomeOperation( <val> ) ## ## performs some operation on <val> ## InstallMethod( SomeProperty, "for left modules", [ IsLeftModule ], 0, function( M ) if IsFreeLeftModule( M ) and not IsTrivial( M ) then return true; fi; TryNextMethod(); end ); ############################################################################# ## #F SomeGlobalFunction( ) ## ## A global variadic funfion. ## InstallGlobalFunction( SomeGlobalFunction, function( arg ) if Length( arg ) = 3 then return arg[1] + arg[2] * arg[3]; elif Length( arg ) = 2 then return arg[1] - arg[2] else Error( "usage: SomeGlobalFunction( <x>, <y>[, <z>] )" ); fi; end ); # # A plain function. # SomeFunc := function(x, y) local z, func, tmp, j; z := x * 1.0; y := 17^17 - y; func := a -> a mod 5; tmp := List( [1..50], func ); while y > 0 do for j in tmp do Print(j, "\n"); od; repeat y := y - 1; until 0 < 1; y := y -1; od; return z; end;
According to the Environmental Protection Agency - EPA - the Day-Night Sound Levels - Ldn - and the Equivalent Sound Level - Leq - should not exceed certain limits to protect public health and welfare. Outdoor activity interference and annoyance Leq(24) < 55 dBA Outdoor areas where people spend limited time such as school yards playgrounds, etc. Indoor activity interference and annoyance Leq(24) < 45 dBA Indoor areas with human activities such as schools, etc. Outdoor yearly Ldn levels protect public health and welfare if they do not exceed 55 dB in sensitive areas as residences, schools, hospitals, etc. Inside buildings yearly Ldn levels protect public health and welfare if they do not exceed 45 dB. Note! To protect against hearing damage, one's 24-hour noise exposure at the ear should not exceed 70 dB.
[STATEMENT] lemma bound_deg_sum: assumes " f \<in> carrier P" assumes "g \<in> carrier P" assumes "degree f \<le> n" assumes "degree g \<le> n" shows "degree (f \<oplus>\<^bsub>P\<^esub> g) \<le> n" [PROOF STATE] proof (prove) goal (1 subgoal): 1. deg R (f \<oplus>\<^bsub>P\<^esub> g) \<le> n [PROOF STEP] using P_def UP_ring_axioms assms(1) assms(2) assms(3) assms(4) [PROOF STATE] proof (prove) using this: P \<equiv> UP R UP_ring R f \<in> carrier P g \<in> carrier P deg R f \<le> n deg R g \<le> n goal (1 subgoal): 1. deg R (f \<oplus>\<^bsub>P\<^esub> g) \<le> n [PROOF STEP] by (meson deg_add max.boundedI order_trans)
x <-c( "apples, pears # and bananas", # the requested hash test "apples, pears ; and bananas", # the requested semicolon test "apples, pears and bananas", # without a comment " apples, pears # and bananas" # with preceding spaces ) strip_comments(x)
module Nat where data Nat : Set data Nat where zero : Nat suc : Nat -> Nat plus : Nat -> Nat -> Nat plus zero n = n plus (suc m) n = suc (plus m n) elim : (P : (n : Nat) -> Set) -> (z : P (plus zero zero)) -> (s : (n : Nat) -> P (plus zero n) -> P (plus (suc zero) n)) -> (n : Nat) -> P n elim P z s zero = z elim P z s (suc n) = s n (elim P z s n)
lemma measurable_ident: "id \<in> measurable M M"
/** * Copyright (2012-2014) JSU Uniphase. All rights reserved. * * Author: LIM Fung Chai */ #include "xtreme/iwf/manual_parser.h" #include "xtreme/iwf/internal/manual_parser_telemetry.h" #include <sstream> #include <iomanip> #include <boost/format.hpp> #include "arpa/inet.h" #include "log4cxx/logger.h" #include "xtreme/iwf/iwf.h" #include "xtreme/cs/cs.h" #include "xtreme/config/csparamapi.h" #include "xtreme/common/event_frame.h" #include "xtreme/common/parsed_frame.h" #include "xtreme/common/debug.h" namespace { log4cxx::LoggerPtr g_logger(log4cxx::Logger::getLogger("xtreme.iwf.manual-parser")); log4cxx::LoggerPtr g_telemetry_logger(log4cxx::Logger::getLogger("xtreme.telemetry.manual-parser")); int g_trace_log_enabled = -1; int g_debug_log_enabled = -1; std::string hex_dump(const uint8_t* data, uint32_t len) { std::ostringstream s; for (size_t i = 0; i < len; ++i) { if (i) { s << ", "; } s << boost::format("0x%1$02x") % static_cast<unsigned int>(data[i]); } return s.str(); } std::string dump_ether_type(uint16_t ether_type) { std::ostringstream stream; stream << "0x" << std::hex << std::setw(4) << std::setfill('0') << htons(ether_type); return stream.str(); } std::string dump_vlan(const xtreme::VlanTag* vlan) { std::ostringstream stream; stream << "0x" << std::hex << std::setw(8) << std::setfill('0') << htonl(vlan->u32b_); return stream.str(); } std::string dump_mpls(const xtreme::MplsEntry* mpls) { std::ostringstream stream; stream << "0x" << std::hex << std::setw(8) << std::setfill('0') << htonl(mpls->u32b_); return stream.str(); } const char* g_protocol_names[] = { 0 // 0x00 IPv6 Hop-by-Hop Option , "ICMPv4" // 0x01 Internet Control Message Protocol , "IGMP" // 0x02 Internet Group Management Protocol (multicast) , "GGP" // 0x03 Gateway-to-Gateway Protocol , 0 // 0x04 IPv4 encapsulation , 0 // 0x05 Internet Stream Protocol , "TCP" // 0x06 Transmission Control Protocol , 0 // 0x07 Core-based trees , "EGP" // 0x08 Exterior Gateway Protocol , "IGP" // 0x09 Interior Gateway Protocol , 0 // 0x0a BBN RCC Monitoring , 0 // 0x0b Network Voice Protocol , 0 // 0x0c Xerox PUP , 0 // 0x0d ARGUS , 0 // 0x0e EMCON , 0 // 0x0f XNET , 0 // 0x10 Chaos , "UDP" // 0x11 User Datagram Protocol , 0 // 0x12 Multiplexing , 0 // 0x13 DCN Measurement Subsystems , 0 // 0x14 Host Monitoring Protocol , 0 // 0x15 Pakcet Radio Measurement , 0 // 0x16 Xerox NS IDP , 0 // 0x17 Trunk-1 , 0 // 0x18 Trunk-2 , 0 // 0x19 Leaf-1 , 0 // 0x1a Leaf-2 , "RDP" // 0x1b Reliable Datagram Protocol , "IRTP" // 0x1c Internet Reliable Transaction Protocol , 0 // 0x1d ISO Transport Protocol Class 4 , 0 // 0x1e Bulk Data Transfer Protocol , 0 // 0x1f MFE Network Service Protocol , 0 // 0x20 Merit Internodal Protocol , 0 // 0x21 Datagram Congestion Control Protocol , 0 // 0x22 Third Party Connect Protocol , 0 // 0x23 Inter-Domain Policy Routing Protocol , 0 // 0x24 Xpress Transport Protocol , 0 // 0x25 Datagram Delivery Protocol , 0 // 0x26 IDPR Control Message Control Protocol , 0 // 0x27 TP++ Transport Protocol , 0 // 0x28 IL Transport Protocol , 0 // 0x29 IPv6 encapsulation , 0 // 0x2a Source Demand Routing Protocol , 0 // 0x2b IPv6 extension Routing Header , 0 // 0x2c IPv6 extension Fragment Header , "IDRP" // 0x2d Inter-Domain Routing Protocol , "RSVP" // 0x2e Resource Reservation Protocol , 0 // 0x2f Generic Routing Encapsulation , 0 // 0x30 Mobile Host Routing Protocol , 0 // 0x31 BNA , 0 // 0x32 IPv6 Extension Encapsulating Security Payload Header , 0 // 0x33 IPv6 Extension Authentication Header , 0 // 0x34 Integrated Net Layer Security Protocol , 0 // 0x35 SwiPe , 0 // 0x36 NBMA Address Resolution Protocol , 0 // 0x37 IPv6 Extension IP Mobility Header , 0 // 0x38 Transport Layer Security Protocol , 0 // 0x39 Simple Key-Management for Internet Protocol , "ICMPv6" // 0x3a ICMP for IPv6 , 0 // 0x3b IPv6 Extension No-Next Header , 0 // 0x3c IPv6 Extension Destination Options Header , 0 // 0x3d Any host internal protocol , 0 // 0x3e CFTP , 0 // 0x3f Any local network , 0 // 0x40 SATNET and Backroom EXPAK , 0 // 0x41 Kryptolan , 0 // 0x42 MIT Remote Virtual Disk Protocol , 0 // 0x43 Internet Pluribus Packet Core , 0 // 0x44 Any distributed file system , 0 // 0x45 SATNET Monitoring , 0 // 0x46 VISA Protocol , 0 // 0x47 Internet Packet Core Utility , 0 // 0x48 Computer Protocol Network Executive , 0 // 0x49 Computer Protocol Heart Beat , 0 // 0x4a Wang Span Network , 0 // 0x4b Packet Video Protocol , 0 // 0x4c Backroom SATNET Monitoring , 0 // 0x4d SUN ND Protocol , 0 // 0x4e Wideband Monitoring , 0 // 0x4f Wideband ExPak , 0 // 0x50 International Organization for Standardization Internet Protocol , 0 // 0x51 Versatile Message Transaction Protocol , 0 // 0x52 Secure Versatile Message Transaction Protocol , 0 // 0x53 VINES , 0 // 0x54 TTP, Internet Protocol Traffic Management , 0 // 0x55 NFSNET-IGP , 0 // 0x56 Disimilar Gateway Protocol , 0 // 0x57 TCF , 0 // 0x58 EIGRP , "OSPF" // 0x59 Open Shortest Path First , 0 // 0x5a Sprite RPC Protocol , 0 // 0x5b Locus Address Resolution Protocol , 0 // 0x5c Multicast Transport Protocol , 0 // 0x5d AX.25 , 0 // 0x5e IP-within-IP Encapsulation Protocol , 0 // 0x5f Mobile Internetworking Control Protocol , 0 // 0x60 Semaphore Communication Sec Protocol , 0 // 0x61 Ethernet-within-IP encapsulation , 0 // 0x62 Encapsulation Header , 0 // 0x63 Any private encryption scheme , 0 // 0x64 GMTP , 0 // 0x65 Ipsilon Flow Management Protocol , 0 // 0x66 PNNI over IP , 0 // 0x67 Protocol Independent Multicast , 0 // 0x68 IBM Aggregate Route IP Switching Protocol , 0 // 0x69 Space Communcations Protocol Standard , 0 // 0x6a QNX , 0 // 0x6b Active Networks , 0 // 0x6c IP Payload Compression Protocol , 0 // 0x6d Sitara Networks Protocol , 0 // 0x6e Compaq Peer Protocol , 0 // 0x6f IPX in IP , 0 // 0x70 Virtual Router Redundancy Protocol , 0 // 0x71 PGM Reliable Transport Protocol , 0 // 0x72 Any 0-hop protocol , 0 // 0x73 Layer Two Tunnelling Protocol , 0 // 0x74 D-II Data Exchange , 0 // 0x75 Interactive Agent Transfer Protocol , 0 // 0x76 Schedule Transfer Protocol , 0 // 0x77 SpectraLink Radio Protocol , 0 // 0x78 Univeral Transport Interface Protocol , 0 // 0x79 Simple Message Protocol , 0 // 0x7a Simple Multicast Protocol , 0 // 0x7b Performance Transparency Protocol , 0 // 0x7c Intermediate System to Intermediate System Protocol , 0 // 0x7d Flexible Intra-AS Routing Environment , 0 // 0x7e Combat Radio Transport Protocol , 0 // 0x7f Combat Radio User Datagram , 0 // 0x80 Service Specific Connection-oriented Protocol , 0 // 0x81 IPLT , 0 // 0x82 Secure Packet Shield , 0 // 0x83 Private IP Encapsulation within IP , "SCTP" // 0x84 Stream Control Transmission Protocol , 0 // 0x85 Fibre Channel , 0 // 0x86 Reservation Protocol End-to_End Ignore , 0 // 0x87 IPv6 Extension Mobilility Header , 0 // 0x88 Lightweight User Datagram Protocol , 0 // 0x89 MPLS within IP , 0 // 0x8a MANET Protocol , 0 // 0x8b Host Identity Protocol , 0 // 0x8c Site Multihoming by IPv6 Intermediation , 0 // 0x8d Wrapped Encapsulating Security Payload , 0 // 0x8e Robust Header Compression , 0 // 0x8f Unassigned }; } // anonymous namespace namespace xtreme { namespace iwf { class ManualParserHelper { public: void set_ethernet_frame(ParsedFrame* pf, const EthernetFrame* ethernet_frame) { pf->ethernet_frame_ = ethernet_frame; pf->ethernet_layer_ = ParsedFrame::ETHERNET_LAYER_; } void set_lower_ipv4_header(ParsedFrame* pf, const IPv4Header* ipv4_header) { pf->lower_network_header_ = ipv4_header; pf->lower_network_layer_ = ParsedFrame::IPv4_NETWORK_LAYER_; } void set_lower_ipv6_header(ParsedFrame* pf, const IPv6Header* ipv6_header) { pf->lower_network_header_ = ipv6_header; pf->lower_network_layer_ = ParsedFrame::IPv6_NETWORK_LAYER_; } void set_lower_udp_header(ParsedFrame* pf, const UDPHeader* udp_header) { pf->lower_transport_header_ = udp_header; pf->lower_transport_layer_ = ParsedFrame::UDP_TRANSPORT_LAYER_; } void set_lower_tcp_header(ParsedFrame* pf, const TCPHeader* tcp_header) { pf->lower_transport_header_ = tcp_header; pf->lower_transport_layer_ = ParsedFrame::TCP_TRANSPORT_LAYER_; } void set_lower_sctp_header(ParsedFrame* pf, const SCTPHeader* sctp_header) { pf->lower_transport_header_ = sctp_header; pf->lower_transport_layer_ = ParsedFrame::SCTP_TRANSPORT_LAYER_; } void set_gtpv1_header(ParsedFrame* pf, const GTPv1Header* gtpv1_header) { pf->gtp_header_ = gtpv1_header; pf->gtp_layer_ = ParsedFrame::GTPv1_LAYER_; } void set_gtpv2_header(ParsedFrame* pf, const GTPv2Header* gtpv2_header) { pf->gtp_header_ = gtpv2_header; pf->gtp_layer_ = ParsedFrame::GTPv2_LAYER_; } void set_upper_ipv4_header(ParsedFrame* pf, const IPv4Header* ipv4_header) { pf->upper_network_header_ = ipv4_header; pf->upper_network_layer_ = ParsedFrame::IPv4_NETWORK_LAYER_; } void set_upper_ipv6_header(ParsedFrame* pf, const IPv6Header* ipv6_header) { pf->upper_network_header_ = ipv6_header; pf->upper_network_layer_ = ParsedFrame::IPv6_NETWORK_LAYER_; } void set_upper_udp_header(ParsedFrame* pf, const UDPHeader* udp_header) { pf->upper_transport_header_ = udp_header; pf->upper_transport_layer_ = ParsedFrame::UDP_TRANSPORT_LAYER_; } void set_upper_tcp_header(ParsedFrame* pf, const TCPHeader* tcp_header) { pf->upper_transport_header_ = tcp_header; pf->upper_transport_layer_ = ParsedFrame::TCP_TRANSPORT_LAYER_; } void set_upper_sctp_header(ParsedFrame* pf, const SCTPHeader* sctp_header) { pf->upper_transport_header_ = sctp_header; pf->upper_transport_layer_ = ParsedFrame::SCTP_TRANSPORT_LAYER_; } }; class ManualParserDataSink::Impl { public: explicit Impl(iwf *manager); ~Impl(); bool decode(Event* frame); bool drop_before_manual_parser_; Telemetry telemetry_; private: bool decode_vlan(); bool decode_mpls(); bool decode_ipv4(bool is_parsing_upper = false); bool decode_ipv6(bool is_parsing_upper = false); bool decode_tcp(bool is_parsing_upper = false); bool decode_udp(bool is_parsing_upper = false); bool decode_sctp(bool is_parsing_upper = false); bool decode_gtp_control(); bool decode_gtp_user(); bool decode_gtpv1_header(); // Decode the payload as a IPv4 or IPv6 packet encapsulated by a tunnel protocol; // decoding stops at the transport-layer. // The parameter, tunnel_protocol_name, is for purpose of logging error message. // An example is "GTP-U". bool decode_tunnelled_ip(const std::string& tunnel_protocol_name); iwf *manager_; ManualParserHelper helper_; // Used by the various decoder stages. xtreme::ParsedFrame* pf_; const uint8_t* packet_data_; uint32_t packet_len_; uint32_t offset_; uint16_t eType_; uint8_t protocol_; uint8_t upper_protocol_; // Telemetry to capture characteristics of the traffic being decoded. bool telemetry_enabled_; uint32_t telemetry_period_; uint32_t throttle_; uint32_t throttle_threshold_; uint32_t last_check_sec_; Timestamp period_start_timestamp_; }; ManualParserDataSink::Impl::Impl(iwf *manager) { manager_ = manager; drop_before_manual_parser_ = false; try { if (manager_) { drop_before_manual_parser_ = manager_->GetCS().getCSParamAPI() ->get_bool("DEBUG/DROP_AT_MANUAL_PARSER_START"); } if (drop_before_manual_parser_) { LOG4CXX_INFO(g_logger, "Dropping frames before manual parsing"); } } catch(...) { } throttle_ = 0; throttle_threshold_ = 10000; last_check_sec_ = 0; telemetry_enabled_ = false; telemetry_period_ = 300; xtreme::config::CSParamAPI* config = nullptr; if (manager_) { config = manager_->GetCS().getCSParamAPI(); try { telemetry_enabled_ = config->get_bool("IWF/manual_parser_telemetry_enabled"); } catch(...) { } try { telemetry_period_ = config->get_uint("IWF/TELEMETRY_PERIOD"); } catch(...) { } } } ManualParserDataSink::Impl::~Impl() { } bool ManualParserDataSink::Impl::decode(Event* event) { if (event->type() != kEVENT_FRAME) { return false; } if (telemetry_enabled_) { ++telemetry_.frames; if (++throttle_ > throttle_threshold_) { throttle_ = 0; const uint32_t this_secs = event->timestamp().sec_; const uint32_t sec_diff = this_secs < last_check_sec_ ? 0 : this_secs - last_check_sec_; if (sec_diff > 10) { last_check_sec_ = this_secs; Timestamp now = Timestamp::SystemNow(); if (period_start_timestamp_.sec_ == 0) { period_start_timestamp_ = now; } else { Duration delta = now - period_start_timestamp_; if (delta.sec() >= telemetry_period_) { telemetry_.dump(); telemetry_.reset(); } } } } } FrameEvent* frame = static_cast<FrameEvent*>(event); pf_ = frame->parsed_frame(); packet_data_ = frame->payload(); packet_len_ = frame->payload_len(); offset_ = 0; if (packet_len_ < sizeof(EthernetFrame)) { LOG_DEBUG("ManualParser::decode: payload is too small to hold an ethernet frame, " "packet={ " << hex_dump(packet_data_, packet_len_) << " }"); return false; } // See http://en.wikipedia.org/wiki/Ethernet_frame helper_.set_ethernet_frame(pf_, reinterpret_cast<const EthernetFrame*>(packet_data_)); offset_ += sizeof *pf_->ethernet_frame_; eType_ = pf_->ethernet_frame_->ether_type_; bool mpls = false; LOG_TRACE("dest=" << pf_->ethernet_frame_->dest_mac_addr() << " src=" << pf_->ethernet_frame_->src_mac_addr() << " ether-type=" << dump_ether_type(eType_)); do { if (eType_ == ETHER_PROTO_VLAN) { if (pf_->vlan_ptr_ == nullptr) { pf_->vlan_ptr_ = reinterpret_cast<const VlanTag*>(&pf_->ethernet_frame_->ether_type_); if (telemetry_enabled_) ++telemetry_.vlan; } if (!decode_vlan()) { return false; } } else if (eType_ == ETHER_PROTO_MPLS_UNICAST || eType_ == ETHER_PROTO_MPLS_MULTICAST) { mpls = true; if (!decode_mpls()) { return false; } else { break; } } else if (eType_ != ETHER_PROTO_IPV4 && eType_ != ETHER_PROTO_IPV6) { if (eType_ == ETHER_PROTO_ARP) { if (telemetry_enabled_) { ++telemetry_.arp; } LOG_TRACE("ARP packet"); } else if (eType_ == ETHER_PROTO_RARP) { if (telemetry_enabled_) { ++telemetry_.rarp; } LOG_TRACE("RARP packet"); } else { if (telemetry_enabled_) { ++telemetry_.other_etypes; } LOG_TRACE("not ip-based ether-type=" << dump_ether_type(eType_)); } return false; } } while (eType_ != ETHER_PROTO_IPV4 && eType_ != ETHER_PROTO_IPV6); // 1. In some packets, the type in the ethernet frame is 0x0800 but the version number in the // IPv4 header is 6. The ethernet frame type should have been 0x86DD to indicate it is an // IPv6 packet. // 2. When MPLS stack exist in the packet, the eType will be set to 0x8847 or 0x8848. And the // following stack will be IP, therefore need to check the first byte of the coming data to // determine the version of IP is used. uint8_t ip_version = 0; if (eType_ == ETHER_PROTO_IPV4 || eType_ == ETHER_PROTO_IPV6 || mpls) { const IPv4Header* ip4 = reinterpret_cast<const IPv4Header*>(packet_data_ + offset_); ip_version = ip4->version(); if (!mpls) { if (ip_version == 6) { eType_ = ETHER_PROTO_IPV6; LOG_TRACE("ipv6 packet masquerading as ipv4"); } } } if (telemetry_enabled_) { if (mpls) { ++telemetry_.mpls; } if (ip_version == 4) { ++telemetry_.lower_ipv4; } else if (ip_version == 6) { ++telemetry_.lower_ipv6; } } if (eType_ == ETHER_PROTO_IPV4 || (mpls && ip_version == 4)) { if (!decode_ipv4()) { return false; } } else if (eType_ == ETHER_PROTO_IPV6 || (mpls && ip_version == 6)) { if (!decode_ipv6()) { return false; } } else { LOG4CXX_ERROR(g_logger, "this can't happen"); return false; } if (telemetry_enabled_) { ++telemetry_.lower_protocols[protocol_]; } if (const IPv4Header* ipv4 = pf_->lower_ipv4_header()) { if (ipv4->offset()) { // When IP fragments, only the first fragment contains the transport protocol header, // the other fragments (non-zero offset) cannot be decoded. ++telemetry_.lower_protocols_ipv4_frags[protocol_]; return true; } } else if (const IPv6ExtHeaders* headers = pf_->lower_ipv6_ext_headers()) { if (headers->fragment_present()) { IPv6FragmentHeader f = headers->fragment_header(); if (f.fragment_offset()) { // When IP fragments, only the first fragment contains the transport protocol // header, the other fragments (non-zero offset) cannot be decoded. ++telemetry_.lower_protocols_ipv6_frags[protocol_]; return true; } } } if (protocol_ == UDP_PROTOCOL) { if (!decode_udp()) { return false; } } else if (protocol_ == TCP_PROTOCOL) { if (!decode_tcp()) { return false; } } else if (protocol_ == SCTP_PROTOCOL) { if (!decode_sctp()) { return false; } } else { // TODO(fclim): handle other transport-layer protocols besides TCP, UDP, and SCTP. LOG_TRACE("ether-type=" << dump_ether_type(eType_) << " protocol=" << static_cast<unsigned int>(protocol_)); } return true; } bool ManualParserDataSink::Impl::decode_vlan() { // See http://en.wikipedia.org/wiki/802.1Q_VLAN_tag const VlanTag* vlan = &pf_->vlan_ptr_[pf_->vlan_count_]; if (offset_ + sizeof *vlan > packet_len_) { LOG_DEBUG("ManualParser::decode: payload is too small to hold a VLAN tag, " "packet={ " << hex_dump(packet_data_, packet_len_) << " }"); return false; } eType_ = *reinterpret_cast<const uint16_t*>(packet_data_ + offset_ + 2); LOG_TRACE("vlan-tag=" << dump_vlan(vlan) << " " << *vlan << " next-ether-type=" << dump_ether_type(eType_)); ++pf_->vlan_count_; offset_ += sizeof *vlan; return true; } bool ManualParserDataSink::Impl::decode_mpls() { // See http://www.ietf.org/rfc/rfc3032.txt const MplsEntry* mpls; do { if (offset_ + sizeof *mpls > packet_len_) { LOG_DEBUG("ManualParser::decode: payload is too small to hold a MPLS tag," " packet={ " << hex_dump(packet_data_, packet_len_) << " }"); return false; } mpls = reinterpret_cast<const MplsEntry*>(packet_data_ + offset_); LOG_TRACE("mpls(whole tag)=" << dump_mpls(mpls) << " " << *mpls); // to record down the first label position if (pf_->mpls_count_ == 0) pf_->mpls_ptr_ = mpls; ++pf_->mpls_count_; offset_ += sizeof *mpls; } while (!mpls->is_bottom()); // loop until s bit(Bottom of Stack) is set to 1 return true; } bool ManualParserDataSink::Impl::decode_ipv4(bool is_parsing_upper) { // See http://en.wikipedia.org/wiki/IPv4 if (offset_ + sizeof(IPv4Header) > packet_len_) { if (is_parsing_upper) { // Handle GTP Error Indicator 0x1a if (const GTPv1Header* gtpv1_header = pf_->gtpv1_header()) { if (gtpv1_header->message_type_ == 0x1a) { return false; } } if (const GTPv2Header* gtpv2_header = pf_->gtpv2_header()) { if (gtpv2_header->message_type_ == 0x1a) { return false; } } } LOG_DEBUG("ManualParser::decode: payload is too small to hold the IPv4 header, " "packet={ " << hex_dump(packet_data_, packet_len_) << " }"); return false; } const IPv4Header* ipv4_header = reinterpret_cast<const IPv4Header*>(packet_data_ + offset_); offset_ += sizeof *ipv4_header; if (ipv4_header->ihl() > 5) { if ((offset_ + (ipv4_header->ihl() - 5) * sizeof(uint32_t)) > packet_len_) { LOG_DEBUG("ManualParser::decode: payload is too small to hold the IPv4 options, " "packet={ " << hex_dump(packet_data_, packet_len_) << " }"); return false; } offset_ += (ipv4_header->ihl() - 5) * sizeof(uint32_t); } if (is_parsing_upper) { upper_protocol_ = ipv4_header->protocol_; helper_.set_upper_ipv4_header(pf_, ipv4_header); pf_->upper_ipv4_options_.set_ipv4_header(ipv4_header); } else { protocol_ = ipv4_header->protocol_; helper_.set_lower_ipv4_header(pf_, ipv4_header); pf_->lower_ipv4_options_.set_ipv4_header(ipv4_header); } LOG_TRACE((is_parsing_upper ? "upper" : "lower") << " ipv4 src-ip=" << ipv4_header->src_ip_addr() << " dest-ip=" << ipv4_header->dest_ip_addr() << " protocol=" << static_cast<unsigned int>(ipv4_header->protocol_)); return true; } bool ManualParserDataSink::Impl::decode_ipv6(bool is_parsing_upper) { // See http://en.wikipedia.org/wiki/IPv6_packet if (offset_ + sizeof(IPv6Header) > packet_len_) { if (is_parsing_upper) { // Handle GTP Error Indicator 0x1a if (const GTPv1Header* gtpv1_header = pf_->gtpv1_header()) { if (gtpv1_header->message_type_ == 0x1a) { return false; } } if (const GTPv2Header* gtpv2_header = pf_->gtpv2_header()) { if (gtpv2_header->message_type_ == 0x1a) { return false; } } } LOG_DEBUG("ManualParser::decode: payload is too small to hold the IPv6 header, " "packet={ " << hex_dump(packet_data_, packet_len_) << " }"); return false; } const IPv6Header* ipv6_header = reinterpret_cast<const IPv6Header*>(packet_data_ + offset_); IPv6ExtHeaders* ipv6_ext_headers = nullptr; if (is_parsing_upper) { helper_.set_upper_ipv6_header(pf_, ipv6_header); ipv6_ext_headers = &pf_->upper_ipv6_ext_headers_; ipv6_ext_headers->decode(packet_data_, packet_len_, offset_); upper_protocol_ = ipv6_ext_headers->protocol(); } else { helper_.set_lower_ipv6_header(pf_, ipv6_header); ipv6_ext_headers = &pf_->lower_ipv6_ext_headers_; ipv6_ext_headers->decode(packet_data_, packet_len_, offset_); protocol_ = ipv6_ext_headers->protocol(); } offset_ += sizeof *ipv6_header; offset_ += ipv6_ext_headers->headers_length(); LOG_TRACE((is_parsing_upper ? "upper" : "lower") << " ipv6 src-ip=" << ipv6_header->source_addr() << " dest-ip=" << ipv6_header->dest_addr() << " protocol=" << static_cast<unsigned int>(ipv6_ext_headers->protocol())); return true; } bool ManualParserDataSink::Impl::decode_tcp(bool is_parsing_upper) { // See http://en.wikipedia.org/wiki/Transmission_Control_Protocol if (offset_ + sizeof(TCPHeader) > packet_len_) { if (is_parsing_upper) { // Handle GTP Error Indicator 0x1a if (const GTPv1Header* gtpv1_header = pf_->gtpv1_header()) { if (gtpv1_header->message_type_ == 0x1a) { return false; } } if (const GTPv2Header* gtpv2_header = pf_->gtpv2_header()) { if (gtpv2_header->message_type_ == 0x1a) { return false; } } } LOG_DEBUG("ManualParser::decode: payload is too small to hold the TCP header, " "packet={ " << hex_dump(packet_data_, packet_len_) << " }"); return false; } const TCPHeader* tcp_header = reinterpret_cast<const TCPHeader*>(packet_data_ + offset_); offset_ += sizeof *tcp_header; TCPOptions* tcp_options = nullptr; if (is_parsing_upper) { helper_.set_upper_tcp_header(pf_, tcp_header); tcp_options = &pf_->upper_tcp_options_; } else { helper_.set_lower_tcp_header(pf_, tcp_header); tcp_options = &pf_->lower_tcp_options_; } tcp_options->set_tcp_header(tcp_header); tcp_options->set_packet(packet_data_, packet_len_); LOG_TRACE((is_parsing_upper ? "upper" : "lower") << " tcp src-port=" << tcp_header->source_port() << " dest-port=" << tcp_header->dest_port()); return true; } bool ManualParserDataSink::Impl::decode_udp(bool is_parsing_upper) { // See http://en.wikipedia.org/wiki/User_Datagram_Protocol if (offset_ + sizeof(UDPHeader) > packet_len_) { if (is_parsing_upper) { // Handle GTP Error Indicator 0x1a if (const GTPv1Header* gtpv1_header = pf_->gtpv1_header()) { if (gtpv1_header->message_type_ == 0x1a) { return false; } } if (const GTPv2Header* gtpv2_header = pf_->gtpv2_header()) { if (gtpv2_header->message_type_ == 0x1a) { return false; } } } LOG_DEBUG("ManualParser::decode: payload is too small to hold the UDP header," " packet={ " << hex_dump(packet_data_, packet_len_) << " }"); return false; } const UDPHeader* udp_header = reinterpret_cast<const UDPHeader*>(packet_data_ + offset_); offset_ += sizeof *udp_header; if (is_parsing_upper) { helper_.set_upper_udp_header(pf_, udp_header); } else { helper_.set_lower_udp_header(pf_, udp_header); } LOG_TRACE((is_parsing_upper ? "upper" : "lower") << " udp src-port=" << udp_header->source_port() << " dest-port=" << udp_header->dest_port() << " payload-length=" << udp_header->length()); if (!is_parsing_upper) { if (pf_->is_gtp_u_packet()) { if (telemetry_enabled_) ++telemetry_.up_frames; if (!decode_gtp_user()) { return false; } } else if (pf_->is_gtp_c_packet()) { if (telemetry_enabled_) ++telemetry_.cp_frames; if (!decode_gtp_control()) { return false; } } } return true; } bool ManualParserDataSink::Impl::decode_sctp(bool is_parsing_upper) { // See http://en.wikipedia.org/wiki/SCTP_packet_structure if (offset_ + sizeof(SCTPHeader) > packet_len_) { LOG_DEBUG("ManualParser::decode: payload is too small to hold the SCTP header, " "packet={ " << hex_dump(packet_data_, packet_len_) << " }"); return false; } const SCTPHeader* sctp_header = reinterpret_cast<const SCTPHeader*>(packet_data_ + offset_); offset_ += sizeof *sctp_header; if (is_parsing_upper) { helper_.set_upper_sctp_header(pf_, sctp_header); } else { helper_.set_lower_sctp_header(pf_, sctp_header); } #if 0 // below code has problem , deadloop sometimes. uint8_t& sctp_chunks_count = is_parsing_upper ? pf_->upper_.sctp_chunks_count_ : pf_->sctp_chunks_count_; const SCTPChunk** sctp_chunks = is_parsing_upper ? pf_->upper_.sctp_chunks_ : pf_->sctp_chunks_; while (offset_ + sizeof(SCTPChunk) < packet_len_) { const SCTPChunk* chunk = reinterpret_cast<const SCTPChunk*>(packet_data_ + offset_); uint16_t length = chunk->length(); if (length == 0) { LOG_DEBUG("ManualParser::decode: SCTP chunk has zero length"); break; } if (sctp_chunks_count < ParsedFrame::MAX_SCTP_CHUNKS) { sctp_chunks[sctp_chunks_count++] = chunk; } uint16_t remainder = length % 4; if (remainder) { length += 4 - remainder; } offset_ += length; if (!length) { break; } } #endif LOG_TRACE((is_parsing_upper ? "upper" : "lower") << " sctp src-port=" << sctp_header->source_port() << " dest-port=" << sctp_header->dest_port()); return true; } bool ManualParserDataSink::Impl::decode_gtp_control() { // See http://en.wikipedia.org/wiki/GPRS_Tunnelling_Protocol if (offset_ + 8 > packet_len_) { LOG_DEBUG("ManualParser::decode: payload is too small to hold the GTP-C header, " "packet={ " << hex_dump(packet_data_, packet_len_) << " }"); return false; } const GTPv1Header* gtp1 = reinterpret_cast<const GTPv1Header*>(packet_data_ + offset_); if (gtp1->version() == 0x01) { if (!decode_gtpv1_header()) { return false; } LOG_TRACE("GTPv1-C message-type=" << static_cast<int>(gtp1->message_type_)); // Handle GTP Error Indicator 0x1a if (const GTPv1Header* gtpv1_header = pf_->gtpv1_header()) { if (gtpv1_header->message_type_ == 0x1a) { return true; } } } else { const GTPv2Header* gtpv2_header = reinterpret_cast<const GTPv2Header*>(packet_data_ + offset_); helper_.set_gtpv2_header(pf_, gtpv2_header); if (gtpv2_header->t_flag()) { offset_ += 12; } else { offset_ += 8; } LOG_TRACE("GTPv2-C message-type=" << static_cast<int>(gtpv2_header->message_type_)); // Handle GTP Error Indicator 0x1a if (gtpv2_header->message_type_ == 0x1a) { return true; } } return true; } bool ManualParserDataSink::Impl::decode_gtp_user() { // See http://en.wikipedia.org/wiki/GPRS_Tunnelling_Protocol if (offset_ + 8 > packet_len_) { LOG_DEBUG("ManualParser::decode: payload is too small to hold the GTP-U header, " "packet={ " << hex_dump(packet_data_, packet_len_) << " }"); return false; } if (!decode_gtpv1_header()) { return false; } // Handle GTP Error Indicator 0x1a if (const GTPv1Header* gtpv1_header = pf_->gtpv1_header()) { if (gtpv1_header->message_type_ == 0x1a) { return true; } } // To confirm that decode_tunnelled_ip() only modifies the data members of parsed_frame->upper_, // prints the pointers to the lower ip, etc before and after. LOG_TRACE("GTP-U packet, lower-ipv4-header=" << pf_->lower_ipv4_header() << " lower-ipv6-header=" << pf_->lower_ipv6_header() << " lower-tcp-header=" << pf_->lower_tcp_header() << " lower-udp-header=" << pf_->lower_udp_header() << " lower-sctp-header=" << pf_->lower_sctp_header() << " message-type=" << static_cast<int>(pf_->gtpv1_header()->message_type_)); static const std::string gtpu_str("GTP-U"); if (!decode_tunnelled_ip(gtpu_str)) { return false; } LOG_TRACE("GTP-U packet, lower-ipv4-header=" << pf_->lower_ipv4_header() << " lower-ipv6-header=" << pf_->lower_ipv6_header() << " lower-tcp-header=" << pf_->lower_tcp_header() << " lower-udp-header=" << pf_->lower_udp_header() << " lower-sctp-header=" << pf_->lower_sctp_header() << " upper-ipv4-header=" << pf_->upper_ipv4_header() << " upper-ipv6-header=" << pf_->upper_ipv6_header() << " upper-tcp-header=" << pf_->upper_tcp_header() << " upper-udp-header=" << pf_->upper_udp_header() << " upper-sctp-header=" << pf_->upper_sctp_header()); return true; } bool ManualParserDataSink::Impl::decode_gtpv1_header() { // See http://en.wikipedia.org/wiki/GPRS_Tunnelling_Protocol // See 3GPP TS 29.281 V10.1.0 (2011-03) const GTPv1Header* gtp1 = reinterpret_cast<const GTPv1Header*>(packet_data_ + offset_); helper_.set_gtpv1_header(pf_, gtp1); if (!(gtp1->e_flag() || gtp1->s_flag() || gtp1->pn_flag())) { offset_ += 8; } else { if (offset_ + 12 > packet_len_) { return false; } offset_ += 12; if (gtp1->e_flag()) { while (packet_data_[offset_ - 1]) { uint8_t n = packet_data_[offset_]; if (n == 0) { LOG_DEBUG("ManualParser::decode: GTPv1 extension header has zero length"); return false; } offset_ += 4 * n; if (offset_ > packet_len_) { return false; } } } } return true; } bool ManualParserDataSink::Impl::decode_tunnelled_ip(const std::string& tunnel_protocol_name) { const IPv4Header* ip4 = reinterpret_cast<const IPv4Header*>(packet_data_ + offset_); if (ip4->version() == 4) { if (telemetry_enabled_) ++telemetry_.upper_ipv4; if (!decode_ipv4(true)) { return false; } } else if (ip4->version() == 6) { if (telemetry_enabled_) ++telemetry_.upper_ipv6; if (!decode_ipv6(true)) { return false; } } else { if (telemetry_enabled_) ++telemetry_.upper_non_ip; LOG_TRACE(tunnel_protocol_name << " packet not embedding IPv4 or IPv6"); return false; } if (telemetry_enabled_) ++telemetry_.upper_protocols[upper_protocol_]; if (const IPv4Header* ipv4 = pf_->upper_ipv4_header()) { if (ipv4->offset()) { // When IP fragments, only the first fragment contains the transport protocol header, // the other fragments (non-zero offset) cannot be decoded. ++telemetry_.upper_protocols_ipv4_frags[upper_protocol_]; return true; } } else if (const IPv6ExtHeaders* headers = pf_->upper_ipv6_ext_headers()) { if (headers->fragment_present()) { IPv6FragmentHeader f = headers->fragment_header(); if (f.fragment_offset()) { // When IP fragments, only the first fragment contains the transport protocol // header, the other fragments (non-zero offset) cannot be decoded. ++telemetry_.upper_protocols_ipv6_frags[upper_protocol_]; return true; } } } if (upper_protocol_ == UDP_PROTOCOL) { if (!decode_udp(true)) return false; } else if (upper_protocol_ == TCP_PROTOCOL) { if (!decode_tcp(true)) return false; } else if (upper_protocol_ == SCTP_PROTOCOL) { if (!decode_sctp(true)) return false; } else { LOG_TRACE(tunnel_protocol_name << " packet not embedding TCP, UDP, or SCTP"); } return true; } void ManualParserDataSink::Telemetry::dump() const { std::ostringstream s; s << "frames=" << frames << " vlan=" << vlan << " mpls=" << mpls << " ipv4=" << lower_ipv4 << " ipv6=" << lower_ipv6 << " arp=" << arp << " rarp=" << rarp << " other-etypes=" << other_etypes; for (size_t i = 0; i < 0x8F; ++i) { if (lower_protocols[i] == 0) { continue; } if (g_protocol_names[i] == 0) { s << " P=" << i; } else { s << " " << g_protocol_names[i]; } s << ":" << lower_protocols[i]; } s << " ipv4-frags "; for (size_t i = 0; i < 0x8F; ++i) { if (lower_protocols_ipv4_frags[i] == 0) { continue; } if (g_protocol_names[i] == 0) { s << " P=" << i; } else { s << " " << g_protocol_names[i]; } s << ":" << lower_protocols_ipv4_frags[i]; } s << " ipv6-frags "; for (size_t i = 0; i < 0x8F; ++i) { if (lower_protocols_ipv6_frags[i] == 0) { continue; } if (g_protocol_names[i] == 0) { s << " P=" << i; } else { s << " " << g_protocol_names[i]; } s << ":" << lower_protocols_ipv6_frags[i]; } s << " cp=" << cp_frames << " up=" << up_frames; s << " upper-ipv4=" << upper_ipv4 << " upper-ipv6=" << upper_ipv6 << " upper-non-ip=" << upper_non_ip; for (size_t i = 0; i < 0x8F; ++i) { if (upper_protocols[i] == 0) { continue; } if (g_protocol_names[i] == 0) { s << " P=" << i; } else { s << " " << g_protocol_names[i]; } s << ":" << upper_protocols[i]; } LOG4CXX_INFO(g_telemetry_logger, s.str()) } ManualParserDataSink::ManualParserDataSink(iwf *manager) : IDataSink(MANUAL_PARSING_DATA_SINK_TYPE) , impl_(new Impl(manager)) { } ManualParserDataSink::~ManualParserDataSink() { delete impl_; } void ManualParserDataSink::process(const Event* event) { if (impl_->drop_before_manual_parser_ && event->type() == kEVENT_FRAME) { delete event; return; } impl_->decode(const_cast<Event*>(event)); if (data_sink_) { data_sink_->process(event); } } } // namespace iwf } // namespace xtreme
[STATEMENT] lemma [code]: "new_array v == new_array' v o integer_of_nat" "array_length == nat_of_integer o array_length'" "array_get a == array_get' a o integer_of_nat" "array_set a == array_set' a o integer_of_nat" "array_grow a == array_grow' a o integer_of_nat" "array_shrink a == array_shrink' a o integer_of_nat" "array_get_oo x a == array_get_oo' x a o integer_of_nat" "array_set_oo f a == array_set_oo' f a o integer_of_nat" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (((new_array v \<equiv> new_array' v \<circ> integer_of_nat) &&& array_length \<equiv> nat_of_integer \<circ> array_length') &&& (array_get a \<equiv> array_get' a \<circ> integer_of_nat) &&& array_set a \<equiv> array_set' a \<circ> integer_of_nat) &&& ((array_grow a \<equiv> array_grow' a \<circ> integer_of_nat) &&& array_shrink a \<equiv> array_shrink' a \<circ> integer_of_nat) &&& (array_get_oo x a \<equiv> array_get_oo' x a \<circ> integer_of_nat) &&& array_set_oo f a \<equiv> array_set_oo' f a \<circ> integer_of_nat [PROOF STEP] by (simp_all add: o_def add: new_array'_def array_length'_def array_get'_def array_set'_def array_grow'_def array_shrink'_def array_get_oo'_def array_set_oo'_def)
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury G. Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.algebra.monoid import Mathlib.algebra.group.pi import Mathlib.PostPort universes u_1 u_2 u_3 l namespace Mathlib /-! # Topological group with zero In this file we define `has_continuous_inv'` to be a mixin typeclass a type with `has_inv` and `has_zero` (e.g., a `group_with_zero`) such that `λ x, x⁻¹` is continuous at all nonzero points. Any normed (semi)field has this property. Currently the only example of `has_continuous_inv'` in `mathlib` which is not a normed field is the type `nnnreal` (a.k.a. `ℝ≥0`) of nonnegative real numbers. Then we prove lemmas about continuity of `x ↦ x⁻¹` and `f / g` providing dot-style `*.inv'` and `*.div` operations on `filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`, and `continuous`. As a special case, we provide `*.div_const` operations that require only `group_with_zero` and `has_continuous_mul` instances. All lemmas about `(⁻¹)` use `inv'` in their names because lemmas without `'` are used for `topological_group`s. We also use `'` in the typeclass name `has_continuous_inv'` for the sake of consistency of notation. -/ /-! ### A group with zero with continuous multiplication If `G₀` is a group with zero with continuous `(*)`, then `(/y)` is continuous for any `y`. In this section we prove lemmas that immediately follow from this fact providing `*.div_const` dot-style operations on `filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`, and `continuous`. -/ theorem filter.tendsto.div_const {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_mul G₀] {f : α → G₀} {l : filter α} {x : G₀} {y : G₀} (hf : filter.tendsto f l (nhds x)) : filter.tendsto (fun (a : α) => f a / y) l (nhds (x / y)) := sorry theorem continuous_at.div_const {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_mul G₀] {f : α → G₀} [topological_space α] (hf : continuous f) {y : G₀} : continuous fun (x : α) => f x / y := sorry theorem continuous_within_at.div_const {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_mul G₀] {f : α → G₀} {s : set α} [topological_space α] {a : α} (hf : continuous_within_at f s a) {y : G₀} : continuous_within_at (fun (x : α) => f x / y) s a := filter.tendsto.div_const hf theorem continuous_on.div_const {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_mul G₀] {f : α → G₀} {s : set α} [topological_space α] (hf : continuous_on f s) {y : G₀} : continuous_on (fun (x : α) => f x / y) s := sorry theorem continuous.div_const {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_mul G₀] {f : α → G₀} [topological_space α] (hf : continuous f) {y : G₀} : continuous fun (x : α) => f x / y := sorry /-- A type with `0` and `has_inv` such that `λ x, x⁻¹` is continuous at all nonzero points. Any normed (semi)field has this property. -/ class has_continuous_inv' (G₀ : Type u_3) [HasZero G₀] [has_inv G₀] [topological_space G₀] where continuous_at_inv' : ∀ {x : G₀}, x ≠ 0 → continuous_at has_inv.inv x /-! ### Continuity of `λ x, x⁻¹` at a non-zero point We define `topological_group_with_zero` to be a `group_with_zero` such that the operation `x ↦ x⁻¹` is continuous at all nonzero points. In this section we prove dot-style `*.inv'` lemmas for `filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`, and `continuous`. -/ theorem tendsto_inv' {G₀ : Type u_2} [HasZero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv' G₀] {x : G₀} (hx : x ≠ 0) : filter.tendsto has_inv.inv (nhds x) (nhds (x⁻¹)) := continuous_at_inv' hx theorem continuous_on_inv' {G₀ : Type u_2} [HasZero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv' G₀] : continuous_on has_inv.inv (singleton 0ᶜ) := fun (x : G₀) (hx : x ∈ (singleton 0ᶜ)) => continuous_at.continuous_within_at (continuous_at_inv' hx) /-- If a function converges to a nonzero value, its inverse converges to the inverse of this value. We use the name `tendsto.inv'` as `tendsto.inv` is already used in multiplicative topological groups. -/ theorem filter.tendsto.inv' {α : Type u_1} {G₀ : Type u_2} [HasZero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv' G₀] {l : filter α} {f : α → G₀} {a : G₀} (hf : filter.tendsto f l (nhds a)) (ha : a ≠ 0) : filter.tendsto (fun (x : α) => f x⁻¹) l (nhds (a⁻¹)) := filter.tendsto.comp (tendsto_inv' ha) hf theorem continuous_within_at.inv' {α : Type u_1} {G₀ : Type u_2} [HasZero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv' G₀] {f : α → G₀} {s : set α} {a : α} [topological_space α] (hf : continuous_within_at f s a) (ha : f a ≠ 0) : continuous_within_at (fun (x : α) => f x⁻¹) s a := filter.tendsto.inv' hf ha theorem continuous_at.inv' {α : Type u_1} {G₀ : Type u_2} [HasZero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv' G₀] {f : α → G₀} {a : α} [topological_space α] (hf : continuous_at f a) (ha : f a ≠ 0) : continuous_at (fun (x : α) => f x⁻¹) a := filter.tendsto.inv' hf ha theorem continuous.inv' {α : Type u_1} {G₀ : Type u_2} [HasZero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv' G₀] {f : α → G₀} [topological_space α] (hf : continuous f) (h0 : ∀ (x : α), f x ≠ 0) : continuous fun (x : α) => f x⁻¹ := iff.mpr continuous_iff_continuous_at fun (x : α) => filter.tendsto.inv' (continuous.tendsto hf x) (h0 x) theorem continuous_on.inv' {α : Type u_1} {G₀ : Type u_2} [HasZero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv' G₀] {f : α → G₀} {s : set α} [topological_space α] (hf : continuous_on f s) (h0 : ∀ (x : α), x ∈ s → f x ≠ 0) : continuous_on (fun (x : α) => f x⁻¹) s := fun (x : α) (hx : x ∈ s) => continuous_within_at.inv' (hf x hx) (h0 x hx) /-! ### Continuity of division If `G₀` is a `group_with_zero` with `x ↦ x⁻¹` continuous at all nonzero points and `(*)`, then division `(/)` is continuous at any point where the denominator is continuous. -/ theorem filter.tendsto.div {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_inv' G₀] [has_continuous_mul G₀] {f : α → G₀} {g : α → G₀} {l : filter α} {a : G₀} {b : G₀} (hf : filter.tendsto f l (nhds a)) (hg : filter.tendsto g l (nhds b)) (hy : b ≠ 0) : filter.tendsto (f / g) l (nhds (a / b)) := sorry theorem continuous_within_at.div {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_inv' G₀] [has_continuous_mul G₀] {f : α → G₀} {g : α → G₀} [topological_space α] {s : set α} {a : α} (hf : continuous_within_at f s a) (hg : continuous_within_at g s a) (h₀ : g a ≠ 0) : continuous_within_at (f / g) s a := filter.tendsto.div hf hg h₀ theorem continuous_on.div {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_inv' G₀] [has_continuous_mul G₀] {f : α → G₀} {g : α → G₀} [topological_space α] {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) (h₀ : ∀ (x : α), x ∈ s → g x ≠ 0) : continuous_on (f / g) s := fun (x : α) (hx : x ∈ s) => continuous_within_at.div (hf x hx) (hg x hx) (h₀ x hx) /-- Continuity at a point of the result of dividing two functions continuous at that point, where the denominator is nonzero. -/ theorem continuous_at.div {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_inv' G₀] [has_continuous_mul G₀] {f : α → G₀} {g : α → G₀} [topological_space α] {a : α} (hf : continuous_at f a) (hg : continuous_at g a) (h₀ : g a ≠ 0) : continuous_at (f / g) a := filter.tendsto.div hf hg h₀ theorem continuous.div {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_inv' G₀] [has_continuous_mul G₀] {f : α → G₀} {g : α → G₀} [topological_space α] (hf : continuous f) (hg : continuous g) (h₀ : ∀ (x : α), g x ≠ 0) : continuous (f / g) := eq.mpr (id ((fun (f f_1 : α → G₀) (e_3 : f = f_1) => congr_arg continuous e_3) (f / g) (f * (g⁻¹)) (div_eq_mul_inv f g))) (eq.mp (Eq.refl (continuous fun (x : α) => f x * (g x⁻¹))) (continuous.mul hf (continuous.inv' hg h₀))) theorem continuous_on_div {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_inv' G₀] [has_continuous_mul G₀] : continuous_on (fun (p : G₀ × G₀) => prod.fst p / prod.snd p) (set_of fun (p : G₀ × G₀) => prod.snd p ≠ 0) := continuous_on.div continuous_on_fst continuous_on_snd fun (_x : G₀ × G₀) => id end Mathlib
# Function to fit discrete heavy tail functions # Mostly using poweRlaw package # fit_dis_heavy_tail <- function (data_set,xmins,options.output) { require(fitdistrplus) n <- length(unique(data_set)) n_models <- 6 # List of models model_list = list(list(model=vector("list", length=0), GOF=vector("list", length=0), xmin_estimation=vector("list", length=0), uncert_estimation=vector("list", length=0), k=0, LL=0, n=n, AICc=0, delta_AICc=0, AICc_weight=0, model_name=character(0), model_set=character(0))) fit_ht <- rep(model_list,n_models) dim(fit_ht) <- c(n_models) # Declare models # # Discrete power law fit_ht[[1]]$model <- displ$new(data_set) fit_ht[[1]]$k <- 1 # Discrete log-normal fit_ht[[2]]$model <- dislnorm$new(data_set) fit_ht[[2]]$k <- 2 # Discrete exponential fit_ht[[3]]$model <- disexp$new(data_set) fit_ht[[3]]$k <- 1 # Poisson fit_ht[[4]]$model <- dispois$new(data_set) fit_ht[[4]]$k <- 1 # power law with exponential cutoff fit_ht[[5]]$model <- "" fit_ht[[5]]$k <- 2 # Uniform fit_ht[[6]]$model <- "" fit_ht[[6]]$k <- 1 # Estimate Xmin with complete data_set for power law model # if(xmins>1) { fit_ht[[1]]$xmin_estimation <- estimate_xmin(fit_ht[[1]]$model, xmins = 1:xmins, pars = NULL, xmax = max(data_set)) fit_ht[[1]]$model$setXmin(fit_ht[[1]]$xmin_estimation) } else { fit_ht[[1]]$model$setXmin(1) } model_names <- c("Power", "LogNorm","Exp","Poisson","PowerExp","Uniform") AICc_weight <- matrix( nrow = n_models, ncol = 1, dimnames = list(model_names)) delta_AICc <- AICc_weight GOF <- delta_AICc aic_min=Inf norm_aic_weight=0 for (i in 1:(n_models)) { # Set cut-off (x_min) fit_ht[[i]]$model$xmin <- fit_ht[[1]]$model$xmin # Correct n with xmin fit_ht[[i]]$n <-length(data_set[data_set>=fit_ht[[1]]$model$xmin]) # Fit models # PowerExp is different!!!!!!!!! # if(i<5){ fit_ht[[i]]$model$setPars(estimate_pars(fit_ht[[i]]$model)) # # Get Loglikelihood fit_ht[[i]]$LL <- dist_ll(fit_ht[[i]]$model) } else if(i==5) { # Fit Power Exponential (not poweRlaw package) # fit_ht[[i]]$model<- discpowerexp.fit(data_set,fit_ht[[1]]$model$xmin) # # Get Loglikelihood fit_ht[[i]]$LL <- fit_ht[[i]]$model$loglike } else if(i==6) { # Fit Power Exponential (not poweRlaw package) # fit_ht[[i]]$model<- max(data_set) teta<- max(data_set) # # Get Loglikelihood fit_ht[[i]]$LL <- log(teta^(-length(data_set))) } # # Get Loglikelihood LL <- fit_ht[[i]]$LL k <- fit_ht[[i]]$k # Compute AICc # fit_ht[[i]]$AICc <- (2*k-2*LL)+2*k*(k+1)/(n-k-1) aic_min <- min(aic_min,fit_ht[[i]]$AICc) fit_ht[[i]]$model_name <- model_names[i] } for (i in 1:n_models){ delta_AICc[i] <- fit_ht[[i]]$AICc - aic_min fit_ht[[i]]$delta_AICc <- delta_AICc[i] norm_aic_weight <- norm_aic_weight + exp(-0.5*fit_ht[[i]]$delta_AICc) } # Akaike weigths and dataframe with parameters # daf<-data.frame() for (i in 1:n_models){ AICc_weight[i] <- exp(-0.5*fit_ht[[i]]$delta_AICc)/norm_aic_weight fit_ht[[i]]$AICc_weight <- AICc_weight[i] if(i<5){ daf <- rbind(daf,data.frame(ModelNames=model_names[i], par1=fit_ht[[i]]$model$pars[1], par2=fit_ht[[i]]$model$pars[2], xmin=fit_ht[[1]]$model$getXmin(), n=fit_ht[[i]]$n, AICc=fit_ht[[i]]$AICc,Delta_AICc=delta_AICc[i],AICc_weight=AICc_weight[i])) } else if(i==5){ daf <- rbind(daf,data.frame(ModelNames=model_names[i], par1=-fit_ht[[i]]$model$exponent, par2=fit_ht[[i]]$model$rate, xmin=fit_ht[[1]]$model$getXmin(), n=fit_ht[[i]]$n, AICc=fit_ht[[i]]$AICc,Delta_AICc=delta_AICc[i],AICc_weight=AICc_weight[i])) }else if(i==6){ daf <- rbind(daf,data.frame(ModelNames=model_names[i], par1=fit_ht[[i]]$model, par2= NA, xmin=fit_ht[[1]]$model$getXmin(), n=fit_ht[[i]]$n, AICc=fit_ht[[i]]$AICc,Delta_AICc=delta_AICc[i],AICc_weight=AICc_weight[i])) } } # Plots # if (options.output$ploting){ #setwd(options.output$resultsDir) require(RColorBrewer) colp <-brewer.pal(8,"Dark2") fnam <-paste0(options.output$data_set_name, "_xmin",fit_ht[[1]]$model$xmin,".png") png(filename=fnam, res=300,units = "mm", height=200, width=200,bg="white") po <-plot(fit_ht[[1]]$model,xlab="Degree",ylab="log[P(X > x)]",main=options.output$data_set_name) for (i in 1:n_models){ if(i<5) { lines(fit_ht[[i]]$model, col=colp[i]) } else if(i==5) { est1 <- fit_ht[[i]]$model est1$xmin <- fit_ht[[1]]$model$xmin x <- sort(unique(data_set)) x <- x[x>=est1$xmin] shift <- max(po[po$x>=est1$xmin,]$y) y <- ppowerexp(x,est1$xmin,est1$exponent,est1$rate,lower.tail=F)*shift lines(x,y,col=colp[i]) } else if(i==6) { est1 <- fit_ht[[i]]$model xmin <- fit_ht[[1]]$model$xmin x <- sort(unique(data_set)) x <- x[x>=xmin] shift <- max(po[po$x>=xmin,]$y) y <- 1-((x - xmin+1)/(est1-xmin+1)*shift) lines(x,y,col=colp[i]) } } legend("topright",model_names,bty="n",col=colp,lty=c(1,1,1,1),cex=1) dev.off() } return(list(fitted_models=fit_ht,da_fit=daf)) } fit_ht_dplyr_helper <-function(df,xmin=1){ opt.output$data_set_name <- unique(df$Network) temp <-fit_dis_heavy_tail(df$Degree,xmin,opt.output) temp <-data.frame(temp$da_fit) temp$Network <- unique(df$Network) return(temp) } # Plot of frequencies of patch sizes with fitted continuous heavy tail functions # x: data # fit_ht_df : dataframe with fitted parameters # freq_plot_con_ht <- function(x,fit_ht,tit="") # PLOT ALL FROM X=1 ????????????????? { require(dplyr) require(ggplot2) xx <-as.data.frame(table(x)) xx$x <- as.numeric(as.character(xx$x)) ff <- filter(fit_ht,ModelNames=="PowerExp") if(nrow(ff)>0){ xmin <- ff$xmin xx$pexp <-dpowerexp(xx$x,1,ff$par1,ff$par2) } else { xx$pexp<-0 } ff <- filter(fit_ht,ModelNames=="Power") xmin <- ff$xmin xx$pow <-dpareto(xx$x,xmin,ff$par1) ff <- filter(fit_ht,ModelNames=="Exp") xx$exp <-dexp(xx$x,ff$par1) xx <-mutate(xx,pexp=ifelse(x<xmin,NA,pexp),pow=ifelse(x<xmin,NA,pow), exp=ifelse(x<xmin,NA,exp), Freq=Freq/sum(Freq)) minFreq <- min(xx$Freq) - 0.5*min(xx$Freq) minFreq <- ifelse(minFreq<0,0,minFreq) g <- ggplot(xx, aes(y=Freq,x=x)) + theme_bw() + geom_point(alpha=0.3) + coord_cartesian(ylim=c(1,min(minFreq)))+ scale_y_log10() +scale_x_log10() + ylab("Frequency") + xlab("Degree") +ggtitle(tit) mc <- c("#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7") g <- g + geom_line(aes(y=pow,x=x,colour="P.law")) + # geom_line(aes(y=pexp,x=x,colour="P.law with\nexp. cutoff"))+ geom_line(aes(y=exp,x=x,colour="Exp."))+ scale_colour_manual(values=mc,name="") fil <- gsub(" ", "", tit, fixed = TRUE) fil <- paste0(fil,".png") if(tit=="") print(g) else ggsave(fil,plot=g,width=6,height=4,units="in",dpi=600) } # Calculates The Corrected Akaike Criterion # k: number of parameters # n: number of points # mdl1,2: fitted nonlinear models # Akaike_criterion<-function(k,n,mdl1,mdl2,names) { Akaike <-data.frame(Model=names, AICc=0) Akaike$AICc[1] <- 2*k - 2* logLik(mdl1) + 2*k*(k+1)/(n-k-1) Akaike$AICc[2] <- 2*k - 2* logLik(mdl2) + 2*k*(k+1)/(n-k-1) Akaike$Delta <- Akaike$AICc - min(Akaike$AICc) return(Akaike) } # Function to plot CCDF of fitted continuous heavy tail functions using ggplo2 # # x: data # fit_ht : dataframe with fitted parameters # tit: file name to save graph # fit_ht1: second set of parameters to superimpose in the same graph cdfplot_displ_exp <- function(x,fit_ht,tit="",xmax=0) { require(poweRlaw) require(viridis) m <- displ$new(x) tP <- plot(m,draw=F) require(ggplot2) require(dplyr) ff <- filter(fit_ht,ModelNames=="Power") xmin <- ff$xmin tP1 <- cdfplot_conpl_exp_helper(x,tP,fit_ht,xmin) #tP2 <-filter(tP2, powl>= min(tP$Rank)) #tP1 <-filter(tP1, powl>= min(tP$Rank)) #mc <- c("#E69F00", "#56B4E9", "#009E73","#F0E442", "#0072B2","#D55E00", "#CC79A7") # Brewer #mc <- c("#d7191c","#fdae61","#abd9e9","#2c7bb6") g <- ggplot(tP, aes(x=x,y=y)) + theme_bw() + geom_point(alpha=0.3) + coord_cartesian(ylim=c(1,min(tP$y)))+ scale_y_log10() +scale_x_log10() + ylab("log[P(X > x)]") + xlab("Degree") #+ggtitle(tit) if(xmax>0) { g<-g + xlim(0,xmax+1) + scale_x_log10() } brk<-unique(tP1$model) g <- g + geom_line(data=tP1,aes(y=powl,x=psize,colour=model)) + #scale_colour_discrete(name="",breaks=brk) #scale_colour_manual(values=mc,name="",breaks=brk) #scale_colour_brewer(type="dark2",palette=7,name="",breaks=brk) scale_colour_viridis(discrete = TRUE) fil <- gsub(" ", "", tit, fixed = TRUE) fil <- paste0(fil,".png") if(tit=="") print(g) else ggsave(fil,plot=g,width=6,height=4,units="in",dpi=600) } cdfplot_conpl_exp_helper <- function(x,tP,fit_ht,xmin,mode="gt") { x1 <- unique(x) # Select model and generate a data frame # ff <- filter(fit_ht,ModelNames=="PowerExp") if(mode=="gt") { x1 <- x1[x1>=xmin] shift <- max(filter(tP,x>=xmin)$y) } else { x1 <- x1[x1<xmin] #xmin<-1 #shift <-1 # First select lower subset the change to the Xmin of this subset xmin <- ff$xmin shift <- max(filter(tP,x>=xmin)$y) } tP2 <- data_frame(psize=x1, powl=ppowerexp(x1,xmin,ff$par1,ff$par2,lower.tail=F)*shift,model="PowerExp") ff <- filter(fit_ht,ModelNames=="Power") m <- displ$new(x) m$setPars(ff$par1) m$setXmin(xmin) tP1 <- data_frame(psize=x1,powl=dist_cdf(m,x1,lower_tail=F)*shift,model="Power") ff <- filter(fit_ht,ModelNames=="Exp") m <- disexp$new(x) m$setPars(ff$par1) m$setXmin(xmin) tP3 <- data_frame(psize=x1,powl=dist_cdf(m,x1,lower_tail=F)*shift,model="Exp") ff <- filter(fit_ht,ModelNames=="LogNorm") m <- dislnorm$new(x) m$setPars(c(ff$par1,ff$par2)) m$setXmin(xmin) tP4 <- data_frame(psize=x1,powl=dist_cdf(m,x1,lower_tail=F)*shift,model="LogNorm") ff <- filter(fit_ht,ModelNames=="Poisson") m <- dispois$new(x) m$setPars(c(ff$par1,ff$par2)) m$setXmin(xmin) tP5 <- data_frame(psize=x1,powl=dist_cdf(m,x1,lower_tail=F)*shift,model="Poisson") tP1 <- bind_rows(tP1,tP2,tP3,tP4,tP5) } # Complementary cumulative distribution plot using base graphics and poweRlaw package # ccdf_base_plot_ht <- function(fit_ht,data_set,netName=""){ # Plots # require(RColorBrewer) colp <-brewer.pal(8,"Dark2") if(netName!="") { fnam <-paste0(netName, "_xmin",fit_ht[1]$xmin,".png") png(filename=fnam, res=300,units = "mm", height=200, width=200,bg="white") } po <-plot(fit_ht[1]$model,xlab="Degree",ylab="log[P(X > x)]",main=options.output$data_set_name) for (i in 1:n_models){ if(i!=n_models) { lines(fit_ht[[i]]$model, col=colp[i]) } else { est1 <- fit_ht[[i]]$model x <- sort(unique(data_set)) x <- x[x>=est1$xmin] shift <- max(po[po$x>=est1$xmin,]$y) y <- ppowerexp(x,est1$xmin,est1$exponent,est1$rate,lower.tail=F)*shift lines(x,y,col=colp[i]) } } legend("topright",model_names,bty="n",col=colp,lty=c(1,1,1,1),cex=1) if(netName!="") dev.off() }
The Möbius function is zero if the two arguments are equal.
(** * PSet 1: Functional Programming in Coq This assignment is designed as a file that you should download and complete in a Coq IDE. Before doing that, you need to install Coq. The installation instructions are on the course website. *) (* Exercise: mult2 [10 points]. Define a function that multiplies its input by 2. *) Let mult2 (x:nat) :nat := 2*x. (* What is the function's type? *) (* The type of the function is : "nat -> nat" *) Print mult2. (* Output: mult2 = fun x : nat => 2 * x : nat -> nat *) (* What is the result of computing the function on 0? On 3110? *) Eval compute in mult2 0. (* Output: "0:nat" *) Eval compute in mult2 3110. (*Output: "6220:nat" *) (* Exercise: xor [10 points]. Define a function that computes the xor of two [bool] inputs. Do this by pattern matching on the inputs. *) Let xor (a:bool) (b:bool) :bool := match a,b with | false,false => false | false,true => true | true,false => true | true,true => false end. (* What is the function's type? *) (* The type of the function is "bool->bool->bool" *) Print xor. (* Output: xor = fun a b : bool => if a then if b then false else true else if b then true else false : bool -> bool -> bool *) (* Compute all four possible combinations of inputs to test your function. *) Eval compute in xor false false. (* Output: "false:bool" *) Eval compute in xor false true. (* Output: "true:bool" *) Eval compute in xor true false. (* Output: "true:bool" *) Eval compute in xor true true. (* Output: "false:bool" *) (* Exercise: is_none [20 points]. Define a function that returns [true] if its input is [None], and [false] otherwise. Your function's type should be [forall A : Type, option A -> bool]. That means the function will actually need to take two inputs: the first has type [Type], and the second is an option. Hint: model your solution on [is_empty] in the notes for this lecture. *) Let is_none (A:Type) (b:option A) :bool := match b with | None => true | Some _=> false end. Print is_none. (* The type: "forall A : Type, option A -> bool" *) (* Verification of definition *) (* Eval compute in is_none nat None. *) (* Output: = true : bool *) (* Eval compute in is_none nat (Some 2). *) (* Output: = false : bool *) Require Import List. Import ListNotations. (* Exercise: double_all [20 points]. There is a function [map] that was imported by the [Require Import List] command above. First, check its type with [Check map]. Explain that type in your own words. Second, print it with [Print map]. Note at the end of that which arguments are _implicit_. For a discussion of what implicit means, see the notes for this lecture. Third, use map to write your own function, which should double (i.e., multiply by 2) every value of a list. For example, [double_all [0;2;10]] should be [[0;4;20]]. *) Check map. (* Output: map : forall A B : Type, (A -> B) -> list A -> list B *) (* Map function takes in a function f:A->B and list l1 of type A and returns another list l2 of type B and this is achieved for all types A and B. Thus, for all types A and B, map takes in a function f:A->B and a list of type A as inputs and outputs a list of type B. *) Print map. (* Output: map = fun (A B : Type) (f : A -> B) => fix map (l : list A) : list B := match l with | [] => [] | a :: t => f a :: map t end : forall A B : Type, (A -> B) -> list A -> list B *) (* Arguments A and B are implicit(they are enclosed within square braces). They can be inferred from the types of the arguments to the function. The first argument f is of type A->B and the second arugment l is of type A. *) Definition double_all (a:list nat) := ((map mult2) a). (*Verification of the Definition*) (* Eval compute in double_all [0;2;10]. *) (* Output: = [0; 4; 20] : list nat *) (* Exercise: sum [20 points] Write a function that sums all the natural numbers in a list. Implement this two different ways: - as a recursive function, using the [Fixpoint] syntax. - as a nonrecursive function, using [Definition] and an application of [fold_left]. *) (* This is the recursive function using [Fixpoint] syntax *) Fixpoint sum (lst: list nat) :nat := match lst with | [] => 0 | h::t => h+(sum t) end. (* This is the non-recursive definition using [fold_left]*) (* Kindly comment the previous definition of sum and uncomment the following definition if the following definition is to be used *) (* Definition sum (lst: list nat): nat := fold_left (fun x y => x+y) lst 0. *) (* Verification of the definition *) (* Eval compute in sum [1;5;7]. Eval compute in sum [20;40;12;89]. Eval compute in sum []. Eval compute in sum [0]. *) (* Outputs: = 13 : nat = 0 : nat = 0 : nat *) Inductive day : Type := | sun : day | mon : day | tue : day | wed : day | thu : day | fri : day | sat : day. Definition next_day d := match d with | sun => mon | mon => tue | tue => wed | wed => thu | thu => fri | fri => sat | sat => sun end. (* Exercise: thu after wed [20 points]. State a theorem that says [thu] is the [next_day] after [wed]. Write down in natural language how you would informally explain to a human why this theorem is true. ---> Don't skip this "natural language" part of the exercise; it's crucial to develop intuition before proceeding. Prove the theorem in Coq. *) Theorem thu_after_wed: next_day wed = thu. Proof. simpl. trivial. Qed. (* Natural language Explanation: We have next_day function which provides the case-wise value for each of the 7 days defined in [Inductive day]. For proving that [next_day] of [wed] is [thu]: 1.We will find [next_day] of [wed] by applying the function [next_day] to [wed]. // Simpl tactic helps us do this 2.We will check/verify that this is [thu] and thus [next_day] of [wed] is thu. // trivial tactic helps us do this. *) (* Exercise: wed before thu [30 points]. Below is a theorem that says if the day after [d] is [thu], then [d] must be [wed]. Write down in natural language how you would informally explain to a human why this theorem is true. ---> Don't skip this "natural language" part of the exercise; it's crucial to develop intuition before proceeding. Prove the theorem in Coq. To do that, delete the [Abort] command, which tells Coq to discard the theorem, then fill in your own proof. *) Theorem wed_proceeds_thu : forall d : day, next_day d = thu -> d = wed. (* Natural Language Explanation: To prove that if [next_day] [d] is [thu], then [d] must be wed: 1. We will compute the [next_day] [d] for all the days defined in [Inductive day] // introd d.destruct d helps us in verifying the theorem for each of the days by creating a subgoal for each day 2. We will verify that either [next_day] [d] is either not thu //tactic discriminate helps us with this. or [next_day] [d] is thu and [d] is wed. //tactic trivial helps us with this. // Note that the simplification of function application([next_day] [d]) is done by discriminate or trivial tactic. *) Proof. intros d. destruct d ; discriminate || trivial. Qed. (*. simpl. discriminate. simpl. discriminate. simpl. discriminate. simpl. trivial. simpl. discriminate. simpl. discriminate. simpl. discriminate. *) (* Exercise: tl_opt [20 points]. Define a function [tl_opt] such that [tl_opt lst] return [Some t] if [t] is the tail of [lst], or [None] if [lst] is empty. We have gotten you started by providing an obviously incorrect definition, below; you should replace the body of the function with a correct definition. *) Definition tl_opt {A : Type} (lst : list A) : option (list A) := match lst with | [] => None | h::t => Some t end. (* Verification of Definition: *) (* Eval compute in tl_opt [1;2;3]. *) (* Output: = Some [2; 3] : option (list nat) *) (* Eval compute in tl_opt []. *) (* Output: = None : option (list ?A) *) (* Here is a new tactic: [rewrite x]. If [H: x = e] is an assumption in the proof state, then [rewrite H] replaces [x] with [e] in the subgoal being proved. For example, here is a proof that incrementing 1 produces 2: *) Theorem inc1_is_2 : forall n, n=1 -> (fun x => x+1) n = 2. Proof. intros n n_is_1. rewrite n_is_1. trivial. Qed. (* Exercise: tl_opt correct [20 points]. Using [rewrite], prove the following theorems. For both, first explain in natural language why the theorem should hold, before moving on to prove it with Coq. *) Theorem nil_implies_tlopt_none : forall A : Type, forall lst : list A, lst = nil -> tl_opt lst = None. Proof. intros A lst lst_is_null. rewrite lst_is_null. simpl. trivial. Qed. (* Natural Language Explanation: Proving "forall A : Type, forall lst : list A, lst = nil -> tl_opt lst = None" is a straightforward problem: We will assume lst=nil(where lst is a list of type A where A is a type) // the intros helps us in achieving this. and will prove tl_opt lst = None To prove tl_opt lst = None, we will apply the function tl_opt to the list lst. From the definition of function, lst will match with empty list and returns None. // simpl tactics helps in this We will check/verify that the output is actually None by comparing it with expected output. // trivial tactic helps in this *) Theorem cons_implies_tlopt_some : forall {A : Type} (h:A) (t : list A) (lst : list A), lst = h::t -> tl_opt lst = Some t. Proof. intros A h t lst lst_is_ht. rewrite lst_is_ht. simpl. trivial. Qed. (* Natural Language Explanation: Proving "forall {A : Type} (h:A) (t : list A) (lst : list A), lst = h::t -> tl_opt lst = Some t." is a straightforward problem: We will assume lst=h:t(given that h is of type A and t is a list of type A and A is a type) // Intros helps us with this. and will prove tl_opt lst = Some t. We will apply the function tl_opt to the list lst. From the definition of function, lst will not match with empty list and will match with h::t and returns Some t . // simpl tactics helps in this We will check/verify that the output is actually None by comparing it with expected output. // trivial tactic helps in this *) (* Ignore the below statements: Let a := simpl mult2 0. Print a. Let b:= mult2 3110. Print b. Theorem a: mult2 0 = 0. Proof. auto. Qed. Print a. Theorem b: mult2 3110 = 6220. Proof. auto. Qed. Print b. *)
using DigitSetSudoku using Base.Test const spec = """ 400000805 030000000 000700000 020000060 000080400 000010000 000603070 500200000 104000000 """ puzzle = SudokuPuzzle(spec) @test (@sprintf "%s" puzzle) == """ 4 . . | . . . | 8 . 5 . 3 . | . . . | . . . . . . | 7 . . | . . . ------+-------+------ . 2 . | . . . | . 6 . . . . | . 8 . | 4 . . . . . | . 1 . | . . . ------+-------+------ . . . | 6 . 3 | . 7 . 5 . . | 2 . . | . . . 1 . 4 | . . . | . . . """ solution = solve(puzzle) @test (@sprintf "%s" solution) == """ 4 1 7 | 3 6 9 | 8 2 5 6 3 2 | 1 5 8 | 9 4 7 9 5 8 | 7 2 4 | 3 1 6 ------+-------+------ 8 2 5 | 4 3 7 | 1 6 9 7 9 1 | 5 8 6 | 4 3 2 3 4 6 | 9 1 2 | 7 5 8 ------+-------+------ 2 8 9 | 6 4 3 | 5 7 1 5 7 3 | 2 9 1 | 6 8 4 1 6 4 | 8 7 5 | 2 9 3 """
module InfIO data InfIO : Type where Do : IO a -> (a -> Inf InfIO) -> InfIO data Fuel = Dry | More (Lazy Fuel) (>>=) : IO a -> (a -> Inf InfIO) -> InfIO (>>=) = Do forever : Fuel forever = More forever tank : Nat -> Fuel tank Z = Dry tank (S k) = More $ tank k run : Fuel -> InfIO -> IO () run Dry (Do action cont) = putStrLn "Out of fuel." run (More x) (Do action cont) = action >>= \res => run x $ cont res loopPrint : String -> InfIO loopPrint m = Do (putStrLn m) (\_ => loopPrint m) lp : String -> InfIO lp m = do putStrLn m lp m
(* * Copyright Brian Huffman, PSU; Jeremy Dawson and Gerwin Klein, NICTA * * SPDX-License-Identifier: BSD-2-Clause *) section \<open>Comprehension syntax for bit expressions\<close> theory Bit_Comprehension imports "HOL-Library.Word" begin class bit_comprehension = ring_bit_operations + fixes set_bits :: \<open>(nat \<Rightarrow> bool) \<Rightarrow> 'a\<close> (binder \<open>BITS \<close> 10) assumes set_bits_bit_eq: \<open>set_bits (bit a) = a\<close> begin lemma set_bits_False_eq [simp]: \<open>(BITS _. False) = 0\<close> using set_bits_bit_eq [of 0] by (simp add: bot_fun_def) end instantiation word :: (len) bit_comprehension begin definition word_set_bits_def: \<open>(BITS n. P n) = (horner_sum of_bool 2 (map P [0..<LENGTH('a)]) :: 'a word)\<close> instance by standard (simp add: word_set_bits_def horner_sum_bit_eq_take_bit) end lemma bit_set_bits_word_iff [bit_simps]: \<open>bit (set_bits P :: 'a::len word) n \<longleftrightarrow> n < LENGTH('a) \<and> P n\<close> by (auto simp add: word_set_bits_def bit_horner_sum_bit_word_iff) lemma word_of_int_conv_set_bits: "word_of_int i = (BITS n. bit i n)" by (rule bit_eqI) (auto simp add: bit_simps) lemma set_bits_K_False: \<open>set_bits (\<lambda>_. False) = (0 :: 'a :: len word)\<close> by (fact set_bits_False_eq) lemma word_test_bit_set_bits: "bit (BITS n. f n :: 'a :: len word) n \<longleftrightarrow> n < LENGTH('a) \<and> f n" by (fact bit_set_bits_word_iff) context includes bit_operations_syntax fixes f :: \<open>nat \<Rightarrow> bool\<close> begin definition set_bits_aux :: \<open>nat \<Rightarrow> 'a word \<Rightarrow> 'a::len word\<close> where \<open>set_bits_aux n w = push_bit n w OR take_bit n (set_bits f)\<close> lemma bit_set_bit_aux [bit_simps]: \<open>bit (set_bits_aux n w) m \<longleftrightarrow> m < LENGTH('a) \<and> (if m < n then f m else bit w (m - n))\<close> for w :: \<open>'a::len word\<close> by (auto simp add: bit_simps set_bits_aux_def) corollary set_bits_conv_set_bits_aux: \<open>set_bits f = (set_bits_aux LENGTH('a) 0 :: 'a :: len word)\<close> by (rule bit_word_eqI) (simp add: bit_simps) lemma set_bits_aux_0 [simp]: \<open>set_bits_aux 0 w = w\<close> by (simp add: set_bits_aux_def) lemma set_bits_aux_Suc [simp]: \<open>set_bits_aux (Suc n) w = set_bits_aux n (push_bit 1 w OR (if f n then 1 else 0))\<close> by (rule bit_word_eqI) (auto simp add: bit_simps le_less_Suc_eq mult.commute [of _ 2]) lemma set_bits_aux_simps [code]: \<open>set_bits_aux 0 w = w\<close> \<open>set_bits_aux (Suc n) w = set_bits_aux n (push_bit 1 w OR (if f n then 1 else 0))\<close> by simp_all lemma set_bits_aux_rec: \<open>set_bits_aux n w = (if n = 0 then w else let n' = n - 1 in set_bits_aux n' (push_bit 1 w OR (if f n' then 1 else 0)))\<close> by (cases n) simp_all end end
With Joker's release on the horizon, I felt like it would be a great time to re-post my dream track list for Persona (assuming that Nintendo/Sakurai would be limited to anything between P3 to PQ2). At least throw in a SMT medley or some subway/underground district themes for Mementos. I'm hoping they changed his idle animation to be his stealth stance, but I doubt it. Not really related, but what do people want Joker’s alt colors to be? Different coloured gloves and that's it. Funny thing is that some of this stuff would easily fly under the radar for those who never played the games if it wasn't for people shouting "OMG THERE ARE SPOILERS!" That's really the case for all of the "spoilers" brought up in this discussion, even the potential Persona 5 spoilers the stage would contain if that leak was real. Angling the knife like he does in Smash just seems... awkward and impractical. My post was an earnest question, not a callout. I don't care what stage they go with because it won't be the casino. Not really related, but what do people want Joker’s alt colors to be? My two ideas were colors corresponding to the different Phantom Thieves, or palettes that reference other Persona protagonists. The possibility of the “Jane” datamine does throw a wrench in that though. It’ll be interesting to see! Generally assume it'll be the other Phantom Thieves, but I'd enjoy a couple related to previous Jokers in Persona, like P2's. If the Jane thing pans out, fingers crossed for a Maya color. Also really hope that the music he brings isn't just P5, but across all SMT. The series has so many good tunes that restricting it to one game, or even just modern 3-5 Persona would be a disservice. I'm surprised that no one has tried making a fake leak with all of the debug info seen on the Ken screenshot leak. Seems like an obvious way to try and make your fake look more valid. The teaser was billed as "Super Smash Bros. X Persona 5" much like "Super Smash Bros. X Final Fantasy VII" so I don't have high hopes for non-P5 content. Yeah, it's the most likely scenario even if it's the most disappointing one. However, I highly doubt Atlus is as protective of its music as Square is and the press release posted by Nintendo alongside Joker's reveal specifically called out the SMT series as a whole, so fingers crossed I guess. edit: Speaking of which, if Jack Frost is part of Joker's moveset I really hope there's a pallete that makes Jack look Virtual Boy inspired. Bayo is listed as Bayonetta 2 on the website, so there’s hope. I'm assuming it's to make him more different than he would be, or perhaps he uses the knife backhand in the anime. It could also be related to one of the new games, or "Jane". EDIT: I mean reverse grip. Yeah the stance is weird, especially when he never ever holds his knife backwards in P5. I'm not talking about website listings. Bayonetta didn't even get one in her trailer. Maybe his hand is upside down. I like how they didn't specify Street Fighter II but excluded everything else anyway. I'm hoping for school clothes and/or casual clothes. I played most of Persona 5 wearing those outfits instead of the phantom thief outfit. Joker looks cool in glasses! Will be a shame when I inevitably can't Smash as Santa. Maybe he'll get this as an alt colour. Just won't have the hat. Exclude Morgana and Futaba and that leaves enough boy thieves and girl thieves for Jack and Jane to reference. There's a 100% chance that Joker's trailer will feature a quick clip of him and Richter adjusting their gloves together, right? Sakurai has been spoiling plot twists with every smash game. Mecha Fiora is in Shulk’s FS. And Sheik in Melee. I don't think they really care. Based on color scheme and my P5 party, I want Yusuke and Haru alts. Makoto was my other, but less interesting color-wise. Remember when sakurai made a post brawl blog post explaining the plot of subspace. Nintendo being all innovative again. Having story based DLC before they even had DLC!!! Then it wouldn't be nearly as funny. Do people still complain about online? I can’t even remember the last time I got in a match that wasn’t my preferred rules, or at least either battlefield or FD. At this point, I see the 3.0 update just dropping with little fanfare. One where you'll just have to try out the new stuff yourself instead of having it all shown to you. They really blew it by having absolutely nothing meaningful to say about the 3.0 update or Joker since the last big update. I got a Little Mac on Pac-Land with items in Elite Smash. I get my fair share of item matches and non-BF/FD still. You guys buckle way too easily. They teased more info in the February Direct and said “before the end of April.” There’s also the Persona concert that we might have to wait to see Jane first revealed. Nintendo knows people go nuts for Smash info, they aren’t gonna undersell it. Sakurai spent 20 minutes talking about menus and languages but isn’t going to talk about Persona content or Stage Builder? I was there then pointed in this direction so guess I'm here now. But it wouldn't fix the fact that it's laggy nonsense most of the time. I guess I’m just lucky. I never get matches with bad rule sets. That leak’s interesting. Hope that it’s right about franchise elements being included in stage builder. Each major franchise as its own palette a la Mario Maker? They really do need to have a way to share stages online though, it would be a weird downgrade from Wii U. And I’m also hoping for a Mii costume set that includes some of my favorites from Smash 4 like Geno and Protoman. He’ll have at least one color based on Crow if nothing else. I’m confidant of that. I would love full alts just because there are some great choices. Other than getting a Smash ball battle today I’ve gotten my preferences nearly every time. Is that Ren as Kiryu? The dancing game had a few crossover costumes.
lemma poly_smult [simp]: "poly (smult a p) x = a * poly p x"
[STATEMENT] lemma of_nat_mask_eq: \<open>of_nat (mask n) = mask n\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. of_nat (mask n) = mask n [PROOF STEP] by (induction n) (simp_all add: mask_Suc_double Bit_Operations.mask_Suc_double of_nat_or_eq)
[STATEMENT] lemma bounded_linear_axis: "bounded_linear (axis i)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. bounded_linear (axis i) [PROOF STEP] proof [PROOF STATE] proof (state) goal (3 subgoals): 1. \<And>b1 b2. axis i (b1 + b2) = axis i b1 + axis i b2 2. \<And>r b. axis i (r *\<^sub>R b) = r *\<^sub>R axis i b 3. \<exists>K. \<forall>x. norm (axis i x) \<le> norm x * K [PROOF STEP] show "axis i (x + y) = axis i x + axis i y" "axis i (r *\<^sub>R x) = r *\<^sub>R axis i x" for x y :: "'a" and r [PROOF STATE] proof (prove) goal (1 subgoal): 1. axis i (x + y) = axis i x + axis i y &&& axis i (r *\<^sub>R x) = r *\<^sub>R axis i x [PROOF STEP] by (auto simp: vec_eq_iff axis_def) [PROOF STATE] proof (state) this: axis i (?x + ?y) = axis i ?x + axis i ?y axis i (?r *\<^sub>R ?x) = ?r *\<^sub>R axis i ?x goal (1 subgoal): 1. \<exists>K. \<forall>x. norm (axis i x) \<le> norm x * K [PROOF STEP] show "\<exists>K. \<forall>x::'a. norm (axis i x) \<le> norm x * K" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>K. \<forall>x. norm (axis i x) \<le> norm x * K [PROOF STEP] by (auto simp add: norm_axis intro!: exI[of _ 1]) [PROOF STATE] proof (state) this: \<exists>K. \<forall>x. norm (axis i x) \<le> norm x * K goal: No subgoals! [PROOF STEP] qed
section {* Entry Point for the Automatic Refinement Tool *} theory Automatic_Refinement imports "Tool/Autoref_Tool" "Autoref_Bindings_HOL" begin text {* The automatic refinement tool should be used by importing this theory *} subsection {* Convenience *} text {* The following lemmas can be used to add tags to theorems *} lemma PREFER_I: "P x \<Longrightarrow> PREFER P x" by simp lemma PREFER_D: "PREFER P x \<Longrightarrow> P x" by simp lemmas PREFER_sv_D = PREFER_D[of single_valued] lemma PREFER_id_D: "PREFER_id R \<Longrightarrow> R=Id" by simp abbreviation "PREFER_RUNIV \<equiv> PREFER (\<lambda>R. Range R = UNIV)" lemmas PREFER_RUNIV_D = PREFER_D[of "(\<lambda>R. Range R = UNIV)"] lemma SIDE_GEN_ALGO_D: "SIDE_GEN_ALGO P \<Longrightarrow> P" by simp lemma GEN_OP_D: "GEN_OP c a R \<Longrightarrow> (c,a)\<in>R" by simp lemma MINOR_PRIO_TAG_I: "P \<Longrightarrow> (MINOR_PRIO_TAG p \<Longrightarrow> P)" by auto lemma MAJOR_PRIO_TAG_I: "P \<Longrightarrow> (MAJOR_PRIO_TAG p \<Longrightarrow> P)" by auto lemma PRIO_TAG_I: "P \<Longrightarrow> (PRIO_TAG ma mi \<Longrightarrow> P)" by auto end
lemma ksimplex_replace_2: assumes s: "ksimplex p n s" and "a \<in> s" and "n \<noteq> 0" and lb: "\<forall>j<n. \<exists>x\<in>s - {a}. x j \<noteq> 0" and ub: "\<forall>j<n. \<exists>x\<in>s - {a}. x j \<noteq> p" shows "card {s'. ksimplex p n s' \<and> (\<exists>b\<in>s'. s' - {b} = s - {a})} = 2"
PitchTraking()
Formal statement is: lemma LIMSEQ_power_zero [tendsto_intros]: "norm x < 1 \<Longrightarrow> (\<lambda>n. x ^ n) \<longlonglongrightarrow> 0" for x :: "'a::real_normed_algebra_1" Informal statement is: If $|x| < 1$, then the sequence $x^n$ converges to $0$.
classdef PTKFissurenessHessianFactor < PTKPlugin % PTKFissureApproximation. Plugin to detect fissures using analysis of the % Hessian matrix % % This is a plugin for the Pulmonary Toolkit. Plugins can be run using % the gui, or through the interfaces provided by the Pulmonary Toolkit. % See PTKPlugin.m for more information on how to run plugins. % % Plugins should not be run directly from your code. % % This is an intermediate stage towards lobar segmentation. % % PTKFissurenessHessianFactor computes the components of the fissureness % generated using analysis of eigenvalues of the Hessian matrix. % % For more information, see % [Doel et al., Pulmonary lobe segmentation from CT images using % fissureness, airways, vessels and multilevel B-splines, 2012] % % Licence % ------- % Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit % Author: Tom Doel, 2012. www.tomdoel.com % Distributed under the GNU GPL v3 licence. Please see website for details. % properties ButtonText = 'Fissureness <BR>(Hessian part)' ToolTip = 'The part of the fissureness filter which uses Hessian-based analysis' Category = 'Fissures' AllowResultsToBeCached = false AlwaysRunPlugin = false PluginType = 'ReplaceOverlay' HidePluginInDisplay = false FlattenPreviewImage = false PTKVersion = '1' ButtonWidth = 6 ButtonHeight = 2 GeneratePreview = true Visibility = 'Developer' Version = 2 MemoryCachePolicy = 'Temporary' DiskCachePolicy = 'Off' end methods (Static) function results = RunPlugin(dataset, reporting) reporting.UpdateProgressValue(0); left_and_right_lungs = dataset.GetResult('PTKLeftAndRightLungs'); right_lung = dataset.GetResult('PTKGetRightLungROI'); fissureness_right = PTKFissurenessHessianFactor.ComputeFissureness(right_lung, left_and_right_lungs, reporting, false); reporting.UpdateProgressValue(50); left_lung = dataset.GetResult('PTKGetLeftLungROI'); fissureness_left = PTKFissurenessHessianFactor.ComputeFissureness(left_lung, left_and_right_lungs, reporting, true); reporting.UpdateProgressValue(100); results = PTKCombineLeftAndRightImages(dataset.GetTemplateImage(PTKContext.LungROI), fissureness_left, fissureness_right, left_and_right_lungs); results.ImageType = PTKImageType.Scaled; end end methods (Static, Access = private) function lung = DuplicateImageInMask(lung, mask_raw) mask_raw = mask_raw > 0; if any(mask_raw(:) > 0) [~, labelmatrix] = bwdist(mask_raw); lung(~mask_raw(:)) = lung(labelmatrix(~mask_raw(:))); else lung(:) = 0; end end function fissureness = ComputeFissureness(image_data, left_and_right_lungs, reporting, is_left_lung) left_and_right_lungs = left_and_right_lungs.Copy; left_and_right_lungs.ResizeToMatch(image_data); image_data.ChangeRawImage(PTKFissurenessHessianFactor.DuplicateImageInMask(image_data.RawImage, left_and_right_lungs.RawImage)); mask = []; fissureness = PTKImageDividerHessian(image_data, @PTKFissurenessHessianFactor.ComputeFissurenessPartImage, mask, 1.5, [], false, false, is_left_lung, reporting); end function fissureness_wrapper = ComputeFissurenessPartImage(hessian_eigs_wrapper, voxel_size) fissureness_wrapper = PTKComputeFissurenessFromHessianeigenvalues(hessian_eigs_wrapper, voxel_size); end end end
Formal statement is: lemma complex_Re_fact [simp]: "Re (fact n) = fact n" Informal statement is: The real part of the factorial of a natural number is the factorial of that natural number.
[STATEMENT] lemma deriv_deriv_real_sqrt [simp]: assumes "x > 0" shows "deriv(deriv sqrt) x = - inverse ((sqrt x)^3)/4" [PROOF STATE] proof (prove) goal (1 subgoal): 1. deriv (deriv sqrt) x = - inverse (sqrt x ^ 3) / 4 [PROOF STEP] using DERIV_imp_deriv assms has_real_derivative_deriv_sqrt [PROOF STATE] proof (prove) using this: (?f has_field_derivative ?f') (at ?x) \<Longrightarrow> deriv ?f ?x = ?f' 0 < x 0 < ?x \<Longrightarrow> (deriv sqrt has_real_derivative - inverse (sqrt ?x ^ 3) / 4) (at ?x) goal (1 subgoal): 1. deriv (deriv sqrt) x = - inverse (sqrt x ^ 3) / 4 [PROOF STEP] by blast
[STATEMENT] lemma [simp]: "from_hma\<^sub>m (y :: 'a ^ 'nc ^ 'nr) \<in> carrier_mat (CARD('nr)) (CARD('nc))" "dim_row (from_hma\<^sub>m (y :: 'a ^ 'nc ^ 'nr )) = CARD('nr)" "dim_col (from_hma\<^sub>m (y :: 'a ^ 'nc ^ 'nr )) = CARD('nc)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. from_hma\<^sub>m y \<in> carrier_mat CARD('nr) CARD('nc) &&& dim_row (from_hma\<^sub>m y) = CARD('nr) &&& dim_col (from_hma\<^sub>m y) = CARD('nc) [PROOF STEP] unfolding from_hma\<^sub>m_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. Matrix.mat CARD('nr) CARD('nc) (\<lambda>(i, j). y $h Bij_Nat.from_nat i $h Bij_Nat.from_nat j) \<in> carrier_mat CARD('nr) CARD('nc) &&& dim_row (Matrix.mat CARD('nr) CARD('nc) (\<lambda>(i, j). y $h Bij_Nat.from_nat i $h Bij_Nat.from_nat j)) = CARD('nr) &&& dim_col (Matrix.mat CARD('nr) CARD('nc) (\<lambda>(i, j). y $h Bij_Nat.from_nat i $h Bij_Nat.from_nat j)) = CARD('nc) [PROOF STEP] by simp_all
\appendix{Some Material} Some text. \section{Some Topic} More text.
{-# OPTIONS --without-K #-} open import HoTT module homotopy.TorusIsProductCircles where surfT' : loopT1 ∙ loopT2 == loopT2 ∙' loopT1 surfT' = surfT ∙ (∙=∙' loopT2 loopT1) private to-surfT : (pair×= loop idp) ∙ (pair×= idp loop) == (pair×= idp loop) ∙ (pair×= loop idp) to-surfT = pair×= loop idp ∙ pair×= idp loop =⟨ ×-∙ loop idp idp loop ⟩ pair×= (loop ∙ idp) (idp ∙ loop) =⟨ ∙-unit-r loop |in-ctx (λ u → pair×= u loop) ⟩ pair×= loop loop =⟨ ! (∙-unit-r loop) |in-ctx (λ u → pair×= loop u) ⟩ pair×= (idp ∙ loop) (loop ∙ idp) =⟨ ! (×-∙ idp loop loop idp) ⟩ pair×= idp loop ∙ pair×= loop idp ∎ module To = TorusRec (base , base) (pair×= loop idp) (pair×= idp loop) to-surfT {- First map -} to : Torus → S¹ × S¹ to = To.f {- Second map -} from-c : S¹ → (S¹ → Torus) from-c = FromC.f module M2 where module FromCBase = S¹Rec baseT loopT2 from-c-base : S¹ → Torus from-c-base = FromCBase.f from-c-loop-loop' : loopT1 ∙ ap from-c-base loop =-= ap from-c-base loop ∙' loopT1 from-c-loop-loop' = loopT1 ∙ ap from-c-base loop =⟪ FromCBase.loop-β |in-ctx (λ u → loopT1 ∙ u) ⟫ loopT1 ∙ loopT2 =⟪ surfT' ⟫ loopT2 ∙' loopT1 =⟪ ! FromCBase.loop-β |in-ctx (λ u → u ∙' loopT1) ⟫ ap from-c-base loop ∙' loopT1 ∎∎ from-c-loop-loop : loopT1 == loopT1 [ (λ x → from-c-base x == from-c-base x) ↓ loop ] from-c-loop-loop = ↓-='-in (↯ from-c-loop-loop') module FromCLoop = S¹Elim loopT1 from-c-loop-loop from-c-loop' = FromCLoop.f from-c-loop = λ= from-c-loop' module FromC = S¹Rec from-c-base from-c-loop from : S¹ × S¹ → Torus from (x , y) = from-c x y open M2 {- First composition -} thing : (y : S¹) → ap (λ x → from-c x y) loop == from-c-loop' y thing y = ap ((λ u → u y) ∘ from-c) loop =⟨ ap-∘ (λ u → u y) from-c loop ⟩ app= (ap from-c loop) y =⟨ FromC.loop-β |in-ctx (λ u → app= u y)⟩ app= (λ= from-c-loop') y =⟨ app=-β from-c-loop' y ⟩ from-c-loop' y ∎ to-from-c : (x y : S¹) → to (from-c x y) == (x , y) to-from-c = {!!} --S¹-elim to-from-c-base (↓-cst→app-in to-from-c-loop) where to-from-c-base-loop' : ap (to ∘ from-c-base) loop =-= ap (λ y → (base , y)) loop to-from-c-base-loop' = ap (to ∘ from-c-base) loop =⟪ ap-∘ to from-c-base loop ⟫ ap to (ap from-c-base loop) =⟪ FromCBase.loop-β |in-ctx ap to ⟫ ap to loopT2 =⟪ To.loopT2-β ⟫ pair×= idp loop =⟪ ! (ap-cst,id _ loop) ⟫ ap (λ y → (base , y)) loop ∎∎ to-from-c-base-loop : idp == idp [ (λ z → to (from-c-base z) == (base , z)) ↓ loop ] to-from-c-base-loop = ↓-='-in (! (↯ to-from-c-base-loop')) module ToFromCBase = S¹Elim idp to-from-c-base-loop -- 1!to-from-c-base-loop : idp == idp [ (λ z → to (from-c-base (fst z)) == z) ↓ (pair×= loop idp) ] -- 1!to-from-c-base-loop = ↓-='-in (! (↯ 1! to-from-c-base-loop')) -- module 1!ToFromCBase!1 = S¹Elim idp 1!to-from-c-base-loop to-from-c-base : (y : S¹) → to (from-c-base y) == (base , y) to-from-c-base = ToFromCBase.f thing2 : (y : S¹) → ap to (from-c-loop' y) == to-from-c-base y ∙ pair×= loop idp ∙' (! (to-from-c-base y)) thing2 = {!S¹-elim To.loopT1-β {!To.loopT1-β!}!} to-from-c-loop : (y : S¹) → to-from-c-base y == to-from-c-base y [ (λ x → to (from-c x y) == (x , y)) ↓ loop ] to-from-c-loop = {!S¹-elim to-from-c-loop-base ?!} where to-from-c-loop-base2 : ap (λ x → (x , base)) loop =-= ap (λ x → to (from-c x base)) loop to-from-c-loop-base2 = ap (λ z → z , base) loop =⟪ {!ap-id,cst _ loop!} ⟫ pair×= loop idp =⟪ ! To.loopT1-β ⟫ ap to loopT1 =⟪ ! (thing base) |in-ctx ap to ⟫ ap to (ap (λ z → from-c z base) loop) =⟪ ! (ap-∘ to (λ z → from-c z base) loop) ⟫ ap (λ z → to (from-c z base)) loop ∎∎ to-from-c-loop-base : idp == idp [ (λ x → to (from-c x base) == (x , base)) ↓ loop ] to-from-c-loop-base = ↓-='-in (↯ to-from-c-loop-base2) lemma : ↯ to-from-c-loop-base2 == ↯ to-from-c-loop-base2 [ (λ y → to-from-c-base y ∙ ap (λ x → x , y) loop == ap (λ x → to (from-c x y)) loop ∙' to-from-c-base y) ↓ loop ] lemma = ↓-=-in ( (↯ to-from-c-loop-base2) ◃ apd (λ y → ap (λ x → to (from-c x y)) loop ∙' to-from-c-base y) loop =⟨ {!!} ⟩ (↯ to-from-c-loop-base2) ◃ ((apd (λ y → ap (λ x → to (from-c x y)) loop) loop) ∙'2 (apd to-from-c-base loop)) =⟨ {!!} ⟩ ((↯ to-from-c-loop-base2) ◃ (apd (λ y → ap (λ x → to (from-c x y)) loop) loop)) ∙'2 (apd to-from-c-base loop) =⟨ {!!} ⟩ ((↯ (to-from-c-loop-base2 !1)) ◃ ((apd (λ y → ap to (ap (λ x → from-c x y) loop)) loop) ▹ (↯ to-from-c-loop-base2 #1))) ∙'2 (apd to-from-c-base loop) =⟨ {!!} ⟩ ((↯ (to-from-c-loop-base2 !2)) ◃ ((apd (λ y → ap to (from-c-loop' y)) loop) ▹ (↯ to-from-c-loop-base2 #2))) ∙'2 (apd to-from-c-base loop) =⟨ {!!} ⟩ ((↯ (to-from-c-loop-base2 !2)) ◃ ((ap↓ (ap to) (apd from-c-loop' loop)) ▹ (↯ to-from-c-loop-base2 #2))) ∙'2 (apd to-from-c-base loop) =⟨ {!!} ⟩ ((↯ (to-from-c-loop-base2 !2)) ◃ ((ap↓ (ap to) from-c-loop-loop) ▹ (↯ to-from-c-loop-base2 #2))) ∙'2 (apd to-from-c-base loop) =⟨ {!!} ⟩ apd (λ y → to-from-c-base y ∙ ap (λ x → x , y) loop) loop ▹ (↯ to-from-c-loop-base2) ∎) {- Have: PathOver (λ z → to (from-c-base z) == to (from-c-base z)) loop (ap (λ x → x , base) loop) (ap (λ x → to (from-c x base)) loop) -} -- lemma2 : apd (λ y → ap (λ x → to (from-c x y)) loop) loop == {!!} -- lemma2 = -- apd (λ y → ap (λ x → to (from-c x y)) loop) loop =⟨ {!!} ⟩ -- apd (λ y → ap to (ap (λ x → from-c x y) loop)) loop =⟨ {!!} ⟩ -- apd (λ y → ap to (from-c-loop' y)) loop =⟨ {!!} ⟩ -- api2 (ap to) (apd from-c-loop' loop) =⟨ {!!} ⟩ -- apd (ap to) surfT =⟨ {!!} ⟩ -- ? ∎ to-from : (x : S¹ × S¹) → to (from x) == x to-from (x , y) = to-from-c x y {- Second composition -} from-to : (x : Torus) → from (to x) == x from-to = {!Torus-elim idp from-to-loopT1 from-to-loopT2 {!!}!} where from-to-loopT1 : idp == idp [ (λ z → from (to z) == z) ↓ loopT1 ] from-to-loopT1 = ↓-∘=idf-in from to (ap from (ap to loopT1) =⟨ To.loopT1-β |in-ctx ap from ⟩ ap from (pair×= loop idp) =⟨ lemma from loop (idp {a = base}) ⟩ ap (λ u → u base) (ap from-c loop) =⟨ FromC.loop-β |in-ctx ap (λ u → u base) ⟩ ap (λ u → u base) (λ= from-c-loop') =⟨ app=-β from-c-loop' base ⟩ loopT1 ∎) where lemma : ∀ {i j k} {A : Type i} {B : Type j} {C : Type k} (f : A × B → C) {x y : A} (p : x == y) {z t : B} (q : z == t) → ap f (pair×= p q) == app= (ap (curry f) p) z ∙' ap (curry f y) q lemma f idp idp = idp from-to-loopT2 : idp == idp [ (λ z → from (to z) == z) ↓ loopT2 ] from-to-loopT2 = ↓-∘=idf-in from to (ap from (ap to loopT2) =⟨ To.loopT2-β |in-ctx ap from ⟩ ap from (pair×= idp loop) =⟨ lemma' from (idp {a = base}) loop ⟩ ap from-c-base loop =⟨ FromCBase.loop-β ⟩ loopT2 ∎) where lemma' : ∀ {i j k} {A : Type i} {B : Type j} {C : Type k} (f : A × B → C) {x y : A} (p : x == y) {z t : B} (q : z == t) → ap f (pair×= p q) == ap (curry f x) q ∙' app= (ap (curry f) p) t lemma' f idp idp = idp -- to-from-c-app-base : (y : S¹) → to (from-c y base) == (y , base) -- to-from-c-app-base = S¹-elim {!to (from-c base base) == base , base!} {!!}
from __future__ import absolute_import from __future__ import division from __future__ import print_function import io import os import tempfile import numpy as np from scipy.misc import imread import tensorflow as tf def load_xy_pair(fake_directory, real_directory, prob_of_real = 0.5): ''' Loads a pair of tensors that are the x (input) and y (label) to the discriminator network. Randomly picks a "fake" or "real" image. Note that setting prob_of_real = 0.0 guarantees a fake image, while setting prob_of_real = 1.0 guarantees a real image. Input: fake_directory: A string filepath to the directory containig "fake" images real_directory: A string filepath to the directory containig "real" images prob_of_real: Float in [0, 1]. Probability of selecting a "real" image. Output: img: A tensor of shape [1, ?, ?, 3] y: A tensor of shape [1, 2]. It is either [1, 0] (real) or [0, 1] (fake). ''' coin_flip = np.random.binomial(1, prob_of_real) fake_img_names = os.listdir(fake_directory) real_img_names = os.listdir(real_directory) name = '' if coin_flip == 1: # pick real index = np.random.randint(low=0, high=len(real_img_names)) name = real_img_names[index] img_path = real_directory + name y = tf.constant([[1.0, 0.0]]) else: # pick fake index = np.random.randint(low=0, high=len(fake_img_names)) name = fake_img_names[index] img_path = fake_directory + name y = tf.constant([[0.0, 1.0]]) img = load_image(img_path, image_size=256) return img, y, name def load_xy_pairs(fake_directory, real_directory, batch_size = 4, prob_of_real = 0.5): ''' Loads a batch of tensor pairs (x, y) that are the x (input) and y (label) to the discriminator network. Randomly picks a "fake" or "real" image each time. See "load_xy_pair" Input: fake_directory: A string filepath to the directory containig "fake" images real_directory: A string filepath to the directory containig "real" images batch_size: A positive integer. Number of tensor pairs to load up. prob_of_real: Float in [0, 1]. Probability of selecting a "real" image. Output: images: A tensor of shape [batch_size, ?, ?, 3] labels: A tensor of shape [batch_size, 2]. ''' fake_img_names = os.listdir(fake_directory) real_img_names = os.listdir(real_directory) images, labels, first_img_path = load_xy_pair(fake_directory, real_directory, prob_of_real) img_paths = [first_img_path] for i in range(batch_size - 1): new_img, new_label, img_path = load_xy_pair(fake_directory, real_directory, prob_of_real) images = tf.concat([images, new_img], axis = 0) labels = tf.concat([labels, new_label], axis = 0) img_paths.append(img_path) return images, labels, img_paths def load_random_images(filepath, batch_size = 4): img_names = os.listdir(filepath) # Create a set of random indices from [0, ..., len(img_names) - 1] indices = np.random.choice(np.arange(len(img_names)), batch_size, replace=False) # Load a single random image. images = load_image(filepath + img_names[indices[0]], image_size=256) # Load the rest of the images, concatenating onto the images tensor. for i in range(1, len(indices)): index = indices[i] next_img = load_image(filepath + img_names[index], image_size=256) images = tf.concat([images, next_img], axis=0) return images def gen_labels(is_real = True, batch_size = 4): if is_real: return tf.constant(np.repeat(np.array([[1.0, 0.0]]), batch_size, axis=0)) else: return tf.constant(np.repeat(np.array([[0.0, 1.0]]), batch_size, axis=0)) def load_np_image_uint8(image_file): """Loads an image as a numpy array. Source: Google Magenta (magenta/models/imgage_stylization/image_utils.py) Args: image_file: str. Image file. Returns: A 3-D numpy array of shape [image_size, image_size, 3] and dtype uint8, with values in [0, 255]. """ with tempfile.NamedTemporaryFile() as f: f.write(tf.gfile.GFile(image_file, 'rb').read()) f.flush() image = imread(f.name) # Workaround for black-and-white images if image.ndim == 2: image = np.tile(image[:, :, None], (1, 1, 3)) return image def load_np_image(image_file): """Loads an image as a numpy array. Source: Google Magenta (magenta/models/imgage_stylization/image_utils.py) Args: image_file: str. Image file. Returns: A 3-D numpy array of shape [image_size, image_size, 3] and dtype float32, with values in [0, 1]. """ return np.float32(load_np_image_uint8(image_file) / 255.0) def load_image(image_file, image_size=None): """Loads an image and center-crops it to a specific size. Source: Google Magenta (magenta/models/imgage_stylization/image_utils.py) Args: image_file: str. Image file. image_size: int, optional. Desired size. If provided, crops the image to a square and resizes it to the requested size. Defaults to None. Returns: A 4-D tensor of shape [1, image_size, image_size, 3] and dtype float32, with values in [0, 1]. """ image = tf.constant(np.uint8(load_np_image(image_file) * 255.0)) if image_size is not None: # Center-crop into a square and resize to image_size small_side = min(image.get_shape()[0].value, image.get_shape()[1].value) image = tf.image.resize_image_with_crop_or_pad(image, small_side, small_side) image = tf.image.resize_images(image, [image_size, image_size]) image = tf.to_float(image) / 255.0 return tf.expand_dims(image, 0)
Class A Burn Prop - Stove Simulator With Overhead Burn Hood - Fire Facilities, Inc. The stove simulator assembly consists of 1/4” thick prime painted angles and 12 gage stainless steel panels bolted together with 3/8” diameter bolts through pre-punched holes for ease of assembly. The prime painted 19W4 x 1 1/2” x 3/16” bar grate is designed to hold class “A” materials 1’-4” above the floor surface. Dimensions for this prop shall be approximately 4’-5 1/2” x 4’-5 1/2” x 6’-7” tall and shall resemble a commercial grade stove. The overhead bar grate hood of this unit is 2’-11” x 4’-5 1/2” and provides another area to hold class “A” materials for a secondary fire. A sliding/removable stainless steel range top with large ventilation holes shall also be provided. The range top helps to limit the number of pallets trainees can place in the unit by covering approximately half of the unit.
function updatelarvaspecies(hfly,hfly_extra,pos) set(hfly,'XData',pos.xspine([1,6,11]),'YData',pos.yspine([1,6,11])); %set(hfly,'XData',[pos.xcontour;nan;pos.xspine],'YData',[pos.ycontour;nan;pos.yspine]); % xhead = pos.x + 2*pos.a*cos(pos.theta); % yhead = pos.y + 2*pos.a*sin(pos.theta); xhead = pos.xspine(1); yhead = pos.yspine(1); set(hfly_extra,'XData',xhead,'YData',yhead);
Formal statement is: lemma smult_content_normalize_primitive_part [simp]: fixes p :: "'a :: {normalization_semidom_multiplicative, semiring_gcd, idom_divide} poly" shows "smult (content p) (normalize (primitive_part p)) = normalize p" Informal statement is: The product of the content of a polynomial and the normalized primitive part of the polynomial is the normalized polynomial.
theory R01Sol imports Main begin text {* Relación 1 *} text {* ---------------------------------------------------------------------- Ejercicio 1. [Cálculo con números naturales] Calcular el valor de las siguientes expresiones con números naturales: + 2 + 2 + 2 * (3 + 1) + 3 * 4 - 2 * (7 + 1) ------------------------------------------------------------------- *} value "2 + (2::nat)" text {* El resultado es "Suc (Suc (Suc (Suc 0)))" *} value "(2::nat) * (3 + 1)" text {* El resultado es "Suc (Suc (Suc (Suc (Suc (Suc (Suc (Suc 0)))))))" *} value "(3::nat) * 4 - 2 * (7 + 1)" text {* El resultado es "0" *} text {* ---------------------------------------------------------------------- Ejercicio 2 [Propiedades de los números naturales] Ejercicio 2.1. Demostrar que la suma de los naturales es conmutativa. ------------------------------------------------------------------- *} lemma "x + y = y + (x::nat)" apply auto done text {* ---------------------------------------------------------------------- Ejercicio 2.2. Demostrar que la suma de los naturales es asociatativa. ------------------------------------------------------------------- *} lemma "x + (y + z) = (x + y) + (z::nat)" apply auto done text {* ---------------------------------------------------------------------- Ejercicio 3. [Ocurrencias de un elemento en una lista] Ejercicio 3.1. Definir la función cuenta :: "'a list \<Rightarrow> 'a \<Rightarrow> nat" tal que (cuenta xs y) es el número de ocurrencia de y en xs. Por ejemplo, cuenta [3, 2] 4 = 0 cuenta [3, 2] 3 = Suc 0 cuenta [3, 3] 3 = Suc (Suc 0) cuenta [] 3 = 0 *} fun cuenta :: "'a list \<Rightarrow> 'a \<Rightarrow> nat" where "cuenta [] _ = 0" | "cuenta (x # xs) y = (if x = y then Suc (cuenta xs y) else cuenta xs y)" value "cuenta [3, 2] (4::nat)" value "cuenta [3, 2] (3::nat)" value "cuenta [3, 3] (3::nat)" value "cuenta [] (3::nat)" text{* ---------------------------------------------------------------------- Ejercicio 3.2. Demostrar que el número de ocurrencia de cualquier elemento en una lista es menor o igual que la longitud de la lista. ------------------------------------------------------------------- *} theorem "cuenta xs x \<le> length xs" apply (induct xs) apply auto done text {* ---------------------------------------------------------------------- Ejercicio 4. [Añadiendo los elementos al final de la lista e inversa] Ejercicio 4.1. Definir, por recursión, la función snoc :: "'a list \<Rightarrow> 'a \<Rightarrow> 'a list" tal que (snoc xs y) es la lista obtenida añadiendo y al final de xs. Por ejemplo, snoc [3,5,2] 7 = [3,5,2,7] *} fun snoc :: "'a list \<Rightarrow> 'a \<Rightarrow> 'a list" where "snoc [] x = [x]" | "snoc (y # ys) x = y # (snoc ys x)" value "snoc [3,5,2] (7::int)" lemma "snoc [3,5,2] (7::int) = [3,5,2,7]" by simp text {* ---------------------------------------------------------------------- Ejercicio 4.2. Definir, por recursión, la función inversa :: "'a list \<Rightarrow> 'a list" tal que (inversa xs) es la lista obtenida invirtiendo el orden de los elementos de xs. Por ejemplo, inversa [a, b, c] = [c, b, a] ------------------------------------------------------------------- *} fun inversa :: "'a list \<Rightarrow> 'a list" where "inversa [] = []" | "inversa (x # xs) = snoc (inversa xs) x" value "inversa [a, b, c]" lemma "inversa [a, b, c] = [c, b, a]" by simp text {* ---------------------------------------------------------------------- Ejercicio 4.3. Demostrar que inversa (inversa xs) = xs" Nota: Se necesita un lema relacionando las funciones inversa y snoc. ------------------------------------------------------------------- *} lemma inversa_snoc: "inversa (snoc xs y) = y # inversa xs" by (induct xs) auto theorem "inversa (inversa xs) = xs" by (induct xs) (auto simp add: inversa_snoc) text {* ---------------------------------------------------------------------- Ejercicio 4.4. Definir la función inversa_it :: "'a list \<Rightarrow> 'a list" tal que (inversa_it xs) es la inversa de xs calculada con un acumulador. Por ejemplo, inversa_it [a,b,c] = [c,b,a] ------------------------------------------------------------------- *} fun inversa_it_aux :: "'a list \<Rightarrow> 'a list \<Rightarrow> 'a list" where "inversa_it_aux ys [] = ys" | "inversa_it_aux ys (x # xs) = inversa_it_aux (x # ys) xs" fun inversa_it :: "'a list \<Rightarrow> 'a list" where "inversa_it xs = inversa_it_aux [] xs" value "inversa_it [a,b,c]" text {* ---------------------------------------------------------------------- Ejercicio 4.5. Demostrar que inversa_it (inversa_it xs) = xs" ------------------------------------------------------------------- *} lemma inversa_it_aux_lemma: "\<forall>ys. inversa_it_aux [] (inversa_it_aux ys xs) = inversa_it_aux xs ys" by (induct xs) auto lemma "inversa_it (inversa_it xs) = xs" by (simp add: inversa_it_aux_lemma) end
module Data.Boolean.Operators where open import Data.Boolean -- Definition of boolean operators with conventions from logic module Logic where infixl 1005 _∧_ infixl 1004 _∨_ _⊕_ infixl 1003 _⟵_ _⟷_ _⟶_ _∧_ : Bool → Bool → Bool _∧_ 𝑇 𝑇 = 𝑇 _∧_ 𝐹 𝑇 = 𝐹 _∧_ 𝑇 𝐹 = 𝐹 _∧_ 𝐹 𝐹 = 𝐹 _∨_ : Bool → Bool → Bool _∨_ 𝑇 𝑇 = 𝑇 _∨_ 𝐹 𝑇 = 𝑇 _∨_ 𝑇 𝐹 = 𝑇 _∨_ 𝐹 𝐹 = 𝐹 open Data.Boolean using () renaming (not to ¬) public _⊕_ : Bool → Bool → Bool _⊕_ 𝑇 𝑇 = 𝐹 _⊕_ 𝐹 𝑇 = 𝑇 _⊕_ 𝑇 𝐹 = 𝑇 _⊕_ 𝐹 𝐹 = 𝐹 _⟶_ : Bool → Bool → Bool _⟶_ 𝑇 𝑇 = 𝑇 _⟶_ 𝐹 𝑇 = 𝑇 _⟶_ 𝑇 𝐹 = 𝐹 _⟶_ 𝐹 𝐹 = 𝑇 _⟵_ : Bool → Bool → Bool _⟵_ 𝑇 𝑇 = 𝑇 _⟵_ 𝐹 𝑇 = 𝐹 _⟵_ 𝑇 𝐹 = 𝑇 _⟵_ 𝐹 𝐹 = 𝑇 _⟷_ : Bool → Bool → Bool _⟷_ 𝑇 𝑇 = 𝑇 _⟷_ 𝐹 𝑇 = 𝐹 _⟷_ 𝑇 𝐹 = 𝐹 _⟷_ 𝐹 𝐹 = 𝑇 _⊼_ : Bool → Bool → Bool _⊼_ 𝑇 𝑇 = 𝐹 _⊼_ 𝐹 𝑇 = 𝑇 _⊼_ 𝑇 𝐹 = 𝑇 _⊼_ 𝐹 𝐹 = 𝑇 _⊽_ : Bool → Bool → Bool _⊽_ 𝑇 𝑇 = 𝐹 _⊽_ 𝐹 𝑇 = 𝐹 _⊽_ 𝑇 𝐹 = 𝐹 _⊽_ 𝐹 𝐹 = 𝑇 ⊤ : Bool ⊤ = 𝑇 ⊥ : Bool ⊥ = 𝐹 -- Definition of boolean operators with conventions from typical programming languages module Programming where open Logic using () renaming (_∧_ to _&&_ ; _∨_ to _||_ ; ¬ to ! ; _⟷_ to _==_ ; _⊕_ to _!=_ ; _⟶_ to _→?_ ; _⟵_ to _←?_ ) public
lemma cCons_not_0_eq [simp]: "x \<noteq> 0 \<Longrightarrow> x ## xs = x # xs"
function [ori,varargout] = loadOrientation(fname,varargin) warning('loadOrientation is depreciated. Please use instead orientation.load'); [ori,varargout{1:nargout-1}] = orientation.load(fname,varargin{:});
import Mathlib /-! # Welcome to the course We start with a quick tour, where we: * Use Lean as a calculator * Define some functions and call them. * Look at some types. * Look at some proofs. We will then see * A glimpse of AI. * A detailed example with programs and proofs. -/ /-! ## Lean as a calculator. We begin by using Lean as a calculator. We can use `#eval` to evaluate expressions. ```lean #eval 1 + 2 -- 3 #eval "Hello " ++ "world!" -- "Hello world!" ``` -/ #eval 1 + 2 #eval "Hello " ++ "world!" /-- An arbitrary number. -/ def some_number := 42 /-! We next evaluate an expression involving a definition. ```lean #eval some_number + 23 -- 65 ``` -/ #eval some_number + 23 /-! ## Defining functions We next define some functions. These are defined in terms of previously defined functions. -/ /-- Add `2` to a natural number -/ def add_two (n : ℕ) : ℕ := n + 2 /-- Cube a natural number -/ def cube (n : ℕ) : ℕ := n * n * n /-! ```lean #eval cube (add_two 3) -- 125 ``` -/ #eval cube (add_two 3) /-- Cube a natural number -/ def cube' := fun (n : ℕ) ↦ n * n * n /-- Cube a natural number -/ def cube'' : ℕ → ℕ := fun n ↦ n * n * n example := λ (n : ℕ) => n * n * n /-! ## Types Terms in Lean, including functions, have types, which can be seen using `#check` ```lean #check 1 + 2 -- ℕ #check "Hello " ++ "world!" -- String #check add_two -- ℕ → ℕ #check cube -- ℕ → ℕ #check ℕ -- Type #check Type -- Type 1 #check ℕ → ℕ -- Type ``` -/ #check 1 + 2 #check "Hello " ++ "world!" #check add_two #check cube #check ℕ #check Type #check ℕ → ℕ /-! We next define a function of two arguments, and look at its type. We see that this is defined as a function from `ℕ` to a function from `ℕ` to `ℕ`. -/ /-- Sum of squares of natural numbers `x` and `y` -/ def sum_of_squares (x y : ℕ) : ℕ := x * x + y * y /-! ```lean #check sum_of_squares -- ℕ → ℕ → ℕ #check sum_of_squares 3 -- ℕ → ℕ ``` We can also define this in a way that makes the type clearer. -/ #check sum_of_squares -- ℕ → (ℕ → ℕ) #check sum_of_squares 3 -- ℕ → ℕ /-- Sum of squares of natural numbers `x` and `y` -/ def sum_of_squares' : ℕ → ℕ → ℕ := fun x ↦ fun y ↦ x * x + y * y
This section provides a tutorial example on how to call an RPC method defined a WSDL 1.1 document with SOAP 1.1 binding. I used the local version of my WSDL document, c:/herong/GetExchangeRate_WSDL_11_SOAP_11_RPC.wsdl. The online version at http://www.herongyang.com/Service/ GetExchangeRate_WSDL_11_SOAP_11_RPC.wsdl gives me an access problem because the site does not like Perl HTTP client agent. I used readable('true') to make the SOAP request XML message is nice format. SOAP::Lite does allow you to make an RPC call through a WSDL document like a local method call: GetExchangeRate('USD', 'JPY', '2007-07-07'). SOAP::Lite is smart to convert the RPC call into a SOAP request message. SOAP::Lite is smart to provide type information xsi:type="..." to support message encoding. SOAP::Lite is smart to pick up the return value from the SOAP response message. SOAP::Lite is not smart to follow the parts="fromCurrencyPart toCurrencyPart datePart" specified in the WSDL document to order the parameters. It follows the original order of how these message parts were defined in the WSDL document. To correct the issue, you need to make the call like this: GetExchangeRate('2007-07-07', 'USD', 'JPY'). Conclusion, SOAP::Lite 0.710 does not support the parts="..." of the "soap:body" WSDL statement.