text
stringlengths 0
3.34M
|
---|
/**
\ * External definitions to parametrize spectrum traces
* in aXe grism exposures
*/
#ifndef _SPC_TRACE_FUNCTIONS_H
#define _SPC_TRACE_FUNCTIONS_H
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_integration.h>
#include "aXe_errors.h"
/* public */
/** A function for parametrizing spectrum traces; deriv and/or path_len
(i.e. its derivative or the path length from parameter 0) may be
NULL if they are not known analytically.
func should return the the y offset for a given pixel column x of
the spectrum trace
*/
typedef struct
{
int type; /* A unique type ID for the trace function */
double (*func) (const double, const void *const pars);
double (*deriv) (const double, const void *const pars);
double (*path_len) (const double, const void *const pars);
void *data; /* private data for trace function, should
be passed as a second parameter */
}
trace_func;
/* The create_xxx functions return a pointer to an allocated trace_func
or NULL if the allocation failed. */
extern trace_func *
create_poly2 (const double a0, const double a1, const double a2);
extern trace_func *
create_polyN (gsl_vector *v);
extern trace_func *
vector_to_trace_poly2 (gsl_vector *v);
extern trace_func *
vector_to_trace_polyN(gsl_vector *v);
extern double
polyN_ds(double x, void *pars);
extern void
free_poly2(trace_func * func);
extern void
free_polyN(trace_func * func);
#endif /* ! _SPC_TRACE_FUNCTIONS_H */
|
% Wrapper for vl_nnselection block
% inputs{1} : X : 1 x 2 x N x b
% obj : idx : 1 x n
% outputs{1}: y : 1 x 2 x n x b
classdef selection < dagnn.Layer
properties
idx = [];
end
methods
function outputs = forward(obj, inputs, ~)
useGPU = isa(inputs{1}, 'gpuArray');
if useGPU
outputs{1} = gpuArray( vl_nnselection(gather(inputs{1}), obj.idx) );
else
outputs{1} = vl_nnselection(inputs{1}, obj.idx);
end
end
function [derInputs, derParams] = backward(obj, inputs, ~, derOutputs)
useGPU = isa(inputs{1}, 'gpuArray');
if useGPU
derInputs{1} = gpuArray( vl_nnselection(gather(inputs{1}), obj.idx, gather(derOutputs{1})) );
else
derInputs{1} = vl_nnselection(inputs{1}, obj.idx, derOutputs{1});
end
derParams = {};
end
function outputSizes = getOutputSizes(obj, inputSizes)
outputSizes = {1 inputSizes{1}(2) length(obj.idx) inputSizes{1}(4)} ;
end
function obj = selection(varargin)
obj.load(varargin);
end
end
end
|
Require Import Bool.Sumbool.
Require Import List.
Import ListNotations.
Require Import ZArith.
Require Import CakeSem.Utils.
Require Import CakeSem.CakeAST.
Require Import CakeSem.Namespace.
Require Import CakeSem.ffi.FFI.
Open Scope string_scope.
Open Scope list_scope.
Set Implicit Arguments.
(* ********************************************************************** *)
(** * Auxiliary semantics constructs *)
(* ---------------------------------------------------------------------- *)
(** ** Stamps and predefined constructors *)
(* constructor name and unique type number *)
Inductive stamp : Type :=
| TypeStamp : conN -> nat -> stamp
| ExnStamp : nat -> stamp.
Scheme Equality for stamp.
#[export] Hint Resolve stamp_eq_dec : DecidableEquality.
(* ---------------------------------------------------------------------- *)
(** ** Environments *)
(* QUESTION: what is the interest of being generic in the type of values? *)
(* ANSWER: I DON'T EVEN KNOW, but also we havent defined our values yet *)
Record sem_env (V : Type) := {
sev : namespace modN varN V;
(* nat is the arity of the constructor name conN *)
sec : namespace modN conN (nat * stamp) }.
Arguments sev {V} _.
Arguments sec {V} _.
(* TODO: Move to theorems file? *)
Theorem sem_env_id : forall (V : Type) (env : sem_env V), env = {| sev := sev env; sec := sec env|}.
Proof. destruct env; reflexivity. Qed.
(** Auxiliary definition to mimic [{ env with sev = .. }] *)
Definition update_sev V (e:sem_env V) (x:namespace modN varN V) :=
{| sev := x; sec := sec e |}.
(** Auxiliary definition to mimic [{ env with sec = .. }] *)
Definition update_sec V (e:sem_env V) x :=
{| sev := sev e; sec := x |}.
(* BACKPORT: use this definition in semantics *)
Definition empty_sem_env {V : Type} : sem_env V :=
{| sev := nsEmpty; sec := nsEmpty |}.
(* BACKPORT: extend_dec_env should be used in definition of combine_dec_result *)
Definition extend_dec_env (V : Type) (new_env env : sem_env V) : sem_env V :=
{| sev := nsAppend (sev new_env) (sev env);
sec := nsAppend (sec new_env) (sec env)|}.
(* ---------------------------------------------------------------------- *)
(** ** Values *)
Unset Elimination Schemes.
(* TODO: HOL4 version now supports floating point and a repl *)
Inductive val : Type :=
| Litv : lit -> val
| Conv : option stamp -> list val -> val
| Closure : sem_env val -> varN -> exp -> val
| Recclosure : sem_env val -> list (varN * varN * exp) -> varN -> val
| Loc : nat -> val
| Vectorv : list val -> val.
Set Elimination Schemes.
Definition env_val := namespace modN varN val.
Definition env_ctor := namespace modN conN (nat * stamp).
(** [is_closure v] captures whether [v] is a closure or a recursive closure. *)
Definition is_closureb (v : val) : bool :=
match v with
| Closure _ _ _ => true
| Recclosure _ _ _ => true
| _ => false
end.
Definition is_closure (v : val) : Prop :=
match v with
| Closure _ _ _ => True
| Recclosure _ _ _ => True
| _ => False
end.
(* ---------------------------------------------------------------------- *)
(** ** Predefined exceptions and constructors *)
(* BACKPORT: bind_stamp is used to mean "match failure", but that's not an intuitive name for it *)
Definition bind_stamp := ExnStamp 0.
Definition chr_stamp := ExnStamp 1.
Definition div_stamp := ExnStamp 2.
Definition subscript_stamp := ExnStamp 3.
Definition bind_exn_v := Conv (Some bind_stamp) [].
Definition chr_exn_v := Conv (Some chr_stamp) [].
Definition div_exn_v := Conv (Some div_stamp) [].
Definition sub_exn_v := Conv (Some subscript_stamp) [].
Definition bool_type_num := 0.
Definition list_type_num := 1.
Definition option_type_num := 2.
(* BACKPORT: define these 3 shorthands *)
Definition ConvTrue := Conv (Some (TypeStamp "True" bool_type_num)) [].
Definition ConvFalse := Conv (Some (TypeStamp "False" bool_type_num)) [].
Definition ConvUnit := Conv None [].
Definition Boolv (b : bool) : val :=
if b then ConvTrue else ConvFalse.
(* ---------------------------------------------------------------------- *)
(** ** Result of an evaluation *)
(* Result of evaluation *)
Inductive abort : Type :=
| Rtype_error : abort
| Rtimeout_error : abort
| Rffi_error : final_event -> abort.
Inductive error_result (A : Type) : Type :=
| Rraise : A -> error_result A
| Rabort : abort -> error_result A.
Arguments Rraise {A}.
Arguments Rabort {A}.
Inductive result (A : Type) (B : Type) : Type :=
| Rval : A -> result A B
| Rerr : error_result B -> result A B.
Arguments Rval {A} {B}.
Arguments Rerr {A} {B}.
Definition combine_dec_result {A : Type} (env : sem_env val) (r : result (sem_env val) A) :
result (sem_env val) A :=
match r with
| Rerr err => r
| Rval env' => Rval (extend_dec_env env' env)
end.
(* ---------------------------------------------------------------------- *)
(** ** Store *)
Inductive store_v (A : Type) : Type :=
(* Reference *)
| Refv : A -> store_v A
(* Byte array *)
| W8array : list word8 -> store_v A
(* Value array *)
| Varray : list A -> store_v A.
Arguments Refv {A}.
Arguments W8array {A}.
Arguments Varray {A}.
(* The nth item in the list is the value at location n *)
Definition store (A : Type) :=
list (store_v A).
(* ---------------------------------------------------------------------- *)
(** ** State *)
Record state (A : Type) :=
{
clock : nat;
refs : store val;
ffi : ffi_state A;
next_type_stamp : nat;
next_exn_stamp : nat
}.
Arguments clock {A} _.
Arguments refs {A} _.
Arguments ffi {A} _.
Arguments next_type_stamp {A} _.
Arguments next_exn_stamp {A} _.
Arguments refs {A} _.
Definition state_update_refs_and_ffi A (st:state A) refs' (ffi':ffi_state A) :=
{| clock := clock st;
refs := refs';
ffi := ffi';
next_type_stamp := next_type_stamp st ;
next_exn_stamp := next_exn_stamp st |}.
(** Auxiliary definition to mimic [{ st with next_type_stamp = .. }] *)
Definition state_update_next_type_stamp A (st:state A) x :=
{| clock := clock st;
refs := refs st;
ffi := ffi st;
next_type_stamp := x ;
next_exn_stamp := next_exn_stamp st |}.
(** Auxiliary definition to mimic [{ st with next_exn_stamp = .. }] *)
Definition state_update_next_exn_stamp A (st:state A) x :=
{| clock := clock st;
refs := refs st;
ffi := ffi st;
next_type_stamp := next_type_stamp st ;
next_exn_stamp := x |}.
(* ---------------------------------------------------------------------- *)
(** ** Pattern-maching result *)
Inductive match_result (A : Type) : Type :=
| No_match : match_result A
| Match_type_error : match_result A
| Match : A -> match_result A.
Arguments No_match {A}.
Arguments Match_type_error {A}.
Arguments Match {A}.
(* ********************************************************************** *)
(** * Auxiliary operations *)
(* BACKPORT: it would scale up better to use modules to organize the names,
e.g. Store.empty, Store.lookup, etc.. (The C-style naming convention
with everything flat eventually shows its limits... *)
(* ---------------------------------------------------------------------- *)
(** ** Typechecking *)
Definition store_v_same_type (A : Type) (v1 v2 : store_v A) : bool :=
match v1, v2 with
| Refv _, Refv _ => true
| W8array _, W8array _ => true
| Varray _, Varray _ => true
| _, _ => false
end.
Definition lit_same_type (l1 l2 : lit) : bool :=
match l1, l2 with
| IntLit _, IntLit _ => true
| CharLit _, CharLit _ => true
| StrLit _, StrLit _ => true
| Word8Lit _, Word8Lit _ => true
| Word64Lit _, Word64Lit _ => true
| _, _ => false
end.
Definition stamp_same_type (s1 s2 : stamp) : bool :=
match s1, s2 with
| TypeStamp _ n1, TypeStamp _ n2 => Nat.eqb n1 n2
| ExnStamp _, ExnStamp _ => true
| _, _ => false
end.
Definition ctor_same_type (os1 os2 : option stamp) : bool :=
match os1, os2 with
| None, None => true
| Some s1, Some s2 => stamp_same_type s1 s2
| _, _ => false
end.
(** [con_check cenv o l] asserts that the constructor (or None for a tuple) admits arity [l].
(Note that tuples admit any arity.)
This is an inductive version of [do_con_check] *)
Definition do_con_check (cenv : env_ctor) (cid : constr_id) (l : nat) : bool :=
match cid with
| None => true
| Some id => match nsLookup (ident_beq _ _ String.eqb String.eqb) id cenv with
| None => false
| Some (l',s) => Nat.eqb l' l
end
end.
(* ---------------------------------------------------------------------- *)
(** ** Operations on the store *)
Definition empty_store (A : Type) : store A := [].
Arguments empty_store {A}.
Definition store_lookup {A : Type} (n : nat) (st : store A) :=
List.nth_error st n.
Definition store_alloc {A : Type} (v : store_v A) (st : store A) : (store A * nat) :=
(st ++ [v], List.length st).
Definition store_assign_nocheck {A : Type} (n : nat) (v : store_v A) (st : store A) : store A :=
Utils.update n v st.
(* ---------------------------------------------------------------------- *)
(** ** Operations on constructors *)
Definition build_conv (cenv : env_ctor) (cid : constr_id) (vs: list val) : option val :=
match cid with
| None => Some (Conv None vs)
| Some id => match nsLookup (ident_beq _ _ String.eqb String.eqb) id cenv with
| None => None
| Some (len,stmp) => Some (Conv (Some stmp) vs)
end
end.
(* ---------------------------------------------------------------------- *)
(** ** Operations for functions *)
Definition build_rec_env (funs : list (varN * varN * exp)) (cl_env : sem_env val)
(add_to_env : env_val) : env_val :=
fold_right (fun '(f,x,e) env' => nsBind f (Recclosure cl_env funs f) env') add_to_env funs.
Fixpoint find_recfun {A B : Type} (n : varN) (funs : list (varN * A * B)) : option (A * B) :=
match funs with
| [] => None
| (f,x,e)::funs' => if string_dec f n then Some (x,e) else find_recfun n funs'
end.
(* ---------------------------------------------------------------------- *)
(** ** Lookup for binary operations *)
Definition opn_lookup (op : opn) : Z -> Z -> Z :=
match op with
| Plus => Z.add
| Minus => Z.sub
| Times => Z.mul
| Divide => Z.div
| Modulo => Z.modulo
end.
Definition opb_lookup (op : opb) : Z -> Z -> bool :=
match op with
| Lt => Z.ltb
| Gt => Z.gtb
| Leq => Z.leb
| Geq => Z.geb
end.
Definition opb_lookup_Prop (op : opb) : Z -> Z -> Prop :=
match op with
| Lt => Z.lt
| Gt => Z.gt
| Leq => Z.le
| Geq => Z.ge
end.
Parameter opw8_lookup : forall (op : opw), word8 -> word8 -> word8.
(* TODO: implement
match op with
| Andw => word_and
| Orw => word_or
| Xorw => word_xor
| Addw => word_add
end 8.*)
Parameter opw64_lookup : forall (op : opw), word64 -> word64 -> word64.
(* TODO: implement
match op with
| Andw => word_and
| Orw => word_or
| Xorw => word_xor
| Addw => word_add
end 64. *)
Parameter shift8_lookup : forall (op : CakeAST.shift), word8 -> nat -> word8.
(* TODO: implement
fun w n => match op with
| Lsl => id w
| Lsr => id w
| Asr => id w
| Ror => id w
end. *)
Parameter shift64_lookup : forall (op : CakeAST.shift), word64 -> nat -> word64.
(* TODO: implement
fun w n => match op with
| Lsl => id w
| Lsr => id w
| Asr => id w
| Ror => id w
end. *)
(* ---------------------------------------------------------------------- *)
(** ** Type definitions *)
Open Scope bool_scope.
Open Scope nat_scope.
Definition UniqueCtorsInDef (td : list tvarN * typeN * list (conN * list ast_t)) : Prop :=
let '(tvs,tn,condefs) := td in
NoDup (List.map (fun '(n,_) => n) condefs).
Definition UniqueCtorsInDefs (tds : typeDef) : Prop :=
List.Forall UniqueCtorsInDef tds.
Definition build_constrs (s : nat) (condefs : list (conN * (list ast_t)) ) :=
List.map (fun '(conN,ts) => (conN,(List.length ts, TypeStamp conN s))) condefs.
Fixpoint build_tdefs (next_stamp : nat) (tds : list (list tvarN * typeN * list (conN * list ast_t))) : env_ctor :=
match tds with
| [] => alist_to_ns []
| (tvars,tn,condefs)::tds' => nsAppend
(build_tdefs (next_stamp + 1) tds')
(alist_to_ns (List.rev (build_constrs next_stamp condefs)))
end.
(* ********************************************************************** *)
(** * Other auxiliary operations,
currently not needed by RelationBigStep, but might be in the future *)
Fixpoint val_to_list (v : val) : option (list val) :=
match v with
| Conv (Some stamp) [] => if stamp_eq_dec stamp (TypeStamp "[]" list_type_num)
then Some []
else None
| Conv (Some stamp) [v1;v2] => if stamp_eq_dec stamp (TypeStamp "::" list_type_num)
then match val_to_list v2 with
| Some vs => Some (v1::vs)
| None => None
end
else None
| _ => None
end.
Fixpoint list_to_val (vs : list val) : val :=
match vs with
| [] => Conv (Some (TypeStamp "[]" list_type_num)) []
| v'::vs' => Conv (Some (TypeStamp "::" list_type_num)) [v'; list_to_val vs']
end.
Fixpoint val_to_char_list (v : val) : option (list char) :=
match v with
| Conv (Some stamp) [] => if stamp_eq_dec stamp (TypeStamp "[]" list_type_num)
then Some []
else None
| Conv (Some stamp) [Litv (CharLit c); v'] =>
if stamp_eq_dec stamp (TypeStamp "::" list_type_num)
then match val_to_char_list v' with
| Some cs => Some (c::cs)
| None => None
end
else None
| _ => None
end.
Fixpoint vals_to_string (vs : list val) : option String.string :=
match vs with
| [] => Some ""
| (Litv (StrLit s1))::vs' => match vals_to_string vs' with
| Some s2 => Some (String.append s1 s2)
| None => None
end
| _ => None
end.
Open Scope bool_scope.
Open Scope Z_scope.
Definition copy_array {A : Type} (p : list A * Z) (len : Z)
(op : option (list A * Z)) : option (list A) :=
let (src,srcoff) := p in
if (srcoff =? 0) || (len <? 0) || (Zlength src <? srcoff + len)
then None
else let copied := List.firstn (Z.to_nat len)
(List.skipn (Z.to_nat srcoff) src) in
match op with
| Some (dst,dstoff) => if (dstoff <? 0) || (Zlength dst <? dstoff + len)
then None
else Some (List.firstn
(Z.to_nat dstoff)
dst ++ copied ++
List.skipn (Z.to_nat (dstoff + len)) dst)
| None => Some copied
end.
Close Scope bool_scope.
Close Scope Z_scope.
(* ********************************************************************** *)
(** * Induction principles *)
(* ---------------------------------------------------------------------- *)
(** ** Induction for values *)
Fixpoint val_rect (P : val -> Type)
(H1 : forall (l : lit), P (Litv l))
(H2 : forall (o : option stamp) (l : list val), Forall'' P l -> P (Conv o l))
(H3 : forall (s : sem_env val) (n : varN) (e : exp), Forall'' (fun p => P (snd p)) (sev s) -> P (Closure s n e))
(H4 : forall (s : sem_env val) (l : list (varN * varN * exp)) (n : varN), Forall'' (fun p => P (snd p)) (sev s) ->
P (Recclosure s l n))
(H5 : forall (n : nat), P (Loc n))
(H6 : forall (l : list val), Forall'' P l -> P (Vectorv l))
(v : val) : P v :=
let val_rect' := @val_rect P H1 H2 H3 H4 H5 H6 in
match v with
| Litv l => H1 l
| Conv o l => let fix loop (l : list val) :=
match l with
| [] => Forall_nil'' val P
| h::t => Forall_cons'' val P h t (val_rect' h) (loop t)
end
in
H2 o l (loop l)
| Closure s n e => let fix loop__ns (ls : namespace modN varN val) :=
match ls with
| [] => Forall_nil'' (ident modN varN * val) (fun p => P (snd p))
| ((i,v'))::ls' => Forall_cons'' (ident modN varN * val) (fun p => P (snd p))
(i,v') ls' (val_rect' v') (loop__ns ls')
end
in
H3 s n e (loop__ns (sev s))
| Recclosure s l n => let fix loop__ns (ls : namespace modN varN val) :=
match ls with
| [] => Forall_nil'' (ident modN varN * val) (fun p => P (snd p))
| ((i,v'))::ls' => Forall_cons'' (ident modN varN * val) (fun p => P (snd p))
(i,v') ls' (val_rect' v') (loop__ns ls')
end
in
H4 s l n (loop__ns (sev s))
| Loc n => H5 n
| Vectorv l => let fix loop (l : list val) :=
match l with
| [] => Forall_nil'' val P
| h::t => Forall_cons'' val P h t (val_rect' h) (loop t)
end
in
H6 l (loop l)
end.
Definition val_ind (P : val -> Prop) := @val_rect P.
Definition val_rec (P : val -> Set) := @val_rect P.
Fixpoint val_beq (v1 v2 : val) : bool :=
match v1, v2 with
| Litv l1, Litv l2 => lit_beq l1 l2
| Conv o1 l1, Conv o2 l2 => andb (option_beq _ stamp_beq o1 o2) (list_beq val_beq l1 l2)
(* not real equality, but considered equivalent by CakeML*)
| Closure env1 v1 e1, Closure env2 v2 e2 => true
| Recclosure env1 l1 v1, Recclosure env2 l2 v2 => true
| Loc n1, Loc n2 => n1 =? n2
| Vectorv l1, Vectorv l2 => list_beq val_beq l1 l2
| _, _ => false
end.
(** Decidability theorems *)
(* Theorem val_eq_dec : forall (v0 v1 : val), {v0 = v1} + {v0 <> v1}. *)
(* Proof. *)
(* decide equality; auto with DecidableEquality. *)
(* - generalize dependent l0. induction l; destruct l0; try (left; reflexivity); try (right; discriminate). *)
(* inversion X; subst; clear X. destruct (X0 v); destruct (IHl X1 l0); subst; try (right; discriminate); try (left; reflexivity). *)
(* right; injection; assumption. *)
(* right; injection; assumption. *)
(* right; injection. intro. assumption. *)
(* - generalize dependent s0. induction s; destruct s0. *)
(* assert (pair_nat_stamp_dec : forall (p p0: (nat * stamp)), {p = p0} + {p <> p0}) *)
(* by (decide equality; auto with DecidableEquality). *)
(* destruct (namespace_eq_dec modN conN (nat * stamp) String.string_dec String.string_dec *)
(* pair_nat_stamp_dec sec0 sec1); subst. *)
(* generalize dependent sev1. *)
(* simpl in X. *)
(* induction X; destruct sev1; try (left; reflexivity); try (right; discriminate). *)
(* destruct x; destruct p0. *)
(* destruct (ident_eq_dec modN varN string_dec string_dec i i0); subst. *)
(* destruct (p v3); subst. *)
(* simpl in *. *)
(* destruct (IHX sev1). *)
(* inversion e1. *)
(* left; reflexivity. *)
(* right; intro con; inversion con. apply n0. rewrite H0. reflexivity. *)
(* right; intro con; inversion con; auto. *)
(* right; intro con; inversion con; auto. *)
(* right; intro con; inversion con; auto. *)
(* - generalize dependent s0. induction s; destruct s0. *)
(* assert (pair_nat_stamp_dec : forall (p p0: (nat * stamp)), {p = p0} + {p <> p0}) *)
(* by (decide equality; auto with DecidableEquality). *)
(* destruct (namespace_eq_dec modN conN (nat * stamp) String.string_dec String.string_dec *)
(* pair_nat_stamp_dec sec0 sec1); subst. *)
(* simpl in X. *)
(* generalize dependent sev1. *)
(* induction X; destruct sev1; try (left; reflexivity); try (right; discriminate). *)
(* destruct x; destruct p0. *)
(* destruct (ident_eq_dec modN varN string_dec string_dec i i0); subst. *)
(* destruct (p v3); subst. *)
(* simpl in *. *)
(* destruct (IHX sev1). *)
(* inversion e. *)
(* left; reflexivity. *)
(* right; intro con; inversion con. apply n0. rewrite H0. reflexivity. *)
(* right; intro con; inversion con; auto. *)
(* right; intro con; inversion con; auto. *)
(* right; intro con; inversion con; auto. *)
(* - generalize dependent l0. induction l; destruct l0; try (left; reflexivity); try (right; discriminate). *)
(* inversion X; subst; clear X. destruct (X0 v); destruct (IHl X1 l0); subst; try (right; discriminate); try (left; reflexivity). *)
(* right; injection; assumption. *)
(* right; injection; assumption. *)
(* right; injection. intro. assumption. *)
(* Defined. *)
Lemma UniqueCtorsInDef_dec : forall (td : (list tvarN * typeN * list (conN * list ast_t))),
{UniqueCtorsInDef td} + {~ UniqueCtorsInDef td}.
Proof.
unfold UniqueCtorsInDef. intro td.
destruct td. destruct p.
apply NoDuplicates_dec.
auto with DecidableEquality.
Defined.
Theorem UniqueCtorsInDefs_dec : forall (tds : typeDef), {UniqueCtorsInDefs tds} + {~ UniqueCtorsInDefs tds}.
Proof.
apply Forall_dec.
apply UniqueCtorsInDef_dec.
Defined.
|
module Category.Profunctor where
open import Agda.Primitive using (Level; _β_; lsuc)
open import Data.Product using (_,_; _Γ_)
open import Function using (id)
open import Relation.Binary.PropositionalEquality using (_β‘_)
Dimap : β {a b} (p : Set a β Set a β Set b) β Set (lsuc a β b)
Lmap : β {a b} (p : Set a β Set a β Set b) β Set (lsuc a β b)
Rmap : β {a b} (p : Set a β Set a β Set b) β Set (lsuc a β b)
Dimap p = β {x y z w} β (f : x -> y) -> (h : z -> w) -> (g : p y z) β p x w
Lmap p = β {x y w} β (f : x -> y) -> (g : p y w) β p x w
Rmap p = β {x z w} β (h : z -> w) -> (g : p x z) β p x w
record ProfunctorImp {a b : Level} (p : Set a β Set a β Set b) : Set (lsuc (a β b)) where
field
dimap : Dimap p
lmap : Lmap p
rmap : Rmap p
dimapFromLmapRmap : β {a b} {p : Set a β Set a β Set b} (lmap : Lmap p) (rmap : Rmap p) β Dimap p
dimapFromLmapRmap lmap rmap f h g = rmap h (lmap f g)
lmapRmapFromDimap : β {a b} {p : Set a β Set a β Set b} (dimap : Dimap p) β (Lmap p Γ Rmap p)
lmapRmapFromDimap dimap = (Ξ» f β dimap f id) , dimap id
module Profunctor {a b : Level} {p : Set a β Set a β Set b} (isProfunctor : ProfunctorImp p) where
open ProfunctorImp isProfunctor public
record LawfulProfunctorImp {a b} {p : Set a β Set a β Set b} (isProfunctor : ProfunctorImp p) : Set (lsuc (a β b)) where
open Profunctor isProfunctor
field
lmapId : β {a b} {g : p a b} β lmap id g β‘ g
rmapId : β {a b} {g : p a b} β rmap id g β‘ g
dimapLmapRmap : β {a b c d} {f : a β b} {g : p b c} {h : c β d} β dimap f h g β‘ lmap f (rmap h g)
module LawfulProfunctor {a b} {p : Set a β Set a β Set b} {isProfunctor : ProfunctorImp p} (isLawful : LawfulProfunctorImp isProfunctor) where
open Profunctor isProfunctor public
open LawfulProfunctorImp isLawful public
|
Anagrams := function(name)
local f, p, L, line, word, words, swords, res, cur, r;
words := [ ];
swords := [ ];
f := InputTextFile(name);
while true do
line := ReadLine(f);
if line = fail then
break;
else
word := Chomp(line);
Add(words, word);
Add(swords, SortedList(word));
fi;
od;
CloseStream(f);
p := SortingPerm(swords);
L := Permuted(words, p);
r := "";
cur := [ ];
res := [ ];
for word in L do
if SortedList(word) = r then
Add(cur, word);
else
if Length(cur) > 0 then
Add(res, cur);
fi;
r := SortedList(word);
cur := [ word ];
fi;
od;
if Length(cur) > 0 then
Add(res, cur);
fi;
return Filtered(res, v -> Length(v) > 1);
end;
ana := Anagrams("my/gap/unixdict.txt");;
# What is the longest anagram sequence ?
Maximum(List(ana, Length));
# 5
# Which are they ?
Filtered(ana, v -> Length(v) = 5);
# [ [ "abel", "able", "bale", "bela", "elba" ],
# [ "caret", "carte", "cater", "crate", "trace" ],
# [ "angel", "angle", "galen", "glean", "lange" ],
# [ "alger", "glare", "lager", "large", "regal" ],
# [ "elan", "lane", "lean", "lena", "neal" ],
# [ "evil", "levi", "live", "veil", "vile" ] ]
|
(* Title: HOL/Auth/n_flash_lemma_on_inv__128.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_flash Protocol Case Study*}
theory n_flash_lemma_on_inv__128 imports n_flash_base
begin
section{*All lemmas on causal relation between inv__128 and some rule r*}
lemma n_PI_Remote_PutXVsinv__128:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_PI_Remote_PutX dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Remote_ReplaceVsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Replace src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_HeadVsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_PutVsinv__128:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_Put_HomeVsinv__128:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_1Vsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_2Vsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_3Vsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_4Vsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_5Vsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_6Vsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_HomeVsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8Vsinv__128:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__128:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10_HomeVsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10Vsinv__128:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_11Vsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutXVsinv__128:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutX_HomeVsinv__128:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutVsinv__128:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "((formEval (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true))) s))" by auto
moreover {
assume c1: "((formEval (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true)) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (neg (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately have "invHoldForRule s f r (invariants N)" by satx
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutXVsinv__128:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_InvVsinv__128:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Inv dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_ReplaceVsinv__128:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Replace src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Replace src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) s))" by auto
moreover {
assume c1: "((formEval (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true)) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''ShrVld'')) (Const true))) s))"
have "?P2 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately have "invHoldForRule s f r (invariants N)" by satx
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__128:
assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__0 N )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__128:
assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__1 N )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_ShWbVsinv__128:
assumes a1: "(r=n_NI_ShWb N )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__128 p__Inv4" apply fastforce done
have "((formEval (andForm (eqn (Const (index p__Inv4)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc''))) (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) s))\<or>((formEval (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)) s))\<or>((formEval (andForm (neg (eqn (Const (index p__Inv4)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc'')))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)))) s))\<or>((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)))) s))" by auto
moreover {
assume c1: "((formEval (andForm (eqn (Const (index p__Inv4)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc''))) (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) s))"
have "?P3 s"
apply (cut_tac a1 a2 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Cmd'')) (Const SHWB_ShWb))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)) s))"
have "?P3 s"
apply (cut_tac a1 a2 c1, simp, rule_tac x="(neg (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (neg (eqn (Const (index p__Inv4)) (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Proc'')))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (andForm (neg (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''HomeProc'')) (Const false))) (neg (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''ShrSet'') p__Inv4)) (Const true)))) s))"
have "?P1 s"
proof(cut_tac a1 a2 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__1Vsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_GetVsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__0Vsinv__128:
assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_WbVsinv__128:
assumes a1: "r=n_NI_Wb " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_StoreVsinv__128:
assumes a1: "\<exists> src data. src\<le>N\<and>data\<le>N\<and>r=n_Store src data" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_GetX__part__1Vsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_3Vsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_1Vsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__1Vsinv__128:
assumes a1: "r=n_PI_Local_GetX_GetX__part__1 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__0Vsinv__128:
assumes a1: "r=n_PI_Local_GetX_GetX__part__0 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_Store_HomeVsinv__128:
assumes a1: "\<exists> data. data\<le>N\<and>r=n_Store_Home data" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_ReplaceVsinv__128:
assumes a1: "r=n_PI_Local_Replace " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__1Vsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__1Vsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Get__part__0Vsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_existsVsinv__128:
assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__2Vsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_PutXVsinv__128:
assumes a1: "r=n_PI_Local_PutX " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__2Vsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_GetX__part__0Vsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_PutVsinv__128:
assumes a1: "r=n_PI_Local_Get_Put " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_Nak_HomeVsinv__128:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutXAcksDoneVsinv__128:
assumes a1: "r=n_NI_Local_PutXAcksDone " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_NakVsinv__128:
assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_NakVsinv__128:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_GetXVsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__1Vsinv__128:
assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Nak_HomeVsinv__128:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_PutVsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__0Vsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_exists_HomeVsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Replace_HomeVsinv__128:
assumes a1: "r=n_NI_Replace_Home " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutVsinv__128:
assumes a1: "r=n_NI_Local_Put " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_NakVsinv__128:
assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_ClearVsinv__128:
assumes a1: "r=n_NI_Nak_Clear " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Put_DirtyVsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__0Vsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_GetVsinv__128:
assumes a1: "r=n_PI_Local_Get_Get " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_HomeVsinv__128:
assumes a1: "r=n_NI_Nak_Home " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_2Vsinv__128:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_FAckVsinv__128:
assumes a1: "r=n_NI_FAck " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__128 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
(*-------------------------------------------*
| CSP-Prover on Isabelle2004 |
| November 2004 |
| |
| CSP-Prover on Isabelle2005 |
| October 2005 (modified) |
| March 2006 (modified) |
| CSP-Prover on Isabelle2016 |
| May 2016 (modified) |
| |
| Yoshinao Isobe (AIST JAPAN) |
*-------------------------------------------*)
theory Norm_seq
imports CMS
begin
(*****************************************************************
1. Definition of Normarized sequences
2. Properties of Normarized sequences
3. How to transform each Cauchy sequence to NF
4. The same limit between xs and NF(xs)
*****************************************************************)
definition
normal :: "'a::ms infinite_seq => bool"
where
normal_def :
"normal xs == ALL (n::nat) (m::nat).
distance(xs n, xs m) <= (1/2)^(min n m)"
definition
Nset :: "'a::ms infinite_seq => real => nat set"
where
Nset_def :
"Nset xs delta ==
{N. ALL n m. (N <= m & N <= n) --> distance(xs n, xs m) <= delta}"
definition
Nmin :: "'a::ms infinite_seq => real => nat"
where
Nmin_def :
"Nmin xs delta == MIN (Nset xs delta)"
definition
NF :: "'a::ms infinite_seq => 'a::ms infinite_seq"
where
NF_def :
"NF xs == (%n. xs (Nmin xs ((1/2)^n)))"
(********************************************************************
Normalization
********************************************************************)
(*** normalized sequence --> Cauchy sequence ***)
lemma normal_cauchy: "normal xs ==> cauchy xs"
apply (simp add: cauchy_def)
apply (intro allI impI)
apply (subgoal_tac "EX n. (1/2) ^ n < delta")
apply (erule exE)
apply (rule_tac x="n" in exI)
apply (intro allI impI)
apply (simp add: normal_def)
apply (drule_tac x="i" in spec)
apply (drule_tac x="j" in spec)
apply (subgoal_tac "((1::real) / 2) ^ min i j <= (1 / 2) ^ n")
apply (simp)
apply (case_tac "i <= j")
apply (simp add: min_def power_decreasing)
apply (simp add: min_def power_decreasing)
apply (simp add: pow_convergence)
done
(*
declare realpow_Suc [simp del]
in isabelle2008
*)
declare power_Suc [simp del]
lemma normal_Limit:
"[| normal xs ; xs convergeTo y |]
==> distance(xs (Suc n), y) < (1/2)^n"
apply (simp add: convergeTo_def)
apply (drule_tac x="(1/2)^(Suc n)" in spec)
apply (simp)
apply (erule exE)
apply (rename_tac N)
apply (case_tac "N <= Suc n")
apply (drule_tac x="Suc n" in spec)
apply (simp add: symmetry_ms)
apply (subgoal_tac "((1::real) / 2) ^ Suc n <= (1 / 2) ^ n")
apply (simp)
apply (simp add: power_decreasing)
(* else (i.e. Suc n < N *)
apply (drule_tac x="N" in spec)
apply (simp)
apply (insert triangle_inequality_ms)
apply (drule_tac x="xs (Suc n)" in spec)
apply (drule_tac x="xs N" in spec)
apply (drule_tac x="y" in spec)
apply (simp add: normal_def)
apply (drule_tac x="Suc n" in spec)
apply (drule_tac x="N" in spec)
apply (simp add: symmetry_ms)
apply (simp add: min_def)
apply (simp add: power_Suc)
done
(*
declare realpow_Suc [simp]
*)
declare power_Suc [simp]
(********************************************************************
Nmin
********************************************************************)
(*** Nmin exists ***)
lemma Nmin_exists:
"[| 0 < delta ; cauchy xs |] ==> EX N. N isMIN (Nset xs delta)"
apply (simp add: cauchy_def)
apply (drule_tac x="delta" in spec)
apply (simp)
apply (erule exE)
apply (rule EX_MIN_nat)
apply (simp add: Nset_def)
apply (rule_tac x="n" in exI)
apply (intro allI impI)
apply (drule_tac x="na" in spec)
apply (drule_tac x="m" in spec)
by (simp)
lemma Nset_hasMIN:
"[| 0 < delta ; cauchy xs |] ==> (Nset xs delta) hasMIN"
apply (simp add: hasMIN_def)
apply (rule Nmin_exists)
by (simp)
(*** Nmin unique ***)
lemma Nmin_unique:
"[| N isMIN (Nset xs delta) ; M isMIN (Nset xs delta) |] ==> N = M"
by (simp add: MIN_unique)
(*-----------------------*
| the Nmin |
*-----------------------*)
lemma Nset_to_Nmin :
"[| 0 < delta ; cauchy xs |]
==> (N isMIN (Nset xs delta)) = (Nmin xs delta = N)"
apply (simp add: Nmin_def)
apply (rule iffI)
apply (simp add: MIN_def Nset_hasMIN)
apply (rule the_equality)
apply (simp)
apply (simp add: Nmin_unique)
by (simp add: MIN_iff Nset_hasMIN)
lemmas Nmin_to_Nset = Nset_to_Nmin[THEN sym]
lemma Nmin_to_Nset_sym :
"[| 0 < delta ; cauchy xs |]
==> (N = Nmin xs delta) = (N isMIN (Nset xs delta))"
by (auto simp add: Nset_to_Nmin)
lemmas Nmin_iff = Nmin_to_Nset Nmin_to_Nset_sym
(*-----------------------*
| property |
*-----------------------*)
lemma Nmin_cauchy_lm:
"[| 0 < delta ; cauchy xs ; Nmin xs delta = N |]
==> (ALL n m. (N <= m & N <= n) --> distance(xs n, xs m) <= delta)"
by (simp add: Nmin_iff Nset_def isMIN_def)
lemma Nmin_cauchy:
"[| 0 < delta ; cauchy xs ; Nmin xs delta <= m ; Nmin xs delta <= n |]
==> distance(xs n, xs m) <= delta"
by (simp add: Nmin_cauchy_lm)
(*-----------------------*
| min_number_cauchy |
*-----------------------*)
(*** Nmin order (check) ***)
lemma min_number_cauchy_lm:
"[| 0 < delta1 ; delta1 <= delta2 ; cauchy xs |]
==> Nset xs delta1 <= Nset xs delta2"
apply (simp add: Nset_def)
apply (rule subsetI)
apply (simp)
apply (intro allI impI)
apply (drule_tac x="n" in spec)
apply (drule_tac x="m" in spec)
by (simp)
(*** Nmin order ***)
lemma min_number_cauchy:
"[| 0 < delta1 ; delta1 <= delta2 ; cauchy xs ;
Nmin xs delta1 = N1 ; Nmin xs delta2 = N2 |]
==> N2 <= N1"
apply (simp add: Nmin_iff)
by (simp add: isMIN_subset min_number_cauchy_lm)
(*** Nmin order half ***)
lemma min_number_cauchy_half:
"[| n <= m ; cauchy xs ; Nmin xs ((1/2)^n) = N1 ; Nmin xs ((1/2)^m) = N2 |]
==> N1 <= N2"
apply (rule min_number_cauchy)
by (simp_all add: power_decreasing)
(*------------------------*
| normal_form_seq_normal |
*------------------------*)
lemma normal_form_seq_normal: "cauchy xs ==> normal (NF(xs))"
apply (simp add: normal_def NF_def)
apply (intro allI)
apply (case_tac "n <= m")
apply (simp add: min_def)
apply (rule Nmin_cauchy, simp_all)
apply (rule min_number_cauchy_half, simp_all)
(* else *)
apply (simp add: min_def)
apply (rule Nmin_cauchy, simp_all)
apply (rule min_number_cauchy_half, simp_all)
done
(*----------------------------*
| normal_form_seq_same_Limit |
*----------------------------*)
(*** only if part ***)
lemma normal_form_seq_same_Limit_only_if:
"[| cauchy xs ; xs convergeTo y |] ==> NF(xs) convergeTo y"
apply (simp add: convergeTo_def)
apply (intro allI impI)
apply (drule_tac x="eps/2" in spec)
apply (simp)
apply (erule exE)
apply (subgoal_tac "EX n. (1 / 2) ^ n < eps/2")
apply (erule exE)
apply (rename_tac eps N M)
apply (rule_tac x="M" in exI)
apply (intro allI impI)
apply (case_tac "N <= Nmin xs ((1/2)^m)")
apply (drule_tac x="Nmin xs ((1/2)^m)" in spec)
apply (simp add: NF_def)
(* else *)
apply (insert triangle_inequality_ms)
apply (drule_tac x="y" in spec)
apply (drule_tac x="xs N" in spec)
apply (drule_tac x="(NF xs) m" in spec)
apply (drule_tac x="N" in spec)
apply (simp add: NF_def)
apply (subgoal_tac "distance (xs N, xs (Nmin xs ((1 / 2) ^ m))) <= (1 / 2) ^ m")
apply (subgoal_tac "((1::real) / 2) ^ m <= (1 / 2) ^ M")
apply (simp)
apply (simp add: power_decreasing)
apply (rule Nmin_cauchy)
apply (simp, simp, simp, simp)
apply (rule pow_convergence)
apply (simp_all)
done
(*** if part ***)
lemma normal_form_seq_same_Limit_if:
"[| cauchy xs ; NF (xs) convergeTo y |] ==> xs convergeTo y"
apply (simp add: convergeTo_def)
apply (intro allI impI)
apply (drule_tac x="eps/2" in spec)
apply (simp)
apply (erule exE)
apply (subgoal_tac "EX n. (1 / 2) ^ n < eps/2")
apply (erule exE)
apply (rename_tac eps N M)
apply (rule_tac x="Nmin xs ((1/2)^(max N M))" in exI)
apply (intro allI impI)
apply (insert triangle_inequality_ms)
apply (drule_tac x="y" in spec)
apply (drule_tac x="xs (Nmin xs ((1/2)^(max N M)))" in spec)
apply (drule_tac x="xs m" in spec)
apply (drule_tac x="max N M" in spec)
(* apply (simp add: le_maxI1) *)
apply (simp add: NF_def)
(* *)
apply (subgoal_tac
"distance(xs (Nmin xs ((1 / 2) ^ max N M)), xs m) <= (1 / 2) ^ max N M")
apply (subgoal_tac "((1::real) / 2) ^ max N M <= (1 / 2) ^ M")
apply (simp)
apply (simp add: max_def power_decreasing)
apply (rule Nmin_cauchy)
apply (simp, simp, simp, simp)
apply (rule pow_convergence)
apply (simp_all)
done
(*** iff ***)
lemma normal_form_seq_same_Limit:
"cauchy xs ==> xs convergeTo y = NF(xs) convergeTo y"
apply (rule iffI)
apply (simp add: normal_form_seq_same_Limit_only_if)
apply (simp add: normal_form_seq_same_Limit_if)
done
end
|
[STATEMENT]
lemma mod_prop1:"((a::nat) mod (b*c)) mod c = (a mod c)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. a mod (b * c) mod c = a mod c
[PROOF STEP]
proof(cases "c = 0")
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. c = 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
2. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
case True
[PROOF STATE]
proof (state)
this:
c = 0
goal (2 subgoals):
1. c = 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
2. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
have "b*c = 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. b * c = 0
[PROOF STEP]
by (metis True mult_0_right)
[PROOF STATE]
proof (state)
this:
b * c = 0
goal (2 subgoals):
1. c = 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
2. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
b * c = 0
[PROOF STEP]
have "(a::nat) mod (b*c) = a"
[PROOF STATE]
proof (prove)
using this:
b * c = 0
goal (1 subgoal):
1. a mod (b * c) = a
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
a mod (b * c) = a
goal (2 subgoals):
1. c = 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
2. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
a mod (b * c) = a
[PROOF STEP]
have "((a::nat) mod (b*c)) mod c = a mod c"
[PROOF STATE]
proof (prove)
using this:
a mod (b * c) = a
goal (1 subgoal):
1. a mod (b * c) mod c = a mod c
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
a mod (b * c) mod c = a mod c
goal (2 subgoals):
1. c = 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
2. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
a mod (b * c) mod c = a mod c
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
a mod (b * c) mod c = a mod c
goal (1 subgoal):
1. a mod (b * c) mod c = a mod c
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
a mod (b * c) mod c = a mod c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
case False
[PROOF STATE]
proof (state)
this:
c \<noteq> 0
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
let ?x = "(a::nat) mod (b*c)"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
let ?z = "?x mod c"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
have "\<exists>m. a = m*(b*c) + ?x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<exists>m. a = m * (b * c) + a mod (b * c)
[PROOF STEP]
by (metis div_mult_mod_eq)
[PROOF STATE]
proof (state)
this:
\<exists>m. a = m * (b * c) + a mod (b * c)
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<exists>m. a = m * (b * c) + a mod (b * c)
[PROOF STEP]
obtain m1 where "a = m1*(b*c) + ?x"
[PROOF STATE]
proof (prove)
using this:
\<exists>m. a = m * (b * c) + a mod (b * c)
goal (1 subgoal):
1. (\<And>m1. a = m1 * (b * c) + a mod (b * c) \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
a = m1 * (b * c) + a mod (b * c)
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
a = m1 * (b * c) + a mod (b * c)
[PROOF STEP]
have "?x = (a - m1*(b*c))"
[PROOF STATE]
proof (prove)
using this:
a = m1 * (b * c) + a mod (b * c)
goal (1 subgoal):
1. a mod (b * c) = a - m1 * (b * c)
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
a mod (b * c) = a - m1 * (b * c)
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
a mod (b * c) = a - m1 * (b * c)
[PROOF STEP]
have "\<exists>m.( ?x = m*c + ?z)"
[PROOF STATE]
proof (prove)
using this:
a mod (b * c) = a - m1 * (b * c)
goal (1 subgoal):
1. \<exists>m. a mod (b * c) = m * c + a mod (b * c) mod c
[PROOF STEP]
using mod_div_decomp
[PROOF STATE]
proof (prove)
using this:
a mod (b * c) = a - m1 * (b * c)
(\<And>q r. \<lbrakk>q = ?a div ?b; r = ?a mod ?b; ?a = q * ?b + r\<rbrakk> \<Longrightarrow> ?thesis) \<Longrightarrow> ?thesis
goal (1 subgoal):
1. \<exists>m. a mod (b * c) = m * c + a mod (b * c) mod c
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
\<exists>m. a mod (b * c) = m * c + a mod (b * c) mod c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<exists>m. a mod (b * c) = m * c + a mod (b * c) mod c
[PROOF STEP]
obtain m where "( ?x = m*c + ?z)"
[PROOF STATE]
proof (prove)
using this:
\<exists>m. a mod (b * c) = m * c + a mod (b * c) mod c
goal (1 subgoal):
1. (\<And>m. a mod (b * c) = m * c + a mod (b * c) mod c \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
a mod (b * c) = m * c + a mod (b * c) mod c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
a mod (b * c) = m * c + a mod (b * c) mod c
[PROOF STEP]
have "(a - m1*(b*c)) = m*c + ?z"
[PROOF STATE]
proof (prove)
using this:
a mod (b * c) = m * c + a mod (b * c) mod c
goal (1 subgoal):
1. a - m1 * (b * c) = m * c + a mod (b * c) mod c
[PROOF STEP]
using \<open>a mod (b * c) = a - m1 * (b * c)\<close>
[PROOF STATE]
proof (prove)
using this:
a mod (b * c) = m * c + a mod (b * c) mod c
a mod (b * c) = a - m1 * (b * c)
goal (1 subgoal):
1. a - m1 * (b * c) = m * c + a mod (b * c) mod c
[PROOF STEP]
by (metis)
[PROOF STATE]
proof (state)
this:
a - m1 * (b * c) = m * c + a mod (b * c) mod c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
a - m1 * (b * c) = m * c + a mod (b * c) mod c
[PROOF STEP]
have "a = m1*b*c + m*c + ?z"
[PROOF STATE]
proof (prove)
using this:
a - m1 * (b * c) = m * c + a mod (b * c) mod c
goal (1 subgoal):
1. a = m1 * b * c + m * c + a mod (b * c) mod c
[PROOF STEP]
using \<open>a = m1 * (b * c) + a mod (b * c)\<close> \<open>a mod (b * c)
= m * c + a mod (b * c) mod c\<close>
[PROOF STATE]
proof (prove)
using this:
a - m1 * (b * c) = m * c + a mod (b * c) mod c
a = m1 * (b * c) + a mod (b * c)
a mod (b * c) = m * c + a mod (b * c) mod c
goal (1 subgoal):
1. a = m1 * b * c + m * c + a mod (b * c) mod c
[PROOF STEP]
by (metis ab_semigroup_add_class.add_ac(1)
ab_semigroup_mult_class.mult_ac(1))
[PROOF STATE]
proof (state)
this:
a = m1 * b * c + m * c + a mod (b * c) mod c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
a = m1 * b * c + m * c + a mod (b * c) mod c
[PROOF STEP]
have 1:"a = (m1*b + m)*c + ?z"
[PROOF STATE]
proof (prove)
using this:
a = m1 * b * c + m * c + a mod (b * c) mod c
goal (1 subgoal):
1. a = (m1 * b + m) * c + a mod (b * c) mod c
[PROOF STEP]
by (metis add_mult_distrib2 mult.commute)
[PROOF STATE]
proof (state)
this:
a = (m1 * b + m) * c + a mod (b * c) mod c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
let ?y = "(a mod c)"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
have "\<exists>n. a = n*(c) + ?y"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<exists>n. a = n * c + a mod c
[PROOF STEP]
by (metis "1" \<open>a mod (b * c) = m * c + a mod (b * c) mod c\<close> mod_mult_self3)
[PROOF STATE]
proof (state)
this:
\<exists>n. a = n * c + a mod c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<exists>n. a = n * c + a mod c
[PROOF STEP]
obtain n where "a = n*(c) + ?y"
[PROOF STATE]
proof (prove)
using this:
\<exists>n. a = n * c + a mod c
goal (1 subgoal):
1. (\<And>n. a = n * c + a mod c \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
a = n * c + a mod c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
with 1
[PROOF STATE]
proof (chain)
picking this:
a = (m1 * b + m) * c + a mod (b * c) mod c
a = n * c + a mod c
[PROOF STEP]
have "(m1*b + m)*c + ?z = n*c + ?y"
[PROOF STATE]
proof (prove)
using this:
a = (m1 * b + m) * c + a mod (b * c) mod c
a = n * c + a mod c
goal (1 subgoal):
1. (m1 * b + m) * c + a mod (b * c) mod c = n * c + a mod c
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
(m1 * b + m) * c + a mod (b * c) mod c = n * c + a mod c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
(m1 * b + m) * c + a mod (b * c) mod c = n * c + a mod c
[PROOF STEP]
have "(m1*b + m)*c - (n*c) = ?y - ?z"
[PROOF STATE]
proof (prove)
using this:
(m1 * b + m) * c + a mod (b * c) mod c = n * c + a mod c
goal (1 subgoal):
1. (m1 * b + m) * c - n * c = a mod c - a mod (b * c) mod c
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
(m1 * b + m) * c - n * c = a mod c - a mod (b * c) mod c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
(m1 * b + m) * c - n * c = a mod c - a mod (b * c) mod c
[PROOF STEP]
have "(m1*b + m - n)*c = (?y - ?z)"
[PROOF STATE]
proof (prove)
using this:
(m1 * b + m) * c - n * c = a mod c - a mod (b * c) mod c
goal (1 subgoal):
1. (m1 * b + m - n) * c = a mod c - a mod (b * c) mod c
[PROOF STEP]
by (metis diff_mult_distrib2 mult.commute)
[PROOF STATE]
proof (state)
this:
(m1 * b + m - n) * c = a mod c - a mod (b * c) mod c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
(m1 * b + m - n) * c = a mod c - a mod (b * c) mod c
[PROOF STEP]
have "c dvd (?y - ?z)"
[PROOF STATE]
proof (prove)
using this:
(m1 * b + m - n) * c = a mod c - a mod (b * c) mod c
goal (1 subgoal):
1. c dvd a mod c - a mod (b * c) mod c
[PROOF STEP]
by (metis dvd_triv_right)
[PROOF STATE]
proof (state)
this:
c dvd a mod c - a mod (b * c) mod c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
c dvd a mod c - a mod (b * c) mod c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
have "?y < c"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. a mod c < c
[PROOF STEP]
using mod_less_divisor False
[PROOF STATE]
proof (prove)
using this:
0 < ?n \<Longrightarrow> ?m mod ?n < ?n
c \<noteq> 0
goal (1 subgoal):
1. a mod c < c
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
a mod c < c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
a mod c < c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
have "?z < c"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. a mod (b * c) mod c < c
[PROOF STEP]
using mod_less_divisor False
[PROOF STATE]
proof (prove)
using this:
0 < ?n \<Longrightarrow> ?m mod ?n < ?n
c \<noteq> 0
goal (1 subgoal):
1. a mod (b * c) mod c < c
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
a mod (b * c) mod c < c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
a mod (b * c) mod c < c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
have "?y - ?z < c"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. a mod c - a mod (b * c) mod c < c
[PROOF STEP]
using calculation(2) less_imp_diff_less
[PROOF STATE]
proof (prove)
using this:
a mod c < c
?j < ?k \<Longrightarrow> ?j - ?n < ?k
goal (1 subgoal):
1. a mod c - a mod (b * c) mod c < c
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
a mod c - a mod (b * c) mod c < c
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
c dvd a mod c - a mod (b * c) mod c
a mod c < c
a mod (b * c) mod c < c
a mod c - a mod (b * c) mod c < c
[PROOF STEP]
have "?y - ?z = 0"
[PROOF STATE]
proof (prove)
using this:
c dvd a mod c - a mod (b * c) mod c
a mod c < c
a mod (b * c) mod c < c
a mod c - a mod (b * c) mod c < c
goal (1 subgoal):
1. a mod c - a mod (b * c) mod c = 0
[PROOF STEP]
by (metis dvd_imp_mod_0 mod_less)
[PROOF STATE]
proof (state)
this:
a mod c - a mod (b * c) mod c = 0
goal (1 subgoal):
1. c \<noteq> 0 \<Longrightarrow> a mod (b * c) mod c = a mod c
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
a mod c - a mod (b * c) mod c = 0
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
a mod c - a mod (b * c) mod c = 0
goal (1 subgoal):
1. a mod (b * c) mod c = a mod c
[PROOF STEP]
using False
[PROOF STATE]
proof (prove)
using this:
a mod c - a mod (b * c) mod c = 0
c \<noteq> 0
goal (1 subgoal):
1. a mod (b * c) mod c = a mod c
[PROOF STEP]
by (metis "1" mod_add_right_eq mod_mult_self2 add.commute mult.commute)
[PROOF STATE]
proof (state)
this:
a mod (b * c) mod c = a mod c
goal:
No subgoals!
[PROOF STEP]
qed
|
```python
import holoviews as hv
hv.extension('bokeh')
hv.opts.defaults(hv.opts.Curve(width=500),
hv.opts.Image(width=500, colorbar=True, cmap='Viridis'))
```
```python
import numpy as np
import scipy.signal
import scipy.fft
from IPython.display import Audio
```
# Sistemas para el procesamiento de seΓ±ales
## IntroducciΓ³n
### DefiniciΓ³n de sistema
Hasta ahora hemos realizado *anΓ‘lisis de seΓ±ales*, es decir el estudio de las seΓ±ales y sus propiedades en el dominio del tiempo y frecuencia
En esta unidad nos enfocaremos en el *procesamiento de seΓ±ales*, es decir el diseΓ±o de **sistemas** que procesan una **seΓ±al de entrada** y producen una **seΓ±al de salida**
Usaremos
- $x[n]$ para denotar la seΓ±al (discreta) de entrada y $X[k]$ su espectro
- $y[n]$ para denotar la seΓ±al (discreta) de salida e $Y[k]$ su espectro
### Ejemplos de sistemas
Utilizando sistemas podemos modificar una seΓ±al para mejorar su calidad o remover efectos indeseados
- Un sistema para reducir el ruido de una seΓ±al de electroencefalograma (EEG)
- Un sistema para mejorar una imagen fuera de foco (sharpening)
- Un sistema para eliminar el eco de un audio
## Propiedades y ejemplos de sistemas
### Sistemas sin memoria
Diremos que un sistema $\Phi$ es un sistema **sin memoria** si
$$
y[n] = \Phi(x[n]),
$$
es decir que la salida del sistema en un instante $n$ dado depende solo de la entrada en ese mismo instante
Veamos algunos ejemplos
**Sistema atenuador/amplificador ideal**
$$
y[n] = A x[n],
$$
donde $A>0$ se llama *ganancia*
Este sistema puede atenuar la entrada si $0<A<1$ y amplificar si $A>1$
**Sistema saturador (clamp)**
$$
y[n] = \begin{cases} B &x[n] > B \\x[n] & x[n] \in [-B, B]\\ -B & x[n] < -B\end{cases}
$$
Este sistema limita los valores de la seΓ±al de entrada en un rango fijo
**Sistema rectificador**
$$
y[n] = | x[n] |
$$
Este sistema eliminar la parte negativa de la seΓ±al de entrada
### Sistema Lineal
Diremos que un sistema $\Phi$ es lineal si cumple con las siguientes propiedades
**Homogeneidad**
Un cambio en la amplitud de la entrada produce un cambio equivalente en la salida
$$
\Phi(cx[n]) = c \Phi(x[n]) = c y[n]
$$
**Aditividad**
SeΓ±ales que se suman en la entrada producen seΓ±ales que se suman en la salida
$$
\Phi(x_1[n] + x_2[n]) = \Phi(x_1[n]) + \Phi(x_2[n]) = y_1[n] + y_2[n]
$$
Es decir que las seΓ±ales pasan por el sistema sin interactuar entre ellas
**Otras propiedades de los sistemas lineales**
Producto de las propiedades anteriores se tiene que una cascada de sistemas lineales forma un sistema lineal equivalente y ademΓ‘s la cascada de sistemas es **conmutativa**, es decir que el orden de los sistemas en la cascada no altera el resultado final
La siguiente figura ejemplifica esta propiedad
Otra propiedad interesante de los sistemas lineales es que cumplen el **Principio de superposiciΓ³n:**
1. Si descomponemos una seΓ±al en $M$ componentes: $x[n] = x_1[n] + x_2[n] + \ldots + x_M[n]$
1. Y aplicamos un **sistema lineal** a cada componente: $y_j[n] = \Phi(x_j[n])$
1. Podemos recuperar la salida total usando **aditividad**: $y_1[n] + y_2[n] + \ldots + y_M[n] = y[n]$
La siguiente figura ejemplifica esta propiedad
### Sistemas con memoria
Un sistema $\Phi$ es un sistema con memoria si su salida actual depende sΓ³lo de la entrada actual, las entradas anteriores o las salidas anteriores
$$
\begin{align}
y[n] = \Phi(x[n], & x[n-1], x[n-2], \ldots, x[0], \\ \nonumber
& y[n-1], y[n-2], \ldots, y[0]) \nonumber
\end{align}
$$
esto tambiΓ©n se conoce como **sistema causal**
Un **sistema con memoria no-causal** usa entradas futuras (es decir $x[n+1]$, $x[n+2]$, ...) y por ende solo se puede implementar de forma offline, es decir una vez que sea ha observado toda la seΓ±al
A continuaciΓ³n veremos algunos ejemplos de sistemas con memoria causales
**Sistema con un retardo (delay)**
Definido como
$$
y[n] = x[n-m],
$$
donde
- la salida depende solo de "una" entrada anterior
- el valor de m define que tan "antigua" es la entrada pasada
El *delay* o retarno no afecta la amplitud de los componentes frecuenciales de la seΓ±al pero si su fase, como muestra la siguiente figura
```python
n = np.arange(0, 200, step=1)
x = lambda m: np.sin(2.0*np.pi*0.05*(n-m))
f = scipy.fft.rfftfreq(d=1, n=len(n))
p = []
for m in [0, 4, 8]:
x_delayed = x(m)
p.append(hv.Curve((n, x_delayed), 'Tiempo [s]', 'SeΓ±al'))
X = scipy.fft.rfft(x_delayed)
Xm = np.absolute(X)
p.append(hv.Curve((f, Xm), 'Frecuencia [Hz]', 'Espectro de amplitud'))
Xp = np.angle(X)
p.append(hv.Curve((f, Xm*Xp/np.amax(Xm)), 'Frecuencia [Hz]', 'Espectro de fase'))
```
```python
hv.Layout(p).cols(3).opts(hv.opts.Curve(width=250, height=200))
```
**Sistema reverberador o eco**
Definido como
$$
y[n] = x[n] + A x[n-m],
$$
donde
- la salida depende de una entrada "pasada" y la entrada actual
- la ganancia controla si el "eco" se atenua o amplifica
Al contrario del sistema anterior, el eco si puede modificar el espectro de amplitud.
Notemos el efecto de interferencia constructiva y destructiva al modificar el retardo, como muestra la siguiente animaciΓ³n
```python
n = np.arange(0, 200, step=1)
x = lambda m, A=1: A*np.sin(2.0*np.pi*0.05*(n-m))
f = scipy.fft.rfftfreq(d=1, n=len(n))
buffer = {}
for m in range(0, 40, 2):
xm = x(m)
buffer[m] = (xm, np.abs(scipy.fft.rfft(x(0) + xm)))
```
```python
hMap1 = hv.HoloMap(kdims='m')
hMap2 = hv.HoloMap(kdims='m')
hMap3 = hv.HoloMap(kdims='m')
for m, (xm, X) in buffer.items():
hMap1[m] = hv.Curve((n, xm), 'Tiempo', 'x', label='Ax[n-m]')
hMap2[m] = hv.Curve((n, x(0) + xm), 'Tiempo', 'y')
hMap3[m] = hv.Curve((f, X), 'Frecuencia', 'Espectro')
p_clean = hv.Curve((n, x(0)), 'Tiempo', 'x', label='x[n]').opts(width=500, height=200)
plot = (p_clean * hMap1 + hMap2 + hMap3).cols(1).opts(hv.opts.Curve(height=200),
hv.opts.Overlay(legend_position='top_right'))
hv.output(plot, holomap='gif', fps=5)
```
El siguiente video muestra un experimento que ejemplifica la interferencia destructiva en una onda mecΓ‘nica: https://www.youtube.com/watch?v=IU8xeJlJ0mk
**Sistemas con mΓΊltiples ecos**
Pueden combinarse mΓ‘s retardos para hacer un sistema reverberante mΓ‘s complejo
Por ejemplo el siguiente sistema
$$
y[n] = x[n] + A_1 x[n-m_1] + A_2 x[n-m_2] + A_3 x[n-m_3] + \ldots,
$$
que lo implementamos como
```python
Fs = 44100;
n = np.arange(0, 4, step=1.0/Fs)
x = lambda m: np.sin(2.0*np.pi*880*(n-m))*np.exp(-(n-m)**2/0.5**2)*np.heaviside(n-m, 0)
y = x(0) + 0.5*x(1.) + 0.25*x(2.) + 0.125*x(3.)
```
Da como resultado grΓ‘fico lo siguiente:
```python
hv.Curve((n, y), 'Tiempo [s]', 'SeΓ±al con eco')
```
y el resultado sonoro es:
```python
Audio(y, rate=Fs, normalize=False)
```
## Sistema de respuesta finita al impulso (FIR)
Generalizando el ejemplo de sistema lineal reverberante a $L$ retardos llegamos a
$$
\begin{align}
y[n] &= h[0] x[n] + h[1] x[n-1] + h[2] x[n-2] + \ldots + h[L] x[n-L] \nonumber \\
&= \sum_{j=0}^{L} h[j] x[n-j] \nonumber \\
&= (h* x)[n] \nonumber
\end{align}
$$
que se puede modelar como una convoluciΓ³n discreta entre $h$ y $x$
Este sistema se conoce como
- Sistema FIR (finite impulse response)
- Sistema MA (moving average)
- Sistema todo-zeros
y es de orden L (posee L+1 coeficientes)
**IntepretaciΓ³n como media movil (MA)**
El sistema FIR es equivalente a una media movil ponderada que se aplica sobre la entrada, donde los coeficientes del sistema son los ponderadores
Por ejemplo sea un sistema de 3 coeficientes $h[0]=a$, $h[1]=b$ y $h[2]=c$
$$
\begin{align}
y[n] = (h*x)[n] &= \sum_{j=0}^{2} h[j] x[n-j] \nonumber \\
&= a x[n] + b x[n-1] + c x[n-2] \nonumber
\end{align}
$$
donde cada salida se calcula a partir de
$$
\overbrace{x[0], x[1], x[2]}^{y[2]} , x[3], x[4], \ldots
$$
$$
x[0], \overbrace{x[1], x[2] , x[3]}^{y[3]}, x[4], \ldots
$$
$$
x[0], x[1], \overbrace{x[2] , x[3], x[4]}^{y[4]}, \ldots
$$
Un detalle es que para obtener el valor de $y[0]$ e $y[1]$ se deben establecer "condiciones de borde", como por ejemplo $x[-2] = x[-1]= 0$
A continuaciΓ³n veremos algunos ejemplos de aplicaciones usando filtros FIR sencillos
### Eliminando ruido blanco aditivo
En ciertos problemas la seΓ±al que observamos $x[n]$ no es exactamente la seΓ±al que deseamos $s[n]$, sino una versiΓ³n corrupta de la misma.
Un ejemplo muy tΓpico es cuando la seΓ±al que deseamos estudiar debe ser transmitida desde su lugar de origen hasta nosotros. El canal suele agregar ruido a la seΓ±al y adicionalmente el ruido aumenta mientras mΓ‘s largo sea el recorrido de nuestra seΓ±al.
Un tipo particular de corrupciΓ³n es el siguiente
$$
x[n] = s[n] + \epsilon[n], \quad \epsilon[n] \sim \mathcal{N}(0,\sigma^2)
$$
es decir una corrupciΓ³n con ruido blanco aditivo y gaussiano, muy comΓΊn en las transmisiones satelitales y espaciales
Consideremos a modo de ejemplo la siguiente seΓ±al observada que fue contaminada por ruido blanco aditivo:
```python
np.random.seed(0)
n = np.arange(0, 200, step=1)
C = 5*np.exp(-0.5*(n[:, np.newaxis] - n[:, np.newaxis].T)**2/10**2)
# SeΓ±al limpia (lo que no conocemos)
s = np.random.multivariate_normal(np.zeros_like(n), C)/8
# Datos: SeΓ±al + ruido (lo que medimos)
x = s + np.random.randn(len(n))/4
p2 = hv.Curve((n, s), 'Tiempo', 'SeΓ±al', label='Deseada (s)').opts(color='k')
p1 = hv.Scatter((n, x), 'Tiempo', 'SeΓ±al', label='Observada (x)').opts(width=500, height=250)
hv.Overlay([p1, p2]).opts(legend_position='top')
```
Podemos usar un sistema FIR de tipo promediador para "suavizar la contaminaciΓ³n" e intentar recuperar la seΓ±al deseada
Sea un sistema FIR con $L$ coeficientes idΓ©nticos e iguales a $1/L$
```python
L = 10
h = np.ones(shape=(L,))/L
y = scipy.signal.convolve(x, h, mode='same', method='auto')
```
La siguiente grΓ‘fica interactiva muestra el resultado de convolucionar este sistema con los datos contaminados
```python
hMap1 = hv.HoloMap(kdims='Instante')
hMap2 = hv.HoloMap(kdims='Instante')
for m in range(0, len(n)-L, 5):
c = np.zeros_like(n, dtype=np.float64);
c[m:m+L] = h
hMap1[m] = hv.Curve((n, c), 'Tiempo', 'Entrada', label='h').opts(color='r')
hMap2[m] = hv.Curve((n[:m], y[:m]), 'Tiempo', 'Salida', label='y')
p_obs = hv.Scatter((n, x), 'Tiempo', 'Entrada', label='x')
p_clean = hv.Curve((n, s), 'Tiempo', 'Salida', label='s').opts(color='k', height=200)
(hMap1 * p_obs + hMap2 * p_clean).cols(1).opts(hv.opts.Curve(height=200),
hv.opts.Overlay(legend_position='top_left'))
```
:::{note}
Este filtro promedia los datos vecinos resultando una versiΓ³n suavizada de los mismos. Esta versiΓ³n suavizada se aproxima a la "seΓ±al limpia" que estΓ‘ escondida en el ruido.
:::
En general, mientras mΓ‘s "largo" sea el filtro mayor serΓ‘ el efecto de suavizado
### Encontrando cambios en una seΓ±al
Sea la siguiente seΓ±al escalonada
```python
n = np.arange(0, 100, step=1)
x = np.zeros_like(n, dtype=np.float64)
x[20:] += 1.
x[40:] += 1.
x[80:] -= 1.
hv.Curve((n, x), 'Tiempo', 'x').opts(width=500, height=200)
```
Si nos interesa encontrar cambios en la seΓ±al podemos usar un sistema de tipo diferenciador
$$
y[n] = (h * x)[n] = \frac{1}{2}x[n] - \frac{1}{2} x[n-1]
$$
```python
h = np.array([0.5, -0.5])
y = scipy.signal.convolve(x, h, mode='same', method='auto')
```
La siguiente grΓ‘fica interactiva muestra el resultado de convolucionar este sistema con la seΓ±al escalonada
```python
hMap1 = hv.HoloMap(kdims='Instante')
hMap2 = hv.HoloMap(kdims='Instante')
for m in range(0, len(n)-len(h), 5):
c = np.zeros_like(n, dtype=np.float64);
c[m:m+len(h)] = h
hMap1[m] = hv.Curve((n, c), 'Tiempo', label='h')
hMap2[m] = hv.Curve((n[:m+1], y[:m+1]), 'Tiempo', 'Salida')
p_obs = hv.Curve((n, x), 'Tiempo', 'Entrada', label='x')
(p_obs * hMap1 + hMap2).cols(1).opts(hv.opts.Curve(height=200),
hv.opts.Overlay(legend_position='top_left'))
```
:::{note}
Los pulsos en la convoluciΓ³n (salida) estΓ‘n asociados a un cambio (ascenso o descenso) en la seΓ±al original
:::
En un caso mΓ‘s general, este filtro nos da informaciΓ³n de la derivada de la seΓ±al, es decir de su velocidad o tasa de cambio
### Remover una tendencia
En ciertas situaciones la seΓ±al que nos interesa (seΓ±al deseada) puede aparecer combinada con otras seΓ±ales (interferencia)
Considere el siguiente ejemplo:
```python
np.random.seed(0);
n = np.arange(0, 150, step=1)
C = np.exp(-0.5*(n[:, np.newaxis] - n[:, np.newaxis].T)**2/30**2)
x_tendencia = 3*np.random.multivariate_normal(np.zeros_like(n), C)+2.5
x_deseada = np.sin(2.0*np.pi*0.1*n)
x = x_deseada + x_tendencia
p3=hv.Curve((n, x_deseada), 'Tiempo', 'SeΓ±al', label='Deseada (s)').opts(color='k', alpha=0.75)
p2=hv.Curve((n, x_tendencia), 'Tiempo', 'SeΓ±al', label='Tendencia').opts(alpha=0.75)
p1=hv.Curve((n, x), 'Tiempo', 'SeΓ±al', label='Observada (x)').opts(height=250)
hv.Overlay([p1,p2,p3]).opts(legend_position='bottom_right')
```
Supongamos que nuestro sensor retorna la seΓ±al observada (azul) pero que lo que en realidad necesitamos es la seΓ±al deseada (negra)
El filtro que se muestra a continuaciΓ³n es capaz de separar la seΓ±al deseada (negro) de la tendencia (rojo) a partir de la seΓ±al observada (azul). En prΓ³ximas lecciones veremos como diseΓ±ar este tipo de filtros
```python
h = np.array([ 0.00099858, 0.00172998, 0.00288273, 0.00437671, 0.00567733, 0.00580422,
0.00350188, -0.00245489, -0.01289227, -0.02790429, -0.04665419, -0.06738128,
-0.08763411, -0.10469179, -0.11608356, 0.88063544, -0.11608356, -0.10469179,
-0.08763411, -0.06738128, -0.04665419, -0.02790429, -0.01289227, -0.00245489,
0.00350188, 0.00580422, 0.00567733, 0.00437671, 0.00288273, 0.00172998,
0.00099858])
hv.Curve((h), 'Tiempo', 'Filtro (h)').opts(height=200)
```
```python
y = scipy.signal.convolve(x, h, mode='same', method='auto')
```
```python
hMap1 = hv.HoloMap(kdims='Instante')
hMap2 = hv.HoloMap(kdims='Instante')
for m in range(0, len(n)-len(h), 5):
c = np.zeros_like(n, dtype=np.float64);
c[m:m+len(h)] = h
hMap1[m] = hv.Curve((n, c), 'Tiempo', 'Entrada', label='h')
hMap2[m] = hv.Curve((n[:m], y[:m]), 'Tiempo', 'Salida', label='y').opts(ylim=(-1.2, 1.2))
p_obs = hv.Curve((n, x), 'Tiempo', 'SeΓ±al', label='x')
p_target = hv.Curve((n, x_deseada), 'Tiempo', 'SeΓ±al', label='s').opts(color='k', alpha=.75, width=4)
(p_obs * hMap1 + hMap2 *p_target).cols(1).opts(hv.opts.Curve(height=200))
```
## ConvoluciΓ³n con scipy
Podemos convolucionar una seΓ±al en Python usando
```python
scipy.signal.convolve(in1, # SeΓ±al de entrada
in2, # Coeficientes del sistema
mode='full',
method='auto'
)
```
donde el argumento `method` puede ser
- `direct`: Realiza la convoluciΓ³n en el dominio del tiempo
- `fft`: Realiza la convoluciΓ³n multiplicando los espectros
- `auto`: Se decide automaticamente en base al largo de las seΓ±ales
y el argumento `mode` indica donde se hace la convoluciΓ³n
Para ejemplificar la influencia de este argumento consideremos una seΓ±al $x=[a,b,c]$ y un sistema $h=[d, e]$
- Si uso `mode=valid` el resultado serΓ‘ $y=[ad+be, bd+ce]$
- Si uso `mode=same` el resultado serΓ‘ $y=[ae, ad+be, bd+ce]$, es decir se agregan ceros al principio de $x$ tal que $y$ sea del mismo largo que $x$
- Si uso `mode=full` el resultado serΓ‘ $y=[ae, ad+be, bd+ce, cd]$, es decir se agregan ceros al principio y al final de $x$
### Eliminando ruido versiΓ³n 2.0
Considerando la misma seΓ±al contaminada con ruido blanco que vimos anteriormente utilizaremos `scipy.signal.convolve` para convolucionar con un filtro que suavice el ruido.
Probaremos dos sistemas FIR
- coeficientes idΓ©nticos e iguales a $1/L$, es decir una ventana rectangular
- coeficientes que decaen suavemente a cero, como por ejemplo una ventana de Hamming
con distintos valores de $L$ (largo del filtro)
En este caso los valores los obtenemos usando la funciΓ³n de scipy
```python
scipy.signal.get_window(window, # String con el nombre de la ventana
Nx, # Entero con el largo de la ventana
...)
```
La ventana rectangular se llama `boxcar` mientras que la de Hamming se llama `hamming`. En la documentaciΓ³n de la funciΓ³n se puede revisar otras ventanas disponibles
```python
# La seΓ±al de ejemplo de la secciΓ³n 7.3.1
np.random.seed(0)
n = np.arange(0, 200, step=1)
C = 5*np.exp(-0.5*(n[:, np.newaxis] - n[:, np.newaxis].T)**2/10**2)
s = np.random.multivariate_normal(np.zeros_like(n), C)/8
x = s + np.random.randn(len(n))/4
# La filtramos con distintas funciones y L para luego visualizar el resultado
filters = {}
results = {}
for L in [5, 10, 20, 30, 40]:
for filter_name in ['boxcar', 'hamming']:
h = scipy.signal.get_window(filter_name, L)
h = h/np.sum(h)
if not L in filters:
filters[L] = {}
results[L] = {}
filters[L][filter_name] = h
results[L][filter_name] = scipy.signal.convolve(x, h, mode='same', method='auto')
```
```python
hMap1 = hv.HoloMap(kdims='L')
hMap2 = hv.HoloMap(kdims='L')
for L, curves in filters.items():
p = []
for filter_name, h in curves.items():
p.append(hv.Curve((range(L), h), 'Largo del filtro (L)', 'Filtro (h)', label=filter_name))
hMap1[L] = hv.Overlay(p)
for L, curves in results.items():
p = []
for filter_name, y in curves.items():
p.append(hv.Curve((n, y), 'Tiempo', 'SeΓ±al', label=filter_name).opts(line_width=2, alpha=0.75))
hMap2[L] = hv.Overlay(p)
p_clean = hv.Curve((n, s), 'Tiempo', 'SeΓ±al', label='Deseada (s)').opts(color='k')
p_data = hv.Scatter((n, x), 'Tiempo', 'Datos (x)').opts(width=500, height=200)
(p_data + hMap1 + hMap2 * p_clean).cols(1).opts(hv.opts.Curve(height=250),
hv.opts.Overlay(legend_position='top'))
```
:::{note}
Mientras mΓ‘s larga es la ventana (L) mayor es el suavizado. Adicionalmente la ventana de Hamming produce un filtrado mΓ‘s suave que la rectangular
:::
En la lecciΓ³n siguiente veremos como diseΓ±ar un filtro, es decir como calcular los valores de `h` para resolver una tarea en particular
```python
```
|
= = = = 2005 = = = =
|
import tactic.linarith
import category_theory.shift
import algebra.homology.homological_complex
import algebra.homology.homotopy_category
import for_mathlib.category_theory.quotient_shift
import for_mathlib.algebra.homology.hom_complex
import for_mathlib.category_theory.shift_misc
noncomputable theory
open category_theory category_theory.category category_theory.limits
variables (C : Type*) [category C] [preadditive C]
namespace cochain_complex
open homological_complex
local attribute [simp] X_iso_of_eq_hom_naturality X_iso_of_eq_inv_naturality
@[simps obj_d map_f]
def shift_functor (n : β€) : cochain_complex C β€ β₯€ cochain_complex C β€ :=
{ obj := Ξ» K,
{ X := Ξ» i, K.X (i+n),
d := Ξ» i j, cochain_complex.hom_complex.Ξ΅ n β’ K.d _ _,
shape' := Ξ» i j hij, begin
rw [K.shape, smul_zero],
intro hij',
apply hij,
dsimp [complex_shape.up] at hij' β’,
linarith,
end, },
map := Ξ» Kβ Kβ Ο,
{ f := Ξ» i, Ο.f _, }, }
variable {C}
@[simp]
lemma X_iso_of_eq_of_shift_functor (K : cochain_complex C β€) (n : β€) {i i' : β€} (h : i = i') :
((shift_functor C n).obj K).X_iso_of_eq h = K.X_iso_of_eq (by subst h) := rfl
@[simp]
def shift_functor_obj_X_iso (K : cochain_complex C β€) (n i m : β€) (hm : m = i + n) :
((shift_functor C n).obj K).X i β
K.X m :=
X_iso_of_eq K hm.symm
variable (C)
@[simp]
def shift_functor_congr {n n' : β€} (h : n = n') :
shift_functor C n β
shift_functor C n' :=
nat_iso.of_components
(Ξ» K, hom.iso_of_components (Ξ» i, K.X_iso_of_eq (by subst h))
(Ξ» i j hij, by { dsimp, simp [h], })) (Ξ» Kβ Kβ Ο, by { ext, dsimp, simp, })
@[simps]
def shift_functor_zero' (n : β€) (h : n = 0) :
shift_functor C n β
π _ :=
nat_iso.of_components (Ξ» K, hom.iso_of_components
(Ξ» i, K.shift_functor_obj_X_iso _ _ _ (by linarith))
(by { subst h, tidy, })) (by tidy)
@[simps]
def shift_functor_add' (nβ nβ nββ : β€) (h : nββ = nβ + nβ) :
shift_functor C nβ β shift_functor C nβ β
shift_functor C nββ :=
nat_iso.of_components
(Ξ» K, hom.iso_of_components (Ξ» i, K.X_iso_of_eq (by linarith))
(Ξ» i j hij, begin
subst h,
dsimp,
simp only [linear.comp_smul, X_iso_of_eq_hom_comp_d, linear.smul_comp,
d_comp_X_iso_of_eq_hom, β mul_smul, β cochain_complex.hom_complex.Ξ΅_add, add_comm nβ],
end)) (by tidy)
instance : has_shift (cochain_complex C β€) β€ :=
has_shift_mk _ _
{ F := shift_functor C,
Ξ΅ := (shift_functor_zero' C _ rfl).symm,
ΞΌ := Ξ» nβ nβ, shift_functor_add' C nβ nβ _ rfl,
associativity := Ξ» nβ nβ nβ K, by { ext i, dsimp [X_iso_of_eq], simp, }, }
variable {C}
@[simp]
lemma shift_functor_map_f' {K L : cochain_complex C β€} (Ο : K βΆ L) (n p : β€) :
((category_theory.shift_functor (cochain_complex C β€) n).map Ο).f p = Ο.f (p+n) := rfl
@[simp]
lemma shift_functor_obj_d' (K : cochain_complex C β€) (n i j : β€) :
((category_theory.shift_functor (cochain_complex C β€) n).obj K).d i j =
cochain_complex.hom_complex.Ξ΅ n β’ K.d _ _ := rfl
lemma shift_functor_add_inv_app_f (K : cochain_complex C β€) (a b n : β€) :
((shift_functor_add (cochain_complex C β€) a b).inv.app K : _ βΆ _).f n =
(K.X_iso_of_eq (by { dsimp, rw [add_comm a, add_assoc],})).hom := rfl
lemma shift_functor_add_hom_app_f (K : cochain_complex C β€) (a b n : β€) :
((shift_functor_add (cochain_complex C β€) a b).hom.app K : _ βΆ _).f n =
(K.X_iso_of_eq (by { dsimp, rw [add_comm a, add_assoc],})).inv :=
begin
haveI : is_iso (((shift_functor_add (cochain_complex C β€) a b).inv.app K : _ βΆ _).f n),
{ rw shift_functor_add_inv_app_f,
apply_instance, },
rw [β cancel_mono (((shift_functor_add (cochain_complex C β€) a b).inv.app K : _ βΆ _).f n),
β homological_complex.comp_f, iso.hom_inv_id_app, homological_complex.id_f,
shift_functor_add_inv_app_f, iso.inv_hom_id],
end
lemma shift_functor_add_comm_hom_app_f (K : cochain_complex C β€) (a b n : β€) :
((shift_functor_add_comm (cochain_complex C β€) a b).hom.app K : _ βΆ _).f n =
(K.X_iso_of_eq (by { dsimp, simp only [add_assoc, add_comm a], })).hom :=
begin
dsimp only [shift_functor_add_comm, iso.trans, iso.symm],
simpa only [nat_trans.comp_app, homological_complex.comp_f,
shift_functor_add_hom_app_f, shift_functor_add_inv_app_f,
homological_complex.X_iso_of_eq, eq_to_iso.inv, eq_to_iso.hom, eq_to_hom_app,
homological_complex.eq_to_hom_f, eq_to_hom_trans],
end
variable (C)
lemma shift_functor_add'_eq (a b c : β€) (h : c = a + b) :
category_theory.shift_functor_add' (cochain_complex C β€) a b c h =
(shift_functor_add' C a b c h).symm :=
begin
subst h,
dsimp only [category_theory.shift_functor_add'],
ext K n,
dsimp only [iso.trans, shift_functor_add', nat_iso.of_components,
nat_trans.comp_app, homological_complex.comp_f, hom.iso_of_components],
simp only [eq_to_hom_app, eq_to_hom_f, shift_functor_add_hom_app_f,
X_iso_of_eq, eq_to_iso, eq_to_hom_trans, eq_to_hom_refl, nat_trans.id_app,
homological_complex.id_f, id_comp],
end
lemma shift_functor_add_eq (a b : β€) :
category_theory.shift_functor_add (cochain_complex C β€) a b =
(shift_functor_add' C a b _ rfl).symm :=
begin
ext1,
rw β shift_functor_add'_eq,
dsimp [category_theory.shift_functor_add'],
rw id_comp,
end
lemma shift_functor_zero_eq :
(category_theory.shift_functor_zero (cochain_complex C β€) β€) =
(shift_functor_zero' C 0 rfl) :=
begin
change (category_theory.shift_functor_zero (cochain_complex C β€) β€).symm.symm =
(shift_functor_zero' C 0 rfl).symm.symm,
congr' 1,
ext1,
refl,
end
variables {C} {D : Type*} [category D] (F : C β₯€ D) [preadditive D] [functor.additive F]
def map_cochain_complex_shift_iso (n : β€) :
shift_functor C n β F.map_homological_complex (complex_shape.up β€) β
F.map_homological_complex (complex_shape.up β€) β shift_functor D n :=
nat_iso.of_components (Ξ» K, hom.iso_of_components (Ξ» i, iso.refl _)
(Ξ» i j hij, by { dsimp, rw [id_comp, comp_id, functor.map_zsmul], })) (by tidy)
instance map_cochain_complex_has_comm_shift :
(functor.map_homological_complex F (complex_shape.up β€)).has_comm_shift β€ :=
{ iso := Ξ» n, map_cochain_complex_shift_iso F n,
iso_zero := begin
ext K i,
rw [functor.comm_shift.unit_hom_app, comp_f,
functor.map_homological_complex_map_f, shift_functor_zero_eq,
shift_functor_zero_eq,
shift_functor_zero'_hom_app_f, shift_functor_zero'_inv_app_f],
dsimp [X_iso_of_eq],
simpa only [eq_to_hom_map, eq_to_hom_trans],
end,
iso_add := Ξ» a b, begin
ext K i,
simp only [functor.comm_shift.add_hom_app, comp_f, iso.symm_inv,
functor.map_homological_complex_map_f, shift_functor_add_eq, iso.symm_hom,
shift_functor_add'_inv_app_f, shift_functor_add'_hom_app_f,
shift_functor_map_f'],
dsimp [map_cochain_complex_shift_iso, iso.refl,
X_iso_of_eq],
erw [eq_to_hom_map, id_comp, id_comp, eq_to_hom_trans, eq_to_hom_refl],
end, }
end cochain_complex
|
Formal statement is: lemma suminf_binaryset_eq: fixes f :: "'a set \<Rightarrow> 'b::{comm_monoid_add, t2_space}" shows "f {} = 0 \<Longrightarrow> (\<Sum>n. f (binaryset A B n)) = f A + f B" Informal statement is: If $f$ is a function from sets to a commutative monoid with identity $0$, then $\sum_{n=0}^\infty f(A \cup B^n) = f(A) + f(B)$.
|
AdderType : (numargs : Nat) -> Type
AdderType Z = Int
AdderType (S k) = (next : Int) -> AdderType k
adder : (numargs : Nat) -> (acc : Int) -> AdderType numargs
adder Z acc = acc
adder (S k) acc = \next => adder k (next + acc)
TupleVect : (length : Nat) -> (ty : Type) -> Type
TupleVect Z _ = ()
TupleVect (S k) x = (x, TupleVect k x)
test : TupleVect 4 Nat
test = (1,2,3,4,())
|
import numpy as np
HPARAMS_REGISTRY = {}
class Hyperparams(dict):
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
return None
def __setattr__(self, attr, value):
self[attr] = value
vmpo_none = Hyperparams()
# model
vmpo_none.model = 'vmpo'
vmpo_none.state_rep = 'none'
# env
vmpo_none.env_name = 'rooms_watermaze'
vmpo_none.action_dim = 9
vmpo_none.action_list = np.array([
[0, 0, 0, 1, 0, 0, 0], # Forward
[0, 0, 0, -1, 0, 0, 0], # Backward
[0, 0, -1, 0, 0, 0, 0], # Strafe Left
[0, 0, 1, 0, 0, 0, 0], # Strafe Right
[-20, 0, 0, 0, 0, 0, 0], # Look Left
[20, 0, 0, 0, 0, 0, 0], # Look Right
[-20, 0, 0, 1, 0, 0, 0], # Look Left + Forward
[20, 0, 0, 1, 0, 0, 0], # Look Right + Forward
[0, 0, 0, 0, 1, 0, 0], # Fire.
])
HPARAMS_REGISTRY['vmpo_none'] = vmpo_none
ppo_none = Hyperparams()
ppo_none.update(vmpo_none)
# model
ppo_none.model = 'ppo'
HPARAMS_REGISTRY['ppo_none'] = ppo_none
def parse_args_and_update_hparams(H, parser, s=None):
args = parser.parse_args(s)
valid_args = set(args.__dict__.keys())
hparam_sets = [x for x in args.hparam_sets.split(',') if x]
for hp_set in hparam_sets:
hps = HPARAMS_REGISTRY[hp_set]
for k in hps:
if k not in valid_args:
raise ValueError(f"{k} not in default args")
parser.set_defaults(**hps)
H.update(parser.parse_args(s).__dict__)
def add_arguments(parser):
# utils
parser.add_argument('--seed', type=int, default=0)
parser.add_argument('--save_dir', type=str, default='./saved_models')
parser.add_argument('--desc', type=str, default='test')
parser.add_argument('--hparam_sets', '--hps', type=str)
parser.add_argument('--gpu', type=str, default='0')
# model
parser.add_argument('--model', type=str, default='vmpo', help='{vmpo|ppo}')
parser.add_argument('--state_rep', type=str, default='none', help='{none|lstm|trxl|gtrxl}')
parser.add_argument('--n_latent_var', type=int, default=64)
parser.add_argument('--n_layer', type=int, default=4)
parser.add_argument('--n_head', type=int, default=8)
parser.add_argument('--dropout', type=float, default=0.0)
parser.add_argument('--mem_len', type=int, default=10)
# env
parser.add_argument('--env_name', type=str, default='rooms_watermaze')
parser.add_argument('--action_dim', type=int, default=9)
parser.add_argument('--log_interval', type=int, default=40)
parser.add_argument('--max_episodes', type=int, default=50000)
parser.add_argument('--max_timesteps', type=int, default=300)
parser.add_argument('--update_timestep', type=int, default=1200)
parser.add_argument('--action_list', type=list, default=[])
# training
parser.add_argument('--lr', type=float, default=0.001)
parser.add_argument('--betas', type=tuple, default=(0.9, 0.999))
parser.add_argument('--gamma', type=float, default=0.99)
parser.add_argument('--K_epochs', type=int, default=4)
parser.add_argument('--eps_clip', type=float, default=0.2)
return parser
|
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
a b c : K
fract_a_ne_zero : Int.fract a β 0
β’ (ββaβ * b + c) / Int.fract a + b = (b * a + c) / Int.fract a
[PROOFSTEP]
field_simp [fract_a_ne_zero]
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
a b c : K
fract_a_ne_zero : Int.fract a β 0
β’ ββaβ * b + c + b * Int.fract a = b * a + c
[PROOFSTEP]
rw [Int.fract]
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
a b c : K
fract_a_ne_zero : Int.fract a β 0
β’ ββaβ * b + c + b * (a - ββaβ) = b * a + c
[PROOFSTEP]
ring
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
β’ β {ifp_n : IntFractPair K},
IntFractPair.stream v n = some ifp_n β
v = compExactValue (continuantsAux (of v) n) (continuantsAux (of v) (n + 1)) ifp_n.fr
[PROOFSTEP]
let g := of v
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
β’ β {ifp_n : IntFractPair K},
IntFractPair.stream v n = some ifp_n β
v = compExactValue (continuantsAux (of v) n) (continuantsAux (of v) (n + 1)) ifp_n.fr
[PROOFSTEP]
induction' n with n IH
[GOAL]
case zero
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
β’ β {ifp_n : IntFractPair K},
IntFractPair.stream v Nat.zero = some ifp_n β
v = compExactValue (continuantsAux (of v) Nat.zero) (continuantsAux (of v) (Nat.zero + 1)) ifp_n.fr
[PROOFSTEP]
intro ifp_zero stream_zero_eq
[GOAL]
case zero
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
ifp_zero : IntFractPair K
stream_zero_eq : IntFractPair.stream v Nat.zero = some ifp_zero
β’ v = compExactValue (continuantsAux (of v) Nat.zero) (continuantsAux (of v) (Nat.zero + 1)) ifp_zero.fr
[PROOFSTEP]
have : IntFractPair.of v = ifp_zero :=
by
have : IntFractPair.stream v 0 = some (IntFractPair.of v) := rfl
simpa only [Nat.zero_eq, this, Option.some.injEq] using stream_zero_eq
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
ifp_zero : IntFractPair K
stream_zero_eq : IntFractPair.stream v Nat.zero = some ifp_zero
β’ IntFractPair.of v = ifp_zero
[PROOFSTEP]
have : IntFractPair.stream v 0 = some (IntFractPair.of v) := rfl
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
ifp_zero : IntFractPair K
stream_zero_eq : IntFractPair.stream v Nat.zero = some ifp_zero
this : IntFractPair.stream v 0 = some (IntFractPair.of v)
β’ IntFractPair.of v = ifp_zero
[PROOFSTEP]
simpa only [Nat.zero_eq, this, Option.some.injEq] using stream_zero_eq
[GOAL]
case zero
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
ifp_zero : IntFractPair K
stream_zero_eq : IntFractPair.stream v Nat.zero = some ifp_zero
this : IntFractPair.of v = ifp_zero
β’ v = compExactValue (continuantsAux (of v) Nat.zero) (continuantsAux (of v) (Nat.zero + 1)) ifp_zero.fr
[PROOFSTEP]
cases this
[GOAL]
case zero.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
stream_zero_eq : IntFractPair.stream v Nat.zero = some (IntFractPair.of v)
β’ v = compExactValue (continuantsAux (of v) Nat.zero) (continuantsAux (of v) (Nat.zero + 1)) (IntFractPair.of v).fr
[PROOFSTEP]
cases' Decidable.em (Int.fract v = 0) with fract_eq_zero fract_ne_zero
[GOAL]
case zero.refl.inl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
stream_zero_eq : IntFractPair.stream v Nat.zero = some (IntFractPair.of v)
fract_eq_zero : Int.fract v = 0
β’ v = compExactValue (continuantsAux (of v) Nat.zero) (continuantsAux (of v) (Nat.zero + 1)) (IntFractPair.of v).fr
[PROOFSTEP]
suffices v = βvβ by
-- Porting note: was `simpa [continuantsAux, fract_eq_zero, compExactValue]`
field_simp [nextContinuants, nextNumerator, nextDenominator, compExactValue]
have : (IntFractPair.of v).fr = Int.fract v := rfl
rwa [this, if_pos fract_eq_zero]
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
stream_zero_eq : IntFractPair.stream v Nat.zero = some (IntFractPair.of v)
fract_eq_zero : Int.fract v = 0
this : v = ββvβ
β’ v = compExactValue (continuantsAux (of v) Nat.zero) (continuantsAux (of v) (Nat.zero + 1)) (IntFractPair.of v).fr
[PROOFSTEP]
field_simp [nextContinuants, nextNumerator, nextDenominator, compExactValue]
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
stream_zero_eq : IntFractPair.stream v Nat.zero = some (IntFractPair.of v)
fract_eq_zero : Int.fract v = 0
this : v = ββvβ
β’ v = if (IntFractPair.of v).fr = 0 then ββvβ else ββvβ + (IntFractPair.of v).fr
[PROOFSTEP]
have : (IntFractPair.of v).fr = Int.fract v := rfl
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
stream_zero_eq : IntFractPair.stream v Nat.zero = some (IntFractPair.of v)
fract_eq_zero : Int.fract v = 0
thisβ : v = ββvβ
this : (IntFractPair.of v).fr = Int.fract v
β’ v = if (IntFractPair.of v).fr = 0 then ββvβ else ββvβ + (IntFractPair.of v).fr
[PROOFSTEP]
rwa [this, if_pos fract_eq_zero]
[GOAL]
case zero.refl.inl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
stream_zero_eq : IntFractPair.stream v Nat.zero = some (IntFractPair.of v)
fract_eq_zero : Int.fract v = 0
β’ v = ββvβ
[PROOFSTEP]
calc
v = Int.fract v + βvβ := by rw [Int.fract_add_floor]
_ = βvβ := by
simp [fract_eq_zero]
-- Int.fract v β 0; the claim then easily follows by unfolding a single computation step
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
stream_zero_eq : IntFractPair.stream v Nat.zero = some (IntFractPair.of v)
fract_eq_zero : Int.fract v = 0
β’ v = Int.fract v + ββvβ
[PROOFSTEP]
rw [Int.fract_add_floor]
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
stream_zero_eq : IntFractPair.stream v Nat.zero = some (IntFractPair.of v)
fract_eq_zero : Int.fract v = 0
β’ Int.fract v + ββvβ = ββvβ
[PROOFSTEP]
simp [fract_eq_zero]
-- Int.fract v β 0; the claim then easily follows by unfolding a single computation step
[GOAL]
case zero.refl.inr
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
stream_zero_eq : IntFractPair.stream v Nat.zero = some (IntFractPair.of v)
fract_ne_zero : Β¬Int.fract v = 0
β’ v = compExactValue (continuantsAux (of v) Nat.zero) (continuantsAux (of v) (Nat.zero + 1)) (IntFractPair.of v).fr
[PROOFSTEP]
field_simp [continuantsAux, nextContinuants, nextNumerator, nextDenominator, of_h_eq_floor, compExactValue]
-- Porting note: this and the if_neg rewrite are needed
[GOAL]
case zero.refl.inr
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
stream_zero_eq : IntFractPair.stream v Nat.zero = some (IntFractPair.of v)
fract_ne_zero : Β¬Int.fract v = 0
β’ v = if (IntFractPair.of v).fr = 0 then ββvβ else ββvβ + (IntFractPair.of v).fr
[PROOFSTEP]
have : (IntFractPair.of v).fr = Int.fract v := rfl
[GOAL]
case zero.refl.inr
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
stream_zero_eq : IntFractPair.stream v Nat.zero = some (IntFractPair.of v)
fract_ne_zero : Β¬Int.fract v = 0
this : (IntFractPair.of v).fr = Int.fract v
β’ v = if (IntFractPair.of v).fr = 0 then ββvβ else ββvβ + (IntFractPair.of v).fr
[PROOFSTEP]
rw [this, if_neg fract_ne_zero, Int.floor_add_fract]
[GOAL]
case succ
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
IH :
β {ifp_n : IntFractPair K},
IntFractPair.stream v n = some ifp_n β
v = compExactValue (continuantsAux (of v) n) (continuantsAux (of v) (n + 1)) ifp_n.fr
β’ β {ifp_n : IntFractPair K},
IntFractPair.stream v (Nat.succ n) = some ifp_n β
v = compExactValue (continuantsAux (of v) (Nat.succ n)) (continuantsAux (of v) (Nat.succ n + 1)) ifp_n.fr
[PROOFSTEP]
intro ifp_succ_n succ_nth_stream_eq
[GOAL]
case succ
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
IH :
β {ifp_n : IntFractPair K},
IntFractPair.stream v n = some ifp_n β
v = compExactValue (continuantsAux (of v) n) (continuantsAux (of v) (n + 1)) ifp_n.fr
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
β’ v = compExactValue (continuantsAux (of v) (Nat.succ n)) (continuantsAux (of v) (Nat.succ n + 1)) ifp_succ_n.fr
[PROOFSTEP]
obtain β¨ifp_n, nth_stream_eq, nth_fract_ne_zero, -β© :
β ifp_n, IntFractPair.stream v n = some ifp_n β§ ifp_n.fr β 0 β§ IntFractPair.of ifp_n.frβ»ΒΉ = ifp_succ_n
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
IH :
β {ifp_n : IntFractPair K},
IntFractPair.stream v n = some ifp_n β
v = compExactValue (continuantsAux (of v) n) (continuantsAux (of v) (n + 1)) ifp_n.fr
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
β’ β ifp_n, IntFractPair.stream v n = some ifp_n β§ ifp_n.fr β 0 β§ IntFractPair.of ifp_n.frβ»ΒΉ = ifp_succ_n
case succ.intro.intro.intro
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
IH :
β {ifp_n : IntFractPair K},
IntFractPair.stream v n = some ifp_n β
v = compExactValue (continuantsAux (of v) n) (continuantsAux (of v) (n + 1)) ifp_n.fr
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
β’ v = compExactValue (continuantsAux (of v) (Nat.succ n)) (continuantsAux (of v) (Nat.succ n + 1)) ifp_succ_n.fr
[PROOFSTEP]
exact IntFractPair.succ_nth_stream_eq_some_iff.1 succ_nth_stream_eq
[GOAL]
case succ.intro.intro.intro
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
IH :
β {ifp_n : IntFractPair K},
IntFractPair.stream v n = some ifp_n β
v = compExactValue (continuantsAux (of v) n) (continuantsAux (of v) (n + 1)) ifp_n.fr
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
β’ v = compExactValue (continuantsAux (of v) (Nat.succ n)) (continuantsAux (of v) (Nat.succ n + 1)) ifp_succ_n.fr
[PROOFSTEP]
let conts := g.continuantsAux (n + 2)
[GOAL]
case succ.intro.intro.intro
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
IH :
β {ifp_n : IntFractPair K},
IntFractPair.stream v n = some ifp_n β
v = compExactValue (continuantsAux (of v) n) (continuantsAux (of v) (n + 1)) ifp_n.fr
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
β’ v = compExactValue (continuantsAux (of v) (Nat.succ n)) (continuantsAux (of v) (Nat.succ n + 1)) ifp_succ_n.fr
[PROOFSTEP]
set pconts := g.continuantsAux (n + 1) with pconts_eq
[GOAL]
case succ.intro.intro.intro
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
IH :
β {ifp_n : IntFractPair K},
IntFractPair.stream v n = some ifp_n β v = compExactValue (continuantsAux (of v) n) pconts ifp_n.fr
pconts_eq : pconts = continuantsAux g (n + 1)
β’ v = compExactValue pconts (continuantsAux (of v) (Nat.succ n + 1)) ifp_succ_n.fr
[PROOFSTEP]
set ppconts := g.continuantsAux n with ppconts_eq
[GOAL]
case succ.intro.intro.intro
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
β’ v = compExactValue pconts (continuantsAux (of v) (Nat.succ n + 1)) ifp_succ_n.fr
[PROOFSTEP]
cases' Decidable.em (ifp_succ_n.fr = 0) with ifp_succ_n_fr_eq_zero ifp_succ_n_fr_ne_zero
[GOAL]
case succ.intro.intro.intro.inl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_eq_zero : ifp_succ_n.fr = 0
β’ v = compExactValue pconts (continuantsAux (of v) (Nat.succ n + 1)) ifp_succ_n.fr
[PROOFSTEP]
suffices v = conts.a / conts.b by
simpa [compExactValue, ifp_succ_n_fr_eq_zero]
-- use the IH and the fact that ifp_n.frβ»ΒΉ = βifp_n.frβ»ΒΉβ to prove this case
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_eq_zero : ifp_succ_n.fr = 0
this : v = conts.a / conts.b
β’ v = compExactValue pconts (continuantsAux (of v) (Nat.succ n + 1)) ifp_succ_n.fr
[PROOFSTEP]
simpa [compExactValue, ifp_succ_n_fr_eq_zero]
-- use the IH and the fact that ifp_n.frβ»ΒΉ = βifp_n.frβ»ΒΉβ to prove this case
[GOAL]
case succ.intro.intro.intro.inl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_eq_zero : ifp_succ_n.fr = 0
β’ v = conts.a / conts.b
[PROOFSTEP]
obtain β¨ifp_n', nth_stream_eq', ifp_n_fract_inv_eq_floorβ© :
β ifp_n, IntFractPair.stream v n = some ifp_n β§ ifp_n.frβ»ΒΉ = βifp_n.frβ»ΒΉβ
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_eq_zero : ifp_succ_n.fr = 0
β’ β ifp_n, IntFractPair.stream v n = some ifp_n β§ ifp_n.frβ»ΒΉ = ββifp_n.frβ»ΒΉβ
case succ.intro.intro.intro.inl.intro.intro
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_eq_zero : ifp_succ_n.fr = 0
ifp_n' : IntFractPair K
nth_stream_eq' : IntFractPair.stream v n = some ifp_n'
ifp_n_fract_inv_eq_floor : ifp_n'.frβ»ΒΉ = ββifp_n'.frβ»ΒΉβ
β’ v = conts.a / conts.b
[PROOFSTEP]
exact IntFractPair.exists_succ_nth_stream_of_fr_zero succ_nth_stream_eq ifp_succ_n_fr_eq_zero
[GOAL]
case succ.intro.intro.intro.inl.intro.intro
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_eq_zero : ifp_succ_n.fr = 0
ifp_n' : IntFractPair K
nth_stream_eq' : IntFractPair.stream v n = some ifp_n'
ifp_n_fract_inv_eq_floor : ifp_n'.frβ»ΒΉ = ββifp_n'.frβ»ΒΉβ
β’ v = conts.a / conts.b
[PROOFSTEP]
have : ifp_n' = ifp_n := by injection Eq.trans nth_stream_eq'.symm nth_stream_eq
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_eq_zero : ifp_succ_n.fr = 0
ifp_n' : IntFractPair K
nth_stream_eq' : IntFractPair.stream v n = some ifp_n'
ifp_n_fract_inv_eq_floor : ifp_n'.frβ»ΒΉ = ββifp_n'.frβ»ΒΉβ
β’ ifp_n' = ifp_n
[PROOFSTEP]
injection Eq.trans nth_stream_eq'.symm nth_stream_eq
[GOAL]
case succ.intro.intro.intro.inl.intro.intro
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_eq_zero : ifp_succ_n.fr = 0
ifp_n' : IntFractPair K
nth_stream_eq' : IntFractPair.stream v n = some ifp_n'
ifp_n_fract_inv_eq_floor : ifp_n'.frβ»ΒΉ = ββifp_n'.frβ»ΒΉβ
this : ifp_n' = ifp_n
β’ v = conts.a / conts.b
[PROOFSTEP]
cases this
[GOAL]
case succ.intro.intro.intro.inl.intro.intro.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_eq_zero : ifp_succ_n.fr = 0
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_inv_eq_floor : ifp_n.frβ»ΒΉ = ββifp_n.frβ»ΒΉβ
β’ v = conts.a / conts.b
[PROOFSTEP]
have s_nth_eq : g.s.get? n = some β¨1, βifp_n.frβ»ΒΉββ© :=
get?_of_eq_some_of_get?_intFractPair_stream_fr_ne_zero nth_stream_eq nth_fract_ne_zero
[GOAL]
case succ.intro.intro.intro.inl.intro.intro.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_eq_zero : ifp_succ_n.fr = 0
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_inv_eq_floor : ifp_n.frβ»ΒΉ = ββifp_n.frβ»ΒΉβ
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
β’ v = conts.a / conts.b
[PROOFSTEP]
rw [β ifp_n_fract_inv_eq_floor] at s_nth_eq
[GOAL]
case succ.intro.intro.intro.inl.intro.intro.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_eq_zero : ifp_succ_n.fr = 0
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_inv_eq_floor : ifp_n.frβ»ΒΉ = ββifp_n.frβ»ΒΉβ
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ifp_n.frβ»ΒΉ }
β’ v = conts.a / conts.b
[PROOFSTEP]
suffices v = compExactValue ppconts pconts ifp_n.fr by
simpa [continuantsAux, s_nth_eq, compExactValue, nth_fract_ne_zero] using this
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_eq_zero : ifp_succ_n.fr = 0
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_inv_eq_floor : ifp_n.frβ»ΒΉ = ββifp_n.frβ»ΒΉβ
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ifp_n.frβ»ΒΉ }
this : v = compExactValue ppconts pconts ifp_n.fr
β’ v = conts.a / conts.b
[PROOFSTEP]
simpa [continuantsAux, s_nth_eq, compExactValue, nth_fract_ne_zero] using this
[GOAL]
case succ.intro.intro.intro.inl.intro.intro.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_eq_zero : ifp_succ_n.fr = 0
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_inv_eq_floor : ifp_n.frβ»ΒΉ = ββifp_n.frβ»ΒΉβ
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ifp_n.frβ»ΒΉ }
β’ v = compExactValue ppconts pconts ifp_n.fr
[PROOFSTEP]
exact IH nth_stream_eq
[GOAL]
case succ.intro.intro.intro.inr
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_ne_zero : Β¬ifp_succ_n.fr = 0
β’ v = compExactValue pconts (continuantsAux (of v) (Nat.succ n + 1)) ifp_succ_n.fr
[PROOFSTEP]
suffices compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts ifp_succ_n.fr
by
have : v = compExactValue ppconts pconts ifp_n.fr := IH nth_stream_eq
conv_lhs => rw [this]
assumption
-- get the correspondence between ifp_n and ifp_succ_n
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_ne_zero : Β¬ifp_succ_n.fr = 0
this : compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts ifp_succ_n.fr
β’ v = compExactValue pconts (continuantsAux (of v) (Nat.succ n + 1)) ifp_succ_n.fr
[PROOFSTEP]
have : v = compExactValue ppconts pconts ifp_n.fr := IH nth_stream_eq
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_ne_zero : Β¬ifp_succ_n.fr = 0
thisβ : compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts ifp_succ_n.fr
this : v = compExactValue ppconts pconts ifp_n.fr
β’ v = compExactValue pconts (continuantsAux (of v) (Nat.succ n + 1)) ifp_succ_n.fr
[PROOFSTEP]
conv_lhs => rw [this]
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_ne_zero : Β¬ifp_succ_n.fr = 0
thisβ : compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts ifp_succ_n.fr
this : v = compExactValue ppconts pconts ifp_n.fr
| v
[PROOFSTEP]
rw [this]
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_ne_zero : Β¬ifp_succ_n.fr = 0
thisβ : compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts ifp_succ_n.fr
this : v = compExactValue ppconts pconts ifp_n.fr
| v
[PROOFSTEP]
rw [this]
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_ne_zero : Β¬ifp_succ_n.fr = 0
thisβ : compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts ifp_succ_n.fr
this : v = compExactValue ppconts pconts ifp_n.fr
| v
[PROOFSTEP]
rw [this]
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_ne_zero : Β¬ifp_succ_n.fr = 0
thisβ : compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts ifp_succ_n.fr
this : v = compExactValue ppconts pconts ifp_n.fr
β’ compExactValue ppconts pconts ifp_n.fr = compExactValue pconts (continuantsAux (of v) (Nat.succ n + 1)) ifp_succ_n.fr
[PROOFSTEP]
assumption
-- get the correspondence between ifp_n and ifp_succ_n
[GOAL]
case succ.intro.intro.intro.inr
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_ne_zero : Β¬ifp_succ_n.fr = 0
β’ compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts ifp_succ_n.fr
[PROOFSTEP]
obtain β¨ifp_n', nth_stream_eq', ifp_n_fract_ne_zero, β¨reflβ©β© :
β ifp_n, IntFractPair.stream v n = some ifp_n β§ ifp_n.fr β 0 β§ IntFractPair.of ifp_n.frβ»ΒΉ = ifp_succ_n
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_succ_n : IntFractPair K
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some ifp_succ_n
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_succ_n_fr_ne_zero : Β¬ifp_succ_n.fr = 0
β’ β ifp_n, IntFractPair.stream v n = some ifp_n β§ ifp_n.fr β 0 β§ IntFractPair.of ifp_n.frβ»ΒΉ = ifp_succ_n
case succ.intro.intro.intro.inr.intro.intro.intro.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_n' : IntFractPair K
nth_stream_eq' : IntFractPair.stream v n = some ifp_n'
ifp_n_fract_ne_zero : ifp_n'.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n'.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n'.frβ»ΒΉ).fr = 0
β’ compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts (IntFractPair.of ifp_n'.frβ»ΒΉ).fr
[PROOFSTEP]
exact IntFractPair.succ_nth_stream_eq_some_iff.1 succ_nth_stream_eq
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_n' : IntFractPair K
nth_stream_eq' : IntFractPair.stream v n = some ifp_n'
ifp_n_fract_ne_zero : ifp_n'.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n'.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n'.frβ»ΒΉ).fr = 0
β’ compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts (IntFractPair.of ifp_n'.frβ»ΒΉ).fr
[PROOFSTEP]
have : ifp_n' = ifp_n := by injection Eq.trans nth_stream_eq'.symm nth_stream_eq
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_n' : IntFractPair K
nth_stream_eq' : IntFractPair.stream v n = some ifp_n'
ifp_n_fract_ne_zero : ifp_n'.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n'.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n'.frβ»ΒΉ).fr = 0
β’ ifp_n' = ifp_n
[PROOFSTEP]
injection Eq.trans nth_stream_eq'.symm nth_stream_eq
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
ifp_n' : IntFractPair K
nth_stream_eq' : IntFractPair.stream v n = some ifp_n'
ifp_n_fract_ne_zero : ifp_n'.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n'.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n'.frβ»ΒΉ).fr = 0
this : ifp_n' = ifp_n
β’ compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts (IntFractPair.of ifp_n'.frβ»ΒΉ).fr
[PROOFSTEP]
cases this
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
β’ compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts (IntFractPair.of ifp_n.frβ»ΒΉ).fr
[PROOFSTEP]
have s_nth_eq : g.s.get? n = some β¨1, (βifp_n.frβ»ΒΉβ : K)β© :=
get?_of_eq_some_of_get?_intFractPair_stream_fr_ne_zero nth_stream_eq ifp_n_fract_ne_zero
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
β’ compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts (IntFractPair.of ifp_n.frβ»ΒΉ).fr
[PROOFSTEP]
let ppA := ppconts.a
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
β’ compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts (IntFractPair.of ifp_n.frβ»ΒΉ).fr
[PROOFSTEP]
let ppB := ppconts.b
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
β’ compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts (IntFractPair.of ifp_n.frβ»ΒΉ).fr
[PROOFSTEP]
let pA := pconts.a
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
β’ compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts (IntFractPair.of ifp_n.frβ»ΒΉ).fr
[PROOFSTEP]
let pB := pconts.b
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
β’ compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts (IntFractPair.of ifp_n.frβ»ΒΉ).fr
[PROOFSTEP]
have : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB) := by
-- unfold compExactValue and the convergent computation once
field_simp [ifp_n_fract_ne_zero, compExactValue, nextContinuants, nextNumerator, nextDenominator]
ac_rfl
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
β’ compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
[PROOFSTEP]
field_simp [ifp_n_fract_ne_zero, compExactValue, nextContinuants, nextNumerator, nextDenominator]
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
β’ ((continuantsAux (of v) (n + 1)).a + (continuantsAux (of v) n).a * ifp_n.fr) /
((continuantsAux (of v) (n + 1)).b + (continuantsAux (of v) n).b * ifp_n.fr) =
((continuantsAux (of v) n).a * ifp_n.fr + (continuantsAux (of v) (n + 1)).a) /
((continuantsAux (of v) n).b * ifp_n.fr + (continuantsAux (of v) (n + 1)).b)
[PROOFSTEP]
ac_rfl
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
β’ compExactValue ppconts pconts ifp_n.fr = compExactValue pconts conts (IntFractPair.of ifp_n.frβ»ΒΉ).fr
[PROOFSTEP]
rw [this]
-- two calculations needed to show the claim
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
β’ (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB) = compExactValue pconts conts (IntFractPair.of ifp_n.frβ»ΒΉ).fr
[PROOFSTEP]
have tmp_calc := compExactValue_correctness_of_stream_eq_some_aux_comp pA ppA ifp_succ_n_fr_ne_zero
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc : (ββifp_n.frβ»ΒΉβ * pA + ppA) / Int.fract ifp_n.frβ»ΒΉ + pA = (pA * ifp_n.frβ»ΒΉ + ppA) / Int.fract ifp_n.frβ»ΒΉ
β’ (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB) = compExactValue pconts conts (IntFractPair.of ifp_n.frβ»ΒΉ).fr
[PROOFSTEP]
have tmp_calc' := compExactValue_correctness_of_stream_eq_some_aux_comp pB ppB ifp_succ_n_fr_ne_zero
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc : (ββifp_n.frβ»ΒΉβ * pA + ppA) / Int.fract ifp_n.frβ»ΒΉ + pA = (pA * ifp_n.frβ»ΒΉ + ppA) / Int.fract ifp_n.frβ»ΒΉ
tmp_calc' : (ββifp_n.frβ»ΒΉβ * pB + ppB) / Int.fract ifp_n.frβ»ΒΉ + pB = (pB * ifp_n.frβ»ΒΉ + ppB) / Int.fract ifp_n.frβ»ΒΉ
β’ (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB) = compExactValue pconts conts (IntFractPair.of ifp_n.frβ»ΒΉ).fr
[PROOFSTEP]
let f := Int.fract (1 / ifp_n.fr)
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc : (ββifp_n.frβ»ΒΉβ * pA + ppA) / Int.fract ifp_n.frβ»ΒΉ + pA = (pA * ifp_n.frβ»ΒΉ + ppA) / Int.fract ifp_n.frβ»ΒΉ
tmp_calc' : (ββifp_n.frβ»ΒΉβ * pB + ppB) / Int.fract ifp_n.frβ»ΒΉ + pB = (pB * ifp_n.frβ»ΒΉ + ppB) / Int.fract ifp_n.frβ»ΒΉ
f : K := Int.fract (1 / ifp_n.fr)
β’ (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB) = compExactValue pconts conts (IntFractPair.of ifp_n.frβ»ΒΉ).fr
[PROOFSTEP]
have f_ne_zero : f β 0 := by simpa using ifp_succ_n_fr_ne_zero
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc : (ββifp_n.frβ»ΒΉβ * pA + ppA) / Int.fract ifp_n.frβ»ΒΉ + pA = (pA * ifp_n.frβ»ΒΉ + ppA) / Int.fract ifp_n.frβ»ΒΉ
tmp_calc' : (ββifp_n.frβ»ΒΉβ * pB + ppB) / Int.fract ifp_n.frβ»ΒΉ + pB = (pB * ifp_n.frβ»ΒΉ + ppB) / Int.fract ifp_n.frβ»ΒΉ
f : K := Int.fract (1 / ifp_n.fr)
β’ f β 0
[PROOFSTEP]
simpa using ifp_succ_n_fr_ne_zero
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc : (ββifp_n.frβ»ΒΉβ * pA + ppA) / Int.fract ifp_n.frβ»ΒΉ + pA = (pA * ifp_n.frβ»ΒΉ + ppA) / Int.fract ifp_n.frβ»ΒΉ
tmp_calc' : (ββifp_n.frβ»ΒΉβ * pB + ppB) / Int.fract ifp_n.frβ»ΒΉ + pB = (pB * ifp_n.frβ»ΒΉ + ppB) / Int.fract ifp_n.frβ»ΒΉ
f : K := Int.fract (1 / ifp_n.fr)
f_ne_zero : f β 0
β’ (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB) = compExactValue pconts conts (IntFractPair.of ifp_n.frβ»ΒΉ).fr
[PROOFSTEP]
rw [inv_eq_one_div] at tmp_calc tmp_calc'
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc :
(ββ1 / ifp_n.frβ * pA + ppA) / Int.fract (1 / ifp_n.fr) + pA = (pA * (1 / ifp_n.fr) + ppA) / Int.fract (1 / ifp_n.fr)
tmp_calc' :
(ββ1 / ifp_n.frβ * pB + ppB) / Int.fract (1 / ifp_n.fr) + pB = (pB * (1 / ifp_n.fr) + ppB) / Int.fract (1 / ifp_n.fr)
f : K := Int.fract (1 / ifp_n.fr)
f_ne_zero : f β 0
β’ (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB) = compExactValue pconts conts (IntFractPair.of ifp_n.frβ»ΒΉ).fr
[PROOFSTEP]
have hA : (ββ1 / ifp_n.frβ * pA + ppA) + pA * f = pA * (1 / ifp_n.fr) + ppA :=
by
have := congrFun (congrArg HMul.hMul tmp_calc) f
rwa [right_distrib, div_mul_cancel (h := f_ne_zero), div_mul_cancel (h := f_ne_zero)] at this
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc :
(ββ1 / ifp_n.frβ * pA + ppA) / Int.fract (1 / ifp_n.fr) + pA = (pA * (1 / ifp_n.fr) + ppA) / Int.fract (1 / ifp_n.fr)
tmp_calc' :
(ββ1 / ifp_n.frβ * pB + ppB) / Int.fract (1 / ifp_n.fr) + pB = (pB * (1 / ifp_n.fr) + ppB) / Int.fract (1 / ifp_n.fr)
f : K := Int.fract (1 / ifp_n.fr)
f_ne_zero : f β 0
β’ ββ1 / ifp_n.frβ * pA + ppA + pA * f = pA * (1 / ifp_n.fr) + ppA
[PROOFSTEP]
have := congrFun (congrArg HMul.hMul tmp_calc) f
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
thisβ : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc :
(ββ1 / ifp_n.frβ * pA + ppA) / Int.fract (1 / ifp_n.fr) + pA = (pA * (1 / ifp_n.fr) + ppA) / Int.fract (1 / ifp_n.fr)
tmp_calc' :
(ββ1 / ifp_n.frβ * pB + ppB) / Int.fract (1 / ifp_n.fr) + pB = (pB * (1 / ifp_n.fr) + ppB) / Int.fract (1 / ifp_n.fr)
f : K := Int.fract (1 / ifp_n.fr)
f_ne_zero : f β 0
this :
((ββ1 / ifp_n.frβ * pA + ppA) / Int.fract (1 / ifp_n.fr) + pA) * f =
(pA * (1 / ifp_n.fr) + ppA) / Int.fract (1 / ifp_n.fr) * f
β’ ββ1 / ifp_n.frβ * pA + ppA + pA * f = pA * (1 / ifp_n.fr) + ppA
[PROOFSTEP]
rwa [right_distrib, div_mul_cancel (h := f_ne_zero), div_mul_cancel (h := f_ne_zero)] at this
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc :
(ββ1 / ifp_n.frβ * pA + ppA) / Int.fract (1 / ifp_n.fr) + pA = (pA * (1 / ifp_n.fr) + ppA) / Int.fract (1 / ifp_n.fr)
tmp_calc' :
(ββ1 / ifp_n.frβ * pB + ppB) / Int.fract (1 / ifp_n.fr) + pB = (pB * (1 / ifp_n.fr) + ppB) / Int.fract (1 / ifp_n.fr)
f : K := Int.fract (1 / ifp_n.fr)
f_ne_zero : f β 0
hA : ββ1 / ifp_n.frβ * pA + ppA + pA * f = pA * (1 / ifp_n.fr) + ppA
β’ (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB) = compExactValue pconts conts (IntFractPair.of ifp_n.frβ»ΒΉ).fr
[PROOFSTEP]
have hB : (ββ1 / ifp_n.frβ * pB + ppB) + pB * f = pB * (1 / ifp_n.fr) + ppB :=
by
have := congrFun (congrArg HMul.hMul tmp_calc') f
rwa [right_distrib, div_mul_cancel (h := f_ne_zero), div_mul_cancel (h := f_ne_zero)] at this
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc :
(ββ1 / ifp_n.frβ * pA + ppA) / Int.fract (1 / ifp_n.fr) + pA = (pA * (1 / ifp_n.fr) + ppA) / Int.fract (1 / ifp_n.fr)
tmp_calc' :
(ββ1 / ifp_n.frβ * pB + ppB) / Int.fract (1 / ifp_n.fr) + pB = (pB * (1 / ifp_n.fr) + ppB) / Int.fract (1 / ifp_n.fr)
f : K := Int.fract (1 / ifp_n.fr)
f_ne_zero : f β 0
hA : ββ1 / ifp_n.frβ * pA + ppA + pA * f = pA * (1 / ifp_n.fr) + ppA
β’ ββ1 / ifp_n.frβ * pB + ppB + pB * f = pB * (1 / ifp_n.fr) + ppB
[PROOFSTEP]
have := congrFun (congrArg HMul.hMul tmp_calc') f
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
thisβ : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc :
(ββ1 / ifp_n.frβ * pA + ppA) / Int.fract (1 / ifp_n.fr) + pA = (pA * (1 / ifp_n.fr) + ppA) / Int.fract (1 / ifp_n.fr)
tmp_calc' :
(ββ1 / ifp_n.frβ * pB + ppB) / Int.fract (1 / ifp_n.fr) + pB = (pB * (1 / ifp_n.fr) + ppB) / Int.fract (1 / ifp_n.fr)
f : K := Int.fract (1 / ifp_n.fr)
f_ne_zero : f β 0
hA : ββ1 / ifp_n.frβ * pA + ppA + pA * f = pA * (1 / ifp_n.fr) + ppA
this :
((ββ1 / ifp_n.frβ * pB + ppB) / Int.fract (1 / ifp_n.fr) + pB) * f =
(pB * (1 / ifp_n.fr) + ppB) / Int.fract (1 / ifp_n.fr) * f
β’ ββ1 / ifp_n.frβ * pB + ppB + pB * f = pB * (1 / ifp_n.fr) + ppB
[PROOFSTEP]
rwa [right_distrib, div_mul_cancel (h := f_ne_zero), div_mul_cancel (h := f_ne_zero)] at this
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc :
(ββ1 / ifp_n.frβ * pA + ppA) / Int.fract (1 / ifp_n.fr) + pA = (pA * (1 / ifp_n.fr) + ppA) / Int.fract (1 / ifp_n.fr)
tmp_calc' :
(ββ1 / ifp_n.frβ * pB + ppB) / Int.fract (1 / ifp_n.fr) + pB = (pB * (1 / ifp_n.fr) + ppB) / Int.fract (1 / ifp_n.fr)
f : K := Int.fract (1 / ifp_n.fr)
f_ne_zero : f β 0
hA : ββ1 / ifp_n.frβ * pA + ppA + pA * f = pA * (1 / ifp_n.fr) + ppA
hB : ββ1 / ifp_n.frβ * pB + ppB + pB * f = pB * (1 / ifp_n.fr) + ppB
β’ (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB) = compExactValue pconts conts (IntFractPair.of ifp_n.frβ»ΒΉ).fr
[PROOFSTEP]
field_simp [compExactValue, continuantsAux_recurrence s_nth_eq ppconts_eq pconts_eq, nextContinuants, nextNumerator,
nextDenominator]
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc :
(ββ1 / ifp_n.frβ * pA + ppA) / Int.fract (1 / ifp_n.fr) + pA = (pA * (1 / ifp_n.fr) + ppA) / Int.fract (1 / ifp_n.fr)
tmp_calc' :
(ββ1 / ifp_n.frβ * pB + ppB) / Int.fract (1 / ifp_n.fr) + pB = (pB * (1 / ifp_n.fr) + ppB) / Int.fract (1 / ifp_n.fr)
f : K := Int.fract (1 / ifp_n.fr)
f_ne_zero : f β 0
hA : ββ1 / ifp_n.frβ * pA + ppA + pA * f = pA * (1 / ifp_n.fr) + ppA
hB : ββ1 / ifp_n.frβ * pB + ppB + pB * f = pB * (1 / ifp_n.fr) + ppB
β’ ((continuantsAux (of v) n).a * ifp_n.fr + (continuantsAux (of v) (n + 1)).a) /
((continuantsAux (of v) n).b * ifp_n.fr + (continuantsAux (of v) (n + 1)).b) =
if (IntFractPair.of (1 / ifp_n.fr)).fr = 0 then
(ββ1 / ifp_n.frβ * (continuantsAux (of v) (n + 1)).a + (continuantsAux (of v) n).a) /
(ββ1 / ifp_n.frβ * (continuantsAux (of v) (n + 1)).b + (continuantsAux (of v) n).b)
else
(ββ1 / ifp_n.frβ * (continuantsAux (of v) (n + 1)).a + (continuantsAux (of v) n).a +
(continuantsAux (of v) (n + 1)).a * (IntFractPair.of (1 / ifp_n.fr)).fr) /
(ββ1 / ifp_n.frβ * (continuantsAux (of v) (n + 1)).b + (continuantsAux (of v) n).b +
(continuantsAux (of v) (n + 1)).b * (IntFractPair.of (1 / ifp_n.fr)).fr)
[PROOFSTEP]
have hfr : (IntFractPair.of (1 / ifp_n.fr)).fr = f := rfl
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc :
(ββ1 / ifp_n.frβ * pA + ppA) / Int.fract (1 / ifp_n.fr) + pA = (pA * (1 / ifp_n.fr) + ppA) / Int.fract (1 / ifp_n.fr)
tmp_calc' :
(ββ1 / ifp_n.frβ * pB + ppB) / Int.fract (1 / ifp_n.fr) + pB = (pB * (1 / ifp_n.fr) + ppB) / Int.fract (1 / ifp_n.fr)
f : K := Int.fract (1 / ifp_n.fr)
f_ne_zero : f β 0
hA : ββ1 / ifp_n.frβ * pA + ppA + pA * f = pA * (1 / ifp_n.fr) + ppA
hB : ββ1 / ifp_n.frβ * pB + ppB + pB * f = pB * (1 / ifp_n.fr) + ppB
hfr : (IntFractPair.of (1 / ifp_n.fr)).fr = f
β’ ((continuantsAux (of v) n).a * ifp_n.fr + (continuantsAux (of v) (n + 1)).a) /
((continuantsAux (of v) n).b * ifp_n.fr + (continuantsAux (of v) (n + 1)).b) =
if (IntFractPair.of (1 / ifp_n.fr)).fr = 0 then
(ββ1 / ifp_n.frβ * (continuantsAux (of v) (n + 1)).a + (continuantsAux (of v) n).a) /
(ββ1 / ifp_n.frβ * (continuantsAux (of v) (n + 1)).b + (continuantsAux (of v) n).b)
else
(ββ1 / ifp_n.frβ * (continuantsAux (of v) (n + 1)).a + (continuantsAux (of v) n).a +
(continuantsAux (of v) (n + 1)).a * (IntFractPair.of (1 / ifp_n.fr)).fr) /
(ββ1 / ifp_n.frβ * (continuantsAux (of v) (n + 1)).b + (continuantsAux (of v) n).b +
(continuantsAux (of v) (n + 1)).b * (IntFractPair.of (1 / ifp_n.fr)).fr)
[PROOFSTEP]
rw [one_div, if_neg _, β one_div, hfr]
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc :
(ββ1 / ifp_n.frβ * pA + ppA) / Int.fract (1 / ifp_n.fr) + pA = (pA * (1 / ifp_n.fr) + ppA) / Int.fract (1 / ifp_n.fr)
tmp_calc' :
(ββ1 / ifp_n.frβ * pB + ppB) / Int.fract (1 / ifp_n.fr) + pB = (pB * (1 / ifp_n.fr) + ppB) / Int.fract (1 / ifp_n.fr)
f : K := Int.fract (1 / ifp_n.fr)
f_ne_zero : f β 0
hA : ββ1 / ifp_n.frβ * pA + ppA + pA * f = pA * (1 / ifp_n.fr) + ppA
hB : ββ1 / ifp_n.frβ * pB + ppB + pB * f = pB * (1 / ifp_n.fr) + ppB
hfr : (IntFractPair.of (1 / ifp_n.fr)).fr = f
β’ ((continuantsAux (of v) n).a * ifp_n.fr + (continuantsAux (of v) (n + 1)).a) /
((continuantsAux (of v) n).b * ifp_n.fr + (continuantsAux (of v) (n + 1)).b) =
(ββ1 / ifp_n.frβ * (continuantsAux (of v) (n + 1)).a + (continuantsAux (of v) n).a +
(continuantsAux (of v) (n + 1)).a * f) /
(ββ1 / ifp_n.frβ * (continuantsAux (of v) (n + 1)).b + (continuantsAux (of v) n).b +
(continuantsAux (of v) (n + 1)).b * f)
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc :
(ββ1 / ifp_n.frβ * pA + ppA) / Int.fract (1 / ifp_n.fr) + pA = (pA * (1 / ifp_n.fr) + ppA) / Int.fract (1 / ifp_n.fr)
tmp_calc' :
(ββ1 / ifp_n.frβ * pB + ppB) / Int.fract (1 / ifp_n.fr) + pB = (pB * (1 / ifp_n.fr) + ppB) / Int.fract (1 / ifp_n.fr)
f : K := Int.fract (1 / ifp_n.fr)
f_ne_zero : f β 0
hA : ββ1 / ifp_n.frβ * pA + ppA + pA * f = pA * (1 / ifp_n.fr) + ppA
hB : ββ1 / ifp_n.frβ * pB + ppB + pB * f = pB * (1 / ifp_n.fr) + ppB
hfr : (IntFractPair.of (1 / ifp_n.fr)).fr = f
β’ Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
[PROOFSTEP]
field_simp [hA, hB]
[GOAL]
case succ.intro.intro.intro.inr.intro.intro.intro.refl.refl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc :
(ββ1 / ifp_n.frβ * pA + ppA) / Int.fract (1 / ifp_n.fr) + pA = (pA * (1 / ifp_n.fr) + ppA) / Int.fract (1 / ifp_n.fr)
tmp_calc' :
(ββ1 / ifp_n.frβ * pB + ppB) / Int.fract (1 / ifp_n.fr) + pB = (pB * (1 / ifp_n.fr) + ppB) / Int.fract (1 / ifp_n.fr)
f : K := Int.fract (1 / ifp_n.fr)
f_ne_zero : f β 0
hA : ββ1 / ifp_n.frβ * pA + ppA + pA * f = pA * (1 / ifp_n.fr) + ppA
hB : ββ1 / ifp_n.frβ * pB + ppB + pB * f = pB * (1 / ifp_n.fr) + ppB
hfr : (IntFractPair.of (1 / ifp_n.fr)).fr = f
β’ ((continuantsAux (of v) n).a * ifp_n.fr + (continuantsAux (of v) (n + 1)).a) /
((continuantsAux (of v) n).b * ifp_n.fr + (continuantsAux (of v) (n + 1)).b) =
((continuantsAux (of v) (n + 1)).a + (continuantsAux (of v) n).a * ifp_n.fr) /
((continuantsAux (of v) (n + 1)).b + (continuantsAux (of v) n).b * ifp_n.fr)
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc :
(ββ1 / ifp_n.frβ * pA + ppA) / Int.fract (1 / ifp_n.fr) + pA = (pA * (1 / ifp_n.fr) + ppA) / Int.fract (1 / ifp_n.fr)
tmp_calc' :
(ββ1 / ifp_n.frβ * pB + ppB) / Int.fract (1 / ifp_n.fr) + pB = (pB * (1 / ifp_n.fr) + ppB) / Int.fract (1 / ifp_n.fr)
f : K := Int.fract (1 / ifp_n.fr)
f_ne_zero : f β 0
hA : ββ1 / ifp_n.frβ * pA + ppA + pA * f = pA * (1 / ifp_n.fr) + ppA
hB : ββ1 / ifp_n.frβ * pB + ppB + pB * f = pB * (1 / ifp_n.fr) + ppB
hfr : (IntFractPair.of (1 / ifp_n.fr)).fr = f
β’ Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
[PROOFSTEP]
ac_rfl
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n : β
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_fract_ne_zero : ifp_n.fr β 0
conts : Pair K := continuantsAux g (n + 2)
pconts : Pair K := continuantsAux g (n + 1)
pconts_eq : pconts = continuantsAux g (n + 1)
ppconts : Pair K := continuantsAux g n
IH : β {ifp_n : IntFractPair K}, IntFractPair.stream v n = some ifp_n β v = compExactValue ppconts pconts ifp_n.fr
ppconts_eq : ppconts = continuantsAux g n
nth_stream_eq' : IntFractPair.stream v n = some ifp_n
ifp_n_fract_ne_zero : ifp_n.fr β 0
succ_nth_stream_eq : IntFractPair.stream v (Nat.succ n) = some (IntFractPair.of ifp_n.frβ»ΒΉ)
ifp_succ_n_fr_ne_zero : Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
s_nth_eq : Stream'.Seq.get? g.s n = some { a := 1, b := ββifp_n.frβ»ΒΉβ }
ppA : K := ppconts.a
ppB : K := ppconts.b
pA : K := pconts.a
pB : K := pconts.b
this : compExactValue ppconts pconts ifp_n.fr = (ppA + ifp_n.frβ»ΒΉ * pA) / (ppB + ifp_n.frβ»ΒΉ * pB)
tmp_calc :
(ββ1 / ifp_n.frβ * pA + ppA) / Int.fract (1 / ifp_n.fr) + pA = (pA * (1 / ifp_n.fr) + ppA) / Int.fract (1 / ifp_n.fr)
tmp_calc' :
(ββ1 / ifp_n.frβ * pB + ppB) / Int.fract (1 / ifp_n.fr) + pB = (pB * (1 / ifp_n.fr) + ppB) / Int.fract (1 / ifp_n.fr)
f : K := Int.fract (1 / ifp_n.fr)
f_ne_zero : f β 0
hA : ββ1 / ifp_n.frβ * pA + ppA + pA * f = pA * (1 / ifp_n.fr) + ppA
hB : ββ1 / ifp_n.frβ * pB + ppB + pB * f = pB * (1 / ifp_n.fr) + ppB
hfr : (IntFractPair.of (1 / ifp_n.fr)).fr = f
β’ Β¬(IntFractPair.of ifp_n.frβ»ΒΉ).fr = 0
[PROOFSTEP]
rwa [inv_eq_one_div, hfr]
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
nth_stream_eq_none : IntFractPair.stream v n = none
β’ v = convergents (of v) (n - 1)
[PROOFSTEP]
induction n with
| zero =>
contradiction
-- IntFractPair.stream v 0 β none
| succ n IH =>
let g := of v
change v = g.convergents n
have : IntFractPair.stream v n = none β¨ β ifp, IntFractPair.stream v n = some ifp β§ ifp.fr = 0 :=
IntFractPair.succ_nth_stream_eq_none_iff.1 nth_stream_eq_none
rcases this with (β¨nth_stream_eq_noneβ© | β¨ifp_n, nth_stream_eq, nth_stream_fr_eq_zeroβ©)
Β· cases' n with n'
Β·
contradiction
-- IntFractPair.stream v 0 β none
Β· have : g.TerminatedAt n' := of_terminatedAt_n_iff_succ_nth_intFractPair_stream_eq_none.2 nth_stream_eq_none
have : g.convergents (n' + 1) = g.convergents n' := convergents_stable_of_terminated n'.le_succ this
rw [this]
exact IH nth_stream_eq_none
Β· simpa [nth_stream_fr_eq_zero, compExactValue] using compExactValue_correctness_of_stream_eq_some nth_stream_eq
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
nth_stream_eq_none : IntFractPair.stream v n = none
β’ v = convergents (of v) (n - 1)
[PROOFSTEP]
induction n with
| zero =>
contradiction
-- IntFractPair.stream v 0 β none
| succ n IH =>
let g := of v
change v = g.convergents n
have : IntFractPair.stream v n = none β¨ β ifp, IntFractPair.stream v n = some ifp β§ ifp.fr = 0 :=
IntFractPair.succ_nth_stream_eq_none_iff.1 nth_stream_eq_none
rcases this with (β¨nth_stream_eq_noneβ© | β¨ifp_n, nth_stream_eq, nth_stream_fr_eq_zeroβ©)
Β· cases' n with n'
Β·
contradiction
-- IntFractPair.stream v 0 β none
Β· have : g.TerminatedAt n' := of_terminatedAt_n_iff_succ_nth_intFractPair_stream_eq_none.2 nth_stream_eq_none
have : g.convergents (n' + 1) = g.convergents n' := convergents_stable_of_terminated n'.le_succ this
rw [this]
exact IH nth_stream_eq_none
Β· simpa [nth_stream_fr_eq_zero, compExactValue] using compExactValue_correctness_of_stream_eq_some nth_stream_eq
[GOAL]
case zero
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
nth_stream_eq_none : IntFractPair.stream v Nat.zero = none
β’ v = convergents (of v) (Nat.zero - 1)
[PROOFSTEP]
| zero =>
contradiction
-- IntFractPair.stream v 0 β none
[GOAL]
case zero
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
nth_stream_eq_none : IntFractPair.stream v Nat.zero = none
β’ v = convergents (of v) (Nat.zero - 1)
[PROOFSTEP]
contradiction
-- IntFractPair.stream v 0 β none
[GOAL]
case succ
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
n : β
IH : IntFractPair.stream v n = none β v = convergents (of v) (n - 1)
nth_stream_eq_none : IntFractPair.stream v (Nat.succ n) = none
β’ v = convergents (of v) (Nat.succ n - 1)
[PROOFSTEP]
| succ n IH =>
let g := of v
change v = g.convergents n
have : IntFractPair.stream v n = none β¨ β ifp, IntFractPair.stream v n = some ifp β§ ifp.fr = 0 :=
IntFractPair.succ_nth_stream_eq_none_iff.1 nth_stream_eq_none
rcases this with (β¨nth_stream_eq_noneβ© | β¨ifp_n, nth_stream_eq, nth_stream_fr_eq_zeroβ©)
Β· cases' n with n'
Β·
contradiction
-- IntFractPair.stream v 0 β none
Β· have : g.TerminatedAt n' := of_terminatedAt_n_iff_succ_nth_intFractPair_stream_eq_none.2 nth_stream_eq_none
have : g.convergents (n' + 1) = g.convergents n' := convergents_stable_of_terminated n'.le_succ this
rw [this]
exact IH nth_stream_eq_none
Β· simpa [nth_stream_fr_eq_zero, compExactValue] using compExactValue_correctness_of_stream_eq_some nth_stream_eq
[GOAL]
case succ
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
n : β
IH : IntFractPair.stream v n = none β v = convergents (of v) (n - 1)
nth_stream_eq_none : IntFractPair.stream v (Nat.succ n) = none
β’ v = convergents (of v) (Nat.succ n - 1)
[PROOFSTEP]
let g := of v
[GOAL]
case succ
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
n : β
IH : IntFractPair.stream v n = none β v = convergents (of v) (n - 1)
nth_stream_eq_none : IntFractPair.stream v (Nat.succ n) = none
g : GeneralizedContinuedFraction K := of v
β’ v = convergents (of v) (Nat.succ n - 1)
[PROOFSTEP]
change v = g.convergents n
[GOAL]
case succ
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
n : β
IH : IntFractPair.stream v n = none β v = convergents (of v) (n - 1)
nth_stream_eq_none : IntFractPair.stream v (Nat.succ n) = none
g : GeneralizedContinuedFraction K := of v
β’ v = convergents g n
[PROOFSTEP]
have : IntFractPair.stream v n = none β¨ β ifp, IntFractPair.stream v n = some ifp β§ ifp.fr = 0 :=
IntFractPair.succ_nth_stream_eq_none_iff.1 nth_stream_eq_none
[GOAL]
case succ
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
n : β
IH : IntFractPair.stream v n = none β v = convergents (of v) (n - 1)
nth_stream_eq_none : IntFractPair.stream v (Nat.succ n) = none
g : GeneralizedContinuedFraction K := of v
this : IntFractPair.stream v n = none β¨ β ifp, IntFractPair.stream v n = some ifp β§ ifp.fr = 0
β’ v = convergents g n
[PROOFSTEP]
rcases this with (β¨nth_stream_eq_noneβ© | β¨ifp_n, nth_stream_eq, nth_stream_fr_eq_zeroβ©)
[GOAL]
case succ.inl
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
n : β
IH : IntFractPair.stream v n = none β v = convergents (of v) (n - 1)
nth_stream_eq_noneβ : IntFractPair.stream v (Nat.succ n) = none
g : GeneralizedContinuedFraction K := of v
nth_stream_eq_none : IntFractPair.stream v n = none
β’ v = convergents g n
[PROOFSTEP]
cases' n with n'
[GOAL]
case succ.inl.zero
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
IH : IntFractPair.stream v Nat.zero = none β v = convergents (of v) (Nat.zero - 1)
nth_stream_eq_noneβ : IntFractPair.stream v (Nat.succ Nat.zero) = none
nth_stream_eq_none : IntFractPair.stream v Nat.zero = none
β’ v = convergents g Nat.zero
[PROOFSTEP]
contradiction
-- IntFractPair.stream v 0 β none
[GOAL]
case succ.inl.succ
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n' : β
IH : IntFractPair.stream v (Nat.succ n') = none β v = convergents (of v) (Nat.succ n' - 1)
nth_stream_eq_noneβ : IntFractPair.stream v (Nat.succ (Nat.succ n')) = none
nth_stream_eq_none : IntFractPair.stream v (Nat.succ n') = none
β’ v = convergents g (Nat.succ n')
[PROOFSTEP]
have : g.TerminatedAt n' := of_terminatedAt_n_iff_succ_nth_intFractPair_stream_eq_none.2 nth_stream_eq_none
[GOAL]
case succ.inl.succ
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n' : β
IH : IntFractPair.stream v (Nat.succ n') = none β v = convergents (of v) (Nat.succ n' - 1)
nth_stream_eq_noneβ : IntFractPair.stream v (Nat.succ (Nat.succ n')) = none
nth_stream_eq_none : IntFractPair.stream v (Nat.succ n') = none
this : TerminatedAt g n'
β’ v = convergents g (Nat.succ n')
[PROOFSTEP]
have : g.convergents (n' + 1) = g.convergents n' := convergents_stable_of_terminated n'.le_succ this
[GOAL]
case succ.inl.succ
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n' : β
IH : IntFractPair.stream v (Nat.succ n') = none β v = convergents (of v) (Nat.succ n' - 1)
nth_stream_eq_noneβ : IntFractPair.stream v (Nat.succ (Nat.succ n')) = none
nth_stream_eq_none : IntFractPair.stream v (Nat.succ n') = none
thisβ : TerminatedAt g n'
this : convergents g (n' + 1) = convergents g n'
β’ v = convergents g (Nat.succ n')
[PROOFSTEP]
rw [this]
[GOAL]
case succ.inl.succ
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
g : GeneralizedContinuedFraction K := of v
n' : β
IH : IntFractPair.stream v (Nat.succ n') = none β v = convergents (of v) (Nat.succ n' - 1)
nth_stream_eq_noneβ : IntFractPair.stream v (Nat.succ (Nat.succ n')) = none
nth_stream_eq_none : IntFractPair.stream v (Nat.succ n') = none
thisβ : TerminatedAt g n'
this : convergents g (n' + 1) = convergents g n'
β’ v = convergents g n'
[PROOFSTEP]
exact IH nth_stream_eq_none
[GOAL]
case succ.inr.intro.intro
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
n : β
IH : IntFractPair.stream v n = none β v = convergents (of v) (n - 1)
nth_stream_eq_none : IntFractPair.stream v (Nat.succ n) = none
g : GeneralizedContinuedFraction K := of v
ifp_n : IntFractPair K
nth_stream_eq : IntFractPair.stream v n = some ifp_n
nth_stream_fr_eq_zero : ifp_n.fr = 0
β’ v = convergents g n
[PROOFSTEP]
simpa [nth_stream_fr_eq_zero, compExactValue] using compExactValue_correctness_of_stream_eq_some nth_stream_eq
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
terminates : Terminates (of v)
β’ βαΆ (n : β) in atTop, v = convergents (of v) n
[PROOFSTEP]
rw [eventually_atTop]
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
terminates : Terminates (of v)
β’ β a, β (b : β), b β₯ a β v = convergents (of v) b
[PROOFSTEP]
obtain β¨n, terminated_at_nβ© : β n, (of v).TerminatedAt n
[GOAL]
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
n : β
instβ : FloorRing K
terminates : Terminates (of v)
β’ β n, TerminatedAt (of v) n
case intro
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
terminates : Terminates (of v)
n : β
terminated_at_n : TerminatedAt (of v) n
β’ β a, β (b : β), b β₯ a β v = convergents (of v) b
[PROOFSTEP]
exact terminates
[GOAL]
case intro
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
terminates : Terminates (of v)
n : β
terminated_at_n : TerminatedAt (of v) n
β’ β a, β (b : β), b β₯ a β v = convergents (of v) b
[PROOFSTEP]
use n
[GOAL]
case h
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
terminates : Terminates (of v)
n : β
terminated_at_n : TerminatedAt (of v) n
β’ β (b : β), b β₯ n β v = convergents (of v) b
[PROOFSTEP]
intro m m_geq_n
[GOAL]
case h
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
terminates : Terminates (of v)
n : β
terminated_at_n : TerminatedAt (of v) n
m : β
m_geq_n : m β₯ n
β’ v = convergents (of v) m
[PROOFSTEP]
rw [convergents_stable_of_terminated m_geq_n terminated_at_n]
[GOAL]
case h
K : Type u_1
instβΒΉ : LinearOrderedField K
v : K
nβ : β
instβ : FloorRing K
terminates : Terminates (of v)
n : β
terminated_at_n : TerminatedAt (of v) n
m : β
m_geq_n : m β₯ n
β’ v = convergents (of v) n
[PROOFSTEP]
exact of_correctness_of_terminatedAt terminated_at_n
|
Require Import GenGraph.
Require Import fintype.
Require Import SetoidList List.
Require Import FunctionalExtensionality.
Ltac in_inv :=
simpl in *;
match goal with
| H : InA ?eq ?elt nil |- _ =>
inversion H
| H : InA ?eq ?x (?h::?t) |- _ =>
inversion H; subst
end.
Ltac solve_InA_In :=
match goal with
| H : InA eq ?x ?l |- In ?x ?l =>
apply In_InAeq_iff; auto
| H : In ?x ?l |- InA eq ?x ?l =>
apply In_InAeq_iff; auto
end.
Lemma equivlistAeq_refl : forall A eqA (a : list A) ,
Equivalence eqA ->
equivlistA eqA a a.
Proof.
split; intros; auto.
Qed.
Ltac rewrite_equiv :=
match goal with
| H : equivlistA eq ?s ?s' |- _ =>
rewrite H in *
| H : equivlistA eq (_::?s) nil |- _ =>
apply equivlistA_cons_nil in H; [exfalso; exact H |typeclasses eauto]
| |- equivlistA eq ?a ?a =>
apply equivlistAeq_refl; try typeclasses eauto
end.
Hint Extern 1 => in_inv : equiv.
Hint Extern 1 => rewrite_equiv; auto : equiv.
Hint Extern 1 => solve_InA_In : equiv.
Hint Constructors InA.
Section AllMIS.
Variable T : Type.
Variable Tdec : forall t1 t2 : T, {t1 = t2} + {t1 <> t2}.
Lemma map_InA_cons : forall s' a s,
InA (equivlistA eq) s' (map (fun l1 : list T => a :: l1) s) ->
InA eq a s'.
Proof.
intros.
{
induction s; simpl in H; auto with equiv.
}
Qed.
Lemma inA_map_iff:
forall (A B : Type) (f : A -> B) (l : list A) (y : B)
(eqB : relation B)
(eqA : relation A),
(* (forall a, Proper (eqA ==> flip impl) (eq (f a))) -> *)
Proper (eqA ==> eqB) f ->
Equivalence eqA ->
Equivalence eqB ->
InA eqB y (map f l) <-> (exists x : A, eqB (f x) y /\ InA eqA x l).
Proof.
intros A B f l y eqB eqA Hprop Aeq Beq.
split; intros H0.
{
induction l; eauto with equiv.
+
simpl in H0.
inversion H0.
{
subst.
exists a.
split; auto.
{
apply eqasym; auto with equiv.
}
{
left; auto.
apply Aeq.
(* apply IHl in H1; eauto. *)
(* destruct H2; eauto. *)
(* exists x; eauto. *)
(* intuition. *)
}
}
{
subst.
apply IHl in H1; eauto.
destruct H1; eauto.
exists x; eauto.
intuition.
}
}
{
induction l; eauto with equiv.
{
simpl in *.
destruct H0; intuition.
}
{
simpl.
destruct H0.
destruct H; auto.
inversion H0; subst; eauto.
left.
rewrite <- H2.
apply Beq; auto.
}
}
Qed.
Lemma remove_NotIn_Id :
forall a x, ~InA eq a x ->
remove Tdec a (a :: x) = x.
intros a0 x Hnot.
simpl.
destruct Tdec; subst; auto.
{
{
induction x; auto with equiv.
simpl.
destruct Tdec; subst; auto with equiv.
exfalso; auto.
rewrite IHx; auto.
}
}
{
contradiction.
}
Qed.
Lemma equivlistA_remove : forall a x s' s,
equivlistA eq (a :: x) s' ->
InA eq x s ->
~ InA eq a x ->
equivlistA eq x (remove Tdec a s').
Proof.
intros.
replace (remove Tdec a s') with
(removeA Tdec a s') by
(unfold removeA; auto).
apply removeA_equivlistA; auto; typeclasses eauto.
Qed.
Lemma InAeq_InAequivlistA : forall A (x : list A) (s : list (list A)),
InA eq x s ->
InA (equivlistA eq) x s.
Proof.
induction s; intros; auto with equiv.
Qed.
Lemma map_cons : forall (s' : list T) (a : T) (s : list (list T)),
InA (equivlistA eq) s' (map (fun l1 : list T => a :: l1) s) <->
InA eq a s' /\
(InA (equivlistA eq) s' s \/ InA (equivlistA eq) (remove Tdec a s') s).
Proof.
intros.
split; intros; auto.
{
split.
{
eapply map_InA_cons; eauto.
}
{
rewrite inA_map_iff in H; try typeclasses eauto; auto.
destruct H.
destruct H; subst.
destruct (InA_dec Tdec a x).
{
left.
rewrite <- H.
induction s; [inversion H0| ].
inversion H0; subst.
auto with equiv.
left; auto.
rewrite H.
{
split; intros; auto with equiv.
{
rewrite <- H in H1.
inversion H1; subst; auto.
}
{
rewrite <- H; auto.
}
}
auto with equiv.
}
{
assert (equivlistA eq x (remove Tdec a s')) by
(eapply equivlistA_remove; eauto).
right.
rewrite <- H1.
clear -H0.
apply InAeq_InAequivlistA; auto.
}
}
}
{
destruct H.
destruct H0.
{
apply inA_map_iff with (eqA := (equivlistA eq)) ; try typeclasses eauto.
{
do 2 red; intros.
rewrite H1; auto with equiv.
}
exists s'.
split; auto.
{
split; intros; auto with equiv.
}
}
apply inA_map_iff with (eqA := (equivlistA eq));
try typeclasses eauto.
{
do 2 red; intros;
rewrite H1; auto with equiv.
}
{
exists (remove Tdec a s').
split; auto with equiv.
clear - H.
{
replace (remove Tdec a s') with
(removeA Tdec a s') by
(unfold removeA; auto).
destruct (InA_dec Tdec a s').
{
split; intros; auto with equiv.
{
inversion H0; subst; auto with equiv.
+
apply removeA_InA in H2; try typeclasses eauto.
destruct H2.
auto.
}
{
destruct (Tdec x a); subst; auto.
right.
apply removeA_InA; try typeclasses eauto.
split; auto with equiv.
}
}
{
split; intros; auto with equiv.
{
inversion H0; subst; auto with equiv.
+
apply removeA_InA in H2; try typeclasses eauto.
destruct H2.
contradiction.
}
{
right.
apply removeA_InA; try typeclasses eauto.
split; auto.
}
}
}
}
}
Qed.
Lemma all_subsets_list_subset :
forall (l l0 : list T),
InA (equivlistA eq) l0 (fintype.all_subsets l) <-> (forall x, InA eq x l0 -> InA eq x l).
Proof.
intros.
generalize dependent l0.
induction l.
{
split; intros.
{
simpl in H.
inversion H; subst;
try rewrite H2 in H0.
inversion H0.
inversion H2.
}
destruct l0.
simpl; left; auto.
{
constructor; intros; auto.
}
assert (InA eq t nil).
apply H; left; auto.
inversion H0.
}
intros.
simpl.
rewrite InA_app_iff.
rewrite map_cons.
do 2 rewrite IHl.
split; intros.
{
intuition.
destruct (Tdec x a).
subst; auto with equiv.
right.
apply H1.
rewrite In_InAeq_iff.
apply remove_mem; intuition.
}
{
destruct (InA_dec Tdec a l0); auto with equiv.
{
right.
intuition.
{
right.
intros.
auto with equiv.
apply In_InAeq_iff in H0.
apply remove_mem in H0.
destruct H0; auto with equiv.
simpl in *.
apply In_InAeq_iff in H0.
apply H in H0.
inversion H0;
intuition.
}
}
{
clear - H n.
left.
intros.
destruct (Tdec x a).
subst.
contradiction.
apply H in H0.
inversion H0.
subst.
contradiction.
auto.
}
}
Qed.
Hint Constructors NoDup.
Hint Constructors NoDupA.
Lemma NoDupA_map : forall a l,
(forall sub : list T,
InA (equivlistA eq) sub l -> ~ InA eq a sub) ->
NoDupA (equivlistA eq) l ->
NoDupA (equivlistA eq)
(map (fun l0 : list T => a :: l0) l).
Proof.
intros.
induction H0.
simpl in *.
auto.
{
simpl.
constructor; auto.
intros Hnot.
rewrite inA_map_iff in Hnot; try typeclasses eauto; eauto.
destruct Hnot.
destruct H2.
clear IHNoDupA.
assert (~ InA eq a x).
{
apply H; left; auto.
apply equivlistAeq_refl; try typeclasses eauto.
}
assert (~ InA eq a x0).
{
apply H.
right; auto.
apply InAeq_InAequivlistA; auto.
}
assert (equivlistA eq x0 x).
{
red in H2.
split; intros; eauto.
+
assert (InA eq x1 (a :: x)).
apply H2; auto.
inversion H7; subst; eauto.
contradiction.
+
assert (InA eq x1 (a :: x0)).
apply H2; auto.
inversion H7; subst; eauto.
contradiction.
}
apply H0.
rewrite<- H6.
apply InAeq_InAequivlistA; auto.
}
Qed.
Lemma no_dups_powerset :
forall (A : Type) (l: list T),
NoDup l ->
NoDupA (equivlistA eq) (fintype.all_subsets l).
Proof.
intros.
pose proof (map_cons).
assert (forall l (a : T) (s : list (list T)),
InA (equivlistA eq) l (map (fun l1 : list T => a :: l1) s) ->
InA eq a l /\
(InA (equivlistA eq) l s \/
InA (equivlistA eq) (remove Tdec a l) s)).
intros.
apply H0; auto.
clear H0.
induction l.
simpl.
apply NoDupA_singleton.
simpl.
apply SetoidList.NoDupA_app; try typeclasses eauto; eauto.
{
apply IHl; auto.
inversion H; subst; auto.
}
{
inversion H; subst.
apply IHl in H4.
apply NoDupA_map; auto.
intros.
clear -H3 H0 Tdec.
induction l.
simpl in H0.
inversion H0; subst; auto with equiv.
{
rewrite all_subsets_list_subset in H0.
intros Hnot.
apply H0 in Hnot.
apply In_InAeq_iff in Hnot.
contradiction.
}
}
{
inversion H; subst.
intros.
apply map_cons in H2.
destruct H2; eauto.
destruct H5; eauto.
{
rewrite all_subsets_list_subset in H0.
assert (InA eq a l) by auto.
apply In_InAeq_iff in H6.
contradiction.
}
{
rewrite all_subsets_list_subset in H0.
assert (InA eq a l).
auto.
apply In_InAeq_iff in H6; eauto.
}
}
Qed.
Definition Teq (t1 t2 : T) :=
match Tdec t1 t2 with
| left _ => true
| right _ => false
end.
Require Import Bool.
Definition list_mem (x : T) (l : list T) : bool :=
existsb (fun elt => if Tdec elt x then true else false) l.
Definition IndependentProg (G : @GenGraph T) (x : list T) :
bool :=
forallb (fun v1 => (forallb
(fun v2 => negb (existsb
(fun edge =>
Teq (fst edge) v1 &&
Teq (snd edge) v2)
(gE _ G))) x)) x.
Definition ValidSetProg (G : @GenGraph T) (x : list T) :=
forallb (fun elt => list_mem elt (gV _ G)) x.
Definition MaximalIndSetProg (G : @GenGraph T) (x : list T) :
bool :=
(ValidSetProg G x) &&
(IndependentProg G x) &&
(forallb (fun v1 => if negb (list_mem v1 x) then
(existsb (fun edge =>
Teq (fst edge) v1 &&
Teq v1 (fst edge) &&
(list_mem (snd edge) x) &&
(list_mem (snd edge) (gV T G)))
(gE _ G))
else
true) (gV _ G)).
(* forall x y : T, In x l -> In y l -> ~ In (x, y) (gE T G) *)
(* IndSet_E G l -> *)
(* (forall x : T, *)
(* In x (gV T G) -> *)
(* ~ In x l -> *)
(* exists y : T, *)
(* In y (gV T G) /\ In y l /\ In (x, y) (gE T G)) -> *)
(* MaximalIndSet_E G l *)
Lemma list_mem_In : forall x1 x,
In x1 x <-> list_mem x1 x = true.
Proof.
split;
intros.
{
unfold list_mem.
apply existsb_exists.
exists x1; intuition.
destruct Tdec; subst; auto.
}
{
unfold list_mem in H.
apply existsb_exists in H.
destruct H.
destruct H; auto.
destruct Tdec; subst; auto.
discriminate.
}
Qed.
Lemma forallb_false1
(f: T -> bool)
(l: list T) :
forallb f l = false ->
(exists x: T, In x l /\ f x = false).
Proof.
induction l.
{ inversion 1. }
simpl.
rewrite andb_false_iff.
intros H.
destruct H.
{ exists a; split; auto. }
destruct (IHl H) as [x [H3 H4]].
exists x; split; auto.
Qed.
Lemma forallb_false2
(f: T -> bool)
(l: list T) :
(exists x: T, In x l /\ f x = false) ->
forallb f l = false.
Proof.
induction l.
{ intros [x [A B]]. inversion A. }
intros [x [A B]].
simpl.
inversion A.
{ subst.
rewrite B; auto. }
rewrite andb_false_iff; right.
apply IHl.
exists x.
split; auto.
Qed.
Lemma forallb_false
(f: T -> bool)
(l: list T) :
forallb f l = false <->
(exists x: T, In x l /\ f x = false).
Proof. split. apply forallb_false1. apply forallb_false2. Qed.
Lemma forallb_equivlistA
(f: T -> bool)
(l1 l2: list T)
(H: equivlistA eq l1 l2) :
forallb f l1 = forallb f l2.
Proof.
destruct (forallb f l2) eqn:H2.
{ rewrite forallb_forall; intros x Hin.
{ destruct (H x) as [A B].
rewrite forallb_forall in H2.
apply H2; auto.
rewrite <-In_InAeq_iff; apply A; rewrite In_InAeq_iff; auto. }}
rewrite forallb_false in H2.
destruct H2 as [x [Hin H3]].
rewrite forallb_false.
exists x; split; auto.
destruct (H x); rewrite <-In_InAeq_iff; apply H1; rewrite In_InAeq_iff; auto.
Qed.
Lemma existsb_demorgan
(A: Type)
(f: A -> bool)
(l: list A) :
existsb f l = negb (forallb (fun x => negb (f x)) l).
Proof.
induction l; auto.
simpl.
rewrite negb_andb, negb_involutive.
f_equal.
rewrite IHl; auto.
Qed.
Lemma existsb_equivlistA
(f: T -> bool)
(l1 l2: list T)
(H: equivlistA eq l1 l2) :
existsb f l1 = existsb f l2.
Proof.
do 2 rewrite existsb_demorgan.
f_equal.
apply forallb_equivlistA; auto.
Qed.
Lemma Teq_refl (x: T): Teq x x = true.
Proof.
unfold Teq.
destruct (Tdec x x); auto.
Qed.
Lemma Teq_eq (x y: T): Teq x y = true -> x=y.
Proof.
unfold Teq.
destruct (Tdec x y); auto.
inversion 1.
Qed.
Lemma MaxProg_iff :forall G x, MaximalIndSetProg G x = true <->
MaximalIndSet_E G x.
Proof.
split; intros.
unfold MaximalIndSetProg in H.
unfold IndependentProg in H.
destruct G.
simpl in *.
rewrite andb_true_iff in H.
rewrite andb_true_iff in H.
do 2 destruct H.
unfold ValidSetProg in H.
rewrite forallb_forall in H0,H,H1.
induction gV; simpl in *; auto.
{
constructor; eauto.
{
constructor; auto.
{
red; intros.
simpl in *.
apply H in H2; discriminate.
}
{
red; intros.
simpl.
intros Hnot.
apply gE_subset_l in Hnot.
exact Hnot.
}
}
{
intros.
simpl in *.
inversion H2.
}
}
{
constructor.
{
constructor.
{
red; intros.
simpl.
specialize (H _ H2).
destruct (Tdec a x0).
{ subst; auto. }
rewrite orb_false_l in H.
unfold list_mem in H.
rewrite existsb_exists in H.
destruct H as [y [Hx Hy]].
right.
destruct (Tdec y x0).
{ subst; auto. }
inversion Hy.
}
red; intros.
simpl.
intros Hnot.
specialize (gE_subset_l _ _ Hnot).
generalize (H _ H2).
generalize (H _ H3).
destruct gE_subset_l.
{ subst.
destruct (Tdec x0 x0); intros A B; try inversion B. clear B.
destruct (Tdec x0 y).
{ clear A.
subst.
eapply gE_irref; eauto. }
rewrite orb_false_l in A.
unfold list_mem in A.
rewrite existsb_exists in A. destruct A as [z [Hz1 Hz2]].
destruct (Tdec z y); try inversion Hz2.
subst. clear Hz2.
clear e.
generalize (H1 _ H2).
generalize (H1 _ H3).
do 2 rewrite forallb_forall.
intros A B.
specialize (A _ H2).
specialize (B _ H3).
rewrite negb_true_iff in A, B.
clear A.
assert (B' : existsb (fun edge : T * T => Teq (fst edge) x0 && Teq (snd edge) y) gE = true).
{ rewrite existsb_exists.
exists (x0,y).
split; auto.
simpl.
rewrite andb_true_iff.
split.
unfold Teq; destruct (Tdec _ _); auto.
unfold Teq; destruct (Tdec _ _); auto. }
rewrite B' in B; congruence.
apply n; auto. }
generalize (H1 _ H2). intros A.
generalize (H1 _ H3). intros B.
rewrite forallb_forall in A, B.
specialize (A _ H3).
rewrite existsb_demorgan, negb_involutive, forallb_forall in A.
specialize (A (x0,y) Hnot). simpl in A. rewrite negb_true_iff in A.
rewrite andb_false_iff in A. exfalso. destruct A as [A|A]; rewrite Teq_refl in A; congruence. }
simpl.
intros x0 [A|A]; intros B.
{ subst.
specialize (H0 x0 (or_introl _ eq_refl)).
assert (C: negb (list_mem x0 x) = true).
{ unfold list_mem; rewrite existsb_demorgan, negb_involutive, forallb_forall.
intros x1 Hin.
destruct (Tdec x1 x0); auto.
subst. exfalso; apply B; auto.
}
rewrite C in H0.
rewrite existsb_exists in H0.
destruct H0 as [[a b] [X Y]].
simpl in Y.
do 3 rewrite andb_true_iff in Y.
destruct Y as [[[Z1 Z2] Y1b] Y2].
apply Teq_eq in Z1.
apply Teq_eq in Z2.
subst.
clear Z2.
exists b.
split.
{ right.
destruct (gE_subset_l _ _ (gE_symm _ _ X)); auto.
subst. exfalso; apply (gE_irref _ X). }
split; auto.
unfold list_mem in Y1b.
rewrite existsb_exists in Y1b. destruct Y1b as [xx [Q R]].
destruct (Tdec xx b). subst. auto. congruence. }
{ specialize (H0 x0 (or_intror _ A)).
assert (C: negb (list_mem x0 x) = true).
{ unfold list_mem; rewrite existsb_demorgan, negb_involutive, forallb_forall.
intros x1 Hin.
destruct (Tdec x1 x0); auto.
subst. exfalso; apply B; auto.
}
rewrite C in H0.
rewrite existsb_exists in H0.
destruct H0 as [[aa b] [X Y]].
simpl in Y.
do 3 rewrite andb_true_iff in Y.
destruct Y as [[[Z1 Z2] Y1b] Y2].
apply Teq_eq in Z1.
apply Teq_eq in Z2.
subst.
clear Z2.
exists b.
split.
{ apply (gE_subset_l _ _ (gE_symm _ _ X)).
}
split; auto.
unfold list_mem in Y1b.
rewrite existsb_exists in Y1b. destruct Y1b as [xx [Q R]].
destruct (Tdec xx b). subst. auto. congruence. }
}
inversion H.
unfold MaximalIndSetProg.
destruct G; simpl in *.
do 2 rewrite andb_true_iff.
split.
{
split.
{
unfold ValidSetProg.
rewrite forallb_forall.
intros.
inversion H0.
red in H3.
apply H3 in H2.
clear -H2.
simpl in *.
unfold list_mem.
apply existsb_exists; auto.
exists x0.
split; auto.
destruct Tdec; subst; auto.
}
{
unfold IndependentProg.
rewrite forallb_forall.
intros.
rewrite forallb_forall.
intros.
simpl.
inversion H0.
red in H5.
clear -H5 H2 H3.
simpl in H5.
specialize (H5 x0 x1 H2 H3).
destruct ((existsb
(fun edge : T * T => Teq (fst edge) x0 && Teq (snd edge) x1) gE))
eqn:N.
{
rewrite existsb_exists in N.
destruct N; auto.
destruct H.
rewrite andb_true_iff in H0.
destruct H0.
unfold Teq in *.
destruct (Tdec (fst x2) x0); subst; auto.
destruct (Tdec (snd x2) x1); subst; auto.
exfalso.
apply H5.
destruct x2; auto.
}
{
auto.
}
}
}
{
rewrite forallb_forall.
intros.
destruct (negb (list_mem x0 x)) eqn:N; auto.
unfold negb in N.
unfold list_mem in N.
destruct (existsb (fun elt : T => if Tdec elt x0 then true else false) x) eqn:Hn.
{
discriminate.
}
assert ( ~ In x0 x).
{
clear -Hn.
intros Hnot.
assert ((exists x' , In x' x /\
(if Tdec x' x0 then true else false) = true)).
exists x0.
split; auto.
{
destruct Tdec; subst; auto.
}
apply existsb_exists in H.
rewrite Hn in H.
discriminate.
}
{
apply H1 in H3; auto.
{
clear -H3.
apply existsb_exists.
destruct H3.
exists (x0,x1).
simpl.
intuition.
unfold Teq.
destruct (Tdec x0 x0); subst; simpl; auto.
apply list_mem_In in H.
apply list_mem_In in H0.
rewrite H0,H.
auto.
}
}
}
Qed.
Definition AllMIS (G : @GenGraph T) :=
filter (fun x => MaximalIndSetProg G x) (fintype.all_subsets (gV _ G)).
Lemma MaximalIndSetProg_equivlistA
(G : GenGraph T)
(x : list T)
(H : MaximalIndSet_E G x)
(x0 y : list T)
(H0 : equivlistA eq x0 y) :
MaximalIndSetProg G x0 = MaximalIndSetProg G y.
Proof.
unfold MaximalIndSetProg.
f_equal.
{
f_equal.
{ unfold ValidSetProg.
apply forallb_equivlistA; auto. }
unfold IndependentProg.
rewrite (forallb_equivlistA _ x0 y); auto.
f_equal.
apply functional_extensionality; intros x1.
rewrite (forallb_equivlistA _ x0 y); auto.
}
f_equal.
apply functional_extensionality; intros x1.
unfold list_mem.
rewrite (existsb_equivlistA _ x0 y); auto.
destruct (negb _); auto.
f_equal.
apply functional_extensionality; intros x2.
f_equal.
f_equal.
apply existsb_equivlistA; auto.
Qed.
Lemma AllMIS_spec : forall G,
MIS_set_gGraph G (AllMIS G).
Proof.
unfold AllMIS.
constructor.
intros.
apply filter_In in H.
destruct H.
apply MaxProg_iff.
auto.
apply filter_NoDupA.
assert (NoDup (gV T G)).
{
destruct G; auto.
}
{
apply no_dups_powerset in H; auto.
}
intros.
apply filter_InA.
{
red.
red.
intros.
eapply MaximalIndSetProg_equivlistA; eauto.
}
split.
{
destruct G.
simpl in *.
assert (forall x0 : T, In x0 x -> In x0 gV).
{
inversion H; intuition; simpl in *; subst.
inversion H0; subst.
simpl in *.
unfold valid_E in H3.
simpl in *.
clear -H3 H2.
apply H3.
auto.
}
apply all_subsets_list_subset; auto.
intros.
rewrite In_InAeq_iff.
apply H0; auto.
apply In_InAeq_iff.
auto.
}
{
apply MaxProg_iff; auto.
}
Qed.
Lemma MIS_exists :
forall G,
exists (l : list (list T)), MIS_set_gGraph G l.
Proof.
intros.
exists (AllMIS G).
apply AllMIS_spec.
Qed.
End AllMIS.
|
function [ beta ] =upadte_beta( H,W,K,grt)
Hc=H*W;
He=abs(Hc).^2;
%% update beta
beta=zeros(1,K);
for k0=1:K
tmp=Hc(k0,:);
tmpe=He(k0,:);
beta(k0)=sqrt(grt(k0))*tmp(k0)/(sum(tmpe)+1);
end
end
|
#---
#title: "Analyzing Age structures in IC"
#author: "Youen Vermard"
#date: '`r date()`'
#output: pdf_document
#---
#### ONLY PIECE TO BE CHANGED working directories
wd <- "~/git/ices-dk/interCatchSummary/"
output_wd <- "~/git/ices-dk/interCatchSummary/"
#This documet uses Table 2 from CatchAndSampleDataTables.txt from the InterCatch outputs to describe the raising procedures that were made.
### libraries
library(data.table)
library(gplots)
library(pander);library(captioner)
library(lattice)
#initialise les fonctions pour lΓ©gender tables et figures
### read the data
test <- scan(paste(wd,"CatchAndSampleDataTables.txt",sep=""),what='character',sep='\t')
table2 <- test[(which(test=="TABLE 2.")+3):length(test)]
tmp<-table2[-c(1:56)]
table2_bis<-data.frame(matrix(tmp,ncol=27,byrow=T), stringsAsFactors =F)
colnames(table2_bis) <- table2[1:27]
table2_bis <- data.table(table2_bis)
table2_bis <- table2_bis[,CATON:=as.numeric(as.character(CATON))]
table2_bis <- table2_bis[,CANUM:=as.numeric(as.character(CANUM))]
table2_bis <- table2_bis[,WECA:=as.numeric(as.character(WECA))]
table2_bis <- table2_bis[,AgeOrLength:=as.numeric(as.character(AgeOrLength))]
table2_bis <- table2_bis[,Area:=as.factor(Area)]
table2_bis <- table2_bis[,Fleet:=factor(Fleet)]
table2_bis <- table2_bis[,Season:=factor(Season)]
table2_bis <- table2_bis[,Country:=factor(Country)]
table2_bis <- table2_bis[,id:=paste(Stock,Country,Area,Season,Fleet)]
table2_bis[Area=="IIIaN ",'Area'] <- "IIIaN"
colnames(table2_bis)[colnames(table2_bis)=='CATONRaisedOrImported'] <- 'RaisedOrImported'
## simple stats on imported data
SummaryReport <- table2_bis[,list(CATON=sum(CANUM*WECA)/1000000), by=c('CatchCategory','RaisedOrImported')]
SummaryReport <- SummaryReport[, perc:=round(CATON/sum(CATON)*100), by='CatchCategory']
SummaryReport <- SummaryReport[order(CatchCategory),]
SOP <- table2_bis[,list(SOP=sum(CANUM*WECA)/1000, CATON=sum(unique(CATON))), by=c('CatchCategory')]
SOP <-SOP[,list(SOP=SOP/CATON), by=c('CatchCategory')]
SampledOrEstimated <- table2_bis[,list(CATON=sum(CANUM*WECA/1000000)), by=c('CatchCategory','RaisedOrImported','SampledOrEstimated')]
SampledOrEstimated <- SampledOrEstimated[, perc:=round(CATON/sum(CATON)*100), by='CatchCategory']
SampledOrEstimated <- SampledOrEstimated[order(CatchCategory, perc, decreasing=T),]
SampledOrEstimatedArea <- table2_bis[,list(CATON=sum(CANUM*WECA/1000000)), by=c('CatchCategory','RaisedOrImported','SampledOrEstimated','Area')]
SampledOrEstimatedArea <- SampledOrEstimatedArea[, perc:=round(CATON/sum(CATON)*100), by=c('CatchCategory','Area')]
SampledOrEstimatedArea <- SampledOrEstimatedArea[order(Area, CatchCategory,perc, decreasing=T),]
### landings with associated discards
landingsWithAssociatedDiscards <- table2_bis[,list(CATON=sum(CANUM*WECA/1000000)), by=c('id','RaisedOrImported','CatchCategory')]
tmp <- landingsWithAssociatedDiscards[(RaisedOrImported=="Imported_Data" & CatchCategory=="Discards") , id]
landingsWithAssociatedDiscards <- landingsWithAssociatedDiscards[id%in%tmp & CatchCategory=="Landings", sum(CATON)]/table2_bis[CatchCategory=="Landings",sum(CANUM*WECA/1000000)]
## summary of the catch per gear
table2_bis <- table2_bis[, Gear:=substr(table2_bis$Fleet,1,3)]
summCatchPerGear <- table2_bis[, list(sumCatch=sum(CANUM*WECA/1000000)), by=c('Stock','Gear')]
summCatchPerGear <- summCatchPerGear[, percCatch:=sumCatch/sum(sumCatch)*100, by=c('Stock')]
summCatchPerGear <- summCatchPerGear[ order(percCatch,decreasing=T),]
### Age Structure
listVAR <- c("CatchCategory",'RaisedOrImported',"SampledOrEstimated","Country","Area","Season","Fleet")
## By Sex
listVAR <- c("CatchCategory",'RaisedOrImported',"SampledOrEstimated","Country","Area","Season","Fleet","Sex")
#table2_bis <- table2_bis[CANUM>0,]
AgeStrucSex <- table2_bis[,meanAge:=weighted.mean(AgeOrLength,CANUM, na.rm=T), by=c(listVAR)]
plotFunction <- function(AgeStrucSexLan,Estim,Sampled){
if(unique(AgeStrucSexLan$AgeOrLengthType)=="Lngt") AgeTit <- "Length" else AgeTit <- "Age"
plotTitle <- paste("Mean", AgeTit, "in the", catchCat, "by", Var, sep=" ")
Formula <-paste('meanAge~',Var, sep="")
boxplot(eval(parse(text=Formula)), data=AgeStrucSexLan,
boxwex = 0.25, at = which(pos%in%unique(AgeStrucSexLan[,which(colnames(Sampled)==Var)])) + 0.3,
col = "red",
main = plotTitle,
xlab = "",
ylab = paste("Mean ",AgeTit, sep=""),
xlim = c(0.5, length(unique(AgeStrucSexLan[,which(colnames(Sampled)==Var)]))+.5), ylim = c(min(AgeStrucSexLan$AgeOrLength), max(AgeStrucSexLan$AgeOrLength)), yaxs = "i", xaxt='n')
boxplot(eval(parse(text=Formula)), data=Estim, add=TRUE,
boxwex = 0.25, at = which(pos%in%unique(Estim[,which(colnames(Sampled)==Var)])),
col = "orange")
boxplot(eval(parse(text=Formula)), data=Sampled, add=TRUE,
boxwex = 0.25, at = which(pos%in%unique(Sampled[,which(colnames(Sampled)==Var)])) - 0.3,
col = "yellow", xaxt='n')
legend(1, max(AgeStrucSexLan$AgeOrLength), c("Imported", "Raised", "All"),
fill = c("yellow", "orange", "red"))
}
plotFunctionMeanWeight <- function(AgeStrucSexLan=AgeStrucSexLan,Estim=Estim,Sampled=Sampled){
if(unique(AgeStrucSexLan$AgeOrLengthType)=="Lngt") AgeTit <- "Length" else AgeTit <- "Age"
plotTitle <- paste("Mean", AgeTit, "in the", catchCat, "by", Var, sep=" ")
AgeStrucSexLan <- data.frame(AgeStrucSexLan)
AgeStrucSexLan[,which(colnames(AgeStrucSexLan)==Var)] <- factor(AgeStrucSexLan[,which(colnames(AgeStrucSexLan)==Var)])
pos <- levels(AgeStrucSexLan[,which(colnames(AgeStrucSexLan)==Var)])
Estim <- AgeStrucSexLan[which(AgeStrucSexLan$SampledOrEstimated=='Estimated_Distribution'),]
Estim[,which(colnames(Estim)==Var)] <- factor(Estim[,which(colnames(Estim)==Var)])
Sampled <- AgeStrucSexLan[which(AgeStrucSexLan$SampledOrEstimated=='Sampled_Distribution'),]
Sampled[,which(colnames(Sampled)==Var)] <- factor(Sampled[,which(colnames(Sampled)==Var)])
Formula <-paste('WECA~',Var, sep="")
boxplot(eval(parse(text=Formula)), data=AgeStrucSexLan,
boxwex = 0.25, at = which(pos%in%unique(AgeStrucSexLan[,which(colnames(Sampled)==Var)])) + 0.3,
col = "red",
main = plotTitle,
xlab = "",
ylab = paste("Mean ",AgeTit, sep=""),
xlim = c(0.5, length(unique(AgeStrucSexLan[,which(colnames(Sampled)==Var)]))+.5), ylim = c(min(AgeStrucSexLan$WECA), max(AgeStrucSexLan$WECA)), yaxs = "i", xaxt='n')
boxplot(eval(parse(text=Formula)), data=Estim, add=TRUE,
boxwex = 0.25, at = which(pos%in%unique(Estim[,which(colnames(Sampled)==Var)])),
col = "orange")
boxplot(eval(parse(text=Formula)), data=Sampled, add=TRUE,
boxwex = 0.25, at = which(pos%in%unique(Sampled[,which(colnames(Sampled)==Var)])) - 0.3,
col = "yellow", xaxt='n')
legend(1, max(AgeStrucSexLan$WECA), c("Imported", "Raised", "All"),
fill = c("yellow", "orange", "red"))
}
## export SOP table
#write.csv(SOP, file=paste0(output_wd,"SOP.csv"), row.names=F)
#Raised and imported datas
##Raised discards
#In InterCatch, the first step consists in raising the discards volumes for strats with landings and no discards associated. These discards are called in the following table 'Raised_Discards'. The data called 'Imported_Data' are landings or discards volumes imported into InterCatch with or without length/age structure.
#The proportion of Landings with Discards associated (same strata) is **`r paste(round(landingsWithAssociatedDiscards*100), 'percent')`**
write.csv(c("Landings with discards associated in percent",round(landingsWithAssociatedDiscards*100)), file=paste0(output_wd,"landingsWithAssociatedDiscards.csv"), row.names=F)
#The volumes (and associated proportion) of landings and discards imported (Imported_Data) or raised (Raised_Discards) are described in the following table.
write.csv(SummaryReport, file=paste0(output_wd,"Imported_Raised_discards.csv"), row.names=F)
##Total catch per gear
#The following table gives a summary of the catch (Landings+discards(imported+raised)) per gear (3 first letters of the metier)
write.csv(summCatchPerGear, file=paste0(output_wd,"Catch_Per_Gear.csv"), row.names=F)
##Length/Age distribution
#For the imported landings/discards and the raised discards without age distribution, the length or age distribution is then computed using the defined allocation scheme. *Sampled_distribution* means that the data (ladings or discards) were input with age/length distribution. *Estimated_distribution* means that the inputed/raised valoumes were estimated using the allocation scheme.
#In the following tables, CATON=WECA*CANUM/1000000 (in tonnes)
write.csv(SampledOrEstimated, file=paste0(output_wd,"Sampled_Estimated_L_D.csv"), row.names=F)
write.csv(SampledOrEstimatedArea, file=paste0(output_wd,"Sampled_Estimated_L_D_PerArea.csv"), row.names=F)
##Impact of the raising on the age/length structure
#Once the samples imported or raised are identified, it is possible to check the impact of the allocation scheme on the mean age/length of the final age/length distribution of the stock.
#The following figures compare the mean age (computed as the weighted mean of the age per strata("CatchCategory",'RaisedOrImported',"SampledOrEstimated","Country","Area","Season","Fleet","Sex")) of the estimated stratas compared to the imported ones and the final distribution. Each individual included in the boxplot corresponds to the weighted mean age of a strata.
###Global mean age
AgeStrucSexLan <- AgeStrucSex
png(filename=paste0(output_wd,"MeanAgeCatchCat.png"))
par(las=2)
boxplot(meanAge~CatchCategory, data=AgeStrucSexLan,
boxwex = 0.25, at = 1:length(unique(AgeStrucSexLan$CatchCategory)) + 0.3,
col = "red",
main = "Mean Age per Catch Category",
xlab = "",
ylab = "Mean Age",
xlim = c(0.5, length(unique(AgeStrucSexLan$CatchCategory))+.5), ylim = c(min(AgeStrucSexLan$AgeOrLength), max(AgeStrucSexLan$AgeOrLength)), yaxs = "i")
boxplot(meanAge~CatchCategory, data=AgeStrucSexLan[SampledOrEstimated=='Estimated_Distribution',], add=TRUE,
boxwex = 0.25, at = 1:length(unique(AgeStrucSexLan$CatchCategory)),
col = "orange")
boxplot(meanAge~CatchCategory, data=AgeStrucSexLan[SampledOrEstimated=='Sampled_Distribution',], add=TRUE,
boxwex = 0.25, at = 1:length(unique(AgeStrucSexLan$CatchCategory)) - 0.3,
col = "yellow")
legend(1, max(AgeStrucSexLan$AgeOrLength), c("Imported", "Raised", "All"),
fill = c("yellow", "orange", "red"))
dev.off()
###Mean Age per sex
var <- "Landings"
AgeStrucSexLan <- AgeStrucSex[CatchCategory==var,]
png(filename=paste0(output_wd,"MeanAge",var,"_Sex.png"))
par(las=2)
boxplot(meanAge~Sex, data=AgeStrucSexLan,
boxwex = 0.25, at = 1:length(unique(AgeStrucSexLan$Sex)) + 0.3,
col = "red",
main = "Mean Age in the Landings",
xlab = "",
ylab = "Mean Age",
xlim = c(0.5, length(unique(AgeStrucSexLan$Sex))+.5), ylim = c(min(AgeStrucSexLan$AgeOrLength), max(AgeStrucSexLan$AgeOrLength)), yaxs = "i")
boxplot(meanAge~Sex, data=AgeStrucSexLan[SampledOrEstimated=='Estimated_Distribution',], add=TRUE,
boxwex = 0.25, at = 1:length(unique(AgeStrucSexLan$Sex)),
col = "orange")
boxplot(meanAge~Sex, data=AgeStrucSexLan[SampledOrEstimated=='Sampled_Distribution',], add=TRUE,
boxwex = 0.25, at = 1:length(unique(AgeStrucSexLan$Sex)) - 0.3,
col = "yellow")
legend(1, max(AgeStrucSexLan$AgeOrLength), c("Imported", "Raised", "All"),
fill = c("yellow", "orange", "red"))
dev.off()
###Mean Age per area
catchCat <- "Landings"
Var <- "Area"
png(filename=paste0(output_wd,"MeanAge",catchCat,Var,".png"))
AgeStrucSexLan <- AgeStrucSex[CatchCategory==catchCat,]
AgeStrucSexLan <- data.frame(AgeStrucSexLan)
AgeStrucSexLan[,which(colnames(AgeStrucSexLan)==Var)] <- factor(AgeStrucSexLan[,which(colnames(AgeStrucSexLan)==Var)])
pos <- levels(AgeStrucSexLan[,which(colnames(AgeStrucSexLan)==Var)])
Estim <- AgeStrucSexLan[which(AgeStrucSexLan$SampledOrEstimated=='Estimated_Distribution'),]
Estim[,which(colnames(Estim)==Var)] <- factor(Estim[,which(colnames(Estim)==Var)])
Sampled <- AgeStrucSexLan[which(AgeStrucSexLan$SampledOrEstimated=='Sampled_Distribution'),]
Sampled[,which(colnames(Sampled)==Var)] <- factor(Sampled[,which(colnames(Sampled)==Var)])
par(las=2)
plotFunction(AgeStrucSexLan,Estim,Sampled)
dev.off()
###Mean Age per fleet
catchCat <- "Landings"
Var <- "Fleet"
png(filename=paste0(output_wd,"MeanAge",catchCat,Var,".png"))
AgeStrucSexLan <- AgeStrucSex[CatchCategory==catchCat,]
AgeStrucSexLan <- data.frame(AgeStrucSexLan)
AgeStrucSexLan[,which(colnames(AgeStrucSexLan)==Var)] <- factor(AgeStrucSexLan[,which(colnames(AgeStrucSexLan)==Var)])
pos <- levels(AgeStrucSexLan[,which(colnames(AgeStrucSexLan)==Var)])
Estim <- AgeStrucSexLan[which(AgeStrucSexLan$SampledOrEstimated=='Estimated_Distribution'),]
Estim[,which(colnames(Estim)==Var)] <- factor(Estim[,which(colnames(Estim)==Var)])
Sampled <- AgeStrucSexLan[which(AgeStrucSexLan$SampledOrEstimated=='Sampled_Distribution'),]
Sampled[,which(colnames(Sampled)==Var)] <- factor(Sampled[,which(colnames(Sampled)==Var)])
par(las=2, mar=c(15,4,4,5))
plotFunction(AgeStrucSexLan,Estim,Sampled)
dev.off()
###Resulting age structure
#The following plot shows the percentage of each age/length for the sampled strata, estimated and the final age structure for the landing and discard fractions.
listVAR <- c("CatchCategory","SampledOrEstimated")
AgeStrucSexProp <- AgeStrucSex[,list(sumCANUM=sum(CANUM)), by=c(listVAR,'AgeOrLength')]
AgeStrucSexProp <- AgeStrucSexProp[,propCanum:=sumCANUM/sum(sumCANUM), by=listVAR]
listVAR <- c("CatchCategory")
AgeStrucSexProp2 <- AgeStrucSex[,list(sumCANUM=sum(CANUM)), by=c(listVAR,'AgeOrLength')]
AgeStrucSexProp2 <- AgeStrucSexProp2[,propCanum:=sumCANUM/sum(sumCANUM), by=listVAR]
AgeStrucSexProp2$SampledOrEstimated <- "Final Distribution"
AgeStrucSexProp<- rbind(AgeStrucSexProp,AgeStrucSexProp2)
png(filename=paste0(output_wd,"AgeStruc.png"))
xyplot(propCanum~AgeOrLength|CatchCategory,groups = SampledOrEstimated, data=AgeStrucSexProp,auto.key = list(space = "right", points = TRUE, lines = FALSE))
dev.off()
##Mean weight at age/length
#the catchAndSampleData also provide the weight at age per strata for the Sampled/Estimated stratas.
#One would also want to check the sampled/estimated and resulting weight at length/age. This is produced in the following graph, each boxplot representing the distribution of the weight at age/length for the different stratas.
catchCat <- "Landings"
Var <- "AgeOrLength"
AgeStrucSexLan <- AgeStrucSex[CatchCategory==catchCat,]
AgeStrucSexLan <- data.frame(AgeStrucSexLan)
AgeStrucSexLan[,which(colnames(AgeStrucSexLan)==Var)] <- factor(AgeStrucSexLan[,which(colnames(AgeStrucSexLan)==Var)])
pos <- levels(AgeStrucSexLan[,which(colnames(AgeStrucSexLan)==Var)])
Estim <- AgeStrucSexLan[which(AgeStrucSexLan$SampledOrEstimated=='Estimated_Distribution'),]
Estim[,which(colnames(Estim)==Var)] <- factor(Estim[,which(colnames(Estim)==Var)])
Sampled <- AgeStrucSexLan[which(AgeStrucSexLan$SampledOrEstimated=='Sampled_Distribution'),]
Sampled[,which(colnames(Sampled)==Var)] <- factor(Sampled[,which(colnames(Sampled)==Var)])
Areas <- unique(AgeStrucSexLan$Area)
png(filename=paste0(output_wd,"MeanWeight",catchCat,Var,".png"))
par(las=2, mfrow=c(1, length(Areas)))
for(i in Areas){
plotFunctionMeanWeight(AgeStrucSexLan=AgeStrucSexLan[AgeStrucSexLan$Area==i,],Estim=Estim[Estim$Area==i,],Sampled=Sampled[Sampled$Area==i,])
}
dev.off()
#The outliers (more than 3 times the standard deviation) are extracted and can be investigated from the following table.
catchCat <- "Landings"
AgeStrucSexLan <- data.table(AgeStrucSexLan[AgeStrucSexLan$RaisedOrImported=="Imported_Data" & AgeStrucSexLan$CatchCategory==catchCat,])
AgeStrucSexLan <- AgeStrucSexLan[,AverageWtSize:=mean(WECA), by=list(RaisedOrImported,AgeOrLength,Area)]
AgeStrucSexLan <- AgeStrucSexLan[,stdWECA:=sd(WECA), by=list(RaisedOrImported,AgeOrLength,Area)]
write.csv(AgeStrucSexLan[WECA>AverageWtSize+3*stdWECA | WECA<AverageWtSize-3*stdWECA ,c('Country','Fleet','CatchCategory','WECA','AverageWtSize','AgeOrLength','Area'), with=F], file=paste0(output_wd,"export_outliers.csv"), row.names=F)
|
A real-valued function $f$ is continuous from the right at $a$ if and only if for every $\epsilon > 0$, there exists $\delta > 0$ such that $f(a + \delta) - f(a) < \epsilon$.
|
section \<open> Countable Non-Determinism \<close>
theory ITree_Countable_Nondeterminism
imports ITree_UTP
begin
text \<open> A type class to characterise a countable nondeterminism event. \<close>
class ndetev =
fixes ndetev :: "nat \<Longrightarrow>\<^sub>\<triangle> 'a"
assumes wb_ndetev [simp]: "wb_prism ndetev"
definition CNChoice :: "nat set \<Rightarrow> (nat \<Rightarrow> ('e::ndetev, 's) htree) \<Rightarrow> ('e, 's) htree" where
"CNChoice A P = input_in ndetev (\<lambda> _. A) P"
lemma CNChoice_pred [itree_pred]: "\<lbrakk>CNChoice A P\<rbrakk>\<^sub>p (s, s') = (\<exists>v\<in>A. \<lbrakk>P v\<rbrakk>\<^sub>p (s, s'))"
by (simp add: CNChoice_def itree_pred)
chantype pndet =
pndetev :: nat
instantiation pndet :: ndetev
begin
definition ndetev_pndet :: "nat \<Longrightarrow>\<^sub>\<triangle> pndet" where
"ndetev_pndet = pndetev"
instance by (intro_classes, simp add: ndetev_pndet_def)
end
definition prog_ndet :: "(pndet, 's) htree \<Rightarrow> (pndet, 's) htree \<Rightarrow> (pndet, 's) htree" where
"prog_ndet P Q = CNChoice {0, 1} ((\<lambda> x. Stop)(0 := P, 1 := Q))"
bundle prog_ndet_syntax
begin
notation
prog_ndet (infixl "\<sqinter>" 60)
end
bundle no_prog_ndet_syntax
begin
no_notation
prog_ndet (infixl "\<sqinter>" 60)
end
unbundle prog_ndet_syntax
lemma prog_ndet_pred [itree_pred]: "\<lbrakk>P \<sqinter> Q\<rbrakk>\<^sub>p (s, s') = ( \<lbrakk>P\<rbrakk>\<^sub>p (s, s') \<or> \<lbrakk>Q\<rbrakk>\<^sub>p (s, s'))"
by (simp add: prog_ndet_def itree_pred)
lemma prog_ndet_rel [itree_rel]: "itree_rel (C\<^sub>1 \<sqinter> C\<^sub>2) = itree_rel C\<^sub>1 \<union> itree_rel C\<^sub>2"
by (simp add: itree_rel_def itree_pred set_eq_iff)
lemma hl_prog_ndet [hoare_safe]:
assumes "\<^bold>{P\<^bold>} C\<^sub>1 \<^bold>{Q\<^bold>}" "\<^bold>{P\<^bold>} C\<^sub>2 \<^bold>{Q\<^bold>}"
shows "\<^bold>{P\<^bold>} C\<^sub>1 \<sqinter> C\<^sub>2 \<^bold>{Q\<^bold>}"
using assms by (simp add: hoare_triple_def itree_rel)
lemma wp_prog_ndet [wp]: "wp (C\<^sub>1 \<sqinter> C\<^sub>2) P = (wp C\<^sub>1 P \<or> wp C\<^sub>2 P)\<^sub>e"
by (expr_simp add: wp_itree_def itree_rel; auto)
lemma wlp_prog_ndet [wp]: "wlp (C\<^sub>1 \<sqinter> C\<^sub>2) P = (wlp C\<^sub>1 P \<and> wlp C\<^sub>2 P)\<^sub>e"
by (expr_simp add: wlp_itree_def itree_rel; auto)
unbundle no_prog_ndet_syntax
end
|
-- Andreas, 2012-01-30, bug reported by Nisse
-- {-# OPTIONS -v tc.term.absurd:50 -v tc.signature:30 -v tc.conv.atom:30 -v tc.conv.elim:50 #-}
module Issue557 where
data β₯ : Set where
postulate
A : Set
a : (β₯ β β₯) β A
F : A β Set
f : (a : A) β F a
module M (I : Set β Set) where
x : A
x = a (Ξ» ())
y : A
y = M.x (Ξ» A β A)
z : F y
z = f y
-- cause was absurd lambda in a module, i.e., under a telescope (I : Set -> Set)
-- (Ξ» ()) must be replaced by (absurd I) not just by (absurd)
|
The integral of $f(g(x)) \cdot g'(x)$ is the same as the integral of $f(g(x)) \cdot g'(x)$ over the interval $[a,b]$.
|
ID PROVIDER MODULE FUNCTION NAME
0
test/unittest/dtrace-util/tst.InvalidId2: dtrace failed
-- @@stderr --
dtrace: failed to match :::-2: No probe matches description
|
impulse process ACV_confirmBlockOption {
ACV_loadChunks()
/clone ${origin + (1 1 -6)} ${origin + (7 2 -6)} 0 1 1
/fill 0 1 2 6 2 2 air
/tellraw @a [{"text":"[","color":"gold"},{"text":"Info","color":"gold","italic":"true"},{"text":"] ","color":"gold"},{"text":"Block-Option confirmed","color":"yellow"}]
}
|
```
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import pydy
import sympy as sym
import sympy.physics.mechanics as me
from scipy.linalg import solve, lstsq
from scipy.integrate import odeint
import time
import functools
me.Vector.simp = False # to increase computation speed
from sympy.physics.vector import init_vprinting
init_vprinting()
from matplotlib import animation
from matplotlib.patches import Ellipse, Rectangle
from IPython.html import widgets
from IPython.html.widgets import interact, interactive
%matplotlib inline
```
```
from IPython.display import Image
Image(filename='snake-schematic.png')
# Note: q3 and q4 are zero for this model since the point J0 is
# fixed at the inertial frame origin.
```
```
# number of links (not currently used)
n = 3
# dynamic variables
q0, q1, q2 = me.dynamicsymbols('q0 q1 q2')
u0, u1, u2 = me.dynamicsymbols('u0 u1 u2')
# dynamic variable derivatives
q0d, q1d, q2d = me.dynamicsymbols('q0 q1 q2', 1)
u0d, u1d, u2d = me.dynamicsymbols('u0 u1 u2', 1)
# variables for bodies
g, t = sym.symbols('g t')
m0, m1, m2 = sym.symbols('m_0 m_1 m_2')
l0, l1, l2 = sym.symbols('l_0 l_1 l_2')
Izz0, Izz1, Izz2 = sym.symbols('I_zz_0 I_zz_1 I_zz_2')
# inertial reference frame
frN = me.ReferenceFrame('fr_N')
# body-fixed frames
fr0 = frN.orientnew('fr_0', 'Axis', [q0, frN.z])
fr1 = fr0.orientnew('fr_1', 'Axis', [q1, fr0.z])
fr2 = fr1.orientnew('fr_2', 'Axis', [q2, fr1.z])
# angular velocities of frames
# fr0.set_ang_vel(frN, u0 * frN.z)
# fr1.set_ang_vel(fr0, u1 * fr0.z) # was frN.z
# fr2.set_ang_vel(fr1, u2 * fr1.z) # was frN.z
fr0.set_ang_vel(frN, u0 * frN.z)
fr1.set_ang_vel(fr0, u1 * fr0.z) # was frN.z
fr2.set_ang_vel(fr1, u2 * fr1.z) # was frN.z
# origin of inertial frame
Nor = me.Point('N_or')
# joints
jt0 = Nor.locatenew('jt_0', 0) # .1 * frN.x + .1 * frN.y)
jt1 = jt0.locatenew('jt_1', l0 * fr0.x)
jt2 = jt1.locatenew('jt_2', l1 * fr1.x)
jt3 = jt2.locatenew('jt_3', l2 * fr2.x)
# mass centers
mc0 = jt0.locatenew('mc_0', l0 / 2 * fr0.x)
mc1 = jt1.locatenew('mc_1', l1 / 2 * fr1.x)
mc2 = jt2.locatenew('mc_2', l2 / 2 * fr2.x)
# constrained point velocities
Nor.set_vel(frN, 0)
jt0.set_vel(frN, 0)
# unconstrained point velocities
jt1.v2pt_theory(jt0, frN, fr0)
jt2.v2pt_theory(jt1, frN, fr1)
jt3.v2pt_theory(jt2, frN, fr2)
mc0.v2pt_theory(jt0, frN, fr0)
mc1.v2pt_theory(jt1, frN, fr1)
mc2.v2pt_theory(jt2, frN, fr2)
# inertia dyads
in0 = (me.inertia(fr0, 0, 0, Izz0), mc0)
in1 = (me.inertia(fr1, 0, 0, Izz1), mc1)
in2 = (me.inertia(fr2, 0, 0, Izz2), mc2)
# bodies
bd0 = me.RigidBody('bd_0', mc0, fr0, m0, in0)
bd1 = me.RigidBody('bd_1', mc1, fr1, m1, in1)
bd2 = me.RigidBody('bd_2', mc2, fr2, m2, in2)
# kinematic differential equations
kd = [q0.diff(t) - u0,
q1.diff(t) - u1,
q2.diff(t) - u2]
# forces
fl = [(mc0, -m0 * g * frN.z),
(mc1, -m1 * g * frN.z),
(mc2, -m2 * g * frN.z)]
fl = [(mc0, -m0 * g * frN.y),
(mc1, -m1 * g * frN.y),
(mc2, -m2 * g * frN.y)]
# bodies
bl = [bd0, bd1, bd2]
# q_ind and u_ind
coords = [q0, q1, q2]
speeds = [u0, u1, u2]
# # try adding some configuration level and configuration velocity constraints
# zero = jt0.pos_from(Nor)
# conlist_coor = [zero & frN.x, zero & frN.y]
# # Define the velocity level constraints
# dzero = me.time_derivative(zero, frN)
# conlist_speed = [dzero & frN.x, dzero & frN.y]
# q3, q4 = me.dynamicsymbols('q3 q4')
# u3, u4 = me.dynamicsymbols('u3 u4')
# equations of motion using Kane's method
kane = me.KanesMethod(frame=frN,
q_ind=coords,
u_ind=speeds,
kd_eqs=kd,
q_dependent=[],
configuration_constraints=[],
u_dependent=[],
velocity_constraints=[])
(fr, frstar) = kane.kanes_equations(fl, bl)
kanezero = fr + frstar
# these take to long...
# solve Kane's equations for the derivatives of the speeds
#eom = sym.solvers.solve(kanezero, q0d, q1d, q2d)
# add the kinematical differential equations to get the equations of motion
#eom.update(kane.kindiffdict())
# print the results
#me.mprint(eom)
#rhs = kane.mass_matrix.inv() * kane.forcing
#me.mprint(rhs)
#j3pos = jt3.pos_from(jt0).express(frN).simplify()
#sym.trigsimp(kanezero)
```
```
# parameter values
ls = .25 # segment lengths
ms = .15 # segment masses
ws_ratio = .1 # width is a function of length
ws = ls * ws_ratio # segment widths
Izzs = ms * (ls**2 + ws**2) / 12 # flat plate about com
# parameter arrays for numerical simulation
param_names = [g, m0, l0, Izz0, m1, l1, Izz1, m2, l2, Izz2]
param_vals = [9.81, ms, ls, Izzs, ms, ls, Izzs, ms, ls, Izzs]
# dummy symbols used for dynamamic variables
dyn_symbols = coords + speeds
dummy_symbols = [sym.Dummy() for i in dyn_symbols]
dummy_dict = dict(zip(dyn_symbols, dummy_symbols))
# substitute dummy symbols into mass matrix and forcing vector
kd_dict = kane.kindiffdict() # solved kinematical differential equations
F = kane.forcing_full.subs(kd_dict).subs(dummy_dict) # substitute into the forcing vector
M = kane.mass_matrix_full.subs(kd_dict).subs(dummy_dict) # substitute into the mass matrix
# callable matrices
F_func = sym.lambdify(param_names + dummy_symbols, F)
M_func = sym.lambdify(param_names + dummy_symbols, M)
# partially evaluate matrices to run faster (maybe 15% or so)
ffunc = functools.partial(F_func, *param_vals)
mfunc = functools.partial(M_func, *param_vals)
def rhs(x, t, args):
arguments = np.hstack((args, x))
dx = np.array(solve(M_func(*arguments), F_func(*arguments))).flatten()
return dx
def rhs_partial(x, t, args):
#x[1] = np.interp(t, ts, theta1)
#x[2] = np.interp(t, ts, theta2)
dx = np.array(solve(mfunc(*x), ffunc(*x))).flatten()
return dx
# initial conditions
qstart = (np.pi / 2, np.pi / 2, np.pi / 2)
ustart = (0, 0, 0) # (0.5, 0.5, 0.5)
#ustart = (0, -1.5, 1.5)
# stable ICs
# qstart = (-np.pi / 2, 0, 0)
# ustart = (0, 0, 0)
ts, dt = linspace(0, 10, 5001, retstep=True)
# theta1 = np.cos(ts)
# theta2 = np.cos(ts + np.pi/8)
# qstart = (np.pi / 4, theta1[0], theta2[0])
x0 = np.hstack((qstart, ustart))
```
```
# numerically integrate
now = time.time()
y1 = odeint(rhs_partial, x0, ts, args=(None,), full_output=False)
y1 = y1.T
print('Elapsed time: {0:.2f} sec'.format(time.time() - now))
```
Elapsed time: 2.00 sec
```
#specified = np.c_[theta1, theta2]
```
```
got = y1[1:3].T
```
```
#(got - specified)
```
```
# # numerically integrate (slower way)
# now = time.time()
# y2 = odeint(rhs, x0, t, args=(param_vals,), full_output=False)
# y2 = y2.T
# print('Elapsed time: {0:.2f} sec'.format(time.time() - now))
```
```
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(6, 6))
ax1.plot(y1[0])
ax1.plot(y1[1])
ax1.plot(y1[2])
ax2.plot(y1[3])
ax2.plot(y1[4])
ax2.plot(y1[5])
# ax1.plot(y2[0])
# ax1.plot(y2[1])
# ax1.plot(y2[2])
# ax2.plot(y2[3])
# ax2.plot(y2[4])
# ax2.plot(y2[5])
# ax1.set_ylim(-15, 15)
# ax2.set_ylim(-50, 50)
ax2.set_xlabel('iteration')
ax1.set_ylabel('q', rotation='horizontal')
ax2.set_ylabel('u', rotation='horizontal')
fig.tight_layout()
#display(fig)
```
```
def plot_chain(ii=0, hst=100):
fig, ax = plt.subplots(1, 1, sharex=True, sharey=True, figsize=(9, 9))
ax.axis('image')
ax.set_xlim(-.8, .8)
ax.set_ylim(-.8, .8)
fig.tight_layout()
time_text = ax.text(0.05, 0.9, '{0:.3} sec'.format(ts[ii]), transform=ax.transAxes)
ellipse_params = dict(alpha=.5, edgecolor='None', color='green')
e0 = Ellipse(xy=c0[ii], width=ws, height=1.05 * ls, angle=dg0[ii] - 90, **ellipse_params)
e1 = Ellipse(xy=c1[ii], width=ws, height=1.05 * ls, angle=dg1[ii] - 90, **ellipse_params)
e2 = Ellipse(xy=c2[ii], width=ws, height=1.05 * ls, angle=dg2[ii] - 90, **ellipse_params)
[ax.add_patch(e) for e in [e0, e1, e2]]
st = ii - hst
#st if st > 0 else 0
if st < 0:
st = 0
# ax.plot(j1[st:ii, 0], j1[st:ii, 1], 'b--')
# ax.plot(j2[st:ii, 0], j2[st:ii, 1], 'g--')
# ax.plot(j3[st:ii, 0], j3[st:ii, 1], 'r--')
ax.plot(c0[st:ii, 0], c0[st:ii, 1], 'b')
ax.plot(c1[st:ii, 0], c1[st:ii, 1], 'g')
ax.plot(c2[st:ii, 0], c2[st:ii, 1], 'r')
ax.plot(com[st:ii, 0], com[st:ii, 1], 'k-', lw=2, alpha=.9)
```
```
# organize the data
th0, th1, th2 = y1[:3]
th1 = th1 + th0
th2 = th2 + th1
dg0, dg1, dg2 = np.rad2deg(y1[:3])
dg1 = dg1 + dg0
dg2 = dg2 + dg1
j0 = np.c_[0, 0]
j1 = j0 + np.c_[ls * np.cos(th0), ls * np.sin(th0)]
j2 = j1 + np.c_[ls * np.cos(th1), ls * np.sin(th1)]
j3 = j2 + np.c_[ls * np.cos(th2), ls * np.sin(th2)]
c0 = j0 + np.c_[ls/2 * np.cos(th0), ls/2 * np.sin(th0)]
c1 = j1 + np.c_[ls/2 * np.cos(th1), ls/2 * np.sin(th1)]
c2 = j2 + np.c_[ls/2 * np.cos(th2), ls/2 * np.sin(th2)]
# j0 = np.c_[0, 0]
# j1 = j0 + np.c_[ls * np.cos(th0), ls * np.sin(th0)]
# j2 = j1 + np.c_[ls * np.cos(th0 + th1), ls * np.sin(th0 + th1)]
# j3 = j2 + np.c_[ls * np.cos(th0 + th1 + th2), ls * np.sin(th0 + th1 + th2)]
# c0 = j0 + np.c_[ls/2 * np.cos(th0), ls/2 * np.sin(th0)]
# c1 = j1 + np.c_[ls/2 * np.cos(th0 + th1), ls/2 * np.sin(th0 + th1)]
# c2 = j2 + np.c_[ls/2 * np.cos(th0 + th1 + th2), ls/2 * np.sin(th0 + th1 + th2)]
# center of mass
mms = np.array([ms, ms, ms])
cx = np.c_[c0[:, 0], c1[:, 0], c2[:, 0]]
cy = np.c_[c0[:, 1], c1[:, 1], c2[:, 1]]
com = np.c_[(cx * mms).sum(axis=1), (cy * mms).sum(axis=1)] / mms.sum()
# make it interactive!
interactive(plot_chain, ii=(0, len(y1.T)-1), hst=(0, 200, 10))
```
```
plot_chain(100)
```
```
mms = np.array([ms, ms, ms])
cx = np.c_[c0[:, 0], c1[:, 0], c2[:, 0]]
cy = np.c_[c0[:, 1], c1[:, 1], c2[:, 1]]
com = np.c_[(cx * mms).sum(axis=1), (cy * mms).sum(axis=1)] / mms.sum()
```
```
cx * mms
```
array([[ 1.14810637e-18, 3.44431912e-18, 5.74053187e-18],
[ -1.87697315e-05, -5.79451744e-05, -9.53940227e-05],
[ -3.75869803e-05, -1.19288568e-04, -1.94067843e-04],
...,
[ 1.85844031e-02, 2.42922480e-02, 3.01055501e-02],
[ 1.86131344e-02, 2.43280868e-02, 3.01447566e-02],
[ 1.86388850e-02, 2.43579289e-02, 3.01711461e-02]])
```
M = 3 * ms
1 / M * np.sum()
```
```
fig, ax = plt.subplots(1, 1, sharex=True, sharey=True, figsize=(6, 6))
fig.tight_layout()
# display the current time
time_text = ax.text(0.05, 0.9, 'time here', transform=ax.transAxes)
# create a rectangular cart
ell = [Ellipse(xy=(0, 0), width=.05*ls, height=1.05 * ls, angle=100 * np.random.random(),
alpha=.5, edgecolor='None', color='green')
for i in range(n)]
[ax.add_patch(ellis) for ellis in ell]
lim = 3 * ls
ax.set_xlim(-lim, lim)
ax.set_ylim(-lim, lim)
th0, th1, th2 = y1[:3]
dg0, dg1, dg2 = np.rad2deg(y1[:3])
j0 = np.c_[0, 0]
c0 = j0 + np.c_[ls/2 * np.cos(th0), ls/2 * np.sin(th0)]
j1 = j0 + np.c_[ls * np.cos(th0), ls * np.sin(th0)]
c1 = j1 + np.c_[ls/2 * np.cos(th1), ls/2 * np.sin(th1)]
j2 = j1 + np.c_[ls * np.cos(th1), ls * np.sin(th1)]
c2 = j2 + np.c_[ls/2 * np.cos(th2), ls/2 * np.sin(th2)]
j3 = j2 + np.c_[ls * np.cos(th2), ls * np.sin(th2)]
ii = 100
ell[0].center = c0[ii]
ell[1].center = c1[ii]
ell[2].center = c2[ii]
ell[0].angle = dg0[ii] - 90
ell[1].angle = dg1[ii] - 90
ell[2].angle = dg2[ii] - 90
ax.axis('image')
ax.set_xlim(-.7, .7)
ax.set_ylim(-.7, .7)
ax.plot(j1[:ii, 0], j1[:ii, 1], 'b--')
ax.plot(j2[:ii, 0], j2[:ii, 1], 'g--')
ax.plot(j3[:ii, 0], j3[:ii, 1], 'r--')
ax.plot(c0[:ii, 0], c0[:ii, 1], 'b')
ax.plot(c1[:ii, 0], c1[:ii, 1], 'g')
ax.plot(c2[:ii, 0], c2[:ii, 1], 'r')
```
[<matplotlib.lines.Line2D at 0xdfbaf10>]
```
-dg2[:20] + 90
```
array([ 0. , -0.05208 , -0.09370436, -0.12483333, -0.14542379,
-0.15542785, -0.15479371, -0.14346486, -0.12138054, -0.08847643,
-0.0446831 , 0.01007321, 0.0758705 , 0.15279123, 0.24092226,
0.34035504, 0.45118562, 0.5735147 , 0.70744765, 0.85309458])
```
fig, ax = plt.subplots(figsize=(7, 7))
ax.plot(j3[:, 0], j3[:, 1], alpha=.4)
ax.plot(j2[:, 0], j2[:, 1], alpha=.7)
ax.plot(j1[:, 0], j1[:, 1], alpha=.7)
ax.plot(j0[:, 0], j0[:, 1], alpha=.7)
ax.axis('equal')
fig.tight_layout()
```
```
# the number of pendulum bobs
numpoints = states.shape[1] / 2
# first set up the figure, the axis, and the plot elements we want to animate
fig = plt.figure()
# some dimesions
cart_width = 0.4
cart_height = 0.2
# set the limits based on the motion
xmin = around(states[:, 0].min() - cart_width / 2.0, 1)
xmax = around(states[:, 0].max() + cart_width / 2.0, 1)
# create the axes
ax = plt.axes(xlim=(xmin, xmax), ylim=(-1.1, 1.1), aspect='equal')
# display the current time
time_text = ax.text(0.04, 0.9, '', transform=ax.transAxes)
# create a rectangular cart
rect = Rectangle([states[0, 0] - cart_width / 2.0, -cart_height / 2],
cart_width, cart_height, fill=True, color='red', ec='black')
ax.add_patch(rect)
# blank line for the pendulum
line, = ax.plot([], [], lw=2, marker='o', markersize=6)
# initialization function: plot the background of each frame
def init():
time_text.set_text('')
rect.set_xy((0.0, 0.0))
line.set_data([], [])
return time_text, rect, line,
# animation function: update the objects
def animate(i):
time_text.set_text('time = {:2.2f}'.format(t[i]))
rect.set_xy((states[i, 0] - cart_width / 2.0, -cart_height / 2))
x = hstack((states[i, 0], zeros((numpoints - 1))))
y = zeros((numpoints))
for j in arange(1, numpoints):
x[j] = x[j - 1] + length * cos(states[i, j])
y[j] = y[j - 1] + length * sin(states[i, j])
line.set_data(x, y)
return time_text, rect, line,
# call the animator function
anim = animation.FuncAnimation(fig, animate, frames=len(t), init_func=init,
interval=t[-1] / len(t) * 1000, blit=True, repeat=False)
# save the animation if a filename is given
if filename is not None:
anim.save(filename, fps=30, codec='libx264')
##############
from matplotlib import animation
ani = animation.FuncAnimation(fig, updatefig, frames=1000, interval=75,
repeat=True, blit=True)
# video save information
metadata = dict(author='Isaac J. Yeaton',
description='Standard and Otsu threholded images.')
Writer = animation.writers['avconv']
writer = Writer(fps=15) # , extra_args=['-vcodec', 'libx264'], metadata=metadata)
if True:
#ani.save('/home/isaac/Desktop/tmp1.mp4', writer=writer)
ani.save('/home/isaac/Desktop/processed_shadowgraph_fields.mp4',
writer=writer)
```
```
```
```
# check that the partial evaulation works
xx = x0
#xx = y.T[696]
arguments = np.hstack((param_vals, xx))
mm = M_func(*arguments)
ff = F_func(*arguments)
# this does not work...
# aargs = dict(zip(param_names, dummy_symbols, arguments))
# mm = M_func(*aargs)
# ff = F_func(*aargs)
print solve(mm, ff).flatten()
print lstsq(mm, ff)[0].flatten()
#part_args = dict(zip(param_names, param_vals))
print solve(mfunc(*xx), ffunc(*xx)).flatten()
```
[ 0. 0. 0. -58.78688199 88.03408696
-48.64785093]
[ 0. 0. 0. -58.78688199 88.03408696
-48.64785093]
[ 0. 0. 0. -58.78688199 88.03408696
-48.64785093]
```
frame0 = I.orientnew('frame0', 'Axis', [q[0], I.z])
mc0 = O.locatenew('mc0', q[1] * frame0.x)
mc0.v2pt_theory(O, I, frame0)
in0 = me.inertia(frame0, 0, 0, Izz[0])
body0 = me.RigidBody('body0', mc0, frame0, m[0], (in0, mc0))
frame1 = frame0.orientnew('frame1', 'Axis', [q[2], I.z])
frame2 = frame1.orientnew('frame2', 'Axis', [q[3], I.z])
frame1.set_ang_vel(I, u[2] * I.z)
frame2.set_ang_vel(I, u[3] * I.z)
in1 = me.inertia(frame1, 0, 0, Izz[1])
in2 = me.inertia(frame2, 0, 0, Izz[2])
# mc1 = mc0.locatenew('mc1', l[0] * frame0.x +
# l[1] * sym.cos(q[2]) * frame1.x +
# l[1] * sym.sin(q[2]) * frame1.y)
# mc2 = mc1.locatenew('mc2', l[1] * frame1.x +
# l[2] * sym.cos(q[3]) * frame2.x +
# l[2] * sym.sin(q[3]) * frame2.y)
# after looking at the n-pendulum example
mc1 = mc0.locatenew('mc1', l[0] * frame0.x + l[1] * frame1.x)
mc2 = mc1.locatenew('mc2', l[1] * frame1.x + l[2] * frame2.x)
mc1.v2pt_theory(mc0, I, frame1)
mc2.v2pt_theory(mc1, I, frame2)
body1 = me.RigidBody('body1', mc1, frame1, m[1], (in1, mc1))
body2 = me.RigidBody('body2', mc2, frame2, m[2], (in2, mc2))
# each one might need four entries...
frames = [I, frame0, frame1, frame2]
points = [O, mc0, mc1, mc2]
bodies = [body0, body1, body2]
forces = [0, 0, 0]
kindiffs = [qq.diff(t) - uu for qq, uu in zip(q, u)]
# need to figure out forces and how to setup me.KanesMethod
# frames = [I] # List to hold the n + 1 frames
# points = [P0] # List to hold the n + 1 points
# particles = [Pa0] # List to hold the n + 1 particles
# forces = [(P0, f * I.x - m[0] * g * I.y)] # List to hold the n + 1 applied forces, including the input force, f
# kindiffs = [q[0].diff(t) - u[0]] # List to hold kinematic ODE's
# for i in range(n):
# Bi = I.orientnew('B' + str(i), 'Axis', [q[i + 1], I.z]) # Create a new frame
# Bi.set_ang_vel(I, u[i + 1] * I.z) # Set angular velocity
# frames.append(Bi) # Add it to the frames list
# Pi = points[-1].locatenew('P' + str(i + 1), l[i] * Bi.x) # Create a new point
# Pi.v2pt_theory(points[-1], I, Bi) # Set the velocity
# points.append(Pi) # Add it to the points list
# Pai = Particle('Pa' + str(i + 1), Pi, m[i + 1]) # Create a new particle
# particles.append(Pai) # Add it to the particles list
# forces.append((Pi, -m[i + 1] * g * I.y)) # Set the force applied at the point
# kindiffs.append(q[i + 1].diff(t) - u[i + 1]) # Define the kinematic ODE: dq_i / dt - u_i = 0
```
|
r=359.30
https://sandbox.dams.library.ucdavis.edu/fcrepo/rest/collection/sherry-lehmann/catalogs/d7gp4v/media/images/d7gp4v-010/svc:tesseract/full/full/359.30/default.jpg Accept:application/hocr+xml
|
/-
Copyright (c) 2017 Johannes HΓΆlzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Floris van Doorn
! This file was ported from Lean 3 source module set_theory.ordinal.basic
! leanprover-community/mathlib commit 8da9e30545433fdd8fe55a0d3da208e5d9263f03
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Data.Sum.Order
import Mathbin.Order.InitialSeg
import Mathbin.SetTheory.Cardinal.Basic
/-!
# Ordinals
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Ordinals are defined as equivalences of well-ordered sets under order isomorphism. They are endowed
with a total order, where an ordinal is smaller than another one if it embeds into it as an
initial segment (or, equivalently, in any way). This total order is well founded.
## Main definitions
* `ordinal`: the type of ordinals (in a given universe)
* `ordinal.type r`: given a well-founded order `r`, this is the corresponding ordinal
* `ordinal.typein r a`: given a well-founded order `r` on a type `Ξ±`, and `a : Ξ±`, the ordinal
corresponding to all elements smaller than `a`.
* `enum r o h`: given a well-order `r` on a type `Ξ±`, and an ordinal `o` strictly smaller than
the ordinal corresponding to `r` (this is the assumption `h`), returns the `o`-th element of `Ξ±`.
In other words, the elements of `Ξ±` can be enumerated using ordinals up to `type r`.
* `ordinal.card o`: the cardinality of an ordinal `o`.
* `ordinal.lift` lifts an ordinal in universe `u` to an ordinal in universe `max u v`.
For a version registering additionally that this is an initial segment embedding, see
`ordinal.lift.initial_seg`.
For a version regiserting that it is a principal segment embedding if `u < v`, see
`ordinal.lift.principal_seg`.
* `ordinal.omega` or `Ο` is the order type of `β`. This definition is universe polymorphic:
`ordinal.omega.{u} : ordinal.{u}` (contrast with `β : Type`, which lives in a specific
universe). In some cases the universe level has to be given explicitly.
* `oβ + oβ` is the order on the disjoint union of `oβ` and `oβ` obtained by declaring that
every element of `oβ` is smaller than every element of `oβ`. The main properties of addition
(and the other operations on ordinals) are stated and proved in `ordinal_arithmetic.lean`. Here,
we only introduce it and prove its basic properties to deduce the fact that the order on ordinals
is total (and well founded).
* `succ o` is the successor of the ordinal `o`.
* `cardinal.ord c`: when `c` is a cardinal, `ord c` is the smallest ordinal with this cardinality.
It is the canonical way to represent a cardinal with an ordinal.
A conditionally complete linear order with bot structure is registered on ordinals, where `β₯` is
`0`, the ordinal corresponding to the empty type, and `Inf` is the minimum for nonempty sets and `0`
for the empty set by convention.
## Notations
* `Ο` is a notation for the first infinite ordinal in the locale `ordinal`.
-/
noncomputable section
open Function Cardinal Set Equiv Order
open Classical Cardinal InitialSeg
universe u v w
variable {Ξ± : Type _} {Ξ² : Type _} {Ξ³ : Type _} {r : Ξ± β Ξ± β Prop} {s : Ξ² β Ξ² β Prop}
{t : Ξ³ β Ξ³ β Prop}
/-! ### Well order on an arbitrary type -/
section WellOrderingThm
parameter {Ο : Type u}
open Function
#print nonempty_embedding_to_cardinal /-
theorem nonempty_embedding_to_cardinal : Nonempty (Ο βͺ Cardinal.{u}) :=
(Embedding.total _ _).resolve_left fun β¨β¨f, hfβ©β© =>
let g : Ο β Cardinal.{u} := invFun f
let β¨x, (hx : g x = 2 ^ Sum g)β© := invFun_surjective hf (2 ^ Sum g)
have : g x β€ Sum g := le_sum.{u, u} g x
not_le_of_gt (by rw [hx] <;> exact cantor _) this
#align nonempty_embedding_to_cardinal nonempty_embedding_to_cardinal
-/
#print embeddingToCardinal /-
/-- An embedding of any type to the set of cardinals. -/
def embeddingToCardinal : Ο βͺ Cardinal.{u} :=
Classical.choice nonempty_embedding_to_cardinal
#align embedding_to_cardinal embeddingToCardinal
-/
#print WellOrderingRel /-
/-- Any type can be endowed with a well order, obtained by pulling back the well order over
cardinals by some embedding. -/
def WellOrderingRel : Ο β Ο β Prop :=
embeddingToCardinal β»ΒΉ'o (Β· < Β·)
#align well_ordering_rel WellOrderingRel
-/
#print WellOrderingRel.isWellOrder /-
instance WellOrderingRel.isWellOrder : IsWellOrder Ο WellOrderingRel :=
(RelEmbedding.preimage _ _).IsWellOrder
#align well_ordering_rel.is_well_order WellOrderingRel.isWellOrder
-/
#print IsWellOrder.subtype_nonempty /-
instance IsWellOrder.subtype_nonempty : Nonempty { r // IsWellOrder Ο r } :=
β¨β¨WellOrderingRel, inferInstanceβ©β©
#align is_well_order.subtype_nonempty IsWellOrder.subtype_nonempty
-/
end WellOrderingThm
/-! ### Definition of ordinals -/
#print WellOrder /-
/-- Bundled structure registering a well order on a type. Ordinals will be defined as a quotient
of this type. -/
structure WellOrder : Type (u + 1) where
Ξ± : Type u
R : Ξ± β Ξ± β Prop
wo : IsWellOrder Ξ± r
#align Well_order WellOrder
-/
attribute [instance] WellOrder.wo
namespace WellOrder
instance : Inhabited WellOrder :=
β¨β¨PEmpty, _, EmptyRelation.isWellOrderβ©β©
#print WellOrder.eta /-
@[simp]
theorem eta (o : WellOrder) : mk o.Ξ± o.R o.wo = o :=
by
cases o
rfl
#align Well_order.eta WellOrder.eta
-/
end WellOrder
#print Ordinal.isEquivalent /-
/-- Equivalence relation on well orders on arbitrary types in universe `u`, given by order
isomorphism. -/
instance Ordinal.isEquivalent : Setoid WellOrder
where
R := fun β¨Ξ±, r, woβ© β¨Ξ², s, wo'β© => Nonempty (r βr s)
iseqv :=
β¨fun β¨Ξ±, r, _β© => β¨RelIso.refl _β©, fun β¨Ξ±, r, _β© β¨Ξ², s, _β© β¨eβ© => β¨e.symmβ©,
fun β¨Ξ±, r, _β© β¨Ξ², s, _β© β¨Ξ³, t, _β© β¨eββ© β¨eββ© => β¨eβ.trans eββ©β©
#align ordinal.is_equivalent Ordinal.isEquivalent
-/
#print Ordinal /-
/-- `ordinal.{u}` is the type of well orders in `Type u`, up to order isomorphism. -/
def Ordinal : Type (u + 1) :=
Quotient Ordinal.isEquivalent
#align ordinal Ordinal
-/
#print hasWellFoundedOut /-
instance hasWellFoundedOut (o : Ordinal) : WellFoundedRelation o.out.Ξ± :=
β¨o.out.R, o.out.wo.wfβ©
#align has_well_founded_out hasWellFoundedOut
-/
#print linearOrderOut /-
instance linearOrderOut (o : Ordinal) : LinearOrder o.out.Ξ± :=
IsWellOrder.linearOrder o.out.R
#align linear_order_out linearOrderOut
-/
#print isWellOrder_out_lt /-
instance isWellOrder_out_lt (o : Ordinal) : IsWellOrder o.out.Ξ± (Β· < Β·) :=
o.out.wo
#align is_well_order_out_lt isWellOrder_out_lt
-/
namespace Ordinal
#print Ordinal.type /-
-- ### Basic properties of the order type
/-- The order type of a well order is an ordinal. -/
def type (r : Ξ± β Ξ± β Prop) [wo : IsWellOrder Ξ± r] : Ordinal :=
β¦β¨Ξ±, r, woβ©β§
#align ordinal.type Ordinal.type
-/
instance : Zero Ordinal :=
β¨type <| @EmptyRelation PEmptyβ©
instance : Inhabited Ordinal :=
β¨0β©
instance : One Ordinal :=
β¨type <| @EmptyRelation PUnitβ©
#print Ordinal.typein /-
/-- The order type of an element inside a well order. For the embedding as a principal segment, see
`typein.principal_seg`. -/
def typein (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] (a : Ξ±) : Ordinal :=
type (Subrel r { b | r b a })
#align ordinal.typein Ordinal.typein
-/
#print Ordinal.type_def' /-
@[simp]
theorem type_def' (w : WellOrder) : β¦wβ§ = type w.R :=
by
cases w
rfl
#align ordinal.type_def' Ordinal.type_def'
-/
#print Ordinal.type_def /-
@[simp]
theorem type_def (r) [wo : IsWellOrder Ξ± r] : (β¦β¨Ξ±, r, woβ©β§ : Ordinal) = type r :=
rfl
#align ordinal.type_def Ordinal.type_def
-/
#print Ordinal.type_out /-
@[simp]
theorem type_out (o : Ordinal) : Ordinal.type o.out.R = o := by
rw [Ordinal.type, WellOrder.eta, Quotient.out_eq]
#align ordinal.type_out Ordinal.type_out
-/
#print Ordinal.type_eq /-
theorem type_eq {Ξ± Ξ²} {r : Ξ± β Ξ± β Prop} {s : Ξ² β Ξ² β Prop} [IsWellOrder Ξ± r] [IsWellOrder Ξ² s] :
type r = type s β Nonempty (r βr s) :=
Quotient.eq'
#align ordinal.type_eq Ordinal.type_eq
-/
#print RelIso.ordinal_type_eq /-
theorem RelIso.ordinal_type_eq {Ξ± Ξ²} {r : Ξ± β Ξ± β Prop} {s : Ξ² β Ξ² β Prop} [IsWellOrder Ξ± r]
[IsWellOrder Ξ² s] (h : r βr s) : type r = type s :=
type_eq.2 β¨hβ©
#align rel_iso.ordinal_type_eq RelIso.ordinal_type_eq
-/
#print Ordinal.type_lt /-
@[simp]
theorem type_lt (o : Ordinal) : type ((Β· < Β·) : o.out.Ξ± β o.out.Ξ± β Prop) = o :=
(type_def' _).symm.trans <| Quotient.out_eq o
#align ordinal.type_lt Ordinal.type_lt
-/
#print Ordinal.type_eq_zero_of_empty /-
theorem type_eq_zero_of_empty (r) [IsWellOrder Ξ± r] [IsEmpty Ξ±] : type r = 0 :=
(RelIso.relIsoOfIsEmpty r _).ordinal_type_eq
#align ordinal.type_eq_zero_of_empty Ordinal.type_eq_zero_of_empty
-/
#print Ordinal.type_eq_zero_iff_isEmpty /-
@[simp]
theorem type_eq_zero_iff_isEmpty [IsWellOrder Ξ± r] : type r = 0 β IsEmpty Ξ± :=
β¨fun h =>
let β¨sβ© := type_eq.1 h
s.toEquiv.isEmpty,
@type_eq_zero_of_empty Ξ± r _β©
#align ordinal.type_eq_zero_iff_is_empty Ordinal.type_eq_zero_iff_isEmpty
-/
#print Ordinal.type_ne_zero_iff_nonempty /-
theorem type_ne_zero_iff_nonempty [IsWellOrder Ξ± r] : type r β 0 β Nonempty Ξ± := by simp
#align ordinal.type_ne_zero_iff_nonempty Ordinal.type_ne_zero_iff_nonempty
-/
#print Ordinal.type_ne_zero_of_nonempty /-
theorem type_ne_zero_of_nonempty (r) [IsWellOrder Ξ± r] [h : Nonempty Ξ±] : type r β 0 :=
type_ne_zero_iff_nonempty.2 h
#align ordinal.type_ne_zero_of_nonempty Ordinal.type_ne_zero_of_nonempty
-/
#print Ordinal.type_pEmpty /-
theorem type_pEmpty : type (@EmptyRelation PEmpty) = 0 :=
rfl
#align ordinal.type_pempty Ordinal.type_pEmpty
-/
#print Ordinal.type_empty /-
theorem type_empty : type (@EmptyRelation Empty) = 0 :=
type_eq_zero_of_empty _
#align ordinal.type_empty Ordinal.type_empty
-/
/- warning: ordinal.type_eq_one_of_unique -> Ordinal.type_eq_one_of_unique is a dubious translation:
lean 3 declaration is
forall {Ξ± : Type.{u1}} (r : Ξ± -> Ξ± -> Prop) [_inst_1 : IsWellOrder.{u1} Ξ± r] [_inst_2 : Unique.{succ u1} Ξ±], Eq.{succ (succ u1)} Ordinal.{u1} (Ordinal.type.{u1} Ξ± r _inst_1) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))
but is expected to have type
forall {Ξ± : Type.{u1}} (r : Ξ± -> Ξ± -> Prop) [_inst_1 : IsWellOrder.{u1} Ξ± r] [_inst_2 : Unique.{succ u1} Ξ±], Eq.{succ (succ u1)} Ordinal.{u1} (Ordinal.type.{u1} Ξ± r _inst_1) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))
Case conversion may be inaccurate. Consider using '#align ordinal.type_eq_one_of_unique Ordinal.type_eq_one_of_uniqueβ'. -/
theorem type_eq_one_of_unique (r) [IsWellOrder Ξ± r] [Unique Ξ±] : type r = 1 :=
(RelIso.relIsoOfUniqueOfIrrefl r _).ordinal_type_eq
#align ordinal.type_eq_one_of_unique Ordinal.type_eq_one_of_unique
/- warning: ordinal.type_eq_one_iff_unique -> Ordinal.type_eq_one_iff_unique is a dubious translation:
lean 3 declaration is
forall {Ξ± : Type.{u1}} {r : Ξ± -> Ξ± -> Prop} [_inst_1 : IsWellOrder.{u1} Ξ± r], Iff (Eq.{succ (succ u1)} Ordinal.{u1} (Ordinal.type.{u1} Ξ± r _inst_1) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))) (Nonempty.{succ u1} (Unique.{succ u1} Ξ±))
but is expected to have type
forall {Ξ± : Type.{u1}} {r : Ξ± -> Ξ± -> Prop} [_inst_1 : IsWellOrder.{u1} Ξ± r], Iff (Eq.{succ (succ u1)} Ordinal.{u1} (Ordinal.type.{u1} Ξ± r _inst_1) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))) (Nonempty.{succ u1} (Unique.{succ u1} Ξ±))
Case conversion may be inaccurate. Consider using '#align ordinal.type_eq_one_iff_unique Ordinal.type_eq_one_iff_uniqueβ'. -/
@[simp]
theorem type_eq_one_iff_unique [IsWellOrder Ξ± r] : type r = 1 β Nonempty (Unique Ξ±) :=
β¨fun h =>
let β¨sβ© := type_eq.1 h
β¨s.toEquiv.uniqueβ©,
fun β¨hβ© => @type_eq_one_of_unique Ξ± r _ hβ©
#align ordinal.type_eq_one_iff_unique Ordinal.type_eq_one_iff_unique
/- warning: ordinal.type_punit -> Ordinal.type_pUnit is a dubious translation:
lean 3 declaration is
Eq.{succ (succ u1)} Ordinal.{u1} (Ordinal.type.{u1} PUnit.{succ u1} (EmptyRelation.{succ u1} PUnit.{succ u1}) (EmptyRelation.isWellOrder.{u1} PUnit.{succ u1} PUnit.subsingleton.{succ u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))
but is expected to have type
Eq.{succ (succ u1)} Ordinal.{u1} (Ordinal.type.{u1} PUnit.{succ u1} (EmptyRelation.{succ u1} PUnit.{succ u1}) (instIsWellOrderEmptyRelation.{u1} PUnit.{succ u1} instSubsingletonPUnit.{succ u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))
Case conversion may be inaccurate. Consider using '#align ordinal.type_punit Ordinal.type_pUnitβ'. -/
theorem type_pUnit : type (@EmptyRelation PUnit) = 1 :=
rfl
#align ordinal.type_punit Ordinal.type_pUnit
/- warning: ordinal.type_unit -> Ordinal.type_unit is a dubious translation:
lean 3 declaration is
Eq.{2} Ordinal.{0} (Ordinal.type.{0} Unit (EmptyRelation.{1} Unit) (EmptyRelation.isWellOrder.{0} Unit PUnit.subsingleton.{1})) (OfNat.ofNat.{1} Ordinal.{0} 1 (OfNat.mk.{1} Ordinal.{0} 1 (One.one.{1} Ordinal.{0} Ordinal.hasOne.{0})))
but is expected to have type
Eq.{2} Ordinal.{0} (Ordinal.type.{0} Unit (EmptyRelation.{1} Unit) (instIsWellOrderEmptyRelation.{0} Unit instSubsingletonPUnit.{1})) (OfNat.ofNat.{1} Ordinal.{0} 1 (One.toOfNat1.{1} Ordinal.{0} Ordinal.one.{0}))
Case conversion may be inaccurate. Consider using '#align ordinal.type_unit Ordinal.type_unitβ'. -/
theorem type_unit : type (@EmptyRelation Unit) = 1 :=
rfl
#align ordinal.type_unit Ordinal.type_unit
#print Ordinal.out_empty_iff_eq_zero /-
@[simp]
theorem out_empty_iff_eq_zero {o : Ordinal} : IsEmpty o.out.Ξ± β o = 0 := by
rw [β @type_eq_zero_iff_is_empty o.out.Ξ± (Β· < Β·), type_lt]
#align ordinal.out_empty_iff_eq_zero Ordinal.out_empty_iff_eq_zero
-/
#print Ordinal.eq_zero_of_out_empty /-
theorem eq_zero_of_out_empty (o : Ordinal) [h : IsEmpty o.out.Ξ±] : o = 0 :=
out_empty_iff_eq_zero.1 h
#align ordinal.eq_zero_of_out_empty Ordinal.eq_zero_of_out_empty
-/
#print Ordinal.isEmpty_out_zero /-
instance isEmpty_out_zero : IsEmpty (0 : Ordinal).out.Ξ± :=
out_empty_iff_eq_zero.2 rfl
#align ordinal.is_empty_out_zero Ordinal.isEmpty_out_zero
-/
#print Ordinal.out_nonempty_iff_ne_zero /-
@[simp]
theorem out_nonempty_iff_ne_zero {o : Ordinal} : Nonempty o.out.Ξ± β o β 0 := by
rw [β @type_ne_zero_iff_nonempty o.out.Ξ± (Β· < Β·), type_lt]
#align ordinal.out_nonempty_iff_ne_zero Ordinal.out_nonempty_iff_ne_zero
-/
#print Ordinal.ne_zero_of_out_nonempty /-
theorem ne_zero_of_out_nonempty (o : Ordinal) [h : Nonempty o.out.Ξ±] : o β 0 :=
out_nonempty_iff_ne_zero.1 h
#align ordinal.ne_zero_of_out_nonempty Ordinal.ne_zero_of_out_nonempty
-/
/- warning: ordinal.one_ne_zero -> Ordinal.one_ne_zero is a dubious translation:
lean 3 declaration is
Ne.{succ (succ u1)} Ordinal.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1})))
but is expected to have type
Ne.{succ (succ u1)} Ordinal.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1}))
Case conversion may be inaccurate. Consider using '#align ordinal.one_ne_zero Ordinal.one_ne_zeroβ'. -/
protected theorem one_ne_zero : (1 : Ordinal) β 0 :=
type_ne_zero_of_nonempty _
#align ordinal.one_ne_zero Ordinal.one_ne_zero
instance : Nontrivial Ordinal.{u} :=
β¨β¨1, 0, Ordinal.one_ne_zeroβ©β©
#print Ordinal.type_preimage /-
@[simp]
theorem type_preimage {Ξ± Ξ² : Type u} (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] (f : Ξ² β Ξ±) :
type (f β»ΒΉ'o r) = type r :=
(RelIso.preimage f r).ordinal_type_eq
#align ordinal.type_preimage Ordinal.type_preimage
-/
#print Ordinal.inductionOn /-
@[elab_as_elim]
theorem inductionOn {C : Ordinal β Prop} (o : Ordinal) (H : β (Ξ± r) [IsWellOrder Ξ± r], C (type r)) :
C o :=
Quot.inductionOn o fun β¨Ξ±, r, woβ© => @H Ξ± r wo
#align ordinal.induction_on Ordinal.inductionOn
-/
/-! ### The order on ordinals -/
instance : PartialOrder Ordinal
where
le a b :=
Quotient.liftOnβ a b (fun β¨Ξ±, r, woβ© β¨Ξ², s, wo'β© => Nonempty (r βΌi s))
fun β¨Ξ±β, rβ, oββ© β¨Ξ±β, rβ, oββ© β¨Ξ²β, sβ, pββ© β¨Ξ²β, sβ, pββ© β¨fβ© β¨gβ© =>
propext
β¨fun β¨hβ© => β¨(InitialSeg.ofIso f.symm).trans <| h.trans (InitialSeg.ofIso g)β©, fun β¨hβ© =>
β¨(InitialSeg.ofIso f).trans <| h.trans (InitialSeg.ofIso g.symm)β©β©
lt a b :=
Quotient.liftOnβ a b (fun β¨Ξ±, r, woβ© β¨Ξ², s, wo'β© => Nonempty (r βΊi s))
fun β¨Ξ±β, rβ, oββ© β¨Ξ±β, rβ, oββ© β¨Ξ²β, sβ, pββ© β¨Ξ²β, sβ, pββ© β¨fβ© β¨gβ© =>
propext
β¨fun β¨hβ© => β¨PrincipalSeg.equivLT f.symm <| h.ltLe (InitialSeg.ofIso g)β©, fun β¨hβ© =>
β¨PrincipalSeg.equivLT f <| h.ltLe (InitialSeg.ofIso g.symm)β©β©
le_refl := Quot.ind fun β¨Ξ±, r, woβ© => β¨InitialSeg.refl _β©
le_trans a b c :=
Quotient.induction_onβ a b c fun β¨Ξ±, r, _β© β¨Ξ², s, _β© β¨Ξ³, t, _β© β¨fβ© β¨gβ© => β¨f.trans gβ©
lt_iff_le_not_le a b :=
Quotient.induction_onβ a b fun β¨Ξ±, r, _β© β¨Ξ², s, _β© =>
β¨fun β¨fβ© => β¨β¨fβ©, fun β¨gβ© => (f.ltLe g).irreflβ©, fun β¨β¨fβ©, hβ© =>
Sum.recOn f.lt_or_eq (fun g => β¨gβ©) fun g => (h β¨InitialSeg.ofIso g.symmβ©).elimβ©
le_antisymm a b :=
Quotient.induction_onβ a b fun β¨Ξ±, r, _β© β¨Ξ², s, _β© β¨hββ© β¨hββ© =>
Quot.sound β¨InitialSeg.antisymm hβ hββ©
/-- Ordinal less-equal is defined such that
well orders `r` and `s` satisfy `type r β€ type s` if there exists
a function embedding `r` as an initial segment of `s`. -/
add_decl_doc ordinal.partial_order.le
/-- Ordinal less-than is defined such that
well orders `r` and `s` satisfy `type r < type s` if there exists
a function embedding `r` as a principal segment of `s`. -/
add_decl_doc ordinal.partial_order.lt
#print Ordinal.type_le_iff /-
theorem type_le_iff {Ξ± Ξ²} {r : Ξ± β Ξ± β Prop} {s : Ξ² β Ξ² β Prop} [IsWellOrder Ξ± r]
[IsWellOrder Ξ² s] : type r β€ type s β Nonempty (r βΌi s) :=
Iff.rfl
#align ordinal.type_le_iff Ordinal.type_le_iff
-/
#print Ordinal.type_le_iff' /-
theorem type_le_iff' {Ξ± Ξ²} {r : Ξ± β Ξ± β Prop} {s : Ξ² β Ξ² β Prop} [IsWellOrder Ξ± r]
[IsWellOrder Ξ² s] : type r β€ type s β Nonempty (r βͺr s) :=
β¨fun β¨fβ© => β¨fβ©, fun β¨fβ© => β¨f.collapseβ©β©
#align ordinal.type_le_iff' Ordinal.type_le_iff'
-/
#print InitialSeg.ordinal_type_le /-
theorem InitialSeg.ordinal_type_le {Ξ± Ξ²} {r : Ξ± β Ξ± β Prop} {s : Ξ² β Ξ² β Prop} [IsWellOrder Ξ± r]
[IsWellOrder Ξ² s] (h : r βΌi s) : type r β€ type s :=
β¨hβ©
#align initial_seg.ordinal_type_le InitialSeg.ordinal_type_le
-/
#print RelEmbedding.ordinal_type_le /-
theorem RelEmbedding.ordinal_type_le {Ξ± Ξ²} {r : Ξ± β Ξ± β Prop} {s : Ξ² β Ξ² β Prop} [IsWellOrder Ξ± r]
[IsWellOrder Ξ² s] (h : r βͺr s) : type r β€ type s :=
β¨h.collapseβ©
#align rel_embedding.ordinal_type_le RelEmbedding.ordinal_type_le
-/
#print Ordinal.type_lt_iff /-
@[simp]
theorem type_lt_iff {Ξ± Ξ²} {r : Ξ± β Ξ± β Prop} {s : Ξ² β Ξ² β Prop} [IsWellOrder Ξ± r]
[IsWellOrder Ξ² s] : type r < type s β Nonempty (r βΊi s) :=
Iff.rfl
#align ordinal.type_lt_iff Ordinal.type_lt_iff
-/
#print PrincipalSeg.ordinal_type_lt /-
theorem PrincipalSeg.ordinal_type_lt {Ξ± Ξ²} {r : Ξ± β Ξ± β Prop} {s : Ξ² β Ξ² β Prop} [IsWellOrder Ξ± r]
[IsWellOrder Ξ² s] (h : r βΊi s) : type r < type s :=
β¨hβ©
#align principal_seg.ordinal_type_lt PrincipalSeg.ordinal_type_lt
-/
#print Ordinal.zero_le /-
protected theorem zero_le (o : Ordinal) : 0 β€ o :=
inductionOn o fun Ξ± r _ => (InitialSeg.ofIsEmpty _ r).ordinal_type_le
#align ordinal.zero_le Ordinal.zero_le
-/
instance : OrderBot Ordinal :=
β¨0, Ordinal.zero_leβ©
/- warning: ordinal.bot_eq_zero -> Ordinal.bot_eq_zero is a dubious translation:
lean 3 declaration is
Eq.{succ (succ u1)} Ordinal.{u1} (Bot.bot.{succ u1} Ordinal.{u1} (OrderBot.toHasBot.{succ u1} Ordinal.{u1} (Preorder.toLE.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) Ordinal.orderBot.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1})))
but is expected to have type
Eq.{succ (succ u1)} Ordinal.{u1} (Bot.bot.{succ u1} Ordinal.{u1} (OrderBot.toBot.{succ u1} Ordinal.{u1} (Preorder.toLE.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) Ordinal.orderBot.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1}))
Case conversion may be inaccurate. Consider using '#align ordinal.bot_eq_zero Ordinal.bot_eq_zeroβ'. -/
@[simp]
theorem bot_eq_zero : (β₯ : Ordinal) = 0 :=
rfl
#align ordinal.bot_eq_zero Ordinal.bot_eq_zero
#print Ordinal.le_zero /-
@[simp]
protected theorem le_zero {o : Ordinal} : o β€ 0 β o = 0 :=
le_bot_iff
#align ordinal.le_zero Ordinal.le_zero
-/
#print Ordinal.pos_iff_ne_zero /-
protected theorem pos_iff_ne_zero {o : Ordinal} : 0 < o β o β 0 :=
bot_lt_iff_ne_bot
#align ordinal.pos_iff_ne_zero Ordinal.pos_iff_ne_zero
-/
#print Ordinal.not_lt_zero /-
protected theorem not_lt_zero (o : Ordinal) : Β¬o < 0 :=
not_lt_bot
#align ordinal.not_lt_zero Ordinal.not_lt_zero
-/
#print Ordinal.eq_zero_or_pos /-
theorem eq_zero_or_pos : β a : Ordinal, a = 0 β¨ 0 < a :=
eq_bot_or_bot_lt
#align ordinal.eq_zero_or_pos Ordinal.eq_zero_or_pos
-/
instance : ZeroLEOneClass Ordinal :=
β¨Ordinal.zero_le _β©
/- warning: ordinal.ne_zero.one -> Ordinal.NeZero.one is a dubious translation:
lean 3 declaration is
NeZero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))
but is expected to have type
NeZero.{succ u1} Ordinal.{u1} Ordinal.zero.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))
Case conversion may be inaccurate. Consider using '#align ordinal.ne_zero.one Ordinal.NeZero.oneβ'. -/
instance NeZero.one : NeZero (1 : Ordinal) :=
β¨Ordinal.one_ne_zeroβ©
#align ordinal.ne_zero.one Ordinal.NeZero.one
#print Ordinal.initialSegOut /-
/-- Given two ordinals `Ξ± β€ Ξ²`, then `initial_seg_out Ξ± Ξ²` is the initial segment embedding
of `Ξ±` to `Ξ²`, as map from a model type for `Ξ±` to a model type for `Ξ²`. -/
def initialSegOut {Ξ± Ξ² : Ordinal} (h : Ξ± β€ Ξ²) :
InitialSeg ((Β· < Β·) : Ξ±.out.Ξ± β Ξ±.out.Ξ± β Prop) ((Β· < Β·) : Ξ².out.Ξ± β Ξ².out.Ξ± β Prop) :=
by
change Ξ±.out.r βΌi Ξ².out.r
rw [β Quotient.out_eq Ξ±, β Quotient.out_eq Ξ²] at h; revert h
cases Quotient.out Ξ±; cases Quotient.out Ξ²; exact Classical.choice
#align ordinal.initial_seg_out Ordinal.initialSegOut
-/
#print Ordinal.principalSegOut /-
/-- Given two ordinals `Ξ± < Ξ²`, then `principal_seg_out Ξ± Ξ²` is the principal segment embedding
of `Ξ±` to `Ξ²`, as map from a model type for `Ξ±` to a model type for `Ξ²`. -/
def principalSegOut {Ξ± Ξ² : Ordinal} (h : Ξ± < Ξ²) :
PrincipalSeg ((Β· < Β·) : Ξ±.out.Ξ± β Ξ±.out.Ξ± β Prop) ((Β· < Β·) : Ξ².out.Ξ± β Ξ².out.Ξ± β Prop) :=
by
change Ξ±.out.r βΊi Ξ².out.r
rw [β Quotient.out_eq Ξ±, β Quotient.out_eq Ξ²] at h; revert h
cases Quotient.out Ξ±; cases Quotient.out Ξ²; exact Classical.choice
#align ordinal.principal_seg_out Ordinal.principalSegOut
-/
#print Ordinal.typein_lt_type /-
theorem typein_lt_type (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] (a : Ξ±) : typein r a < type r :=
β¨PrincipalSeg.ofElement _ _β©
#align ordinal.typein_lt_type Ordinal.typein_lt_type
-/
#print Ordinal.typein_lt_self /-
theorem typein_lt_self {o : Ordinal} (i : o.out.Ξ±) : typein (Β· < Β·) i < o :=
by
simp_rw [β type_lt o]
apply typein_lt_type
#align ordinal.typein_lt_self Ordinal.typein_lt_self
-/
#print Ordinal.typein_top /-
@[simp]
theorem typein_top {Ξ± Ξ²} {r : Ξ± β Ξ± β Prop} {s : Ξ² β Ξ² β Prop} [IsWellOrder Ξ± r] [IsWellOrder Ξ² s]
(f : r βΊi s) : typein s f.top = type r :=
Eq.symm <|
Quot.sound
β¨RelIso.ofSurjective (RelEmbedding.codRestrict _ f f.lt_top) fun β¨a, hβ© => by
rcases f.down.1 h with β¨b, rflβ© <;> exact β¨b, rflβ©β©
#align ordinal.typein_top Ordinal.typein_top
-/
/- warning: ordinal.typein_apply -> Ordinal.typein_apply is a dubious translation:
lean 3 declaration is
forall {Ξ± : Type.{u1}} {Ξ² : Type.{u1}} {r : Ξ± -> Ξ± -> Prop} {s : Ξ² -> Ξ² -> Prop} [_inst_1 : IsWellOrder.{u1} Ξ± r] [_inst_2 : IsWellOrder.{u1} Ξ² s] (f : InitialSeg.{u1, u1} Ξ± Ξ² r s) (a : Ξ±), Eq.{succ (succ u1)} Ordinal.{u1} (Ordinal.typein.{u1} Ξ² s _inst_2 (coeFn.{succ u1, succ u1} (InitialSeg.{u1, u1} Ξ± Ξ² r s) (fun (_x : InitialSeg.{u1, u1} Ξ± Ξ² r s) => Ξ± -> Ξ²) (FunLike.hasCoeToFun.{succ u1, succ u1, succ u1} (InitialSeg.{u1, u1} Ξ± Ξ² r s) Ξ± (fun (_x : Ξ±) => Ξ²) (EmbeddingLike.toFunLike.{succ u1, succ u1, succ u1} (InitialSeg.{u1, u1} Ξ± Ξ² r s) Ξ± Ξ² (InitialSeg.embeddingLike.{u1, u1} Ξ± Ξ² r s))) f a)) (Ordinal.typein.{u1} Ξ± r _inst_1 a)
but is expected to have type
forall {Ξ± : Type.{u1}} {Ξ² : Type.{u1}} {r : Ξ± -> Ξ± -> Prop} {s : Ξ² -> Ξ² -> Prop} [_inst_1 : IsWellOrder.{u1} Ξ± r] [_inst_2 : IsWellOrder.{u1} Ξ² s] (f : InitialSeg.{u1, u1} Ξ± Ξ² r s) (a : Ξ±), Eq.{succ (succ u1)} Ordinal.{u1} (Ordinal.typein.{u1} Ξ² s _inst_2 (FunLike.coe.{succ u1, succ u1, succ u1} (InitialSeg.{u1, u1} Ξ± Ξ² r s) Ξ± (fun (_x : Ξ±) => (fun ([email protected]._hyg.19 : Ξ±) => Ξ²) _x) (EmbeddingLike.toFunLike.{succ u1, succ u1, succ u1} (InitialSeg.{u1, u1} Ξ± Ξ² r s) Ξ± Ξ² (InitialSeg.instEmbeddingLikeInitialSeg.{u1, u1} Ξ± Ξ² r s)) f a)) (Ordinal.typein.{u1} Ξ± r _inst_1 a)
Case conversion may be inaccurate. Consider using '#align ordinal.typein_apply Ordinal.typein_applyβ'. -/
@[simp]
theorem typein_apply {Ξ± Ξ²} {r : Ξ± β Ξ± β Prop} {s : Ξ² β Ξ² β Prop} [IsWellOrder Ξ± r] [IsWellOrder Ξ² s]
(f : r βΌi s) (a : Ξ±) : Ordinal.typein s (f a) = Ordinal.typein r a :=
Eq.symm <|
Quotient.sound
β¨RelIso.ofSurjective
(RelEmbedding.codRestrict _ ((Subrel.relEmbedding _ _).trans f) fun β¨x, hβ© => by
rw [RelEmbedding.trans_apply] <;> exact f.to_rel_embedding.map_rel_iff.2 h)
fun β¨y, hβ© => by
rcases f.init h with β¨a, rflβ© <;>
exact
β¨β¨a, f.to_rel_embedding.map_rel_iff.1 hβ©,
Subtype.eq <| RelEmbedding.trans_apply _ _ _β©β©
#align ordinal.typein_apply Ordinal.typein_apply
#print Ordinal.typein_lt_typein /-
@[simp]
theorem typein_lt_typein (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] {a b : Ξ±} :
typein r a < typein r b β r a b :=
β¨fun β¨fβ© =>
by
have : f.top.1 = a := by
let f' := PrincipalSeg.ofElement r a
let g' := f.trans (PrincipalSeg.ofElement r b)
have : g'.top = f'.top := by rw [Subsingleton.elim f' g']
exact this
rw [β this]
exact f.top.2, fun h =>
β¨PrincipalSeg.codRestrict _ (PrincipalSeg.ofElement r a) (fun x => @trans _ r _ _ _ _ x.2 h) hβ©β©
#align ordinal.typein_lt_typein Ordinal.typein_lt_typein
-/
#print Ordinal.typein_surj /-
theorem typein_surj (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] {o} (h : o < type r) :
β a, typein r a = o :=
inductionOn o (fun Ξ² s _ β¨fβ© => β¨f.top, typein_top _β©) h
#align ordinal.typein_surj Ordinal.typein_surj
-/
#print Ordinal.typein_injective /-
theorem typein_injective (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] : Injective (typein r) :=
injective_of_increasing r (Β· < Β·) (typein r) fun x y => (typein_lt_typein r).2
#align ordinal.typein_injective Ordinal.typein_injective
-/
#print Ordinal.typein_inj /-
@[simp]
theorem typein_inj (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] {a b} : typein r a = typein r b β a = b :=
(typein_injective r).eq_iff
#align ordinal.typein_inj Ordinal.typein_inj
-/
/-! ### Enumerating elements in a well-order with ordinals. -/
#print Ordinal.enum /-
/-- `enum r o h` is the `o`-th element of `Ξ±` ordered by `r`.
That is, `enum` maps an initial segment of the ordinals, those
less than the order type of `r`, to the elements of `Ξ±`. -/
def enum (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] (o) : o < type r β Ξ± :=
Quot.recOn' o (fun β¨Ξ², s, _β© h => (Classical.choice h).top) fun β¨Ξ², s, _β© β¨Ξ³, t, _β© β¨hβ© =>
by
skip
refine' funext fun Hβ : type t < type r => _
have Hβ : type s < type r := by rwa [type_eq.2 β¨hβ©]
have :
β {o e} (H : o < type r),
@Eq.ndrec (fun o : Ordinal => o < type r β Ξ±)
(fun h : type s < type r => (Classical.choice h).top) e H =
(Classical.choice Hβ).top :=
by
intros
subst e
exact (this Hβ).trans (PrincipalSeg.top_eq h (Classical.choice Hβ) (Classical.choice Hβ))
#align ordinal.enum Ordinal.enum
-/
#print Ordinal.enum_type /-
theorem enum_type {Ξ± Ξ²} {r : Ξ± β Ξ± β Prop} {s : Ξ² β Ξ² β Prop} [IsWellOrder Ξ± r] [IsWellOrder Ξ² s]
(f : s βΊi r) {h : type s < type r} : enum r (type s) h = f.top :=
PrincipalSeg.top_eq (RelIso.refl _) _ _
#align ordinal.enum_type Ordinal.enum_type
-/
#print Ordinal.enum_typein /-
@[simp]
theorem enum_typein (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] (a : Ξ±) :
enum r (typein r a) (typein_lt_type r a) = a :=
enum_type (PrincipalSeg.ofElement r a)
#align ordinal.enum_typein Ordinal.enum_typein
-/
#print Ordinal.typein_enum /-
@[simp]
theorem typein_enum (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] {o} (h : o < type r) :
typein r (enum r o h) = o := by
let β¨a, eβ© := typein_surj r h
clear _let_match <;> subst e <;> rw [enum_typein]
#align ordinal.typein_enum Ordinal.typein_enum
-/
#print Ordinal.enum_lt_enum /-
theorem enum_lt_enum {r : Ξ± β Ξ± β Prop} [IsWellOrder Ξ± r] {oβ oβ : Ordinal} (hβ : oβ < type r)
(hβ : oβ < type r) : r (enum r oβ hβ) (enum r oβ hβ) β oβ < oβ := by
rw [β typein_lt_typein r, typein_enum, typein_enum]
#align ordinal.enum_lt_enum Ordinal.enum_lt_enum
-/
/- warning: ordinal.rel_iso_enum' -> Ordinal.relIso_enum' is a dubious translation:
lean 3 declaration is
forall {Ξ± : Type.{u1}} {Ξ² : Type.{u1}} {r : Ξ± -> Ξ± -> Prop} {s : Ξ² -> Ξ² -> Prop} [_inst_1 : IsWellOrder.{u1} Ξ± r] [_inst_2 : IsWellOrder.{u1} Ξ² s] (f : RelIso.{u1, u1} Ξ± Ξ² r s) (o : Ordinal.{u1}) (hr : LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o (Ordinal.type.{u1} Ξ± r _inst_1)) (hs : LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o (Ordinal.type.{u1} Ξ² s _inst_2)), Eq.{succ u1} Ξ² (coeFn.{succ u1, succ u1} (RelIso.{u1, u1} Ξ± Ξ² r s) (fun (_x : RelIso.{u1, u1} Ξ± Ξ² r s) => Ξ± -> Ξ²) (RelIso.hasCoeToFun.{u1, u1} Ξ± Ξ² r s) f (Ordinal.enum.{u1} Ξ± r _inst_1 o hr)) (Ordinal.enum.{u1} Ξ² s _inst_2 o hs)
but is expected to have type
forall {Ξ± : Type.{u1}} {Ξ² : Type.{u1}} {r : Ξ± -> Ξ± -> Prop} {s : Ξ² -> Ξ² -> Prop} [_inst_1 : IsWellOrder.{u1} Ξ± r] [_inst_2 : IsWellOrder.{u1} Ξ² s] (f : RelIso.{u1, u1} Ξ± Ξ² r s) (o : Ordinal.{u1}) (hr : LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o (Ordinal.type.{u1} Ξ± r _inst_1)) (hs : LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o (Ordinal.type.{u1} Ξ² s _inst_2)), Eq.{succ u1} ((fun ([email protected]._hyg.19 : Ξ±) => Ξ²) (Ordinal.enum.{u1} Ξ± r _inst_1 o hr)) (FunLike.coe.{succ u1, succ u1, succ u1} (Function.Embedding.{succ u1, succ u1} Ξ± Ξ²) Ξ± (fun (_x : Ξ±) => (fun ([email protected]._hyg.19 : Ξ±) => Ξ²) _x) (EmbeddingLike.toFunLike.{succ u1, succ u1, succ u1} (Function.Embedding.{succ u1, succ u1} Ξ± Ξ²) Ξ± Ξ² (Function.instEmbeddingLikeEmbedding.{succ u1, succ u1} Ξ± Ξ²)) (RelEmbedding.toEmbedding.{u1, u1} Ξ± Ξ² r s (RelIso.toRelEmbedding.{u1, u1} Ξ± Ξ² r s f)) (Ordinal.enum.{u1} Ξ± r _inst_1 o hr)) (Ordinal.enum.{u1} Ξ² s _inst_2 o hs)
Case conversion may be inaccurate. Consider using '#align ordinal.rel_iso_enum' Ordinal.relIso_enum'β'. -/
theorem relIso_enum' {Ξ± Ξ² : Type u} {r : Ξ± β Ξ± β Prop} {s : Ξ² β Ξ² β Prop} [IsWellOrder Ξ± r]
[IsWellOrder Ξ² s] (f : r βr s) (o : Ordinal) :
β (hr : o < type r) (hs : o < type s), f (enum r o hr) = enum s o hs :=
by
refine' induction_on o _; rintro Ξ³ t wo β¨gβ© β¨hβ©
skip; rw [enum_type g, enum_type (PrincipalSeg.ltEquiv g f)]; rfl
#align ordinal.rel_iso_enum' Ordinal.relIso_enum'
/- warning: ordinal.rel_iso_enum -> Ordinal.relIso_enum is a dubious translation:
lean 3 declaration is
forall {Ξ± : Type.{u1}} {Ξ² : Type.{u1}} {r : Ξ± -> Ξ± -> Prop} {s : Ξ² -> Ξ² -> Prop} [_inst_1 : IsWellOrder.{u1} Ξ± r] [_inst_2 : IsWellOrder.{u1} Ξ² s] (f : RelIso.{u1, u1} Ξ± Ξ² r s) (o : Ordinal.{u1}) (hr : LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o (Ordinal.type.{u1} Ξ± r _inst_1)), Eq.{succ u1} Ξ² (coeFn.{succ u1, succ u1} (RelIso.{u1, u1} Ξ± Ξ² r s) (fun (_x : RelIso.{u1, u1} Ξ± Ξ² r s) => Ξ± -> Ξ²) (RelIso.hasCoeToFun.{u1, u1} Ξ± Ξ² r s) f (Ordinal.enum.{u1} Ξ± r _inst_1 o hr)) (Ordinal.enum.{u1} Ξ² s _inst_2 o (Eq.mpr.{0} (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o (Ordinal.type.{u1} Ξ² s _inst_2)) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o (Ordinal.type.{u1} Ξ± r _inst_1)) ((fun [self : LT.{succ u1} Ordinal.{u1}] (αΎ° : Ordinal.{u1}) (αΎ°_1 : Ordinal.{u1}) (e_2 : Eq.{succ (succ u1)} Ordinal.{u1} αΎ° αΎ°_1) (αΎ°_2 : Ordinal.{u1}) (αΎ°_3 : Ordinal.{u1}) (e_3 : Eq.{succ (succ u1)} Ordinal.{u1} αΎ°_2 αΎ°_3) => congr.{succ (succ u1), 1} Ordinal.{u1} Prop (LT.lt.{succ u1} Ordinal.{u1} self αΎ°) (LT.lt.{succ u1} Ordinal.{u1} self αΎ°_1) αΎ°_2 αΎ°_3 (congr_arg.{succ (succ u1), succ (succ u1)} Ordinal.{u1} (Ordinal.{u1} -> Prop) αΎ° αΎ°_1 (LT.lt.{succ u1} Ordinal.{u1} self) e_2) e_3) (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o o (rfl.{succ (succ u1)} Ordinal.{u1} o) (Ordinal.type.{u1} Ξ² s _inst_2) (Ordinal.type.{u1} Ξ± r _inst_1) (Quotient.sound.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (WellOrder.mk.{u1} Ξ² s _inst_2) (WellOrder.mk.{u1} Ξ± r _inst_1) (Nonempty.intro.{succ u1} (RelIso.{u1, u1} Ξ² Ξ± s r) (RelIso.symm.{u1, u1} Ξ± Ξ² r s f)))) hr))
but is expected to have type
forall {Ξ± : Type.{u1}} {Ξ² : Type.{u1}} {r : Ξ± -> Ξ± -> Prop} {s : Ξ² -> Ξ² -> Prop} [_inst_1 : IsWellOrder.{u1} Ξ± r] [_inst_2 : IsWellOrder.{u1} Ξ² s] (f : RelIso.{u1, u1} Ξ± Ξ² r s) (o : Ordinal.{u1}) (hr : LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o (Ordinal.type.{u1} Ξ± r _inst_1)), Eq.{succ u1} ((fun ([email protected]._hyg.19 : Ξ±) => Ξ²) (Ordinal.enum.{u1} Ξ± r _inst_1 o hr)) (FunLike.coe.{succ u1, succ u1, succ u1} (Function.Embedding.{succ u1, succ u1} Ξ± Ξ²) Ξ± (fun (_x : Ξ±) => (fun ([email protected]._hyg.19 : Ξ±) => Ξ²) _x) (EmbeddingLike.toFunLike.{succ u1, succ u1, succ u1} (Function.Embedding.{succ u1, succ u1} Ξ± Ξ²) Ξ± Ξ² (Function.instEmbeddingLikeEmbedding.{succ u1, succ u1} Ξ± Ξ²)) (RelEmbedding.toEmbedding.{u1, u1} Ξ± Ξ² r s (RelIso.toRelEmbedding.{u1, u1} Ξ± Ξ² r s f)) (Ordinal.enum.{u1} Ξ± r _inst_1 o hr)) (Ordinal.enum.{u1} Ξ² s _inst_2 o (Eq.mpr.{0} (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o (Ordinal.type.{u1} Ξ² s _inst_2)) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o (Ordinal.type.{u1} Ξ± r _inst_1)) (eq_of_heq.{1} Prop (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o (Ordinal.type.{u1} Ξ² s _inst_2)) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o (Ordinal.type.{u1} Ξ± r _inst_1)) ((fun (Ξ± : Type.{succ u1}) (self : LT.{succ u1} Ξ±) ([email protected]._hyg.2009 : Ξ±) ([email protected]._hyg.2011 : Ξ±) (a'[email protected]._hyg.2011 : Ξ±) (e'_4 : Eq.{succ (succ u1)} Ξ± [email protected]._hyg.2011 a'[email protected]._hyg.2011) => Eq.casesOn.{0, succ (succ u1)} Ξ± [email protected]._hyg.2011 (fun ([email protected]._hyg.170 : Ξ±) (x : Eq.{succ (succ u1)} Ξ± [email protected]._hyg.2011 [email protected]._hyg.170) => (Eq.{succ (succ u1)} Ξ± a'[email protected]._hyg.2011 [email protected]._hyg.170) -> (HEq.{0} (Eq.{succ (succ u1)} Ξ± [email protected]._hyg.2011 a'[email protected]._hyg.2011) e'_4 (Eq.{succ (succ u1)} Ξ± [email protected]._hyg.2011 [email protected]._hyg.170) x) -> (HEq.{1} Prop (LT.lt.{succ u1} Ξ± self [email protected]._hyg.2009 [email protected]._hyg.2011) Prop (LT.lt.{succ u1} Ξ± self [email protected]._hyg.2009 a'[email protected]._hyg.2011))) a'[email protected]._hyg.2011 e'_4 (fun ([email protected]._hyg.5692 : Eq.{succ (succ u1)} Ξ± a'[email protected]._hyg.2011 [email protected]._hyg.2011) => Eq.ndrec.{0, succ (succ u1)} Ξ± [email protected]._hyg.2011 (fun (a'[email protected]._hyg.5690 : Ξ±) => forall ([email protected]._hyg.5691 : Eq.{succ (succ u1)} Ξ± [email protected]._hyg.2011 a'[email protected]._hyg.5690), (HEq.{0} (Eq.{succ (succ u1)} Ξ± [email protected]._hyg.2011 a'[email protected]._hyg.5690) [email protected]._hyg.5691 (Eq.{succ (succ u1)} Ξ± [email protected]._hyg.2011 [email protected]._hyg.2011) (Eq.refl.{succ (succ u1)} Ξ± [email protected]._hyg.2011)) -> (HEq.{1} Prop (LT.lt.{succ u1} Ξ± self [email protected]._hyg.2009 [email protected]._hyg.2011) Prop (LT.lt.{succ u1} Ξ± self [email protected]._hyg.2009 a'[email protected]._hyg.5690))) (fun ([email protected]._hyg.5691 : Eq.{succ (succ u1)} Ξ± [email protected]._hyg.2011 [email protected]._hyg.2011) ([email protected]._hyg.5693 : HEq.{0} (Eq.{succ (succ u1)} Ξ± [email protected]._hyg.2011 [email protected]._hyg.2011) [email protected]._hyg.5691 (Eq.{succ (succ u1)} Ξ± [email protected]._hyg.2011 [email protected]._hyg.2011) (Eq.refl.{succ (succ u1)} Ξ± [email protected]._hyg.2011)) => Eq.ndrec.{0, 0} (Eq.{succ (succ u1)} Ξ± [email protected]._hyg.2011 [email protected]._hyg.2011) (Eq.refl.{succ (succ u1)} Ξ± [email protected]._hyg.2011) (fun ([email protected]._hyg.5691 : Eq.{succ (succ u1)} Ξ± [email protected]._hyg.2011 [email protected]._hyg.2011) => HEq.{1} Prop (LT.lt.{succ u1} Ξ± self [email protected]._hyg.2009 [email protected]._hyg.2011) Prop (LT.lt.{succ u1} Ξ± self [email protected]._hyg.2009 [email protected]._hyg.2011)) (HEq.refl.{1} Prop (LT.lt.{succ u1} Ξ± self [email protected]._hyg.2009 [email protected]._hyg.2011)) [email protected]._hyg.5691 (Eq.symm.{0} (Eq.{succ (succ u1)} Ξ± [email protected]._hyg.2011 [email protected]._hyg.2011) [email protected]._hyg.5691 (Eq.refl.{succ (succ u1)} Ξ± [email protected]._hyg.2011) (eq_of_heq.{0} (Eq.{succ (succ u1)} Ξ± [email protected]._hyg.2011 [email protected]._hyg.2011) [email protected]._hyg.5691 (Eq.refl.{succ (succ u1)} Ξ± [email protected]._hyg.2011) [email protected]._hyg.5693))) a'[email protected]._hyg.2011 (Eq.symm.{succ (succ u1)} Ξ± a'[email protected]._hyg.2011 [email protected]._hyg.2011 [email protected]._hyg.5692) e'_4) (Eq.refl.{succ (succ u1)} Ξ± a'[email protected]._hyg.2011) (HEq.refl.{0} (Eq.{succ (succ u1)} Ξ± [email protected]._hyg.2011 a'[email protected]._hyg.2011) e'_4)) Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o (Ordinal.type.{u1} Ξ² s _inst_2) (Ordinal.type.{u1} Ξ± r _inst_1) (Quotient.sound.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (WellOrder.mk.{u1} Ξ² s _inst_2) (WellOrder.mk.{u1} Ξ± r _inst_1) (Nonempty.intro.{succ u1} (RelIso.{u1, u1} Ξ² Ξ± s r) (RelIso.symm.{u1, u1} Ξ± Ξ² r s f))))) hr))
Case conversion may be inaccurate. Consider using '#align ordinal.rel_iso_enum Ordinal.relIso_enumβ'. -/
theorem relIso_enum {Ξ± Ξ² : Type u} {r : Ξ± β Ξ± β Prop} {s : Ξ² β Ξ² β Prop} [IsWellOrder Ξ± r]
[IsWellOrder Ξ² s] (f : r βr s) (o : Ordinal) (hr : o < type r) :
f (enum r o hr) =
enum s o
(by
convert hr using 1
apply Quotient.sound
exact β¨f.symmβ©) :=
relIso_enum' _ _ _ _
#align ordinal.rel_iso_enum Ordinal.relIso_enum
#print Ordinal.lt_wf /-
theorem lt_wf : @WellFounded Ordinal (Β· < Β·) :=
β¨fun a =>
inductionOn a fun Ξ± r wo =>
suffices β a, Acc (Β· < Β·) (typein r a) from
β¨_, fun o h =>
let β¨a, eβ© := typein_surj r h
e βΈ this aβ©
fun a =>
Acc.recOn (wo.wf.apply a) fun x H IH =>
β¨_, fun o h =>
by
rcases typein_surj r (lt_trans h (typein_lt_type r _)) with β¨b, rflβ©
exact IH _ ((typein_lt_typein r).1 h)β©β©
#align ordinal.lt_wf Ordinal.lt_wf
-/
instance : WellFoundedRelation Ordinal :=
β¨(Β· < Β·), lt_wfβ©
#print Ordinal.induction /-
/-- Reformulation of well founded induction on ordinals as a lemma that works with the
`induction` tactic, as in `induction i using ordinal.induction with i IH`. -/
theorem induction {p : Ordinal.{u} β Prop} (i : Ordinal.{u}) (h : β j, (β k, k < j β p k) β p j) :
p i :=
lt_wf.induction i h
#align ordinal.induction Ordinal.induction
-/
#print Ordinal.typein.principalSeg /-
/-- Principal segment version of the `typein` function, embedding a well order into
ordinals as a principal segment. -/
def typein.principalSeg {Ξ± : Type u} (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] :
@PrincipalSeg Ξ± Ordinal.{u} r (Β· < Β·) :=
β¨RelEmbedding.ofMonotone (typein r) fun a b => (typein_lt_typein r).2, type r, fun b =>
β¨fun h => β¨enum r _ h, typein_enum r hβ©, fun β¨a, eβ© => e βΈ typein_lt_type _ _β©β©
#align ordinal.typein.principal_seg Ordinal.typein.principalSeg
-/
/- warning: ordinal.typein.principal_seg_coe -> Ordinal.typein.principalSeg_coe is a dubious translation:
lean 3 declaration is
forall {Ξ± : Type.{u1}} (r : Ξ± -> Ξ± -> Prop) [_inst_1 : IsWellOrder.{u1} Ξ± r], Eq.{succ (succ u1)} ((fun (_x : PrincipalSeg.{u1, succ u1} Ξ± Ordinal.{u1} r (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})))) => Ξ± -> Ordinal.{u1}) (Ordinal.typein.principalSeg.{u1} Ξ± r _inst_1)) (coeFn.{succ (succ u1), succ (succ u1)} (PrincipalSeg.{u1, succ u1} Ξ± Ordinal.{u1} r (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})))) (fun (_x : PrincipalSeg.{u1, succ u1} Ξ± Ordinal.{u1} r (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})))) => Ξ± -> Ordinal.{u1}) (PrincipalSeg.hasCoeToFun.{u1, succ u1} Ξ± Ordinal.{u1} r (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})))) (Ordinal.typein.principalSeg.{u1} Ξ± r _inst_1)) (Ordinal.typein.{u1} Ξ± r _inst_1)
but is expected to have type
forall {Ξ± : Type.{u1}} (r : Ξ± -> Ξ± -> Prop) [_inst_1 : IsWellOrder.{u1} Ξ± r], Eq.{succ (succ u1)} (forall (a : Ξ±), (fun ([email protected]._hyg.19 : Ξ±) => Ordinal.{u1}) a) (FunLike.coe.{succ (succ u1), succ u1, succ (succ u1)} (Function.Embedding.{succ u1, succ (succ u1)} Ξ± Ordinal.{u1}) Ξ± (fun (_x : Ξ±) => (fun ([email protected]._hyg.19 : Ξ±) => Ordinal.{u1}) _x) (EmbeddingLike.toFunLike.{succ (succ u1), succ u1, succ (succ u1)} (Function.Embedding.{succ u1, succ (succ u1)} Ξ± Ordinal.{u1}) Ξ± Ordinal.{u1} (Function.instEmbeddingLikeEmbedding.{succ u1, succ (succ u1)} Ξ± Ordinal.{u1})) (RelEmbedding.toEmbedding.{u1, succ u1} Ξ± Ordinal.{u1} r (fun ([email protected]._hyg.6003 : Ordinal.{u1}) ([email protected]._hyg.6005 : Ordinal.{u1}) => LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) [email protected]._hyg.6003 [email protected]._hyg.6005) (PrincipalSeg.toRelEmbedding.{u1, succ u1} Ξ± Ordinal.{u1} r (fun ([email protected]._hyg.6003 : Ordinal.{u1}) ([email protected]._hyg.6005 : Ordinal.{u1}) => LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) [email protected]._hyg.6003 [email protected]._hyg.6005) (Ordinal.typein.principalSeg.{u1} Ξ± r _inst_1)))) (Ordinal.typein.{u1} Ξ± r _inst_1)
Case conversion may be inaccurate. Consider using '#align ordinal.typein.principal_seg_coe Ordinal.typein.principalSeg_coeβ'. -/
@[simp]
theorem typein.principalSeg_coe (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] :
(typein.principalSeg r : Ξ± β Ordinal) = typein r :=
rfl
#align ordinal.typein.principal_seg_coe Ordinal.typein.principalSeg_coe
/-! ### Cardinality of ordinals -/
#print Ordinal.card /-
/-- The cardinal of an ordinal is the cardinality of any type on which a relation with that order
type is defined. -/
def card : Ordinal β Cardinal :=
Quotient.map WellOrder.Ξ± fun β¨Ξ±, r, _β© β¨Ξ², s, _β© β¨eβ© => β¨e.toEquivβ©
#align ordinal.card Ordinal.card
-/
#print Ordinal.card_type /-
@[simp]
theorem card_type (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] : card (type r) = (#Ξ±) :=
rfl
#align ordinal.card_type Ordinal.card_type
-/
#print Ordinal.card_typein /-
@[simp]
theorem card_typein {r : Ξ± β Ξ± β Prop} [wo : IsWellOrder Ξ± r] (x : Ξ±) :
(#{ y // r y x }) = (typein r x).card :=
rfl
#align ordinal.card_typein Ordinal.card_typein
-/
#print Ordinal.card_le_card /-
theorem card_le_card {oβ oβ : Ordinal} : oβ β€ oβ β card oβ β€ card oβ :=
inductionOn oβ fun Ξ± r _ => inductionOn oβ fun Ξ² s _ β¨β¨β¨f, _β©, _β©β© => β¨fβ©
#align ordinal.card_le_card Ordinal.card_le_card
-/
#print Ordinal.card_zero /-
@[simp]
theorem card_zero : card 0 = 0 :=
rfl
#align ordinal.card_zero Ordinal.card_zero
-/
#print Ordinal.card_eq_zero /-
@[simp]
theorem card_eq_zero {o} : card o = 0 β o = 0 :=
β¨inductionOn o fun Ξ± r _ h => by
haveI := Cardinal.mk_eq_zero_iff.1 h
apply type_eq_zero_of_empty,
fun e => by simp only [e, card_zero]β©
#align ordinal.card_eq_zero Ordinal.card_eq_zero
-/
/- warning: ordinal.card_one -> Ordinal.card_one is a dubious translation:
lean 3 declaration is
Eq.{succ (succ u1)} Cardinal.{u1} (Ordinal.card.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))) (OfNat.ofNat.{succ u1} Cardinal.{u1} 1 (OfNat.mk.{succ u1} Cardinal.{u1} 1 (One.one.{succ u1} Cardinal.{u1} Cardinal.hasOne.{u1})))
but is expected to have type
Eq.{succ (succ u1)} Cardinal.{u1} (Ordinal.card.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))) (OfNat.ofNat.{succ u1} Cardinal.{u1} 1 (One.toOfNat1.{succ u1} Cardinal.{u1} Cardinal.instOneCardinal.{u1}))
Case conversion may be inaccurate. Consider using '#align ordinal.card_one Ordinal.card_oneβ'. -/
@[simp]
theorem card_one : card 1 = 1 :=
rfl
#align ordinal.card_one Ordinal.card_one
/-! ### Lifting ordinals to a higher universe -/
#print Ordinal.lift /-
/-- The universe lift operation for ordinals, which embeds `ordinal.{u}` as
a proper initial segment of `ordinal.{v}` for `v > u`. For the initial segment version,
see `lift.initial_seg`. -/
def lift (o : Ordinal.{v}) : Ordinal.{max v u} :=
Quotient.liftOn o (fun w => type <| ULift.down β»ΒΉ'o w.R) fun β¨Ξ±, r, _β© β¨Ξ², s, _β© β¨fβ© =>
Quot.sound
β¨(RelIso.preimage Equiv.ulift r).trans <| f.trans (RelIso.preimage Equiv.ulift s).symmβ©
#align ordinal.lift Ordinal.lift
-/
/- warning: ordinal.type_ulift -> Ordinal.type_uLift is a dubious translation:
lean 3 declaration is
forall {Ξ± : Type.{u2}} (r : Ξ± -> Ξ± -> Prop) [_inst_1 : IsWellOrder.{u2} Ξ± r], Eq.{succ (succ (max u2 u1))} Ordinal.{max u2 u1} (Ordinal.type.{max u2 u1} (ULift.{u1, u2} Ξ±) (Order.Preimage.{succ (max u2 u1), succ u2} (ULift.{u1, u2} Ξ±) Ξ± (ULift.down.{u1, u2} Ξ±) r) (RelIso.IsWellOrder.ulift.{u2, u1} Ξ± r _inst_1)) (Ordinal.lift.{u1, u2} (Ordinal.type.{u2} Ξ± r _inst_1))
but is expected to have type
forall {Ξ± : Type.{u1}} (r : Ξ± -> Ξ± -> Prop) [_inst_1 : IsWellOrder.{u1} Ξ± r], Eq.{max (succ (succ u1)) (succ (succ u2))} Ordinal.{max u1 u2} (Ordinal.type.{max u1 u2} (ULift.{u2, u1} Ξ±) (Order.Preimage.{succ (max u1 u2), succ u1} (ULift.{u2, u1} Ξ±) Ξ± (ULift.down.{u2, u1} Ξ±) r) (RelIso.IsWellOrder.ulift.{u1, u2} Ξ± r _inst_1)) (Ordinal.lift.{u2, u1} (Ordinal.type.{u1} Ξ± r _inst_1))
Case conversion may be inaccurate. Consider using '#align ordinal.type_ulift Ordinal.type_uLiftβ'. -/
@[simp]
theorem type_uLift (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] :
type (ULift.down β»ΒΉ'o r) = lift.{v} (type r) :=
rfl
#align ordinal.type_ulift Ordinal.type_uLift
#print RelIso.ordinal_lift_type_eq /-
theorem RelIso.ordinal_lift_type_eq {Ξ± : Type u} {Ξ² : Type v} {r : Ξ± β Ξ± β Prop} {s : Ξ² β Ξ² β Prop}
[IsWellOrder Ξ± r] [IsWellOrder Ξ² s] (f : r βr s) : lift.{v} (type r) = lift.{u} (type s) :=
((RelIso.preimage Equiv.ulift r).trans <|
f.trans (RelIso.preimage Equiv.ulift s).symm).ordinal_type_eq
#align rel_iso.ordinal_lift_type_eq RelIso.ordinal_lift_type_eq
-/
#print Ordinal.type_lift_preimage /-
@[simp]
theorem type_lift_preimage {Ξ± : Type u} {Ξ² : Type v} (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r]
(f : Ξ² β Ξ±) : lift.{u} (type (f β»ΒΉ'o r)) = lift.{v} (type r) :=
(RelIso.preimage f r).ordinal_lift_type_eq
#align ordinal.type_lift_preimage Ordinal.type_lift_preimage
-/
#print Ordinal.lift_umax /-
/-- `lift.{(max u v) u}` equals `lift.{v u}`. Using `set_option pp.universes true` will make it much
easier to understand what's happening when using this lemma. -/
@[simp]
theorem lift_umax : lift.{max u v, u} = lift.{v, u} :=
funext fun a =>
inductionOn a fun Ξ± r _ =>
Quotient.sound β¨(RelIso.preimage Equiv.ulift r).trans (RelIso.preimage Equiv.ulift r).symmβ©
#align ordinal.lift_umax Ordinal.lift_umax
-/
#print Ordinal.lift_umax' /-
/-- `lift.{(max v u) u}` equals `lift.{v u}`. Using `set_option pp.universes true` will make it much
easier to understand what's happening when using this lemma. -/
@[simp]
theorem lift_umax' : lift.{max v u, u} = lift.{v, u} :=
lift_umax
#align ordinal.lift_umax' Ordinal.lift_umax'
-/
/- warning: ordinal.lift_id' -> Ordinal.lift_id' is a dubious translation:
lean 3 declaration is
forall (a : Ordinal.{max u1 u2}), Eq.{succ (succ (max u1 u2))} Ordinal.{max u1 u2} (Ordinal.lift.{u1, max u1 u2} a) a
but is expected to have type
forall (a : Ordinal.{max u2 u1}), Eq.{max (succ (succ u2)) (succ (succ u1))} Ordinal.{max u2 u1} (Ordinal.lift.{u2, max u2 u1} a) a
Case conversion may be inaccurate. Consider using '#align ordinal.lift_id' Ordinal.lift_id'β'. -/
/-- An ordinal lifted to a lower or equal universe equals itself. -/
@[simp]
theorem lift_id' (a : Ordinal) : lift a = a :=
inductionOn a fun Ξ± r _ => Quotient.sound β¨RelIso.preimage Equiv.ulift rβ©
#align ordinal.lift_id' Ordinal.lift_id'
#print Ordinal.lift_id /-
/-- An ordinal lifted to the same universe equals itself. -/
@[simp]
theorem lift_id : β a, lift.{u, u} a = a :=
lift_id'.{u, u}
#align ordinal.lift_id Ordinal.lift_id
-/
#print Ordinal.lift_uzero /-
/-- An ordinal lifted to the zero universe equals itself. -/
@[simp]
theorem lift_uzero (a : Ordinal.{u}) : lift.{0} a = a :=
lift_id'.{0, u} a
#align ordinal.lift_uzero Ordinal.lift_uzero
-/
/- warning: ordinal.lift_lift -> Ordinal.lift_lift is a dubious translation:
lean 3 declaration is
forall (a : Ordinal.{u3}), Eq.{succ (succ (max (max u3 u1) u2))} Ordinal.{max (max u3 u1) u2} (Ordinal.lift.{u2, max u3 u1} (Ordinal.lift.{u1, u3} a)) (Ordinal.lift.{max u1 u2, u3} a)
but is expected to have type
forall (a : Ordinal.{u1}), Eq.{max (max (succ (succ u2)) (succ (succ u3))) (succ (succ u1))} Ordinal.{max (max u2 u1) u3} (Ordinal.lift.{u3, max u2 u1} (Ordinal.lift.{u2, u1} a)) (Ordinal.lift.{max u2 u3, u1} a)
Case conversion may be inaccurate. Consider using '#align ordinal.lift_lift Ordinal.lift_liftβ'. -/
@[simp]
theorem lift_lift (a : Ordinal) : lift.{w} (lift.{v} a) = lift.{max v w} a :=
inductionOn a fun Ξ± r _ =>
Quotient.sound
β¨(RelIso.preimage Equiv.ulift _).trans <|
(RelIso.preimage Equiv.ulift _).trans (RelIso.preimage Equiv.ulift _).symmβ©
#align ordinal.lift_lift Ordinal.lift_lift
#print Ordinal.lift_type_le /-
theorem lift_type_le {Ξ± : Type u} {Ξ² : Type v} {r s} [IsWellOrder Ξ± r] [IsWellOrder Ξ² s] :
lift.{max v w} (type r) β€ lift.{max u w} (type s) β Nonempty (r βΌi s) :=
β¨fun β¨fβ© =>
β¨(InitialSeg.ofIso (RelIso.preimage Equiv.ulift r).symm).trans <|
f.trans (InitialSeg.ofIso (RelIso.preimage Equiv.ulift s))β©,
fun β¨fβ© =>
β¨(InitialSeg.ofIso (RelIso.preimage Equiv.ulift r)).trans <|
f.trans (InitialSeg.ofIso (RelIso.preimage Equiv.ulift s).symm)β©β©
#align ordinal.lift_type_le Ordinal.lift_type_le
-/
#print Ordinal.lift_type_eq /-
theorem lift_type_eq {Ξ± : Type u} {Ξ² : Type v} {r s} [IsWellOrder Ξ± r] [IsWellOrder Ξ² s] :
lift.{max v w} (type r) = lift.{max u w} (type s) β Nonempty (r βr s) :=
Quotient.eq'.trans
β¨fun β¨fβ© =>
β¨(RelIso.preimage Equiv.ulift r).symm.trans <| f.trans (RelIso.preimage Equiv.ulift s)β©,
fun β¨fβ© =>
β¨(RelIso.preimage Equiv.ulift r).trans <| f.trans (RelIso.preimage Equiv.ulift s).symmβ©β©
#align ordinal.lift_type_eq Ordinal.lift_type_eq
-/
#print Ordinal.lift_type_lt /-
theorem lift_type_lt {Ξ± : Type u} {Ξ² : Type v} {r s} [IsWellOrder Ξ± r] [IsWellOrder Ξ² s] :
lift.{max v w} (type r) < lift.{max u w} (type s) β Nonempty (r βΊi s) := by
haveI :=
@RelEmbedding.isWellOrder _ _ (@Equiv.ulift.{max v w} Ξ± β»ΒΉ'o r) r
(RelIso.preimage Equiv.ulift.{max v w} r) _ <;>
haveI :=
@RelEmbedding.isWellOrder _ _ (@Equiv.ulift.{max u w} Ξ² β»ΒΉ'o s) s
(RelIso.preimage Equiv.ulift.{max u w} s) _ <;>
exact
β¨fun β¨fβ© =>
β¨(f.equivLT (RelIso.preimage Equiv.ulift r).symm).ltLe
(InitialSeg.ofIso (RelIso.preimage Equiv.ulift s))β©,
fun β¨fβ© =>
β¨(f.equivLT (RelIso.preimage Equiv.ulift r)).ltLe
(InitialSeg.ofIso (RelIso.preimage Equiv.ulift s).symm)β©β©
#align ordinal.lift_type_lt Ordinal.lift_type_lt
-/
#print Ordinal.lift_le /-
@[simp]
theorem lift_le {a b : Ordinal} : lift.{u, v} a β€ lift b β a β€ b :=
inductionOn a fun Ξ± r _ =>
inductionOn b fun Ξ² s _ => by
rw [β lift_umax]
exact lift_type_le
#align ordinal.lift_le Ordinal.lift_le
-/
/- warning: ordinal.lift_inj -> Ordinal.lift_inj is a dubious translation:
lean 3 declaration is
forall {a : Ordinal.{u1}} {b : Ordinal.{u1}}, Iff (Eq.{succ (succ (max u1 u2))} Ordinal.{max u1 u2} (Ordinal.lift.{u2, u1} a) (Ordinal.lift.{u2, u1} b)) (Eq.{succ (succ u1)} Ordinal.{u1} a b)
but is expected to have type
forall {a : Ordinal.{u2}} {b : Ordinal.{u2}}, Iff (Eq.{max (succ (succ u1)) (succ (succ u2))} Ordinal.{max u2 u1} (Ordinal.lift.{u1, u2} a) (Ordinal.lift.{u1, u2} b)) (Eq.{succ (succ u2)} Ordinal.{u2} a b)
Case conversion may be inaccurate. Consider using '#align ordinal.lift_inj Ordinal.lift_injβ'. -/
@[simp]
theorem lift_inj {a b : Ordinal} : lift a = lift b β a = b := by
simp only [le_antisymm_iff, lift_le]
#align ordinal.lift_inj Ordinal.lift_inj
/- warning: ordinal.lift_lt -> Ordinal.lift_lt is a dubious translation:
lean 3 declaration is
forall {a : Ordinal.{u1}} {b : Ordinal.{u1}}, Iff (LT.lt.{succ (max u1 u2)} Ordinal.{max u1 u2} (Preorder.toLT.{succ (max u1 u2)} Ordinal.{max u1 u2} (PartialOrder.toPreorder.{succ (max u1 u2)} Ordinal.{max u1 u2} Ordinal.partialOrder.{max u1 u2})) (Ordinal.lift.{u2, u1} a) (Ordinal.lift.{u2, u1} b)) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) a b)
but is expected to have type
forall {a : Ordinal.{u2}} {b : Ordinal.{u2}}, Iff (LT.lt.{max (succ u1) (succ u2)} Ordinal.{max u2 u1} (Preorder.toLT.{max (succ u1) (succ u2)} Ordinal.{max u2 u1} (PartialOrder.toPreorder.{max (succ u1) (succ u2)} Ordinal.{max u2 u1} Ordinal.partialOrder.{max u1 u2})) (Ordinal.lift.{u1, u2} a) (Ordinal.lift.{u1, u2} b)) (LT.lt.{succ u2} Ordinal.{u2} (Preorder.toLT.{succ u2} Ordinal.{u2} (PartialOrder.toPreorder.{succ u2} Ordinal.{u2} Ordinal.partialOrder.{u2})) a b)
Case conversion may be inaccurate. Consider using '#align ordinal.lift_lt Ordinal.lift_ltβ'. -/
@[simp]
theorem lift_lt {a b : Ordinal} : lift a < lift b β a < b := by
simp only [lt_iff_le_not_le, lift_le]
#align ordinal.lift_lt Ordinal.lift_lt
/- warning: ordinal.lift_zero -> Ordinal.lift_zero is a dubious translation:
lean 3 declaration is
Eq.{succ (succ (max u1 u2))} Ordinal.{max u1 u2} (Ordinal.lift.{u2, u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1})))) (OfNat.ofNat.{succ (max u1 u2)} Ordinal.{max u1 u2} 0 (OfNat.mk.{succ (max u1 u2)} Ordinal.{max u1 u2} 0 (Zero.zero.{succ (max u1 u2)} Ordinal.{max u1 u2} Ordinal.hasZero.{max u1 u2})))
but is expected to have type
Eq.{max (succ (succ u2)) (succ (succ u1))} Ordinal.{max u2 u1} (Ordinal.lift.{u1, u2} (OfNat.ofNat.{succ u2} Ordinal.{u2} 0 (Zero.toOfNat0.{succ u2} Ordinal.{u2} Ordinal.zero.{u2}))) (OfNat.ofNat.{max (succ u2) (succ u1)} Ordinal.{max u2 u1} 0 (Zero.toOfNat0.{max (succ u2) (succ u1)} Ordinal.{max u2 u1} Ordinal.zero.{max u2 u1}))
Case conversion may be inaccurate. Consider using '#align ordinal.lift_zero Ordinal.lift_zeroβ'. -/
@[simp]
theorem lift_zero : lift 0 = 0 :=
type_eq_zero_of_empty _
#align ordinal.lift_zero Ordinal.lift_zero
/- warning: ordinal.lift_one -> Ordinal.lift_one is a dubious translation:
lean 3 declaration is
Eq.{succ (succ (max u1 u2))} Ordinal.{max u1 u2} (Ordinal.lift.{u2, u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))) (OfNat.ofNat.{succ (max u1 u2)} Ordinal.{max u1 u2} 1 (OfNat.mk.{succ (max u1 u2)} Ordinal.{max u1 u2} 1 (One.one.{succ (max u1 u2)} Ordinal.{max u1 u2} Ordinal.hasOne.{max u1 u2})))
but is expected to have type
Eq.{max (succ (succ u2)) (succ (succ u1))} Ordinal.{max u2 u1} (Ordinal.lift.{u1, u2} (OfNat.ofNat.{succ u2} Ordinal.{u2} 1 (One.toOfNat1.{succ u2} Ordinal.{u2} Ordinal.one.{u2}))) (OfNat.ofNat.{max (succ u2) (succ u1)} Ordinal.{max u2 u1} 1 (One.toOfNat1.{max (succ u2) (succ u1)} Ordinal.{max u2 u1} Ordinal.one.{max u2 u1}))
Case conversion may be inaccurate. Consider using '#align ordinal.lift_one Ordinal.lift_oneβ'. -/
@[simp]
theorem lift_one : lift 1 = 1 :=
type_eq_one_of_unique _
#align ordinal.lift_one Ordinal.lift_one
/- warning: ordinal.lift_card -> Ordinal.lift_card is a dubious translation:
lean 3 declaration is
forall (a : Ordinal.{u1}), Eq.{succ (succ (max u1 u2))} Cardinal.{max u1 u2} (Cardinal.lift.{u2, u1} (Ordinal.card.{u1} a)) (Ordinal.card.{max u1 u2} (Ordinal.lift.{u2, u1} a))
but is expected to have type
forall (a : Ordinal.{u2}), Eq.{max (succ (succ u1)) (succ (succ u2))} Cardinal.{max u2 u1} (Cardinal.lift.{u1, u2} (Ordinal.card.{u2} a)) (Ordinal.card.{max u1 u2} (Ordinal.lift.{u1, u2} a))
Case conversion may be inaccurate. Consider using '#align ordinal.lift_card Ordinal.lift_cardβ'. -/
@[simp]
theorem lift_card (a) : (card a).lift = card (lift a) :=
inductionOn a fun Ξ± r _ => rfl
#align ordinal.lift_card Ordinal.lift_card
#print Ordinal.lift_down' /-
theorem lift_down' {a : Cardinal.{u}} {b : Ordinal.{max u v}} (h : card b β€ a.lift) :
β a', lift a' = b :=
let β¨c, eβ© := Cardinal.lift_down h
Cardinal.inductionOn c
(fun Ξ± =>
inductionOn b fun Ξ² s _ e' => by
skip
rw [card_type, β Cardinal.lift_id'.{max u v, u} (#Ξ²), β Cardinal.lift_umax.{u, v},
lift_mk_eq.{u, max u v, max u v}] at e'
cases' e' with f
have g := RelIso.preimage f s
haveI := (g : βf β»ΒΉ'o s βͺr s).IsWellOrder
have := lift_type_eq.{u, max u v, max u v}.2 β¨gβ©
rw [lift_id, lift_umax.{u, v}] at this
exact β¨_, thisβ©)
e
#align ordinal.lift_down' Ordinal.lift_down'
-/
#print Ordinal.lift_down /-
theorem lift_down {a : Ordinal.{u}} {b : Ordinal.{max u v}} (h : b β€ lift a) : β a', lift a' = b :=
@lift_down' (card a) _ (by rw [lift_card] <;> exact card_le_card h)
#align ordinal.lift_down Ordinal.lift_down
-/
#print Ordinal.le_lift_iff /-
theorem le_lift_iff {a : Ordinal.{u}} {b : Ordinal.{max u v}} :
b β€ lift a β β a', lift a' = b β§ a' β€ a :=
β¨fun h =>
let β¨a', eβ© := lift_down h
β¨a', e, lift_le.1 <| e.symm βΈ hβ©,
fun β¨a', e, hβ© => e βΈ lift_le.2 hβ©
#align ordinal.le_lift_iff Ordinal.le_lift_iff
-/
#print Ordinal.lt_lift_iff /-
theorem lt_lift_iff {a : Ordinal.{u}} {b : Ordinal.{max u v}} :
b < lift a β β a', lift a' = b β§ a' < a :=
β¨fun h =>
let β¨a', eβ© := lift_down (le_of_lt h)
β¨a', e, lift_lt.1 <| e.symm βΈ hβ©,
fun β¨a', e, hβ© => e βΈ lift_lt.2 hβ©
#align ordinal.lt_lift_iff Ordinal.lt_lift_iff
-/
#print Ordinal.lift.initialSeg /-
/-- Initial segment version of the lift operation on ordinals, embedding `ordinal.{u}` in
`ordinal.{v}` as an initial segment when `u β€ v`. -/
def lift.initialSeg : @InitialSeg Ordinal.{u} Ordinal.{max u v} (Β· < Β·) (Β· < Β·) :=
β¨β¨β¨lift.{v}, fun a b => lift_inj.1β©, fun a b => lift_ltβ©, fun a b h => lift_down (le_of_lt h)β©
#align ordinal.lift.initial_seg Ordinal.lift.initialSeg
-/
/- warning: ordinal.lift.initial_seg_coe -> Ordinal.lift.initialSeg_coe is a dubious translation:
lean 3 declaration is
Eq.{max (succ (succ u1)) (succ (succ (max u1 u2)))} ((fun (_x : InitialSeg.{succ u1, succ (max u1 u2)} Ordinal.{u1} Ordinal.{max u1 u2} (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}))) (LT.lt.{succ (max u1 u2)} Ordinal.{max u1 u2} (Preorder.toLT.{succ (max u1 u2)} Ordinal.{max u1 u2} (PartialOrder.toPreorder.{succ (max u1 u2)} Ordinal.{max u1 u2} Ordinal.partialOrder.{max u1 u2})))) => Ordinal.{u1} -> Ordinal.{max u1 u2}) Ordinal.lift.initialSeg.{u1, u2}) (coeFn.{max (succ (succ u1)) (succ (succ (max u1 u2))), max (succ (succ u1)) (succ (succ (max u1 u2)))} (InitialSeg.{succ u1, succ (max u1 u2)} Ordinal.{u1} Ordinal.{max u1 u2} (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}))) (LT.lt.{succ (max u1 u2)} Ordinal.{max u1 u2} (Preorder.toLT.{succ (max u1 u2)} Ordinal.{max u1 u2} (PartialOrder.toPreorder.{succ (max u1 u2)} Ordinal.{max u1 u2} Ordinal.partialOrder.{max u1 u2})))) (fun (_x : InitialSeg.{succ u1, succ (max u1 u2)} Ordinal.{u1} Ordinal.{max u1 u2} (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}))) (LT.lt.{succ (max u1 u2)} Ordinal.{max u1 u2} (Preorder.toLT.{succ (max u1 u2)} Ordinal.{max u1 u2} (PartialOrder.toPreorder.{succ (max u1 u2)} Ordinal.{max u1 u2} Ordinal.partialOrder.{max u1 u2})))) => Ordinal.{u1} -> Ordinal.{max u1 u2}) (FunLike.hasCoeToFun.{max (succ (succ u1)) (succ (succ (max u1 u2))), succ (succ u1), succ (succ (max u1 u2))} (InitialSeg.{succ u1, succ (max u1 u2)} Ordinal.{u1} Ordinal.{max u1 u2} (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}))) (LT.lt.{succ (max u1 u2)} Ordinal.{max u1 u2} (Preorder.toLT.{succ (max u1 u2)} Ordinal.{max u1 u2} (PartialOrder.toPreorder.{succ (max u1 u2)} Ordinal.{max u1 u2} Ordinal.partialOrder.{max u1 u2})))) Ordinal.{u1} (fun (_x : Ordinal.{u1}) => Ordinal.{max u1 u2}) (EmbeddingLike.toFunLike.{max (succ (succ u1)) (succ (succ (max u1 u2))), succ (succ u1), succ (succ (max u1 u2))} (InitialSeg.{succ u1, succ (max u1 u2)} Ordinal.{u1} Ordinal.{max u1 u2} (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}))) (LT.lt.{succ (max u1 u2)} Ordinal.{max u1 u2} (Preorder.toLT.{succ (max u1 u2)} Ordinal.{max u1 u2} (PartialOrder.toPreorder.{succ (max u1 u2)} Ordinal.{max u1 u2} Ordinal.partialOrder.{max u1 u2})))) Ordinal.{u1} Ordinal.{max u1 u2} (InitialSeg.embeddingLike.{succ u1, succ (max u1 u2)} Ordinal.{u1} Ordinal.{max u1 u2} (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}))) (LT.lt.{succ (max u1 u2)} Ordinal.{max u1 u2} (Preorder.toLT.{succ (max u1 u2)} Ordinal.{max u1 u2} (PartialOrder.toPreorder.{succ (max u1 u2)} Ordinal.{max u1 u2} Ordinal.partialOrder.{max u1 u2})))))) Ordinal.lift.initialSeg.{u1, u2}) Ordinal.lift.{u2, u1}
but is expected to have type
Eq.{max (succ (succ u1)) (succ (succ u2))} (forall (a : Ordinal.{u1}), (fun ([email protected]._hyg.19 : Ordinal.{u1}) => Ordinal.{max u1 u2}) a) (FunLike.coe.{max (succ (succ u1)) (succ (succ u2)), succ (succ u1), max (succ (succ u1)) (succ (succ u2))} (InitialSeg.{succ u1, max (succ u1) (succ u2)} Ordinal.{u1} Ordinal.{max u1 u2} (fun ([email protected]._hyg.8587 : Ordinal.{u1}) ([email protected]._hyg.8589 : Ordinal.{u1}) => LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) [email protected]._hyg.8587 [email protected]._hyg.8589) (fun ([email protected]._hyg.8602 : Ordinal.{max u1 u2}) ([email protected]._hyg.8604 : Ordinal.{max u1 u2}) => LT.lt.{max (succ u1) (succ u2)} Ordinal.{max u1 u2} (Preorder.toLT.{max (succ u1) (succ u2)} Ordinal.{max u1 u2} (PartialOrder.toPreorder.{max (succ u1) (succ u2)} Ordinal.{max u1 u2} Ordinal.partialOrder.{max u1 u2})) [email protected]._hyg.8602 [email protected]._hyg.8604)) Ordinal.{u1} (fun (_x : Ordinal.{u1}) => (fun ([email protected]._hyg.19 : Ordinal.{u1}) => Ordinal.{max u1 u2}) _x) (EmbeddingLike.toFunLike.{max (succ (succ u1)) (succ (succ u2)), succ (succ u1), max (succ (succ u1)) (succ (succ u2))} (InitialSeg.{succ u1, max (succ u1) (succ u2)} Ordinal.{u1} Ordinal.{max u1 u2} (fun ([email protected]._hyg.8587 : Ordinal.{u1}) ([email protected]._hyg.8589 : Ordinal.{u1}) => LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) [email protected]._hyg.8587 [email protected]._hyg.8589) (fun ([email protected]._hyg.8602 : Ordinal.{max u1 u2}) ([email protected]._hyg.8604 : Ordinal.{max u1 u2}) => LT.lt.{max (succ u1) (succ u2)} Ordinal.{max u1 u2} (Preorder.toLT.{max (succ u1) (succ u2)} Ordinal.{max u1 u2} (PartialOrder.toPreorder.{max (succ u1) (succ u2)} Ordinal.{max u1 u2} Ordinal.partialOrder.{max u1 u2})) [email protected]._hyg.8602 [email protected]._hyg.8604)) Ordinal.{u1} Ordinal.{max u1 u2} (InitialSeg.instEmbeddingLikeInitialSeg.{succ u1, max (succ u1) (succ u2)} Ordinal.{u1} Ordinal.{max u1 u2} (fun ([email protected]._hyg.8587 : Ordinal.{u1}) ([email protected]._hyg.8589 : Ordinal.{u1}) => LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) [email protected]._hyg.8587 [email protected]._hyg.8589) (fun ([email protected]._hyg.8602 : Ordinal.{max u1 u2}) ([email protected]._hyg.8604 : Ordinal.{max u1 u2}) => LT.lt.{max (succ u1) (succ u2)} Ordinal.{max u1 u2} (Preorder.toLT.{max (succ u1) (succ u2)} Ordinal.{max u1 u2} (PartialOrder.toPreorder.{max (succ u1) (succ u2)} Ordinal.{max u1 u2} Ordinal.partialOrder.{max u1 u2})) [email protected]._hyg.8602 [email protected]._hyg.8604))) Ordinal.lift.initialSeg.{u1, u2}) Ordinal.lift.{u2, u1}
Case conversion may be inaccurate. Consider using '#align ordinal.lift.initial_seg_coe Ordinal.lift.initialSeg_coeβ'. -/
@[simp]
theorem lift.initialSeg_coe : (lift.initialSeg : Ordinal β Ordinal) = lift :=
rfl
#align ordinal.lift.initial_seg_coe Ordinal.lift.initialSeg_coe
/-! ### The first infinite ordinal `omega` -/
#print Ordinal.omega /-
/-- `Ο` is the first infinite ordinal, defined as the order type of `β`. -/
def omega : Ordinal.{u} :=
lift <| @type β (Β· < Β·) _
#align ordinal.omega Ordinal.omega
-/
-- mathport name: ordinal.omega
scoped notation "Ο" => Ordinal.omega
#print Ordinal.type_nat_lt /-
/-- Note that the presence of this lemma makes `simp [omega]` form a loop. -/
@[simp]
theorem type_nat_lt : @type β (Β· < Β·) _ = Ο :=
(lift_id _).symm
#align ordinal.type_nat_lt Ordinal.type_nat_lt
-/
#print Ordinal.card_omega /-
@[simp]
theorem card_omega : card Ο = β΅β :=
rfl
#align ordinal.card_omega Ordinal.card_omega
-/
#print Ordinal.lift_omega /-
@[simp]
theorem lift_omega : lift Ο = Ο :=
lift_lift _
#align ordinal.lift_omega Ordinal.lift_omega
-/
/-!
### Definition and first properties of addition on ordinals
In this paragraph, we introduce the addition on ordinals, and prove just enough properties to
deduce that the order on ordinals is total (and therefore well-founded). Further properties of
the addition, together with properties of the other operations, are proved in
`ordinal_arithmetic.lean`.
-/
/-- `oβ + oβ` is the order on the disjoint union of `oβ` and `oβ` obtained by declaring that
every element of `oβ` is smaller than every element of `oβ`. -/
instance : Add Ordinal.{u} :=
β¨fun oβ oβ =>
Quotient.liftOnβ oβ oβ (fun β¨Ξ±, r, woβ© β¨Ξ², s, wo'β© => type (Sum.Lex r s))
fun β¨Ξ±β, rβ, oββ© β¨Ξ±β, rβ, oββ© β¨Ξ²β, sβ, pββ© β¨Ξ²β, sβ, pββ© β¨fβ© β¨gβ© =>
Quot.sound β¨RelIso.sumLexCongr f gβ©β©
instance : AddMonoidWithOne Ordinal.{u}
where
add := (Β· + Β·)
zero := 0
one := 1
zero_add o :=
inductionOn o fun Ξ± r _ =>
Eq.symm <| Quotient.sound β¨β¨(emptySum PEmpty Ξ±).symm, fun a b => Sum.lex_inr_inrβ©β©
add_zero o :=
inductionOn o fun Ξ± r _ =>
Eq.symm <| Quotient.sound β¨β¨(sumEmpty Ξ± PEmpty).symm, fun a b => Sum.lex_inl_inlβ©β©
add_assoc oβ oβ oβ :=
Quotient.induction_onβ oβ oβ oβ fun β¨Ξ±, r, _β© β¨Ξ², s, _β© β¨Ξ³, t, _β© =>
Quot.sound
β¨β¨sumAssoc _ _ _, fun a b => by
rcases a with (β¨a | aβ© | a) <;> rcases b with (β¨b | bβ© | b) <;>
simp only [sum_assoc_apply_inl_inl, sum_assoc_apply_inl_inr, sum_assoc_apply_inr,
Sum.lex_inl_inl, Sum.lex_inr_inr, Sum.Lex.sep, Sum.lex_inr_inl]β©β©
/- warning: ordinal.card_add -> Ordinal.card_add is a dubious translation:
lean 3 declaration is
forall (oβ : Ordinal.{u1}) (oβ : Ordinal.{u1}), Eq.{succ (succ u1)} Cardinal.{u1} (Ordinal.card.{u1} (HAdd.hAdd.{succ u1, succ u1, succ u1} Ordinal.{u1} Ordinal.{u1} Ordinal.{u1} (instHAdd.{succ u1} Ordinal.{u1} Ordinal.hasAdd.{u1}) oβ oβ)) (HAdd.hAdd.{succ u1, succ u1, succ u1} Cardinal.{u1} Cardinal.{u1} Cardinal.{u1} (instHAdd.{succ u1} Cardinal.{u1} Cardinal.hasAdd.{u1}) (Ordinal.card.{u1} oβ) (Ordinal.card.{u1} oβ))
but is expected to have type
forall (oβ : Ordinal.{u1}) (oβ : Ordinal.{u1}), Eq.{succ (succ u1)} Cardinal.{u1} (Ordinal.card.{u1} (HAdd.hAdd.{succ u1, succ u1, succ u1} Ordinal.{u1} Ordinal.{u1} Ordinal.{u1} (instHAdd.{succ u1} Ordinal.{u1} Ordinal.add.{u1}) oβ oβ)) (HAdd.hAdd.{succ u1, succ u1, succ u1} Cardinal.{u1} Cardinal.{u1} Cardinal.{u1} (instHAdd.{succ u1} Cardinal.{u1} Cardinal.instAddCardinal.{u1}) (Ordinal.card.{u1} oβ) (Ordinal.card.{u1} oβ))
Case conversion may be inaccurate. Consider using '#align ordinal.card_add Ordinal.card_addβ'. -/
@[simp]
theorem card_add (oβ oβ : Ordinal) : card (oβ + oβ) = card oβ + card oβ :=
inductionOn oβ fun Ξ± r _ => inductionOn oβ fun Ξ² s _ => rfl
#align ordinal.card_add Ordinal.card_add
#print Ordinal.type_sum_lex /-
@[simp]
theorem type_sum_lex {Ξ± Ξ² : Type u} (r : Ξ± β Ξ± β Prop) (s : Ξ² β Ξ² β Prop) [IsWellOrder Ξ± r]
[IsWellOrder Ξ² s] : type (Sum.Lex r s) = type r + type s :=
rfl
#align ordinal.type_sum_lex Ordinal.type_sum_lex
-/
/- warning: ordinal.card_nat -> Ordinal.card_nat is a dubious translation:
lean 3 declaration is
forall (n : Nat), Eq.{succ (succ u1)} Cardinal.{u1} (Ordinal.card.{u1} ((fun (a : Type) (b : Type.{succ u1}) [self : HasLiftT.{1, succ (succ u1)} a b] => self.0) Nat Ordinal.{u1} (HasLiftT.mk.{1, succ (succ u1)} Nat Ordinal.{u1} (CoeTCβ.coe.{1, succ (succ u1)} Nat Ordinal.{u1} (Nat.castCoe.{succ u1} Ordinal.{u1} (AddMonoidWithOne.toNatCast.{succ u1} Ordinal.{u1} Ordinal.addMonoidWithOne.{u1})))) n)) ((fun (a : Type) (b : Type.{succ u1}) [self : HasLiftT.{1, succ (succ u1)} a b] => self.0) Nat Cardinal.{u1} (HasLiftT.mk.{1, succ (succ u1)} Nat Cardinal.{u1} (CoeTCβ.coe.{1, succ (succ u1)} Nat Cardinal.{u1} (Nat.castCoe.{succ u1} Cardinal.{u1} Cardinal.hasNatCast.{u1}))) n)
but is expected to have type
forall (n : Nat), Eq.{succ (succ u1)} Cardinal.{u1} (Ordinal.card.{u1} (Nat.cast.{succ u1} Ordinal.{u1} (AddMonoidWithOne.toNatCast.{succ u1} Ordinal.{u1} Ordinal.addMonoidWithOne.{u1}) n)) (Nat.cast.{succ u1} Cardinal.{u1} Cardinal.instNatCastCardinal.{u1} n)
Case conversion may be inaccurate. Consider using '#align ordinal.card_nat Ordinal.card_natβ'. -/
@[simp]
theorem card_nat (n : β) : card.{u} n = n := by
induction n <;> [rfl, simp only [card_add, card_one, Nat.cast_succ, *]]
#align ordinal.card_nat Ordinal.card_nat
#print Ordinal.add_covariantClass_le /-
instance add_covariantClass_le : CovariantClass Ordinal.{u} Ordinal.{u} (Β· + Β·) (Β· β€ Β·) :=
β¨fun c a b h => by revert h c;
exact
induction_on a fun Ξ±β rβ _ =>
induction_on b fun Ξ±β rβ _ β¨β¨β¨f, foβ©, fiβ©β© c =>
induction_on c fun Ξ² s _ =>
β¨β¨β¨(embedding.refl _).sum_map f, fun a b =>
match a, b with
| Sum.inl a, Sum.inl b => sum.lex_inl_inl.trans sum.lex_inl_inl.symm
| Sum.inl a, Sum.inr b => by apply iff_of_true <;> apply Sum.Lex.sep
| Sum.inr a, Sum.inl b => by apply iff_of_false <;> exact Sum.lex_inr_inl
| Sum.inr a, Sum.inr b => sum.lex_inr_inr.trans <| fo.trans sum.lex_inr_inr.symmβ©,
fun a b H =>
match a, b, H with
| _, Sum.inl b, _ => β¨Sum.inl b, rflβ©
| Sum.inl a, Sum.inr b, H => (Sum.lex_inr_inl H).elim
| Sum.inr a, Sum.inr b, H =>
let β¨w, hβ© := fi _ _ (Sum.lex_inr_inr.1 H)
β¨Sum.inr w, congr_arg Sum.inr hβ©β©β©β©
#align ordinal.add_covariant_class_le Ordinal.add_covariantClass_le
-/
#print Ordinal.add_swap_covariantClass_le /-
instance add_swap_covariantClass_le :
CovariantClass Ordinal.{u} Ordinal.{u} (swap (Β· + Β·)) (Β· β€ Β·) :=
β¨fun c a b h => by revert h c;
exact
induction_on a fun Ξ±β rβ hrβ =>
induction_on b fun Ξ±β rβ hrβ β¨β¨β¨f, foβ©, fiβ©β© c =>
induction_on c fun Ξ² s hs =>
@RelEmbedding.ordinal_type_le _ _ (Sum.Lex rβ s) (Sum.Lex rβ s) _ _
β¨f.sum_map (embedding.refl _), fun a b =>
by
constructor <;> intro H
Β·
cases' a with a a <;> cases' b with b b <;> cases H <;> constructor <;>
[rwa [β fo], assumption]
Β· cases H <;> constructor <;> [rwa [fo], assumption]β©β©
#align ordinal.add_swap_covariant_class_le Ordinal.add_swap_covariantClass_le
-/
#print Ordinal.le_add_right /-
theorem le_add_right (a b : Ordinal) : a β€ a + b := by
simpa only [add_zero] using add_le_add_left (Ordinal.zero_le b) a
#align ordinal.le_add_right Ordinal.le_add_right
-/
#print Ordinal.le_add_left /-
theorem le_add_left (a b : Ordinal) : a β€ b + a := by
simpa only [zero_add] using add_le_add_right (Ordinal.zero_le b) a
#align ordinal.le_add_left Ordinal.le_add_left
-/
instance : LinearOrder Ordinal :=
{
Ordinal.partialOrder with
le_total := fun a b =>
match lt_or_eq_of_le (le_add_left b a), lt_or_eq_of_le (le_add_right a b) with
| Or.inr h, _ => by rw [h] <;> exact Or.inl (le_add_right _ _)
| _, Or.inr h => by rw [h] <;> exact Or.inr (le_add_left _ _)
| Or.inl hβ, Or.inl hβ =>
inductionOn a
(fun Ξ±β rβ _ =>
inductionOn b fun Ξ±β rβ _ β¨fβ© β¨gβ© => by
skip
rw [β typein_top f, β typein_top g, le_iff_lt_or_eq, le_iff_lt_or_eq,
typein_lt_typein, typein_lt_typein]
rcases trichotomous_of (Sum.Lex rβ rβ) g.top f.top with (h | h | h) <;>
[exact Or.inl (Or.inl h),
Β· left
right
rw [h], exact Or.inr (Or.inl h)])
hβ hβ
decidableLe := Classical.decRel _ }
instance : WellFoundedLT Ordinal :=
β¨lt_wfβ©
instance : IsWellOrder Ordinal (Β· < Β·) where
instance : ConditionallyCompleteLinearOrderBot Ordinal :=
IsWellOrder.conditionallyCompleteLinearOrderBot _
/- warning: ordinal.max_zero_left -> Ordinal.max_zero_left is a dubious translation:
lean 3 declaration is
forall (a : Ordinal.{u1}), Eq.{succ (succ u1)} Ordinal.{u1} (LinearOrder.max.{succ u1} Ordinal.{u1} Ordinal.linearOrder.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) a) a
but is expected to have type
forall (a : Ordinal.{u1}), Eq.{succ (succ u1)} Ordinal.{u1} (Max.max.{succ u1} Ordinal.{u1} (LinearOrder.toMax.{succ u1} Ordinal.{u1} Ordinal.linearOrder.{u1}) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1})) a) a
Case conversion may be inaccurate. Consider using '#align ordinal.max_zero_left Ordinal.max_zero_leftβ'. -/
@[simp]
theorem max_zero_left : β a : Ordinal, max 0 a = a :=
max_bot_left
#align ordinal.max_zero_left Ordinal.max_zero_left
/- warning: ordinal.max_zero_right -> Ordinal.max_zero_right is a dubious translation:
lean 3 declaration is
forall (a : Ordinal.{u1}), Eq.{succ (succ u1)} Ordinal.{u1} (LinearOrder.max.{succ u1} Ordinal.{u1} Ordinal.linearOrder.{u1} a (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1})))) a
but is expected to have type
forall (a : Ordinal.{u1}), Eq.{succ (succ u1)} Ordinal.{u1} (Max.max.{succ u1} Ordinal.{u1} (LinearOrder.toMax.{succ u1} Ordinal.{u1} Ordinal.linearOrder.{u1}) a (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1}))) a
Case conversion may be inaccurate. Consider using '#align ordinal.max_zero_right Ordinal.max_zero_rightβ'. -/
@[simp]
theorem max_zero_right : β a : Ordinal, max a 0 = a :=
max_bot_right
#align ordinal.max_zero_right Ordinal.max_zero_right
/- warning: ordinal.max_eq_zero -> Ordinal.max_eq_zero is a dubious translation:
lean 3 declaration is
forall {a : Ordinal.{u1}} {b : Ordinal.{u1}}, Iff (Eq.{succ (succ u1)} Ordinal.{u1} (LinearOrder.max.{succ u1} Ordinal.{u1} Ordinal.linearOrder.{u1} a b) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1})))) (And (Eq.{succ (succ u1)} Ordinal.{u1} a (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1})))) (Eq.{succ (succ u1)} Ordinal.{u1} b (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1})))))
but is expected to have type
forall {a : Ordinal.{u1}} {b : Ordinal.{u1}}, Iff (Eq.{succ (succ u1)} Ordinal.{u1} (Max.max.{succ u1} Ordinal.{u1} (LinearOrder.toMax.{succ u1} Ordinal.{u1} Ordinal.linearOrder.{u1}) a b) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1}))) (And (Eq.{succ (succ u1)} Ordinal.{u1} a (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1}))) (Eq.{succ (succ u1)} Ordinal.{u1} b (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1}))))
Case conversion may be inaccurate. Consider using '#align ordinal.max_eq_zero Ordinal.max_eq_zeroβ'. -/
@[simp]
theorem max_eq_zero {a b : Ordinal} : max a b = 0 β a = 0 β§ b = 0 :=
max_eq_bot
#align ordinal.max_eq_zero Ordinal.max_eq_zero
/- warning: ordinal.Inf_empty -> Ordinal.infβ_empty is a dubious translation:
lean 3 declaration is
Eq.{succ (succ u1)} Ordinal.{u1} (InfSet.infβ.{succ u1} Ordinal.{u1} (ConditionallyCompleteLattice.toHasInf.{succ u1} Ordinal.{u1} (ConditionallyCompleteLinearOrder.toConditionallyCompleteLattice.{succ u1} Ordinal.{u1} (ConditionallyCompleteLinearOrderBot.toConditionallyCompleteLinearOrder.{succ u1} Ordinal.{u1} Ordinal.conditionallyCompleteLinearOrderBot.{u1}))) (EmptyCollection.emptyCollection.{succ u1} (Set.{succ u1} Ordinal.{u1}) (Set.hasEmptyc.{succ u1} Ordinal.{u1}))) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1})))
but is expected to have type
Eq.{succ (succ u1)} Ordinal.{u1} (InfSet.infβ.{succ u1} Ordinal.{u1} (ConditionallyCompleteLattice.toInfSet.{succ u1} Ordinal.{u1} (ConditionallyCompleteLinearOrder.toConditionallyCompleteLattice.{succ u1} Ordinal.{u1} (ConditionallyCompleteLinearOrderBot.toConditionallyCompleteLinearOrder.{succ u1} Ordinal.{u1} Ordinal.instConditionallyCompleteLinearOrderBotOrdinal.{u1}))) (EmptyCollection.emptyCollection.{succ u1} (Set.{succ u1} Ordinal.{u1}) (Set.instEmptyCollectionSet.{succ u1} Ordinal.{u1}))) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1}))
Case conversion may be inaccurate. Consider using '#align ordinal.Inf_empty Ordinal.infβ_emptyβ'. -/
@[simp]
theorem infβ_empty : infβ (β
: Set Ordinal) = 0 :=
dif_neg not_nonempty_empty
#align ordinal.Inf_empty Ordinal.infβ_empty
-- ### Successor order properties
private theorem succ_le_iff' {a b : Ordinal} : a + 1 β€ b β a < b :=
β¨lt_of_lt_of_le
(inductionOn a fun Ξ± r _ =>
β¨β¨β¨β¨fun x => Sum.inl x, fun _ _ => Sum.inl.injβ©, fun _ _ => Sum.lex_inl_inlβ©,
Sum.inr PUnit.unit, fun b =>
Sum.recOn b (fun x => β¨fun _ => β¨x, rflβ©, fun _ => Sum.Lex.sep _ _β©) fun x =>
Sum.lex_inr_inr.trans β¨False.elim, fun β¨x, Hβ© => Sum.inl_ne_inr Hβ©β©β©),
inductionOn a fun Ξ± r hr =>
inductionOn b fun Ξ² s hs β¨β¨f, t, hfβ©β© => by
haveI := hs
refine'
β¨β¨@RelEmbedding.ofMonotone (Sum Ξ± PUnit) Ξ² _ _ _ _ (Sum.rec _ _) fun a b => _, fun a b =>
_β©β©
Β· exact f; Β· exact fun _ => t
Β· rcases a with (a | _) <;> rcases b with (b | _)
Β· simpa only [Sum.lex_inl_inl] using f.map_rel_iff.2
Β· intro
rw [hf]
exact β¨_, rflβ©
Β· exact False.elim β Sum.lex_inr_inl
Β· exact False.elim β Sum.lex_inr_inr.1
Β· rcases a with (a | _)
Β· intro h
have := @PrincipalSeg.init _ _ _ _ _ β¨f, t, hfβ© _ _ h
cases' this with w h
exact β¨Sum.inl w, hβ©
Β· intro h
cases' (hf b).1 h with w h
exact β¨Sum.inl w, hβ©β©
#align ordinal.succ_le_iff' ordinal.succ_le_iff'
instance : NoMaxOrder Ordinal :=
β¨fun a => β¨_, succ_le_iff'.1 le_rflβ©β©
instance : SuccOrder Ordinal.{u} :=
SuccOrder.ofSuccLeIff (fun o => o + 1) fun a b => succ_le_iff'
/- warning: ordinal.add_one_eq_succ -> Ordinal.add_one_eq_succ is a dubious translation:
lean 3 declaration is
forall (o : Ordinal.{u1}), Eq.{succ (succ u1)} Ordinal.{u1} (HAdd.hAdd.{succ u1, succ u1, succ u1} Ordinal.{u1} Ordinal.{u1} Ordinal.{u1} (instHAdd.{succ u1} Ordinal.{u1} Ordinal.hasAdd.{u1}) o (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))) (Order.succ.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}) Ordinal.succOrder.{u1} o)
but is expected to have type
forall (o : Ordinal.{u1}), Eq.{succ (succ u1)} Ordinal.{u1} (HAdd.hAdd.{succ u1, succ u1, succ u1} Ordinal.{u1} Ordinal.{u1} Ordinal.{u1} (instHAdd.{succ u1} Ordinal.{u1} Ordinal.add.{u1}) o (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))) (Order.succ.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}) Ordinal.succOrder.{u1} o)
Case conversion may be inaccurate. Consider using '#align ordinal.add_one_eq_succ Ordinal.add_one_eq_succβ'. -/
@[simp]
theorem add_one_eq_succ (o : Ordinal) : o + 1 = succ o :=
rfl
#align ordinal.add_one_eq_succ Ordinal.add_one_eq_succ
/- warning: ordinal.succ_zero -> Ordinal.succ_zero is a dubious translation:
lean 3 declaration is
Eq.{succ (succ u1)} Ordinal.{u1} (Order.succ.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}) Ordinal.succOrder.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1})))) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))
but is expected to have type
Eq.{succ (succ u1)} Ordinal.{u1} (Order.succ.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}) Ordinal.succOrder.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1}))) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))
Case conversion may be inaccurate. Consider using '#align ordinal.succ_zero Ordinal.succ_zeroβ'. -/
@[simp]
theorem succ_zero : succ (0 : Ordinal) = 1 :=
zero_add 1
#align ordinal.succ_zero Ordinal.succ_zero
/- warning: ordinal.succ_one -> Ordinal.succ_one is a dubious translation:
lean 3 declaration is
Eq.{succ (succ u1)} Ordinal.{u1} (Order.succ.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}) Ordinal.succOrder.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))) (OfNat.ofNat.{succ u1} Ordinal.{u1} 2 (OfNat.mk.{succ u1} Ordinal.{u1} 2 (bit0.{succ u1} Ordinal.{u1} Ordinal.hasAdd.{u1} (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))
but is expected to have type
Eq.{succ (succ u1)} Ordinal.{u1} (Order.succ.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}) Ordinal.succOrder.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))) (OfNat.ofNat.{succ u1} Ordinal.{u1} 2 (instOfNat.{succ u1} Ordinal.{u1} 2 (AddMonoidWithOne.toNatCast.{succ u1} Ordinal.{u1} Ordinal.addMonoidWithOne.{u1}) (instAtLeastTwoHAddNatInstHAddInstAddNatOfNat (OfNat.ofNat.{0} Nat 0 (instOfNatNat 0)))))
Case conversion may be inaccurate. Consider using '#align ordinal.succ_one Ordinal.succ_oneβ'. -/
@[simp]
theorem succ_one : succ (1 : Ordinal) = 2 :=
rfl
#align ordinal.succ_one Ordinal.succ_one
#print Ordinal.add_succ /-
theorem add_succ (oβ oβ : Ordinal) : oβ + succ oβ = succ (oβ + oβ) :=
(add_assoc _ _ _).symm
#align ordinal.add_succ Ordinal.add_succ
-/
/- warning: ordinal.one_le_iff_pos -> Ordinal.one_le_iff_pos is a dubious translation:
lean 3 declaration is
forall {o : Ordinal.{u1}}, Iff (LE.le.{succ u1} Ordinal.{u1} (Preorder.toLE.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))) o) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) o)
but is expected to have type
forall {o : Ordinal.{u1}}, Iff (LE.le.{succ u1} Ordinal.{u1} (Preorder.toLE.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})) o) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1})) o)
Case conversion may be inaccurate. Consider using '#align ordinal.one_le_iff_pos Ordinal.one_le_iff_posβ'. -/
theorem one_le_iff_pos {o : Ordinal} : 1 β€ o β 0 < o := by rw [β succ_zero, succ_le_iff]
#align ordinal.one_le_iff_pos Ordinal.one_le_iff_pos
/- warning: ordinal.one_le_iff_ne_zero -> Ordinal.one_le_iff_ne_zero is a dubious translation:
lean 3 declaration is
forall {o : Ordinal.{u1}}, Iff (LE.le.{succ u1} Ordinal.{u1} (Preorder.toLE.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))) o) (Ne.{succ (succ u1)} Ordinal.{u1} o (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))))
but is expected to have type
forall {o : Ordinal.{u1}}, Iff (LE.le.{succ u1} Ordinal.{u1} (Preorder.toLE.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})) o) (Ne.{succ (succ u1)} Ordinal.{u1} o (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1})))
Case conversion may be inaccurate. Consider using '#align ordinal.one_le_iff_ne_zero Ordinal.one_le_iff_ne_zeroβ'. -/
theorem one_le_iff_ne_zero {o : Ordinal} : 1 β€ o β o β 0 := by
rw [one_le_iff_pos, Ordinal.pos_iff_ne_zero]
#align ordinal.one_le_iff_ne_zero Ordinal.one_le_iff_ne_zero
#print Ordinal.succ_pos /-
theorem succ_pos (o : Ordinal) : 0 < succ o :=
bot_lt_succ o
#align ordinal.succ_pos Ordinal.succ_pos
-/
#print Ordinal.succ_ne_zero /-
theorem succ_ne_zero (o : Ordinal) : succ o β 0 :=
ne_of_gt <| succ_pos o
#align ordinal.succ_ne_zero Ordinal.succ_ne_zero
-/
/- warning: ordinal.lt_one_iff_zero -> Ordinal.lt_one_iff_zero is a dubious translation:
lean 3 declaration is
forall {a : Ordinal.{u1}}, Iff (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) a (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))) (Eq.{succ (succ u1)} Ordinal.{u1} a (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))))
but is expected to have type
forall {a : Ordinal.{u1}}, Iff (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) a (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))) (Eq.{succ (succ u1)} Ordinal.{u1} a (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1})))
Case conversion may be inaccurate. Consider using '#align ordinal.lt_one_iff_zero Ordinal.lt_one_iff_zeroβ'. -/
theorem lt_one_iff_zero {a : Ordinal} : a < 1 β a = 0 := by simpa using @lt_succ_bot_iff _ _ _ a _ _
#align ordinal.lt_one_iff_zero Ordinal.lt_one_iff_zero
/- warning: ordinal.le_one_iff -> Ordinal.le_one_iff is a dubious translation:
lean 3 declaration is
forall {a : Ordinal.{u1}}, Iff (LE.le.{succ u1} Ordinal.{u1} (Preorder.toLE.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) a (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))) (Or (Eq.{succ (succ u1)} Ordinal.{u1} a (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1})))) (Eq.{succ (succ u1)} Ordinal.{u1} a (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))))
but is expected to have type
forall {a : Ordinal.{u1}}, Iff (LE.le.{succ u1} Ordinal.{u1} (Preorder.toLE.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) a (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))) (Or (Eq.{succ (succ u1)} Ordinal.{u1} a (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1}))) (Eq.{succ (succ u1)} Ordinal.{u1} a (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))))
Case conversion may be inaccurate. Consider using '#align ordinal.le_one_iff Ordinal.le_one_iffβ'. -/
theorem le_one_iff {a : Ordinal} : a β€ 1 β a = 0 β¨ a = 1 := by
simpa using @le_succ_bot_iff _ _ _ a _
#align ordinal.le_one_iff Ordinal.le_one_iff
/- warning: ordinal.card_succ -> Ordinal.card_succ is a dubious translation:
lean 3 declaration is
forall (o : Ordinal.{u1}), Eq.{succ (succ u1)} Cardinal.{u1} (Ordinal.card.{u1} (Order.succ.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}) Ordinal.succOrder.{u1} o)) (HAdd.hAdd.{succ u1, succ u1, succ u1} Cardinal.{u1} Cardinal.{u1} Cardinal.{u1} (instHAdd.{succ u1} Cardinal.{u1} Cardinal.hasAdd.{u1}) (Ordinal.card.{u1} o) (OfNat.ofNat.{succ u1} Cardinal.{u1} 1 (OfNat.mk.{succ u1} Cardinal.{u1} 1 (One.one.{succ u1} Cardinal.{u1} Cardinal.hasOne.{u1}))))
but is expected to have type
forall (o : Ordinal.{u1}), Eq.{succ (succ u1)} Cardinal.{u1} (Ordinal.card.{u1} (Order.succ.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}) Ordinal.succOrder.{u1} o)) (HAdd.hAdd.{succ u1, succ u1, succ u1} Cardinal.{u1} Cardinal.{u1} Cardinal.{u1} (instHAdd.{succ u1} Cardinal.{u1} Cardinal.instAddCardinal.{u1}) (Ordinal.card.{u1} o) (OfNat.ofNat.{succ u1} Cardinal.{u1} 1 (One.toOfNat1.{succ u1} Cardinal.{u1} Cardinal.instOneCardinal.{u1})))
Case conversion may be inaccurate. Consider using '#align ordinal.card_succ Ordinal.card_succβ'. -/
@[simp]
theorem card_succ (o : Ordinal) : card (succ o) = card o + 1 := by
simp only [β add_one_eq_succ, card_add, card_one]
#align ordinal.card_succ Ordinal.card_succ
#print Ordinal.nat_cast_succ /-
theorem nat_cast_succ (n : β) : βn.succ = succ (n : Ordinal) :=
rfl
#align ordinal.nat_cast_succ Ordinal.nat_cast_succ
-/
/- warning: ordinal.unique_Iio_one -> Ordinal.uniqueIioOne is a dubious translation:
lean 3 declaration is
Unique.{succ (succ u1)} (coeSort.{succ (succ u1), succ (succ (succ u1))} (Set.{succ u1} Ordinal.{u1}) Type.{succ u1} (Set.hasCoeToSort.{succ u1} Ordinal.{u1}) (Set.Iio.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))))
but is expected to have type
Unique.{succ (succ u1)} (Set.Elem.{succ u1} Ordinal.{u1} (Set.Iio.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))))
Case conversion may be inaccurate. Consider using '#align ordinal.unique_Iio_one Ordinal.uniqueIioOneβ'. -/
instance uniqueIioOne : Unique (Iio (1 : Ordinal))
where
default := β¨0, zero_lt_oneβ©
uniq a := Subtype.ext <| lt_one_iff_zero.1 a.Prop
#align ordinal.unique_Iio_one Ordinal.uniqueIioOne
/- warning: ordinal.unique_out_one -> Ordinal.uniqueOutOne is a dubious translation:
lean 3 declaration is
Unique.{succ u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))))
but is expected to have type
Unique.{succ u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))))
Case conversion may be inaccurate. Consider using '#align ordinal.unique_out_one Ordinal.uniqueOutOneβ'. -/
instance uniqueOutOne : Unique (1 : Ordinal).out.Ξ±
where
default := enum (Β· < Β·) 0 (by simp)
uniq a := by
rw [β enum_typein (Β· < Β·) a]
unfold default
congr
rw [β lt_one_iff_zero]
apply typein_lt_self
#align ordinal.unique_out_one Ordinal.uniqueOutOne
/- warning: ordinal.one_out_eq -> Ordinal.one_out_eq is a dubious translation:
lean 3 declaration is
forall (x : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))), Eq.{succ u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) x (Ordinal.enum.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (LinearOrder.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (linearOrderOut.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))))))))) (isWellOrder_out_lt.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) (Eq.mpr.{0} (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) (Ordinal.type.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (LinearOrder.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (linearOrderOut.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))))))))) (isWellOrder_out_lt.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))))) True (id_tag Tactic.IdTag.simp (Eq.{1} Prop (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) (Ordinal.type.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (LinearOrder.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (linearOrderOut.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))))))))) (isWellOrder_out_lt.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))))) True) (Eq.trans.{1} Prop (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) (Ordinal.type.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (LinearOrder.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (linearOrderOut.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))))))))) (isWellOrder_out_lt.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))))) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))) True ((fun [self : LT.{succ u1} Ordinal.{u1}] (αΎ° : Ordinal.{u1}) (αΎ°_1 : Ordinal.{u1}) (e_2 : Eq.{succ (succ u1)} Ordinal.{u1} αΎ° αΎ°_1) (αΎ°_2 : Ordinal.{u1}) (αΎ°_3 : Ordinal.{u1}) (e_3 : Eq.{succ (succ u1)} Ordinal.{u1} αΎ°_2 αΎ°_3) => congr.{succ (succ u1), 1} Ordinal.{u1} Prop (LT.lt.{succ u1} Ordinal.{u1} self αΎ°) (LT.lt.{succ u1} Ordinal.{u1} self αΎ°_1) αΎ°_2 αΎ°_3 (congr_arg.{succ (succ u1), succ (succ u1)} Ordinal.{u1} (Ordinal.{u1} -> Prop) αΎ° αΎ°_1 (LT.lt.{succ u1} Ordinal.{u1} self) e_2) e_3) (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) (rfl.{succ (succ u1)} Ordinal.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1})))) (Ordinal.type.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (LinearOrder.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (linearOrderOut.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))))))))) (isWellOrder_out_lt.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))) (Ordinal.type_lt.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (propext (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))) True ((fun {Ξ± : Type.{succ u1}} [_inst_1 : Zero.{succ u1} Ξ±] [_inst_2 : One.{succ u1} Ξ±] [_inst_3 : PartialOrder.{succ u1} Ξ±] [_inst_4 : ZeroLEOneClass.{succ u1} Ξ± _inst_1 _inst_2 (Preorder.toLE.{succ u1} Ξ± (PartialOrder.toPreorder.{succ u1} Ξ± _inst_3))] [_inst_5 : NeZero.{succ u1} Ξ± _inst_1 (OfNat.ofNat.{succ u1} Ξ± 1 (OfNat.mk.{succ u1} Ξ± 1 (One.one.{succ u1} Ξ± _inst_2)))] => iff_true_intro (LT.lt.{succ u1} Ξ± (Preorder.toLT.{succ u1} Ξ± (PartialOrder.toPreorder.{succ u1} Ξ± _inst_3)) (OfNat.ofNat.{succ u1} Ξ± 0 (OfNat.mk.{succ u1} Ξ± 0 (Zero.zero.{succ u1} Ξ± _inst_1))) (OfNat.ofNat.{succ u1} Ξ± 1 (OfNat.mk.{succ u1} Ξ± 1 (One.one.{succ u1} Ξ± _inst_2)))) (zero_lt_one.{succ u1} Ξ± _inst_1 _inst_2 _inst_3 _inst_4 _inst_5)) Ordinal.{u1} Ordinal.hasZero.{u1} Ordinal.hasOne.{u1} Ordinal.partialOrder.{u1} Ordinal.zeroLeOneClass.{u1} Ordinal.NeZero.one.{u1})))) trivial))
but is expected to have type
forall (x : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))), Eq.{succ u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) x (Ordinal.enum.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (fun ([email protected]._hyg.12858 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) ([email protected]._hyg.12860 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) => LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (DistribLattice.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (instDistribLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (linearOrderOut.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))))))))) [email protected]._hyg.12858 [email protected]._hyg.12860) (isWellOrder_out_lt.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1})) (of_eq_true (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1})) (Ordinal.type.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (fun ([email protected]._hyg.1293 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) ([email protected]._hyg.1295 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) => LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (DistribLattice.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (instDistribLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (linearOrderOut.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))))))))) [email protected]._hyg.1293 [email protected]._hyg.1295) (isWellOrder_out_lt.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))))) (Eq.trans.{1} Prop (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1})) (Ordinal.type.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (fun ([email protected]._hyg.1293 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) ([email protected]._hyg.1295 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) => LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (DistribLattice.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (instDistribLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (linearOrderOut.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))))))))) [email protected]._hyg.1293 [email protected]._hyg.1295) (isWellOrder_out_lt.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))))) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))) True (congrArg.{succ (succ u1), 1} Ordinal.{u1} Prop (Ordinal.type.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (fun ([email protected]._hyg.1293 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) ([email protected]._hyg.1295 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) => LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (DistribLattice.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (instDistribLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (linearOrderOut.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))))))))) [email protected]._hyg.1293 [email protected]._hyg.1295) (isWellOrder_out_lt.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1}))) (Ordinal.type_lt.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (Mathlib.Algebra.Order.ZeroLEOne._auxLemma.2.{succ u1} Ordinal.{u1} Ordinal.zero.{u1} Ordinal.one.{u1} Ordinal.partialOrder.{u1} Ordinal.zeroLEOneClass.{u1} Ordinal.NeZero.one.{u1}))))
Case conversion may be inaccurate. Consider using '#align ordinal.one_out_eq Ordinal.one_out_eqβ'. -/
theorem one_out_eq (x : (1 : Ordinal).out.Ξ±) : x = enum (Β· < Β·) 0 (by simp) :=
Unique.eq_default x
#align ordinal.one_out_eq Ordinal.one_out_eq
/-! ### Extra properties of typein and enum -/
/- warning: ordinal.typein_one_out -> Ordinal.typein_one_out is a dubious translation:
lean 3 declaration is
forall (x : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))), Eq.{succ (succ u1)} Ordinal.{u1} (Ordinal.typein.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (LinearOrder.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1}))))) (linearOrderOut.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))))))))) (isWellOrder_out_lt.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))) x) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1})))
but is expected to have type
forall (x : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))), Eq.{succ (succ u1)} Ordinal.{u1} (Ordinal.typein.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (fun ([email protected]._hyg.12913 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) ([email protected]._hyg.12915 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) => LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (DistribLattice.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (instDistribLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1})))) (linearOrderOut.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))))))))) [email protected]._hyg.12913 [email protected]._hyg.12915) (isWellOrder_out_lt.{u1} (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))) x) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1}))
Case conversion may be inaccurate. Consider using '#align ordinal.typein_one_out Ordinal.typein_one_outβ'. -/
@[simp]
theorem typein_one_out (x : (1 : Ordinal).out.Ξ±) : typein (Β· < Β·) x = 0 := by
rw [one_out_eq x, typein_enum]
#align ordinal.typein_one_out Ordinal.typein_one_out
#print Ordinal.typein_le_typein /-
@[simp]
theorem typein_le_typein (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] {x x' : Ξ±} :
typein r x β€ typein r x' β Β¬r x' x := by rw [β not_lt, typein_lt_typein]
#align ordinal.typein_le_typein Ordinal.typein_le_typein
-/
#print Ordinal.typein_le_typein' /-
@[simp]
theorem typein_le_typein' (o : Ordinal) {x x' : o.out.Ξ±} :
typein (Β· < Β·) x β€ typein (Β· < Β·) x' β x β€ x' :=
by
rw [typein_le_typein]
exact not_lt
#align ordinal.typein_le_typein' Ordinal.typein_le_typein'
-/
#print Ordinal.enum_le_enum /-
@[simp]
theorem enum_le_enum (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] {o o' : Ordinal} (ho : o < type r)
(ho' : o' < type r) : Β¬r (enum r o' ho') (enum r o ho) β o β€ o' := by
rw [β @not_lt _ _ o' o, enum_lt_enum ho']
#align ordinal.enum_le_enum Ordinal.enum_le_enum
-/
#print Ordinal.enum_le_enum' /-
@[simp]
theorem enum_le_enum' (a : Ordinal) {o o' : Ordinal} (ho : o < type (Β· < Β·))
(ho' : o' < type (Β· < Β·)) : enum (Β· < Β·) o ho β€ @enum a.out.Ξ± (Β· < Β·) _ o' ho' β o β€ o' := by
rw [β enum_le_enum (Β· < Β·), β not_lt]
#align ordinal.enum_le_enum' Ordinal.enum_le_enum'
-/
#print Ordinal.enum_zero_le /-
theorem enum_zero_le {r : Ξ± β Ξ± β Prop} [IsWellOrder Ξ± r] (h0 : 0 < type r) (a : Ξ±) :
Β¬r a (enum r 0 h0) := by
rw [β enum_typein r a, enum_le_enum r]
apply Ordinal.zero_le
#align ordinal.enum_zero_le Ordinal.enum_zero_le
-/
#print Ordinal.enum_zero_le' /-
theorem enum_zero_le' {o : Ordinal} (h0 : 0 < o) (a : o.out.Ξ±) :
@enum o.out.Ξ± (Β· < Β·) _ 0 (by rwa [type_lt]) β€ a :=
by
rw [β not_lt]
apply enum_zero_le
#align ordinal.enum_zero_le' Ordinal.enum_zero_le'
-/
#print Ordinal.le_enum_succ /-
theorem le_enum_succ {o : Ordinal} (a : (succ o).out.Ξ±) :
a β€
@enum (succ o).out.Ξ± (Β· < Β·) _ o
(by
rw [type_lt]
exact lt_succ o) :=
by
rw [β enum_typein (Β· < Β·) a, enum_le_enum', β lt_succ_iff]
apply typein_lt_self
#align ordinal.le_enum_succ Ordinal.le_enum_succ
-/
#print Ordinal.enum_inj /-
@[simp]
theorem enum_inj {r : Ξ± β Ξ± β Prop} [IsWellOrder Ξ± r] {oβ oβ : Ordinal} (hβ : oβ < type r)
(hβ : oβ < type r) : enum r oβ hβ = enum r oβ hβ β oβ = oβ :=
β¨fun h => by
by_contra hne
cases' lt_or_gt_of_ne hne with hlt hlt <;> apply (IsWellOrder.isIrrefl r).1
Β· rwa [β @enum_lt_enum Ξ± r _ oβ oβ hβ hβ, h] at hlt
Β· change _ < _ at hlt
rwa [β @enum_lt_enum Ξ± r _ oβ oβ hβ hβ, h] at hlt, fun h => by simp_rw [h]β©
#align ordinal.enum_inj Ordinal.enum_inj
-/
#print Ordinal.enumIso /-
/-- A well order `r` is order isomorphic to the set of ordinals smaller than `type r`. -/
@[simps]
def enumIso (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] : Subrel (Β· < Β·) (Β· < type r) βr r
where
toFun x := enum r x.1 x.2
invFun x := β¨typein r x, typein_lt_type r xβ©
left_inv := fun β¨o, hβ© => Subtype.ext_val (typein_enum _ _)
right_inv h := enum_typein _ _
map_rel_iff' := by
rintro β¨a, _β© β¨b, _β©
apply enum_lt_enum
#align ordinal.enum_iso Ordinal.enumIso
-/
#print Ordinal.enumIsoOut /-
/-- The order isomorphism between ordinals less than `o` and `o.out.Ξ±`. -/
@[simps]
noncomputable def enumIsoOut (o : Ordinal) : Set.Iio o βo o.out.Ξ±
where
toFun x :=
enum (Β· < Β·) x.1 <| by
rw [type_lt]
exact x.2
invFun x := β¨typein (Β· < Β·) x, typein_lt_self xβ©
left_inv := fun β¨o', hβ© => Subtype.ext_val (typein_enum _ _)
right_inv h := enum_typein _ _
map_rel_iff' := by
rintro β¨a, _β© β¨b, _β©
apply enum_le_enum'
#align ordinal.enum_iso_out Ordinal.enumIsoOut
-/
#print Ordinal.outOrderBotOfPos /-
/-- `o.out.Ξ±` is an `order_bot` whenever `0 < o`. -/
def outOrderBotOfPos {o : Ordinal} (ho : 0 < o) : OrderBot o.out.Ξ± :=
β¨_, enum_zero_le' hoβ©
#align ordinal.out_order_bot_of_pos Ordinal.outOrderBotOfPos
-/
/- warning: ordinal.enum_zero_eq_bot -> Ordinal.enum_zero_eq_bot is a dubious translation:
lean 3 declaration is
forall {o : Ordinal.{u1}} (ho : LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) o), Eq.{succ u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Ordinal.enum.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (LinearOrder.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (linearOrderOut.{u1} o))))))) (isWellOrder_out_lt.{u1} o) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) (Eq.mpr.{0} (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) (Ordinal.type.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (LinearOrder.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (linearOrderOut.{u1} o))))))) (isWellOrder_out_lt.{u1} o))) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) o) (id_tag Tactic.IdTag.rw (Eq.{1} Prop (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) (Ordinal.type.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (LinearOrder.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (linearOrderOut.{u1} o))))))) (isWellOrder_out_lt.{u1} o))) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) o)) (Eq.ndrec.{0, succ (succ u1)} Ordinal.{u1} (Ordinal.type.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (LinearOrder.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (linearOrderOut.{u1} o))))))) (isWellOrder_out_lt.{u1} o)) (fun (_a : Ordinal.{u1}) => Eq.{1} Prop (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) (Ordinal.type.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (LinearOrder.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (linearOrderOut.{u1} o))))))) (isWellOrder_out_lt.{u1} o))) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) _a)) (rfl.{1} Prop (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (OfNat.mk.{succ u1} Ordinal.{u1} 0 (Zero.zero.{succ u1} Ordinal.{u1} Ordinal.hasZero.{u1}))) (Ordinal.type.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (LinearOrder.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (linearOrderOut.{u1} o))))))) (isWellOrder_out_lt.{u1} o)))) o (Ordinal.type_lt.{u1} o))) ho)) (Bot.bot.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (OrderBot.toHasBot.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Preorder.toLE.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (LinearOrder.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (linearOrderOut.{u1} o)))))) (Ordinal.outOrderBotOfPos.{u1} o ho)))
but is expected to have type
forall {o : Ordinal.{u1}} (ho : LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1})) o), Eq.{succ u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Ordinal.enum.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (fun ([email protected]._hyg.14389 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) ([email protected]._hyg.14391 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) => LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (DistribLattice.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (instDistribLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (linearOrderOut.{u1} o))))))) [email protected]._hyg.14389 [email protected]._hyg.14391) (isWellOrder_out_lt.{u1} o) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1})) (Eq.mpr.{0} (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1})) (Ordinal.type.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (fun ([email protected]._hyg.14389 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) ([email protected]._hyg.14391 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) => LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (DistribLattice.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (instDistribLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (linearOrderOut.{u1} o))))))) [email protected]._hyg.14389 [email protected]._hyg.14391) (isWellOrder_out_lt.{u1} o))) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1})) o) (id.{0} (Eq.{1} Prop (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1})) (Ordinal.type.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (fun ([email protected]._hyg.14389 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) ([email protected]._hyg.14391 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) => LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (DistribLattice.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (instDistribLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (linearOrderOut.{u1} o))))))) [email protected]._hyg.14389 [email protected]._hyg.14391) (isWellOrder_out_lt.{u1} o))) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1})) o)) (Eq.ndrec.{0, succ (succ u1)} Ordinal.{u1} (Ordinal.type.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (fun ([email protected]._hyg.1293 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) ([email protected]._hyg.1295 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) => LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (DistribLattice.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (instDistribLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (linearOrderOut.{u1} o))))))) [email protected]._hyg.1293 [email protected]._hyg.1295) (isWellOrder_out_lt.{u1} o)) (fun (_a : Ordinal.{u1}) => Eq.{1} Prop (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1})) (Ordinal.type.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (fun ([email protected]._hyg.14389 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) ([email protected]._hyg.14391 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) => LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (DistribLattice.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (instDistribLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (linearOrderOut.{u1} o))))))) [email protected]._hyg.14389 [email protected]._hyg.14391) (isWellOrder_out_lt.{u1} o))) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1})) _a)) (Eq.refl.{1} Prop (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (OfNat.ofNat.{succ u1} Ordinal.{u1} 0 (Zero.toOfNat0.{succ u1} Ordinal.{u1} Ordinal.zero.{u1})) (Ordinal.type.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (fun ([email protected]._hyg.14389 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) ([email protected]._hyg.14391 : WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) => LT.lt.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Preorder.toLT.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (DistribLattice.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (instDistribLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (linearOrderOut.{u1} o))))))) [email protected]._hyg.14389 [email protected]._hyg.14391) (isWellOrder_out_lt.{u1} o)))) o (Ordinal.type_lt.{u1} o))) ho)) (Bot.bot.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (OrderBot.toBot.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Preorder.toLE.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (PartialOrder.toPreorder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (SemilatticeInf.toPartialOrder.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (Lattice.toSemilatticeInf.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (DistribLattice.toLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (instDistribLattice.{u1} (WellOrder.Ξ±.{u1} (Quotient.out.{succ (succ u1)} WellOrder.{u1} Ordinal.isEquivalent.{u1} o)) (linearOrderOut.{u1} o))))))) (Ordinal.outOrderBotOfPos.{u1} o ho)))
Case conversion may be inaccurate. Consider using '#align ordinal.enum_zero_eq_bot Ordinal.enum_zero_eq_botβ'. -/
theorem enum_zero_eq_bot {o : Ordinal} (ho : 0 < o) :
enum (Β· < Β·) 0 (by rwa [type_lt]) =
haveI H := out_order_bot_of_pos ho
β₯ :=
rfl
#align ordinal.enum_zero_eq_bot Ordinal.enum_zero_eq_bot
/-! ### Universal ordinal -/
#print Ordinal.univ /-
-- intended to be used with explicit universe parameters
/-- `univ.{u v}` is the order type of the ordinals of `Type u` as a member
of `ordinal.{v}` (when `u < v`). It is an inaccessible cardinal. -/
@[nolint check_univs]
def univ : Ordinal.{max (u + 1) v} :=
lift.{v, u + 1} (@type Ordinal (Β· < Β·) _)
#align ordinal.univ Ordinal.univ
-/
#print Ordinal.univ_id /-
theorem univ_id : univ.{u, u + 1} = @type Ordinal (Β· < Β·) _ :=
lift_id _
#align ordinal.univ_id Ordinal.univ_id
-/
#print Ordinal.lift_univ /-
@[simp]
theorem lift_univ : lift.{w} univ.{u, v} = univ.{u, max v w} :=
lift_lift _
#align ordinal.lift_univ Ordinal.lift_univ
-/
#print Ordinal.univ_umax /-
theorem univ_umax : univ.{u, max (u + 1) v} = univ.{u, v} :=
congr_fun lift_umax _
#align ordinal.univ_umax Ordinal.univ_umax
-/
#print Ordinal.lift.principalSeg /-
/-- Principal segment version of the lift operation on ordinals, embedding `ordinal.{u}` in
`ordinal.{v}` as a principal segment when `u < v`. -/
def lift.principalSeg : @PrincipalSeg Ordinal.{u} Ordinal.{max (u + 1) v} (Β· < Β·) (Β· < Β·) :=
β¨βlift.initialSeg.{u, max (u + 1) v}, univ.{u, v},
by
refine' fun b => induction_on b _; intro Ξ² s _
rw [univ, β lift_umax]; constructor <;> intro h
Β· rw [β lift_id (type s)] at hβ’
cases' lift_type_lt.1 h with f
cases' f with f a hf
exists a
revert hf
apply induction_on a
intro Ξ± r _ hf
refine'
lift_type_eq.{u, max (u + 1) v, max (u + 1) v}.2
β¨(RelIso.ofSurjective (RelEmbedding.ofMonotone _ _) _).symmβ©
Β· exact fun b => enum r (f b) ((hf _).2 β¨_, rflβ©)
Β· refine' fun a b h => (typein_lt_typein r).1 _
rw [typein_enum, typein_enum]
exact f.map_rel_iff.2 h
Β· intro a'
cases' (hf _).1 (typein_lt_type _ a') with b e
exists b
simp
simp [e]
Β· cases' h with a e
rw [β e]
apply induction_on a
intro Ξ± r _
exact lift_type_lt.{u, u + 1, max (u + 1) v}.2 β¨typein.principal_seg rβ©β©
#align ordinal.lift.principal_seg Ordinal.lift.principalSeg
-/
/- warning: ordinal.lift.principal_seg_coe -> Ordinal.lift.principalSeg_coe is a dubious translation:
lean 3 declaration is
Eq.{max (succ (succ u1)) (succ (succ (max (succ u1) u2)))} ((fun (_x : PrincipalSeg.{succ u1, succ (max (succ u1) u2)} Ordinal.{u1} Ordinal.{max (succ u1) u2} (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}))) (LT.lt.{succ (max (succ u1) u2)} Ordinal.{max (succ u1) u2} (Preorder.toLT.{succ (max (succ u1) u2)} Ordinal.{max (succ u1) u2} (PartialOrder.toPreorder.{succ (max (succ u1) u2)} Ordinal.{max (succ u1) u2} Ordinal.partialOrder.{max (succ u1) u2})))) => Ordinal.{u1} -> Ordinal.{max (succ u1) u2}) Ordinal.lift.principalSeg.{u1, u2}) (coeFn.{max (succ (succ u1)) (succ (succ (max (succ u1) u2))), max (succ (succ u1)) (succ (succ (max (succ u1) u2)))} (PrincipalSeg.{succ u1, succ (max (succ u1) u2)} Ordinal.{u1} Ordinal.{max (succ u1) u2} (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}))) (LT.lt.{succ (max (succ u1) u2)} Ordinal.{max (succ u1) u2} (Preorder.toLT.{succ (max (succ u1) u2)} Ordinal.{max (succ u1) u2} (PartialOrder.toPreorder.{succ (max (succ u1) u2)} Ordinal.{max (succ u1) u2} Ordinal.partialOrder.{max (succ u1) u2})))) (fun (_x : PrincipalSeg.{succ u1, succ (max (succ u1) u2)} Ordinal.{u1} Ordinal.{max (succ u1) u2} (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}))) (LT.lt.{succ (max (succ u1) u2)} Ordinal.{max (succ u1) u2} (Preorder.toLT.{succ (max (succ u1) u2)} Ordinal.{max (succ u1) u2} (PartialOrder.toPreorder.{succ (max (succ u1) u2)} Ordinal.{max (succ u1) u2} Ordinal.partialOrder.{max (succ u1) u2})))) => Ordinal.{u1} -> Ordinal.{max (succ u1) u2}) (PrincipalSeg.hasCoeToFun.{succ u1, succ (max (succ u1) u2)} Ordinal.{u1} Ordinal.{max (succ u1) u2} (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}))) (LT.lt.{succ (max (succ u1) u2)} Ordinal.{max (succ u1) u2} (Preorder.toLT.{succ (max (succ u1) u2)} Ordinal.{max (succ u1) u2} (PartialOrder.toPreorder.{succ (max (succ u1) u2)} Ordinal.{max (succ u1) u2} Ordinal.partialOrder.{max (succ u1) u2})))) Ordinal.lift.principalSeg.{u1, u2}) Ordinal.lift.{max (succ u1) u2, u1}
but is expected to have type
Eq.{max (succ (succ (succ u1))) (succ (succ u2))} (forall (a : Ordinal.{u1}), (fun ([email protected]._hyg.19 : Ordinal.{u1}) => Ordinal.{max (succ u1) u2}) a) (FunLike.coe.{max (succ (succ u1)) (succ (max (succ (succ u1)) (succ u2))), succ (succ u1), succ (max (succ (succ u1)) (succ u2))} (Function.Embedding.{succ (succ u1), succ (max (succ (succ u1)) (succ u2))} Ordinal.{u1} Ordinal.{max (succ u1) u2}) Ordinal.{u1} (fun (_x : Ordinal.{u1}) => (fun ([email protected]._hyg.19 : Ordinal.{u1}) => Ordinal.{max (succ u1) u2}) _x) (EmbeddingLike.toFunLike.{max (succ (succ u1)) (succ (max (succ (succ u1)) (succ u2))), succ (succ u1), succ (max (succ (succ u1)) (succ u2))} (Function.Embedding.{succ (succ u1), succ (max (succ (succ u1)) (succ u2))} Ordinal.{u1} Ordinal.{max (succ u1) u2}) Ordinal.{u1} Ordinal.{max (succ u1) u2} (Function.instEmbeddingLikeEmbedding.{succ (succ u1), succ (max (succ (succ u1)) (succ u2))} Ordinal.{u1} Ordinal.{max (succ u1) u2})) (RelEmbedding.toEmbedding.{succ u1, max (succ (succ u1)) (succ u2)} Ordinal.{u1} Ordinal.{max (succ u1) u2} (fun ([email protected]._hyg.14630 : Ordinal.{u1}) ([email protected]._hyg.14632 : Ordinal.{u1}) => LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) [email protected]._hyg.14630 [email protected]._hyg.14632) (fun ([email protected]._hyg.14645 : Ordinal.{max (succ u1) u2}) ([email protected]._hyg.14647 : Ordinal.{max (succ u1) u2}) => LT.lt.{max (succ (succ u1)) (succ u2)} Ordinal.{max (succ u1) u2} (Preorder.toLT.{max (succ (succ u1)) (succ u2)} Ordinal.{max (succ u1) u2} (PartialOrder.toPreorder.{max (succ (succ u1)) (succ u2)} Ordinal.{max (succ u1) u2} Ordinal.partialOrder.{max (succ u1) u2})) [email protected]._hyg.14645 [email protected]._hyg.14647) (PrincipalSeg.toRelEmbedding.{succ u1, max (succ (succ u1)) (succ u2)} Ordinal.{u1} Ordinal.{max (succ u1) u2} (fun ([email protected]._hyg.14630 : Ordinal.{u1}) ([email protected]._hyg.14632 : Ordinal.{u1}) => LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) [email protected]._hyg.14630 [email protected]._hyg.14632) (fun ([email protected]._hyg.14645 : Ordinal.{max (succ u1) u2}) ([email protected]._hyg.14647 : Ordinal.{max (succ u1) u2}) => LT.lt.{max (succ (succ u1)) (succ u2)} Ordinal.{max (succ u1) u2} (Preorder.toLT.{max (succ (succ u1)) (succ u2)} Ordinal.{max (succ u1) u2} (PartialOrder.toPreorder.{max (succ (succ u1)) (succ u2)} Ordinal.{max (succ u1) u2} Ordinal.partialOrder.{max (succ u1) u2})) [email protected]._hyg.14645 [email protected]._hyg.14647) Ordinal.lift.principalSeg.{u1, u2}))) Ordinal.lift.{max (succ u1) u2, u1}
Case conversion may be inaccurate. Consider using '#align ordinal.lift.principal_seg_coe Ordinal.lift.principalSeg_coeβ'. -/
@[simp]
theorem lift.principalSeg_coe :
(lift.principalSeg.{u, v} : Ordinal β Ordinal) = lift.{max (u + 1) v} :=
rfl
#align ordinal.lift.principal_seg_coe Ordinal.lift.principalSeg_coe
#print Ordinal.lift.principalSeg_top /-
@[simp]
theorem lift.principalSeg_top : lift.principalSeg.top = univ :=
rfl
#align ordinal.lift.principal_seg_top Ordinal.lift.principalSeg_top
-/
#print Ordinal.lift.principalSeg_top' /-
theorem lift.principalSeg_top' : lift.principalSeg.{u, u + 1}.top = @type Ordinal (Β· < Β·) _ := by
simp only [lift.principal_seg_top, univ_id]
#align ordinal.lift.principal_seg_top' Ordinal.lift.principalSeg_top'
-/
end Ordinal
/-! ### Representing a cardinal with an ordinal -/
namespace Cardinal
open Ordinal
#print Cardinal.mk_ordinal_out /-
@[simp]
theorem mk_ordinal_out (o : Ordinal) : (#o.out.Ξ±) = o.card :=
(Ordinal.card_type _).symm.trans <| by rw [Ordinal.type_lt]
#align cardinal.mk_ordinal_out Cardinal.mk_ordinal_out
-/
#print Cardinal.ord /-
/-- The ordinal corresponding to a cardinal `c` is the least ordinal
whose cardinal is `c`. For the order-embedding version, see `ord.order_embedding`. -/
def ord (c : Cardinal) : Ordinal :=
let F := fun Ξ± : Type u => β¨
r : { r // IsWellOrder Ξ± r }, @type Ξ± r.1 r.2
Quot.liftOn c F
(by
suffices : β {Ξ± Ξ²}, Ξ± β Ξ² β F Ξ± β€ F Ξ²
exact fun Ξ± Ξ² h => (this h).antisymm (this (Setoid.symm h))
rintro Ξ± Ξ² β¨fβ©
refine' le_cinfα΅’_iff'.2 fun i => _
haveI := @RelEmbedding.isWellOrder _ _ (f β»ΒΉ'o i.1) _ (β(RelIso.preimage f i.1)) i.2
exact
(cinfα΅’_le' _
(Subtype.mk (βf β»ΒΉ'o i.val)
(@RelEmbedding.isWellOrder _ _ _ _ (β(RelIso.preimage f i.1)) i.2))).trans_eq
(Quot.sound β¨RelIso.preimage f i.1β©))
#align cardinal.ord Cardinal.ord
-/
/- warning: cardinal.ord_eq_Inf -> Cardinal.ord_eq_Inf is a dubious translation:
lean 3 declaration is
forall (Ξ± : Type.{u1}), Eq.{succ (succ u1)} Ordinal.{u1} (Cardinal.ord.{u1} (Cardinal.mk.{u1} Ξ±)) (infα΅’.{succ u1, succ u1} Ordinal.{u1} (ConditionallyCompleteLattice.toHasInf.{succ u1} Ordinal.{u1} (ConditionallyCompleteLinearOrder.toConditionallyCompleteLattice.{succ u1} Ordinal.{u1} (ConditionallyCompleteLinearOrderBot.toConditionallyCompleteLinearOrder.{succ u1} Ordinal.{u1} Ordinal.conditionallyCompleteLinearOrderBot.{u1}))) (Subtype.{succ u1} (Ξ± -> Ξ± -> Prop) (fun (r : Ξ± -> Ξ± -> Prop) => IsWellOrder.{u1} Ξ± r)) (fun (r : Subtype.{succ u1} (Ξ± -> Ξ± -> Prop) (fun (r : Ξ± -> Ξ± -> Prop) => IsWellOrder.{u1} Ξ± r)) => Ordinal.type.{u1} Ξ± (Subtype.val.{succ u1} (Ξ± -> Ξ± -> Prop) (fun (r : Ξ± -> Ξ± -> Prop) => IsWellOrder.{u1} Ξ± r) r) (Subtype.property.{succ u1} (Ξ± -> Ξ± -> Prop) (fun (r : Ξ± -> Ξ± -> Prop) => IsWellOrder.{u1} Ξ± r) r)))
but is expected to have type
forall (Ξ± : Type.{u1}), Eq.{succ (succ u1)} Ordinal.{u1} (Cardinal.ord.{u1} (Cardinal.mk.{u1} Ξ±)) (infα΅’.{succ u1, succ u1} Ordinal.{u1} (ConditionallyCompleteLattice.toInfSet.{succ u1} Ordinal.{u1} (ConditionallyCompleteLinearOrder.toConditionallyCompleteLattice.{succ u1} Ordinal.{u1} (ConditionallyCompleteLinearOrderBot.toConditionallyCompleteLinearOrder.{succ u1} Ordinal.{u1} Ordinal.instConditionallyCompleteLinearOrderBotOrdinal.{u1}))) (Subtype.{succ u1} (Ξ± -> Ξ± -> Prop) (fun (r : Ξ± -> Ξ± -> Prop) => IsWellOrder.{u1} Ξ± r)) (fun (r : Subtype.{succ u1} (Ξ± -> Ξ± -> Prop) (fun (r : Ξ± -> Ξ± -> Prop) => IsWellOrder.{u1} Ξ± r)) => Ordinal.type.{u1} Ξ± (Subtype.val.{succ u1} (Ξ± -> Ξ± -> Prop) (fun (r : Ξ± -> Ξ± -> Prop) => IsWellOrder.{u1} Ξ± r) r) (Subtype.property.{succ u1} (Ξ± -> Ξ± -> Prop) (fun (r : Ξ± -> Ξ± -> Prop) => IsWellOrder.{u1} Ξ± r) r)))
Case conversion may be inaccurate. Consider using '#align cardinal.ord_eq_Inf Cardinal.ord_eq_Infβ'. -/
theorem ord_eq_Inf (Ξ± : Type u) : ord (#Ξ±) = β¨
r : { r // IsWellOrder Ξ± r }, @type Ξ± r.1 r.2 :=
rfl
#align cardinal.ord_eq_Inf Cardinal.ord_eq_Inf
#print Cardinal.ord_eq /-
theorem ord_eq (Ξ±) : β (r : Ξ± β Ξ± β Prop)(wo : IsWellOrder Ξ± r), ord (#Ξ±) = @type Ξ± r wo :=
let β¨r, woβ© := cinfα΅’_mem fun r : { r // IsWellOrder Ξ± r } => @type Ξ± r.1 r.2
β¨r.1, r.2, wo.symmβ©
#align cardinal.ord_eq Cardinal.ord_eq
-/
#print Cardinal.ord_le_type /-
theorem ord_le_type (r : Ξ± β Ξ± β Prop) [h : IsWellOrder Ξ± r] : ord (#Ξ±) β€ type r :=
cinfα΅’_le' _ (Subtype.mk r h)
#align cardinal.ord_le_type Cardinal.ord_le_type
-/
#print Cardinal.ord_le /-
theorem ord_le {c o} : ord c β€ o β c β€ o.card :=
inductionOn c fun Ξ± =>
Ordinal.inductionOn o fun Ξ² s _ => by
let β¨r, _, eβ© := ord_eq Ξ±
skip; simp only [card_type]; constructor <;> intro h
Β· rw [e] at h
exact
let β¨fβ© := h
β¨f.toEmbeddingβ©
Β· cases' h with f
have g := RelEmbedding.preimage f s
haveI := RelEmbedding.isWellOrder g
exact le_trans (ord_le_type _) g.ordinal_type_le
#align cardinal.ord_le Cardinal.ord_le
-/
#print Cardinal.gc_ord_card /-
theorem gc_ord_card : GaloisConnection ord card := fun _ _ => ord_le
#align cardinal.gc_ord_card Cardinal.gc_ord_card
-/
#print Cardinal.lt_ord /-
theorem lt_ord {c o} : o < ord c β o.card < c :=
gc_ord_card.lt_iff_lt
#align cardinal.lt_ord Cardinal.lt_ord
-/
#print Cardinal.card_ord /-
@[simp]
theorem card_ord (c) : (ord c).card = c :=
Quotient.inductionOn c fun Ξ± => by
let β¨r, _, eβ© := ord_eq Ξ±
simp only [mk_def, e, card_type]
#align cardinal.card_ord Cardinal.card_ord
-/
#print Cardinal.gciOrdCard /-
/-- Galois coinsertion between `cardinal.ord` and `ordinal.card`. -/
def gciOrdCard : GaloisCoinsertion ord card :=
gc_ord_card.toGaloisCoinsertion fun c => c.card_ord.le
#align cardinal.gci_ord_card Cardinal.gciOrdCard
-/
#print Cardinal.ord_card_le /-
theorem ord_card_le (o : Ordinal) : o.card.ord β€ o :=
gc_ord_card.l_u_le _
#align cardinal.ord_card_le Cardinal.ord_card_le
-/
/- warning: cardinal.lt_ord_succ_card -> Cardinal.lt_ord_succ_card is a dubious translation:
lean 3 declaration is
forall (o : Ordinal.{u1}), LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o (Cardinal.ord.{u1} (Order.succ.{succ u1} Cardinal.{u1} (PartialOrder.toPreorder.{succ u1} Cardinal.{u1} Cardinal.partialOrder.{u1}) Cardinal.succOrder.{u1} (Ordinal.card.{u1} o)))
but is expected to have type
forall (o : Ordinal.{u1}), LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o (Cardinal.ord.{u1} (Order.succ.{succ u1} Cardinal.{u1} (PartialOrder.toPreorder.{succ u1} Cardinal.{u1} Cardinal.partialOrder.{u1}) Cardinal.instSuccOrderCardinalToPreorderPartialOrder.{u1} (Ordinal.card.{u1} o)))
Case conversion may be inaccurate. Consider using '#align cardinal.lt_ord_succ_card Cardinal.lt_ord_succ_cardβ'. -/
theorem lt_ord_succ_card (o : Ordinal) : o < (succ o.card).ord :=
lt_ord.2 <| lt_succ _
#align cardinal.lt_ord_succ_card Cardinal.lt_ord_succ_card
#print Cardinal.ord_strictMono /-
@[mono]
theorem ord_strictMono : StrictMono ord :=
gciOrdCard.strictMono_l
#align cardinal.ord_strict_mono Cardinal.ord_strictMono
-/
#print Cardinal.ord_mono /-
@[mono]
theorem ord_mono : Monotone ord :=
gc_ord_card.monotone_l
#align cardinal.ord_mono Cardinal.ord_mono
-/
#print Cardinal.ord_le_ord /-
@[simp]
theorem ord_le_ord {cβ cβ} : ord cβ β€ ord cβ β cβ β€ cβ :=
gciOrdCard.l_le_l_iff
#align cardinal.ord_le_ord Cardinal.ord_le_ord
-/
#print Cardinal.ord_lt_ord /-
@[simp]
theorem ord_lt_ord {cβ cβ} : ord cβ < ord cβ β cβ < cβ :=
ord_strictMono.lt_iff_lt
#align cardinal.ord_lt_ord Cardinal.ord_lt_ord
-/
#print Cardinal.ord_zero /-
@[simp]
theorem ord_zero : ord 0 = 0 :=
gc_ord_card.l_bot
#align cardinal.ord_zero Cardinal.ord_zero
-/
/- warning: cardinal.ord_nat -> Cardinal.ord_nat is a dubious translation:
lean 3 declaration is
forall (n : Nat), Eq.{succ (succ u1)} Ordinal.{u1} (Cardinal.ord.{u1} ((fun (a : Type) (b : Type.{succ u1}) [self : HasLiftT.{1, succ (succ u1)} a b] => self.0) Nat Cardinal.{u1} (HasLiftT.mk.{1, succ (succ u1)} Nat Cardinal.{u1} (CoeTCβ.coe.{1, succ (succ u1)} Nat Cardinal.{u1} (Nat.castCoe.{succ u1} Cardinal.{u1} Cardinal.hasNatCast.{u1}))) n)) ((fun (a : Type) (b : Type.{succ u1}) [self : HasLiftT.{1, succ (succ u1)} a b] => self.0) Nat Ordinal.{u1} (HasLiftT.mk.{1, succ (succ u1)} Nat Ordinal.{u1} (CoeTCβ.coe.{1, succ (succ u1)} Nat Ordinal.{u1} (Nat.castCoe.{succ u1} Ordinal.{u1} (AddMonoidWithOne.toNatCast.{succ u1} Ordinal.{u1} Ordinal.addMonoidWithOne.{u1})))) n)
but is expected to have type
forall (n : Nat), Eq.{succ (succ u1)} Ordinal.{u1} (Cardinal.ord.{u1} (Nat.cast.{succ u1} Cardinal.{u1} Cardinal.instNatCastCardinal.{u1} n)) (Nat.cast.{succ u1} Ordinal.{u1} (AddMonoidWithOne.toNatCast.{succ u1} Ordinal.{u1} Ordinal.addMonoidWithOne.{u1}) n)
Case conversion may be inaccurate. Consider using '#align cardinal.ord_nat Cardinal.ord_natβ'. -/
@[simp]
theorem ord_nat (n : β) : ord n = n :=
(ord_le.2 (card_nat n).ge).antisymm
(by
induction' n with n IH
Β· apply Ordinal.zero_le
Β· exact succ_le_of_lt (IH.trans_lt <| ord_lt_ord.2 <| nat_cast_lt.2 (Nat.lt_succ_self n)))
#align cardinal.ord_nat Cardinal.ord_nat
/- warning: cardinal.ord_one -> Cardinal.ord_one is a dubious translation:
lean 3 declaration is
Eq.{succ (succ u1)} Ordinal.{u1} (Cardinal.ord.{u1} (OfNat.ofNat.{succ u1} Cardinal.{u1} 1 (OfNat.mk.{succ u1} Cardinal.{u1} 1 (One.one.{succ u1} Cardinal.{u1} Cardinal.hasOne.{u1})))) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (OfNat.mk.{succ u1} Ordinal.{u1} 1 (One.one.{succ u1} Ordinal.{u1} Ordinal.hasOne.{u1})))
but is expected to have type
Eq.{succ (succ u1)} Ordinal.{u1} (Cardinal.ord.{u1} (OfNat.ofNat.{succ u1} Cardinal.{u1} 1 (One.toOfNat1.{succ u1} Cardinal.{u1} Cardinal.instOneCardinal.{u1}))) (OfNat.ofNat.{succ u1} Ordinal.{u1} 1 (One.toOfNat1.{succ u1} Ordinal.{u1} Ordinal.one.{u1}))
Case conversion may be inaccurate. Consider using '#align cardinal.ord_one Cardinal.ord_oneβ'. -/
@[simp]
theorem ord_one : ord 1 = 1 := by simpa using ord_nat 1
#align cardinal.ord_one Cardinal.ord_one
/- warning: cardinal.lift_ord -> Cardinal.lift_ord is a dubious translation:
lean 3 declaration is
forall (c : Cardinal.{u1}), Eq.{succ (succ (max u1 u2))} Ordinal.{max u1 u2} (Ordinal.lift.{u2, u1} (Cardinal.ord.{u1} c)) (Cardinal.ord.{max u1 u2} (Cardinal.lift.{u2, u1} c))
but is expected to have type
forall (c : Cardinal.{u2}), Eq.{max (succ (succ u1)) (succ (succ u2))} Ordinal.{max u2 u1} (Ordinal.lift.{u1, u2} (Cardinal.ord.{u2} c)) (Cardinal.ord.{max u1 u2} (Cardinal.lift.{u1, u2} c))
Case conversion may be inaccurate. Consider using '#align cardinal.lift_ord Cardinal.lift_ordβ'. -/
@[simp]
theorem lift_ord (c) : (ord c).lift = ord (lift c) :=
by
refine' le_antisymm (le_of_forall_lt fun a ha => _) _
Β· rcases Ordinal.lt_lift_iff.1 ha with β¨a, rfl, hβ©
rwa [lt_ord, β lift_card, lift_lt, β lt_ord, β Ordinal.lift_lt]
Β· rw [ord_le, β lift_card, card_ord]
#align cardinal.lift_ord Cardinal.lift_ord
#print Cardinal.mk_ord_out /-
theorem mk_ord_out (c : Cardinal) : (#c.ord.out.Ξ±) = c := by simp
#align cardinal.mk_ord_out Cardinal.mk_ord_out
-/
#print Cardinal.card_typein_lt /-
theorem card_typein_lt (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] (x : Ξ±) (h : ord (#Ξ±) = type r) :
card (typein r x) < (#Ξ±) := by
rw [β lt_ord, h]
apply typein_lt_type
#align cardinal.card_typein_lt Cardinal.card_typein_lt
-/
#print Cardinal.card_typein_out_lt /-
theorem card_typein_out_lt (c : Cardinal) (x : c.ord.out.Ξ±) : card (typein (Β· < Β·) x) < c :=
by
rw [β lt_ord]
apply typein_lt_self
#align cardinal.card_typein_out_lt Cardinal.card_typein_out_lt
-/
#print Cardinal.ord_injective /-
theorem ord_injective : Injective ord := by
intro c c' h
rw [β card_ord c, β card_ord c', h]
#align cardinal.ord_injective Cardinal.ord_injective
-/
#print Cardinal.ord.orderEmbedding /-
/-- The ordinal corresponding to a cardinal `c` is the least ordinal
whose cardinal is `c`. This is the order-embedding version. For the regular function, see `ord`.
-/
def ord.orderEmbedding : Cardinal βͺo Ordinal :=
RelEmbedding.orderEmbeddingOfLTEmbedding
(RelEmbedding.ofMonotone Cardinal.ord fun a b => Cardinal.ord_lt_ord.2)
#align cardinal.ord.order_embedding Cardinal.ord.orderEmbedding
-/
/- warning: cardinal.ord.order_embedding_coe -> Cardinal.ord.orderEmbedding_coe is a dubious translation:
lean 3 declaration is
Eq.{succ (succ u1)} ((fun (_x : RelEmbedding.{succ u1, succ u1} Cardinal.{u1} Ordinal.{u1} (LE.le.{succ u1} Cardinal.{u1} Cardinal.hasLe.{u1}) (LE.le.{succ u1} Ordinal.{u1} (Preorder.toLE.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})))) => Cardinal.{u1} -> Ordinal.{u1}) Cardinal.ord.orderEmbedding.{u1}) (coeFn.{succ (succ u1), succ (succ u1)} (OrderEmbedding.{succ u1, succ u1} Cardinal.{u1} Ordinal.{u1} Cardinal.hasLe.{u1} (Preorder.toLE.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1}))) (fun (_x : RelEmbedding.{succ u1, succ u1} Cardinal.{u1} Ordinal.{u1} (LE.le.{succ u1} Cardinal.{u1} Cardinal.hasLe.{u1}) (LE.le.{succ u1} Ordinal.{u1} (Preorder.toLE.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})))) => Cardinal.{u1} -> Ordinal.{u1}) (RelEmbedding.hasCoeToFun.{succ u1, succ u1} Cardinal.{u1} Ordinal.{u1} (LE.le.{succ u1} Cardinal.{u1} Cardinal.hasLe.{u1}) (LE.le.{succ u1} Ordinal.{u1} (Preorder.toLE.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})))) Cardinal.ord.orderEmbedding.{u1}) Cardinal.ord.{u1}
but is expected to have type
Eq.{succ (succ u1)} (forall (a : Cardinal.{u1}), (fun ([email protected]._hyg.19 : Cardinal.{u1}) => Ordinal.{u1}) a) (FunLike.coe.{succ (succ u1), succ (succ u1), succ (succ u1)} (Function.Embedding.{succ (succ u1), succ (succ u1)} Cardinal.{u1} Ordinal.{u1}) Cardinal.{u1} (fun (_x : Cardinal.{u1}) => (fun ([email protected]._hyg.19 : Cardinal.{u1}) => Ordinal.{u1}) _x) (EmbeddingLike.toFunLike.{succ (succ u1), succ (succ u1), succ (succ u1)} (Function.Embedding.{succ (succ u1), succ (succ u1)} Cardinal.{u1} Ordinal.{u1}) Cardinal.{u1} Ordinal.{u1} (Function.instEmbeddingLikeEmbedding.{succ (succ u1), succ (succ u1)} Cardinal.{u1} Ordinal.{u1})) (RelEmbedding.toEmbedding.{succ u1, succ u1} Cardinal.{u1} Ordinal.{u1} (fun ([email protected]._hyg.680 : Cardinal.{u1}) ([email protected]._hyg.682 : Cardinal.{u1}) => LE.le.{succ u1} Cardinal.{u1} Cardinal.instLECardinal.{u1} [email protected]._hyg.680 [email protected]._hyg.682) (fun ([email protected]._hyg.695 : Ordinal.{u1}) ([email protected]._hyg.697 : Ordinal.{u1}) => LE.le.{succ u1} Ordinal.{u1} (Preorder.toLE.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) [email protected]._hyg.695 [email protected]._hyg.697) Cardinal.ord.orderEmbedding.{u1})) Cardinal.ord.{u1}
Case conversion may be inaccurate. Consider using '#align cardinal.ord.order_embedding_coe Cardinal.ord.orderEmbedding_coeβ'. -/
@[simp]
theorem ord.orderEmbedding_coe : (ord.orderEmbedding : Cardinal β Ordinal) = ord :=
rfl
#align cardinal.ord.order_embedding_coe Cardinal.ord.orderEmbedding_coe
#print Cardinal.univ /-
-- intended to be used with explicit universe parameters
/-- The cardinal `univ` is the cardinality of ordinal `univ`, or
equivalently the cardinal of `ordinal.{u}`, or `cardinal.{u}`,
as an element of `cardinal.{v}` (when `u < v`). -/
@[nolint check_univs]
def univ :=
lift.{v, u + 1} (#Ordinal)
#align cardinal.univ Cardinal.univ
-/
#print Cardinal.univ_id /-
theorem univ_id : univ.{u, u + 1} = (#Ordinal) :=
lift_id _
#align cardinal.univ_id Cardinal.univ_id
-/
#print Cardinal.lift_univ /-
@[simp]
theorem lift_univ : lift.{w} univ.{u, v} = univ.{u, max v w} :=
lift_lift _
#align cardinal.lift_univ Cardinal.lift_univ
-/
#print Cardinal.univ_umax /-
theorem univ_umax : univ.{u, max (u + 1) v} = univ.{u, v} :=
congr_fun lift_umax _
#align cardinal.univ_umax Cardinal.univ_umax
-/
#print Cardinal.lift_lt_univ /-
theorem lift_lt_univ (c : Cardinal) : lift.{u + 1, u} c < univ.{u, u + 1} := by
simpa only [lift.principal_seg_coe, lift_ord, lift_succ, ord_le, succ_le_iff] using
le_of_lt (lift.principalSeg.{u, u + 1}.lt_top (succ c).ord)
#align cardinal.lift_lt_univ Cardinal.lift_lt_univ
-/
#print Cardinal.lift_lt_univ' /-
theorem lift_lt_univ' (c : Cardinal) : lift.{max (u + 1) v, u} c < univ.{u, v} := by
simpa only [lift_lift, lift_univ, univ_umax] using lift_lt.{_, max (u + 1) v}.2 (lift_lt_univ c)
#align cardinal.lift_lt_univ' Cardinal.lift_lt_univ'
-/
#print Cardinal.ord_univ /-
@[simp]
theorem ord_univ : ord univ.{u, v} = Ordinal.univ.{u, v} :=
le_antisymm (ord_card_le _) <|
le_of_forall_lt fun o h =>
lt_ord.2
(by
rcases lift.principalSeg.{u, v}.down.1
(by simpa only [lift.principal_seg_coe] using h) with
β¨o', rflβ©
simp only [lift.principal_seg_coe]; rw [β lift_card]
apply lift_lt_univ')
#align cardinal.ord_univ Cardinal.ord_univ
-/
#print Cardinal.lt_univ /-
theorem lt_univ {c} : c < univ.{u, u + 1} β β c', c = lift.{u + 1, u} c' :=
β¨fun h => by
have := ord_lt_ord.2 h
rw [ord_univ] at this
cases' lift.principalSeg.{u, u + 1}.down.1 (by simpa only [lift.principal_seg_top] ) with o e
have := card_ord c
rw [β e, lift.principal_seg_coe, β lift_card] at this
exact β¨_, this.symmβ©, fun β¨c', eβ© => e.symm βΈ lift_lt_univ _β©
#align cardinal.lt_univ Cardinal.lt_univ
-/
#print Cardinal.lt_univ' /-
theorem lt_univ' {c} : c < univ.{u, v} β β c', c = lift.{max (u + 1) v, u} c' :=
β¨fun h => by
let β¨a, e, h'β© := lt_lift_iff.1 h
rw [β univ_id] at h'
rcases lt_univ.{u}.1 h' with β¨c', rflβ©
exact β¨c', by simp only [e.symm, lift_lift]β©, fun β¨c', eβ© => e.symm βΈ lift_lt_univ' _β©
#align cardinal.lt_univ' Cardinal.lt_univ'
-/
#print Cardinal.small_iff_lift_mk_lt_univ /-
theorem small_iff_lift_mk_lt_univ {Ξ± : Type u} :
Small.{v} Ξ± β Cardinal.lift (#Ξ±) < univ.{v, max u (v + 1)} :=
by
rw [lt_univ']
constructor
Β· rintro β¨Ξ², eβ©
exact β¨#Ξ², lift_mk_eq.{u, _, v + 1}.2 eβ©
Β· rintro β¨c, hcβ©
exact β¨β¨c.out, lift_mk_eq.{u, _, v + 1}.1 (hc.trans (congr rfl c.mk_out.symm))β©β©
#align cardinal.small_iff_lift_mk_lt_univ Cardinal.small_iff_lift_mk_lt_univ
-/
end Cardinal
namespace Ordinal
#print Ordinal.card_univ /-
@[simp]
theorem card_univ : card univ = Cardinal.univ :=
rfl
#align ordinal.card_univ Ordinal.card_univ
-/
/- warning: ordinal.nat_le_card -> Ordinal.nat_le_card is a dubious translation:
lean 3 declaration is
forall {o : Ordinal.{u1}} {n : Nat}, Iff (LE.le.{succ u1} Cardinal.{u1} Cardinal.hasLe.{u1} ((fun (a : Type) (b : Type.{succ u1}) [self : HasLiftT.{1, succ (succ u1)} a b] => self.0) Nat Cardinal.{u1} (HasLiftT.mk.{1, succ (succ u1)} Nat Cardinal.{u1} (CoeTCβ.coe.{1, succ (succ u1)} Nat Cardinal.{u1} (Nat.castCoe.{succ u1} Cardinal.{u1} Cardinal.hasNatCast.{u1}))) n) (Ordinal.card.{u1} o)) (LE.le.{succ u1} Ordinal.{u1} (Preorder.toLE.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) ((fun (a : Type) (b : Type.{succ u1}) [self : HasLiftT.{1, succ (succ u1)} a b] => self.0) Nat Ordinal.{u1} (HasLiftT.mk.{1, succ (succ u1)} Nat Ordinal.{u1} (CoeTCβ.coe.{1, succ (succ u1)} Nat Ordinal.{u1} (Nat.castCoe.{succ u1} Ordinal.{u1} (AddMonoidWithOne.toNatCast.{succ u1} Ordinal.{u1} Ordinal.addMonoidWithOne.{u1})))) n) o)
but is expected to have type
forall {o : Ordinal.{u1}} {n : Nat}, Iff (LE.le.{succ u1} Cardinal.{u1} Cardinal.instLECardinal.{u1} (Nat.cast.{succ u1} Cardinal.{u1} Cardinal.instNatCastCardinal.{u1} n) (Ordinal.card.{u1} o)) (LE.le.{succ u1} Ordinal.{u1} (Preorder.toLE.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (Nat.cast.{succ u1} Ordinal.{u1} (AddMonoidWithOne.toNatCast.{succ u1} Ordinal.{u1} Ordinal.addMonoidWithOne.{u1}) n) o)
Case conversion may be inaccurate. Consider using '#align ordinal.nat_le_card Ordinal.nat_le_cardβ'. -/
@[simp]
theorem nat_le_card {o} {n : β} : (n : Cardinal) β€ card o β (n : Ordinal) β€ o := by
rw [β Cardinal.ord_le, Cardinal.ord_nat]
#align ordinal.nat_le_card Ordinal.nat_le_card
/- warning: ordinal.nat_lt_card -> Ordinal.nat_lt_card is a dubious translation:
lean 3 declaration is
forall {o : Ordinal.{u1}} {n : Nat}, Iff (LT.lt.{succ u1} Cardinal.{u1} (Preorder.toLT.{succ u1} Cardinal.{u1} (PartialOrder.toPreorder.{succ u1} Cardinal.{u1} Cardinal.partialOrder.{u1})) ((fun (a : Type) (b : Type.{succ u1}) [self : HasLiftT.{1, succ (succ u1)} a b] => self.0) Nat Cardinal.{u1} (HasLiftT.mk.{1, succ (succ u1)} Nat Cardinal.{u1} (CoeTCβ.coe.{1, succ (succ u1)} Nat Cardinal.{u1} (Nat.castCoe.{succ u1} Cardinal.{u1} Cardinal.hasNatCast.{u1}))) n) (Ordinal.card.{u1} o)) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) ((fun (a : Type) (b : Type.{succ u1}) [self : HasLiftT.{1, succ (succ u1)} a b] => self.0) Nat Ordinal.{u1} (HasLiftT.mk.{1, succ (succ u1)} Nat Ordinal.{u1} (CoeTCβ.coe.{1, succ (succ u1)} Nat Ordinal.{u1} (Nat.castCoe.{succ u1} Ordinal.{u1} (AddMonoidWithOne.toNatCast.{succ u1} Ordinal.{u1} Ordinal.addMonoidWithOne.{u1})))) n) o)
but is expected to have type
forall {o : Ordinal.{u1}} {n : Nat}, Iff (LT.lt.{succ u1} Cardinal.{u1} (Preorder.toLT.{succ u1} Cardinal.{u1} (PartialOrder.toPreorder.{succ u1} Cardinal.{u1} Cardinal.partialOrder.{u1})) (Nat.cast.{succ u1} Cardinal.{u1} Cardinal.instNatCastCardinal.{u1} n) (Ordinal.card.{u1} o)) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) (Nat.cast.{succ u1} Ordinal.{u1} (AddMonoidWithOne.toNatCast.{succ u1} Ordinal.{u1} Ordinal.addMonoidWithOne.{u1}) n) o)
Case conversion may be inaccurate. Consider using '#align ordinal.nat_lt_card Ordinal.nat_lt_cardβ'. -/
@[simp]
theorem nat_lt_card {o} {n : β} : (n : Cardinal) < card o β (n : Ordinal) < o :=
by
rw [β succ_le_iff, β succ_le_iff, β nat_succ, nat_le_card]
rfl
#align ordinal.nat_lt_card Ordinal.nat_lt_card
/- warning: ordinal.card_lt_nat -> Ordinal.card_lt_nat is a dubious translation:
lean 3 declaration is
forall {o : Ordinal.{u1}} {n : Nat}, Iff (LT.lt.{succ u1} Cardinal.{u1} (Preorder.toLT.{succ u1} Cardinal.{u1} (PartialOrder.toPreorder.{succ u1} Cardinal.{u1} Cardinal.partialOrder.{u1})) (Ordinal.card.{u1} o) ((fun (a : Type) (b : Type.{succ u1}) [self : HasLiftT.{1, succ (succ u1)} a b] => self.0) Nat Cardinal.{u1} (HasLiftT.mk.{1, succ (succ u1)} Nat Cardinal.{u1} (CoeTCβ.coe.{1, succ (succ u1)} Nat Cardinal.{u1} (Nat.castCoe.{succ u1} Cardinal.{u1} Cardinal.hasNatCast.{u1}))) n)) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o ((fun (a : Type) (b : Type.{succ u1}) [self : HasLiftT.{1, succ (succ u1)} a b] => self.0) Nat Ordinal.{u1} (HasLiftT.mk.{1, succ (succ u1)} Nat Ordinal.{u1} (CoeTCβ.coe.{1, succ (succ u1)} Nat Ordinal.{u1} (Nat.castCoe.{succ u1} Ordinal.{u1} (AddMonoidWithOne.toNatCast.{succ u1} Ordinal.{u1} Ordinal.addMonoidWithOne.{u1})))) n))
but is expected to have type
forall {o : Ordinal.{u1}} {n : Nat}, Iff (LT.lt.{succ u1} Cardinal.{u1} (Preorder.toLT.{succ u1} Cardinal.{u1} (PartialOrder.toPreorder.{succ u1} Cardinal.{u1} Cardinal.partialOrder.{u1})) (Ordinal.card.{u1} o) (Nat.cast.{succ u1} Cardinal.{u1} Cardinal.instNatCastCardinal.{u1} n)) (LT.lt.{succ u1} Ordinal.{u1} (Preorder.toLT.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o (Nat.cast.{succ u1} Ordinal.{u1} (AddMonoidWithOne.toNatCast.{succ u1} Ordinal.{u1} Ordinal.addMonoidWithOne.{u1}) n))
Case conversion may be inaccurate. Consider using '#align ordinal.card_lt_nat Ordinal.card_lt_natβ'. -/
@[simp]
theorem card_lt_nat {o} {n : β} : card o < n β o < n :=
lt_iff_lt_of_le_iff_le nat_le_card
#align ordinal.card_lt_nat Ordinal.card_lt_nat
/- warning: ordinal.card_le_nat -> Ordinal.card_le_nat is a dubious translation:
lean 3 declaration is
forall {o : Ordinal.{u1}} {n : Nat}, Iff (LE.le.{succ u1} Cardinal.{u1} Cardinal.hasLe.{u1} (Ordinal.card.{u1} o) ((fun (a : Type) (b : Type.{succ u1}) [self : HasLiftT.{1, succ (succ u1)} a b] => self.0) Nat Cardinal.{u1} (HasLiftT.mk.{1, succ (succ u1)} Nat Cardinal.{u1} (CoeTCβ.coe.{1, succ (succ u1)} Nat Cardinal.{u1} (Nat.castCoe.{succ u1} Cardinal.{u1} Cardinal.hasNatCast.{u1}))) n)) (LE.le.{succ u1} Ordinal.{u1} (Preorder.toLE.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o ((fun (a : Type) (b : Type.{succ u1}) [self : HasLiftT.{1, succ (succ u1)} a b] => self.0) Nat Ordinal.{u1} (HasLiftT.mk.{1, succ (succ u1)} Nat Ordinal.{u1} (CoeTCβ.coe.{1, succ (succ u1)} Nat Ordinal.{u1} (Nat.castCoe.{succ u1} Ordinal.{u1} (AddMonoidWithOne.toNatCast.{succ u1} Ordinal.{u1} Ordinal.addMonoidWithOne.{u1})))) n))
but is expected to have type
forall {o : Ordinal.{u1}} {n : Nat}, Iff (LE.le.{succ u1} Cardinal.{u1} Cardinal.instLECardinal.{u1} (Ordinal.card.{u1} o) (Nat.cast.{succ u1} Cardinal.{u1} Cardinal.instNatCastCardinal.{u1} n)) (LE.le.{succ u1} Ordinal.{u1} (Preorder.toLE.{succ u1} Ordinal.{u1} (PartialOrder.toPreorder.{succ u1} Ordinal.{u1} Ordinal.partialOrder.{u1})) o (Nat.cast.{succ u1} Ordinal.{u1} (AddMonoidWithOne.toNatCast.{succ u1} Ordinal.{u1} Ordinal.addMonoidWithOne.{u1}) n))
Case conversion may be inaccurate. Consider using '#align ordinal.card_le_nat Ordinal.card_le_natβ'. -/
@[simp]
theorem card_le_nat {o} {n : β} : card o β€ n β o β€ n :=
le_iff_le_iff_lt_iff_lt.2 nat_lt_card
#align ordinal.card_le_nat Ordinal.card_le_nat
/- warning: ordinal.card_eq_nat -> Ordinal.card_eq_nat is a dubious translation:
lean 3 declaration is
forall {o : Ordinal.{u1}} {n : Nat}, Iff (Eq.{succ (succ u1)} Cardinal.{u1} (Ordinal.card.{u1} o) ((fun (a : Type) (b : Type.{succ u1}) [self : HasLiftT.{1, succ (succ u1)} a b] => self.0) Nat Cardinal.{u1} (HasLiftT.mk.{1, succ (succ u1)} Nat Cardinal.{u1} (CoeTCβ.coe.{1, succ (succ u1)} Nat Cardinal.{u1} (Nat.castCoe.{succ u1} Cardinal.{u1} Cardinal.hasNatCast.{u1}))) n)) (Eq.{succ (succ u1)} Ordinal.{u1} o ((fun (a : Type) (b : Type.{succ u1}) [self : HasLiftT.{1, succ (succ u1)} a b] => self.0) Nat Ordinal.{u1} (HasLiftT.mk.{1, succ (succ u1)} Nat Ordinal.{u1} (CoeTCβ.coe.{1, succ (succ u1)} Nat Ordinal.{u1} (Nat.castCoe.{succ u1} Ordinal.{u1} (AddMonoidWithOne.toNatCast.{succ u1} Ordinal.{u1} Ordinal.addMonoidWithOne.{u1})))) n))
but is expected to have type
forall {o : Ordinal.{u1}} {n : Nat}, Iff (Eq.{succ (succ u1)} Cardinal.{u1} (Ordinal.card.{u1} o) (Nat.cast.{succ u1} Cardinal.{u1} Cardinal.instNatCastCardinal.{u1} n)) (Eq.{succ (succ u1)} Ordinal.{u1} o (Nat.cast.{succ u1} Ordinal.{u1} (AddMonoidWithOne.toNatCast.{succ u1} Ordinal.{u1} Ordinal.addMonoidWithOne.{u1}) n))
Case conversion may be inaccurate. Consider using '#align ordinal.card_eq_nat Ordinal.card_eq_natβ'. -/
@[simp]
theorem card_eq_nat {o} {n : β} : card o = n β o = n := by
simp only [le_antisymm_iff, card_le_nat, nat_le_card]
#align ordinal.card_eq_nat Ordinal.card_eq_nat
#print Ordinal.type_fintype /-
@[simp]
theorem type_fintype (r : Ξ± β Ξ± β Prop) [IsWellOrder Ξ± r] [Fintype Ξ±] : type r = Fintype.card Ξ± :=
by rw [β card_eq_nat, card_type, mk_fintype]
#align ordinal.type_fintype Ordinal.type_fintype
-/
#print Ordinal.type_fin /-
theorem type_fin (n : β) : @type (Fin n) (Β· < Β·) _ = n := by simp
#align ordinal.type_fin Ordinal.type_fin
-/
end Ordinal
|
State Before: C : Type u
instββ΅ : Category C
instββ΄ : Preadditive C
J : Type
instβΒ³ : Fintype J
fβ : J β C
instβΒ² : HasBiproduct fβ
K : Type
instβΒΉ : Fintype K
instβ : HasFiniteBiproducts C
f g : J β C
h : K β C
m : (k : J) β f k βΆ g k
n : (j : J) β (k : K) β g j βΆ h k
β’ map m β« matrix n = matrix fun j k => m j β« n j k State After: case w.w
C : Type u
instββ΅ : Category C
instββ΄ : Preadditive C
J : Type
instβΒ³ : Fintype J
fβ : J β C
instβΒ² : HasBiproduct fβ
K : Type
instβΒΉ : Fintype K
instβ : HasFiniteBiproducts C
f g : J β C
h : K β C
m : (k : J) β f k βΆ g k
n : (j : J) β (k : K) β g j βΆ h k
jβΒΉ : J
jβ : K
β’ (ΞΉ (fun b => f b) jβΒΉ β« map m β« matrix n) β« Ο (fun k => h k) jβ =
(ΞΉ (fun b => f b) jβΒΉ β« matrix fun j k => m j β« n j k) β« Ο (fun k => h k) jβ Tactic: ext State Before: case w.w
C : Type u
instββ΅ : Category C
instββ΄ : Preadditive C
J : Type
instβΒ³ : Fintype J
fβ : J β C
instβΒ² : HasBiproduct fβ
K : Type
instβΒΉ : Fintype K
instβ : HasFiniteBiproducts C
f g : J β C
h : K β C
m : (k : J) β f k βΆ g k
n : (j : J) β (k : K) β g j βΆ h k
jβΒΉ : J
jβ : K
β’ (ΞΉ (fun b => f b) jβΒΉ β« map m β« matrix n) β« Ο (fun k => h k) jβ =
(ΞΉ (fun b => f b) jβΒΉ β« matrix fun j k => m j β« n j k) β« Ο (fun k => h k) jβ State After: no goals Tactic: simp
|
Formal statement is: proposition\<^marker>\<open>tag unimportant\<close> power_series_and_derivative: fixes a :: "nat \<Rightarrow> complex" and r::real assumes "summable (\<lambda>n. a n * r^n)" obtains g g' where "\<forall>z \<in> ball w r. ((\<lambda>n. a n * (z - w) ^ n) sums g z) \<and> ((\<lambda>n. of_nat n * a n * (z - w) ^ (n - 1)) sums g' z) \<and> (g has_field_derivative g' z) (at z)" Informal statement is: Suppose $a_n$ is a sequence of complex numbers such that $\sum_{n=0}^\infty a_n r^n$ converges for some $r > 0$. Then there exists a function $g$ and its derivative $g'$ such that for all $z$ in the ball of radius $r$ centered at $w$, the power series $\sum_{n=0}^\infty a_n (z - w)^n$ converges to $g(z)$ and the power series $\sum_{n=0}^\infty n a_n (z - w)^{n-1}$ converges to $g'(z)$, and $g'(z)$ is the derivative of $g$ at $z$.
|
# Autogenerated wrapper script for SFML_jll for x86_64-w64-mingw32-cxx11
export libsfml_audio, libsfml_graphics, libsfml_network, libsfml_system, libsfml_window
using Libglvnd_jll
using Ogg_jll
using FLAC_jll
using FreeType2_jll
using libvorbis_jll
using Xorg_libXrandr_jll
using Xorg_libX11_jll
using OpenAL_jll
using eudev_jll
JLLWrappers.@generate_wrapper_header("SFML")
JLLWrappers.@declare_library_product(libsfml_audio, "sfml-audio-2.dll")
JLLWrappers.@declare_library_product(libsfml_graphics, "sfml-graphics-2.dll")
JLLWrappers.@declare_library_product(libsfml_network, "sfml-network-2.dll")
JLLWrappers.@declare_library_product(libsfml_system, "sfml-system-2.dll")
JLLWrappers.@declare_library_product(libsfml_window, "sfml-window-2.dll")
function __init__()
JLLWrappers.@generate_init_header(Libglvnd_jll, Ogg_jll, FLAC_jll, FreeType2_jll, libvorbis_jll, Xorg_libXrandr_jll, Xorg_libX11_jll, OpenAL_jll, eudev_jll)
JLLWrappers.@init_library_product(
libsfml_audio,
"bin\\sfml-audio-2.dll",
RTLD_LAZY | RTLD_DEEPBIND,
)
JLLWrappers.@init_library_product(
libsfml_graphics,
"bin\\sfml-graphics-2.dll",
RTLD_LAZY | RTLD_DEEPBIND,
)
JLLWrappers.@init_library_product(
libsfml_network,
"bin\\sfml-network-2.dll",
RTLD_LAZY | RTLD_DEEPBIND,
)
JLLWrappers.@init_library_product(
libsfml_system,
"bin\\sfml-system-2.dll",
RTLD_LAZY | RTLD_DEEPBIND,
)
JLLWrappers.@init_library_product(
libsfml_window,
"bin\\sfml-window-2.dll",
RTLD_LAZY | RTLD_DEEPBIND,
)
JLLWrappers.@generate_init_footer()
end # __init__()
|
#redirect Solo Dining
|
[STATEMENT]
lemma n_L_T_meet_mult_propagate:
"C x * y \<le> x * C y"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. C x * y \<le> x * C y
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. C x * y \<le> x * C y
[PROOF STEP]
have "C x * y \<le> C x * 1 * C y"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. C x * y \<le> C x * (1::'a) * C y
[PROOF STEP]
by (metis mult_1_right mult_assoc n_L_T_meet_mult_combined mult_1_right)
[PROOF STATE]
proof (state)
this:
C x * y \<le> C x * (1::'a) * C y
goal (1 subgoal):
1. C x * y \<le> x * C y
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
C x * y \<le> C x * (1::'a) * C y
goal (1 subgoal):
1. C x * y \<le> x * C y
[PROOF STEP]
have "... \<le> x * C y"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. C x * (1::'a) * C y \<le> x * C y
[PROOF STEP]
by (simp add: mult_right_sub_dist_inf_right)
[PROOF STATE]
proof (state)
this:
C x * (1::'a) * C y \<le> x * C y
goal (1 subgoal):
1. C x * y \<le> x * C y
[PROOF STEP]
finally
[PROOF STATE]
proof (chain)
picking this:
C x * y \<le> x * C y
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
C x * y \<le> x * C y
goal (1 subgoal):
1. C x * y \<le> x * C y
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
C x * y \<le> x * C y
goal:
No subgoals!
[PROOF STEP]
qed
|
(*
* Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
*
* SPDX-License-Identifier: BSD-2-Clause
*)
theory ListLibLemmas
imports List_Lib LemmaBucket
begin
(* This theory contains various list results that
are used in proofs related to the abstract cdt_list.*)
(* Sorting a list given a partial ordering, where
elements are only necessarily comparable if
relation R holds between them. *)
locale partial_sort =
fixes less :: "'a \<Rightarrow> 'a \<Rightarrow> bool"
fixes R :: "'a \<Rightarrow> 'a \<Rightarrow> bool"
assumes all_comp: "\<And>x y. R x y \<Longrightarrow> (less x y \<or> less y x)"
(*This is only necessary to guarantee the uniqueness of
sorted lists. *)
assumes antisym: "\<And>x y. R x y \<Longrightarrow> less x y \<and> less y x \<Longrightarrow> x = y"
assumes trans: "\<And>x y z. less x y \<Longrightarrow> less y z \<Longrightarrow> less x z"
begin
primrec pinsort :: " 'a \<Rightarrow> 'a list \<Rightarrow> 'a list" where
"pinsort x [] = [x]" |
"pinsort x (y#ys) = (if (less x y) then (x#y#ys) else y#(pinsort x ys))"
inductive psorted :: "'a list \<Rightarrow> bool" where
Nil [iff]: "psorted []"
| Cons: "\<forall>y\<in>set xs. less x y \<Longrightarrow> psorted xs \<Longrightarrow> psorted (x # xs)"
definition R_set where
"R_set S \<equiv> \<forall>x y. x \<in> S \<longrightarrow> y \<in> S \<longrightarrow> R x y"
abbreviation R_list where
"R_list xs \<equiv> R_set (set xs)"
definition psort :: "'a list \<Rightarrow> 'a list" where
"psort xs = foldr pinsort xs []"
end
context partial_sort begin
lemma psorted_Cons: "psorted (x#xs) = (psorted xs & (\<forall> y \<in> set xs. less x y))"
apply (rule iffI)
apply (erule psorted.cases,simp)
apply clarsimp
apply (rule psorted.Cons,clarsimp+)
done
lemma psorted_distinct_set_unique:
assumes "psorted xs" "distinct xs" "psorted ys" "distinct ys" "set xs = set ys"
"R_list xs"
shows "xs = ys"
proof -
from assms have 1: "length xs = length ys" by (auto dest!: distinct_card)
from assms show ?thesis
proof(induct rule:list_induct2[OF 1])
case 1 show ?case by simp
next
case 2 thus ?case
by (simp add: psorted_Cons R_set_def)
(metis Diff_insert_absorb antisym insertE insert_iff)
qed
qed
lemma pinsort_set: "set (pinsort a xs) = insert a (set xs)"
apply (induct xs)
apply simp
apply simp
apply blast
done
lemma all_comp': "R x y \<Longrightarrow> \<not>less x y \<Longrightarrow> less y x"
apply (cut_tac x=x and y=y in all_comp,simp+)
done
lemma pinsort_sorted: "R_set (insert a (set xs)) \<Longrightarrow> psorted xs \<Longrightarrow> psorted (pinsort a xs)"
apply (induct xs arbitrary: a)
apply (simp add: psorted_Cons)
apply (simp add: psorted_Cons)
apply clarsimp
apply (simp add: pinsort_set)
apply (intro impI conjI)
apply (intro ballI)
apply (drule_tac x=x in bspec)
apply simp
apply (frule(1) trans)
apply simp
apply (simp add: R_set_def)
apply (rule all_comp')
apply (simp add: R_set_def)
apply simp
done
lemma psort_set: "set (psort xs) = set xs"
apply (simp add: psort_def)
apply (induct xs)
apply simp
apply (simp add: pinsort_set)
done
lemma psort_psorted: "R_list xs \<Longrightarrow> psorted (psort xs)"
apply (simp add: psort_def)
apply (induct xs)
apply simp
apply simp
apply (cut_tac xs =xs in psort_set)
apply (simp add: psort_def)
apply (rule pinsort_sorted)
apply simp
apply (simp add: R_set_def)
done
lemma insort_length: "length (pinsort a xs) = Suc (length xs)"
apply (induct xs)
apply simp
apply simp
done
lemma psort_length: "length (psort xs) = length xs"
apply (simp add: psort_def)
apply (induct xs)
apply simp
apply simp
apply (simp add: insort_length)
done
lemma pinsort_distinct: "\<lbrakk>a \<notin> set xs; distinct xs\<rbrakk>
\<Longrightarrow> distinct (pinsort a xs)"
apply (induct xs)
apply simp
apply (clarsimp simp add: pinsort_set)
done
lemma psort_distinct: "distinct xs \<Longrightarrow> distinct (psort xs)"
apply (simp add: psort_def)
apply (induct xs)
apply simp
apply simp
apply (rule pinsort_distinct)
apply (fold psort_def)
apply (simp add: psort_set)+
done
lemma in_can_split: "y \<in> set list \<Longrightarrow> \<exists>ys xs. list = xs @ (y # ys)"
apply (induct list)
apply simp
apply clarsimp
apply (elim disjE)
apply simp
apply force
apply simp
apply (elim exE)
apply simp
apply (rule_tac x=ys in exI)
apply force
done
lemma lsorted_sorted:
assumes lsorted: "\<And>x y xs ys . list = xs @ (x # y # ys) \<Longrightarrow> less x y"
shows "psorted list"
apply (insert lsorted)
apply atomize
apply simp
apply (induct list)
apply simp
apply (simp add: psorted_Cons)
apply (rule context_conjI)
apply (erule meta_mp)
apply clarsimp
apply (drule_tac x="a#xs" in spec)
apply (drule_tac x=x in spec)
apply (drule_tac x=y in spec)
apply (erule mp)
apply force
apply (intro ballI)
apply clarsimp
apply (drule in_can_split)
apply (elim exE)
apply (drule_tac x="[]" in spec)
apply simp
apply (case_tac xs)
apply simp
apply (clarsimp simp add: psorted_Cons)
apply (blast intro: trans)
done
lemma psorted_set: "finite A \<Longrightarrow> R_set A \<Longrightarrow> \<exists>!xs. set xs = A \<and> psorted xs \<and> distinct xs"
apply (drule finite_distinct_list)
apply clarify
apply (rule_tac a="psort xs" in ex1I)
apply (auto simp: psorted_distinct_set_unique psort_set psort_psorted psort_distinct)
done
end
text \<open>These list operations roughly correspond to cdt
operations.\<close>
lemma after_can_split: "after_in_list list x = Some y \<Longrightarrow> \<exists>ys xs. list = xs @ (x # y # ys)"
apply (induct list x rule: after_in_list.induct)
apply simp+
apply (simp split: if_split_asm)
apply force
apply (elim exE)
apply simp
apply (rule_tac x="ys" in exI)
apply simp
done
lemma distinct_inj_middle: "distinct list \<Longrightarrow> list = (xa @ x # xb) \<Longrightarrow> list = (ya @ x # yb) \<Longrightarrow> xa = ya \<and> xb = yb"
apply (induct list arbitrary: xa ya)
apply simp
apply clarsimp
apply (case_tac "xa")
apply simp
apply (case_tac "ya")
apply simp
apply clarsimp
apply clarsimp
apply (case_tac "ya")
apply (simp (no_asm_simp))
apply simp
apply clarsimp
done
lemma after_can_split_distinct:
"distinct list \<Longrightarrow> after_in_list list x = Some y \<Longrightarrow> \<exists>!ys. \<exists>!xs. list = xs @ (x # y # ys)"
apply (frule after_can_split)
apply (elim exE)
apply (rule ex1I)
apply (rule ex1I)
apply assumption
apply simp
apply (elim ex1E)
apply (thin_tac "\<forall>x. P x" for P)
apply (frule_tac yb="y#ysa" in distinct_inj_middle,assumption+)
apply simp
done
lemma after_ignore_head: "x \<notin> set list \<Longrightarrow> after_in_list (list @ list') x = after_in_list list' x"
apply (induct list x rule: after_in_list.induct)
apply simp
apply simp
apply (case_tac list',simp+)
done
lemma after_distinct_one_sibling: "distinct list \<Longrightarrow> list = xs @ x # y # ys \<Longrightarrow> after_in_list list x = Some y"
apply (induct xs)
apply simp
apply simp
apply clarsimp
apply (subgoal_tac "after_in_list ((a # xs) @ (x # y # ys)) x = after_in_list (x # y # ys) x")
apply simp
apply (rule after_ignore_head)
apply simp
done
lemma (in partial_sort) after_order_sorted:
assumes after_order: "\<And>x y. after_in_list list x = Some y \<Longrightarrow> less x y"
assumes distinct: "distinct list"
shows "psorted list"
apply (rule lsorted_sorted)
apply (rule after_order)
apply (erule after_distinct_one_sibling[OF distinct])
done
lemma hd_not_after_in_list:
"\<lbrakk>distinct xs; x \<notin> set xs\<rbrakk> \<Longrightarrow> after_in_list (x # xs) a \<noteq> Some x"
apply (induct xs a rule: after_in_list.induct)
apply simp+
apply fastforce
done
lemma after_in_list_inj:
"\<lbrakk>distinct list; after_in_list list a = Some x; after_in_list list b = Some x\<rbrakk>
\<Longrightarrow> a = b"
apply(induct list)
apply(simp)
apply(simp)
apply(case_tac "a=aa")
apply(case_tac list, simp)
apply(simp add: hd_not_after_in_list split: if_split_asm)
apply(case_tac list, simp)
apply(simp add: hd_not_after_in_list split: if_split_asm)
done
lemma list_replace_ignore:"a \<notin> set list \<Longrightarrow> list_replace list a b = list"
apply (simp add: list_replace_def)
apply (induct list,clarsimp+)
done
lemma list_replace_empty[simp]: "list_replace [] a b = []"
by (simp add: list_replace_def)
lemma list_replace_empty2[simp]:
"(list_replace list a b = []) = (list = [])"
by (simp add: list_replace_def)
lemma after_in_list_list_replace: "\<lbrakk>p \<noteq> dest; p \<noteq> src;
after_in_list list p = Some src\<rbrakk>
\<Longrightarrow> after_in_list (list_replace list src dest) p = Some dest"
apply (simp add: list_replace_def)
apply (induct list)
apply simp+
apply (case_tac list)
apply simp+
apply (intro conjI impI,simp+)
done
lemma replace_list_preserve_after: "dest \<notin> set list \<Longrightarrow> distinct list \<Longrightarrow> after_in_list (list_replace list src dest) dest = after_in_list list src"
apply (simp add: list_replace_def)
apply (induct list src rule: after_in_list.induct)
apply (simp+)
apply fastforce
done
lemma replace_list_preserve_after': "\<lbrakk>p \<noteq> dest; p \<noteq> src;
after_in_list list p \<noteq> Some src\<rbrakk>
\<Longrightarrow> after_in_list (list_replace list src dest) p = after_in_list list p"
apply (simp add: list_replace_def)
apply (induct list p rule: after_in_list.induct)
apply (simp+)
apply fastforce
done
lemma distinct_after_in_list_not_self:
"distinct list \<Longrightarrow> after_in_list list src \<noteq> Some src"
apply (induct list,simp+)
apply (case_tac list,clarsimp+)
done
lemma set_list_insert_after:
"set (list_insert_after list a b) = set list \<union> (if a \<in> set list then {b} else {})"
apply(induct list)
apply(simp)
apply(simp)
done
lemma distinct_list_insert_after:
"\<lbrakk>distinct list; b \<notin> set list \<or> a \<notin> set list\<rbrakk> \<Longrightarrow> distinct (list_insert_after list a b)"
apply(induct list)
apply(simp)
apply(fastforce simp: set_list_insert_after)
done
lemma list_insert_after_after:
"\<lbrakk>distinct list; b \<notin> set list; a \<in> set list\<rbrakk>
\<Longrightarrow> after_in_list (list_insert_after list a b) p
= (if p = a then Some b else if p = b then after_in_list list a else after_in_list list p)"
apply(induct list p rule: after_in_list.induct)
apply (simp split: if_split_asm)+
apply fastforce
done
lemma list_remove_removed:
"set (list_remove list x) = (set list) - {x}"
apply (induct list,simp+)
apply blast
done
lemma remove_distinct_helper: "\<lbrakk>distinct (list_remove list x); a \<noteq> x; a \<notin> set list;
distinct list\<rbrakk>
\<Longrightarrow> a \<notin> set (list_remove list x)"
apply (induct list)
apply (simp split: if_split_asm)+
done
lemma list_remove_distinct:
"distinct list \<Longrightarrow> distinct (list_remove list x)"
apply (induct list)
apply (simp add: remove_distinct_helper split: if_split_asm)+
done
lemma list_remove_none: "x \<notin> set list \<Longrightarrow> list_remove list x = list"
apply (induct list)
apply clarsimp+
done
lemma replace_distinct: "x \<notin> set list \<Longrightarrow> distinct list \<Longrightarrow> distinct (list_replace list y x)"
apply (induct list)
apply (simp add: list_replace_def)+
apply blast
done
lemma set_list_replace_list:
"\<lbrakk>distinct list; slot \<in> set list; slot \<notin> set list'\<rbrakk>
\<Longrightarrow> set (list_replace_list list slot list') = set list \<union> set list' - {slot}"
apply (induct list)
apply auto
done
lemma after_in_list_in_list:
"after_in_list list a = Some b \<Longrightarrow> b \<in> set list"
apply(induct list a arbitrary: b rule: after_in_list.induct)
apply (simp split: if_split_asm)+
done
lemma list_replace_empty_after_empty:
"\<lbrakk>after_in_list list p = Some slot; distinct list\<rbrakk>
\<Longrightarrow> after_in_list (list_replace_list list slot []) p = after_in_list list slot"
apply(induct list slot rule: after_in_list.induct)
apply (simp split: if_split_asm)+
apply (case_tac xs,simp+)
apply (case_tac xs,simp+)
apply (auto dest!: after_in_list_in_list)
done
lemma list_replace_after_fst_list:
"\<lbrakk>after_in_list list p = Some slot; distinct list\<rbrakk>
\<Longrightarrow> after_in_list (list_replace_list list slot (x # xs)) p = Some x"
apply(induct list p rule: after_in_list.induct)
apply (simp split: if_split_asm)+
apply (drule after_in_list_in_list)+
apply force
done
lemma after_in_list_append_notin_hd:
"p \<notin> set list' \<Longrightarrow> after_in_list (list' @ list) p = after_in_list list p"
apply(induct list', simp, simp)
apply(case_tac list', simp)
apply(case_tac list, simp+)
done
lemma after_in_list_append_last_hd:
"\<lbrakk>p \<in> set list'; after_in_list list' p = None\<rbrakk>
\<Longrightarrow> after_in_list (list' @ x # xs) p = Some x"
apply(induct list' p rule: after_in_list.induct)
apply(simp)
apply(simp)
apply(simp split: if_split_asm)
done
lemma after_in_list_append_in_hd:
"after_in_list list p = Some a \<Longrightarrow> after_in_list (list @ list') p = Some a"
apply(induct list p rule: after_in_list.induct)
apply(simp split: if_split_asm)+
done
lemma after_in_list_in_list': "after_in_list list a = Some y \<Longrightarrow> a \<in> set list"
apply (induct list a rule: after_in_list.induct)
apply simp+
apply force
done
lemma list_replace_after_None_notin_new:
"\<lbrakk>after_in_list list p = None; p \<notin> set list'\<rbrakk>
\<Longrightarrow> after_in_list (list_replace_list list slot list') p = None"
apply(induct list)
apply(simp)
apply(simp)
apply(intro conjI impI)
apply(simp)
apply(case_tac list, simp)
apply(induct list')
apply(simp)
apply(simp)
apply(case_tac list', simp, simp)
apply(simp split: if_split_asm)
apply(simp add: after_in_list_append_notin_hd)
apply(simp add: after_in_list_append_notin_hd)
apply(case_tac "list_replace_list list slot list'")
apply(simp)
apply(simp)
apply(case_tac list, simp, simp split: if_split_asm)
done
lemma list_replace_after_notin_new:
"\<lbrakk>after_in_list list p = Some a; a \<noteq> slot; p \<notin> set list'; p \<noteq> slot\<rbrakk>
\<Longrightarrow> after_in_list (list_replace_list list slot list') p = Some a"
apply(induct list)
apply(simp)
apply(simp)
apply(intro conjI impI)
apply(simp add: after_in_list_append_notin_hd)
apply(case_tac list, simp, simp)
apply(case_tac list, simp, simp split: if_split_asm)
apply(insert after_in_list_append_notin_hd)
apply(atomize)
apply(erule_tac x=p in allE, erule_tac x="[aa]" in allE, erule_tac x="list' @ lista" in allE)
apply(simp)
done
lemma list_replace_after_None_notin_old:
"\<lbrakk>after_in_list list' p = None; p \<in> set list'; p \<notin> set list\<rbrakk>
\<Longrightarrow> after_in_list (list_replace_list list slot list') p = after_in_list list slot"
apply(induct list)
apply(simp)
apply(simp)
apply(intro conjI impI)
apply(simp)
apply(case_tac list)
apply(simp)
apply(simp add: after_in_list_append_last_hd)
apply(case_tac "list_replace_list list slot list'")
apply(simp)
apply(case_tac list, simp, simp)
apply(simp)
apply(case_tac list, simp, simp)
done
lemma list_replace_after_notin_old:
"\<lbrakk>after_in_list list' p = Some a; p \<notin> set list; slot \<in> set list\<rbrakk>
\<Longrightarrow> after_in_list (list_replace_list list slot list') p = Some a"
apply(induct list)
apply(simp)
apply(simp)
apply(intro conjI impI)
apply(simp add: after_in_list_append_in_hd)
apply(simp)
apply(case_tac "list_replace_list list slot list'")
apply(simp)
apply(simp)
done
lemma list_replace_set: "x \<in> set list \<Longrightarrow> set (list_replace list x y) = insert y (set (list) - {x})"
apply (induct list)
apply (simp add: list_replace_def)+
apply (intro impI conjI)
apply blast+
done
lemma list_swap_both: "x \<in> set list \<Longrightarrow> y \<in> set list \<Longrightarrow> set (list_swap list x y) = set (list)"
apply (induct list)
apply (simp add: list_swap_def)+
apply (intro impI conjI)
apply blast+
done
lemma list_swap_self[simp]: "list_swap list x x = list"
apply (simp add: list_swap_def)
done
lemma map_ignore: "x \<notin> set list \<Longrightarrow> (map (\<lambda>xa. if xa = x then y else xa)
list) = list"
apply (induct list)
apply simp+
apply blast
done
lemma map_ignore2: "y \<notin> set list \<Longrightarrow> (map (\<lambda>xa. if xa = x then y else if xa = y then x else xa)
list) = (map (\<lambda>xa. if xa = x then y else xa) list)"
apply (simp add: map_ignore)
done
lemma map_ignore2': "y \<notin> set list \<Longrightarrow> (map (\<lambda>xa. if xa = y then x else if xa = x then y else xa)
list) = (map (\<lambda>xa. if xa = x then y else xa) list)"
apply (simp add: map_ignore)
apply force
done
lemma swap_distinct_helper: "\<lbrakk>x \<in> set list; y \<noteq> x; y \<notin> set list; distinct list\<rbrakk>
\<Longrightarrow> distinct (map (\<lambda>xa. if xa = x then y else xa) list)"
apply (induct list)
apply (simp add: map_ignore | elim conjE | intro impI conjI | blast)+
done
lemma swap_distinct: "x \<in> set list \<Longrightarrow> y \<in> set list \<Longrightarrow> distinct list \<Longrightarrow> distinct (list_swap list x y)"
apply (induct list)
apply (simp add: list_swap_def)+
apply (intro impI conjI,simp_all)
apply (simp add: map_ignore2 map_ignore2' swap_distinct_helper | elim conjE | force)+
done
lemma list_swap_none: "x \<notin> set list \<Longrightarrow> y \<notin> set list \<Longrightarrow> list_swap list x y = list"
apply (induct list)
apply (simp add: list_swap_def)+
apply blast
done
lemma list_swap_one: "x \<in> set list \<Longrightarrow> y \<notin> set list \<Longrightarrow> set (list_swap list x y) = insert y (set (list)) - {x}"
apply (induct list)
apply (simp add: list_swap_def)+
apply (intro impI conjI)
apply blast+
done
lemma list_swap_one': "x \<notin> set list \<Longrightarrow> y \<in> set list \<Longrightarrow> set (list_swap list x y) = insert x (set (list)) - {y}"
apply (induct list)
apply (simp add: list_swap_def)+
apply (intro impI conjI)
apply blast+
done
lemma in_swapped_list: "y \<in> set list \<Longrightarrow> x \<in> set (list_swap list x y)"
apply (case_tac "x \<in> set list")
apply (simp add: list_swap_both)
apply (simp add: list_swap_one')
apply (intro notI,simp)
done
lemma list_swap_empty : "(list_swap list x y = []) = (list = [])"
by(simp add: list_swap_def)
lemma distinct_after_in_list_antisym:
"distinct list \<Longrightarrow> after_in_list list a = Some b \<Longrightarrow> after_in_list list b \<noteq> Some a"
apply (induct list b arbitrary: a rule: after_in_list.induct)
apply simp+
apply (case_tac xs)
apply (clarsimp split: if_split_asm | intro impI conjI)+
done
lemma after_in_listD: "after_in_list list x = Some y \<Longrightarrow> \<exists>xs ys. list = xs @ (x # y # ys) \<and> x \<notin> set xs"
apply (induct list x arbitrary: a rule: after_in_list.induct)
apply (simp split: if_split_asm | elim exE | force)+
apply (rule_tac x="x # xsa" in exI)
apply simp
done
lemma list_swap_symmetric: "list_swap list a b = list_swap list b a"
apply (simp add: list_swap_def)
done
lemma list_swap_preserve_after:
"\<lbrakk>desta \<notin> set list; distinct list\<rbrakk>
\<Longrightarrow> after_in_list (list_swap list srca desta) desta =
after_in_list list srca"
apply (induct list desta rule: after_in_list.induct)
apply (simp add: list_swap_def)+
apply force
done
lemma list_swap_preserve_after':
"\<lbrakk>p \<noteq> desta; p \<noteq> srca; after_in_list list p = Some srca\<rbrakk>
\<Longrightarrow> after_in_list (list_swap list srca desta) p = Some desta"
apply (induct list p rule: after_in_list.induct)
apply (simp add: list_swap_def)+
apply force
done
lemma list_swap_does_swap:
"\<lbrakk>distinct list; after_in_list list desta = Some srca\<rbrakk>
\<Longrightarrow> after_in_list (list_swap list srca desta) srca = Some desta"
apply (induct list srca rule: after_in_list.induct)
apply (simp add: list_swap_def)+
apply (elim conjE)
apply (intro impI conjI,simp_all)
apply (frule after_in_list_in_list,simp)+
done
lemma list_swap_does_swap':
"distinct list \<Longrightarrow> after_in_list list srca = Some desta \<Longrightarrow>
after_in_list (list_swap list srca desta) srca =
after_in_list list desta"
apply (induct list srca rule: after_in_list.induct)
apply (simp add: list_swap_def)+
apply (elim conjE)
apply (intro impI conjI,simp_all)
apply (case_tac xs)
apply (clarsimp+)[2]
apply (case_tac xs)
apply clarsimp+
done
lemmas list_swap_preserve_after'' = list_swap_preserve_after'[simplified list_swap_symmetric]
lemma list_swap_preserve_Some_other:
"\<lbrakk>z \<noteq> desta; z \<noteq> srca; after_in_list list srca = Some z\<rbrakk>
\<Longrightarrow> after_in_list (list_swap list srca desta) desta = Some z"
apply (induct list srca rule: after_in_list.induct)
apply (simp add: list_swap_def)+
apply force
done
lemmas list_swap_preserve_Some_other' = list_swap_preserve_Some_other[simplified list_swap_symmetric]
lemma list_swap_preserve_None:
"\<lbrakk>after_in_list list srca = None\<rbrakk>
\<Longrightarrow> after_in_list (list_swap list desta srca) desta = None"
apply (induct list srca rule: after_in_list.induct)
apply (simp add: list_swap_def)+
apply force
done
lemma list_swap_preserve_None':
"\<lbrakk>after_in_list list srca = None\<rbrakk>
\<Longrightarrow> after_in_list (list_swap list srca desta) desta = None"
apply (subst list_swap_symmetric)
apply (erule list_swap_preserve_None)
done
lemma list_swap_preserve_after_None:
"\<lbrakk>p \<noteq> desta; p \<noteq> srca; after_in_list list p = None\<rbrakk>
\<Longrightarrow> after_in_list (list_swap list srca desta) p = None"
apply (induct list p rule: after_in_list.induct)
apply (simp add: list_swap_def)+
apply force
done
lemma list_swap_preserve_Some_other_distinct:
"\<lbrakk>distinct list; z \<noteq> desta; after_in_list list srca = Some z\<rbrakk>
\<Longrightarrow> after_in_list (list_swap list srca desta) desta = Some z"
apply (rule list_swap_preserve_Some_other)
apply simp+
apply (rule notI)
apply simp
apply (frule distinct_after_in_list_not_self[where src=srca])
apply simp+
done
lemma list_swap_preserve_separate:
"\<lbrakk>p \<noteq> desta; p \<noteq> srca; z \<noteq> desta; z \<noteq> srca; after_in_list list p = Some z\<rbrakk>
\<Longrightarrow> after_in_list (list_swap list srca desta) p = Some z"
apply (induct list p rule: after_in_list.induct)
apply (simp add: list_swap_def split: if_split_asm)+
apply (intro impI conjI)
apply simp+
done
fun after_in_list_list where
"after_in_list_list [] a = []" |
"after_in_list_list (x # xs) a = (if a = x then xs else after_in_list_list xs a)"
lemma after_in_list_list_in_list:
notes split_paired_All[simp del] split_paired_Ex[simp del]
shows "y \<in> set (after_in_list_list list x) \<Longrightarrow> y \<in> set list"
apply(induct list arbitrary:x y)
apply(simp)
apply(case_tac "x=a", simp+)
done
lemma range_nat_relation_induct:
"\<lbrakk> m = Suc (n + k) ; m < cap ; \<forall>n. Suc n < cap \<longrightarrow> P n (Suc n );
\<forall>i j k. i < cap \<and> j < cap \<and> k < cap \<longrightarrow> P i j \<longrightarrow> P j k \<longrightarrow> P i k \<rbrakk> \<Longrightarrow> P n m"
apply (clarify)
apply (thin_tac "m = t" for t)
apply (induct k)
apply (drule_tac x = "n" in spec)
apply (erule impE, simp, simp)
apply (frule_tac x = "Suc (n + k)" in spec)
apply (erule impE)
apply (simp only: add_Suc_right)
apply (rotate_tac 3, frule_tac x = n in spec)
apply (rotate_tac -1, drule_tac x = "Suc (n + k)" in spec)
apply (rotate_tac -1, drule_tac x = "Suc (n + Suc k) " in spec)
apply (erule impE)
apply (intro conjI)
apply (rule_tac y = "Suc (n + Suc k)" in less_trans)
apply (rule less_SucI)
apply (simp only: add_Suc_right)+
done
lemma indexed_trancl_as_set_helper : "\<lbrakk>p < q; q < length list; list ! p = a; list ! q = b;
q = Suc (p + k); Suc n < length list\<rbrakk>
\<Longrightarrow> (a, b) \<in> {(i, j). \<exists>p. Suc p <length list \<and> list ! p = i \<and> list ! Suc p = j}\<^sup>+"
apply (induct k arbitrary: p q a b)
apply (rule r_into_trancl,simp, rule_tac x = p in exI, simp)
apply (atomize)
apply (erule_tac x = p in allE, erule_tac x = "Suc (p + k)" in allE, erule_tac x = "a" in allE, erule_tac x = "list ! Suc (p + k)" in allE)
apply (elim impE)
apply (simp)+
apply (rule_tac b = "list ! Suc (p + k)" in trancl_into_trancl)
apply (simp)+
apply (rule_tac x = "Suc (p + k)" in exI, simp)
done
lemma indexed_trancl_as_set: "distinct list \<Longrightarrow> {(i, j). \<exists> p q. p < q \<and> q < length list \<and> list ! p = i \<and> list ! q = j }
= {(i, j). \<exists> p. Suc p < length list \<and> list ! p = i \<and> list ! Suc p = j }\<^sup>+"
apply (rule equalityI)
apply (rule subsetI)
apply (case_tac x, simp)
apply (elim exE conjE)
apply (frule less_imp_Suc_add)
apply (erule exE)
apply (rule_tac cap = "length list" and m = q and n = p and k = k in range_nat_relation_induct)
apply (simp)
apply (simp)
apply (rule allI, rule impI)
apply (rule_tac p = p and q = q and k = k and n = n in indexed_trancl_as_set_helper)
apply (simp)+
apply (rule subsetI)
apply (case_tac x, simp)
apply (erule trancl_induct)
apply (simp, elim exE conjE)
apply (rule_tac x = p in exI, rule_tac x = "Suc p" in exI, simp)
apply (simp)
apply (rotate_tac 4, erule exE, rule_tac x = p in exI)
apply (erule exE, rule_tac x = "Suc pa" in exI)
apply (intro conjI)
defer
apply (simp)
apply (erule exE, simp)
apply (simp)
apply (erule exE)
apply (subgoal_tac "pa = q")
apply (simp)
apply (frule_tac xs = list and i = pa and j = q in nth_eq_iff_index_eq)
apply (simp)+
done
lemma indexed_trancl_irrefl: "distinct list \<Longrightarrow> (x,x) \<notin> {(i, j). \<exists> p. Suc p < length list \<and> list ! p = i \<and> list ! Suc p = j }\<^sup>+"
apply (frule indexed_trancl_as_set [THEN sym])
apply (simp)
apply (intro allI impI notI)
apply (frule_tac xs = list and i = p and j = q in nth_eq_iff_index_eq)
apply (simp+)
done
lemma after_in_list_trancl_indexed_trancl: "distinct list \<Longrightarrow> {(p, q). after_in_list list p = Some q}\<^sup>+ = {(i, j). \<exists> p. Suc p < length list \<and> list ! p = i \<and> list ! Suc p = j }\<^sup>+"
apply (rule_tac f = "\<lambda> x. x\<^sup>+" in arg_cong)
apply (intro equalityI subsetI)
apply (case_tac x, simp)
apply (induct list)
apply (simp)
apply (case_tac "a = aa")
apply (rule_tac x = 0 in exI, case_tac list, simp, simp)
apply (case_tac list, simp, simp)
apply (atomize, drule_tac x = x in spec, drule_tac x = aa in spec, drule_tac x = b in spec, simp)
apply (erule exE, rule_tac x = "Suc p" in exI, simp)
apply (case_tac x, simp)
apply (induct list)
apply (simp)
apply (case_tac "a = aa")
apply (erule exE)
apply (subgoal_tac "p = 0")
apply (case_tac list, simp, simp)
apply (subgoal_tac "distinct (aa # list)")
apply (frule_tac i = 0 and j = p and xs = "aa # list" in nth_eq_iff_index_eq)
apply (simp, simp, simp, simp)
apply (atomize, drule_tac x = x in spec, drule_tac x = aa in spec, drule_tac x = b in spec, simp)
apply (drule mp)
apply (erule exE)
apply (case_tac p, simp, simp)
apply (rule_tac x = nat in exI, simp)
apply (case_tac list, simp, simp)
done
lemma distinct_after_in_list_not_self_trancl:
notes split_paired_All[simp del] split_paired_Ex[simp del]
shows "distinct list \<Longrightarrow> (x, x) \<notin> {(p, q). after_in_list list p = Some q}\<^sup>+"
by (simp add: after_in_list_trancl_indexed_trancl indexed_trancl_irrefl)
lemma distinct_after_in_list_in_list_trancl:
notes split_paired_All[simp del] split_paired_Ex[simp del]
shows "\<lbrakk>distinct list; (x, y) \<in> {(p, q). after_in_list list q = Some p}\<^sup>+\<rbrakk> \<Longrightarrow> x \<in> set list"
by(erule tranclE2, (drule CollectD, simp, drule after_in_list_in_list, simp)+)
lemma after_in_list_trancl_prepend:
notes split_paired_All[simp del] split_paired_Ex[simp del]
shows "\<lbrakk>distinct (y # list); x \<in> set list\<rbrakk> \<Longrightarrow> (y, x) \<in> {(n, p). after_in_list (y # list) n = Some p}\<^sup>+"
apply(induct list arbitrary:x y)
apply(simp)
apply(case_tac "x=a")
apply(rule r_into_trancl)
apply(simp)
apply(drule set_ConsD)
apply(elim disjE)
apply(simp)
apply(atomize)
apply(drule_tac x=x in spec)
apply(drule_tac x=y in spec)
apply(drule_tac mp)
apply(simp)
apply(drule_tac mp)
apply(simp)
apply(erule trancl_induct)
apply(drule CollectD, simp)
apply(rule_tac b = a in trancl_into_trancl2)
apply(simp)
apply(rule r_into_trancl)
apply(rule_tac a = "(a,ya)" in CollectI)
apply(clarsimp)
apply(case_tac list)
apply(simp)
apply(simp)
apply(case_tac "ya=a")
apply(drule CollectD)
apply(simp del:after_in_list.simps)
apply(drule after_in_list_in_list')
apply(simp)
apply(rule_tac b=ya in trancl_into_trancl)
apply(simp)
apply(drule CollectD)
apply(rule CollectI)
apply(case_tac "ya=y")
apply(frule_tac x=y in distinct_after_in_list_not_self_trancl)
apply(simp)
apply(case_tac list)
apply(simp)
apply(simp)
done
lemma after_in_list_append_not_hd:
notes split_paired_All[simp del] split_paired_Ex[simp del]
shows "a \<noteq> x \<Longrightarrow> after_in_list (a # list) x = after_in_list list x"
by (case_tac list, simp, simp)
lemma trancl_Collect_rev:
"(a, b) \<in> {(x, y). P x y}\<^sup>+ \<Longrightarrow> (b, a) \<in> {(x, y). P y x}\<^sup>+"
apply(induct rule: trancl_induct)
apply(fastforce intro: trancl_into_trancl2)+
done
lemma prepend_after_in_list_distinct : "distinct (a # list) \<Longrightarrow> {(next, p). after_in_list (a # list) p = Some next}\<^sup>+ =
{(next, p). after_in_list (list) p = Some next}\<^sup>+ \<union>
set list \<times> {a} "
apply (rule equalityI)
(* \<subseteq> direction *)
apply (rule subsetI, case_tac x)
apply (simp)
apply (erule trancl_induct)
(* base case *)
apply (drule CollectD, simp)
apply (case_tac list, simp)
apply (simp split:if_split_asm)
apply (rule r_into_trancl)
apply (rule CollectI, simp)
(* Inductive case *)
apply (drule CollectD, simp)
apply (erule disjE)
apply (case_tac "a \<noteq> z")
apply (rule disjI1)
apply (rule_tac b =y in trancl_into_trancl)
apply (simp, case_tac list, simp, simp)
apply (simp)
apply (rule disjI2)
apply (erule conjE)
apply (frule_tac x = aa and y = y in distinct_after_in_list_in_list_trancl)
apply (simp)
apply (simp)
apply (subgoal_tac "after_in_list (a # list) z \<noteq> Some a", simp)
apply (rule_tac hd_not_after_in_list, simp, simp)
(* \<supseteq> direction *)
apply (rule subsetI)
apply (case_tac x)
apply (simp)
apply (erule disjE)
(* transitive case *)
apply (erule tranclE2)
apply (drule CollectD, simp)
apply (subgoal_tac "b \<noteq> a")
apply (rule r_into_trancl)
apply (rule CollectI, simp)
apply (case_tac list, simp, simp)
apply (frule after_in_list_in_list')
apply (erule conjE)
apply (blast)
apply (rule_tac y = c in trancl_trans)
apply (subgoal_tac "c \<noteq> a")
apply (case_tac list, simp, simp)
apply (case_tac "aaa = aa")
apply (rule r_into_trancl)
apply (rule CollectI, simp)
apply (rule r_into_trancl)
apply (rule CollectI, simp)
apply (erule CollectE, simp)
apply (frule after_in_list_in_list')
apply (erule conjE, blast)
apply (erule trancl_induct)
apply (simp)
apply (rule r_into_trancl, simp)
apply (subgoal_tac "y \<noteq> a")
apply (case_tac list, simp, simp)
apply (rotate_tac 3)
apply (frule after_in_list_in_list')
apply (erule conjE, blast)
apply (rule_tac b = y in trancl_into_trancl, simp)
apply (rule CollectI, simp)
apply (subgoal_tac "a \<noteq> z")
apply (case_tac list, simp, simp)
apply (rotate_tac 3)
apply (frule after_in_list_in_list')
apply (blast)
(* not so transitive case *)
apply (subgoal_tac "distinct (a # list)")
apply (frule_tac x = aa in after_in_list_trancl_prepend, simp, simp)
apply (rule trancl_Collect_rev, simp)
apply (simp)
done
lemma after_in_list_in_cons:
notes split_paired_All[simp del] split_paired_Ex[simp del]
shows "\<lbrakk>after_in_list (x # xs) y = Some z; distinct (x # xs); y \<in> set xs\<rbrakk> \<Longrightarrow> z \<in> set xs"
apply(case_tac "y=x")
apply(simp)
apply(simp add:after_in_list_append_not_hd after_in_list_in_list)
done
lemma after_in_list_list_set:
notes split_paired_All[simp del] split_paired_Ex[simp del]
shows "distinct list \<Longrightarrow>
set (after_in_list_list list x)
= {a. (a, x) \<in> {(next, p). after_in_list list p = Some next}\<^sup>+}"
apply(intro equalityI)
(* \<subseteq> *)
apply(induct list arbitrary:x)
apply(simp)
apply(atomize)
apply(simp)
apply(rule conjI, rule impI, rule subsetI)
apply(rule_tac a = xa in CollectI)
apply(rule trancl_Collect_rev)
apply(rule after_in_list_trancl_prepend)
apply(simp)
apply(simp)
apply(clarify)
apply(drule_tac x=x in spec)
apply(drule_tac B="{a. (a, x) \<in> {(next, p). after_in_list list p = Some next}\<^sup>+}" in set_rev_mp)
apply(simp)
apply(drule CollectD)
apply(simp add:prepend_after_in_list_distinct)
(* \<supseteq> *)
apply(clarsimp)
apply(drule trancl_Collect_rev)
apply(erule trancl_induct)
(* base *)
apply(simp)
apply(induct list arbitrary:x)
apply(simp)
apply(case_tac "a=x")
apply(frule_tac src=x in distinct_after_in_list_not_self)
apply(simp)
apply(drule after_in_list_in_list)
apply(simp)+
apply(drule_tac list=list in after_in_list_append_not_hd)
apply(simp)
(* inductive *)
apply(simp)
apply(drule trancl_Collect_rev)
apply(induct list arbitrary: x)
apply(simp)
apply(case_tac "a\<noteq>x")
(* a\<noteq>x *)
apply(atomize, drule_tac x=y in spec, drule_tac x=z in spec, drule_tac x=x in spec)
apply(simp add:prepend_after_in_list_distinct)
apply(case_tac "a=y")
apply(simp add:after_in_list_list_in_list)
apply(simp add:after_in_list_append_not_hd)
(* a=x *)
apply(frule after_in_list_in_cons, simp+)
done
lemma list_eq_after_in_list':
"\<lbrakk> distinct xs; p = xs ! i; i < length xs \<rbrakk>
\<Longrightarrow> \<exists>list. xs = list @ p # after_in_list_list xs p"
apply (induct xs arbitrary: i)
apply (simp)
apply (atomize)
apply (case_tac i)
apply (simp)
apply (drule_tac x = nat in spec, simp)
apply (erule exE, rule impI, rule_tac x = "a # list" in exI)
apply (simp)
done
lemma after_in_list_last_None:
"distinct list \<Longrightarrow> after_in_list list (last list) = None"
apply(induct list)
apply(simp)
apply(case_tac list)
apply(simp)
apply(fastforce split: if_split_asm)
done
lemma after_in_list_None_last:
"\<lbrakk>after_in_list list x = None; x \<in> set list\<rbrakk> \<Longrightarrow> x = last list"
by (induct list x rule: after_in_list.induct,(simp split: if_split_asm)+)
lemma map2_append1:
"map2 f (as @ bs) cs = map2 f as (take (length as) cs) @ map2 f bs (drop (length as) cs)"
by (simp add: map_def zip_append1)
end
|
[STATEMENT]
lemma INV_from_Refinement_using_invariants:
assumes "refines R pi Sa Sc" "Range (R \<inter> I \<times> J) \<subseteq> K"
"reach Sa \<subseteq> I" "reach Sc \<subseteq> J"
shows "reach Sc \<subseteq> K"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. reach Sc \<subseteq> K
[PROOF STEP]
proof (rule INV_from_Refinement_basic)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. refines ?R ?pi ?Sa Sc
2. Range ?R \<subseteq> K
[PROOF STEP]
show "refines (R \<inter> reach Sa \<times> reach Sc) pi Sa Sc"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. refines (R \<inter> reach Sa \<times> reach Sc) pi Sa Sc
[PROOF STEP]
using assms(1)
[PROOF STATE]
proof (prove)
using this:
refines R pi Sa Sc
goal (1 subgoal):
1. refines (R \<inter> reach Sa \<times> reach Sc) pi Sa Sc
[PROOF STEP]
by (rule refines_reachable_strengthening)
[PROOF STATE]
proof (state)
this:
refines (R \<inter> reach Sa \<times> reach Sc) pi Sa Sc
goal (1 subgoal):
1. Range (R \<inter> reach Sa \<times> reach Sc) \<subseteq> K
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. Range (R \<inter> reach Sa \<times> reach Sc) \<subseteq> K
[PROOF STEP]
show "Range (R \<inter> reach Sa \<times> reach Sc) \<subseteq> K"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Range (R \<inter> reach Sa \<times> reach Sc) \<subseteq> K
[PROOF STEP]
using assms(2-4)
[PROOF STATE]
proof (prove)
using this:
Range (R \<inter> I \<times> J) \<subseteq> K
reach Sa \<subseteq> I
reach Sc \<subseteq> J
goal (1 subgoal):
1. Range (R \<inter> reach Sa \<times> reach Sc) \<subseteq> K
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
Range (R \<inter> reach Sa \<times> reach Sc) \<subseteq> K
goal:
No subgoals!
[PROOF STEP]
qed
|
[STATEMENT]
lemma model_to_dimacs_model_sound_exists:
"1 < n_vars \<Longrightarrow> (\<forall>v\<in>atoms f. 0 < v \<and> v < n_vars) \<Longrightarrow> is_cnf f \<Longrightarrow> M \<Turnstile> f \<Longrightarrow>
\<exists>M_dimacs. dimacs_model M_dimacs (cnf_to_dimacs f)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>1 < n_vars; \<forall>v\<in>atoms f. 0 < v \<and> v < n_vars; is_cnf f; M \<Turnstile> f\<rbrakk> \<Longrightarrow> \<exists>M_dimacs. dimacs_model M_dimacs (cnf_to_dimacs f)
[PROOF STEP]
using model_to_dimacs_model_sound
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>1 < ?n_vars; \<forall>v\<in>atoms ?f. 0 < v \<and> v < ?n_vars; is_cnf ?f; ?M \<Turnstile> ?f\<rbrakk> \<Longrightarrow> dimacs_model (model_to_dimacs_model ?M [1..<?n_vars]) (cnf_to_dimacs ?f)
goal (1 subgoal):
1. \<lbrakk>1 < n_vars; \<forall>v\<in>atoms f. 0 < v \<and> v < n_vars; is_cnf f; M \<Turnstile> f\<rbrakk> \<Longrightarrow> \<exists>M_dimacs. dimacs_model M_dimacs (cnf_to_dimacs f)
[PROOF STEP]
by metis
|
// BeOS Resource Specifications
// --- Icons ---
resource('ICON', 101, "BEOS:L:STD_ICON") {
read("icon-32x32.raw")
}
resource('MICN', 101, "BEOS:M:STD_ICON") {
read("icon-16x16.raw")
}
|
\chapter{Classes and objects}
\label{objects}
\index{object}
\index{class}
At this point you know how to use functions to organize code and
built-in types to organize data. The next step is to learn
``object-oriented programming'', which uses programmer-defined types
to organize both code and data.
\index{abstraction}
\index{encapsulation}
When software applications start to grow large, the number of
details to be handled becomes overwhelming. The only
way to manage this complexity is to use abstraction and
encapsulation. Object orientation is a very popular and efficient
way to implement abstraction and encapsulation.
Perl~6 is an {\bf object-oriented programming language}, which means
that it provides features that support object-oriented
programming, which has these defining characteristics:
\index{object-oriented programming}
\begin{itemize}
\item Programs include class and method definitions.
\index{class}
\index{method}
\item Most of the computation is expressed in terms of operations on
objects.
\item Objects often represent things in the real world, and methods
often correspond to the ways things in the real world interact.
\end{itemize}
Object-oriented programming in
Perl~6 is a big topic that may be worth a book by itself (and
there will probably be a book or two on the subject sometimes). This
chapter will hopefully do more than just skim the surface
and enable you to create and use objects, but will not
cover some of the details and more advanced features.
\index{OOP (object-oriented programming)}
\index{object-oriented programming (OOP)}
\section{Objects, methods and Object oriented programming}
\index{object-oriented programming (OOP)}
\index{programming!object-oriented}
Let us start with a high-level non-technical overview
of object-oriented programming in general and a brief
introduction to the jargon associated with it.
\index{object}
In computer science, an object may loosely describe a memory
location or an entity having a value, and often be referred to
by an identifier. This can be a variable, a data structure,
an array, or possibly even a function. This general meaning
is not the sense that we will use in this chapter.
In object-oriented programming (OOP), the word {\bf object}
has a much more specific meaning: an object is an entity
which often has:
\begin{itemize}
\item an identity (for example its name);
\index{object! behavior}
\item some properties defining its behavior (in the form of
special functions that are usually called {\bf methods}); this
behavior usually does not change over time and is generally
common to all objects of the same type;
\index{method}
\item a {\bf state} defined by some special variables (called,
depending on the language, attributes, instance data, fields
or members); the state may change over time and is generally
specific to each object. In Perl, we speak about
{\bf attributes}.
\index{object!state}
\index{object!attribute}
\index{attribute!object}
\end{itemize}
In brief, an object is a set of attributes and methods packed
together.
\index{class}
Objects are usually defined in a kind of code package called
a {\bf class}. A class defines the methods and the nature of
the attributes associated with an object. In Perl~6, a class makes it
possible to define new types similar to the built-in types
that we have seen before. Very soon, we will start to define
some classes and to use them to create objects.
\index{type!building new type}
\index{invocant}
\index{method}
\index{dot notation}
You already know informally what a method is, as we have
used built-in methods throughout the book. It is a sort of
function with a special postfix syntax using the dot notation
on the invocant. For example, you may invoke the {\tt say}
method on a simple string:
\begin{verbatim}
"foo".say; # -> foo
\end{verbatim}
Note that ``foo'' isn't an object, but a simple string, but
you can invoke the \verb'say' method on it, because Perl
can treat it internally as an object when needed. In some
OOP languages, this implicit conversion of a native type
into an object is sometimes called autoboxing.
\index{autoboxing}
You probably also remember that methods can be chained in a
process where the value returned by a method becomes the
invocant for the next method:
\begin{verbatim}
"foo".uc.say; # -> FOO
my @alphabet = <charlie foxtrot alpha golf echo bravo delta>;
@alphabet.sort.uc.say;
# prints: ALPHA BRAVO CHARLIE DELTA ECHO FOXTROT GOLF
\end{verbatim}
\index{role}
In OOP, methods applicable to objects are usually defined
within classes, often the class that also defined the
object or some other class closely related to it. In Perl~6,
methods can also be defined in a {\bf role}, which is
another type of code package somewhat resembling to a class,
as we will see later.
\index{black box}
\index{encapsulation}
The basic idea of object-oriented programming is that an
object is a kind of black box that hides its internals
(data and code) from the user; the user can consult or change
the state of an object through the methods. Hiding the
internals of objects is called {\bf encapsulation}. This
often enables a higher-level view and a better data
abstraction than what we have seen so far; this in turns
helps to make programs less buggy (especially large programs).
In addition, OOP usually also offers the following concepts:
\begin{itemize}
\index{polymorphism}
\item polymorphism, i.e. the possibility for a function or
a method to do different things depending of the type of
object which calls it;
\index{inheritance}
\item inheritance, i.e. the possibility to derive a class from
another class, so that the child class inherits some of
the properties of the parent class, which is a powerful tool
for code reuse.
\end{itemize}
We will now study how all these concepts are implemented in Perl.
\section{Programmer-defined types}
\label{point}
\index{programmer-defined type}
\index{type!programmer-defined}
We have used many of Perl's built-in types; now we are going
to define a new type. As an example, we will create a type
called {\tt Point2D} that represents a point in
two-dimensional space.
\index{point, mathematical}
\index{two-dimensional space}
In mathematical notation, points are often written in
parentheses with a comma separating the coordinates. For example,
in Cartesian or rectangular coordinates, $(0,0)$ represents
the origin, and $(x,y)$ represents the point $x$ units to the
right and $y$ units up from the origin. $x$ is called
the abscissa of the point, and $y$ the ordinate.
\index{Cartesian coordinates}
\index{coordinates!Cartesian}
\index{coordinates!rectangular}
\index{rectangular coordinates}
There are several ways we might represent points in Perl:
\begin{itemize}
\item We could store the coordinates separately in two
variables, {\tt \$x} and {\tt \$y}.
\item We could store the coordinates as elements in a list,
an array or a pair.
\item We could create a new type to represent points as
objects.
\end{itemize}
\index{representation}
Creating a new type is a bit more complicated than the
other options, but it has advantages that will be apparent soon.
A programmer-defined type is usually created by a {\bf class}
(or a \emph{role}, but we will come back to that later).
A bare-bone class definition for a point type looks like this:
\index{class}
\index{object!class}
\index{class!definition}
\index{definition!class}
\index{role}
\index{Point2D class}
\begin{verbatim}
class Point2D {
has $.abscissa; # "x" value
has $.ordinate; # "y" value
}
\end{verbatim}
%
The header indicates that the new class is called {\tt Point2D}.
The body is defining two attributes, i.e. named properties
associated with the class, here the abscissa and ordinate
(or $x$ and $y$ coordinates) of the point.
\index{Point2D class}
\index{class!Point2D}
\index{type object}
Defining a class named {\tt Point2D} creates a {\bf type object}.
The type object is like a factory for creating objects. To create
a point, you call the {\tt new} method on the {\tt Point2D} class:
\begin{verbatim}
my $point = Point2D.new(
abscissa => 3,
ordinate => 4
);
say $point.WHAT; # -> (Point2D)
say $point.isa(Point2D) # -> True
say $point.abscissa; # -> 3
\end{verbatim}
%
\index{isa method}
\index{WHAT}
You can of course create as many points as you wish.
\index{constructor}
\index{new, object constructor}
\index{dot notation}
\index{object!constructor}
The {\tt new} method is called a {\bf constructor} and has not
been defined in this example; this is not needed because
Perl~6 supplies a default {\tt new} constructor method for
every class (we'll see later how). The method invocation
syntax, with the dot-notation, is the same as what we have
used throughout the book to invoke built-in methods. You
are not forced to use this constructor, you can also create
your own (and you may name it {\tt new} or something else),
but we will stay with the built-in {\tt new} method for the
time being.
\index{invocation!method}
\index{method invocation}
Creating a new object with a class is called {\bf instantiation},
and the object is an {\bf instance} of the class.
\index{instance}
\index{object!instance}
\index{instantiation}
Every object is an instance of some class, so the terms
``object'' and ``instance'' are interchangeable. But
we will often use ``instance'' to indicate that we are
talking about an object belonging to a programmer-defined type.
\index{type}
\index{programmer-defined type}
\section{Attributes}
\label{attributes}
\index{instance attribute}
\index{attribute!instance}
\index{dot notation}
The attributes that we have defined are properties associated
with the {\tt Point2D} class, but they are specific to the
instance of the class that has been created. They are
instance attributes. If we create another {\tt Point2D} object,
it will also have these attributes, but the values of
these attributes are likely to be different.
Figure~\ref{fig.point2d} shows the result of these assignments.
A state diagram that shows an object and its attributes is
called an {\bf object diagram}.
\index{state diagram}
\index{diagram!state}
\index{object diagram}
\index{diagram!object}
\begin{figure}
\centerline
{\includegraphics[scale=0.8]{figs/point2D.png}}
\caption{Object diagram.}
\label{fig.point2d}
\end{figure}
The variable {\tt \$point} refers to a {\tt Point2D} object,
which contains two attributes.
Each attribute of the {\tt Point2D} class should refer to a
number, but this is not obvious in the current definition of
the class. As it stands right now, we could create a {\tt Point2D}
object with a string for the abscissa, which would not make
much sense. We can improve the class definition by specifying
a numeric type for the attributes:
%
\begin{verbatim}
class Point2D {
has Numeric $.abscissa; # "x" value
has Numeric $.ordinate; # "y" value
}
\end{verbatim}
%
\index{private attribute}
\index{attribute!private}
The instance attributes are private to the class, which means
that they normally cannot be accessed from outside the class:
you would usually need to invoke a method of the class
(i.e. a kind of subroutine defined within the class), to get
their value. However, when an attribute is defined with a dot
as in \verb'$.abscissa':
\begin{verbatim}
has $.abscissa;
\end{verbatim}
%
\index{accessor}
\index{method!accessor}
Perl automatically creates an implicit \emph{accessor} method,
i.e. a method having the same name as the attribute and returning
the value of this attribute. Thus, when we wrote:
\begin{verbatim}
say $point.abscissa; # -> 3
\end{verbatim}
%
we were not accessing directly the {\tt abscissa} attribute of
the \verb'$point' object, but we were really calling the
{\tt abscissa} method on the object, which in turn returned
the value of that attribute.
\index{dot notation}
\index{accessor}
You can use such an accessor with dot notation as part of any
expression. For example:
\begin{verbatim}
my $dist-to-center = sqrt($point.abscissa ** 2 + $point.ordinate ** 2);
\end{verbatim}
%
There is another way to declare an attribute in a class, with
an exclamation mark twigil instead of a dot:
\index{twigil}
\begin{verbatim}
has $!abscissa;
\end{verbatim}
%
\index{attribute!private}
\index{private attribute}
In that case, Perl does not create an implicit accessor method
and the attribute can only be accessed from methods within
the class. Such an attribute is now fully private.
However, if you declare attributes this way, you
will not be able to populate them at object creation with
the default {\tt new} constructor and will need to create your
own constructor (or indirectly modify {\tt new}). So don't try
that for the time being, as you would not be able to do much
with your objects at this point. We'll get back to that later.
\index{attribute!mutable}
\index{attribute!immutable}
By default, object attributes are not mutable, they are read-only.
This means you cannot modify them once the object has been created.
This is fine for some attributes: if an object represents a
person, that person's name and birth date are unlikely to
change. Some other attributes may need to be updated, sometimes
very frequently. In such cases, attributes can be declared
to be mutable with the {\tt is rw} trait:
\index{is rw trait}
\index{trait!is rw}
\begin{verbatim}
class Point2D {
has Numeric $.abscissa is rw; # "x" value
has Numeric $.ordinate is rw; # "y" value
}
\end{verbatim}
%
It is now possible to modify these attributes. For example,
we can change the newly-created point's abscissa:
\begin{verbatim}
# First creating a Point2D object:
my $point = Point2D.new(abscissa => 3, ordinate => 4);
say $point; # -> Point2D.new(abscissa => 3, ordinate => 4)
# Now moving the $point object two units to the right:
$point.abscissa = 5;
say $point; # -> Point2D.new(abscissa => 5, ordinate => 4)
\end{verbatim}
\index{class!attribute}
\index{attribute!class}
Almost all of the information presented so far about attributes
related to instance attributes, i.e. to properties related to
individual objects. You can also have attributes pertaining
to the whole class, which are named \emph{class attributes}.
They are less common than instance attributes and are declared
with the {\tt my} declarator (instead of {\tt has}). A typical
example of a class attribute would be a counter at the class level
to keep track of the number of objects that have been
instantiated.
\section{Creating methods}
\index{method}
The simple {\tt Point2D} class and its instance \verb'$point'
are not very useful so far. Let's complete the class definition
with some methods.
\index{Point2D class}
\begin{verbatim}
class Point2D {
has Numeric $.abscissa;
has Numeric $.ordinate;
method coordinates { # accessor to both x and y
return (self.abscissa, self.ordinate)
}
method distanceToCenter {
(self.abscissa ** 2 + self.ordinate ** 2) ** 0.5
}
method polarCoordinates {
my $radius = self.distanceToCenter;
my $theta = atan2 self.ordinate, self.abscissa;
return $radius, $theta;
}
}
\end{verbatim}
We declare three methods in the class:
\begin{itemize}
\item {\tt coordinates}, a simple accessor to the Cartesian
coordinates;
\index{coordinates!Cartesian}
\index{Cartesian coordinates}
\item{\tt distanceToCenter}, a method to compute and return
the distance between the object and the origin;
\index{polar coordinates}
\index{coordinates!polar}
\item{\tt polarCoordinates}, a method to compute the radius
and azimuth (\verb'$theta') of the object in the polar
coordinates system (notice that {\tt polarCoordinates}
invokes the {\tt distanceToCenter} method to find the radius
component of the polar coordinates).
\end{itemize}
\index{invocant}
A method definition is not very different from a subroutine
definition, except that it uses the {\tt method} keyword
instead of the {\tt sub} keyword. This is not a surprise
since a method is essentially a subroutine that is defined
within a class (or a role) and knows about its
\emph{invocant}, i.e. the object that called it and its class.
And, of course, it has a different calling syntax.
\index{method}
\index{method!dispatch}
\index{dispatching methods}
\index{invocation!method}
\index{method invocation}
Another important difference between a subroutine and a method
is that, since there may be several methods with the same name
defined in different classes (or different roles), a method
invocation involves a \emph{dispatch} phase, in
which the object system selects which method to call, usually
based on the class or type of the invocant. However, in
Perl~6, that difference is blurred by the fact that you can
have multi subroutines, i.e. subroutines with the same name
and a different signature that are also resolved at run time,
depending on the \emph{arity} (number of arguments) and type of
the arguments.
\index{arity}
\index{type}
Within a method definition, {\tt self} refers to the
\emph{invocant}, the object that invoked the method.
There is a short hand for it: \verb'$.' so that we could
write the {\tt coordinates} method as follows:
\index{self}
\begin{verbatim}
method coordinates { # accessor to both x and y
return ($.abscissa, $.ordinate)
}
\end{verbatim}
The two syntax formats, \verb'$.' and {\tt self.}, are
essentially equivalent.
There is a third syntactic way of doing it, using an
exclamation mark instead of a dot:
\begin{verbatim}
method coordinates { # accessor to both x and y
return ($!abscissa, $!ordinate)
}
\end{verbatim}
Here, the result would be the same, but this new syntax is
not equivalent: \verb'$.abscissa' is a method invocation,
whereas \verb'$!abscissa' provides direct access to the attribute.
The difference is that \verb'$!abscissa' is available only
within the class (and might be slightly faster), while
the method invocation syntax can be used somewhere else
(for example in another class). We will see in the next section
examples of this distinction and its consequences.
\index{invocation!method}
\index{method invocation}
We can now create an object and call our methods on it:
\begin{verbatim}
my $point = Point2D.new(
abscissa => 4,
ordinate => 3
);
say $point.coordinates; # -> (4 3)
say $point.distanceToCenter; # -> 5
say $point.polarCoordinates; # -> (5 0.643501108793284)
\end{verbatim}
\index{topical variable}
\index{invocant}
You might remember from previous chapters that if you use a method
without naming an explicit invocant, then the method applies to
the \verb'$_' topical variable:
\begin{verbatim}
.say for <one two three>; # -> one two three (each on one line)
\end{verbatim}
\index{for loop}
\index{given statement}
Now that we have created an object with some methods, we can also
take advantage of the same syntax shortcut. For example if we
use {\tt for} or {\tt given} to populate the \verb'$_' topical
variable with the \verb'$point' object, we can write:
\begin{verbatim}
given $point {
say .coordinates; # -> (4 3)
say .distanceToCenter; # -> 5
.polarCoordinates.say; # -> (5 0.643501108793284)
}
\end{verbatim}
As an exercise, you could write a method called
\verb"distance_between_points" that takes two Points
as arguments and returns the distance between
them using the Pythagorean theorem.
The methods of our class so far are all \emph{accessors}, which
means they provide a snapshot of some of the invocant's attributes.
If the attributes are mutable (declared with the \verb'is rw'
trait), we can also create some \emph{mutators}, i.e. methods
that can be invoked to change those mutable attributes:
\index{accessor}
\index{mutator}
\begin{verbatim}
class Point2D-mutable {
has Numeric $.abscissa is rw;
has Numeric $.ordinate is rw;
# perhaps the same accessors as in the class definition above
method new-ordinate (Numeric $ord) {
self.ordinate = $ord;
}
}
# Creating the Point2D-mutable object:
my $point = Point2D-mutable.new(abscissa => 3, ordinate => 4);
say $point; # -> Point2D-mutable.new(abscissa => 3, ordinate => 4)
# Modifying the ordinate:
$point.new-ordinate(6);
say $point; # -> Point2D-mutable.new(abscissa => 3, ordinate => 6)
\end{verbatim}
\section{Rectangles and object composition}
\label{rectangles}
\index{rectangle}
\index{composition!object}
\index{object!composition}
Sometimes it is obvious what the attributes of an object should be,
but other times you have to make decisions. For example, imagine you
are designing a class to represent rectangles. What attributes would
you use to specify the location and size of a rectangle? You can
ignore angle; to keep things simple, assume that the rectangle's edges
are either vertical or horizontal.
\index{representation}
There are at least two possibilities:
\begin{itemize}
\item You could specify one corner of the rectangle
(or the center), the width, and the height.
\item You could specify two opposing corners.
\end{itemize}
At this point it is hard to say whether either is better than
the other, so we'll implement the first one, just as an example.
\index{Rectangle class}
\index{class!Rectangle}
Here is the class definition:
\begin{verbatim}
class Rectangle {
has Numeric $.width;
has Numeric $.height;
has Point2D $.corner; # lower left vertex
method area { return $.width * $.height }
method topLeft { $.corner.abscissa, $.corner.ordinate + $.height; }
# other methods, e.g. for other corners' coordinates, center, etc.
}
\end{verbatim}
%
The new feature compared to the previous {\tt Point2D} class
definition is that the \verb'Rectangle' class can now use the
{\tt Point2D} type created previously for defining the corner
attribute.
The {\tt topLeft} method returns the coordinates of
the top left angle of the rectangle. This {\tt topLeft}
method gives us an opportunity to explain a bit more
the difference between the \verb'$.' and \verb'$!' twigils. We have
used \verb'$.corner.abscissa' to obtain the abscissa of
the corner, i.e. in effect an accessor invocation. We could
have directly accessed the {\tt corner} and {\tt height}
attributes of the {\tt Rectangle} class and used the following
method definition:
\index{twigil}
\index{invocation!method}
\index{method invocation}
\begin{verbatim}
method topLeft { $!corner.abscissa, $!corner.ordinate + $!height; }
\end{verbatim}
But it would not be possible to use \verb'$!corner!abscissa' or
\verb'$.corner!abscissa', because {\tt abscissa} is not an
attribute defined in the {\tt Rectangle} class, and thus cannot
be accessed directly there. You can use direct access
to the attribute (for example with the \verb'$!abscissa' syntax)
only within the class where this attribute is defined,
{\tt Point2D}. So, in {\tt Rectangle}, we need to invoke the
accessor (i.e. the syntax with \verb'$.') for obtaining the
value of the corner abscissa.
We can now create a {\tt Rectangle} object:
\index{rectangle}
\begin{verbatim}
my $start-pt = Point2D.new(abscissa => 4, ordinate => 3);
my $rect = Rectangle.new(corner => $start-pt, height => 10, width => 5);
say "Topleft coord.: ", $rect.topLeft; # -> Topleft coord.: (4 13)
say "Rectangle area: ", $rect.area; # -> Rectangle area: 50
\end{verbatim}
\index{named parameter}
\index{parameter!named}
You might have noticed that the arguments passed to the
{\tt Rectangle.new} constructor are not in the same order as
in the class definition. We did that on purpose
to show that the order is unimportant because we
are using named arguments.
Figure~\ref{fig.rectangle} shows the state of this object.
\begin{figure}
\centerline
{\includegraphics[scale=0.8]{figs/rectangle.png}}
\caption{Object diagram.}
\label{fig.rectangle}
\end{figure}
\index{state diagram}
\index{diagram!state}
\index{object diagram}
\index{diagram!object}
\index{embedded object}
\index{object!embedded}
\index{object!composition}
\index{composition!object}
Using an object as an attribute of another object, possibly
of another class, is called {\bf object composition}. An object
that is an attribute of another object is {\bf embedded}. Object
composition makes it possible to easily define nested layers of
abstraction and is a powerful feature of object oriented
programming. In our ``geometry'' example, we started to define
a low level object, a {\tt Point2D} instance, and then used
that point to build a higher level type, {\tt Rectangle}.
\section{Instances as return values}
\index{instance!as return value}
\index{return!value}
Methods can return instances of another class. For example,
the {\tt Rectangle} class can have methods returning
instances of {\tt Point2D} for the other corners:
\begin{verbatim}
method topRightPoint {
return Point2D.new(
abscissa => $!corner.abscissa + $!width,
ordinate => $!corner.ordinate + $!height
);
}
# other methods for other corners
\end{verbatim}
Notice that we don't even bother to give a name to upper right
point (although we could, if we wanted); we create it with the
constructor and return it on the fly.
We can use the new method as follows:
\begin{verbatim}
my $topRightPt = $rect.topRightPoint;
say "Top right corner: ", $topRightPt;
# -> Top right corner: Point2D.new(abscissa => 9, ordinate => 13)
\end{verbatim}
\index{type}
Although this is not very useful in such a simple case, we
could play it safe and declare a {\tt Point2D} type for
\verb'$topRightPt':
\begin{verbatim}
my Point2D $topRightPt = $rect.topRightPoint;
\end{verbatim}
This way, the code will raise an error if the {\tt topRightPoint}
happens to return something else than a {\tt Point2D} instance.
Similarly, the \verb"find-center" method invoked on a
{\tt Rectangle} returns a {\tt Point2D} instance
representing the center of the {\tt Rectangle}:
\begin{verbatim}
method find-center { Point2D.new(
abscissa => $!corner.abscissa + $!width / 2,
ordinate => $!corner.ordinate + $!height / 2
);
}
\end{verbatim}
%
This new method can be used as follows:
\begin{verbatim}
say "Center = ", $rect.find-center;
# -> Center = Point2D.new(abscissa => 6.5, ordinate => 8.0)
\end{verbatim}
%
\section{Inheritance}
\index{inheritance}
\index{inheritance!class}
\index{class!inheritance}
Inheritance is probably the most emblematic feature of
object-oriented programming. It is a mechanism through which it
is possible to derive a class from another class. Inheritance is
one of the standard ways to implement code reuse in
object-oriented programming. It is also another useful way of
defining successive layers of abstraction and a hierarchy of
types.
\subsection{The Pixel class}
\index{class!Pixel}
\index{Pixel class}
The {\tt Point2D} class is very general and could be used for
a variety of purposes: geometry, vector graphics, animated mangas
and so on. We may want to use it to display graphic data on a
screen. For this scenario, let's create a new derived class,
{\tt Pixel}, adding new properties to the point, such as color,
perhaps transparency, etc.
Do we need to redefine all the attributes and methods for
the new class? No, we don't. We can define a new class that
\emph{inherits} the properties of the {\tt Point2D} base class
and only modify what is no longer suitable or add whatever
new features we need. Here, we want a new attribute to represent
the pixel color and probably some new methods dealing with this
new attribute.
According to the most common standards, a color is defined
by three integers (really three octets, i.e. integers
between 0 and 255 in decimal notation), representing the red,
green and blue (RGB) components of the pixel:
\index{class!child}
\index{Pixel class}
\index{RGB}
\index{octet}
\begin{verbatim}
class Pixel is Point2D {
has %.color is rw;
method change_color(%hue) {
self!color = %hue
}
method change_color2(Int $red, Int $green, Int $blue) {
# signature using positional parameters
self!color = (red => $red, green => $green, blue => $blue)
}
}
\end{verbatim}
\index{parameter!positional}
\index{parameter!named}
\index{positional parameter}
\index{octet}
\index{is!subclassing trait}
The new class \emph{inherits} the properties of {\tt Point2D}
thanks to the {\tt is Point2D} trait, except possibly those
which are explicitly modified (or overridden) or added in
the new class. The new class is sometimes
called child class or subclass, whereas {\tt Point2D} is the
parent class. Creating this new class based on
{\tt Point2D} is called subclassing the {\tt Point2D}
parent class.
\index{class!parent}
\index{class!child}
\index{class!subclass}
\index{subclassing}
\index{overriding a method}
\index{method!overriding}
The new child class inherits the {\tt abscissa} and
{\tt ordinate} attributes of the {\tt Point2D} parent
class (and their specific type and properties if any),
as well as the methods such as {\tt coordinates} defined
in the parent class. The child class has a new
attribute (the color) and two new methods.
In the preceding code example, we have written two different
methods for changing the color
only to illustrate two possible syntax formats, for pedagogical
purpose. The first one receives a hash as a parameter, and
the second one uses positional parameters, which forces
the user to remember the order (RGB) in which the arguments must
be passed; this can be a source of error and should be avoided
when the number of the parameters exceeds a certain limit
(which will be left to the decision of the reader). On the other
hand, anyone working commonly with graphics knows by heart the
standard conventional order of colors (i.e. RGB). Also,
the second method has the
advantage of enabling some type checks (the arguments must
be integers). This is a simplified example; in real life, it
may be desirable to check that the parameters are octets, i.e.
integers between 0 and 255 (which could be done by adding a
type constraint or defining a subset of the Integer type).
\index{subset}
\index{RGB}
\index{octet}
Using the new {\tt Pixel} class is straight forward:
\begin{verbatim}
say "Original colors: ", $pix.color;
$pix.change_color({:red(195), :green(110), :blue(70),});
say "Modified colors: ", $pix.color;
say "New pixel caracteristics:";
printf \tAbscissa: %.2f\n\tOrdinate: %.2f\n\tColors: R: %d, G: %d, B: %d\n",
$pix.abscissa, $pix.ordinate,
$pix.color<red>, $pix.color{"green"}, $pix.color{"blue"};
$pix.change_color2(90, 180, 30); # positional args
say "New colors: R: {$pix.color<red>}, G: {$pix.color<green>}, B: {$pix.color<blue>} ";
\end{verbatim}
This displays the following output:
\begin{verbatim}
Original colors: {blue => 145, green => 233, red => 34}
Modified colors: {blue => 70, green => 110, red => 195}
New pixel caracteristics:
Abscissa: 3.30
Ordinate: 4.20
Colors: R: 195, G: 110, B: 70
New colors: R: 90, G: 180, B: 30
\end{verbatim}
To tell the truth, it was not necessary to use two different
method names, \verb'change_color' and \verb'change_color2', as
we did in the {\tt Pixel} class definition to simplify matters.
It would just work the same way if we use these definitions:
\index{Pixel class}
\index{method dispatch}
\begin{verbatim}
multi method change_color(%hue) {
self.color = %hue
}
multi method change_color(Int $red, Int $green, Int $blue) {
# signature using positional parameters
self.color = (red => $red, green => $green, blue => $blue)
}
\end{verbatim}
Since the multi method is defined twice, with the same name but
with a different signature, the object system is able to
dispatch the invocation to the right method.
\index{method!dispatch}
\index{multi method}
\subsection{The MovablePoint class}
\index{class!MovablePoint}
\index{MovablePoint class}
The \verb'$.abscissa' and \verb'$.ordinate' attributes of
class {\tt Point2D} are defaulted to read-only. After all,
when you define a point in the plan, it usually has a fixed
position and there is generally no reason to change its
coordinates.
Suppose, however, that our application is about kinematics
(the branch of physics dealing with the motion of points or
bodies) or is a video game. In such a case, we probably want
our points (or sets of points) to move. We need a new class,
{\tt MovablePoint}, enabling the modification of coordinates.
We don't need to redefine all the attributes and methods for
the new class. Again, we can define a new class that
\emph{inherits} the properties of the {\tt Point2D} base class
and only modify what is no longer suitable or add whatever
new features we need, for example:
\begin{verbatim}
class MovablePoint is Point2D {
has Numeric $.abscissa is rw;
has Numeric $.ordinate is rw;
method move (Numeric $x, Numeric $y) {
$.abscissa += $x;
$.ordinate += $y;
}
}
\end{verbatim}
\index{is!subclassing trait}
Again, the new class inherits the properties of {\tt Point2D} thanks
to the {\tt is Point2D} trait, except those which are explicitly
modified (or overridden) or added in the new class.
Methods that exist in the parent class and are
redefined in a child class are said to be \emph{overridden}
within that class.
\index{class!parent}
\index{class!child}
\index{class!subclass}
\index{subclassing}
\index{overriding a method}
\index{method!overriding}
Here, the \verb'$.abscissa' and \verb'$.ordinate' attributes are
redefined as read and write (through the {\tt is rw} trait) and
a new method, {\tt move}, is defined to modify the position of
a point by adding the received parameters to the coordinates
of the point.
\index{is rw trait}
Note that we have used here positional parameters for the
{\tt move} method. We said that it is often better for the sake of clarity
to use named parameters, but we have here only two parameters;
as it is fairly simple to remember that the \verb'$x'
parameter should come before the \verb'$y' parameter, this
was a good occasion to illustrate the possibility of using
positional parameters.
\index{positional parameter}
\index{parameter!positional}
\index{parameter!named}
\index{named parameter}
We can now test our new child class, create a {\tt MovablePoint}
instance, display its characteristics, move it to a different
location, and display the new position:
\begin{verbatim}
my $point = MovablePoint.new(
abscissa => 6,
ordinate => 7,
);
say "Coordinates : ", $point.coordinates;
say "Distance to origin: ", $point.distanceToCenter.round(0.01);
printf "%s: radius = %.4f, theta (rad) = %.4f\n",
"Polar coordinates", $point.polarCoordinates;
say "--> Moving the point.";
$point.move(4, 5);
say "New coordinates: ", $point.coordinates;
say "Distance to origin: ", $point.distanceToCenter.round(0.01);
printf "%s: radius = %.4f, theta (rad) = %.4f\n",
"Polar coordinates", $point.polarCoordinates;
\end{verbatim}
This produces the following output:
\begin{verbatim}
Coordinates : (6 7)
Distance to origin: 9.22
Polar coordinates: radius = 9.2195, theta (rad) = 0.8622
--> Moving the point.
New coordinates: (10 12)
Distance to origin: 15.62
Polar coordinates: radius = 15.6205, theta (rad) = 0.8761
\end{verbatim}
\index{polar coordinates}
\index{coordinates!polar}
Here, when the user code invokes the {\tt coordinates},
{\tt distanceToCenter} and {\tt polarCoordinates} methods,
Perl find that they do not exist in {\tt MovablePoint}. But,
as \verb'MovablePoint' subclasses {\tt Point2D}, the program
looks for method having this name in the parent class and
invokes them if it finds them. If it did not find them, it
might look up into the parent's parent if there is any, and
so on.
\subsection{Multiple inheritance: attractive, but is it wise?}
In object-oriented programming, the inheritance mechanism is
a traditional way to reuse code, it is even probably the most
common way to do it.
A class may have several parent classes and, thus, subclass
several other classes. This is what is called multiple
inheritance. We might want to build a new {\tt MovablePixel}
class inheriting from both {\tt MovablePoint} and {\tt Pixel}
(and, indirectly, from {\tt Point2D}). Technically, you can
easily do it in Perl:
\begin{verbatim}
class MovablePixel is MovablePoint is Pixel {
# ...
}
\end{verbatim}
Now, {\tt MovablePixel} is subclassing both
{\tt MovablePoint} and {\tt Pixel} and inheriting
from both parent classes.
\index{subclass}
\index{class!parent}
This looks very promising, but it turns out to be more
complicated than expected in real situations. If there is a
conflict (for example a name collision between two methods),
which one shall prevail? There exists some mechanism to
handle such situations (for example in the C++ programming
language), and Perl has some metaobject methods to find out
about the method resolution order (MRO), but this
might quickly leads to severe design
problems and to really subtle or complicated bugs. In
short, while multiple inheritance originally looked as a
attractive idea, it turned out to be complicated to master,
because it creates multiple and often implicit dependencies
that are quite hard to sort out.
This is the reason why, contrary to C++, relatively more recent
OO programming languages such as Java (which came out not
so recently, back in 1995) have decided not to implement
multiple inheritance.
Perl~6 does not want to forbid such things and allows you
to do multiple inheritance if you wish, and it can be useful
for simple cases; so don't necessarily rule it out, but
remember that, contrary to early expectations, it often
leads to a mess and turns out to be quite unmanageable.
Perl offers better concepts for tackling such situations,
as we will see shortly.
\section{Roles and composition}
\index{role}
\index{inheritance}
Inheritance is a very powerful concept to describe a hierarchical
tree of concepts. For example, you can think of a hierarchy of
geometrical figures having more and more specific properties:
\begin{enumerate}
\item Polygon.
\index{quadrilateral}
\item Quadrilateral (a polygon with four edges and four corners).
\index{trapezoid}
\item Trapezoid (a quadrilateral with one pair of parallel edges).
\index{parallelogram}
\item Parallelogram (a trapezoid with two pairs of parallel
edges and opposite sides of equal length).
\index{rectangle}
\item Rectangle (a parallelogram with four right angles).
\index{square}
\item Square (a rectangle with all four edges of equal length).
\end{enumerate}
\index{rhombus}
It is relatively easy to imagine a series of classes with a
hierarchical inheritance tree reflecting those properties. It
gets slightly more complicated, however, if we add the rhombus
(a parallelogram with all sides equal), because the square is
now \emph{also} a rhombus with four right angles, so that
the square class would subclass both the rectangle and the
rhombus, and we might have here a possible multiple inheritance
issue.
\index{integer} \index{rational} \index{real number} \index{complex number}
\index{vertebrate} \index{mammal} \index{carnivoran}
\index{canid} \index{dog}
Similarly, we can think of a tree of classes with nested
inheritance representing various types of numbers (e.g. integer,
rational, real, complex) or animals species (e.g. vertebrate,
mammal, carnivoran, canid, dog, Irish setter).
\index{hierarchical model}
These are great examples for inheritance, but the real world is
rarely so hierarchical, and it is often difficult to force
everything to fit into such a hierarchical model.
\index{role}
This is one of the reasons why Perl introduces the notion of
roles. A role is a set of behaviors or actions that can be shared
between various classes. Technically, a role is a collection
of methods (with possibly some attributes); it is therefore
quite similar to a class, but the first obvious difference
is that a role is not designed to be instantiated as an object
(although roles can be promoted into classes). The
second difference, perhaps more important, is that roles
don't inherit: they are used through application to a class
and/or composition.
\subsection{Classes and roles: an example}
\index{vertebrate} \index{mammal} \index{dog}
Let's come back to vertebrates, mammals and dogs. A dog is
a mammal and inherits some characteristics from the mammals,
such as having a neocortex (a region of the brain), hair,
and mammary glands, as well as a vertebral column, which
all mammals (along with fishes, birds, reptiles and others)
inherit from vertebrates. So far, the class hierarchy seems
simple and natural.
\index{feral animal}
\index{pet animal}
But dogs can have very different characteristics and behaviors.
To quote the Wikipedia article on dogs: ``Dogs perform many
\emph{roles} for people, such as hunting, herding, pulling
loads, protection, assisting police and military, companionship
and, more recently, aiding handicapped individuals'' (italic emphasis
added). Dogs can also be \emph{feral} animals
(i.e. animals living in the wild but
descended from domesticated individuals) or stray dogs. All
these additional behaviors might be added to the dog class.
Similarly, a cat, another mammal, may also be a pet
or a feral animal. Mustangs, North-American free-roaming horses,
are also feral animals, descended from once-domesticated horses;
but a mustang may also be captured and brought back to
domesticated state. This return to the wild of feral animals
is not limited to mammals: pigeons living in our cities are
often descended from once-domesticated homing pigeons used
in the past. It can even happen with invertebrates, such
as swarms of honey bees.
It is apparent that a hierarchical modeling of inheritance
trees is not adapted to describe such behaviors.
\index{vertebrate} \index{mammal} \index{dog}
We can define classes for dogs, cats, and horses as subclasses
of mammals (which itself inherits from vertebrates). Besides
that, we define roles for pet or feral animals. In addition,
we can create new classes subclassing the dog, horse and cat
classes and doing some specific roles; or we can assign roles
to individual instances of a class. This could look like this
(this is a dummy example which cannot be tested):
\begin{verbatim}
class Vertebrate { method speak {say "vertebrate"};}
class Mammal is Vertebrate { method speak { say "mammal" } }
class Bird is Vertebrate { method fly {} }
class Dog is Mammal { method bark {} }
class Horse is Mammal { method neigh {} }
class Cat is Mammal { method meow {} }
class Mouse is Mammal { method squeek {} }
class Duck is Bird { method quack {} }
# ...
role Pet-animal {
method is-companion() {...}
# other methods
}
role Shepherd { ... } # sheep keeper
role Feral { ... } # animal back to wild life
role Guide { ... } # blind guide
role Human-like { ... } # animal behaving like a human
# ...
class Guide-dog is Dog does Guide { ... }
class Shepherd-dog is Dog does Shepherd { ... }
class Stray-dog is Dog does Feral { ... }
class Pet-cat is Cat does Pet-animal { ... }
class Feral-cat is Cat does Feral { ... }
class Mustang is Horse does Feral { ... }
class Domestic-canary is Bird does Pet-animal { ... }
# ...
# Role can also be applied to instances:
my $garfield = Pet-cat.new(...);
my $mickey = Mouse.new(...);
$mickey does Human-like;
my $donald = Duck.new(...);
$donald does Human-like;
my $pluto = Dog.new(...);
$pluto does Pet-animal;
my $snoopy = Dog.new(...);
$snoopy does Pet-animal does Human-like;
\end{verbatim}
\index{role!application}
\index{does trait}
\index{trait!does}
\index{trait!is}
A role is applied to a class or an object with the {\tt does}
trait (as opposed to {\tt is} for inheritance). These
different keywords reflect the semantic difference associated
to them: composing a role into a class or an object provides
this class or object with the \emph{supplementary behavior} associated with
the role, but it does not follow that the object receiving
the role is \emph{the same thing} as or of the same nature
as the role.
\index{feral animal}
\index{pet animal}
If the {\tt Pet-animal} and {\tt feral} roles had been defined
as classes, then the {\tt Pet-cat} and {\tt Feral-cat} classes
would have undergone double inheritance, with the potential
problems associated with that. By applying a role to a
class, you avoid constructing a multiple-inheritance tree
that is probably not really justified and can be complicated
to conceptualize and difficult to maintain. Judicious use
of classes and roles can lead to a model that is simpler,
more natural, and closer to the real relations between the
entities and behaviors under scrutiny.
\index{multiple inheritance}
\index{method!dispatch}
\index{role!composition}
In addition, if you inadvertently compose several roles with
two methods having the same name, this raises immediately
an error (unless a method of the same name exists within the
class, in which case it prevails), rather than dispatching
silently to one of the two methods as in the case of multiple
inheritance. In that case, naming conflicts are identified
immediately (at compile time), which has the benefit of
immediately finding a bug that might otherwise go
unseen for a while.
\subsection{Role composition and code reuse}
Classes are meant for managing instances and roles are
meant for managing behaviors and code reuse. The following
example shows how classes and roles can play together.
\index{class}
\index{role}
\index{code reuse}
\begin{verbatim}
role Drawable {
has $.color is rw;
method draw { ... }
}
class Figure {
method area { ... }
}
class Rectangle is Figure does Drawable {
has $.width;
has $.height;
method area {
$!width * $!height;
}
method draw() {
for 1..$.height {
say 'x' x $.width;
}
}
}
Rectangle.new(width => 10, height => 4).draw;
\end{verbatim}
\index{ellipsis}
Please note that the ellipsis \verb'...' used in the code
above is meant here to represent some code that is left
to your implementation. However, this is actually valid code
and it will compile and even run without any problem. The
ellipsis is used to figure a functionality that is not yet
there but is supposed to be implemented at a later point. This
will work so long as you don't invoke these methods (you would
get a runtime error) or don't setup a situation where it would
need to be defined (which would cause a compile time error).
In the case of the {\tt draw} method in the
{\tt Drawable} role, role composition into the {\tt Rectangle}
class works only because {\tt draw} is redefined in the
{\tt Rectangle} class; without this redefinition, it would
have raised a compile-time error. Similarly,
the \verb'method area { ... }'
code of the {\tt Figure} class would raise a run-time error if it
were called without having been redefined in the {\tt Rectangle}
class. The ellipsis has been used here only as a convenient way
to represent code whose implementation is not important for
our example because it is being redefined anyway. In real coding,
it is probably best advised not to use ellipsis, except as a
temporary expedient for code that is not yet developed but
will be implemented.
The code example above draws an ASCII rectangle:
\begin{verbatim}
~ perl6 test_drawable.pl6
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
\end{verbatim}
\subsection{Roles, classes, objects, and types}
\index{role}
\index{class}
\index{object}
\index{type}
A role can be applied to an entire class or only to some
instances of the class:
\begin{verbatim}
role Guide { ...}
class Guide-dog is Dog does Guide {
...
} # Composing the Guide role into the Guide-dog class
# inheriting from the Dog class
my $doggy = new Dog; # creating a Dog object
$doggy does Guide; # applying the role to the object
\end{verbatim}
\index{type}
\index{role!type}
\index{type!-defining role}
\index{guide}
Roles and classes are different, but both are or define types.
This means that a role can be used as a type for a variable
declaration where you might expect a class name. For example,
the {\tt Guide} role sketched in the code snippet above does
effectively create a {\tt Guide} type. So a {\tt Blind} role for
a human might have an attribute of {\tt Guide} type, which
might represent a guide-doq, a guide-horse, a human guide or
even a guiding robot.
\begin{verbatim}
class Human {
has Dog $dog; # May contain any dog, with or without
# a guide role
}
role Blind {
has Guide $guide; # May contain any Guide type, whether
# a dog, a horse, a human or a robot
}
\end{verbatim}
\index{type!built-in}
A number of Perl~6 built-in types are defined by roles and
not by classes, such as {\tt IO}, {\tt Iterable},
{\tt Iterator}, {\tt Numeric}, {\tt Rational}, {\tt Real},
etc.
\section{Method delegation}
\index{delegation}
Delegation is another way to link an object to another piece
of code. The delegation technique has been relatively well
studied at the theoretical level and implemented in a few
specialized research languages, but mainstream generalist
languages implementing delegation are rather rare.
Rather than defining methods in a class or in a role, the
idea is to invoke methods belonging to another object, as
if they were methods of the current class. In Perl~6, delegation
may be performed at the level of a class or a role. A delegated
object is simply an attribute defined in the class or in the role
with the {\tt handles} keyword which makes it possible to specify
which methods of the delegated object may be used in the
current class.
\index{Cervantes, Miguel de} \index{Shakespeare, William}
\index{Chekhov, Anton} \index{Schiller, Friedrich} \index{Hamlet}
\index{Don-Quijote} \index{Don-Carlos} \index{Three Sisters}
\begin{verbatim}
class BaseClass {
method Don-Quijote() { "Cervantes" }
method Hamlet() { "Shakespeare" }
method Three-Sisters () { "Chekhov" }
method Don-Carlos() { "Schiller" }
}
class Uses {
has $.base is rw handles < Don-Quijote Hamlet Three-Sisters >;
}
my $user = Uses.new;
$user.base = BaseClass.new(); # implementing an object-handler
say $user.Don-Quijote;
say $user.Hamlet;
say $user.Three-Sisters;
say $user.Don-Carlos;
\end{verbatim}
This displays the following output:
\begin{verbatim}
Cervantes
Shakespeare
Chekhov
Method 'Don-Carlos' not found for invocant of class 'Uses'
in block <unit> at delegate.pl6 line 16
\end{verbatim}
\index{invocant}
The program properly displays the names of writers returned
by the first three methods, because they have been sort of
``imported'' into the {\tt Uses} class, but it fails on the
last one, because ``Don-Carlos'' is not part of the handler's
list. The error on the last method is a run-time exception
and the program would stop running there even if there
were some more correct code afterward.
Note that the {\tt Uses} class does not know from where the
methods will be imported; it only knows about the names of
the methods that will be imported. It is only when the
\verb'$user' object is created and the \verb'$user.base'
attribute added to it that the object is dynamically
associated with the methods defined in {\tt BaseClass}.
By the way, this process could be done in just one step:
\begin{verbatim}
my $user = Uses.new( base => BaseClass.new() );
\end{verbatim}
There is no need to enumerate the methods to be handled. The
{\tt Uses} class can import all the methods of {\tt BaseClass}:
\begin{verbatim}
class Uses {
has $.base is rw handles BaseClass;
}
\end{verbatim}
This will work as before, except of course that it will not fail
on the {\tt Don-Carlos} method this time, since this method is
also imported now:
\begin{verbatim}
Cervantes
Shakespeare
Chekhov
Schiller
\end{verbatim}
\section{Polymorphism}
\index{polymorphism}
\index{interface}
Polymorphism is a way to supply a common or close interface
to different types. In a certain way, the inheritance examples
studied previously offer a form of polymorphism: the
{\tt coordinates}, {\tt distanceToCenter} and {\tt PolarCoordinates}
methods are polymorphic, since they can apply to
{\tt Point2D}, {\tt movablePoint} and {\tt pixel} types. But
these are trivial forms of polymorphism. We will speak of
polymorphism when the relevant methods or functions are
doing something different from each other, at least at the
implementation level, even if they share the same name and
interface.
\index{multi!subroutine}
\index{invocant}
Outside of the object-oriented programming, Perl's
\emph{multi} subroutines implement a form of polymorphism,
since they can behave differently depending on the
type and number of their arguments. Within the OOP context,
it is often the type of the invocant (its class or possibly one
of its roles) which will determine, usually at run-time,
which of the possible methods will be invoked.
For example, we might want to create a new class for points
in a three-dimensional space. The methods will have to be
different, but it seems interesting to offer the user an
interface that is the same (or almost) as for two-dimensional
points.
\index{Point3D class}
\begin{verbatim}
class Point3D {
has Numeric $.x;
has Numeric $.y;
has Numeric $.z;
method coordinates () { # accessor to the 3 coordinates
return $.x, $.y, $.z
}
method distanceToCenter () {
return ($.x ** 2 + $.y ** 2 + $.z ** 2) ** 0.5
}
method polarCoordinates () {
return self.sphericalCordinates;
}
method sphericalCoordinates {
my $rho = $.distanceToCenter;
my $longitude = atan2 $.y, $.x; # theta
my $latitude = acos $.z / $rho; # phi
return $rho, $longitude, $latitude;
}
method cylindricalCoordinates {
# ...
}
}
\end{verbatim}
The methods in this new class are not the same as those in
{\tt Point2D}, but methods having a similar semantics have
the same name; it is thus possible to use either class
without being lost with different names.
The {\tt distanceToCenter} method has exactly the same interface.
The {\tt coordinates} method returns a list of three values
instead of two, but the calling convention is the same. Note
that it might also have been possible to design {\tt Point2D}
so that this method would return also a third zero value, in order
to have exactly the same interface (after all, a point in
the plane might be considered as a point in the 3D space
with a zero height); complying to exactly the same
interface is not mandatory, but only a possible implementation
decision that might make a more intuitive interface.
\index{polar coordinates}
\index{spherical coordinates}
\index{coordinates!polar}
\index{coordinates!spherical}
The notion of polar coordinates does not have a well-defined
meaning in a 3D-space, but we have chosen here to keep the name
in our interface because it is intuitively quite similar to
the idea of spherical coordinates; but it does nothing more
than invoking the sphericalCoordinates method on its invocant
and to return the return values.
\index{invocant}
Please note that mathematicians, physicists, astronomers,
engineers, geographers, and navigators all use the same basic system
for spherical coordinates, but their conventions are different
concerning the origin, the angle range, angle measurement
units and rotation direction, and the name of the various
values or symbols associated with them. So you might find
some different formulas in a textbook. The conventions and
formulas we have used here are commonly used in geography and
some branches of mathematics. A real general-purpose class
might have to take these varying conventions into account and
implement the necessary conversions.
\section{Encapsulation}
\index{encapsulation}
Encapsulation is the idea of hiding the data and the code
of a library or a module from the user. It is not specific to
object-oriented programming, but it is a fundamental concept
of OOP.
\index{accessor}
\index{mutator}
\index{getter}
\index{setter}
In object-oriented programming, encapsulation consists in
protecting the data in an object from being tampered
directly (and possibly made inconsistent)
by their user, who can access such data only through
the means of methods. This is achieved by providing to the
user methods that are commonly called \emph{accessors} (or
\emph{getters}) and \emph{mutators} (or \emph{setters}). This
makes is possible to ensure that the object properties will
be validated by its methods.
\index{black box}
\index{object!interface}
Encapsulation is a strong form of data abstraction and
procedural abstraction. Seen from outside, an object
is a black box having some specified properties and
behaviors. This way, these properties and behaviors are
\emph{hidden} from the user. They're not hidden in the
sense that the user cannot know about them (at least in
the open-source world, it is easy to know that), but
hidden in the sense that it is usually not possible to
use that knowledge to bypass the supplied interface. This
means that the internal implementation of the object may
change without having to modify the external behavior. If you
are going to use insider knowledge, your code will
probably break when the internal implementation is
modified, so don't do that.
Various programming languages don't have same rules for
guaranteeing encapsulation. Some are stricter than others,
some are less restrictive for read access than for write access,
others don't make such a distinction but rather rely on the
visibility level specified for an attribute, for example
``public'' or ``private'' (with sometimes an intermediate
``protected'' level).
\index{attribute!private}
Perl~6 lets you choose the encapsulation model you want to
apply to your objects and attributes. All attributes are
private. If you declare a class as follows:
\begin{verbatim}
class Point2D {
has $!abscissa;
has $!ordinate;
# β¦
method value_x { return $!abscissa }
method value_y { return $!ordinate }
}
\end{verbatim}
the \verb'$!x' and \verb'$!y' coordinates will be
accessible only from within the class. This is why
we have added accessor methods. In addition, the
attributes are immutable by default.
But as we have seen earlier, if you declare this class
as follows:
\begin{verbatim}
class Point2D {
has $.abscissa;
has $.ordinate;
# ...
}
\end{verbatim}
the coordinates will still be private attributes, but Perl~6
will automatically generate accessor methods having the same
names as the attributes, so that it will be possible to access
them from outside the class almost as if they were public:
\index{attribute!public}
\begin{verbatim}
class Point2D {
# ...
}
my $point = Point2D.new(abscissa => 2, ordinate => 3);
say $point.abscissa; # -> 2
\end{verbatim}
\index{attribute!mutable}
\index{attribute!immutable}
Whether the attribute is mutable or not is managed separately
by the {\tt is rw} trait. In brief, Perl~6 offers a default
access mode, but you can finely tune what you need.
\subsection{Private methods}
\index{private method}
\index{method!private}
\index{interface}
Methods are the normal way to use objects, whether with read only
or read and write access. They usually form the \emph{interface}
of a class, that is the part of the class that is made public
and available to programmers wishing to use them. It is thus
natural and legitimate for methods to be public, i.e. accessible
from outside the class.
\index{method!public}
\index{public method}
But a class may also contain numerous methods that are part
of the internal cooking recipes of the class, i.e. the way it does
things internally, and that are not
meant to be used from outside the class. It is possible to prevent
their use from outside the class by making these methods private.
A Perl~6 private method is prefixed with an exclamation mark:
\begin{verbatim}
method !private-behavior($x, $y) {
...
}
\end{verbatim}
You will also need to use an exclamation mark to call them:
\begin{verbatim}
$my-object!private-behavior($val1, $val2)
\end{verbatim}
\index{private method}
\index{method!private}
Private methods are really internal to a given class. In
particular, they are not inherited by child classes.
\subsection{Constructing objects with private attributes}
Constructing objects with private attributes raises a
little difficulty. Let's consider the following program:
\index{private attribute}
\begin{verbatim}
class Point3D {
has $.x;
has $.y;
has $!z;
method get {
return ($!x, $!y, $!z);
}
};
my $a = Point3D.new(x => 23, y => 42, z => 2);
say $_ for $a.get;
\end{verbatim}
\index{attribute!private}
\index{attribute!public}
In this example, we have declared \verb'$.x' and \verb'$.y'
as ``public'' (so to speak) attributes, and \verb'$.z' as
a truly private attribute. Running this code displays this:
\begin{verbatim}
23
42
(Any)
\end{verbatim}
Oops, what is going on? It seems that the {\tt get}
method is not able to read \verb'$!z', since it returns
an undefined value. This method is defined within the
class; so it should be able to access this attribute. In
fact, {\tt get} is not the problem, it is \verb'$!z' which is
not defined within the object, because it hasn't been properly
initialized during object construction.
\index{new!constructor}
\index{constructor!new}
The guilt lies with the {\tt new} implicit constructor which,
by default, initializes only ``public'' attributes.
\index{submethod}
Here, the simplest solution is probably to add a {\tt BUILD}
submethod in the class definition.
\index{BUILD submethod}
\index{submethod}
\index{subclass}
\index{type}
A \emph{submethod} is a public method of a class that is not inherited
in its child classes. Semantically, it is really equivalent
to a subroutine, but it is called with a method syntax (hence
the name). Submethods are especially useful to perform object
construction and destruction tasks which should not be
inherited by subclasses, as well as for tasks that are
so specific to a given type that classes derived from it
will almost for sure have to redefine them.
Initializing private attributes at object instantiation
might look like this:
\begin{verbatim}
class Point3D {
has $.x;
has $.y;
has $!z;
submethod BUILD (:$!x, :$!y, :$!z) {
say "Initialization";
$!x := $!x;
$!y := $!y;
$!z := $!z;
}
method get {
return ($!x, $!y, $!z);
}
};
my $a = Point3D.new(x => 23, y => 42, z => 2);
say $_ for $a.get;
\end{verbatim}
The program now works as desired and displays all
three attributes:
\begin{verbatim}
Initialization!
23
42
2
\end{verbatim}
This works because the default {\tt new} constructor, a method
defined in the {\tt Mu} ultimate superclass and inherited by
default by any Perl~6 class, calls
the default {\tt BUILD} submethod. If we redefine {\tt BUILD}
in our class, it will supersede the default one
called by {\tt new}. By redefining {\tt BUILD}, we force
the constructor to take into account the private attribute that
was not used previously.
Quite a bit of simplification is possible. Since passing arguments
to a routine binds the arguments to the parameters, a separate
binding step is unnecessary if the attributes are used as
parameters. Hence, the {\tt BUILD} submethod in the example
above could also have been written simply as:
\index{BUILD submethod}
\begin{verbatim}
submethod BUILD(:$!x, :$!y, :$!z) {
say "Initialization!";
}
\end{verbatim}
\index{overriding a method}
\index{named parameter}
\index{positional parameter}
\index{parameter!named}
\index{parameter!positional}
\index{constructor!new}
\index{new!constructor}
While we are speaking about the intricacies of object
construction, note that since {\tt new} is a method inherited
from the {\tt Mu} superclass, you can override it if you wish.
The default {\tt new} constructor can only be used with named
arguments. Assuming you absolutely want to use positional parameters, you
could override {\tt new} with your own method, like so:
\index{new!constructor} \index{constructor!new}
\begin{verbatim}
class Point2D {
has Numeric $.abscissa;
has Numeric $.ordinate;
method new ($x, $y) {
self.bless(abscissa => $x, ordinate => $y);
}
method coordinates { # accessor to both coordinates
return (self.abscissa, self.ordinate)
}
# other methods
};
my $point = Point2D.new(3, 5);
say $_ for $point.coordinates;
\end{verbatim}
This will duly display the two coordinates. {\tt bless} is a
low-level method for object construction, inherited from
{\tt Mu} and called automatically when you invoke
{\tt new} to construct an object. You usually don't need
to know about it, except when you want to write your own custom
constructor.
\index{constructor!custom}
You can give the constructor another name than {\tt new},
for example:
\begin{verbatim}
class Point2D {
has Numeric $.abscissa;
has Numeric $.ordinate;
method construct ($x, $y) {
self.bless(abscissa => $x, ordinate => $y);
}
method coordinates { # accessor to both coordinates
return (self.abscissa, self.ordinate)
}
# other methods
};
my $point = Point2D.construct(3, 5);
say $_ for $point.coordinates;
\end{verbatim}
Think twice, though, before you override {\tt new} or create your
own custom constructor with a different name, as it may make it
more complicated to subclass your {\tt Point2D} class.
\section{Interface and implementation}
One of the goals of object-oriented design is to make software more
maintainable, which means that you can keep the program working when
other parts of the system change, and modify the program to meet new
requirements.
\index{interface}
\index{implementation}
\index{maintainable}
\index{object-oriented design}
A design principle that helps achieve that goal is to keep
interfaces separate from implementations. For objects, that means
that the public interface of the methods provided by a class
should not depend on how the attributes are represented.
\index{attribute}
\index{coordinates!Cartesian}
\index{Cartesian coordinates}
\index{polar coordinates}
For example, we designed a {\tt Point2D} class in which the main
attributes were the point's Cartesian coordinates. We may find
out that, for the purpose of our application, it would be easier
or faster to store the point's polar coordinates in the object
attributes. It is entirely possible to change the internal
implementation of the class, and yet keep the same interface.
In order to do that, we would need the constructor
to convert input parameters from
Cartesian into polar coordinates, and store the latter in the
object attribute. The {\tt polarCoordinates} method would
return the stored attributes, whereas methods returning the
Cartesian coordinates may have to do the backward conversion
(or may perhaps be stored separately in private attributes).
Overall, the change can be made with relatively heavy refactoring
of the {\tt Point2D} class, but users of the class would still
use the same interface and not see the difference.
After you deploy a new class, you might discover a better
implementation. If other parts of the program are using your
class, it might be time-consuming and error-prone to change the
interface.
But if you designed the interface carefully, you can
change the implementation without changing the interface, which
means that other parts of the program don't have to change.
\section{Object-oriented programming: a tale}
\index{tale about OOP}
\index{OOP (object-oriented programming)!a tale}
\index{object-oriented programming (OOP))!a tale}
Most tutorials and books teaching object-oriented
programming tend to focus on the technical aspects
of OOP (as we have done in this chapter so far), and
that's a very important part of it, but they sometimes
neglect to explain the reasons for it. They say ``how'',
but not ``why''. We've tried, and hopefully succeeded, to
explain the ``why'', but this section attempts to
explain OOP from the standpoint of the reasons for it
and its benefits, independently of any technical
consideration, in the form of a parable (the code
examples are only pseudo-code and are not supposed
to compile, let alone to run).
\subsection{The fable of the shepherd}
\index{shepherd}
Once upon a time, there was a sheep farmer who had a
flock of sheep. His typical workday looked like this:
\begin{verbatim}
$shepherd.move_flock($pasture);
$shepherd.monitor_flock();
$shepherd.move_flock($home);
\end{verbatim}
Eventually, due to successful wool sales, he expanded
his farming activities and his day became like this:
\begin{verbatim}
$shepherd.move_flock($pasture);
$shepherd.monitor_flock();
$shepherd.move_flock($home);
$shepherd.other_important_work();
\end{verbatim}
But now the shepherd wanted to devote more time to
\verb'other_important_work()', so he decided to hire
a minion to handle the sheep related work, so the
work was now split like this:
\index{shepherd-boy}
\index{tale about OOP}
\begin{verbatim}
$shepherd-boy.move_flock($pasture);
$shepherd-boy.monitor_flock();
$shepherd-boy.move_flock($home);
$shepherd.other_important_work();
\end{verbatim}
This did give the shepherd more time for
\verb'other_important_work()', but unfortunately the
\verb'$shepherd-boy' had a tendency to cry wolf, so
the farmer had to replace him with a new assistant:
\index{sheep dog}
\index{dog!shepherd}
\begin{verbatim}
$sheep-dog.move_flock($pasture);
$sheep-dog.monitor_flock();
$sheep-dog.move_flock($home);
$shepherd.other_important_work();
\end{verbatim}
\verb'$sheep-dog' was more reliable and demanded
less pay than \verb'$shepherd-boy', so this was
a win for the farmer.
\subsection{The moral}
We can learn a few things from this parable.
\subsubsection{Delegation}
\index{delegation}
To handle complexity, delegate to a suitable
entity e.g. the farmer delegates some of his
work to \verb'$shepherd-boy'.
\subsubsection{Encapsulation}
\index{encapsulation}
Tell objects what to do, rather than micro-manage e.g.:
\begin{verbatim}
$sheep-dog.monitor_flock();
\end{verbatim}
rather than something like:
\begin{verbatim}
$sheep-dog.brain.task.monitor_flock;
\end{verbatim}
At a high level, we do not particularly care
what the internals of the object are. We only
care what the object can do.
An object becomes harder to change the
more its internals are exposed.
\subsubsection{Polymorphism}
\index{polymorphism}
\verb'$sheep-dog' and \verb'$shepherd-boy' both
understood the same commands, so replacing the
latter with the former was easier than it would
have been otherwise.
\index{tale about OOP}
\emph{The fable of this section is adapted
from a post by ``Arunbear'' on the ``Perlmonks''
website: \url{http://www.perlmonks.org/?node_id=1146129}.
Thanks to ``Arunbear'' for having authorized me
to reuse it.}
\section{Debugging}
\label{perl-debugger}
\index{debugger}
\index{debugger!using a}
This section is about using a debugger, a program that is
designed to help you to debug your programs. ``What? There
is a tool to debug my programs, and you're telling me only
now?'' you might complain. Well, it's not quite that. A debugger
is not going to do the debugging for you, you'll still have
to do the hard investigation work, but a debugger can help
you very much figuring out why your program isn't doing
what you think it should be doing. Or, rather, why what your
program is doing isn't quite what you want it to do.
Debuggers are a bit like persons with a strong personality:
some people love them and others hate them. Often, people
who don't like debuggers simply never took the time to learn
how to use them, but there are also many expert programmers
who don't like them and whom we can't suspect of not having
seriously tried. Whether you like debuggers or not is
probably a matter of personal taste, but they can provide an
invaluable help, if you know how to use them.
\subsection{The Perl~6 debugger}
\index{debugger!the Perl~6 debugger}
\index{debugger!launching the}
\index{debugging!using a debugger}
\index{debugging!the Perl 6 debugger}
Rakudo-Perl~6 ships with an interactive debugger which
you call with the {\tt perl6-debug} command (or, on
some installs at least, {\tt perl6-debug-m}). You can
just fire this command, followed by the name of the program
to be debugged, just as you would normally use {\tt perl6} with
the name of a program to run the program. One word of
warning: you can run the debugger on a program only if
the program compiles with no error; a debugger is not
aimed as finding compile-time error, but only execution
or semantic errors.
Once you've launched the debugger, you will see something
like this:
\begin{verbatim}
>>> LOADING while_done.pl6
+ while_done.pl6 (1 - 3)
| while True {
| my $line = prompt "Enter something ('done' for exiting)\n";
| last if $line eq "done";
>
\end{verbatim}
\index{prompt}
This says that it is loading the \verb'while_done.pl6' program,
and displays the first lines of the program; the last line at
the bottom (``\verb">"'') is a prompt where you can enter some
commands. The program
is stopped at the first statement that actually does something
and waits for your input. The code line that is waiting to be
executed is highlighted in a different color.
\subsection{Getting some help}
\index{debugger!help}
The first command you probably want to issue is ``h'', which
will display the debugger help and return to the prompt.
Below, we have omitted most of the output for brevity:
\begin{verbatim}
> h
<enter> single step, stepping into any calls
s step to next statement, stepping over any calls
so step out of the current routine
[...]
q[uit] exit the debugger
>
\end{verbatim}
Take the time to issue that command and to read the
various possible instructions you can enter. We will
describe the most common ones. As you can see
above, just use ``q'' or ``quit'' to exit the debugger.
\subsection{Stepping through the code}
\index{debugger!running code step by step}
\index{debugger!stepping over subroutines}
\index{debugger!stepping out of subroutines}
The main characteristic of a debugger is that it
lets you run the program step
by step. Each time you hit the {\tt enter} key, the
program will move forward one step (e.g. one code line).
It will enter into any subroutine if the code line
is a subroutine call, but you can step over the
subroutine call by issuing the ``s''
command at the debugger prompt: this will run the subroutine
and bring you to the first code line after the subroutine
call (and any nested call of other subroutines) is over.
If you entered into a subroutine but are no longer
interested in stepping through it, just issue the ``so''
command to step out of it.
\index{debugger!accessing variables}
At any point through that process, you can look at the
content of variables or even call methods on them. To
view a variable, just type its name and then press
{\tt enter}:
\begin{verbatim}
> $line
"foo"
\end{verbatim}
You can also view an array or a hash, or use the index
or the key, for example \verb'@array[10]' or
\verb'%hash{"bar"}'), to visualize one specific item of
the array or the hash.
You may also use ``s'' (or ``say'') or ``p'' (or ``print'')
to evaluate and display an expression in the current scope.
\subsection{Stopping at the right place with breakpoints}
\index{breakpoint}
\index{debugger!breakpoint}
You might find it tedious to run through the program step
by step until you get to the interesting part. As it happens,
you can get there immediately using a \emph{breakpoint}. For
adding a breakpoint, you type ``{\tt bp add line}'', where
``{\tt line}''
is the line number where you want the program to stop running
and resume stepping line by line. Then you enter the ``r''
command and the program will run until it reaches one of the
breakpoints that you have set. The execution will also
stop if the program runs into an exception; in that case,
you can still access variables to try to figure out what went
wrong. If it does not hit a breakpoint or an exception, it
will run to the end.
You can view all breakpoints (``{\tt bp list}''), remove
one breakpoint (``{\tt bp rm line}''), or remove all breakpoints
(``{\tt bp rm all}''). You can also set a breakpoint in
another file (for example if you are using a module) by
using the following syntax: ``{\tt bp add file:line}'', where
``file'' is the file name.
\subsubsection{You're all set to start using the debugger}
You probably know enough by now to make good use of the Perl~6
debugger, step through your program and find out where it
does something that isn't what you intended. It wasn't so
much to learn, was it? Try it!
We'll cover a couple of additional goodies, though.
\subsection{Logging information with trace points}
\index{debugger!trace point}
It is possible to set trace points on specific lines of code
and variables (or expressions), with the command {\tt tp add
line \$var}. This will record the value of \verb'$var' each
time the programs hits the chosen line. Then you simply run
the program for a while and, at some point, you can visualize
how the variable changed over time, using the command
{\tt tp show}.
For example, we used it to log variable \verb'$rotated-word'
in the solution to the Caesar's cipher exercise
(see Subsection~\ref{sol_rotate}) for the
``ABCDabcd'' input string with a rotation of 25 letters;
the {\tt tp show} command displayed how the coded output
string was progressively populated letter by letter:
\index{Caesar cipher}
\begin{verbatim}
> tp show
>>> rotate.pl6:23
*
* Z
* ZA
* ZAC
* ZACB
* ZACBz
* ZACBza
* ZACBzab
\end{verbatim}
\subsection{Stepping through a regex match}
\label{regex-debugging}
\index{regex}
\index{regex!debugging}
\index{debugger!stepping through a regex}
The debugger can also provide useful information when the
code is trying to match a regex. For example, suppose we're
running under the debugger a program in which we have the
following code:
\begin{verbatim}
"foobar" ~~ /f.+b/;
\end{verbatim}
\index{backtracking}
If you run the regex step by step, color highlighting will show
atom by atom where it is in the regex and which part of the
string has been matched. (We can't show the color highlighting
here, but you should try it to see it.)
With the above regex, you'll see that
the regex engine tries to match the ``f'' of the pattern and that
it finds an ``f'' at the beginning of the string; next, you'll see
that the regex engines tries to match the ``.+'' subpattern and
that it matches the whole string; then, when the regex engine
tries to match the final ``b'' of the pattern, you'll see that
the regex engine backtracks and gives away the ``r'' and then the
``a''; finally, the regex engine succeeds with ``foob'.
\index{backtracking}
If you have difficulties understanding how regexes work or are
mystified by backtracking, just run the debugger on a few
regexes and observe what's going on step by step. You don't
even have to write a program, you can use it as a one-liner.
For example, to test the above regex as a one-liner under
Windows, just type the following command at the prompt:
\index{one-liner mode}
\begin{verbatim}
C:\Users\Laurent>perl6-debug-m -e "'foobar' ~~ /f.+b/;"
\end{verbatim}
As usual, change double quotes to single quotes and the other
way around if you are using a Unix-like platform.
Our final word on the debugger: remember you can always hit
``h'' to get help on the command you need.
\section{Glossary}
\begin{description}
\item[object:] An entity that encloses its state (attributes)
and its behavior (methods).
\index{object}
\item[class:] A programmer-defined type. A class definition
creates a new type object (a form of abstract definition) and
makes it possible to instantiate concrete objects representing
real data.
\index{class}
\index{programmer-defined type}
\index{type!programmer-defined}
\item[method:] A special kind of subroutine defined within a class or a role, that can be called using the dot notation syntax
\index{method}
\index{dot notation}
\item[type object:] An object that contains information about a
programmer-defined type. The type object can be used to create instances
of the type.
\index{type object}
\index{object!type}
\item[instance:] An object that belongs to a class and contains
real data.
\index{instance}
\item[instantiate:] To create a new object.
\index{instantiate}
\item[attribute:] A state property akin to a variable within
an OOP framework. An instance attribute is one of the named
values associated with an object. Class attributes are variables
associated with the whole class.
\index{attribute!instance}
\index{instance attribute}
\index{attribute!class}
\index{class!attribute}
\item[embedded object:] An object that is stored as an attribute
of another object.
\index{embedded object}
\index{object!embedded}
\item[object composition:] Using an object as part of the definition
of another object, especially using an object as an attribute of
another object.
\index{composition}
\index{object!composition}
\item[object diagram:] A diagram that shows objects, their
attributes, and the values of the attributes.
\index{object diagram}
\index{diagram!object}
\item[role:] A collection of methods quite similar to a class but
that is not designed to build objects. A role contains methods
that can be applied to a class or an object to add new behaviors
to them.
\index{role}
\item[polymorphic:] Pertaining to a function that can work with more
than one type.
\index{polymorphism}
\item[encapsulation:] The principle that the interface provided
by an object should not depend on its implementation, in particular
the representation of its attributes. This is also called
\emph{information hiding}.
\index{encapsulation}
\index{information hiding}
\item[inheritance:] The ability to define a new class that is a
modified version of a previously defined class.
\index{inheritance}
\item[parent class:] The class from which a child class inherits.
\index{parent class}
\item[child class:] A new class created by inheriting from an
existing class; also called a ``subclass''.
\index{child class}
\index{class!child}
\item[subclassing:] Creating a child class derived from an
existing parent class.
\index{subclass}
\item[override:] when the method of a parent class is
redefined in a child class, it is said to be overridden
within that child class.
\item[multiple inheritance:] A situation in which a child class
is derived and inherits from more than one parent class.
\item[delegation:] Defining a class or a role in which it is
possible to invoke methods belonging to another object.
\index{delegation}
\end{description}
|
theory padic_fields
imports padic_integers
begin
lemma(in padic_integers) Qp_nonzero_def:
assumes "a \<in> nonzero Q\<^sub>p"
shows "a \<in> carrier Q\<^sub>p"
"a \<noteq>\<zero>\<^bsub>Q\<^sub>p\<^esub>"
using assms nonzero_def apply force
using assms nonzero_def by fastforce
lemma(in padic_integers) Qp_is_field[simp]:
"field Q\<^sub>p"
by (simp add: Q\<^sub>p_def domain.fraction_field_is_field)
lemma(in padic_integers) Qp_is_domain[simp]:
"domain Q\<^sub>p"
using Qp_is_field
by (simp add: field_def)
(*choice function for numerator and denominator*)
definition(in padic_integers) denom where
"denom = domain.denom Z\<^sub>p"
definition(in padic_integers) numer where
"numer = domain.numer Z\<^sub>p"
definition(in padic_integers) frac where
"frac = domain.frac Z\<^sub>p"
(*Qp one isn't zero*)
lemma(in padic_integers) Qp_one_car:
"\<one>\<^bsub>Q\<^sub>p\<^esub> \<in> carrier Q\<^sub>p"
by (simp add: cring.cring_simprules(6) fieldE(1))
lemma(in padic_integers) Qp_one_notzero:
"\<one>\<^bsub>Q\<^sub>p\<^esub> \<noteq>\<zero>\<^bsub>Q\<^sub>p\<^esub>"
by (simp add: one_not_zero)
lemma(in padic_integers) Qp_one_nonzero:
"\<one>\<^bsub>Q\<^sub>p\<^esub> \<in> nonzero Q\<^sub>p"
by (simp add: Qp_one_car Qp_one_notzero nonzero_def)
(*name for the isomorphic copy of Zp living in Qp*)
abbreviation(in padic_integers) \<O>\<^sub>p where
"\<O>\<^sub>p \<equiv> \<iota> ` carrier Z\<^sub>p"
(*alternate definition of the map \<iota>:*)
lemma(in padic_integers) inc_def:
assumes "a \<in> carrier Z\<^sub>p"
shows "\<iota> a = frac a \<one>"
using frac_def Z\<^sub>p_def Q\<^sub>p_def domain.inc_equation
Zp_is_domain \<iota>_def assms by fastforce
(*Properties of \<iota> :*)
lemma( in padic_integers) inc_of_nonzero:
assumes "a \<in> nonzero Z\<^sub>p"
shows "\<iota> a \<in> nonzero Q\<^sub>p"
using Q\<^sub>p_def Zp_is_domain \<iota>_def assms domain.Frac_def
domain.eq_obj_rng_of_frac_nonzero domain.inc_def
domain.units_of_fraction_field eq_obj_rng_of_frac.one_over
nonzero_def
by (smt Zp_one_nonzero domain.frac_im domain.inc_inj1
local.frac_def local.inc_def mem_Collect_eq)
lemma(in padic_integers) inc_of_one:
"\<iota> \<one> = \<one>\<^bsub>Q\<^sub>p\<^esub>"
by (simp add: Q\<^sub>p_def Zp_one_car Zp_one_nonzero \<iota>_def domain.frac_one domain.inc_equation)
lemma(in padic_integers) inc_of_sum:
assumes "a \<in> carrier Z\<^sub>p"
assumes "b \<in> carrier Z\<^sub>p"
shows "\<iota> (a \<oplus> b) = (\<iota> a) \<oplus>\<^bsub>Q\<^sub>p\<^esub> (\<iota> b)"
by (simp add: Q\<^sub>p_def Zp_one_nonzero \<iota>_def assms(1) assms(2) cring.cring_simprules(1)
domain.axioms(1) domain.frac_add_common_denom domain.inc_equation)
lemma(in padic_integers) inc_of_prod:
assumes "a \<in> carrier Z\<^sub>p"
assumes "b \<in> carrier Z\<^sub>p"
shows "\<iota> (a \<otimes> b) = (\<iota> a) \<otimes>\<^bsub>Q\<^sub>p\<^esub> (\<iota> b)"
using Localization.submonoid.one_closed Q\<^sub>p_def Zp_is_domain
assms(1) assms(2) cring.cring_simprules(5) domain.axioms(1)
domain.i_mult domain.inc_equation domain.nonzero_is_submonoid
local.frac_def local.inc_def
by metis
lemma(in padic_integers) inc_pow:
assumes "a \<in> nonzero Z\<^sub>p"
shows "\<iota> (a[^](n::nat)) = (\<iota> a)[^]\<^bsub>Q\<^sub>p\<^esub> n"
proof(induction n)
case 0
have P0: "(a[^](0::nat)) = \<one>"
by (simp add: assms domain.pow_0)
have P1: "(\<iota> a) \<in> nonzero Q\<^sub>p"
by (simp add: assms inc_of_nonzero)
have QD: "domain Q\<^sub>p"
by (simp add: field.axioms(1))
have P2: "(\<iota> a)[^]\<^bsub>Q\<^sub>p\<^esub> (0::nat) = \<one>\<^bsub>Q\<^sub>p\<^esub>"
using QD P1 by (simp add: domain.pow_0)
then show ?case
by (simp add: P0 inc_of_one)
next
case (Suc n)
fix n::nat
have QD: "domain Q\<^sub>p"
by (simp add: field.axioms(1))
have A: "a \<in> carrier Z\<^sub>p"
using assms nonzero_def Zp_nonzero_def(1) by presburger
have An: "(a[^]n) \<in> carrier Z\<^sub>p"
using Zp_nat_pow_nonzero Zp_nonzero_def(1) assms by blast
have iA: "\<iota> a \<in> carrier Q\<^sub>p"
by (simp add: Qp_nonzero_def(1) assms inc_of_nonzero)
have iAn: "\<iota> (a[^]n) \<in> carrier Q\<^sub>p"
using Qp_nonzero_def(1) Zp_nat_pow_nonzero assms inc_of_nonzero
by blast
assume "\<iota> (a[^]n) = (\<iota> a)[^]\<^bsub>Q\<^sub>p\<^esub> n"
have "(a[^](Suc n)) = (a\<otimes> (a[^]n))"
by (meson A Zp_is_domain domain.pow_suc)
then have "\<iota> (a[^](Suc n)) = (\<iota> (a\<otimes> (a[^]n)))"
by simp
then have "\<iota> (a[^](Suc n)) = (\<iota> a) \<otimes>\<^bsub>Q\<^sub>p\<^esub> (\<iota>(a[^]n))"
using inc_of_prod A An by blast
then have P: "\<iota> (a[^](Suc n)) = (\<iota> a) \<otimes>\<^bsub>Q\<^sub>p\<^esub> (\<iota> a)[^]\<^bsub>Q\<^sub>p\<^esub>n"
by (simp add: \<open>\<iota> (a [^] n) = \<iota> a [^]\<^bsub>Q\<^sub>p\<^esub> n\<close>)
have "\<iota> a [^]\<^bsub>Q\<^sub>p\<^esub> (Suc n) = (\<iota> a) \<otimes>\<^bsub>Q\<^sub>p\<^esub> (\<iota> a)[^]\<^bsub>Q\<^sub>p\<^esub>n"
by (meson Qp_is_domain domain.pow_suc iA)
then show "\<iota> (a[^](Suc n)) = \<iota> a [^]\<^bsub>Q\<^sub>p\<^esub> (Suc n)"
using P by blast
qed
lemma(in padic_integers) inc_of_diff:
assumes "a \<in> carrier Z\<^sub>p"
assumes "b \<in> carrier Z\<^sub>p"
shows "\<iota> (a \<ominus> b) = (\<iota> a) \<ominus>\<^bsub>Q\<^sub>p\<^esub> (\<iota> b)"
using assms unfolding a_minus_def
using inc_of_sum[of a "\<ominus> b"]
by (simp add: \<open>b \<in> carrier Z\<^sub>p\<close> Q\<^sub>p_def Zp_one_nonzero cring.cring_simprules(3)
domain.axioms(1) domain.frac_uminus local.frac_def local.inc_def)
lemma(in padic_integers) Units_nonzero_Qp[simp]:
assumes "u \<in> Units Q\<^sub>p"
shows "u \<in> nonzero Q\<^sub>p"
by (simp add: assms domain.Units_nonzero field.axioms(1))
lemma(in padic_integers) Units_inverse_Qp[simp]:
assumes "u \<in> Units Q\<^sub>p"
shows "inv\<^bsub>Q\<^sub>p\<^esub> u \<in> Units Q\<^sub>p"
by (simp add: assms domain.Units_inverse)
(*************************************************************************************************)
(*************************************************************************************************)
(************************************* FACTS FROM **************************************)
(************************************* fractionfield.thy **************************************)
(*************************************************************************************************)
(*************************************************************************************************)
lemma(in padic_integers) frac_add:
assumes "a \<in> carrier Z\<^sub>p"
assumes "b \<in> nonzero Z\<^sub>p"
assumes "c \<in> carrier Z\<^sub>p"
assumes "d \<in> nonzero Z\<^sub>p"
shows "(frac a b) \<oplus>\<^bsub>Q\<^sub>p\<^esub> (frac c d) = (frac ((a \<otimes> d) \<oplus> (b \<otimes> c)) (b \<otimes> d))"
by (simp add: Q\<^sub>p_def assms(1) assms(2) assms(3) assms(4) domain.frac_add local.frac_def)
lemma(in padic_integers) frac_add_common_denom:
assumes "a \<in> carrier Z\<^sub>p"
assumes "b \<in> carrier Z\<^sub>p"
assumes "c \<in> nonzero Z\<^sub>p"
shows "(frac a c) \<oplus>\<^bsub>Q\<^sub>p\<^esub> (frac b c) = frac (a \<oplus> b) c"
by (simp add: Q\<^sub>p_def assms(1) assms(2) assms(3) domain.frac_add_common_denom local.frac_def)
lemma(in padic_integers) frac_mult:
assumes "a \<in> carrier Z\<^sub>p"
assumes "b \<in> nonzero Z\<^sub>p"
assumes "c \<in> carrier Z\<^sub>p"
assumes "d \<in> nonzero Z\<^sub>p"
shows "(frac a b) \<otimes>\<^bsub>Q\<^sub>p\<^esub> (frac c d) = (frac (a \<otimes> c) (b \<otimes> d))"
by (simp add: Q\<^sub>p_def assms(1) assms(2) assms(3) assms(4) domain.frac_mult local.frac_def)
lemma(in padic_integers) frac_one:
assumes "a \<in> nonzero Z\<^sub>p"
shows "frac a a = \<one>\<^bsub>Q\<^sub>p\<^esub>"
by (simp add: Q\<^sub>p_def assms domain.frac_one local.frac_def)
lemma(in padic_integers) frac_closed:
assumes "a \<in> carrier Z\<^sub>p"
assumes "b \<in> nonzero Z\<^sub>p"
shows "frac a b \<in> carrier Q\<^sub>p"
by (simp add: Q\<^sub>p_def assms(1) assms(2) domain.frac_im local.frac_def)
lemma(in padic_integers) inv_in_frac:
assumes "a \<in> carrier Q\<^sub>p"
assumes "a \<noteq>\<zero>\<^bsub>Q\<^sub>p\<^esub>"
shows "inv\<^bsub>Q\<^sub>p\<^esub> a \<in> carrier Q\<^sub>p"
"inv\<^bsub>Q\<^sub>p\<^esub> a \<noteq>\<zero>\<^bsub>Q\<^sub>p\<^esub>"
"inv\<^bsub>Q\<^sub>p\<^esub> a \<in> nonzero Q\<^sub>p"
proof-
have "a \<in> Units Q\<^sub>p" using assms Units_def domain.units_of_fraction_field
using Diff_iff Q\<^sub>p_def Zp_is_domain by fastforce
then show 0:"inv\<^bsub>Q\<^sub>p\<^esub> a \<in> carrier Q\<^sub>p"
by (meson Qp_is_field cring_def fieldE(1) monoid.Units_inv_closed ring_def)
show 1: "inv\<^bsub>Q\<^sub>p\<^esub> a \<noteq>\<zero>\<^bsub>Q\<^sub>p\<^esub>"
by (metis Q\<^sub>p_def Qp_is_field Zp_is_domain assms(1) assms(2)
cring.cring_simprules(27) domain.one_not_zero
domain.units_of_fraction_field0(2) field.axioms(1) fieldE(1))
show "inv\<^bsub>Q\<^sub>p\<^esub> a \<in> nonzero Q\<^sub>p"
by (simp add: "0" "1" nonzero_def)
qed
lemma(in padic_integers) nonzero_numer_imp_nonzero_fraction:
assumes "a \<in> nonzero Z\<^sub>p"
assumes "b \<in> nonzero Z\<^sub>p"
shows "frac a b \<noteq> \<zero>\<^bsub>Q\<^sub>p\<^esub>"
by (simp add: Q\<^sub>p_def assms(1) assms(2) domain.nonzero_fraction local.frac_def)
lemma(in padic_integers) nonzero_fraction_imp_numer_not_zero:
assumes "a \<in> carrier Z\<^sub>p"
assumes "b \<in> nonzero Z\<^sub>p"
assumes "frac a b \<noteq> \<zero>\<^bsub>Q\<^sub>p\<^esub>"
shows "a \<noteq> \<zero>"
proof
assume "a = \<zero>"
then have "frac a b = frac \<zero> \<one>"
by (metis Q\<^sub>p_def Qp_is_field Zp_is_domain \<iota>_def assms(1) assms(2)
cring.cring_simprules(26) domain.axioms(1) domain.frac_im
domain.i_mult domain.nat_0 domain.nat_inc_rep field.axioms(1) local.frac_def local.inc_def)
then show False
by (metis Q\<^sub>p_def Qp_is_field Zp_is_domain assms(3)
domain.nat_0 domain.nat_inc_rep field.axioms(1) local.frac_def)
qed
lemma(in padic_integers) nonzero_fraction_imp_nonzero_numer:
assumes "a \<in> carrier Z\<^sub>p"
assumes "b \<in> nonzero Z\<^sub>p"
assumes "frac a b \<noteq> \<zero>\<^bsub>Q\<^sub>p\<^esub>"
shows "a \<in> nonzero Z\<^sub>p"
proof-
have "a \<noteq> \<zero>"
using assms(1) assms(2) assms(3) nonzero_fraction_imp_numer_not_zero
by blast
then show ?thesis
using assms(1) nonzero_def by (simp add: nonzero_def)
qed
lemma(in padic_integers) frac_inv:
assumes "a \<in> nonzero Z\<^sub>p"
assumes "b \<in> nonzero Z\<^sub>p"
shows "inv\<^bsub>Q\<^sub>p\<^esub> (frac a b) = (frac b a)"
by (simp add: Q\<^sub>p_def assms(1) assms(2) domain.frac_inv local.frac_def)
lemma(in padic_integers) frac_inv_id:
assumes "a \<in> nonzero Z\<^sub>p"
assumes "b \<in> nonzero Z\<^sub>p"
assumes "c \<in> nonzero Z\<^sub>p"
assumes "d \<in> nonzero Z\<^sub>p"
assumes "frac a b = frac c d"
shows "frac b a = frac d c"
using frac_inv assms by metis
lemma(in padic_integers) frac_uminus:
assumes "a \<in> carrier Z\<^sub>p"
assumes "b \<in> nonzero Z\<^sub>p"
shows "\<ominus>\<^bsub>Q\<^sub>p\<^esub> (frac a b) = frac (\<ominus> a) b"
by (simp add: Q\<^sub>p_def assms(1) assms(2) domain.frac_uminus local.frac_def)
lemma(in padic_integers) frac_cancel_l:
assumes "a \<in>nonzero Z\<^sub>p"
assumes "b \<in>nonzero Z\<^sub>p"
assumes "c \<in>carrier Z\<^sub>p"
shows "frac (a \<otimes>c) (a \<otimes>b) = frac c b"
by (simp add: assms(1) assms(2) assms(3) domain.frac_cancel_l local.frac_def)
lemma(in padic_integers) frac_cancel_r:
assumes "a \<in>nonzero Z\<^sub>p"
assumes "b \<in>nonzero Z\<^sub>p"
assumes "c \<in>carrier Z\<^sub>p"
shows "frac (c \<otimes>a) (b \<otimes>a) = frac c b"
by (simp add: assms(1) assms(2) assms(3) domain.frac_cancel_r local.frac_def)
lemma(in padic_integers) frac_cancel_lr:
assumes "a \<in>nonzero Z\<^sub>p"
assumes "b \<in>nonzero Z\<^sub>p"
assumes "c \<in>carrier Z\<^sub>p"
shows "frac (a \<otimes>c) (b \<otimes>a) = frac c b"
by (simp add: assms(1) assms(2) assms(3) domain.frac_cancel_lr local.frac_def)
lemma(in padic_integers) frac_cancel_rl:
assumes "a \<in>nonzero Z\<^sub>p"
assumes "b \<in>nonzero Z\<^sub>p"
assumes "c \<in>carrier Z\<^sub>p"
shows "frac (c \<otimes>a) (a \<otimes>b) = frac c b"
by (simp add: assms(1) assms(2) assms(3) domain.frac_cancel_rl local.frac_def)
lemma(in padic_integers) i_mult:
assumes "a \<in> carrier Z\<^sub>p"
assumes "c \<in> carrier Z\<^sub>p"
assumes "d \<in> nonzero Z\<^sub>p"
shows "(\<iota> a) \<otimes>\<^bsub>Q\<^sub>p\<^esub> (frac c d) = frac (a \<otimes> c) d"
by (simp add: Q\<^sub>p_def \<iota>_def assms(1) assms(2) assms(3) domain.i_mult local.frac_def)
lemma(in padic_integers) numer_denom_facts:
assumes "a \<in> carrier Q\<^sub>p"
shows "(numer a) \<in> carrier Z\<^sub>p"
"(denom a) \<in> nonzero Z\<^sub>p"
"a \<noteq> \<zero>\<^bsub>Q\<^sub>p\<^esub> \<Longrightarrow> numer a \<noteq> \<zero> "
"a \<otimes>\<^bsub>Q\<^sub>p\<^esub> (\<iota> (denom a)) = \<iota> (numer a)"
"a = frac (numer a) (denom a)"
using Q\<^sub>p_def assms domain.numer_denom_facts(1) numer_def
apply force
using Q\<^sub>p_def assms denom_def domain.numer_denom_facts(2)
apply (metis Zp_is_domain)
using Q\<^sub>p_def assms domain.numer_denom_facts(3) numer_def
apply force
using Q\<^sub>p_def \<iota>_def assms denom_def domain.numer_denom_facts(4) numer_def
apply force
using Q\<^sub>p_def assms denom_def domain.numer_denom_facts(5) local.frac_def numer_def
by force
lemma(in padic_integers) get_common_denominator:
assumes "x \<in> carrier Q\<^sub>p"
assumes "y \<in> carrier Q\<^sub>p"
obtains a b c where
"a \<in> carrier Z\<^sub>p"
"b \<in> carrier Z\<^sub>p"
"c \<in> nonzero Z\<^sub>p"
"x = frac a c"
"y = frac b c"
using Q\<^sub>p_def Zp_is_domain assms(1) assms(2) domain.common_denominator local.frac_def that
by metis
abbreviation(in padic_integers) fract :: "_ \<Rightarrow> _ \<Rightarrow> _" (infixl "\<div>" 50) where
"(fract a b) \<equiv> (a \<otimes>\<^bsub>Q\<^sub>p\<^esub> (inv\<^bsub>Q\<^sub>p\<^esub> b))"
(*fract generalizes frac*)
lemma(in padic_integers) fract_frac:
assumes "a \<in> carrier Z\<^sub>p"
assumes "b \<in> nonzero Z\<^sub>p"
shows "(frac a b) = (\<iota> a \<div> \<iota> b)"
proof-
have B: "b \<in> carrier Z\<^sub>p"
using assms(2) nonzero_def Zp_nonzero_def(1)
by presburger
have P0:"(inv\<^bsub>Q\<^sub>p\<^esub> (\<iota> b)) = frac \<one> b"
using B inc_def frac_inv Zp_one_nonzero assms(2)
by presburger
have P1: "(frac a b) = (\<iota> a) \<otimes>\<^bsub>Q\<^sub>p\<^esub> (frac \<one> b)"
by (metis B Localization.submonoid.one_closed Zp_is_domain assms(1)
assms(2) cring.cring_simprules(12) cring.cring_simprules(6)
domain.axioms(1) domain.nonzero_is_submonoid frac_cancel_rl i_mult)
show ?thesis
by (simp add: P0 P1)
qed
lemma(in padic_integers) frac_eq:
assumes "a \<in> nonzero Z\<^sub>p"
assumes "b \<in> nonzero Z\<^sub>p"
assumes "frac a b = \<one>\<^bsub>Q\<^sub>p\<^esub>"
shows "a = b"
proof-
have "frac a b = frac b b"
by (simp add: assms(2) assms(3) frac_one)
then have "frac a \<one> = frac b \<one>"
by (metis (no_types, lifting) Q\<^sub>p_def Qp_is_domain Z\<^sub>p_def
Zp_nonzero_def(1) Zp_one_nonzero assms(1) assms(2) assms(3)
cring.cring_simprules(11) cring.cring_simprules(12) cring.cring_simprules(14)
domain.axioms(1) fract_frac local.inc_def padic_integers.frac_closed
padic_integers.frac_inv padic_integers_axioms)
then show ?thesis
using Zp_is_domain Zp_nonzero_def(1) \<iota>_def assms(1) assms(2)
domain.inc_inj2 local.inc_def by metis
qed
lemma(in padic_integers) Qp_nat_pow_nonzero:
assumes "x \<in> nonzero Q\<^sub>p"
shows "x[^]\<^bsub>Q\<^sub>p\<^esub>(n::nat) \<in> nonzero Q\<^sub>p"
by (simp add: assms domain.nat_pow_nonzero)
lemma(in padic_integers) pow_p_frac_0:
assumes "(m::int) \<ge> n"
assumes "n \<ge>0"
shows "(frac (\<p>[^]m) (\<p>[^]n)) = \<iota> (\<p>[^](m-n))"
proof-
have 0: "\<p>\<in>carrier Z\<^sub>p"
by (simp add: Zp_nat_inc_closed)
have 1: "m - n \<ge>0"
using assms(1) by auto
have 2: "nat (m - n) + (nat n) = nat m"
using "1" assms(2) by linarith
have 3: "m \<ge>0"
using assms by auto
then have "(\<p>[^] (nat (m-n))) \<otimes> (\<p>[^](nat n)) = (\<p>[^] (nat m))"
using Zp_is_domain 0 1 2 3 monoid.nat_pow_mult
by (metis "0" Z\<^sub>p_def cring_def monoid.nat_pow_mult padic_int_is_cring prime ring_def)
then have "(\<p>[^] (m-n)) \<otimes> (\<p>[^]n) = (\<p>[^]m)"
using int_pow_int 1 3 assms(2) int_nat_eq by metis
then have P0: "(frac (\<p>[^]m) (\<p>[^]n)) = frac ((\<p>[^](m-n))\<otimes> (\<p>[^]n)) (\<p>[^]n)"
by simp
have "\<p> \<in>carrier Z\<^sub>p"
by (simp add: "0")
have "(\<p>[^](nat n)) = [(p^(nat n))] \<cdot> \<one>"
by (simp add: p_pow_rep0)
then have "(\<p>[^](nat n)) \<in> carrier Z\<^sub>p"
by (simp add: Zp_nat_inc_closed)
then have "(\<p>[^]n) \<in> carrier Z\<^sub>p"
using assms(2) by (metis int_nat_eq int_pow_int)
then have P1: "(frac (\<p>[^]m) (\<p>[^]n)) = frac ((\<p>[^](m-n))\<otimes> (\<p>[^]n)) ((\<one> \<otimes> (\<p>[^]n)))"
using Zp_is_domain P0
by (simp add: cring.cring_simprules(12) domain_def)
have P2: "(\<p>[^](m-n)) \<in> carrier Z\<^sub>p"
using "1" p_pow_car by blast
have P3: "(\<p>[^]n) \<in> carrier Z\<^sub>p"
using \<open>\<p> [^] n \<in> carrier Z\<^sub>p\<close> by blast
have P4: "(\<p>[^]n) \<in> nonzero Z\<^sub>p"
by (metis assms(2) int_eq_iff int_pow_int p_pow_nonzero)
have P5: "\<one> \<in> nonzero Z\<^sub>p"
using nonzero_def Zp_one_nonzero
by blast
have "(frac (\<p>[^](m-n)) \<one>) \<otimes>\<^bsub>Q\<^sub>p\<^esub> (frac (\<p>[^]n) (\<p>[^]n))
= frac ((\<p>[^](m-n))\<otimes> (\<p>[^]n)) ((\<one> \<otimes> (\<p>[^]n)))"
using Zp_is_domain P2 P4 P3 P5 frac_def Q\<^sub>p_def frac_mult
by blast
then have "frac ((\<p>[^](m-n))\<otimes> (\<p>[^]n)) ((\<one> \<otimes> (\<p>[^]n))) = (frac (\<p>[^](m-n)) \<one>) "
by (simp add: domain.frac_cancel_r P2 P4 P5 local.frac_def)
then have P6: "(frac (\<p>[^]m) (\<p>[^]n)) = (frac (\<p>[^](m-n)) \<one>) "
using P1 by blast
have "(frac (\<p>[^](m-n)) \<one>) = \<iota> (\<p>[^](m-n))"
using inc_def by (simp add: P2)
then show ?thesis
using P6 by blast
qed
lemma(in padic_integers) pow_p_frac:
assumes "(m::int) \<le> n"
assumes "m \<ge>0"
shows "(frac (\<p>[^]m) (\<p>[^]n)) = frac \<one> (\<p>[^](n-m))"
proof-
have "(frac (\<p>[^]n) (\<p>[^]m)) = \<iota> (\<p>[^](n-m))"
by (simp add: assms(1) assms(2) pow_p_frac_0)
then have P0:"(frac (\<p>[^]n) (\<p>[^]m)) = frac (\<p>[^](n-m)) \<one>"
by (simp add: assms(1) local.inc_def)
have P1: "\<one>\<in>nonzero Z\<^sub>p"
by (simp add: Zp_one_nonzero)
have P2: "\<p>[^]n \<in> nonzero Z\<^sub>p"
by (metis assms(1) assms(2) diff_ge_0_iff_ge diff_mono
eq_iff_diff_eq_0 int_eq_iff int_nat_eq int_pow_int p_pow_nonzero)
have P3: "\<p>[^]m \<in> nonzero Z\<^sub>p"
by (metis assms(2) int_eq_iff int_pow_int p_pow_nonzero)
have P4: "(\<p>[^](n-m)) \<in> nonzero Z\<^sub>p"
by (metis assms(1) diff_ge_0_iff_ge int_eq_iff
int_pow_int ord_Zp_def ord_Zp_p_pow ord_of_nonzero(2) p_pow_car)
show " frac (\<p>[^]m) (\<p>[^]n) = frac \<one> (\<p>[^](n-m))"
using P0 P1 P2 P3 P4 p_pow_nonzero domain.frac_inv_id frac_def Zp_is_domain
by (metis (mono_tags, lifting))
qed
(**********************************************************************************************************)
(*The copy of the prime p living in Q\<^sub>p*)
abbreviation(in padic_integers) \<pp> where
"\<pp> \<equiv> [p] \<cdot>\<^bsub>Q\<^sub>p\<^esub> \<one>\<^bsub>Q\<^sub>p\<^esub>"
abbreviation(in padic_integers) exp (infixl "e" 50) where
"exp a n \<equiv> a [^]\<^bsub>Q\<^sub>p\<^esub> n"
lemma(in padic_integers) p_inc:
"\<pp> = \<iota> \<p>"
proof-
have "\<pp> = frac \<p> \<one>"
by (simp add: domain.nat_inc_rep Q\<^sub>p_def local.frac_def)
then show ?thesis
by (simp add: local.inc_def Zp_nat_inc_closed)
qed
lemma(in padic_integers) p_nonzero[simp]:
"\<pp>\<in>nonzero Q\<^sub>p"
using Z\<^sub>p_def Zp_nat_inc_closed inc_of_nonzero ord_Zp_p p_inc
padic_integers.ord_of_nonzero(2) padic_integers_axioms
by auto
lemma(in padic_integers) p_natpow_inc:
fixes n::nat
shows "\<pp> e n = \<iota> (\<p> [^] n)"
by (metis Zp_nat_inc_closed inc_pow not_nonzero_Zp p_inc
p_pow_nonzero_0(2) p_pow_rep0 power_Suc0_right)
lemma(in padic_integers) p_intpow_inc:
fixes n::int
assumes "n \<ge>0"
shows "\<pp> e n = \<iota> (\<p> [^] n)"
using p_natpow_inc
by (metis assms int_nat_eq int_pow_int)
lemma(in padic_integers) p_intpow:
fixes n::int
assumes "n < 0"
shows "\<pp> e n = (frac \<one> (\<p> [^] (-n)))"
proof-
have U0: "(\<pp> e (nat (-n))) \<in> Units Q\<^sub>p" using Qp_is_field
by (metis Diff_iff Localization.submonoid.one_closed Q\<^sub>p_def Z\<^sub>p_def
Zp_is_domain \<iota>_def domain.frac_im domain.inc_inj1 domain.nonzero_is_submonoid
domain.units_of_fraction_field local.frac_def local.inc_def
padic_integers.p_natpow_inc p_pow_nonzero_0(1)
padic_integers.p_pow_nonzero_0(2) padic_integers_axioms singletonD)
have E0: "(\<pp> e (nat (-n))) = (\<pp> e (-n))"
using assms by (simp add: int_pow_def nat_pow_def)
then have U1: "(\<pp> e (-n)) \<in> Units Q\<^sub>p" using U0
by simp
have "(\<pp> e n) = inv \<^bsub>Q\<^sub>p\<^esub> (\<pp> e (nat (-n)))"
using assms by (simp add: int_pow_def nat_pow_def)
then have "(\<pp> e n) = inv \<^bsub>Q\<^sub>p\<^esub> (\<pp> e (-n))"
using E0 by simp
then have "(\<pp> e n) = inv \<^bsub>Q\<^sub>p\<^esub> \<iota> (\<p> [^](-n))"
using assms p_intpow_inc by auto
then have E1: "(\<pp> e n) = inv \<^bsub>Q\<^sub>p\<^esub> frac (\<p> [^](-n)) \<one>"
using assms local.inc_def p_pow_car by auto
have A: "(\<p> [^](-n)) \<in> nonzero Z\<^sub>p"
using assms p_pow_nonzero
by (metis (mono_tags) add.inverse_inverse diff_0
int.lless_eq int_nat_eq int_pow_int neg_0_le_iff_le )
then show ?thesis using A frac_inv inc_def
using E1 Zp_one_nonzero
by blast
qed
lemma(in padic_integers) p_natpow_closed[simp]:
fixes n::nat
shows "(\<pp> e n) \<in> (carrier Q\<^sub>p)"
"(\<pp> e n) \<in> (nonzero Q\<^sub>p)"
using Qp_nat_pow_nonzero Qp_nonzero_def(1) p_nonzero
apply blast
using Qp_nat_pow_nonzero p_nonzero by blast
lemma(in padic_integers) Zp_is_subring:
"subring \<O>\<^sub>p Q\<^sub>p"
by (simp add: Q\<^sub>p_def \<iota>_def domain.inc_im_is_subring)
lemma(in padic_integers) p_pow_diff:
fixes n::int
fixes m::int
assumes "n \<ge>0"
assumes "m \<ge>0"
shows "\<pp> e (n - m) = frac (\<p>[^] n) (\<p>[^]m)"
proof-
have 0: "comm_monoid Q\<^sub>p"
using Qp_is_domain cring_def domain_def by blast
have 1: "\<pp> \<in> Units Q\<^sub>p"
by (metis Qp_is_domain Qp_is_field Qp_nonzero_def(1) Qp_nonzero_def(2) field.field_inv(2)
inv_in_frac(1) is_UnitI(1) p_nonzero)
have 2: "\<pp> e (n - m) = (\<pp> e n) \<otimes>\<^bsub>Q\<^sub>p\<^esub> (\<pp> e -m)"
using int_pow_add[of Q\<^sub>p \<pp> n "-m"]
by (simp add: "0" "1")
have 3: "\<pp> e (n - m) = (\<pp> e n) \<otimes>\<^bsub>Q\<^sub>p\<^esub> inv\<^bsub>Q\<^sub>p\<^esub>(\<pp> e m)"
using 0 2
by (simp add: "1" int_pow_inv')
then show ?thesis using assms
using fract_frac p_int_pow_nonzero p_intpow_inc p_pow_car by presburger
qed
lemma(in padic_integers) Qp_is_comm_monoid[simp]:
"comm_monoid Q\<^sub>p"
using Qp_is_domain cring_def domain_def by blast
lemma(in padic_integers) Qp_Units_nonzero:
"(a \<in> (Units Q\<^sub>p)) \<longleftrightarrow> (a \<in> ( nonzero Q\<^sub>p))"
unfolding nonzero_def using Qp_is_field
by (simp add: Q\<^sub>p_def domain.units_of_fraction_field)
lemma(in padic_integers) Qp_int_pow_add:
fixes n::int
fixes m::int
assumes "a \<in> nonzero Q\<^sub>p"
shows "a [^]\<^bsub>Q\<^sub>p\<^esub> (n + m) = (a [^]\<^bsub>Q\<^sub>p\<^esub> n) \<otimes>\<^bsub>Q\<^sub>p\<^esub> (a [^]\<^bsub>Q\<^sub>p\<^esub> m)"
using int_pow_add[of Q\<^sub>p a n m] Qp_Units_nonzero Qp_is_comm_monoid assms
by blast
lemma(in padic_integers) p_intpow_closed[simp]:
fixes n::int
shows "(\<pp> e n) \<in> (carrier Q\<^sub>p)"
"(\<pp> e n) \<in> (nonzero Q\<^sub>p)"
apply (meson Qp_Units_nonzero Qp_is_comm_monoid Qp_nonzero_def(1) int_pow_unit_closed p_nonzero)
by (meson Qp_Units_nonzero Qp_is_comm_monoid int_pow_unit_closed p_nonzero)
lemma (in padic_integers) p_intpow_add:
fixes n::int
fixes m::int
shows "\<pp> [^]\<^bsub>Q\<^sub>p\<^esub> (n + m) = (\<pp> [^]\<^bsub>Q\<^sub>p\<^esub> n) \<otimes>\<^bsub>Q\<^sub>p\<^esub> (\<pp> [^]\<^bsub>Q\<^sub>p\<^esub> m)"
by (meson Qp_Units_nonzero Qp_is_comm_monoid int_pow_add p_nonzero)
lemma (in padic_integers) p_intpow_inv:
fixes n::int
shows "(\<pp> [^]\<^bsub>Q\<^sub>p\<^esub> n) \<otimes>\<^bsub>Q\<^sub>p\<^esub> (\<pp> [^]\<^bsub>Q\<^sub>p\<^esub> -n) = \<one>\<^bsub>Q\<^sub>p\<^esub>"
by (simp add: Qp_Units_nonzero int_pow_inv')
lemma (in padic_integers) p_intpow_inv':
fixes n::int
shows "(\<pp> [^]\<^bsub>Q\<^sub>p\<^esub> -n) \<otimes>\<^bsub>Q\<^sub>p\<^esub> (\<pp> [^]\<^bsub>Q\<^sub>p\<^esub> n) = \<one>\<^bsub>Q\<^sub>p\<^esub>"
by (simp add: Qp_Units_nonzero Qp_nonzero_def(2) field.field_inv(1) int_pow_inv')
lemma (in padic_integers) p_intpow_inv'':
fixes n::int
shows "(\<pp> [^]\<^bsub>Q\<^sub>p\<^esub> -n) = inv\<^bsub>Q\<^sub>p\<^esub> (\<pp> [^]\<^bsub>Q\<^sub>p\<^esub> n)"
by (metis Qp_is_comm_monoid comm_monoid.comm_inv_char p_intpow_closed(1) p_intpow_inv)
(*************************************************************************************************)
(*************************************************************************************************)
(************************************* THE VALUATION ON Qp **************************************)
(*************************************************************************************************)
(*************************************************************************************************)
definition(in padic_integers) ord where
"ord x = (ord_Zp (numer x)) - (ord_Zp (denom x))"
definition(in padic_integers) val where
"val x = (if (x = \<zero>\<^bsub>Q\<^sub>p\<^esub>) then \<infinity>\<^bsub>G\<^esub> else (Some (ord x)))"
lemma(in padic_integers) val_ord[simp]:
assumes "a \<in> nonzero Q\<^sub>p"
shows "val a = *ord a*"
using assms nonzero_def val_def by force
(**************************************************************************************************)
(**************************************************************************************************)
(********************************* ************************************)
(********************************* PROPERTIES OF VAL AND ORD ************************************)
(********************************* ************************************)
(**************************************************************************************************)
(**************************************************************************************************)
lemma(in padic_integers) ord_of_frac:
assumes "a \<in> nonzero Z\<^sub>p"
assumes "b \<in> nonzero Z\<^sub>p"
shows "ord (frac a b) = (ord_Zp a) - (ord_Zp b)"
proof-
have "frac a b = frac (numer (frac a b)) (denom (frac a b))"
using Q\<^sub>p_def Zp_is_domain assms(1) assms(2) domain.frac_im
local.frac_def Zp_nonzero_def(1) numer_denom_facts(5)
by metis
then have "a \<otimes> (denom (frac a b)) = b \<otimes> (numer (frac a b))"
by (metis Zp_is_domain Zp_nonzero_def(1) assms(1) assms(2) domain.frac_eq
frac_closed local.frac_def numer_denom_facts(1) numer_denom_facts(2))
then have "(ord_Zp a) - (ord_Zp b) = (ord_Zp (numer (frac a b))) - (ord_Zp (denom (frac a b)))"
using ord_Zp_eq_frac
by (metis Q\<^sub>p_def Z\<^sub>p_def Zp_is_domain assms(1) assms(2) domain.frac_im domain.nonzero_fraction
local.frac_def Zp_nonzero_def(1) numer_denom_facts(1) numer_denom_facts(3) ord_of_nonzero(2)
ord_pos padic_integers.numer_denom_facts(2) padic_integers_axioms)
then show ?thesis
using ord_def
by presburger
qed
lemma(in padic_integers) val_zero:
"val (\<zero>\<^bsub>Q\<^sub>p\<^esub>) = \<infinity>\<^bsub>G\<^esub>" by (simp add: val_def)
lemma(in padic_integers) ord_one[simp]:
"ord (\<one>\<^bsub>Q\<^sub>p\<^esub>) = 0"
using ord_of_frac[of \<one> \<one>] frac_one[of \<one>] Zp_one_nonzero
by (metis (mono_tags, hide_lams) diff_self local.frac_def)
lemma(in padic_integers) val_one[simp]:
"val (\<one>\<^bsub>Q\<^sub>p\<^esub>) = \<zero>\<^bsub>G\<^esub>"
using ord_one by (simp add: gzero_id one_not_zero val_def)
lemma(in padic_integers) val_of_frac:
assumes "a \<in> carrier Z\<^sub>p"
assumes "b \<in> nonzero Z\<^sub>p"
shows "val (frac a b) = (val_Zp a) \<ominus>\<^bsub>G\<^esub> (val_Zp b)"
proof(cases "a = \<zero>")
case True
then show ?thesis
using G_mult(1) assms(1) assms(2) local.val_zero Zp_nonzero_def(2) val_Zp_def
nonzero_fraction_imp_numer_not_zero by metis
next
case False
then have "a \<in> nonzero Z\<^sub>p"
by (simp add: assms(1) nonzero_def)
then show ?thesis using ord_of_frac
using assms(2) gminus_minus Zp_nonzero_def(1) Zp_nonzero_def(2) val_def val_ord_Zp
by (metis nonzero_numer_imp_nonzero_fraction)
qed
lemma(in padic_integers) Zp_division_Qp_0[simp]:
assumes "u \<in> Units Z\<^sub>p"
assumes "v \<in> Units Z\<^sub>p"
shows "frac (u \<otimes> (inv\<^bsub>Z\<^sub>p\<^esub> v)) \<one> = frac u v"
proof-
have 0: "frac v v = \<one>\<^bsub>Q\<^sub>p\<^esub>"
using frac_one
by (meson Units_nonzero_Zp assms(2))
have 1:"(inv\<^bsub>Z\<^sub>p\<^esub> v) \<in> carrier Z\<^sub>p"
using assms Zp_is_domain by (metis cring_def domain_def monoid.Units_inv_closed ring_def)
have 2:"frac (u \<otimes> (inv\<^bsub>Z\<^sub>p\<^esub> v)) \<one> \<in> carrier Q\<^sub>p"
using 1 assms Units_nonzero_Zp Zp_is_domain cring.cring_simprules(5)
domain.axioms(1) frac_closed Zp_nonzero_def(1) Zp_one_nonzero
by (metis (mono_tags, hide_lams) local.frac_def )
have 3: "frac (u \<otimes> (inv\<^bsub>Z\<^sub>p\<^esub> v)) \<one> = (frac (u \<otimes> (inv\<^bsub>Z\<^sub>p\<^esub> v)) \<one>) \<otimes>\<^bsub>Q\<^sub>p\<^esub> frac v v"
using Qp_is_field 0 2
by (metis "1" Units_nonzero_Zp Zp_is_domain assms(1) cring.cring_simprules(5)
domain.axioms(1) frac_inv fract_frac inc_of_one local.inc_def
Zp_nonzero_def(1) Zp_one_nonzero)
then have 4: "frac (u \<otimes> (inv\<^bsub>Z\<^sub>p\<^esub> v)) \<one> = (frac ((u \<otimes> (inv\<^bsub>Z\<^sub>p\<^esub> v)) \<otimes> v) v)"
by (metis "1" Units_nonzero_Zp Zp_is_domain assms(1) assms(2)
cring.cring_simprules(5) domain.axioms(1) i_mult local.inc_def Zp_nonzero_def(1))
then have 4: "frac (u \<otimes> (inv\<^bsub>Z\<^sub>p\<^esub> v)) \<one> = (frac (u \<otimes> ((inv\<^bsub>Z\<^sub>p\<^esub> v) \<otimes> v)) v)"
by (simp add: "1" assms(1) assms(2) cring.cring_simprules(11)
domain.axioms(1) Zp_nonzero_def(1))
have 5:"(inv\<^bsub>Z\<^sub>p\<^esub> v) \<otimes> v = \<one>"
by (meson Zp_is_domain assms(2) cring_def domain_def monoid.Units_l_inv ring_def)
then show "frac (u \<otimes> (inv\<^bsub>Z\<^sub>p\<^esub> v)) \<one> = (frac u v)"
using 4
by (metis "1" Units_nonzero_Zp Zp_is_domain Zp_nonzero_def(1) Zp_one_notzero
assms(1) assms(2) domain.integral_iff frac_cancel_rl not_nonzero_Zp)
qed
lemma(in padic_integers) Zp_division_Qp_1:
assumes "u \<in> Units Z\<^sub>p"
assumes "v \<in> Units Z\<^sub>p"
obtains w where "w \<in> Units Z\<^sub>p"
"\<iota> w = frac u v"
proof-
have " (inv\<^bsub>Z\<^sub>p\<^esub> v) \<in> Units Z\<^sub>p"
using Zp_is_domain domain_def cring_def ring_def assms(2) Units_inverse_Zp
by blast
then have "(u \<otimes> (inv\<^bsub>Z\<^sub>p\<^esub> v)) \<in> Units Z\<^sub>p"
using assms Zp_is_domain
by (metis Units_closed)
then show ?thesis using Zp_division_Qp_0
by (metis (mono_tags, hide_lams) Zp_is_domain \<iota>_def assms(1) assms(2)
cring_def domain.axioms(1) domain.inc_equation local.frac_def
monoid.Units_closed ring_def that)
qed
(*Showing that the image of Zp in Qp is a valuation ring*)
lemma(in padic_integers) Zp_ord_criterion[simp]:
assumes "a \<in> carrier Q\<^sub>p"
assumes "a \<noteq> \<zero>\<^bsub>Q\<^sub>p\<^esub>"
assumes "ord a \<ge> 0"
shows "a \<in> \<O>\<^sub>p"
proof-
obtain c d where P0: "a = frac c d" and P1: "c \<in> nonzero Z\<^sub>p" and P2: "d \<in> nonzero Z\<^sub>p"
using Q\<^sub>p_def Zp_is_domain assms(1) domain.numer_denom_facts(1)
domain.numer_denom_facts(2) domain.numer_denom_facts(5) local.frac_def
by (metis assms(2) domain.numer_denom_facts(3) ord_of_nonzero(2) ord_pos)
obtain m n where P3: "m = ord_Zp c" and P4:"n = ord_Zp d"
by metis
obtain u where "u = ac_Zp c"
by simp
have P5:"c = (\<p>[^]m) \<otimes> u" and P6:"u \<in> Units Z\<^sub>p"
apply (metis P1 P3 \<open>u = ac_Zp c\<close> ac_Zp_factors_x int_pow_int Zp_nonzero_def(1) Zp_nonzero_def(2) ord_nat)
using P1 Zp_nonzero_def(1) Zp_nonzero_def(2) \<open>u = ac_Zp c\<close> ac_Zp_is_Unit
by blast
obtain v where "v = ac_Zp d" by simp
have P7:"d = (\<p>[^]n) \<otimes> v" and P8:"v \<in> Units Z\<^sub>p"
apply (metis P2 P4 \<open>v = ac_Zp d\<close> ac_Zp_factors_x int_pow_int Zp_nonzero_def(1) Zp_nonzero_def(2) ord_nat)
using P2 Zp_nonzero_def(1) Zp_nonzero_def(2) \<open>v = ac_Zp d\<close> ac_Zp_is_Unit by blast
have P9: "a = frac ((\<p>[^]m) \<otimes> u) ((\<p>[^]n) \<otimes> v)"
by (simp add: P0 P5 P7)
have P10: "(\<p>[^]m) \<in> carrier Z\<^sub>p"
using P1 P3 Z\<^sub>p_def ord_pos Zp_nonzero_def padic_integers.p_pow_car padic_integers_axioms by blast
have P11: "(\<p>[^]n) \<in> nonzero Z\<^sub>p"
by (metis P2 P4 int_nat_eq int_pow_int ord_Zp_def ord_pos Zp_nonzero_def p_pow_nonzero)
have P12: "u \<in> carrier Z\<^sub>p"
using P6 Units_def Units_nonzero_Zp Zp_nonzero_def(1)
by presburger
have P13: "v \<in> nonzero Z\<^sub>p"
using P8 Units_def ord_of_nonzero(2) unit_imp_ord_Zp0
by (simp add: Units_def)
have P14: "a = (frac (\<p>[^]m) (\<p>[^]n)) \<otimes>\<^bsub>Q\<^sub>p\<^esub> (frac u v)"
using P12 P13 P10 P9 P11 Q\<^sub>p_def frac_def frac_mult by metis
have P15: "m \<ge> n"
proof-
have "ord_Zp c \<ge> ord_Zp d"
using P0 P1 P2 assms(3) ord_of_frac[of c d]
by (metis P3 P4 antisym eq_iff eq_iff_diff_eq_0 le_cases le_iff_diff_le_0 ord_Zp_def)
then show ?thesis
using P3 P4 by blast
qed
have P16: "n \<ge> 0"
using P2 P4 Z\<^sub>p_def padic_integers_axioms Zp_nonzero_def(1) Zp_nonzero_def(2) ord_pos by blast
have P17: "a = (frac (\<p>[^](m-n)) \<one>) \<otimes>\<^bsub>Q\<^sub>p\<^esub> (frac u v)"
by (simp add: P14 P15 P16 local.inc_def pow_p_frac_0)
obtain w where P18: "w \<in> Units Z\<^sub>p" and P19: "\<iota> w = frac u v "
using Zp_division_Qp_1 P6 P8 by blast
have P20: "w \<in> carrier Z\<^sub>p"
using P18 Units_def Units_nonzero_Zp Zp_nonzero_def(1)
by presburger
have P21: "a = \<iota> (\<p>[^](m-n)) \<otimes>\<^bsub>Q\<^sub>p\<^esub> \<iota> w"
by (simp add: P15 P17 P19 local.inc_def)
have P22: "a = (frac (\<p>[^](m-n)) \<one>) \<otimes>\<^bsub>Q\<^sub>p\<^esub> (frac w \<one>)"
using P17 P19 P20 local.inc_def by auto
have P23: "\<p>[^](m-n) \<in> carrier Z\<^sub>p"
by (simp add: P15)
have P24: "a = (frac ((\<p>[^](m-n)) \<otimes> w) \<one>)"
using P20 P22 P23 frac_mult Zp_is_domain
by (metis Zp_one_nonzero i_mult local.inc_def)
have P24: "a = \<iota>((\<p>[^](m-n)) \<otimes> w)"
by (simp add: P20 P23 P24 cring.cring_simprules(5) domain.axioms(1) local.inc_def)
then show ?thesis
by (meson P20 P23 Zp_is_domain cring.cring_simprules(5) domain.axioms(1) image_iff)
qed
lemma(in padic_integers) ord_of_inv:
assumes "a \<in> carrier Q\<^sub>p"
assumes "a \<noteq> \<zero>\<^bsub>Q\<^sub>p\<^esub>"
shows "ord (inv\<^bsub>Q\<^sub>p\<^esub> a) = - (ord a)"
proof-
obtain b c where
Frac: "a = frac b c" and
Car: "b \<in> carrier Z\<^sub>p" and
Nz_c: "c \<in> nonzero Z\<^sub>p"
using Q\<^sub>p_def Zp_is_domain assms(1) domain.numer_denom_facts(1)
domain.numer_denom_facts(2) domain.numer_denom_facts(5)
local.frac_def
by metis
have Nz_b: "b \<in> nonzero Z\<^sub>p"
using Frac Car Nz_c assms(2) nonzero_fraction_imp_nonzero_numer by metis
then have "(inv\<^bsub>Q\<^sub>p\<^esub> a) = frac c b"
using Frac Nz_c frac_inv by metis
then show ?thesis using Frac Nz_b Nz_c ord_of_frac[of b c] ord_of_frac[of c b]
by (simp add: nonzero_def ord_Zp_def)
qed
lemma(in padic_integers) val_of_inv:
assumes "a \<in> carrier Q\<^sub>p"
assumes "a \<noteq> \<zero>\<^bsub>Q\<^sub>p\<^esub>"
shows "val (inv\<^bsub>Q\<^sub>p\<^esub> a) = neg (val a)"
by (simp add: assms(1) assms(2) g_uminus_minus inv_in_frac(2) ord_of_inv val_def)
(*Zp is a valuation ring in Qp*)
lemma(in padic_integers) Zp_mem:
assumes "a \<in> carrier Q\<^sub>p"
shows "a \<in> \<O>\<^sub>p \<or> (inv\<^bsub>Q\<^sub>p\<^esub> a \<in> \<O>\<^sub>p)"
proof(cases "inv\<^bsub>Q\<^sub>p\<^esub>a \<in> \<O>\<^sub>p \<or> a = \<zero>\<^bsub>Q\<^sub>p\<^esub>")
case True
then show ?thesis
using Zp_is_subring subringE(2) by auto
next
case False
then have Nz: "a \<noteq> \<zero>\<^bsub>Q\<^sub>p\<^esub>" by auto
have "\<not> (ord a < 0)"
proof
assume "ord a < 0"
then have "ord (inv\<^bsub>Q\<^sub>p\<^esub> a) >0"
by (simp add: assms(1) Nz ord_of_inv)
then have 0: "ord (inv\<^bsub>Q\<^sub>p\<^esub> a) \<ge>0"
by auto
have 1: "(inv\<^bsub>Q\<^sub>p\<^esub> a) \<in> carrier Q\<^sub>p"
by (simp add: assms(1) Nz inv_in_frac)
have 2: "(inv\<^bsub>Q\<^sub>p\<^esub> a) \<noteq>\<zero>\<^bsub>Q\<^sub>p\<^esub>"
by (simp add: assms(1) Nz inv_in_frac(2))
then have "(inv\<^bsub>Q\<^sub>p\<^esub> a) \<in> \<O>\<^sub>p"
using Zp_ord_criterion by (simp add: "0" "1")
then show False
using False by blast
qed
then show ?thesis
using Zp_ord_criterion assms(1) Nz by auto
qed
lemma(in padic_integers) Zp_val_criterion[simp]:
assumes "a \<in> carrier Q\<^sub>p"
assumes "val a \<succeq>\<^bsub>G\<^esub> \<zero>\<^bsub>G\<^esub>"
shows "a \<in> \<O>\<^sub>p"
proof(cases "a = \<zero>\<^bsub>Q\<^sub>p\<^esub>")
case True
then show ?thesis
by (simp add: Zp_is_subring subringE(2))
next
case False
have " 0 \<le> ord a"
using False assms(1) G_ord(2)[of 0 "ord a"] assms(2)
by (metis gzero_id val_def)
then show ?thesis
using False assms(1) Zp_ord_criterion[of a] by auto
qed
(*Criterion for determining when an element in Qp is zero*)
lemma (in padic_integers) val_nonzero[simp]:
assumes "a \<in> carrier Q\<^sub>p"
assumes "s \<succ>\<^bsub>G\<^esub> val a"
shows "a \<in> nonzero Q\<^sub>p"
proof-
have "val a \<noteq> \<infinity>\<^bsub>G\<^esub>"
by (metis assms(2) infinity_not_less)
then show ?thesis
using assms
by (metis (mono_tags, hide_lams) local.val_zero not_nonzero_Qp)
qed
(*function for division of a padic_integer by a power of n*)
definition(in padic_integers) divide where
"divide a b = (if a = \<zero> then \<zero> else (THE c. c \<in> carrier Z\<^sub>p \<and> \<iota> c = frac a b))"
lemma(in padic_integers) divide_id[simp]:
assumes "a \<in> nonzero Z\<^sub>p"
assumes "b \<in> nonzero Z\<^sub>p"
assumes "ord_Zp a \<ge> ord_Zp b"
shows "divide a b \<in> carrier Z\<^sub>p"
"(divide a b) \<otimes> b = a"
"ord_Zp (divide a b) = ord_Zp a - ord_Zp b"
proof-
have "(frac a b) \<in> \<O>\<^sub>p"
using frac_closed[of a b] assms ord_of_frac[of a b]
Zp_ord_criterion[of "frac a b"] Zp_nonzero_def(1)
nonzero_numer_imp_nonzero_fraction diff_ge_0_iff_ge local.frac_def
by (metis (mono_tags, hide_lams))
then obtain c where c_def: "c \<in> carrier Z\<^sub>p \<and> \<iota> c = frac a b"
by auto
obtain P where P_def: "P = (\<lambda>x. x \<in> carrier Z\<^sub>p \<and> \<iota> x = frac a b)"
by simp
have 0: "(THE x. P x) = c"
proof(rule the_equality)
show "P c" using P_def c_def by auto
show " \<And>x. P x \<Longrightarrow> x = c"
using P_def domain.inc_inj2[of Z\<^sub>p _ c] Zp_is_domain \<iota>_def c_def
by simp
qed
have 1: "c \<otimes> b = a"
proof-
have "frac (c \<otimes> b) a = (frac c \<one>) \<otimes>\<^bsub>Q\<^sub>p\<^esub> frac b a"
using assms c_def Zp_nonzero_def(1) i_mult local.inc_def by metis
then have "frac (c \<otimes> b) a = (frac a b) \<otimes>\<^bsub>Q\<^sub>p\<^esub> frac b a"
using c_def \<iota>_def local.inc_def by auto
then have "frac (c \<otimes> b) a = \<one>\<^bsub>Q\<^sub>p\<^esub>"
using assms(1) assms(2)
by (simp add: \<open>a \<in> nonzero Z\<^sub>p\<close> \<open>b \<in> nonzero Z\<^sub>p\<close> Zp_nonzero_def(1)
frac_cancel_lr frac_mult frac_one)
then show ?thesis using assms c_def
by (metis Qp_one_notzero Zp_is_domain Zp_nonzero_def(1) cring.cring_simprules(5)
domain.axioms(1) local.frac_eq nonzero_fraction_imp_nonzero_numer)
qed
have "a \<noteq>\<zero>"
by (simp add: assms(1) Zp_nonzero_def(2))
then have 2: "c = divide a b"
using 0 P_def divide_def[of a b] by auto
show "divide a b \<in> carrier Z\<^sub>p" using c_def 2 by auto
show "divide a b \<otimes> b = a" using 1 2 by auto
show "ord_Zp (divide a b) = ord_Zp a - ord_Zp b"
proof-
have "divide a b \<in> nonzero Z\<^sub>p"
using "1" "2" Zp_is_domain Zp_nonzero_def(1) \<open>a \<noteq> \<zero>\<close> assms(2)
c_def domain.integral_iff not_nonzero_Zp by metis
then have "ord_Zp (divide a b) + ord_Zp b = ord_Zp a"
by (metis "1" "2" assms(2) ord_Zp_mult)
then show ?thesis
by linarith
qed
qed
lemma(in padic_integers) divide_id'[simp]:
assumes "a \<in> carrier Z\<^sub>p"
assumes "b \<in> nonzero Z\<^sub>p"
assumes "val_Zp b \<preceq>\<^bsub>G\<^esub> val_Zp a"
shows "divide a b \<in> carrier Z\<^sub>p"
"(divide a b) \<otimes> b = a"
"val_Zp (divide a b) = val_Zp a \<ominus>\<^bsub>G\<^esub> val_Zp b"
proof-
show C0: "(divide a b) \<otimes> b = a"
proof(cases "a = \<zero>")
case True
have "divide a b = \<zero>"
by (simp add: True divide_def)
then show ?thesis
by (simp add: True Zp_nonzero_def(1) assms(2) cring.cring_simprules(26) domain.axioms(1))
next
case False
then have 0: "a \<in> nonzero Z\<^sub>p"
by (simp add: False assms(1) nonzero_def)
have 1: "ord_Zp b \<le> ord_Zp a" using 0 assms
by (metis G_ord(2) Zp_nonzero_def(2) ord_Zp_def val_Zp_def)
then show ?thesis using divide_id assms 0 1
by blast
qed
show C1: "divide a b \<in> carrier Z\<^sub>p"
proof(cases "a = \<zero>")
case True
then have "divide a b = \<zero>"
by (simp add: divide_def)
then show ?thesis
using True assms(1) by auto
next
case False
then have 0: "a \<in> nonzero Z\<^sub>p"
by (simp add: False assms(1) nonzero_def)
have 1: "ord_Zp b \<le> ord_Zp a" using 0 assms
by (metis G_ord(2) Zp_nonzero_def(2) ord_Zp_def val_Zp_def)
then show ?thesis using divide_id assms 0 1
by blast
qed
show C2: "val_Zp (divide a b) = val_Zp a \<ominus>\<^bsub>G\<^esub> val_Zp b"
proof-
have "(divide a b) \<otimes> b = a \<otimes> \<one>"
using Zp_is_domain Zp_one_car \<open>local.divide a b \<otimes> b = a\<close> assms(1)
cring.cring_simprules(12) cring.cring_simprules(14) domain.axioms(1)
by metis
then have "(val_Zp (divide a b)) \<ominus>\<^bsub>G\<^esub> (val_Zp \<one>) = (val_Zp a) \<ominus>\<^bsub>G\<^esub>(val_Zp b)"
using val_Zp_eq_frac_0
by (metis Zp_one_nonzero \<open>local.divide a b \<in> carrier Z\<^sub>p\<close> \<open>local.divide a b \<otimes> b = a\<close>
assms(1) assms(2) frac_cancel_r frac_cancel_rl val_of_frac)
then have 0: "(val_Zp (divide a b)) \<ominus>\<^bsub>G\<^esub> \<zero>\<^bsub>G\<^esub> = (val_Zp a) \<ominus>\<^bsub>G\<^esub>(val_Zp b)"
using Z\<^sub>p_def Zp_one_car Zp_one_notzero gzero_id ord_Zp_one
padic_integers.val_ord_Zp padic_integers_axioms
by fastforce
have "(val_Zp (divide a b)) \<ominus>\<^bsub>G\<^esub> \<zero>\<^bsub>G\<^esub> = (val_Zp (divide a b))"
proof(cases "(divide a b) = \<zero>")
case True
then show ?thesis
by (simp add: val_Zp_def)
next
case False
then show ?thesis
by (meson C1 gzero_simps(1) not_nonzero_Zp val_Zp_closed)
qed
then show ?thesis using 0
by metis
qed
qed
(*ord and val of negatives*)
lemma (in padic_integers) ord_minus:
assumes "a \<in> nonzero Q\<^sub>p"
shows "ord a = ord (\<ominus>\<^bsub>Q\<^sub>p\<^esub>a)"
proof-
have "\<ominus>\<^bsub>Q\<^sub>p\<^esub> a = \<ominus>\<^bsub>Q\<^sub>p\<^esub> (frac (numer a) (denom a))"
using assms Qp_nonzero_def(1) numer_denom_facts(5)
by presburger
then have "\<ominus>\<^bsub>Q\<^sub>p\<^esub> a = (frac (\<ominus> (numer a)) (denom a))"
using Qp_nonzero_def(1) assms frac_uminus numer_denom_facts(1) numer_denom_facts(2)
by blast
then show ?thesis
by (metis (no_types, lifting) Qp_is_domain Qp_nonzero_def(1) Zp_is_domain assms
cring.cring_simprules(21) cring.cring_simprules(22) cring.cring_simprules(3)
domain.axioms(1) nonzero_fraction_imp_nonzero_numer numer_denom_facts(1)
numer_denom_facts(2) ord_Zp_of_ominus ord_def ord_of_frac)
qed
lemma (in padic_integers) val_minus:
assumes "a \<in> carrier Q\<^sub>p"
shows "val a = val (\<ominus>\<^bsub>Q\<^sub>p\<^esub>a)"
proof(cases "a = \<zero>\<^bsub>Q\<^sub>p\<^esub>")
case True
then show ?thesis
by (metis Qp_is_domain cring.cring_simprules(22) domain.axioms(1))
next
case False
then show ?thesis
by (metis Qp_is_domain assms cring.cring_simprules(21)
cring.cring_simprules(22) domain.axioms(1) not_nonzero_Qp
ord_minus val_def)
qed
(*Ultrametric inequality on Qp*)
lemma(in padic_integers) ord_ultrametric[simp]:
assumes "x \<in> nonzero Q\<^sub>p"
assumes "y \<in> nonzero Q\<^sub>p"
assumes "x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y \<in> nonzero Q\<^sub>p"
shows "ord (x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y) \<ge> min (ord x) (ord y)"
proof-
have 0:"x \<in> carrier Q\<^sub>p" using assms by(simp add:nonzero_def)
have 1:"y \<in>carrier Q\<^sub>p" using assms by(simp add:nonzero_def)
obtain a b c where
A: "a \<in> carrier Z\<^sub>p" and
B: "b \<in> carrier Z\<^sub>p" and
C: "c \<in> nonzero Z\<^sub>p" and
Fx: "x = frac a c" and
Fy: "y = frac b c"
using 0 1 get_common_denominator by blast
have An: "a \<in> nonzero Z\<^sub>p"
using A C Fx assms(1) Qp_nonzero_def(2) nonzero_fraction_imp_nonzero_numer by metis
have Bn: " b \<in> nonzero Z\<^sub>p"
using B C Fy assms(2) Qp_nonzero_def(2) nonzero_fraction_imp_nonzero_numer by metis
have Fxy: "x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y = frac (a \<oplus> b) c" using 0 1
by (simp add: A B C Fx Fy frac_add_common_denom)
have ABn: " a \<oplus> b \<in> nonzero Z\<^sub>p"
proof-
have "a \<oplus> b \<in> carrier Z\<^sub>p"
using A B Z\<^sub>p_def padic_add_closed prime by blast
then show ?thesis
using Fxy C assms(3) Qp_nonzero_def(2) nonzero_fraction_imp_nonzero_numer
by (metis (mono_tags, hide_lams) local.frac_def not_nonzero_Zp)
qed
have Ordx: "ord x = ord_Zp a - ord_Zp c"
using Fx An C ord_of_frac by metis
have Ordy: "ord y = ord_Zp b - ord_Zp c"
using Fy Bn C ord_of_frac by metis
have Ordxy: "ord (x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y) = ord_Zp (a \<oplus> b) - ord_Zp c"
using Fxy ABn C ord_of_frac by metis
then show ?thesis
using Ordx Ordy Ordxy ord_Zp_ultrametric[of a b] ABn An Bn
by linarith
qed
lemma(in padic_integers) ord_ultrametric'[simp]:
assumes "x \<in> nonzero Q\<^sub>p"
assumes "y \<in> nonzero Q\<^sub>p"
assumes "x \<ominus> \<^bsub>Q\<^sub>p\<^esub> y \<in> nonzero Q\<^sub>p"
shows "ord (x \<ominus> \<^bsub>Q\<^sub>p\<^esub> y) \<ge> min (ord x) (ord y)"
proof-
have "ord y = ord (\<ominus>\<^bsub>Q\<^sub>p\<^esub>y)"
using assms(2) ord_minus by blast
then show ?thesis
using assms ord_ultrametric[of x "\<ominus>\<^bsub>Q\<^sub>p\<^esub>y"]
unfolding a_minus_def
by (smt Qp_is_domain Qp_nonzero_def(1) cring.cring_simprules(16)
cring.cring_simprules(3) domain.axioms(1) not_nonzero_Qp)
qed
lemma(in padic_integers) val_ultrametric0[simp]:
assumes "x \<in> nonzero Q\<^sub>p"
assumes "y \<in> nonzero Q\<^sub>p"
assumes "x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y \<in> nonzero Q\<^sub>p"
shows " Min\<^bsub>G\<^esub> (val x) (val y) \<preceq>\<^bsub>G\<^esub> val (x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y) "
proof-
have 0: "val (x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y) = *ord (x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y)*"
using assms(3) nonzero_def val_def[of "(x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y)"] by fastforce
have 1: "val x = *ord x*"
using assms(1) nonzero_def val_def by force
have 2: "val y = *ord y*"
using assms(2) nonzero_def val_def by force
have 3: "ord (x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y) \<ge> min (ord x) (ord y)"
by (simp add: assms(1) assms(2) assms(3) )
then show ?thesis
using Min_min[of "ord x" "ord y"]
G_ord(2)[of "min (ord x) (ord y)" "ord (x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y)"]
0 1 2 3
by presburger
qed
lemma(in padic_integers) val_ultrametric[simp]:
assumes "x \<in> carrier Q\<^sub>p"
assumes "y \<in> carrier Q\<^sub>p"
shows " Min\<^bsub>G\<^esub> (val x) (val y) \<preceq>\<^bsub>G\<^esub> val (x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y)"
proof(cases "x = \<zero>\<^bsub>Q\<^sub>p\<^esub> \<or> y = \<zero>\<^bsub>Q\<^sub>p\<^esub>")
case True
then show ?thesis
proof(cases "x = \<zero>\<^bsub>Q\<^sub>p\<^esub>")
case True
then have T0: "Min\<^bsub>G\<^esub> (val x) (val y) = (val y)"
by (simp add: G_def val_def)
have T1: "val (x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y) = val y"
using True Qp_is_field
by (metis Qp_is_domain assms(2) cring.cring_simprules(8) domain.axioms(1))
then show ?thesis
using T0 T1 G_def
by (metis (full_types) G_eq)
next
case False
then have F0:" Min\<^bsub>G\<^esub> (val x) (val y) = (val x)"
using G_ord(1) True val_def
by (simp add: G_ord(1) val_def)
have F1: "val (x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y) = val x"
using False True Qp_is_field field_def assms(1)
cring.cring_simprules(16) domain.axioms(1)
by metis
then show ?thesis
using F0 F1 G_eq
by presburger
qed
next
case False
have Px: "x \<in> nonzero Q\<^sub>p"
using False assms(1)
by (metis (mono_tags, hide_lams) not_nonzero_Qp)
have Py: "y \<in> nonzero Q\<^sub>p"
using False assms(2)
by (metis (mono_tags, hide_lams) not_nonzero_Qp)
show ?thesis
proof(cases "x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y = \<zero>\<^bsub>Q\<^sub>p\<^esub>")
case True
then show ?thesis
using G_ord(1) local.val_zero by presburger
next
case False
have Pxy: "x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y \<in> nonzero Q\<^sub>p"
by (simp add: False assms(1) assms(2) cring.cring_simprules(1) fieldE(1) nonzero_def)
then show ?thesis using Px Py val_ultrametric0
by blast
qed
qed
lemma(in padic_integers) val_ultrametric'[simp]:
assumes "x \<in> carrier Q\<^sub>p"
assumes "y \<in> carrier Q\<^sub>p"
shows " Min\<^bsub>G\<^esub> (val x) (val y) \<preceq>\<^bsub>G\<^esub> val (x \<ominus>\<^bsub>Q\<^sub>p\<^esub> y)"
using val_ultrametric[of x "\<ominus>\<^bsub>Q\<^sub>p\<^esub>y"]
val_minus[of y]
assms
by (metis Qp_is_domain a_minus_def cring.cring_simprules(3) domain.axioms(1))
(*Alternate versions of the triangle inequality*)
lemma(in padic_integers) ord_ultrametric_noteq[simp]:
assumes "x \<in> nonzero Q\<^sub>p"
assumes "y \<in> nonzero Q\<^sub>p"
assumes "x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y \<in> nonzero Q\<^sub>p"
assumes "ord x > ord y"
shows "ord (x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y) = (ord y)"
proof(rule ccontr)
assume "ord (x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y) \<noteq> ord y"
then have 0: "ord (x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y) > ord y"
using assms(1) assms(2) assms(3) assms(4) ord_ultrametric[of x y]
by linarith
have 1: "((y \<oplus>\<^bsub>Q\<^sub>p\<^esub> x) \<ominus>\<^bsub>Q\<^sub>p\<^esub> x) = y"
by (metis (no_types, lifting) Qp_is_domain Qp_nonzero_def(1) a_minus_def assms(1)
assms(2) cring.cring_simprules(1) cring.cring_simprules(10) cring.cring_simprules(19)
cring.cring_simprules(3) domain.axioms(1))
have 2: "ord ((y \<oplus>\<^bsub>Q\<^sub>p\<^esub> x) \<ominus>\<^bsub>Q\<^sub>p\<^esub> x) \<ge> min (ord (y \<oplus>\<^bsub>Q\<^sub>p\<^esub> x)) (ord x) "
using 1 assms ord_ultrametric'[of "(y \<oplus>\<^bsub>Q\<^sub>p\<^esub> x)" x]
by (metis Qp_is_domain Qp_nonzero_def(1) cring.cring_simprules(10) domain.axioms(1))
have 3: "ord y \<ge> min (ord x) (ord (x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y))"
using 2 1 Q\<^sub>p_def Qp_is_domain Z\<^sub>p_def assms(1) assms(2) cring.cring_simprules(10)
domain.axioms(1) padic_integers.Qp_nonzero_def(1) padic_integers_axioms
by fastforce
show False
using 3 0 assms
by linarith
qed
lemma(in padic_integers) ord_ultrametric_noteq'[simp]:
assumes "x \<in> nonzero Q\<^sub>p"
assumes "y \<in> nonzero Q\<^sub>p"
assumes "x \<ominus>\<^bsub>Q\<^sub>p\<^esub> y \<in> nonzero Q\<^sub>p"
assumes "ord x > ord y"
shows "ord (x \<ominus>\<^bsub>Q\<^sub>p\<^esub> y) = (ord y)"
using assms ord_ultrametric_noteq[of x "\<ominus>\<^bsub>Q\<^sub>p\<^esub>y"]
by (metis Qp_is_domain Qp_nonzero_def(1) a_minus_def cring.cring_simprules(21)
cring.cring_simprules(22) cring.cring_simprules(3) domain.axioms(1) not_nonzero_Qp ord_minus)
lemma(in padic_integers) val_ultrametric_noteq[simp]:
assumes "x \<in> carrier Q\<^sub>p"
assumes "y \<in> carrier Q\<^sub>p"
assumes "val x \<succ>\<^bsub>G\<^esub> val y"
shows "val (x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y) = val y"
proof(cases "x = \<zero>\<^bsub>Q\<^sub>p\<^esub>")
case True
then show ?thesis
by (metis Qp_is_domain assms(2) cring.cring_simprules(8) domain.axioms(1))
next
case False
have F0: "y \<in> nonzero Q\<^sub>p"
using False assms
by (meson val_nonzero)
have F1: "x \<in> nonzero Q\<^sub>p"
by (simp add: False assms(1) nonzero_def)
have F2: "(x \<oplus>\<^bsub>Q\<^sub>p\<^esub> y) \<in> nonzero Q\<^sub>p"
by (metis (no_types, lifting) Qp_is_domain assms(1) assms(2) assms(3) cring.cring_simprules(1)
cring.cring_simprules(17) cring.cring_simprules(19) cring.cring_simprules(3)
domain.axioms(1) not_nonzero_Qp val_minus)
then show ?thesis
using ord_ultrametric_noteq[of x y] F0 F1
by (smt G_ord(2) assms(3) val_ord)
qed
lemma(in padic_integers) val_ultrametric_noteq'[simp]:
assumes "x \<in> carrier Q\<^sub>p"
assumes "y \<in> carrier Q\<^sub>p"
assumes "val x \<succ>\<^bsub>G\<^esub> val y"
shows "val (x \<ominus>\<^bsub>Q\<^sub>p\<^esub> y) = val y"
using assms val_ultrametric_noteq[of x "\<ominus>\<^bsub>Q\<^sub>p\<^esub>y"]
by (metis Qp_is_domain a_minus_def cring.cring_simprules(3) domain.axioms(1) val_minus)
(*useful simprules for reasoning about distances*)
lemma (in padic_integers) Qp_diff_diff:
assumes "x \<in> carrier Q\<^sub>p"
assumes "c \<in> carrier Q\<^sub>p"
assumes "d \<in> carrier Q\<^sub>p"
shows "(x \<ominus>\<^bsub>Q\<^sub>p\<^esub>c) \<ominus>\<^bsub>Q\<^sub>p\<^esub> (d \<ominus>\<^bsub>Q\<^sub>p\<^esub>c) = x \<ominus>\<^bsub>Q\<^sub>p\<^esub> d "
by (smt Qp_is_domain a_minus_def assms(1) assms(2) assms(3) cring.cring_simprules(10)
cring.cring_simprules(19) cring.cring_simprules(3) cring.cring_simprules(4)
cring.cring_simprules(7) domain.axioms(1))
(*"All triangles in Qp are isosceles"*)
lemma (in padic_integers) Qp_isosceles[simp]:
assumes "x \<in> carrier Q\<^sub>p"
assumes "c \<in> carrier Q\<^sub>p"
assumes "d \<in> carrier Q\<^sub>p"
assumes "val (x \<ominus>\<^bsub>Q\<^sub>p\<^esub>c) \<succeq>\<^bsub>G\<^esub> v"
assumes "val (d \<ominus>\<^bsub>Q\<^sub>p\<^esub>c) \<succeq>\<^bsub>G\<^esub> v"
shows "val (x \<ominus>\<^bsub>Q\<^sub>p\<^esub>d) \<succeq>\<^bsub>G\<^esub> v"
proof-
have "val (x \<ominus>\<^bsub>Q\<^sub>p\<^esub>d) \<succeq>\<^bsub>G\<^esub> Min\<^bsub>G\<^esub> (val (x \<ominus>\<^bsub>Q\<^sub>p\<^esub>c)) (val (d \<ominus>\<^bsub>Q\<^sub>p\<^esub>c))"
using assms Qp_diff_diff[of x c d]
by (metis Qp_is_domain cring.cring_simprules(4) domain.axioms(1) val_ultrametric')
then show ?thesis using assms
by (smt G_ord_trans)
qed
(*val and ord are multiplicative*)
lemma(in padic_integers) ord_mult[simp]:
assumes "x \<in> nonzero Q\<^sub>p"
assumes "y \<in> nonzero Q\<^sub>p"
shows "(ord (x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y)) = (ord x) + (ord y)"
proof-
have 0:"x \<in> carrier Q\<^sub>p" using assms by(simp add:nonzero_def)
have 1:"y \<in>carrier Q\<^sub>p" using assms by(simp add:nonzero_def)
obtain a b c where
A: "a \<in> carrier Z\<^sub>p" and
B: "b \<in> carrier Z\<^sub>p" and
C: "c \<in> nonzero Z\<^sub>p" and
Fx: "x = frac a c" and
Fy: "y = frac b c"
using get_common_denominator 0 1 by blast
have An: "a \<in> nonzero Z\<^sub>p"
using A C Fx assms(1) Qp_nonzero_def(2) nonzero_fraction_imp_nonzero_numer by blast
have Bn: " b \<in> nonzero Z\<^sub>p"
using B C Fy assms(2) Qp_nonzero_def(2) nonzero_fraction_imp_nonzero_numer by blast
have Fxy: "x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y = frac (a \<otimes> b) (c \<otimes>c)"
by (simp add: A B C Fx Fy frac_mult)
have Cn: "c \<otimes>c \<in> nonzero Z\<^sub>p"
using C Localization.submonoid.m_closed Zp_is_domain domain.nonzero_is_submonoid
by metis
have Ordxy0: "ord (x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y) = ord_Zp (a \<otimes> b) - ord_Zp (c \<otimes>c)"
by (metis An Bn Cn Fxy Localization.submonoid.m_closed Z\<^sub>p_def
domain.nonzero_is_submonoid ord_of_frac padic_integers.Zp_is_domain padic_integers_axioms)
have Ordxy1: "ord (x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y) = (ord_Zp a) + (ord_Zp b) - ((ord_Zp c) + (ord_Zp c))"
using An Bn C Ordxy0 ord_Zp_mult
by presburger
show ?thesis
proof-
have "ord x + ord y = (ord_Zp a) - (ord_Zp c) + ((ord_Zp b) - (ord_Zp c))"
using An Bn C Fx Fy ord_of_frac[of a c] ord_of_frac[of b c] by presburger
then show ?thesis
using Ordxy1
by presburger
qed
qed
lemma(in padic_integers) val_mult0[simp]:
assumes "x \<in> nonzero Q\<^sub>p"
assumes "y \<in> nonzero Q\<^sub>p"
shows "(val (x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y)) = (val x) \<oplus>\<^bsub>G\<^esub> (val y)"
proof-
have 0: "(val x) = *(ord x)*"
using assms(1) val_ord by metis
have 1: "(val y) = *(ord y)*"
using assms(2) val_ord by metis
have "(x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y) \<noteq> \<zero>\<^bsub>Q\<^sub>p\<^esub>"
using Qp_is_field assms(1) assms(2) integral nonzero_def
by (smt mem_Collect_eq)
then have 2: "val (x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y) = *ord (x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y)*"
by (simp add: val_def)
have 3: "(val x) \<otimes>\<^bsub>G\<^esub> (val y) = *(ord x) + (ord y)* "
by (metis "0" "1" G_mult(3))
have 4: "val (x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y) = *ord (x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y)*"
using "2" by auto
then show ?thesis using 3 4 ord_mult assms nonzero_def
by (simp add: nonzero_def)
qed
(*val is multiplicative everywhere*)
lemma(in padic_integers) val_mult[simp]:
assumes "x \<in> carrier Q\<^sub>p"
assumes "y \<in> carrier Q\<^sub>p"
shows "(val (x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y)) = (val x) \<otimes>\<^bsub>G\<^esub> (val y)"
proof(cases "x = \<zero>\<^bsub>Q\<^sub>p\<^esub> \<or> y = \<zero>\<^bsub>Q\<^sub>p\<^esub>")
case True
then show ?thesis
using G_mult(1) G_mult(2) Qp_is_field assms(1) assms(2)
domain.integral_iff field.axioms(1) val_def
by (metis (no_types, lifting))
next
case False
have Px: "x \<in> nonzero Q\<^sub>p"
using False assms(1)
by (metis (mono_tags, hide_lams) not_nonzero_Qp)
have Py: "y \<in> nonzero Q\<^sub>p"
using False assms(2)
by (metis (mono_tags, hide_lams) not_nonzero_Qp)
then show ?thesis
by (simp add: Px)
qed
(*val and ord are compatible with \<iota>*)
lemma(in padic_integers) ord_of_inc:
assumes "x \<in> nonzero Z\<^sub>p"
shows "ord_Zp x = ord(\<iota> x)"
proof-
have "\<iota> x = frac x \<one>"
using assms(1) Zp_nonzero_def(1) local.inc_def
by blast
then have "ord ( \<iota> x) = ord_Zp x - ord_Zp \<one>"
using assms(1) ord_of_frac Zp_one_nonzero
by presburger
then show ?thesis
using ord_Zp_one
by (simp add: ord_Zp_def)
qed
lemma(in padic_integers) val_of_inc:
assumes "x \<in> carrier Z\<^sub>p"
shows "val_Zp x = val (\<iota> x)"
proof(cases "x \<in> nonzero Z\<^sub>p")
case True
then show ?thesis
using inc_of_nonzero nonzero_def ord_Zp_def ord_of_inc val_Zp_def val_ord
by (simp add: nonzero_def)
next
case False
then show ?thesis
by (metis (mono_tags, hide_lams) Zp_nat_mult_zero Zp_one_nonzero assms local.frac_def
local.inc_def nonzero_fraction_imp_numer_not_zero not_nonzero_Zp val_Zp_def val_def)
qed
lemma(in padic_integers) Qp_inc_id:
assumes "a \<in> nonzero Q\<^sub>p"
assumes "ord a \<ge>0"
obtains b where "b \<in> nonzero Z\<^sub>p" and "a = \<iota> b"
using assms
by (smt Q\<^sub>p_def Qp_nonzero_def(2) Z\<^sub>p_def \<iota>_def imageE local.inc_def
nonzero_fraction_imp_nonzero_numer padic_integers.Qp_nonzero_def(1)
padic_integers.Zp_one_nonzero padic_integers.Zp_ord_criterion padic_integers_axioms)
(*ord and val on powers of p*)
lemma(in padic_integers) ord_p:
"ord \<pp> = 1"
using p_nonzero ord_Zp_p ord_of_inc p_inc
by (metis (mono_tags, hide_lams) Zp_nat_inc_closed ord_of_nonzero(2) zero_le_one)
lemma(in padic_integers) ord_p_pow_nat:
"ord (\<pp> e (n::nat)) = n"
using p_pow_nonzero ord_Zp_p ord_of_inc p_inc ord_Zp_p_pow p_natpow_inc
by presburger
lemma(in padic_integers) ord_p_pow_int:
"ord (\<pp> e (n::int)) = n"
proof(cases "n \<ge>0")
case True
then show ?thesis
by (metis int_nat_eq int_pow_int ord_p_pow_nat)
next
case False
then have Neg: "n <0" by auto
then have 0: "\<pp> e n = frac \<one> (\<p>[^](-n))"
using p_intpow by auto
have "(\<p>[^](-n)) \<in> nonzero Z\<^sub>p"
using False p_int_pow_nonzero
by (simp add: nonzero_def)
then have "ord (\<pp> e (n::int)) = ord_Zp \<one> - ord_Zp (\<p>[^](-n))"
using "0" ord_of_frac Zp_one_nonzero
by presburger
then have "ord (\<pp> e (n::int)) = - ord_Zp (\<p>[^](-n))"
using ord_Zp_one by linarith
then have "ord (\<pp> e (n::int)) = -(-n)"
using Neg ord_Zp_p_int_pow
by (metis int.lless_eq neg_0_le_iff_le)
then show ?thesis
by auto
qed
lemma(in padic_integers) ord_nonneg:
assumes "x \<in> \<O>\<^sub>p"
assumes "x \<noteq> \<zero>\<^bsub>Q\<^sub>p\<^esub>"
shows "ord x \<ge>0"
proof-
obtain a where A: "x = \<iota> a \<and> a \<in> carrier Z\<^sub>p"
using assms(1) by blast
then have "a \<in> nonzero Z\<^sub>p" using assms(2) Zp_one_nonzero
local.inc_def nonzero_fraction_imp_numer_not_zero not_nonzero_Zp by blast
then have "ord_Zp a \<ge>0"
using A Zp_nonzero_def(2) ord_pos by metis
then show ?thesis
using A \<open>a \<in> nonzero Z\<^sub>p\<close> ord_of_inc by metis
qed
lemma(in padic_integers) val_p:
"(val \<pp>) = (1\<^sub>v)"
by (simp add: ord_p val_of_def)
(*The angular component function on Qp*)
definition(in padic_integers) angular_component where
"angular_component a = (ac_Zp (numer a)) \<otimes> (inv\<^bsub>Z\<^sub>p\<^esub> ac_Zp (denom a))"
lemma(in padic_integers) ac_fract:
assumes "c \<in> carrier Q\<^sub>p"
assumes "a \<in> nonzero Z\<^sub>p"
assumes "b \<in> nonzero Z\<^sub>p"
assumes "c = frac a b"
shows "angular_component c = (ac_Zp a)\<otimes> inv(ac_Zp b)"
proof-
have "(numer c) \<otimes> b = (denom c) \<otimes> a"
by (metis Q\<^sub>p_def Zp_is_domain Zp_nonzero_def(1) assms(1) assms(2) assms(3) assms(4) denom_def
domain.frac_eq domain.numer_denom_facts(1) domain.numer_denom_facts(2)
domain.numer_denom_facts(5) local.frac_def numer_def)
then have "ac_Zp ((numer c) \<otimes> b) = ac_Zp ((denom c) \<otimes> a)"
by simp
then have "(ac_Zp (numer c)) \<otimes> (ac_Zp b) = (ac_Zp (denom c)) \<otimes> (ac_Zp a)"
by (metis Q\<^sub>p_def Zp_is_domain ac_Zp_mult assms(1) assms(2) assms(3) assms(4)
domain.numer_denom_facts(1) domain.numer_denom_facts(3) nonzero_numer_imp_nonzero_fraction
not_nonzero_Zp numer_def numer_denom_facts(2))
then have "(inv (ac_Zp (denom c))) \<otimes> (ac_Zp (numer c)) \<otimes> (ac_Zp b) = (ac_Zp a)"
using ac_Zp_is_Unit[of "ac_Zp (denom c)"] Zp_is_domain inv_cancelR(1)
by (metis (no_types, lifting) Q\<^sub>p_def Units_nonzero_Zp Z\<^sub>p_def Zp_nonzero_def(1) Zp_nonzero_def(2)
ac_Zp_is_Unit assms(1) assms(2) assms(3) assms(4) cring.cring_simprules(11)
cring.cring_simprules(5) denom_def domain.Units_inverse domain.axioms(1)
domain.numer_denom_facts(2) nonzero_numer_imp_nonzero_fraction
padic_integers.numer_denom_facts(1) padic_integers.numer_denom_facts(3) padic_integers_axioms)
then have "(inv (ac_Zp (denom c))) \<otimes> (ac_Zp (numer c)) = (ac_Zp a) \<otimes> inv (ac_Zp b)"
using ac_Zp_is_Unit[of "ac_Zp b"] Zp_is_domain inv_cancelL(2)
by (metis Q\<^sub>p_def Units_nonzero_Zp Z\<^sub>p_def Zp_nonzero_def(1) Zp_nonzero_def(2) assms(1)
assms(2) assms(3) assms(4) cring.cring_simprules(5) domain.Units_inverse domain.axioms(1)
nonzero_numer_imp_nonzero_fraction numer_denom_facts(2) numer_denom_facts(3)
padic_integers.ac_Zp_is_Unit padic_integers.numer_denom_facts(1) padic_integers_axioms)
then show ?thesis
by (metis Units_nonzero_Zp Zp_is_domain Zp_nonzero_def(1) Zp_nonzero_def(2) ac_Zp_is_Unit
angular_component_def assms(1) assms(2) assms(3) assms(4) cring.cring_simprules(14) domain.Units_inverse
domain.axioms(1) nonzero_numer_imp_nonzero_fraction numer_denom_facts(1)
numer_denom_facts(2) numer_denom_facts(3))
qed
lemma(in padic_integers) angular_component_closed[simp]:
assumes "a \<in> nonzero Q\<^sub>p"
shows "angular_component a \<in> carrier Z\<^sub>p"
by (metis Localization.submonoid.m_closed Q\<^sub>p_def Qp_nonzero_def(1) Qp_nonzero_def(2)
Units_nonzero_Zp Z\<^sub>p_def Zp_is_domain Zp_nonzero_def(1) Zp_nonzero_def(2)
ac_Zp_is_Unit angular_component_def assms denom_def domain.nonzero_is_submonoid
domain.numer_denom_facts(2) domain.numer_denom_facts(3) numer_def numer_denom_facts(1)
padic_integers.Units_inverse_Zp padic_integers_axioms)
lemma(in padic_integers) angular_component_unit[simp]:
assumes "a \<in> nonzero Q\<^sub>p"
shows "angular_component a \<in> Units Z\<^sub>p"
by (smt Q\<^sub>p_def Qp_nonzero_def(1) Qp_nonzero_def(2) Units_nonzero_Zp Z\<^sub>p_def
Zp_is_domain Zp_nonzero_def(1) Zp_nonzero_def(2) angular_component_def
assms cring.cring_simprules(5) domain.axioms(1) numer_denom_facts(2)
ord_Zp_0_imp_unit ord_Zp_mult padic_integers.Units_inverse_Zp
padic_integers.ac_Zp_is_Unit padic_integers.numer_denom_facts(1)
padic_integers.numer_denom_facts(3) padic_integers_axioms unit_imp_ord_Zp0)
lemma(in padic_integers) angular_component_factors_x:
assumes "x \<in> nonzero Q\<^sub>p"
shows "x = (\<pp>[^]\<^bsub>Q\<^sub>p\<^esub>(ord x)) \<otimes>\<^bsub>Q\<^sub>p\<^esub> \<iota> (angular_component x)"
proof-
have 0: "angular_component x = (ac_Zp (numer x)) \<otimes> (inv\<^bsub>Z\<^sub>p\<^esub> ac_Zp (denom x))"
by (simp add: angular_component_def)
have 1: "(numer x) = (\<p>[^](ord_Zp (numer x))) \<otimes> (ac_Zp (numer x))"
proof-
have "numer x \<in> nonzero Z\<^sub>p"
by (metis Q\<^sub>p_def Qp_nonzero_def(2) Z\<^sub>p_def Zp_is_domain assms
domain.numer_denom_facts(3) not_nonzero_Zp numer_def
padic_integers.Qp_nonzero_def(1) padic_integers.numer_denom_facts(1)
padic_integers_axioms)
then show ?thesis using ac_Zp_factors_x[of "numer x"]
by (metis Zp_nonzero_def(1) Zp_nonzero_def(2) int_pow_int ord_nat)
qed
have 2: "(denom x) = (\<p>[^](ord_Zp (denom x))) \<otimes> (ac_Zp (denom x))"
proof-
have "denom x \<in> nonzero Z\<^sub>p"
using Qp_nonzero_def(1) assms numer_denom_facts(2)
by blast
then show ?thesis
using ac_Zp_factors_x[of "denom x"]
by (metis Zp_nonzero_def(1) Zp_nonzero_def(2) int_pow_int ord_nat)
qed
have 3: "\<iota> (angular_component x) = frac (ac_Zp (numer x)) (ac_Zp (denom x))"
by (metis "0" Q\<^sub>p_def Qp_nonzero_def(1) Qp_nonzero_def(2) Z\<^sub>p_def Zp_division_Qp_0
Zp_nonzero_def(1) Zp_nonzero_def(2) angular_component_closed assms local.inc_def
numer_denom_facts(1) numer_denom_facts(2) padic_integers.ac_Zp_is_Unit
padic_integers.numer_denom_facts(3) padic_integers_axioms)
have 4: "(\<pp>[^]\<^bsub>Q\<^sub>p\<^esub>((ord x))) \<otimes>\<^bsub>Q\<^sub>p\<^esub> \<iota> (angular_component x) =
(\<pp>[^]\<^bsub>Q\<^sub>p\<^esub>((ord_Zp (numer x)) - (ord_Zp (denom x)))) \<otimes>\<^bsub>Q\<^sub>p\<^esub> frac (ac_Zp (numer x)) (ac_Zp (denom x))"
using "3" ord_def by presburger
have 5: "(\<pp>[^]\<^bsub>Q\<^sub>p\<^esub>((ord x))) \<otimes>\<^bsub>Q\<^sub>p\<^esub> \<iota> (angular_component x) =
frac (\<p>[^]((ord_Zp (numer x)))) (\<p>[^] (ord_Zp (denom x))) \<otimes>\<^bsub>Q\<^sub>p\<^esub> frac (ac_Zp (numer x)) (ac_Zp (denom x))"
proof-
have "(\<pp>[^]\<^bsub>Q\<^sub>p\<^esub>((ord_Zp (numer x)) - (ord_Zp (denom x))))
= frac (\<p>[^]((ord_Zp (numer x)))) (\<p>[^] (ord_Zp (denom x)))"
using p_pow_diff[of "(ord_Zp (numer x))" "(ord_Zp (denom x))"] Qp_nonzero_def(1)
Qp_nonzero_def(2) Zp_nonzero_def(1) Zp_nonzero_def(2)
assms numer_denom_facts(1) numer_denom_facts(2) numer_denom_facts(3) ord_pos
by presburger
then show ?thesis using 4 by metis
qed
have 6: "(\<pp>[^]\<^bsub>Q\<^sub>p\<^esub>((ord x))) \<otimes>\<^bsub>Q\<^sub>p\<^esub> \<iota> (angular_component x) =
frac (\<p>[^]((ord_Zp (numer x))) \<otimes> (ac_Zp (numer x))) (\<p>[^] (ord_Zp (denom x)) \<otimes> (ac_Zp (denom x)))"
using 5
by (metis "2" Q\<^sub>p_def Qp_nonzero_def(1) Qp_nonzero_def(2) Z\<^sub>p_def Zp_is_domain Zp_nonzero_def(1)
Zp_nonzero_def(2) assms domain.integral_iff frac_mult not_nonzero_Zp numer_denom_facts(1)
numer_denom_facts(2) ord_pos p_int_pow_nonzero padic_integers.ac_Zp_in_Zp
padic_integers.numer_denom_facts(3) padic_integers_axioms)
then show ?thesis
using "1" "2" Qp_nonzero_def(1) assms numer_denom_facts(5)
by presburger
qed
lemma(in padic_integers) angular_component_mult:
assumes "x \<in> nonzero Q\<^sub>p"
assumes "y \<in> nonzero Q\<^sub>p"
shows "angular_component (x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y) = (angular_component x) \<otimes> (angular_component y)"
proof-
obtain a b where "a = numer x" and
"b = denom x" and
a_nz: "a \<in> nonzero Z\<^sub>p" and
b_nz: "b \<in> nonzero Z\<^sub>p" and
x_frac: "x = frac a b"
by (metis Q\<^sub>p_def Qp_nonzero_def(1) Qp_nonzero_def(2) Z\<^sub>p_def assms(1)
not_nonzero_Zp numer_denom_facts(1) numer_denom_facts(3) numer_denom_facts(5)
padic_integers.numer_denom_facts(2) padic_integers_axioms)
obtain c d where "c = numer y" and
"d = denom y" and
c_nz: "c \<in> nonzero Z\<^sub>p" and
d_nz: "d \<in> nonzero Z\<^sub>p" and
y_frac: "y = frac c d"
by (metis Q\<^sub>p_def Qp_nonzero_def(1) Qp_nonzero_def(2) Z\<^sub>p_def assms(2) not_nonzero_Zp
numer_denom_facts(1) numer_denom_facts(3) numer_denom_facts(5)
padic_integers.numer_denom_facts(2) padic_integers_axioms)
have 0: "(x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y) = frac (a \<otimes> c) (b \<otimes> d)"
by (simp add: Zp_nonzero_def(1) a_nz b_nz c_nz d_nz frac_mult x_frac y_frac)
have 1: "angular_component (x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y) = (ac_Zp (a \<otimes> c)) \<otimes> inv (ac_Zp (b \<otimes> d))"
by (metis (mono_tags, hide_lams) "0" Localization.submonoid.m_closed Qp_is_domain
Qp_nonzero_def(1) Zp_is_domain a_nz ac_fract assms(1) assms(2) b_nz c_nz
cring.cring_simprules(5) d_nz domain.nonzero_is_submonoid domain_def)
have 2: "angular_component (x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y) = (ac_Zp a) \<otimes> (ac_Zp c) \<otimes> inv ((ac_Zp b) \<otimes> (ac_Zp d))"
by (simp add: "1" a_nz ac_Zp_mult b_nz c_nz d_nz)
have 3: "angular_component (x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y) = (ac_Zp a) \<otimes> (ac_Zp c) \<otimes> inv (ac_Zp b) \<otimes> inv (ac_Zp d)"
by (metis (no_types, lifting) "1" Units_nonzero_Zp Z\<^sub>p_def Zp_is_comm_monoid
Zp_is_domain Zp_nonzero_def(1) Zp_nonzero_def(2) a_nz ac_Zp_mult b_nz c_nz
cring.cring_simprules(11) cring.cring_simprules(5) d_nz domain.axioms(1)
inv_of_prod padic_integers.Units_inverse_Zp padic_integers.ac_Zp_is_Unit
padic_integers_axioms)
have 4: "angular_component (x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y) = (ac_Zp a) \<otimes> inv (ac_Zp b) \<otimes> (ac_Zp c) \<otimes> inv (ac_Zp d)"
by (smt "3" Units_inverse_Zp Units_nonzero_Zp Zp_is_comm_monoid Zp_nonzero_def(1)
Zp_nonzero_def(2) a_nz ac_Zp_is_Unit b_nz c_nz comm_monoid.m_ac(1) comm_monoid.m_comm)
have 5: "angular_component (x \<otimes>\<^bsub>Q\<^sub>p\<^esub> y) = ((ac_Zp a) \<otimes> inv (ac_Zp b)) \<otimes> ( (ac_Zp c) \<otimes> inv (ac_Zp d))"
using 4
by (metis Units_nonzero_Zp Z\<^sub>p_def Zp_is_domain Zp_nonzero_def(1) Zp_nonzero_def(2)
a_nz ac_fract angular_component_closed assms(1) b_nz c_nz cring.cring_simprules(11)
d_nz domain.axioms(1) frac_closed padic_integers.Units_inverse_Zp
padic_integers.ac_Zp_is_Unit padic_integers_axioms x_frac)
then show ?thesis
by (simp add: Z\<^sub>p_def \<open>a = numer x\<close> \<open>b = denom x\<close> \<open>c = numer y\<close> \<open>d = denom y\<close>
padic_integers.angular_component_def padic_integers_axioms)
qed
lemma(in padic_integers) angular_component_inv:
assumes "x \<in> nonzero Q\<^sub>p"
shows "angular_component (inv\<^bsub>Q\<^sub>p\<^esub> x) = inv\<^bsub>Z\<^sub>p\<^esub> (angular_component x)"
by (metis Qp_is_field Qp_nonzero_def(1) Qp_nonzero_def(2) Qp_one_car Zp_is_domain
Zp_one_car Zp_one_nonzero ac_Zp_one ac_fract angular_component_closed
angular_component_mult assms cring.cring_simprules(12) domain.axioms(1)
field.field_inv(1) inc_of_one invI(2) inv_in_frac(3) local.inc_def)
lemma(in padic_integers) angular_component_one:
"angular_component \<one>\<^bsub>Q\<^sub>p\<^esub> = \<one>"
by (metis Qp_one_car Zp_is_comm_monoid Zp_is_domain Zp_one_car Zp_one_nonzero
ac_Zp_one ac_fract comm_monoid.comm_inv_char cring.cring_simprules(12)
domain.axioms(1) inc_of_one local.inc_def)
lemma(in padic_integers) angular_component_ord_zero:
assumes "ord x = 0"
assumes "x \<in> nonzero Q\<^sub>p"
shows "\<iota> (angular_component x) = x"
proof-
have 0: "ord x \<ge>0"
using assms by auto
have 1: "x \<in> nonzero Q\<^sub>p"
proof-
have "x \<noteq> \<zero>\<^bsub>Q\<^sub>p\<^esub>"
using Qp_nonzero_def(2) assms(2) by blast
then show ?thesis
by (simp add: assms(2))
qed
obtain a where a_def: "a \<in> nonzero Z\<^sub>p \<and> \<iota> a = x"
using 0 1 assms Qp_inc_id[of x]
by metis
then have "x = frac a \<one>"
using local.inc_def Zp_nonzero_def(1)
by blast
then have "angular_component x = ac_Zp a \<otimes> inv (ac_Zp \<one>)"
using ac_fract[of x a \<one>] "1" Qp_nonzero_def(1) Zp_one_nonzero a_def
by blast
then have "angular_component x = ac_Zp a \<otimes> inv \<one>"
by (simp add: ac_Zp_one)
then have "angular_component x = ac_Zp a \<otimes> \<one>"
by (metis Units_nonzero_Zp Zp_is_domain Zp_nonzero_def(1)
Zp_one_car cring.cring_simprules(12) domain.Units_inverse
domain.axioms(1) inv_cancelL(1) ord_Zp_0_imp_unit ord_Zp_one)
then show ?thesis
by (metis (mono_tags, hide_lams) "1" Zp_division_Qp_0 Zp_nonzero_def(1) Zp_one_car
\<open>angular_component x = ac_Zp a \<otimes> inv \<one>\<close> \<open>x = local.frac a \<one>\<close> a_def ac_Zp_of_Unit
angular_component_closed assms(1) local.inc_def
ord_Zp_0_imp_unit ord_Zp_one ord_of_inc)
qed
lemma(in padic_integers) res_uminus:
assumes "k > 0"
assumes "f \<in> carrier Z\<^sub>p"
assumes "c \<in> carrier (R k)"
assumes "c = \<ominus>\<^bsub>R k\<^esub> (f k)"
shows "c = ((\<ominus> f) k)"
using Z\<^sub>p_def assms(2) assms(4) padic_inv prime by auto
(*
lemma(in padic_integers) val_p_pow_nat:
"val (\<pp> e (n::int)) = *n*"
proof-
have
using ord_p_pow_int val_ord p_pow_nonzero sledgehammer
*)
end
|
open import Prelude hiding (β₯)
module Implicits.Resolution.Infinite.Algorithm where
open import Data.Bool
open import Data.Unit.Base
open import Data.Maybe using (is-just; functor)
open import Coinduction
open import Data.Fin.Substitution
open import Data.Vec hiding (_>>=_)
open import Data.List hiding (monad)
open import Data.List.Any hiding (tail)
open import Data.Maybe hiding (monad; module Eq)
open import Implicits.Syntax
open import Implicits.Substitutions
open import Implicits.Substitutions.Lemmas
open import Implicits.Syntax.Type.Unification
open import Implicits.Resolution.Termination
open import Category.Monad
open import Category.Functor
open import Category.Monad.Partiality as P
open import Category.Monad.Partiality.All
private module M {f} = RawMonad (monad {f})
private module MaybeFunctor {f} = RawFunctor (functor {f})
open import Induction.WellFounded
open import Induction.Nat
module _ where
open P.Workaround
m<-Acc : β {m Ξ½} β MetaType m Ξ½ β Set
m<-Acc {m} {Ξ½} r = Acc _m<_ (m , Ξ½ , r)
mutual
map-bool' : β {A : Set} β A β Bool β Maybe A β₯P
map-bool' u true = now (just u)
map-bool' u false = now nothing
delayed-resolve' : β {Ξ½} (Ξ : ICtx Ξ½) a β Bool β₯P
delayed-resolve' Ξ a = (later (β― (resolve' Ξ a)))
resolve-context' : β {Ξ½ m} (Ξ : ICtx Ξ½) a β (Maybe (Sub (flip MetaType Ξ½) m zero)) β
(Maybe (Sub (flip MetaType Ξ½) m zero)) β₯P
resolve-context' Ξ a (just u) =
(delayed-resolve' Ξ (from-meta (MetaTypeMetaSubst._/_ a u)))
>>= (map-bool' u)
resolve-context' Ξ a nothing = now nothing
-- match' uses MetaType m Ξ½ instead of Type Ξ½ to be able to distinguish unification variables
-- from other, non-unifiable tvars.
-- The difference is subtle but the gist is that we can only unify variables that we open
-- during matching. Any variables that are already open in the context are fixed.
match-u' : β {Ξ½ m} (Ξ : ICtx Ξ½) β (Ο : SimpleType Ξ½) β (r : MetaType m Ξ½) β
m<-Acc r β
(Maybe (Sub (flip MetaType Ξ½) m zero)) β₯P
-- For rule types we first check if b matches our query Ο.
-- If this is the case, we use the unifier to instantiate the unification vars in a and
-- recursively try to resolve the result.
match-u' {Ξ½} {m} Ξ Ο (a β b) (acc f) =
(match-u' Ξ Ο b (f _ (b-m<-aβb a b))) >>= (resolve-context' Ξ a)
-- On type vars we simply open it up, adding the tvar to the set of unification variables.
-- and recursively try to match.
match-u' Ξ Ο (β' a) (acc f) = (match-u' Ξ Ο (open-meta a) (f _ (open-meta-a-m<-β'a a))) >>=
(now β (MaybeFunctor._<$>_ tail))
-- The only thing left to do is to try and unify Ο and x.
match-u' Ξ Ο (simpl x) _ = now (mgu (simpl x) Ο)
match' : β {Ξ½} (Ξ : ICtx Ξ½) β (Ο : SimpleType Ξ½) β Type Ξ½ β Bool β₯P
match' {Ξ½} Ξ Ο r = match-u' Ξ Ο (to-meta {zero} r) (m<-well-founded _) >>= (now β is-just)
match1st-recover' : β {Ξ½} (Ξ Οs : ICtx Ξ½) β (Ο : SimpleType Ξ½) β Bool β Bool β₯P
match1st-recover' _ _ _ true = now true
match1st-recover' Ξ Οs Ο false = match1st' Ξ Οs Ο
match1st' : β {Ξ½} (Ξ : ICtx Ξ½) β (Οs : ICtx Ξ½) β (Ο : SimpleType Ξ½) β Bool β₯P
match1st' Ξ List.[] _ = now false
match1st' Ξ (x List.β· Οs) Ο = match' Ξ Ο x >>= (match1st-recover' Ξ Οs Ο)
-- resolution in ResP
resolve' : β {Ξ½} (Ξ : ICtx Ξ½) (a : Type Ξ½) β Bool β₯P
resolve' Ξ (simpl x) = match1st' Ξ Ξ x
resolve' Ξ (a β b) = resolve' (a List.β· Ξ) b
resolve' Ξ (β' a) = resolve' (ictx-weaken Ξ) a
module _ where
open P.Workaround using (β¦_β§P)
open P.Workaround.Correct
open M
module Eq {l} {A : Set l} where
open import Relation.Binary.PropositionalEquality as PEq using (_β‘_) public
open module Eq = P.Equality {A = A} _β‘_ public
open module R = P.Reasoning (PEq.isEquivalence {A = A}) public
map-bool : β {A : Set} β A β Bool β (Maybe A) β₯
map-bool x b = β¦ map-bool' x b β§P
delayed-resolve : β {Ξ½} (Ξ : ICtx Ξ½) a β Bool β₯
delayed-resolve Ξ a = β¦ delayed-resolve' Ξ a β§P
resolve-context : β {Ξ½ m} (Ξ : ICtx Ξ½) a β (Maybe (Sub (flip MetaType Ξ½) m zero)) β
(Maybe (Sub (flip MetaType Ξ½) m zero)) β₯
resolve-context Ξ a p = β¦ resolve-context' Ξ a p β§P
match-u : β {Ξ½ m} (Ξ : ICtx Ξ½) β SimpleType Ξ½ β (r : MetaType m Ξ½) β m<-Acc r β
(Maybe (Sub (flip MetaType Ξ½) m zero)) β₯
match-u Ξ Ο r f = β¦ match-u' Ξ Ο r f β§P
match : β {Ξ½} (Ξ : ICtx Ξ½) β (Ο : SimpleType Ξ½) β (r : Type Ξ½) β Bool β₯
match Ξ Ο r = β¦ match' Ξ Ο r β§P
match1st-recover : β {Ξ½} (Ξ : ICtx Ξ½) β (Οs : ICtx Ξ½) β (Ο : SimpleType Ξ½) β Bool β Bool β₯
match1st-recover Ξ Οs Ο b = β¦ match1st-recover' Ξ Οs Ο b β§P
match1st : β {Ξ½} (Ξ : ICtx Ξ½) β (Οs : ICtx Ξ½) β (Ο : SimpleType Ξ½) β Bool β₯
match1st Ξ Οs Ο = β¦ match1st' Ξ Οs Ο β§P
resolve : β {Ξ½} (Ξ : ICtx Ξ½) (r : Type Ξ½) β Bool β₯
resolve Ξ r = β¦ resolve' Ξ r β§P
--
-- compositionality of resolution functions
--
resolve-context-comp : β {m Ξ½} (Ξ : ICtx Ξ½) a u β
(resolve-context {Ξ½} {m} Ξ a (just u))
Eq.β
(delayed-resolve Ξ (from-meta (MetaTypeMetaSubst._/_ a u))
>>= (map-bool u))
resolve-context-comp {m} {Ξ½} Ξ a u =
(resolve-context {Ξ½} {m} Ξ a (just u))
Eq.β
β¨ >>=-hom (delayed-resolve' Ξ (from-meta (MetaTypeMetaSubst._/_ a u))) _ β©
(delayed-resolve Ξ (from-meta (MetaTypeMetaSubst._/_ a u)) >>= (map-bool u)) Eq.β
match-u-iabs-comp : β {m Ξ½} (Ξ : ICtx Ξ½) Ο (a b : MetaType m Ξ½) f β
(match-u Ξ Ο (a β b) (acc f))
Eq.β
((match-u Ξ Ο b (f _ (b-m<-aβb a b))) >>= (resolve-context Ξ a))
match-u-iabs-comp Ξ Ο a b f =
(match-u Ξ Ο (a β b) (acc f))
Eq.β
β¨ >>=-hom (match-u' Ξ Ο b (f _ (b-m<-aβb a b))) _ β©
((match-u Ξ Ο b (f _ (b-m<-aβb a b))) >>= (resolve-context Ξ a)) Eq.β
match-u-tabs-comp : β {m Ξ½} (Ξ : ICtx Ξ½) Ο (r : MetaType m (suc Ξ½)) f β
(match-u Ξ Ο (β' r) (acc f))
Eq.β
((match-u Ξ Ο (open-meta r) (f _ (open-meta-a-m<-β'a r))) >>=
(now β (MaybeFunctor._<$>_ tail)))
match-u-tabs-comp Ξ Ο r f =
match-u Ξ Ο (β' r) (acc f)
Eq.β
β¨ >>=-hom (match-u' Ξ Ο (open-meta r) (f _ (open-meta-a-m<-β'a r))) _ β©
((match-u Ξ Ο (open-meta r) (f _ (open-meta-a-m<-β'a r))) >>= (now β (MaybeFunctor._<$>_ tail))) Eq.β
match-comp : β {Ξ½} (Ξ : ICtx Ξ½) Ο r β
match Ξ Ο r
Eq.β
((match-u Ξ Ο (to-meta {zero} r) (m<-well-founded _)) >>= (now β is-just))
match-comp Ξ Ο r =
match Ξ Ο r
Eq.β
β¨ >>=-hom (match-u' Ξ Ο (to-meta {zero} r) (m<-well-founded _)) _ β©
_>>=_ (match-u Ξ Ο (to-meta {zero} r) (m<-well-founded _)) (now β is-just) Eq.β
match1st-comp : β {Ξ½} (Ξ : ICtx Ξ½) x Οs Ο β match1st Ξ (x List.β· Οs) Ο Eq.β
((match Ξ Ο x) >>=
(match1st-recover Ξ Οs Ο))
match1st-comp Ξ x Οs Ο =
match1st Ξ (x List.β· Οs) Ο
Eq.β
β¨ >>=-hom (match' Ξ Ο x) _ β©
((match Ξ Ο x) >>= (match1st-recover Ξ Οs Ο)) Eq.β
|
If $c \neq 0$ and $n > 0$, then the number of $n$th roots of $c$ is $n$.
|
/*
Copyright (C) 2018 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file ored/configuration/commoditycurveconfig.hpp
\brief Commodity curve configuration class
\ingroup configuration
*/
#pragma once
#include <ored/configuration/bootstrapconfig.hpp>
#include <ored/configuration/curveconfig.hpp>
#include <boost/optional/optional.hpp>
namespace ore {
namespace data {
/*! Class for holding information on a set of instruments used in bootstrapping a piecewise price curve.
\ingroup configuration
*/
class PriceSegment : public XMLSerializable {
public:
//! Type of price segment being represented, i.e. type of instrument in the price segment.
enum class Type { Future, AveragingFuture, AveragingSpot, AveragingOffPeakPower, OffPeakPowerDaily };
//! Class to store quotes used in building daily off-peak power quotes.
class OffPeakDaily : public XMLSerializable {
public:
//! Constructor.
OffPeakDaily();
//! Detailed constructor.
OffPeakDaily(
const std::vector<std::string>& offPeakQuotes,
const std::vector<std::string>& peakQuotes);
const std::vector<std::string>& offPeakQuotes() const { return offPeakQuotes_; }
const std::vector<std::string>& peakQuotes() const { return peakQuotes_; }
void fromXML(XMLNode* node) override;
XMLNode* toXML(XMLDocument& doc) override;
private:
std::vector<std::string> offPeakQuotes_;
std::vector<std::string> peakQuotes_;
};
//! \name Constructors
//@{
//! Default constructor
PriceSegment();
//! Detailed constructor
PriceSegment(const std::string& type,
const std::string& conventionsId,
const std::vector<std::string>& quotes,
const boost::optional<unsigned short>& priority = boost::none,
const boost::optional<OffPeakDaily>& offPeakDaily = boost::none,
const std::string& peakPriceCurveId = "",
const std::string& peakPriceCalendar = "");
//@}
//! \name Inspectors
//@{
Type type() const;
const std::string& conventionsId() const;
const std::vector<std::string>& quotes() const;
const boost::optional<unsigned short>& priority() const;
const boost::optional<OffPeakDaily>& offPeakDaily() const;
const std::string& peakPriceCurveId() const;
const std::string& peakPriceCalendar() const;
bool empty() const;
//@}
//! \name Serialisation
//@{
void fromXML(XMLNode* node) override;
XMLNode* toXML(XMLDocument& doc) override;
//@}
private:
//! Populate quotes
void populateQuotes();
std::string strType_;
std::string conventionsId_;
std::vector<std::string> quotes_;
boost::optional<unsigned short> priority_;
boost::optional<OffPeakDaily> offPeakDaily_;
std::string peakPriceCurveId_;
std::string peakPriceCalendar_;
bool empty_;
Type type_;
};
//! Commodity curve configuration
/*!
\ingroup configuration
*/
class CommodityCurveConfig : public CurveConfig {
public:
/*! The type of commodity curve that has been configured:
- Direct: if the commodity price curve is built from commodity forward quotes
- CrossCurrency: if the commodity price curve is implied from a price curve in a different currency
- Basis: if the commodity price curve is built from basis quotes
- Piecewise: if the commodity price curve is bootstrapped from sets of instruments
*/
enum class Type { Direct, CrossCurrency, Basis, Piecewise };
//! \name Constructors
//@{
//! Default constructor
CommodityCurveConfig() : type_(Type::Direct), extrapolation_(true), addBasis_(true),
monthOffset_(0), averageBase_(true) {}
//! Detailed constructor for Direct commodity curve configuration
CommodityCurveConfig(const std::string& curveId, const std::string& curveDescription, const std::string& currency,
const std::vector<std::string>& quotes, const std::string& commoditySpotQuote = "",
const std::string& dayCountId = "A365", const std::string& interpolationMethod = "Linear",
bool extrapolation = true, const std::string& conventionsId = "");
//! Detailed constructor for CrossCurrency commodity curve configuration
CommodityCurveConfig(const std::string& curveId, const std::string& curveDescription, const std::string& currency,
const std::string& basePriceCurveId, const std::string& baseYieldCurveId,
const std::string& yieldCurveId, bool extrapolation = true);
//! Detailed constructor for Basis commodity curve configuration
CommodityCurveConfig(const std::string& curveId, const std::string& curveDescription, const std::string& currency,
const std::string& basePriceCurveId, const std::string& baseConventionsId,
const std::vector<std::string>& basisQuotes, const std::string& basisConventionsId,
const std::string& dayCountId = "A365", const std::string& interpolationMethod = "Linear",
bool extrapolation = true, bool addBasis = true, QuantLib::Natural monthOffset = 0,
bool averageBase = true);
//! Detailed constructor for Piecewise commodity curve configuration
CommodityCurveConfig(const std::string& curveId, const std::string& curveDescription, const std::string& currency,
const std::vector<PriceSegment>& priceSegments, const std::string& dayCountId = "A365",
const std::string& interpolationMethod = "Linear", bool extrapolation = true,
const boost::optional<BootstrapConfig>& bootstrapConfig = boost::none);
//@}
//! \name Serialisation
//@{
void fromXML(XMLNode* node) override;
XMLNode* toXML(XMLDocument& doc) override;
//@}
//! \name Inspectors
//@{
const Type& type() const { return type_; }
const std::string& currency() const { return currency_; }
const std::string& commoditySpotQuoteId() const { return commoditySpotQuoteId_; }
const std::string& dayCountId() const { return dayCountId_; }
const std::string& interpolationMethod() const { return interpolationMethod_; }
const std::string& basePriceCurveId() const { return basePriceCurveId_; }
const std::string& baseYieldCurveId() const { return baseYieldCurveId_; }
const std::string& yieldCurveId() const { return yieldCurveId_; }
bool extrapolation() const { return extrapolation_; }
const vector<string>& fwdQuotes() const { return fwdQuotes_; }
const std::string& conventionsId() const { return conventionsId_; }
const std::string& baseConventionsId() const { return baseConventionsId_; }
bool addBasis() const { return addBasis_; }
QuantLib::Natural monthOffset() const { return monthOffset_; }
bool averageBase() const { return averageBase_; }
const std::map<unsigned short, PriceSegment>& priceSegments() const { return priceSegments_; }
const boost::optional<BootstrapConfig>& bootstrapConfig() const { return bootstrapConfig_; }
//@}
//! \name Setters
//@{
Type& type() { return type_; }
std::string& currency() { return currency_; }
std::string& commoditySpotQuoteId() { return commoditySpotQuoteId_; }
std::string& dayCountId() { return dayCountId_; }
std::string& interpolationMethod() { return interpolationMethod_; }
std::string& basePriceCurveId() { return basePriceCurveId_; }
std::string& baseYieldCurveId() { return baseYieldCurveId_; }
std::string& yieldCurveId() { return yieldCurveId_; }
bool& extrapolation() { return extrapolation_; }
std::string& conventionsId() { return conventionsId_; }
std::string& baseConventionsId() { return baseConventionsId_; }
bool& addBasis() { return addBasis_; }
QuantLib::Natural& monthOffset() { return monthOffset_; }
bool& averageBase() { return averageBase_; }
void setPriceSegments(const std::map<unsigned short, PriceSegment>& priceSegments) {
priceSegments_ = priceSegments;
}
void setBootstrapConfig(const BootstrapConfig& bootstrapConfig) { bootstrapConfig_ = bootstrapConfig; }
//@}
private:
//! Populate any dependent curve IDs.
void populateRequiredCurveIds();
//! Process price segments when configuring a Piecewise curve.
void processSegments(std::vector<PriceSegment> priceSegments);
Type type_;
vector<string> fwdQuotes_;
std::string currency_;
std::string commoditySpotQuoteId_;
std::string dayCountId_;
std::string interpolationMethod_;
std::string basePriceCurveId_;
std::string baseYieldCurveId_;
std::string yieldCurveId_;
bool extrapolation_;
std::string conventionsId_;
std::string baseConventionsId_;
bool addBasis_;
QuantLib::Natural monthOffset_;
bool averageBase_;
/*! The map key is the internal priority of the price segment and does not necessarily map the PriceSegment's
priority member value. We are allowing here for the priority to be unspecified in the PriceSegment during
configuration.
*/
std::map<unsigned short, PriceSegment> priceSegments_;
boost::optional<BootstrapConfig> bootstrapConfig_;
};
} // namespace data
} // namespace ore
|
[STATEMENT]
lemma pders_coeffs_sgn_eq:"map (\<lambda>p. sgn(poly p 0)) (pders p) = map sgn (coeffs p)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
[PROOF STEP]
proof (induct "degree p" arbitrary:p)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>p. 0 = degree p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
2. \<And>x p. \<lbrakk>\<And>p. x = degree p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p); Suc x = degree p\<rbrakk> \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
[PROOF STEP]
case 0
[PROOF STATE]
proof (state)
this:
0 = degree p
goal (2 subgoals):
1. \<And>p. 0 = degree p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
2. \<And>x p. \<lbrakk>\<And>p. x = degree p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p); Suc x = degree p\<rbrakk> \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
0 = degree p
[PROOF STEP]
obtain a where "p=[:a:]"
[PROOF STATE]
proof (prove)
using this:
0 = degree p
goal (1 subgoal):
1. (\<And>a. p = [:a:] \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using degree_eq_zeroE
[PROOF STATE]
proof (prove)
using this:
0 = degree p
\<lbrakk>degree ?p = 0; \<And>a. ?p = [:a:] \<Longrightarrow> ?thesis\<rbrakk> \<Longrightarrow> ?thesis
goal (1 subgoal):
1. (\<And>a. p = [:a:] \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
p = [:a:]
goal (2 subgoals):
1. \<And>p. 0 = degree p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
2. \<And>x p. \<lbrakk>\<And>p. x = degree p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p); Suc x = degree p\<rbrakk> \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
p = [:a:]
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
p = [:a:]
goal (1 subgoal):
1. map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
[PROOF STEP]
by (auto simp: pders.simps)
[PROOF STATE]
proof (state)
this:
map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
goal (1 subgoal):
1. \<And>x p. \<lbrakk>\<And>p. x = degree p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p); Suc x = degree p\<rbrakk> \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x p. \<lbrakk>\<And>p. x = degree p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p); Suc x = degree p\<rbrakk> \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
[PROOF STEP]
case (Suc x)
[PROOF STATE]
proof (state)
this:
x = degree ?p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders ?p) = map sgn (coeffs ?p)
Suc x = degree p
goal (1 subgoal):
1. \<And>x p. \<lbrakk>\<And>p. x = degree p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p); Suc x = degree p\<rbrakk> \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
x = degree ?p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders ?p) = map sgn (coeffs ?p)
Suc x = degree p
[PROOF STEP]
have "pderiv p\<noteq>0" "p\<noteq>0"
[PROOF STATE]
proof (prove)
using this:
x = degree ?p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders ?p) = map sgn (coeffs ?p)
Suc x = degree p
goal (1 subgoal):
1. pderiv p \<noteq> 0 &&& p \<noteq> 0
[PROOF STEP]
using pderiv_eq_0_iff
[PROOF STATE]
proof (prove)
using this:
x = degree ?p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders ?p) = map sgn (coeffs ?p)
Suc x = degree p
(pderiv ?p = 0) = (degree ?p = 0)
goal (1 subgoal):
1. pderiv p \<noteq> 0 &&& p \<noteq> 0
[PROOF STEP]
by force+
[PROOF STATE]
proof (state)
this:
pderiv p \<noteq> 0
p \<noteq> 0
goal (1 subgoal):
1. \<And>x p. \<lbrakk>\<And>p. x = degree p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p); Suc x = degree p\<rbrakk> \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
[PROOF STEP]
have "map (\<lambda>p. sgn (poly p 0)) (pders p)
= sgn (poly p 0)# map (\<lambda>p. sgn (poly p 0)) (pders (pderiv p))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. map (\<lambda>p. sgn (poly p 0)) (pders p) = sgn (poly p 0) # map (\<lambda>p. sgn (poly p 0)) (pders (pderiv p))
[PROOF STEP]
apply (subst pders.simps)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. map (\<lambda>p. sgn (poly p 0)) (if p = 0 then [] else p # pders (pderiv p)) = sgn (poly p 0) # map (\<lambda>p. sgn (poly p 0)) (pders (pderiv p))
[PROOF STEP]
using \<open>p\<noteq>0\<close>
[PROOF STATE]
proof (prove)
using this:
p \<noteq> 0
goal (1 subgoal):
1. map (\<lambda>p. sgn (poly p 0)) (if p = 0 then [] else p # pders (pderiv p)) = sgn (poly p 0) # map (\<lambda>p. sgn (poly p 0)) (pders (pderiv p))
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
map (\<lambda>p. sgn (poly p 0)) (pders p) = sgn (poly p 0) # map (\<lambda>p. sgn (poly p 0)) (pders (pderiv p))
goal (1 subgoal):
1. \<And>x p. \<lbrakk>\<And>p. x = degree p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p); Suc x = degree p\<rbrakk> \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
map (\<lambda>p. sgn (poly p 0)) (pders p) = sgn (poly p 0) # map (\<lambda>p. sgn (poly p 0)) (pders (pderiv p))
goal (1 subgoal):
1. \<And>x p. \<lbrakk>\<And>p. x = degree p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p); Suc x = degree p\<rbrakk> \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
[PROOF STEP]
have "... = sgn (coeff p 0) # map sgn (coeffs (pderiv p))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sgn (poly p 0) # map (\<lambda>p. sgn (poly p 0)) (pders (pderiv p)) = sgn (coeff p 0) # map sgn (coeffs (pderiv p))
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. sgn (poly p 0) # map (\<lambda>p. sgn (poly p 0)) (pders (pderiv p)) = sgn (coeff p 0) # map sgn (coeffs (pderiv p))
[PROOF STEP]
have "sgn (poly p 0) = sgn (coeff p 0)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sgn (poly p 0) = sgn (coeff p 0)
[PROOF STEP]
by (simp add: poly_0_coeff_0)
[PROOF STATE]
proof (state)
this:
sgn (poly p 0) = sgn (coeff p 0)
goal (1 subgoal):
1. sgn (poly p 0) # map (\<lambda>p. sgn (poly p 0)) (pders (pderiv p)) = sgn (coeff p 0) # map sgn (coeffs (pderiv p))
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
sgn (poly p 0) = sgn (coeff p 0)
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
sgn (poly p 0) = sgn (coeff p 0)
goal (1 subgoal):
1. sgn (poly p 0) # map (\<lambda>p. sgn (poly p 0)) (pders (pderiv p)) = sgn (coeff p 0) # map sgn (coeffs (pderiv p))
[PROOF STEP]
apply (subst Suc(1))
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. sgn (poly p 0) = sgn (coeff p 0) \<Longrightarrow> x = degree (pderiv p)
2. sgn (poly p 0) = sgn (coeff p 0) \<Longrightarrow> sgn (poly p 0) # map sgn (coeffs (pderiv p)) = sgn (coeff p 0) # map sgn (coeffs (pderiv p))
[PROOF STEP]
subgoal
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sgn (poly p 0) = sgn (coeff p 0) \<Longrightarrow> x = degree (pderiv p)
[PROOF STEP]
by (metis Suc.hyps(2) degree_pderiv diff_Suc_1)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sgn (poly p 0) = sgn (coeff p 0) \<Longrightarrow> sgn (poly p 0) # map sgn (coeffs (pderiv p)) = sgn (coeff p 0) # map sgn (coeffs (pderiv p))
[PROOF STEP]
subgoal
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sgn (poly p 0) = sgn (coeff p 0) \<Longrightarrow> sgn (poly p 0) # map sgn (coeffs (pderiv p)) = sgn (coeff p 0) # map sgn (coeffs (pderiv p))
[PROOF STEP]
by auto
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
sgn (poly p 0) # map (\<lambda>p. sgn (poly p 0)) (pders (pderiv p)) = sgn (coeff p 0) # map sgn (coeffs (pderiv p))
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
sgn (poly p 0) # map (\<lambda>p. sgn (poly p 0)) (pders (pderiv p)) = sgn (coeff p 0) # map sgn (coeffs (pderiv p))
goal (1 subgoal):
1. \<And>x p. \<lbrakk>\<And>p. x = degree p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p); Suc x = degree p\<rbrakk> \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
sgn (poly p 0) # map (\<lambda>p. sgn (poly p 0)) (pders (pderiv p)) = sgn (coeff p 0) # map sgn (coeffs (pderiv p))
goal (1 subgoal):
1. \<And>x p. \<lbrakk>\<And>p. x = degree p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p); Suc x = degree p\<rbrakk> \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
[PROOF STEP]
have "... = map sgn (coeffs p)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sgn (coeff p 0) # map sgn (coeffs (pderiv p)) = map sgn (coeffs p)
[PROOF STEP]
proof (rule nth_equalityI)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. length (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) = length (map sgn (coeffs p))
2. \<And>i. i < length (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) \<Longrightarrow> (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
[PROOF STEP]
show p_length:"length (sgn (coeff p 0) # map sgn (coeffs (pderiv p)))
= length (map sgn (coeffs p))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. length (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) = length (map sgn (coeffs p))
[PROOF STEP]
by (metis Suc.hyps(2) \<open>p \<noteq> 0\<close> \<open>pderiv p \<noteq> 0\<close> degree_pderiv diff_Suc_1 length_Cons
length_coeffs_degree length_map)
[PROOF STATE]
proof (state)
this:
length (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) = length (map sgn (coeffs p))
goal (1 subgoal):
1. \<And>i. i < length (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) \<Longrightarrow> (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
[PROOF STEP]
show "(sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i"
if "i < length (sgn (coeff p 0) # map sgn (coeffs (pderiv p)))" for i
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
[PROOF STEP]
show "(sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
[PROOF STEP]
proof (cases i)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. i = 0 \<Longrightarrow> (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
2. \<And>nat. i = Suc nat \<Longrightarrow> (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
[PROOF STEP]
case 0
[PROOF STATE]
proof (state)
this:
i = 0
goal (2 subgoals):
1. i = 0 \<Longrightarrow> (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
2. \<And>nat. i = Suc nat \<Longrightarrow> (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
i = 0
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
i = 0
goal (1 subgoal):
1. (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
[PROOF STEP]
by (simp add: \<open>p \<noteq> 0\<close> coeffs_nth)
[PROOF STATE]
proof (state)
this:
(sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
goal (1 subgoal):
1. \<And>nat. i = Suc nat \<Longrightarrow> (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>nat. i = Suc nat \<Longrightarrow> (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
[PROOF STEP]
case (Suc i')
[PROOF STATE]
proof (state)
this:
i = Suc i'
goal (1 subgoal):
1. \<And>nat. i = Suc nat \<Longrightarrow> (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
i = Suc i'
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
i = Suc i'
goal (1 subgoal):
1. (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
[PROOF STEP]
using that p_length
[PROOF STATE]
proof (prove)
using this:
i = Suc i'
i < length (sgn (coeff p 0) # map sgn (coeffs (pderiv p)))
length (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) = length (map sgn (coeffs p))
goal (1 subgoal):
1. (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
[PROOF STEP]
apply simp
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>i = Suc i'; i' < length (coeffs (pderiv p)); Suc (length (coeffs (pderiv p))) = length (coeffs p)\<rbrakk> \<Longrightarrow> sgn (coeffs (pderiv p) ! i') = sgn (coeffs p ! Suc i')
[PROOF STEP]
apply (subst (1 2) coeffs_nth)
[PROOF STATE]
proof (prove)
goal (5 subgoals):
1. \<lbrakk>i = Suc i'; i' < length (coeffs (pderiv p)); Suc (length (coeffs (pderiv p))) = length (coeffs p)\<rbrakk> \<Longrightarrow> p \<noteq> 0
2. \<lbrakk>i = Suc i'; i' < length (coeffs (pderiv p)); Suc (length (coeffs (pderiv p))) = length (coeffs p)\<rbrakk> \<Longrightarrow> Suc i' \<le> degree p
3. \<lbrakk>i = Suc i'; i' < length (coeffs (pderiv p)); Suc (length (coeffs (pderiv p))) = length (coeffs p)\<rbrakk> \<Longrightarrow> pderiv p \<noteq> 0
4. \<lbrakk>i = Suc i'; i' < length (coeffs (pderiv p)); Suc (length (coeffs (pderiv p))) = length (coeffs p)\<rbrakk> \<Longrightarrow> i' \<le> degree (pderiv p)
5. \<lbrakk>i = Suc i'; i' < length (coeffs (pderiv p)); Suc (length (coeffs (pderiv p))) = length (coeffs p)\<rbrakk> \<Longrightarrow> sgn (coeff (pderiv p) i') = sgn (coeff p (Suc i'))
[PROOF STEP]
by (auto simp add: \<open>p \<noteq> 0\<close> \<open>pderiv p \<noteq> 0\<close> length_coeffs_degree coeff_pderiv sgn_mult)
[PROOF STATE]
proof (state)
this:
(sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
(sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! i = map sgn (coeffs p) ! i
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
?i < length (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) \<Longrightarrow> (sgn (coeff p 0) # map sgn (coeffs (pderiv p))) ! ?i = map sgn (coeffs p) ! ?i
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
sgn (coeff p 0) # map sgn (coeffs (pderiv p)) = map sgn (coeffs p)
goal (1 subgoal):
1. \<And>x p. \<lbrakk>\<And>p. x = degree p \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p); Suc x = degree p\<rbrakk> \<Longrightarrow> map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
[PROOF STEP]
finally
[PROOF STATE]
proof (chain)
picking this:
map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
goal (1 subgoal):
1. map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
map (\<lambda>p. sgn (poly p 0)) (pders p) = map sgn (coeffs p)
goal:
No subgoals!
[PROOF STEP]
qed
|
If the degree of a polynomial $p$ is less than $n$, and the degree of a polynomial $q$ is less than $n$, then the degree of $p + q$ is less than $n$.
|
##### Copyright 2020 The TensorFlow Authors.
```python
#@title 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
#
# https://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.
```
# MNIST classification
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/quantum/tutorials/mnist">View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/quantum/blob/master/docs/tutorials/mnist.ipynb">Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/tensorflow/quantum/blob/master/docs/tutorials/mnist.ipynb">View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/quantum/docs/tutorials/mnist.ipynb">Download notebook</a>
</td>
</table>
This tutorial builds a quantum neural network (QNN) to classify a simplified version of MNIST, similar to the approach used in <a href="https://arxiv.org/pdf/1802.06002.pdf" class="external">Farhi et al</a>. The performance of the quantum neural network on this classical data problem is compared with a classical neural network.
## Setup
```python
try:
# %tensorflow_version only works in Colab.
%tensorflow_version 2.x
except Exception:
pass
```
Install TensorFlow Quantum:
```python
!pip install tensorflow-quantum
```
Now import TensorFlow and the module dependencies:
```python
import tensorflow as tf
import tensorflow_quantum as tfq
import cirq
import sympy
import numpy as np
import seaborn as sns
import collections
# visualization tools
%matplotlib inline
import matplotlib.pyplot as plt
from cirq.contrib.svg import SVGCircuit
```
## 1. Load the data
In this tutorial you will build a binary classifier to distinguish between the digits 3 and 6, following <a href="https://arxiv.org/pdf/1802.06002.pdf" class="external">Farhi et al.</a> This section covers the data handling that:
- Loads the raw data from Keras.
- Filters the dataset to only 3s and 6s.
- Downscales the images so they fit can fit in a quantum computer.
- Removes any contradictory examples.
- Converts the binary images to Cirq circuits.
- Converts the Circ circuits to TensorFlow Quantum circuits.
### 1.1 Load the raw data
Load the MNIST dataset distributed with Keras.
```python
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# Rescale the images from [0,255] to the [0.0,1.0] range.
x_train, x_test = x_train[..., np.newaxis]/255.0, x_test[..., np.newaxis]/255.0
print("Number of original training examples:", len(x_train))
print("Number of original test examples:", len(x_train))
```
Filter the dataset to keep just the 3s and 6s, remove the other classes. At the same time convert the label, `y`, to boolean: `True` for `3` and `False` for 6.
```python
def filter_36(x, y):
keep = (y == 3) | (y == 6)
x, y = x[keep], y[keep]
y = y == 3
return x,y
```
```python
x_train, y_train = filter_36(x_train, y_train)
x_test, y_test = filter_36(x_test, y_test)
print("Number of filtered training examples:", len(x_train))
print("Number of filtered test examples:", len(x_test))
```
Show the first example:
```python
print(y_train[0])
plt.imshow(x_train[0, :, :, 0])
plt.colorbar()
```
### 1.2 Downscale the images
An image size of 28x28 is much too large for current quantum computers. Resize the image down to 4x4:
```python
x_train_small = tf.image.resize(x_train, (4,4)).numpy()
x_test_small = tf.image.resize(x_test, (4,4)).numpy()
```
Again, display the first training exampleβafter resize:
```python
print(y_train[0])
plt.imshow(x_train_small[0,:,:,0], vmin=0, vmax=1)
plt.colorbar()
```
### 1.3 Remove contradictory examples
From section *3.3 Learning to Distinguish Digits* of <a href="https://arxiv.org/pdf/1802.06002.pdf" class="external">Farhi et al.</a>, filter the dataset to remove images that are labeled as belonging to both classes.
This is not a standard machine-learning procedure, but is included in the interest of following the paper.
```python
def remove_contradicting(xs, ys):
mapping = collections.defaultdict(set)
# Determine the set of labels for each unique image:
for x,y in zip(xs,ys):
mapping[tuple(x.flatten())].add(y)
new_x = []
new_y = []
for x,y in zip(xs, ys):
labels = mapping[tuple(x.flatten())]
if len(labels) == 1:
new_x.append(x)
new_y.append(list(labels)[0])
else:
# Throw out images that match more than one label.
pass
num_3 = sum(1 for value in mapping.values() if True in value)
num_6 = sum(1 for value in mapping.values() if False in value)
num_both = sum(1 for value in mapping.values() if len(value) == 2)
print("Number of unique images:", len(mapping.values()))
print("Number of 3s: ", num_3)
print("Number of 6s: ", num_6)
print("Number of contradictory images: ", num_both)
print()
print("Initial number of examples: ", len(xs))
print("Remaining non-contradictory examples: ", len(new_x))
return np.array(new_x), np.array(new_y)
```
The resulting counts do not closely match the reported values, but the exact procedure is not specified.
It is also worth noting here that applying filtering contradictory examples at this point does not totally prevent the model from receiving contradictory training examples: the next step binarizes the data which will cause more collisions.
```python
x_train_nocon, y_train_nocon = remove_contradicting(x_train_small, y_train)
```
### 1.3 Encode the data as quantum circuits
To process images using a quantum computer, <a href="https://arxiv.org/pdf/1802.06002.pdf" class="external">Farhi et al.</a> proposed representing each pixel with a qubit, with the state depending on the value of the pixel. The first step is to convert to a binary encoding.
```python
THRESHOLD = 0.5
x_train_bin = np.array(x_train_nocon > THRESHOLD, dtype=np.float32)
x_test_bin = np.array(x_test_small > THRESHOLD, dtype=np.float32)
```
The qubits at pixel indices with values that exceed a threshold, are rotated through an $X$ gate.
```python
def convert_to_circuit(image):
"""Encode truncated classical image into quantum datapoint."""
values = np.ndarray.flatten(image)
qubits = cirq.GridQubit.rect(4, 4)
circuit = cirq.Circuit()
for i, value in enumerate(values):
if value:
circuit.append(cirq.X(qubits[i]))
return circuit
x_train_circ = [convert_to_circuit(x) for x in x_train_bin]
x_test_circ = [convert_to_circuit(x) for x in x_test_bin]
```
Here is the circuit created for the first example (circuit diagrams do not show qubits with zero gates):
```python
SVGCircuit(x_train_circ[0])
```
Compare this circuit to the indices where the image value exceeds the threshold:
```python
bin_img = x_train_bin[0,:,:,0]
indices = np.array(np.where(bin_img)).T
indices
```
Convert these `Cirq` circuits to tensors for `tfq`:
```python
x_train_tfcirc = tfq.convert_to_tensor(x_train_circ)
x_test_tfcirc = tfq.convert_to_tensor(x_test_circ)
```
## 2. Quantum neural network
There is little guidance for a quantum circuit structure that classifies images. Since the classification is based on the expectation of the readout qubit, <a href="https://arxiv.org/pdf/1802.06002.pdf" class="external">Farhi et al.</a> propose using two qubit gates, with the readout qubit always acted upon. This is similar in some ways to running small a <a href="https://arxiv.org/abs/1511.06464" class="external">Unitary RNN</a> across the pixels.
### 2.1 Build the model circuit
This following example shows this layered approach. Each layer uses *n* instances of the same gate, with each of the data qubits acting on the readout qubit.
Start with a simple class that will add a layer of these gates to a circuit:
```python
class CircuitLayerBuilder():
def __init__(self, data_qubits, readout):
self.data_qubits = data_qubits
self.readout = readout
def add_layer(self, circuit, gate, prefix):
for i, qubit in enumerate(self.data_qubits):
symbol = sympy.Symbol(prefix + '-' + str(i))
circuit.append(gate(qubit, self.readout)**symbol)
```
Build an example circuit layer to see how it looks:
```python
demo_builder = CircuitLayerBuilder(data_qubits = cirq.GridQubit.rect(4,1),
readout=cirq.GridQubit(-1,-1))
circuit = cirq.Circuit()
demo_builder.add_layer(circuit, gate = cirq.XX, prefix='xx')
SVGCircuit(circuit)
```
Now build a two-layered model, matching the data-circuit size, and include the preparation and readout operations.
```python
def create_quantum_model():
"""Create a QNN model circuit and readout operation to go along with it."""
data_qubits = cirq.GridQubit.rect(4, 4) # a 4x4 grid.
readout = cirq.GridQubit(-1, -1) # a single qubit at [-1,-1]
circuit = cirq.Circuit()
# Prepare the readout qubit.
circuit.append(cirq.X(readout))
circuit.append(cirq.H(readout))
builder = CircuitLayerBuilder(
data_qubits = data_qubits,
readout=readout)
# Then add layers (experiment by adding more).
builder.add_layer(circuit, cirq.XX, "xx1")
builder.add_layer(circuit, cirq.ZZ, "zz1")
# Finally, prepare the readout qubit.
circuit.append(cirq.H(readout))
return circuit, cirq.Z(readout)
```
```python
model_circuit, model_readout = create_quantum_model()
```
### 2.2 Wrap the model-circuit in a tfq-keras model
Build the Keras model with the quantum components. This model is fed the "quantum data", from `x_train_circ`, that encodes the classical data. It uses a *Parametrized Quantum Circuit* layer, `tfq.layers.PQC`, to train the model circuit, on the quantum data.
To classify these images, <a href="https://arxiv.org/pdf/1802.06002.pdf" class="external">Farhi et al.</a> proposed taking the expectation of a readout qubit in a parameterized circuit. The expectation returns a value between 1 and -1.
```python
# Build the Keras model.
model = tf.keras.Sequential([
# The input is the data-circuit, encoded as a tf.string
tf.keras.layers.Input(shape=(), dtype=tf.string),
# The PQC layer returns the expected value of the readout gate, range [-1,1].
tfq.layers.PQC(model_circuit, model_readout),
])
```
Next, describe the training procedure to the model, using the `compile` method.
Since the the expected readout is in the range `[-1,1]`, optimizing the hinge loss is a somewhat natural fit.
Note: Another valid approach would be to shift the output range to `[0,1]`, and treat it as the probability the model assigns to class `3`. This could be used with a standard a `tf.losses.BinaryCrossentropy` loss.
To use the hinge loss here you need to make two small adjustments. First convert the labels, `y_train`, from boolean to `[-1,1]`, as expected by the hinge loss.
```python
y_train_hinge = 2.0*y_train-1.0
y_test_hinge = 2.0*y_test-1.0
```
Second, use a custiom `hinge_accuracy` metric that correctly handles `[-1, 1]` as the `y_true` labels argument.
`tf.losses.BinaryAccuracy(threshold=0.0)` expects `y_true` to be a boolean, and so can't be used with hinge loss).
```python
def hinge_accuracy(y_true, y_pred):
y_true = tf.squeeze(y_true) > 0.0
y_pred = tf.squeeze(y_pred) > 0.0
result = tf.cast(y_true == y_pred, tf.float32)
return tf.reduce_mean(result)
```
```python
model.compile(
loss=tf.keras.losses.Hinge(),
optimizer=tf.keras.optimizers.Adam(),
metrics=[hinge_accuracy])
```
```python
print(model.summary())
```
### Train the quantum model
Now train the modelβthis takes about 45 min. If you don't want to wait that long, use a small subset of the data (set `NUM_EXAMPLES=500`, below). This doesn't really affect the model's progress during training (it only has 32 parameters, and doesn't need much data to constrain these). Using fewer examples just ends training earlier (5min), but runs long enough to show that it is making progress in the validation logs.
```python
EPOCHS = 3
BATCH_SIZE = 32
NUM_EXAMPLES = len(x_train_tfcirc)
```
```python
x_train_tfcirc_sub = x_train_tfcirc[:NUM_EXAMPLES]
y_train_hinge_sub = y_train_hinge[:NUM_EXAMPLES]
```
Training this model to convergence should achieve >85% accuracy on the test set.
```python
qnn_history = model.fit(
x_train_tfcirc_sub, y_train_hinge_sub,
batch_size=32,
epochs=EPOCHS,
verbose=1,
validation_data=(x_test_tfcirc, y_test_hinge))
qnn_results = model.evaluate(x_test_tfcirc, y_test)
```
Note: The training accuracy reports the average over the epoch. The validation accuracy is evaluated at the end of each epoch.
## 3. Classical neural network
While the quantum neural network works for this simplified MNIST problem, a basic classical neural network can easily outperform a QNN on this task. After a single epoch, a classical neural network can achieve >98% accuracy on the holdout set.
In the following example, a classical neural network is used for for the 3-6 classification problem using the entire 28x28 image instead of subsampling the image. This easily converges to nearly 100% accuracy of the test set.
```python
def create_classical_model():
# A simple model based off LeNet from https://keras.io/examples/mnist_cnn/
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(32, [3, 3], activation='relu', input_shape=(28,28,1)))
model.add(tf.keras.layers.Conv2D(64, [3, 3], activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))
model.add(tf.keras.layers.Dropout(0.25))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(1))
return model
model = create_classical_model()
model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
optimizer=tf.keras.optimizers.Adam(),
metrics=['accuracy'])
model.summary()
```
```python
model.fit(x_train,
y_train,
batch_size=128,
epochs=1,
verbose=1,
validation_data=(x_test, y_test))
cnn_results = model.evaluate(x_test, y_test)
```
The above model has nearly 1.2M parameters. For a more fair comparison, try a 37-parameter model, on the subsampled images:
```python
def create_fair_classical_model():
# A simple model based off LeNet from https://keras.io/examples/mnist_cnn/
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(4,4,1)))
model.add(tf.keras.layers.Dense(2, activation='relu'))
model.add(tf.keras.layers.Dense(1))
return model
model = create_fair_classical_model()
model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
optimizer=tf.keras.optimizers.Adam(),
metrics=['accuracy'])
model.summary()
```
```python
model.fit(x_train_bin,
y_train_nocon,
batch_size=128,
epochs=20,
verbose=2,
validation_data=(x_test_bin, y_test))
fair_nn_results = model.evaluate(x_test_bin, y_test)
```
## 4. Comparison
Higher resolution input and a more powerful model make this problem easy for the CNN. While a classical model of similar power (~32 parameters) trains to a similar accuracy in a fraction of the time. One way or the other, the classical neural network easily outperforms the quantum neural network. For classical data, it is difficult to beat a classical neural network.
```python
qnn_accuracy = qnn_results[1]
cnn_accuracy = cnn_results[1]
fair_nn_accuracy = fair_nn_results[1]
sns.barplot(["Quantum", "Classical, full", "Classical, fair"],
[qnn_accuracy, cnn_accuracy, fair_nn_accuracy])
```
|
module Parser.Source
import public Parser.Lexer.Source
import public Parser.Rule.Source
import public Parser.Unlit
import System.File
import Utils.Either
%default total
export
runParserTo : {e : _} ->
Maybe LiterateStyle -> (WithBounds Token -> Bool) ->
String -> Grammar Token e ty -> Either (ParseError Token) ty
runParserTo lit pred str p
= do str <- mapError LitFail $ unlit lit str
toks <- mapError LexFail $ lexTo pred str
parsed <- mapError toGenericParsingError $ parse p toks
Right (fst parsed)
export
runParser : {e : _} ->
Maybe LiterateStyle -> String -> Grammar Token e ty -> Either (ParseError Token) ty
runParser lit = runParserTo lit (const False)
export covering
parseFile : (fn : String) -> Rule ty -> IO (Either (ParseError Token) ty)
parseFile fn p
= do Right str <- readFile fn
| Left err => pure (Left (FileFail err))
pure (runParser (isLitFile fn) str p)
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*/
#include "MessagingFixture.h"
#include "qpid/sys/Runnable.h"
#include "qpid/sys/Thread.h"
#include <boost/lexical_cast.hpp>
namespace qpid {
namespace tests {
QPID_AUTO_TEST_SUITE(MessagingThreadTests)
using namespace messaging;
using namespace boost::assign;
using namespace std;
struct ReceiveThread : public sys::Runnable {
Receiver receiver;
vector<string> received;
string error;
ReceiveThread(Receiver s) : receiver(s) {}
void run() {
try {
while(true) {
Message m = receiver.fetch(Duration::SECOND*5);
if (m.getContent() == "END") break;
received.push_back(m.getContent());
}
} catch (const NoMessageAvailable& e) {
// Indicates that fetch timed out OR receiver was closed by other thread.
if (!receiver.isClosed()) // timeout
error = e.what();
} catch (const std::exception& e) {
error = e.what();
}
}
};
struct NextReceiverThread : public sys::Runnable {
Session session;
vector<string> received;
string error;
NextReceiverThread(Session s) : session(s) {}
void run() {
try {
while(true) {
Message m = session.nextReceiver(Duration::SECOND*5).fetch();
if (m.getContent() == "END") break;
received.push_back(m.getContent());
}
} catch (const std::exception& e) {
error = e.what();
}
}
};
QPID_AUTO_TEST_CASE(testConcurrentSendReceive) {
MessagingFixture fix;
Sender s = fix.session.createSender("concurrent;{create:always}");
Receiver r = fix.session.createReceiver("concurrent;{create:always,link:{reliability:unreliable}}");
ReceiveThread rt(r);
sys::Thread thread(rt);
const size_t COUNT=100;
for (size_t i = 0; i < COUNT; ++i) {
s.send(Message());
}
s.send(Message("END"));
thread.join();
BOOST_CHECK_EQUAL(rt.error, string());
BOOST_CHECK_EQUAL(COUNT, rt.received.size());
}
QPID_AUTO_TEST_CASE(testCloseBusyReceiver) {
MessagingFixture fix;
Receiver r = fix.session.createReceiver("closeReceiver;{create:always}");
ReceiveThread rt(r);
sys::Thread thread(rt);
sys::usleep(1000); // Give the receive thread time to block.
r.close();
thread.join();
BOOST_CHECK_EQUAL(rt.error, string());
// Fetching on closed receiver should fail.
Message m;
BOOST_CHECK(!r.fetch(m, Duration(0)));
BOOST_CHECK_THROW(r.fetch(Duration(0)), NoMessageAvailable);
}
QPID_AUTO_TEST_CASE(testCloseSessionBusyReceiver) {
MessagingFixture fix;
Receiver r = fix.session.createReceiver("closeSession;{create:always}");
ReceiveThread rt(r);
sys::Thread thread(rt);
sys::usleep(1000); // Give the receive thread time to block.
fix.session.close();
thread.join();
BOOST_CHECK_EQUAL(rt.error, string());
// Fetching on closed receiver should fail.
Message m;
BOOST_CHECK(!r.fetch(m, Duration(0)));
BOOST_CHECK_THROW(r.fetch(Duration(0)), NoMessageAvailable);
}
QPID_AUTO_TEST_CASE(testConcurrentSendNextReceiver) {
MessagingFixture fix;
Receiver r = fix.session.createReceiver("concurrent;{create:always,link:{reliability:unreliable}}");
const size_t COUNT=100;
r.setCapacity(COUNT);
NextReceiverThread rt(fix.session);
sys::Thread thread(rt);
sys::usleep(1000); // Give the receive thread time to block.
Sender s = fix.session.createSender("concurrent;{create:always}");
for (size_t i = 0; i < COUNT; ++i) {
s.send(Message());
}
s.send(Message("END"));
thread.join();
BOOST_CHECK_EQUAL(rt.error, string());
BOOST_CHECK_EQUAL(COUNT, rt.received.size());
}
QPID_AUTO_TEST_SUITE_END()
}} // namespace qpid::tests
|
import to_mathlib
import data.fin.basic
import Rings.ToMathlib.fin
namespace dvector
variables {Ξ± : Type*} {n : β}
lemma nil_append (as : dvector Ξ± n) :
dvector.append dvector.nil as = as :=
by simp
/-- Converts a dvector into an n-ary tuple -/
@[simp] def fin_val (as : dvector Ξ± n) : fin n β Ξ± :=
Ξ» k, dvector.nth' as k
@[simp] lemma cons_nth'_succ_eq_nth' {n} {x : Ξ±} {as : dvector Ξ± n} {k : fin n} :
(dvector.cons x as).nth' (k.succ) = as.nth' k :=
begin
unfold dvector.nth',
simp,
end
/-- x_val is the same data as concatenation of dvectors -/
lemma fin_val_eq_x_val {x : Ξ±} {as : dvector Ξ± n} :
fin_val (dvector.cons x as) = fin.x_val x (fin_val as) :=
funext (
@fin.cases n
(Ξ» k, fin_val (dvector.cons x as) k = fin.x_val x (fin_val as) k)
rfl
(Ξ» k, begin unfold fin_val, simp, end)
)
lemma nth_eq_succ_nth : Ξ {k n : β} {as : dvector Ξ± (n + 1)} {h : k < n},
as.nth k (lt_trans h (by simp)) = (dvector.remove_mth (n + 2) as).nth k h
| k nat.zero (dvector.cons a _) h := by {exfalso, simpa using h}
| nat.zero (nat.succ n) (dvector.cons a as) h := by simp
| (nat.succ k) (nat.succ n) (dvector.cons a as) h :=
by {simpa using nth_eq_succ_nth}
def of_list : Ξ (as : list Ξ±), dvector Ξ± (list.length as)
| list.nil := dvector.nil
| (list.cons a as) := dvector.cons a (of_list as)
def reverse : Ξ {n : β} (v : dvector Ξ± n),
dvector Ξ± n
| nat.zero _ := dvector.nil
| (nat.succ n) (dvector.cons a v) := dvector.concat (reverse v) a
/-- if you append and take nth its the same as just taking nth for small n-/
lemma nth_append_small : Ξ {xl yl : β}
{xs : dvector Ξ± xl} {ys : dvector Ξ± yl} {n : β} (h : n < xl),
(dvector.append xs ys).nth n (nat.lt_of_lt_of_le h (nat.le_add_left _ _))
= xs.nth n h
| 0 yl xs ys n h := by simpa using h
| (nat.succ xl) yl (dvector.cons x xs) ys 0 h := by simp
| (nat.succ xl) yl (dvector.cons x xs) ys (nat.succ n) h :=
begin
simp only [dvector.nth, dvector.append],
rw β (@nth_append_small xl yl xs ys n (nat.succ_lt_succ_iff.1 h)),
refl,
end
/-- if you append and take nth its the same as just taking n - kth for big n-/
lemma nth_append_big : Ξ {xl yl : β}
{xs : dvector Ξ± xl} {ys : dvector Ξ± yl} {n : β}
(hbig : xl β€ n) (h : n < yl + xl),
(dvector.append xs ys).nth n h
= ys.nth (n - xl) ((tsub_lt_iff_right hbig).2 h)
| 0 yl nil ys n hbig h := by simpa
| (nat.succ xl) yl (dvector.cons x xs) ys 0 hbig h :=
begin
exfalso,
exact nat.not_succ_le_zero _ hbig,
end
| (nat.succ xl) yl (dvector.cons x xs) ys (nat.succ n) hbig h :=
begin
simp only [nat.succ_sub_succ_eq_sub, dvector.append, dvector.nth],
apply nth_append_big (nat.le_of_succ_le_succ hbig),
end
lemma nth_cast : Ξ {xl yl k : β}
{xs : dvector Ξ± xl}
(heq : xl = yl) (hk : k < yl),
(dvector.cast heq xs).nth k hk = xs.nth k (by simp [heq, hk])
| 0 yl k nil heq hk :=
(k.not_lt_zero (by simp [heq, hk])).elim
| (nat.succ xl) 0 k (cons x xs) heq hk :=
(nat.succ_ne_zero _ heq).elim
| (nat.succ xl) (nat.succ yl) k (cons x xs) heq hk :=
begin
rw dvector.cast_cons heq x xs,
induction k with k hk,
{simp},
rw dvector.nth_cons _ _ _ (nat.lt_of_succ_lt_succ hk),
exact nth_cast (nat.succ_injective heq) (nat.lt_of_succ_lt_succ hk),
end
lemma nth_of_list : Ξ (l : list Ξ±) (k : β) (h : k < l.length),
(dvector.of_list l).nth k h = list.nth_le l k h
| list.nil k h :=
begin
exfalso,
rw list.length at h,
exact nat.not_lt_zero _ h,
end
| (a :: l) k h :=
begin
rw of_list,
induction k with k hk,
{rw [dvector.nth, list.nth_le]},
{simpa [dvector.nth, list.nth_le, nth_of_list l]},
end
def of_fn : (fin n β Ξ±) β dvector Ξ± n :=
Ξ» f, dvector.cast (list.length_of_fn _) (dvector.of_list (list.of_fn f))
lemma nth_of_fn (as : fin n β Ξ±) (k : β) (hk : k < n) :
(dvector.of_fn as).nth k hk = as β¨ k , hk β© :=
by rw [of_fn, nth_cast, nth_of_list, list.nth_le_of_fn']
lemma nth'_of_fn (as : fin n β Ξ±) (k : fin n) :
(dvector.of_fn as).nth' k = as k :=
by simp only [dvector.nth', nth_of_fn, fin.val_eq_coe, fin.eta]
lemma nth'_of_fn1 (as : fin n β Ξ±) :
(dvector.of_fn as).nth' = as :=
funext $ nth'_of_fn as
--by rw [of_fn, nth_cast, nth_of_list, list.nth_le_of_fn']
def to_list : Ξ {n : β},
dvector Ξ± n β list Ξ±
| 0 as := []
| (nat.succ n) (dvector.cons a as) := list.cons a (to_list as)
lemma to_list_length : Ξ {n : β} {as : dvector Ξ± n},
list.length (to_list as) = n
| 0 as := rfl
| (nat.succ n) (dvector.cons a as) :=
by simp only [to_list, list.length_cons, @to_list_length n as]
lemma ith_chunk_aux {n m : β} (i : fin n) (k : fin m) :
i.val * m + βk < n * m :=
begin
induction n with n hn,
{ apply fin_zero_elim i },
{
rw nat.succ_mul,
cases fin.lt_or_eq_nat i with hi hi,
{
apply add_lt_add _ k.2,
apply lt_of_le_of_lt _ (hn β¨ i.1 , hi β©),
apply le_add_right,
apply le_of_eq,
refl,
},
{ rw [fin.val_eq_coe, hi, add_lt_add_iff_left],
exact k.2, }
}
end
def ith_chunk {n m : β} (i : fin n) (xs : dvector Ξ± (n * m)) :
dvector Ξ± m :=
of_fn (Ξ» k, dvector.nth xs (i.1 * m + k) (dvector.ith_chunk_aux i k))
lemma nth'_eq {Ξ±} {n} (ys : dvector Ξ± n) :
(Ξ» (i : fin n), ys.nth i i.2) = ys.nth' :=
begin
funext, rw dvector.nth', refl,
end
lemma ith_chunk_nth {n m : β} (i : fin n) (xs : dvector Ξ± (n * m))
(l : β) (hl : l < m) :
dvector.nth (dvector.ith_chunk i xs) l hl =
xs.nth (i.1 * m + l) (dvector.ith_chunk_aux i β¨ l , hl β©) :=
by simpa only [dvector.ith_chunk, dvector.nth_of_fn]
lemma nth_remove_mth_big_m : Ξ {n m} (xs : dvector Ξ± (n+1)) {k : β}
(hk : k < n) (hm : k < m),
(dvector.remove_mth m xs).nth k hk
=
xs.nth k (lt_trans hk (nat.lt_succ_self _))
| 0 _ _ k hk hm := false.elim (nat.not_lt_zero _ hk)
| n 0 (dvector.cons y ys) k hk hm := false.elim (nat.not_lt_zero _ hm)
| (n+1) (m+1) (dvector.cons y ys) 0 hk hm :=
begin
simp only [dvector.remove_mth, dvector.nth],
end
| (n+1) (m+1) (dvector.cons y ys) (k+1) hk hm :=
begin
rw [dvector.remove_mth,
dvector.nth_cons y (dvector.remove_mth m ys) _ (nat.succ_lt_succ_iff.mp hk),
dvector.nth_cons y ys _ (lt_trans (nat.lt_succ_self _) hk)],
apply nth_remove_mth_big_m,
rw β nat.succ_lt_succ_iff,
exact hm,
end
lemma ext : Ξ {as bs : dvector Ξ± n},
as = bs β β (i : fin n), as.nth' i = bs.nth' i :=
begin
intros as bs,
induction as with n a as hind, cases bs,
{ simp only [implies_true_iff, eq_self_iff_true] },
{
cases bs with _ b bs,
split,
{
intros heq i, rw heq,
},
{
intros heq,
simp only,
split,
{
specialize heq 0,
simp [dvector.nth', fin.val_zero', dvector.nth] at heq,
exact heq,
},
{
rw hind,
intro i,
specialize heq β¨ i + 1 , nat.succ_lt_succ i.2 β©,
simp [dvector.nth', dvector.nth] at heq,
simp only [dvector.nth'],
convert heq,
},
},
},
end
lemma of_fn_eq_cons_of_fn_succ {f : β β Ξ±} :
of_fn (Ξ» i : fin (n+1), f i) =
cons (f 0) (of_fn (Ξ» (i : fin n), f (i + 1))) :=
begin
rw ext,
intro i,
cases i with i hi,
cases i with i hind,
{ simp only [nth'_of_fn, fin.mk_zero, fin.coe_eq_cast_succ,
fin.coe_succ_eq_succ],
simpa only [dvector.nth', fin.val_zero', dvector.nth], },
{
simp only [nth'_of_fn, dvector.nth', dvector.nth, nth_of_fn],
congr1,
},
end
lemma remove_mth_of_fn_last_aux (i : fin n) :
((i : fin n.succ) : fin n.succ.succ) = (i : fin n.succ.succ) :=
begin
cases i with i hi,
simp only [fin.coe_eq_cast_succ, fin.cast_succ_mk, fin.coe_mk, coe_coe],
ext1,
simp only [fin.coe_of_nat_eq_mod],
rw nat.mod_eq_of_lt (lt_trans hi (nat.lt_succ_self _)),
end
lemma remove_mth_of_fn_last {n : β} : Ξ {f : β β Ξ±},
dvector.remove_mth n (of_fn (Ξ» (i : fin (n+1)), f i))
=
dvector.of_fn (Ξ» i : fin n, f i) :=
begin
induction n with n hn,
{intro f, refl},
{
intro f,
have hrw : (of_fn (Ξ» (i : fin (n+2)), f i))
= cons (f 0) (of_fn (Ξ» i : fin n.succ, f (i + 1))) :=
of_fn_eq_cons_of_fn_succ,
have hrw1 : of_fn (Ξ» (i : fin n.succ), f i)
= cons (f 0) (of_fn (Ξ» i : fin n, f (i + 1))) :=
of_fn_eq_cons_of_fn_succ,
rw hrw,
rw [dvector.remove_mth],
rw hrw1,
congr1,
rw @hn (Ξ» n, f (n + 1)),
},
end
section ulift
def ulift_up {Ξ±} {n} : dvector Ξ± n β dvector (ulift Ξ±) n :=
dvector.map ulift.up
def ulift_down {Ξ±} {n} : dvector (ulift Ξ±) n β dvector Ξ± n :=
dvector.map ulift.down
end ulift
@[simp] protected lemma map_id' : β{n : β} (xs : dvector Ξ± n), xs.map id = xs
| _ dvector.nil := rfl
| _ (dvector.cons x xs) := by { dsimp, simp* }
@[simp] protected lemma map_comp {Ξ² Ξ³ : Type*} :
β{n : β} (xs : dvector Ξ± n) (g : Ξ± β Ξ²) (f : Ξ² β Ξ³),
xs.map (f β g) = (xs.map g).map f
| _ dvector.nil g f := rfl
| _ (dvector.cons x xs) g f := by simp
lemma pmem_nth {xs : dvector Ξ± n} {k : β} (hk : k < n) :
dvector.pmem (xs.nth k hk) xs :=
begin
induction xs with m a xs hind generalizing k,
{ exfalso, apply nat.not_lt_zero _ hk, },
{ cases k with k,
{ exact psum.inl rfl },
{ dsimp only [dvector.nth, dvector.pmem],
apply psum.inr,
apply hind }},
end
lemma pmem_nth' {xs : dvector Ξ± n} {k : fin n} :
dvector.pmem (xs.nth' k) xs := pmem_nth _
lemma cast_nil {Ξ±} (h : 0 = 0) : (dvector.cast h dvector.nil : dvector Ξ± 0) = dvector.nil :=
by refl
lemma of_fn_zero {Ξ± : Type*} (f : fin 0 β Ξ±) : dvector.of_fn f = dvector.nil := rfl
lemma of_fn_eq_cons_of_fn_succ' {Ξ± : Type*} {n : β} {f : fin n.succ β Ξ±} :
dvector.of_fn f = dvector.cons (f 0) (dvector.of_fn (Ξ» (i : fin n), f (i + 1))) :=
begin
set g : β β Ξ± := Ξ» k, ite (k < n.succ) (f k) (f 0) with hg,
have hrw1 : dvector.of_fn f = dvector.of_fn (Ξ» k, g k),
{ congr, ext x, rw hg, simp only [fin.coe_coe_eq_self],
by_cases hx : (x : β) < n.succ,
{ simp [if_pos hx] },
{ exfalso, apply hx x.2 }},
rw hrw1,
rw dvector.of_fn_eq_cons_of_fn_succ,
congr,
ext,
rw hg,
simp only [fin.coe_coe_eq_self],
by_cases hx : (x : β) + 1 < n.succ,
{ simp only [if_pos hx], congr },
{ exfalso, apply hx, apply nat.succ_lt_succ x.2 }
end
end dvector
|
[STATEMENT]
lemma substitute_only_empty:
assumes "const_on f (carrier t) empty"
shows "substitute f T t = t"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. substitute f T t = t
[PROOF STEP]
proof (intro paths_inj set_eqI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. (x \<in> paths (substitute f T t)) = (x \<in> paths t)
[PROOF STEP]
fix xs
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. (x \<in> paths (substitute f T t)) = (x \<in> paths t)
[PROOF STEP]
from assms
[PROOF STATE]
proof (chain)
picking this:
const_on f (carrier t) TTree.empty
[PROOF STEP]
show "xs \<in> paths (substitute f T t) \<longleftrightarrow> xs \<in> paths t"
[PROOF STATE]
proof (prove)
using this:
const_on f (carrier t) TTree.empty
goal (1 subgoal):
1. (xs \<in> paths (substitute f T t)) = (xs \<in> paths t)
[PROOF STEP]
proof (induction xs arbitrary: f t)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>f t. const_on f (carrier t) TTree.empty \<Longrightarrow> ([] \<in> paths (substitute f T t)) = ([] \<in> paths t)
2. \<And>a xs f t. \<lbrakk>\<And>f t. const_on f (carrier t) TTree.empty \<Longrightarrow> (xs \<in> paths (substitute f T t)) = (xs \<in> paths t); const_on f (carrier t) TTree.empty\<rbrakk> \<Longrightarrow> (a # xs \<in> paths (substitute f T t)) = (a # xs \<in> paths t)
[PROOF STEP]
case Nil
[PROOF STATE]
proof (state)
this:
const_on f (carrier t) TTree.empty
goal (2 subgoals):
1. \<And>f t. const_on f (carrier t) TTree.empty \<Longrightarrow> ([] \<in> paths (substitute f T t)) = ([] \<in> paths t)
2. \<And>a xs f t. \<lbrakk>\<And>f t. const_on f (carrier t) TTree.empty \<Longrightarrow> (xs \<in> paths (substitute f T t)) = (xs \<in> paths t); const_on f (carrier t) TTree.empty\<rbrakk> \<Longrightarrow> (a # xs \<in> paths (substitute f T t)) = (a # xs \<in> paths t)
[PROOF STEP]
thus ?case
[PROOF STATE]
proof (prove)
using this:
const_on f (carrier t) TTree.empty
goal (1 subgoal):
1. ([] \<in> paths (substitute f T t)) = ([] \<in> paths t)
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
([] \<in> paths (substitute f T t)) = ([] \<in> paths t)
goal (1 subgoal):
1. \<And>a xs f t. \<lbrakk>\<And>f t. const_on f (carrier t) TTree.empty \<Longrightarrow> (xs \<in> paths (substitute f T t)) = (xs \<in> paths t); const_on f (carrier t) TTree.empty\<rbrakk> \<Longrightarrow> (a # xs \<in> paths (substitute f T t)) = (a # xs \<in> paths t)
[PROOF STEP]
case (Cons x xs f t)
[PROOF STATE]
proof (state)
this:
const_on ?f (carrier ?t) TTree.empty \<Longrightarrow> (xs \<in> paths (substitute ?f T ?t)) = (xs \<in> paths ?t)
const_on f (carrier t) TTree.empty
goal (1 subgoal):
1. \<And>a xs f t. \<lbrakk>\<And>f t. const_on f (carrier t) TTree.empty \<Longrightarrow> (xs \<in> paths (substitute f T t)) = (xs \<in> paths t); const_on f (carrier t) TTree.empty\<rbrakk> \<Longrightarrow> (a # xs \<in> paths (substitute f T t)) = (a # xs \<in> paths t)
[PROOF STEP]
note const_onD[OF Cons.prems carrier_possible, where y = x, simp]
[PROOF STATE]
proof (state)
this:
possible t x \<Longrightarrow> f x = TTree.empty
goal (1 subgoal):
1. \<And>a xs f t. \<lbrakk>\<And>f t. const_on f (carrier t) TTree.empty \<Longrightarrow> (xs \<in> paths (substitute f T t)) = (xs \<in> paths t); const_on f (carrier t) TTree.empty\<rbrakk> \<Longrightarrow> (a # xs \<in> paths (substitute f T t)) = (a # xs \<in> paths t)
[PROOF STEP]
have [simp]: "possible t x \<Longrightarrow> f_nxt f T x = f"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. possible t x \<Longrightarrow> f_nxt f T x = f
[PROOF STEP]
by (rule f_nxt_empty', rule const_onD[OF Cons.prems carrier_possible, where y = x])
[PROOF STATE]
proof (state)
this:
possible t x \<Longrightarrow> f_nxt f T x = f
goal (1 subgoal):
1. \<And>a xs f t. \<lbrakk>\<And>f t. const_on f (carrier t) TTree.empty \<Longrightarrow> (xs \<in> paths (substitute f T t)) = (xs \<in> paths t); const_on f (carrier t) TTree.empty\<rbrakk> \<Longrightarrow> (a # xs \<in> paths (substitute f T t)) = (a # xs \<in> paths t)
[PROOF STEP]
from Cons.prems carrier_nxt_subset
[PROOF STATE]
proof (chain)
picking this:
const_on f (carrier t) TTree.empty
carrier (nxt ?t ?x) \<subseteq> carrier ?t
[PROOF STEP]
have "const_on f (carrier (nxt t x)) empty"
[PROOF STATE]
proof (prove)
using this:
const_on f (carrier t) TTree.empty
carrier (nxt ?t ?x) \<subseteq> carrier ?t
goal (1 subgoal):
1. const_on f (carrier (nxt t x)) TTree.empty
[PROOF STEP]
by (rule const_on_subset)
[PROOF STATE]
proof (state)
this:
const_on f (carrier (nxt t x)) TTree.empty
goal (1 subgoal):
1. \<And>a xs f t. \<lbrakk>\<And>f t. const_on f (carrier t) TTree.empty \<Longrightarrow> (xs \<in> paths (substitute f T t)) = (xs \<in> paths t); const_on f (carrier t) TTree.empty\<rbrakk> \<Longrightarrow> (a # xs \<in> paths (substitute f T t)) = (a # xs \<in> paths t)
[PROOF STEP]
hence "const_on (f_nxt f T x) (carrier (nxt t x)) empty"
[PROOF STATE]
proof (prove)
using this:
const_on f (carrier (nxt t x)) TTree.empty
goal (1 subgoal):
1. const_on (f_nxt f T x) (carrier (nxt t x)) TTree.empty
[PROOF STEP]
by (auto simp add: const_on_def f_nxt_def)
[PROOF STATE]
proof (state)
this:
const_on (f_nxt f T x) (carrier (nxt t x)) TTree.empty
goal (1 subgoal):
1. \<And>a xs f t. \<lbrakk>\<And>f t. const_on f (carrier t) TTree.empty \<Longrightarrow> (xs \<in> paths (substitute f T t)) = (xs \<in> paths t); const_on f (carrier t) TTree.empty\<rbrakk> \<Longrightarrow> (a # xs \<in> paths (substitute f T t)) = (a # xs \<in> paths t)
[PROOF STEP]
note Cons.IH[OF this]
[PROOF STATE]
proof (state)
this:
(xs \<in> paths (substitute (f_nxt f T x) T (nxt t x))) = (xs \<in> paths (nxt t x))
goal (1 subgoal):
1. \<And>a xs f t. \<lbrakk>\<And>f t. const_on f (carrier t) TTree.empty \<Longrightarrow> (xs \<in> paths (substitute f T t)) = (xs \<in> paths t); const_on f (carrier t) TTree.empty\<rbrakk> \<Longrightarrow> (a # xs \<in> paths (substitute f T t)) = (a # xs \<in> paths t)
[PROOF STEP]
hence [simp]: "possible t x \<Longrightarrow> (xs \<in> paths (substitute f T (nxt t x))) = (xs \<in> paths (nxt t x))"
[PROOF STATE]
proof (prove)
using this:
(xs \<in> paths (substitute (f_nxt f T x) T (nxt t x))) = (xs \<in> paths (nxt t x))
goal (1 subgoal):
1. possible t x \<Longrightarrow> (xs \<in> paths (substitute f T (nxt t x))) = (xs \<in> paths (nxt t x))
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
possible t x \<Longrightarrow> (xs \<in> paths (substitute f T (nxt t x))) = (xs \<in> paths (nxt t x))
goal (1 subgoal):
1. \<And>a xs f t. \<lbrakk>\<And>f t. const_on f (carrier t) TTree.empty \<Longrightarrow> (xs \<in> paths (substitute f T t)) = (xs \<in> paths t); const_on f (carrier t) TTree.empty\<rbrakk> \<Longrightarrow> (a # xs \<in> paths (substitute f T t)) = (a # xs \<in> paths t)
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (x # xs \<in> paths (substitute f T t)) = (x # xs \<in> paths t)
[PROOF STEP]
by (auto simp add: Cons_path)
[PROOF STATE]
proof (state)
this:
(x # xs \<in> paths (substitute f T t)) = (x # xs \<in> paths t)
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
(xs \<in> paths (substitute f T t)) = (xs \<in> paths t)
goal:
No subgoals!
[PROOF STEP]
qed
|
[STATEMENT]
lemma weakBisimParSym:
fixes \<Psi> :: 'b
and P :: "('a, 'b, 'c) psi"
and Q :: "('a, 'b, 'c) psi"
and R :: "('a, 'b, 'c) psi"
assumes "\<Psi> \<rhd> P \<approx> Q"
shows "\<Psi> \<rhd> R \<parallel> P \<approx> R \<parallel> Q"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Psi> \<rhd> R \<parallel> P \<approx> R \<parallel> Q
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
\<Psi> \<rhd> P \<approx> Q
goal (1 subgoal):
1. \<Psi> \<rhd> R \<parallel> P \<approx> R \<parallel> Q
[PROOF STEP]
by(metis weakBisimParComm weakBisimParPres weakBisimTransitive)
|
(*
* Copyright 2023, Proofcraft Pty Ltd
* Copyright 2014, General Dynamics C4 Systems
*
* SPDX-License-Identifier: GPL-2.0-only
*)
(*
Top level architecture related proofs.
*)
theory Arch_R
imports Untyped_R Finalise_R
begin
unbundle l4v_word_context
context begin interpretation Arch . (*FIXME: arch_split*)
declare is_aligned_shiftl [intro!]
declare is_aligned_shiftr [intro!]
definition
"asid_ci_map i \<equiv>
case i of ARM_A.MakePool frame slot parent base \<Rightarrow>
ARM_H.MakePool frame (cte_map slot) (cte_map parent) base"
definition
"valid_aci' aci \<equiv> case aci of MakePool frame slot parent base \<Rightarrow>
\<lambda>s. cte_wp_at' (\<lambda>c. cteCap c = NullCap) slot s \<and>
cte_wp_at' (\<lambda>cte. \<exists>idx. cteCap cte = UntypedCap False frame pageBits idx) parent s \<and>
descendants_of' parent (ctes_of s) = {} \<and>
slot \<noteq> parent \<and>
ex_cte_cap_to' slot s \<and>
sch_act_simple s \<and>
is_aligned base asid_low_bits \<and> base \<le> 2^asid_bits - 1"
lemma vp_strgs':
"valid_pspace' s \<longrightarrow> pspace_distinct' s"
"valid_pspace' s \<longrightarrow> pspace_aligned' s"
"valid_pspace' s \<longrightarrow> valid_mdb' s"
by auto
lemma safe_parent_strg':
"cte_wp_at' (\<lambda>cte. cteCap cte = UntypedCap False frame pageBits idx) p s \<and>
descendants_of' p (ctes_of s) = {} \<and>
valid_pspace' s
\<longrightarrow> safe_parent_for' (ctes_of s) p (ArchObjectCap (ASIDPoolCap frame base))"
apply (clarsimp simp: safe_parent_for'_def cte_wp_at_ctes_of)
apply (case_tac cte)
apply (simp add: isCap_simps)
apply (subst conj_comms)
apply (rule context_conjI)
apply (drule ctes_of_valid_cap', fastforce)
apply (clarsimp simp: valid_cap'_def capAligned_def)
apply (drule is_aligned_no_overflow)
apply (clarsimp simp: capRange_def asid_low_bits_def pageBits_def)
apply (clarsimp simp: sameRegionAs_def2 isCap_simps capRange_def asid_low_bits_def pageBits_def)
done
lemma descendants_of'_helper:
"\<lbrace>P\<rbrace> f \<lbrace>\<lambda>r s. Q (descendants_of' t (null_filter' (ctes_of s)))\<rbrace>
\<Longrightarrow> \<lbrace>P\<rbrace> f \<lbrace>\<lambda>r s. Q (descendants_of' t (ctes_of s))\<rbrace>"
apply (clarsimp simp:valid_def)
apply (subst null_filter_descendants_of')
prefer 2
apply fastforce
apply simp
done
lemma createObject_typ_at':
"\<lbrace>\<lambda>s. koTypeOf ty = otype \<and> is_aligned ptr (objBitsKO ty) \<and>
pspace_aligned' s \<and> pspace_no_overlap' ptr (objBitsKO ty) s\<rbrace>
createObjects' ptr (Suc 0) ty 0
\<lbrace>\<lambda>rv s. typ_at' otype ptr s\<rbrace>"
apply (clarsimp simp:createObjects'_def alignError_def split_def | wp unless_wp | wpc )+
apply (clarsimp simp:obj_at'_def ko_wp_at'_def typ_at'_def pspace_distinct'_def)+
apply (subgoal_tac "ps_clear ptr (objBitsKO ty)
(s\<lparr>ksPSpace := \<lambda>a. if a = ptr then Some ty else ksPSpace s a\<rparr>)")
apply (simp add:ps_clear_def)+
apply (rule ccontr)
apply (drule int_not_emptyD)
apply clarsimp
apply (unfold pspace_no_overlap'_def)
apply (erule allE)+
apply (erule(1) impE)
apply (subgoal_tac "x \<in> {x..x + 2 ^ objBitsKO y - 1}")
apply (fastforce simp: p_assoc_help)
apply (rule first_in_uptoD)
apply (drule(1) pspace_alignedD')
apply (clarsimp simp: is_aligned_no_wrap' p_assoc_help)
done
lemma retype_region2_ext_retype_region_ArchObject:
"retype_region ptr n us (ArchObject x)=
retype_region2 ptr n us (ArchObject x)"
apply (rule ext)
apply (simp add:retype_region_def retype_region2_def bind_assoc
retype_region2_ext_def retype_region_ext_def default_ext_def)
apply (rule ext)
apply (intro monad_eq_split_tail ext)+
apply simp
apply simp
apply (simp add:gets_def get_def bind_def return_def simpler_modify_def )
apply (rule_tac x = xc in fun_cong)
apply (rule_tac f = do_extended_op in arg_cong)
apply (rule ext)
apply simp
apply simp
done
lemma set_cap_device_and_range_aligned:
"is_aligned ptr sz \<Longrightarrow> \<lbrace>\<lambda>_. True\<rbrace>
set_cap
(cap.UntypedCap dev ptr sz idx)
aref
\<lbrace>\<lambda>rv s.
\<exists>slot.
cte_wp_at
(\<lambda>c. cap_is_device c = dev \<and>
up_aligned_area ptr sz \<subseteq> cap_range c)
slot s\<rbrace>"
apply (subst is_aligned_neg_mask_eq[symmetric])
apply simp
apply (wp set_cap_device_and_range)
done
lemma performASIDControlInvocation_corres:
"asid_ci_map i = i' \<Longrightarrow>
corres dc
(einvs and ct_active and valid_aci i)
(invs' and ct_active' and valid_aci' i')
(perform_asid_control_invocation i)
(performASIDControlInvocation i')"
supply
is_aligned_neg_mask_eq[simp del]
is_aligned_neg_mask_weaken[simp del]
apply (cases i)
apply (rename_tac word1 prod1 prod2 word2)
apply (clarsimp simp: asid_ci_map_def)
apply (simp add: perform_asid_control_invocation_def placeNewObject_def2
performASIDControlInvocation_def)
apply (rule corres_name_pre)
apply (clarsimp simp:valid_aci_def valid_aci'_def cte_wp_at_ctes_of cte_wp_at_caps_of_state)
apply (subgoal_tac "valid_cap' (capability.UntypedCap False word1 pageBits idx) s'")
prefer 2
apply (case_tac ctea)
apply clarsimp
apply (erule ctes_of_valid_cap')
apply fastforce
apply (frule valid_capAligned)
apply (clarsimp simp: capAligned_def page_bits_def)
apply (rule corres_guard_imp)
apply (rule corres_split)
apply (erule deleteObjects_corres)
apply (simp add:pageBits_def)
apply (rule corres_split[OF getSlotCap_corres])
apply simp
apply (rule_tac F = " pcap = (cap.UntypedCap False word1 pageBits idxa)" in corres_gen_asm)
apply (rule corres_split[OF updateFreeIndex_corres])
apply (clarsimp simp:is_cap_simps)
apply (simp add: free_index_of_def)
apply (rule corres_split)
apply (simp add: retype_region2_ext_retype_region_ArchObject )
apply (rule corres_retype [where ty="Inl (KOArch (KOASIDPool F))",
unfolded APIType_map2_def makeObjectKO_def,
THEN createObjects_corres',simplified,
where val = "makeObject::asidpool"])
apply simp
apply (simp add: objBits_simps obj_bits_api_def arch_kobj_size_def
default_arch_object_def archObjSize_def)+
apply (simp add: obj_relation_retype_def default_object_def
default_arch_object_def objBits_simps archObjSize_def)
apply (simp add: other_obj_relation_def asid_pool_relation_def)
apply (simp add: makeObject_asidpool const_def inv_def)
apply (rule range_cover_full)
apply (simp add:obj_bits_api_def arch_kobj_size_def default_arch_object_def)+
apply (rule corres_split)
apply (rule cteInsert_simple_corres, simp, rule refl, rule refl)
apply (rule_tac F="is_aligned word2 asid_low_bits" in corres_gen_asm)
apply (simp add: is_aligned_mask dc_def[symmetric])
apply (rule corres_split[where P=\<top> and P'=\<top> and r'="\<lambda>t t'. t = t' o ucast"])
apply (clarsimp simp: state_relation_def arch_state_relation_def)
apply (rule corres_trivial)
apply (rule corres_modify)
apply (thin_tac "x \<in> state_relation" for x)
apply (clarsimp simp: state_relation_def arch_state_relation_def o_def)
apply (rule ext)
apply clarsimp
apply (erule_tac P = "x = asid_high_bits_of word2" in notE)
apply (rule word_eqI[rule_format])
apply (drule_tac x1="ucast x" in bang_eq [THEN iffD1])
apply (erule_tac x=n in allE)
apply (simp add: word_size nth_ucast)
apply wp+
apply (strengthen safe_parent_strg[where idx = "2^pageBits"])
apply (strengthen invs_valid_objs invs_distinct
invs_psp_aligned invs_mdb
| simp cong:conj_cong)+
apply (wp retype_region_plain_invs[where sz = pageBits]
retype_cte_wp_at[where sz = pageBits])+
apply (strengthen vp_strgs'
safe_parent_strg'[where idx = "2^pageBits"])
apply (simp cong: conj_cong)
apply (wp createObjects_valid_pspace'
[where sz = pageBits and ty="Inl (KOArch (KOASIDPool undefined))"])
apply (simp add: makeObjectKO_def)+
apply (simp add:objBits_simps archObjSize_def range_cover_full)+
apply (clarsimp simp:valid_cap'_def)
apply (wp createObject_typ_at'
createObjects_orig_cte_wp_at'[where sz = pageBits])
apply (rule descendants_of'_helper)
apply (wp createObjects_null_filter'
[where sz = pageBits and ty="Inl (KOArch (KOASIDPool undefined))"])
apply (clarsimp simp: conj_comms obj_bits_api_def arch_kobj_size_def
objBits_simps archObjSize_def default_arch_object_def
pred_conj_def)
apply (clarsimp simp: conj_comms
| strengthen invs_mdb invs_valid_pspace)+
apply (simp add:region_in_kernel_window_def)
apply (wp set_untyped_cap_invs_simple[where sz = pageBits]
set_cap_cte_wp_at
set_cap_caps_no_overlap[where sz = pageBits]
set_cap_no_overlap
set_cap_device_and_range_aligned[where dev = False,simplified]
set_untyped_cap_caps_overlap_reserved[where sz = pageBits])+
apply (clarsimp simp: conj_comms obj_bits_api_def arch_kobj_size_def
objBits_simps archObjSize_def default_arch_object_def
makeObjectKO_def range_cover_full
simp del: capFreeIndex_update.simps
| strengthen invs_valid_pspace' invs_pspace_aligned'
invs_pspace_distinct'
exI[where x="makeObject :: asidpool"])+
apply (wp updateFreeIndex_forward_invs'
updateFreeIndex_pspace_no_overlap'
updateFreeIndex_caps_no_overlap''
updateFreeIndex_descendants_of2
updateFreeIndex_cte_wp_at
updateFreeIndex_caps_overlap_reserved
| simp add: descendants_of_null_filter' split del: if_split)+
apply (wp get_cap_wp)+
apply (subgoal_tac "word1 && ~~ mask pageBits = word1 \<and> pageBits \<le> word_bits \<and> word_size_bits \<le> pageBits")
prefer 2
apply (clarsimp simp:pageBits_def word_bits_def is_aligned_neg_mask_eq word_size_bits_def)
apply (simp only:delete_objects_rewrite)
apply wp+
apply (clarsimp simp: conj_comms)
apply (clarsimp simp: conj_comms ex_disj_distrib
| strengthen invs_valid_pspace' invs_pspace_aligned'
invs_pspace_distinct')+
apply (wp deleteObjects_invs'[where p="makePoolParent i'"]
deleteObjects_cte_wp_at'
deleteObjects_descendants[where p="makePoolParent i'"])
apply (clarsimp split del: if_split simp:valid_cap'_def)
apply (wp hoare_vcg_ex_lift
deleteObjects_caps_no_overlap''[where slot="makePoolParent i'"]
deleteObject_no_overlap
deleteObjects_ct_active'[where cref="makePoolParent i'"])
apply (clarsimp simp: is_simple_cap_def valid_cap'_def max_free_index_def is_cap_simps
cong: conj_cong)
apply (strengthen empty_descendants_range_in')
apply (wp deleteObjects_descendants[where p="makePoolParent i'"]
deleteObjects_cte_wp_at'
deleteObjects_null_filter[where p="makePoolParent i'"])
apply (clarsimp simp:invs_mdb max_free_index_def invs_untyped_children)
apply (subgoal_tac "detype_locale x y sa" for x y)
prefer 2
apply (simp add:detype_locale_def)
apply (fastforce simp:cte_wp_at_caps_of_state descendants_range_def2
empty_descendants_range_in invs_untyped_children)
apply (intro conjI)
apply (clarsimp)
apply (erule(1) caps_of_state_valid)
subgoal by (fastforce simp:cte_wp_at_caps_of_state
descendants_range_def2 empty_descendants_range_in)
apply (fold_subgoals (prefix))[2]
subgoal premises prems using prems by (clarsimp simp:invs_def valid_state_def)+
apply (clarsimp simp:cte_wp_at_caps_of_state)
apply (drule detype_locale.non_null_present)
apply (fastforce simp:cte_wp_at_caps_of_state)
apply simp
apply (frule_tac ptr = "(aa,ba)" in detype_invariants [rotated 3])
apply fastforce
apply simp
apply (simp add: cte_wp_at_caps_of_state)
apply (simp add: is_cap_simps)
apply (simp add:empty_descendants_range_in descendants_range_def2)
apply (frule intvl_range_conv[where bits = pageBits])
apply (clarsimp simp:pageBits_def word_bits_def)
apply (clarsimp simp: invs_valid_objs cte_wp_at_caps_of_state range_cover_full
invs_psp_aligned invs_distinct cap_master_cap_simps is_cap_simps
is_simple_cap_def)
apply (clarsimp simp: conj_comms)
apply (rule conjI,clarsimp)
apply (frule ex_cte_cap_protects)
apply (simp add:cte_wp_at_caps_of_state)
apply (simp add:empty_descendants_range_in)
apply fastforce
apply (rule subset_refl)
apply fastforce
apply clarsimp
apply (rule conjI,clarsimp simp:clear_um_def)
apply (simp add:detype_clear_um_independent)
apply (rule conjI,erule caps_no_overlap_detype[OF descendants_range_caps_no_overlapI])
apply (clarsimp simp:is_aligned_neg_mask_eq cte_wp_at_caps_of_state)
apply (simp add:empty_descendants_range_in)+
apply (rule conjI)
apply clarsimp
apply (drule_tac p = "(aa,ba)" in cap_refs_in_kernel_windowD2[OF caps_of_state_cteD])
apply fastforce
apply (clarsimp simp: region_in_kernel_window_def valid_cap_def
cap_aligned_def is_aligned_neg_mask_eq detype_def clear_um_def)
apply (rule conjI, rule pspace_no_overlap_subset,
rule pspace_no_overlap_detype[OF caps_of_state_valid])
apply (simp add:invs_psp_aligned invs_valid_objs is_aligned_neg_mask_eq)+
apply (clarsimp simp: detype_def clear_um_def detype_ext_def valid_sched_def valid_etcbs_def
st_tcb_at_kh_def obj_at_kh_def st_tcb_at_def obj_at_def is_etcb_at_def)
apply (simp add: detype_def clear_um_def)
apply (drule_tac x = "cte_map (aa,ba)" in pspace_relation_cte_wp_atI[OF state_relation_pspace_relation])
apply (simp add:invs_valid_objs)+
apply clarsimp
apply (drule cte_map_inj_eq)
apply ((fastforce simp:cte_wp_at_caps_of_state)+)[5]
apply (clarsimp simp:cte_wp_at_caps_of_state invs_valid_pspace' conj_comms cte_wp_at_ctes_of
valid_cap_simps')
apply (strengthen refl)
apply clarsimp
apply (frule empty_descendants_range_in')
apply (intro conjI,
simp_all add: is_simple_cap'_def isCap_simps descendants_range'_def2
null_filter_descendants_of'[OF null_filter_simp']
capAligned_def asid_low_bits_def)
apply (erule descendants_range_caps_no_overlapI')
apply (fastforce simp:cte_wp_at_ctes_of is_aligned_neg_mask_eq)
apply (simp add:empty_descendants_range_in')
apply (simp add:word_bits_def pageBits_def)
apply (rule is_aligned_weaken)
apply (rule is_aligned_shiftl_self[unfolded shiftl_t2n,where p = 1,simplified])
apply (simp add:pageBits_def)
apply clarsimp
apply (drule(1) cte_cap_in_untyped_range)
apply (fastforce simp:cte_wp_at_ctes_of)
apply assumption+
apply fastforce
apply simp
apply clarsimp
apply (drule (1) cte_cap_in_untyped_range)
apply (fastforce simp add: cte_wp_at_ctes_of)
apply assumption+
apply (clarsimp simp: invs'_def valid_state'_def if_unsafe_then_cap'_def cte_wp_at_ctes_of)
apply fastforce
apply simp
done
definition
archinv_relation :: "arch_invocation \<Rightarrow> Arch.invocation \<Rightarrow> bool"
where
"archinv_relation ai ai' \<equiv> case ai of
arch_invocation.InvokePageTable pti \<Rightarrow>
\<exists>pti'. ai' = InvokePageTable pti' \<and> page_table_invocation_map pti pti'
| arch_invocation.InvokePageDirectory pdi \<Rightarrow>
\<exists>pdi'. ai' = InvokePageDirectory pdi' \<and> page_directory_invocation_map pdi pdi'
| arch_invocation.InvokePage pgi \<Rightarrow>
\<exists>pgi'. ai' = InvokePage pgi' \<and> page_invocation_map pgi pgi'
| arch_invocation.InvokeASIDControl aci \<Rightarrow>
\<exists>aci'. ai' = InvokeASIDControl aci' \<and> aci' = asid_ci_map aci
| arch_invocation.InvokeASIDPool ap \<Rightarrow>
\<exists>ap'. ai' = InvokeASIDPool ap' \<and> ap' = asid_pool_invocation_map ap"
definition
valid_arch_inv' :: "Arch.invocation \<Rightarrow> kernel_state \<Rightarrow> bool"
where
"valid_arch_inv' ai \<equiv> case ai of
InvokePageTable pti \<Rightarrow> valid_pti' pti
| InvokePageDirectory pdi \<Rightarrow> \<top>
| InvokePage pgi \<Rightarrow> valid_page_inv' pgi
| InvokeASIDControl aci \<Rightarrow> valid_aci' aci
| InvokeASIDPool ap \<Rightarrow> valid_apinv' ap"
lemma mask_vmrights_corres:
"maskVMRights (vmrights_map R) (rightsFromWord d) =
vmrights_map (mask_vm_rights R (data_to_rights d))"
by (clarsimp simp: rightsFromWord_def data_to_rights_def
vmrights_map_def Let_def maskVMRights_def
mask_vm_rights_def nth_ucast
validate_vm_rights_def vm_read_write_def
vm_kernel_only_def vm_read_only_def
split: bool.splits)
lemma vm_attributes_corres:
"vmattributes_map (attribs_from_word w) = attribsFromWord w"
by (clarsimp simp: attribsFromWord_def attribs_from_word_def
Let_def vmattributes_map_def)
lemma checkVPAlignment_corres:
"corres (ser \<oplus> dc) \<top> \<top>
(check_vp_alignment sz w)
(checkVPAlignment sz w)"
apply (simp add: check_vp_alignment_def checkVPAlignment_def)
apply (cases sz, simp_all add: corres_returnOk unlessE_whenE is_aligned_mask)
apply ((rule corres_guard_imp, rule corres_whenE, rule refl, auto)[1])+
done
lemma checkVP_wpR [wp]:
"\<lbrace>\<lambda>s. vmsz_aligned' w sz \<longrightarrow> P () s\<rbrace>
checkVPAlignment sz w \<lbrace>P\<rbrace>, -"
apply (simp add: checkVPAlignment_def unlessE_whenE cong: vmpage_size.case_cong)
apply (rule hoare_pre)
apply (wp whenE_wp|wpc)+
apply (simp add: is_aligned_mask vmsz_aligned'_def)
done
lemma asidHighBits [simp]:
"asidHighBits = asid_high_bits"
by (simp add: asidHighBits_def asid_high_bits_def)
declare word_unat_power [symmetric, simp del]
lemma ARMMMU_improve_cases:
"(if isPageDirectoryCap cap then P
else if isPageTableCap cap then Q
else if isPageCap cap then R
else if isASIDControlCap cap then S
else if isASIDPoolCap cap then T
else undefined)
=
(if isPageDirectoryCap cap then P
else if isPageTableCap cap then Q
else if isPageCap cap then R
else if isASIDControlCap cap then S
else T)"
by (cases cap, simp_all add: isCap_simps)
crunch inv [wp]: "ARM_H.decodeInvocation" "P"
(wp: crunch_wps mapME_x_inv_wp getASID_wp
simp: crunch_simps ARMMMU_improve_cases)
lemma case_option_corresE:
assumes nonec: "corres r Pn Qn (nc >>=E f) (nc' >>=E g)"
and somec: "\<And>v'. corres r (Ps v') (Qs v') (sc v' >>=E f) (sc' v' >>=E g)"
shows "corres r (case_option Pn Ps v) (case_option Qn Qs v) (case_option nc sc v >>=E f) (case_option nc' sc' v >>=E g)"
apply (cases v)
apply simp
apply (rule nonec)
apply simp
apply (rule somec)
done
lemma cap_relation_Untyped_eq:
"cap_relation c (UntypedCap d p sz f) = (c = cap.UntypedCap d p sz f)"
by (cases c) auto
lemma vmsz_aligned_less_kernel_base_eq:
"\<lbrakk>ptr + 2 ^ pageBitsForSize vmpage_size - 1 < kernel_base;vmsz_aligned ptr vmpage_size\<rbrakk>
\<Longrightarrow> ptr < kernel_base"
apply (simp add:vmsz_aligned_def)
apply (rule ccontr)
apply (simp add:not_less)
apply (drule(1) less_le_trans)
apply (drule is_aligned_no_overflow)
apply (simp add:not_less[symmetric])
done
declare check_vp_alignment_inv[wp del]
lemma select_ext_fa:
"free_asid_select asid_tbl \<in> S
\<Longrightarrow> ((select_ext (\<lambda>_. free_asid_select asid_tbl) S) :: (7 word) det_ext_monad)
= return (free_asid_select asid_tbl)"
by (simp add: select_ext_def get_def gets_def bind_def assert_def return_def fail_def)
lemma select_ext_fap:
"free_asid_pool_select p b \<in> S
\<Longrightarrow> ((select_ext (\<lambda>_. free_asid_pool_select p b) S) :: (10 word) det_ext_monad)
= return (free_asid_pool_select p b)"
by (simp add: select_ext_def get_def gets_def bind_def assert_def return_def)
lemma lookup_pt_slot_no_fail_corres[simp]:
"lookupPTSlotFromPT pt vptr
= (do stateAssert (page_table_at' pt) []; return (lookup_pt_slot_no_fail pt vptr) od)"
by (simp add: lookup_pt_slot_no_fail_def lookupPTSlotFromPT_def mask_def checkPTAt_def
ptBits_def pteBits_def pageBits_def)
lemma page_base_corres[simp]:
"pageBase vaddr vmsize = page_base vaddr vmsize"
by (clarsimp simp: pageBase_def page_base_def)
lemma flush_type_map:
"ARM_H.isPageFlushLabel (invocation_type (mi_label mi))
\<or> ARM_H.isPDFlushLabel (invocation_type (mi_label mi))
\<Longrightarrow> labelToFlushType (mi_label mi) =
flush_type_map (label_to_flush_type (invocation_type (mi_label mi)))"
by (clarsimp simp: label_to_flush_type_def labelToFlushType_def flush_type_map_def
ARM_H.isPageFlushLabel_def ARM_H.isPDFlushLabel_def
split: ARM_A.flush_type.splits invocation_label.splits arch_invocation_label.splits)
lemma resolveVAddr_corres:
"\<lbrakk> is_aligned pd pd_bits; vaddr < kernel_base \<rbrakk> \<Longrightarrow>
corres (=) (pspace_aligned and valid_vspace_objs and page_directory_at pd
and (\<exists>\<rhd> (lookup_pd_slot pd vaddr && ~~ mask pd_bits)))
(\<lambda>s. pspace_aligned' s \<and> pspace_distinct' s \<and> vs_valid_duplicates' (ksPSpace s))
(resolve_vaddr pd vaddr) (resolveVAddr pd vaddr)"
apply (clarsimp simp: resolve_vaddr_def resolveVAddr_def)
apply (rule stronger_corres_guard_imp)
apply (rule_tac R="\<lambda>rv s. valid_pde rv s \<and> pspace_aligned s"
and R'="\<lambda>_ s. pspace_distinct' s \<and> pspace_aligned' s
\<and> vs_valid_duplicates' (ksPSpace s)"
in corres_split[OF get_master_pde_corres])
apply simp
apply (case_tac rv, simp_all add: pde_relation'_def)[1]
apply (rule corres_stateAssert_assume_stronger)
apply (rule stronger_corres_guard_imp)
apply (rule corres_split[OF get_master_pte_corres[OF refl]])
apply (rule corres_trivial)
apply (case_tac rva, simp_all add: pte_relation'_def)[1]
apply (wp get_master_pte_inv)+
apply (clarsimp simp: page_table_pte_at_lookupI)
apply (clarsimp simp: page_table_pte_at_lookupI' page_table_at_state_relation)
apply clarsimp
apply (erule(3) page_table_at_state_relation)
apply wpsimp+
apply (clarsimp simp: page_directory_pde_at_lookupI less_kernel_base_mapping_slots)
apply (clarsimp simp: page_directory_pde_at_lookupI' page_directory_at_state_relation)
done
lemma decodeARMPageFlush_corres:
"ARM_H.isPageFlushLabel (invocation_type (mi_label mi)) \<Longrightarrow>
corres (ser \<oplus> archinv_relation)
(invs and
valid_cap (cap.ArchObjectCap (arch_cap.PageCap d word seta vmpage_size option)) and
cte_wp_at
((=) (cap.ArchObjectCap (arch_cap.PageCap d word seta vmpage_size option)))
slot and
(\<lambda>s. \<forall>x\<in>set excaps. s \<turnstile> fst x \<and> cte_wp_at (\<lambda>_. True) (snd x) s))
(invs' and
valid_cap'
(capability.ArchObjectCap
(arch_capability.PageCap d word (vmrights_map seta) vmpage_size option)) and
(\<lambda>s. \<forall>x\<in>set excaps'. valid_cap' (fst x) s \<and> cte_wp_at' (\<lambda>_. True) (snd x) s) and
(\<lambda>s. vs_valid_duplicates' (ksPSpace s)))
(if Suc 0 < length args
then let start = args ! 0; end = args ! 1
in doE (asid, vaddr) \<leftarrow>
case option of
None \<Rightarrow> throwError ExceptionTypes_A.syscall_error.IllegalOperation
| Some x \<Rightarrow> returnOk x;
pd \<leftarrow> lookup_error_on_failure False $ find_pd_for_asid asid;
whenE (end \<le> start) $
throwError $ ExceptionTypes_A.syscall_error.InvalidArgument 1;
page_size \<leftarrow> returnOk $ 1 << pageBitsForSize vmpage_size;
whenE (page_size \<le> start \<or> page_size < end) $
throwError $ ExceptionTypes_A.syscall_error.InvalidArgument 0;
returnOk $
arch_invocation.InvokePage $
ARM_A.page_invocation.PageFlush
(label_to_flush_type (invocation_type (mi_label mi))) (start + vaddr)
(end + vaddr - 1) (addrFromPPtr word + start) pd asid
odE
else throwError ExceptionTypes_A.syscall_error.TruncatedMessage)
(decodeARMPageFlush (mi_label mi) args
(arch_capability.PageCap d word (vmrights_map seta) vmpage_size option))"
apply (simp add: decodeARMPageFlush_def split del: if_split)
apply (cases args, simp)
apply (rename_tac a0 as)
apply (case_tac as, simp)
apply (rename_tac a1 as')
apply (cases option, simp)
apply (case_tac a)
apply (rename_tac asid vref)
apply clarsimp
apply (rule corres_guard_imp)
apply (rule corres_splitEE)
apply (rule corres_lookup_error)
apply (rule find_pd_for_asid_corres[OF refl])
apply (rule whenE_throwError_corres, simp)
apply simp
apply (rule whenE_throwError_corres, simp)
apply simp
apply (rule corres_trivial)
apply (rule corres_returnOk)
apply (clarsimp simp: archinv_relation_def page_invocation_map_def
label_to_flush_type_def labelToFlushType_def flush_type_map_def
ARM_H.isPageFlushLabel_def
split: flush_type.splits invocation_label.splits arch_invocation_label.splits)
apply wp+
apply (fastforce simp: valid_cap_def mask_def
invs_vspace_objs[simplified])
apply (auto)
done
lemma vs_lookup_pages1I:
"\<lbrakk> ko_at ko p s; (r, p') \<in> vs_refs_pages ko;
rs' = r # rs \<rbrakk> \<Longrightarrow> ((rs,p) \<unrhd>1 (rs',p')) s"
by (fastforce simp add: vs_lookup_pages1_def)
lemma vs_refs_pages_ptI:
"pt x = pte \<Longrightarrow> pte_ref_pages pte = Some r'
\<Longrightarrow> (VSRef (ucast x) (Some APageTable), r') \<in> vs_refs_pages (ArchObj (PageTable pt))"
apply (simp add: vs_refs_pages_def)
apply (rule image_eqI[rotated], rule graph_ofI[where x=x], simp)
apply simp
done
lemmas vs_refs_pages_pt_largeI
= vs_refs_pages_ptI[where pte="ARM_A.pte.LargePagePTE x y z" for x y z,
unfolded pte_ref_pages_def, simplified, OF _ refl]
lemmas vs_refs_pages_pt_smallI
= vs_refs_pages_ptI[where pte="ARM_A.pte.SmallPagePTE x y z" for x y z,
unfolded pte_ref_pages_def, simplified, OF _ refl]
lemma vs_refs_pages_pdI:
"pd x = pde \<Longrightarrow> pde_ref_pages pde = Some r'
\<Longrightarrow> x \<notin> kernel_mapping_slots
\<Longrightarrow> (VSRef (ucast x) (Some APageDirectory), r') \<in> vs_refs_pages (ArchObj (PageDirectory pd))"
apply (simp add: vs_refs_pages_def)
apply (rule image_eqI[rotated], rule graph_ofI[where x=x], simp)
apply simp
done
lemmas vs_refs_pages_pd_sectionI
= vs_refs_pages_pdI[where pde="ARM_A.pde.SectionPDE x y z w" for x y z w,
unfolded pde_ref_pages_def, simplified, OF _ refl]
lemmas vs_refs_pages_pd_supersectionI
= vs_refs_pages_pdI[where pde="ARM_A.pde.SuperSectionPDE x y z" for x y z,
unfolded pde_ref_pages_def, simplified, OF _ refl]
lemma get_master_pde_sp:
"\<lbrace> P \<rbrace> get_master_pde pd_slot \<lbrace> \<lambda>pde s. P s
\<and> (\<exists>pd pd_slot'. ko_at (ArchObj (PageDirectory pd)) (pd_slot && ~~ mask pd_bits) s
\<and> pd_slot' && ~~ mask pd_bits = pd_slot && ~~ mask pd_bits
\<and> ((ucast (pd_slot' && mask pd_bits >> 2) \<in> kernel_mapping_slots)
\<longrightarrow> (ucast (pd_slot && mask pd_bits >> 2) \<in> kernel_mapping_slots))
\<and> pd (ucast (pd_slot' && mask pd_bits >> 2)) = pde) \<rbrace>"
apply (simp add: get_master_pde_def)
apply (wp get_pde_wp | wpc)+
apply (clarsimp simp: obj_at_def)
apply (safe, simp_all add: exI[where x=pd_slot])
apply (cut_tac max.absorb2[where a=6 and b=pd_bits])
apply (clarsimp simp: word_bw_assocs neg_mask_combine)
apply (rule_tac x="pd_slot && ~~ mask 6" in exI)
apply (simp add: word_bw_assocs neg_mask_combine)
apply (clarsimp simp: kernel_mapping_slots_def)
apply (erule order_trans)
apply (rule ucast_mono_le)
apply (rule le_shiftr)
apply (metis word_and_le1 word_bw_assocs(1) word_bw_comms(1))
apply (rule shiftr_less_t2n)
apply (rule order_less_le_trans, rule and_mask_less_size)
apply (simp add: pd_bits_def pageBits_def word_size)
apply (simp add: pd_bits_def pageBits_def)
apply (simp add: pd_bits_def pageBits_def)
done
lemma get_master_pte_wp:
"\<lbrace> \<lambda>s. (\<forall>pt pt_slot'. ko_at (ArchObj (PageTable pt)) (pt_slot && ~~ mask pt_bits) s
\<and> pt_slot' && ~~ mask pt_bits = pt_slot && ~~ mask pt_bits
\<longrightarrow> Q (pt (ucast (pt_slot' && mask pt_bits >> 2))) s) \<rbrace>
get_master_pte pt_slot \<lbrace> Q \<rbrace>"
apply (simp add: get_master_pte_def)
apply (wp get_pte_wp | wpc)+
apply clarsimp
apply (drule spec, drule_tac x="pt_slot && ~~ mask 6" in spec)
apply (cut_tac max.absorb2[where a=6 and b=pt_bits])
apply (simp add: word_bw_assocs neg_mask_combine obj_at_def)
apply fastforce
apply (simp add: pt_bits_def pageBits_def)
done
lemma resolve_vaddr_valid_mapping_size:
"\<lbrace> valid_vs_lookup and pspace_aligned and valid_vspace_objs and page_directory_at pd
and (\<exists>\<rhd> (lookup_pd_slot pd vaddr && ~~ mask pd_bits))
and valid_objs and K (vaddr < kernel_base) \<rbrace>
resolve_vaddr pd vaddr \<lbrace> \<lambda>rv s. case rv of None \<Rightarrow> True
| Some (a, b) \<Rightarrow> \<exists>p cap. caps_of_state s p = Some cap
\<and> (case cap of cap.ArchObjectCap c \<Rightarrow> is_page_cap c | _ \<Rightarrow> False)
\<and> cap_bits cap = pageBitsForSize a \<rbrace> "
apply (simp add: resolve_vaddr_def)
apply (rule hoare_seq_ext[OF _ get_master_pde_sp])
apply (rule hoare_pre)
apply (wp get_master_pte_wp | wpc
| simp add: lookup_pt_slot_no_fail_def)+
apply (clarsimp simp: obj_at_def)
apply (frule(1) pspace_alignedD, simp)
apply (drule_tac y=pd_bits in is_aligned_weaken, simp add: pd_bits_def pageBits_def)
apply (frule valid_vspace_objsD, simp add: obj_at_def lookup_pd_slot_eq, simp)
apply (simp add: lookup_pd_slot_eq less_kernel_base_mapping_slots)
apply (drule bspec, simp)
apply (rule conjI)
apply clarsimp
apply (drule vs_lookup_step)
apply (rule vs_lookup1I, simp add: obj_at_def)
apply (erule(1) vs_refs_pdI2)
apply simp
apply (drule sym[where s=pd])
apply (simp add: lookup_pd_slot_eq)
apply (frule(1) is_aligned_pt)
apply (frule is_aligned_weaken[where x=pt_bits and y=10])
apply (simp add: pt_bits_def pageBits_def)
apply (simp add: vaddr_segment_nonsense3)
apply (frule valid_vspace_objsD, simp add: obj_at_def, simp)
apply (drule vs_lookup_pages_vs_lookupI)
apply (rule conjI)
apply (clarsimp simp:)
apply (drule_tac x="ucast (pt_slot' && mask pt_bits >> 2)" in spec)
apply (drule vs_lookup_pages_step)
apply (rule vs_lookup_pages1I, simp add: obj_at_def)
apply (erule vs_refs_pages_pt_largeI)
apply simp
apply (drule(1) valid_vs_lookupD)
apply simp
apply (erule exEI)+
apply (clarsimp simp: vs_cap_ref_def split: cap.split_asm arch_cap.split_asm
option.split_asm vmpage_size.split_asm)
apply (frule(1) caps_of_state_valid_cap)
apply (clarsimp simp: valid_cap_def obj_at_def data_at_def a_type_simps
split: if_split_asm)
apply (clarsimp simp: vaddr_segment_nonsense4)
apply (drule_tac x="ucast (pt_slot' && mask pt_bits >> 2)" in spec)
apply (drule vs_lookup_pages_step)
apply (rule vs_lookup_pages1I, simp add: obj_at_def)
apply (erule vs_refs_pages_pt_smallI)
apply simp
apply (drule(1) valid_vs_lookupD)
apply simp
apply (erule exEI)+
apply (clarsimp simp: vs_cap_ref_def split: cap.split_asm arch_cap.split_asm
option.split_asm vmpage_size.split_asm)
apply (frule(1) caps_of_state_valid_cap)
apply (clarsimp simp: valid_cap_def obj_at_def data_at_def a_type_simps
split: if_split_asm)
apply (drule vs_lookup_pages_vs_lookupI)
apply (rule conjI)
apply clarsimp
apply (drule vs_lookup_pages_step)
apply (rule vs_lookup_pages1I, simp add: obj_at_def)
apply (erule(1) vs_refs_pages_pd_sectionI)
apply simp
apply (drule(1) valid_vs_lookupD)
apply simp
apply (erule exEI)+
apply (clarsimp simp: vs_cap_ref_def split: cap.split_asm arch_cap.split_asm
option.split_asm vmpage_size.split_asm)
apply (frule(1) caps_of_state_valid_cap)
apply (clarsimp simp: valid_cap_def obj_at_def data_at_def a_type_simps
split: if_split_asm)
apply (frule(1) caps_of_state_valid_cap)
apply (clarsimp simp: valid_cap_def obj_at_def data_at_def a_type_simps
split: if_split_asm)
apply clarsimp
apply (drule vs_lookup_pages_step)
apply (rule vs_lookup_pages1I, simp add: obj_at_def)
apply (erule(1) vs_refs_pages_pd_supersectionI)
apply simp
apply (drule(1) valid_vs_lookupD)
apply simp
apply (erule exEI)+
apply (clarsimp simp: vs_cap_ref_def
split: cap.split_asm arch_cap.split_asm
option.split_asm vmpage_size.split_asm)
apply (frule(1) caps_of_state_valid_cap)
apply (clarsimp simp: valid_cap_def obj_at_def data_at_def a_type_simps
split: if_split_asm)
apply (frule(1) caps_of_state_valid_cap)
apply (clarsimp simp: valid_cap_def obj_at_def data_at_def a_type_simps
split: if_split_asm)
done
lemmas whenE_throwError_corres_terminal =
whenE_throwError_corres[where m="returnOk ()" and m'="returnOk ()", OF _ _ corres_returnOkTT, simplified]
lemma arch_decodeInvocation_corres:
notes check_vp_inv[wp del] check_vp_wpR[wp]
(* FIXME: check_vp_inv shadowed check_vp_wpR. Instead,
check_vp_wpR should probably be generalised to replace check_vp_inv. *)
shows
"\<lbrakk> acap_relation arch_cap arch_cap';
list_all2 cap_relation (map fst excaps) (map fst excaps');
list_all2 (\<lambda>s s'. s' = cte_map s) (map snd excaps) (map snd excaps') \<rbrakk> \<Longrightarrow>
corres
(ser \<oplus> archinv_relation)
(invs and valid_cap (cap.ArchObjectCap arch_cap) and
cte_wp_at ((=) (cap.ArchObjectCap arch_cap)) slot and
(\<lambda>s. \<forall>x\<in>set excaps. s \<turnstile> fst x \<and> cte_at (snd x) s))
(invs' and valid_cap' (capability.ArchObjectCap arch_cap') and
(\<lambda>s. \<forall>x\<in>set excaps'. s \<turnstile>' fst x \<and> cte_at' (snd x) s) and
(\<lambda>s. vs_valid_duplicates' (ksPSpace s)))
(arch_decode_invocation (mi_label mi) args (to_bl cptr') slot
arch_cap excaps)
(Arch.decodeInvocation (mi_label mi) args cptr'
(cte_map slot) arch_cap' excaps')"
apply (simp add: arch_decode_invocation_def ARM_H.decodeInvocation_def decodeARMMMUInvocation_def
split del: if_split)
apply (cases arch_cap)
apply (simp add: isCap_simps split del: if_split)
apply (cases "invocation_type (mi_label mi) \<noteq> ArchInvocationLabel ARMASIDPoolAssign")
apply (simp split: invocation_label.split arch_invocation_label.split)
apply (rename_tac word1 word2)
apply (cases "excaps", simp)
apply (cases "excaps'", simp)
apply clarsimp
apply (case_tac a, simp_all)[1]
apply (rename_tac arch_capa)
apply (case_tac arch_capa, simp_all)[1]
apply (rename_tac word3 option)
apply (case_tac option, simp_all)[1]
apply (rule corres_guard_imp)
apply (rule corres_splitEE)
apply (rule corres_trivial [where r="ser \<oplus> (\<lambda>p p'. p = p' o ucast)"])
apply (clarsimp simp: state_relation_def arch_state_relation_def)
apply (rule whenE_throwError_corres, simp)
apply (simp add: lookup_failure_map_def)
apply simp
apply (rule_tac P="\<lambda>s. asid_table (asid_high_bits_of word2) = Some word1 \<longrightarrow> asid_pool_at word1 s" and
P'="pspace_aligned' and pspace_distinct'" in corres_inst)
apply (simp add: liftME_return)
apply (rule whenE_throwError_corres_initial, simp)
apply auto[1]
apply (rule corres_guard_imp)
apply (rule corres_splitEE)
apply simp
apply (rule get_asid_pool_corres_inv')
apply (simp add: bindE_assoc)
apply (rule corres_splitEE)
apply (rule corres_whenE)
apply (subst conj_assoc [symmetric])
apply (subst assocs_empty_dom_comp [symmetric])
apply (rule dom_ucast_eq)
apply (rule corres_trivial)
apply simp
apply simp
apply (rule_tac F="- dom pool \<inter> {x. ucast x + word2 \<noteq> 0} \<noteq> {}" in corres_gen_asm)
apply (frule dom_hd_assocsD)
apply (simp add: select_ext_fap[simplified free_asid_pool_select_def]
free_asid_pool_select_def)
apply (simp add: returnOk_liftE[symmetric])
apply (rule corres_returnOk)
apply (simp add: archinv_relation_def asid_pool_invocation_map_def)
apply (rule hoare_pre, wp whenE_wp)
apply (clarsimp simp: ucast_fst_hd_assocs)
apply (wp hoareE_TrueI whenE_wp getASID_wp | simp)+
apply ((clarsimp simp: p2_low_bits_max | rule TrueI impI)+)[2]
apply (wp whenE_wp getASID_wp)+
apply (clarsimp simp: valid_cap_def)
apply auto[1]
apply (simp add: isCap_simps split del: if_split)
apply (cases "invocation_type (mi_label mi) \<noteq> ArchInvocationLabel ARMASIDControlMakePool")
apply (simp split: invocation_label.split arch_invocation_label.split)
apply (subgoal_tac "length excaps' = length excaps")
prefer 2
apply (simp add: list_all2_iff)
apply (cases args, simp)
apply (rename_tac a0 as)
apply (case_tac as, simp)
apply (rename_tac a1 as')
apply (cases excaps, simp)
apply (rename_tac excap0 exs)
apply (case_tac exs)
apply (auto split: list.split)[1]
apply (rename_tac excap1 exss)
apply (case_tac excap0)
apply (rename_tac c0 slot0)
apply (case_tac excap1)
apply (rename_tac c1 slot1)
apply (clarsimp simp: Let_def split del: if_split)
apply (cases excaps', simp)
apply (case_tac list, simp)
apply (rename_tac c0' exs' c1' exss')
apply (clarsimp split del: if_split)
apply (rule corres_guard_imp)
apply (rule corres_splitEE[where r'="\<lambda>p p'. p = p' o ucast"])
apply (rule corres_trivial)
apply (clarsimp simp: state_relation_def arch_state_relation_def)
apply (simp only: bindE_assoc)
apply (rule corres_splitEE)
apply (rule corres_whenE)
apply (subst assocs_empty_dom_comp [symmetric])
apply (simp add: o_def)
apply (rule dom_ucast_eq_7)
apply (rule corres_trivial, simp, simp)
apply (simp split del: if_split)
apply (rule_tac F="- dom (asidTable \<circ> ucast) \<inter> {x. x \<le> 2 ^ asid_high_bits - 1} \<noteq> {}"
in corres_gen_asm)
apply (drule dom_hd_assocsD)
apply (simp add: select_ext_fa[simplified free_asid_select_def]
free_asid_select_def o_def returnOk_liftE[symmetric]
split del: if_split)
apply (thin_tac "fst a \<notin> b \<and> P" for a b P)
apply (case_tac "isUntypedCap a \<and> capBlockSize a = objBits (makeObject::asidpool)
\<and> \<not> capIsDevice a")
prefer 2
apply (rule corres_guard_imp)
apply (rule corres_trivial)
apply (case_tac ad, simp_all add: isCap_simps split del: if_split)[1]
apply (case_tac x21, simp_all split del: if_split)[1]
apply (clarsimp simp: objBits_simps archObjSize_def
split del: if_split)
apply clarsimp
apply (rule TrueI)+
apply (clarsimp simp: isCap_simps cap_relation_Untyped_eq lookupTargetSlot_def
objBits_simps archObjSize_def bindE_assoc split_def)
apply (rule corres_splitEE)
apply (fold ser_def)
apply (rule ensureNoChildren_corres, rule refl)
apply (rule corres_splitEE)
apply (erule lookupSlotForCNodeOp_corres, rule refl)
apply (rule corres_splitEE)
apply (rule ensureEmptySlot_corres)
apply clarsimp
apply (rule corres_returnOk[where P="\<top>"])
apply (clarsimp simp add: archinv_relation_def asid_ci_map_def split_def)
apply (clarsimp simp add: ucast_assocs[unfolded o_def] split_def
filter_map asid_high_bits_def)
apply (simp add: ord_le_eq_trans [OF word_n1_ge])
apply (wp hoare_drop_imps)+
apply (simp add: o_def validE_R_def)
apply (wp whenE_wp)+
apply fastforce
apply clarsimp
apply (simp add: null_def split_def asid_high_bits_def word_le_make_less)
apply (subst hd_map, assumption)
\<comment> \<open>need abstract guard to show list nonempty\<close>
apply (simp add: word_le_make_less)
apply (subst ucast_ucast_len)
apply (drule hd_in_set)
apply simp
apply fastforce
apply (simp add: isCap_simps split del: if_split)
apply (cases "invocation_type (mi_label mi) = ArchInvocationLabel ARMPageMap")
apply (rename_tac dev frame_ptr cap_rights vmpage_size map_data)
apply (case_tac "\<not>(2 < length args \<and> excaps \<noteq> [])", clarsimp split: list.splits)
apply (simp add: Let_def neq_Nil_conv)
apply (elim exE conjE)
apply (rename_tac pd_cap pd_cap_cnode pd_cap_slot excaps_rest)
apply (clarsimp split: list.split, intro conjI impI allI; clarsimp)
apply (rename_tac vaddr rights_mask attr pd_cap' excaps'_rest args_rest)
apply (rule corres_guard_imp)
apply (rule_tac P="\<nexists>pd asid. pd_cap = cap.ArchObjectCap (arch_cap.PageDirectoryCap pd (Some asid))"
in corres_symmetric_bool_cases[where Q=\<top> and Q'=\<top>, OF refl])
apply (case_tac pd_cap; clarsimp; rename_tac pd_acap pd_acap'; case_tac pd_acap; clarsimp)
apply (rule corres_splitEE[where r'="(=)" and P=\<top> and P'=\<top>])
apply (clarsimp simp: corres_returnOkTT)
apply (rule_tac F="pd_cap = cap.ArchObjectCap (arch_cap.PageDirectoryCap (fst rv) (Some (snd rv)))"
in corres_gen_asm)
apply (clarsimp cong: option.case_cong)
apply (rename_tac vspace asid)
apply wpfix \<comment> \<open>get asid and vspace parameters in schematic preconditions\<close>
apply (rule_tac P="map_data = None \<and> kernel_base \<le> vaddr + 2 ^ pageBitsForSize vmpage_size - 1
\<or> (\<exists>asid' vaddr'. map_data = Some (asid', vaddr') \<and> (asid',vaddr') \<noteq> (asid,vaddr))"
in corres_symmetric_bool_cases[where Q=\<top> and Q'=\<top>, OF refl])
apply (erule disjE; clarsimp simp: whenE_def kernel_base_def pptrBase_def
split: option.splits)
apply clarsimp
apply (rule corres_splitEE[where r'=dc and P=\<top> and P'=\<top>])
apply (case_tac map_data
; clarsimp simp: whenE_def kernel_base_def pptrBase_def
corres_returnOkTT)
\<comment> \<open>pd=undefined as vspace_at_asid not used in find_pd_for_asid_corres and avoid unresolved schematics\<close>
apply (rule corres_splitEE[
OF corres_lookup_error[OF find_pd_for_asid_corres[where pd=undefined, OF refl]]])
apply (rule whenE_throwError_corres; simp)
apply (rule corres_splitEE[where r'=dc, OF checkVPAlignment_corres])
apply (rule corres_splitEE[OF createMappingEntries_corres]
; simp add: mask_vmrights_corres vm_attributes_corres)
apply (rule corres_splitEE[OF ensureSafeMapping_corres], assumption)
apply (rule corres_returnOkTT)
\<comment> \<open>program split done, now prove resulting preconditions and Hoare triples\<close>
apply (simp add: archinv_relation_def page_invocation_map_def)
apply wpsimp+
apply (wp find_pd_for_asid_pd_at_asid_again)
apply (wp findPDForASID_pd_at_wp)
apply wpsimp
apply wpsimp
apply wpsimp
apply wpsimp
apply (clarsimp simp: cte_wp_at_caps_of_state cong: conj_cong)
apply (rename_tac pd_ptr asid')
apply (prop_tac "is_aligned pd_ptr pd_bits")
apply (clarsimp simp: valid_cap_simps cap_aligned_def pd_bits)
apply (prop_tac "\<forall>vaddr. lookup_pd_slot pd_ptr vaddr && ~~ mask pd_bits = pd_ptr")
apply (clarsimp simp: lookup_pd_slot_eq)
apply (fastforce simp: valid_cap_simps mask_def aligned_sum_less_kernel_base word_not_le
vmsz_aligned_def vspace_at_asid_def
intro!: page_directory_pde_at_lookupI page_directory_at_aligned_pd_bits)
apply fastforce
apply (simp split del: if_split)
apply (cases "invocation_type (mi_label mi) = ArchInvocationLabel ARMPageUnmap")
apply simp
apply (rule corres_returnOk)
apply (clarsimp simp: archinv_relation_def page_invocation_map_def)
apply (cases "ARM_H.isPageFlushLabel (invocation_type (mi_label mi))")
apply (clarsimp simp: ARM_H.isPageFlushLabel_def split del: if_split)
apply (clarsimp split: invocation_label.splits arch_invocation_label.splits split del: if_split)
apply (rule decodeARMPageFlush_corres,
clarsimp simp: ARM_H.isPageFlushLabel_def)+
apply (clarsimp simp: ARM_H.isPageFlushLabel_def split del: if_split)
apply (cases "invocation_type (mi_label mi) = ArchInvocationLabel ARMPageGetAddress")
apply simp
apply (rule corres_returnOk)
apply (clarsimp simp: archinv_relation_def page_invocation_map_def)
subgoal by (clarsimp split: invocation_label.splits arch_invocation_label.splits split del: if_split)
apply (simp add: isCap_simps split del: if_split)
apply (simp split: invocation_label.split arch_invocation_label.splits split del: if_split)
apply (intro conjI impI allI)
apply (simp split: list.split, intro conjI impI allI, simp_all)[1]
apply (clarsimp simp: neq_Nil_conv)
apply (rule whenE_throwError_corres_initial, simp+)
apply (simp split: cap.split arch_cap.split option.split,
intro conjI allI impI, simp_all)[1]
apply (rule whenE_throwError_corres_initial, simp)
apply (simp add: kernel_base_def pptrBase_def)
apply (rule corres_guard_imp)
apply (rule corres_splitEE)
apply (rule corres_lookup_error)
apply (rule find_pd_for_asid_corres[OF refl])
apply (rule whenE_throwError_corres, simp, simp)
apply (rule corres_splitEE)
apply (simp add: pageBits_def ptBits_def pdeBits_def)
apply (rule get_master_pde_corres')
apply (simp add: unlessE_whenE)
apply (rule corres_splitEE)
apply (rule corres_whenE)
apply clarsimp
apply (case_tac oldpde, simp_all)[1]
apply (rule corres_trivial)
apply simp
apply simp
apply (rule corres_trivial)
apply (rule corres_returnOk)
apply (clarsimp simp: archinv_relation_def page_table_invocation_map_def)
apply (clarsimp simp: attribs_from_word_def attribsFromWord_def Let_def)
apply (simp add: shiftr_shiftl1 pageBits_def ptBits_def pdeBits_def pteBits_def)
apply (wp whenE_wp get_master_pde_wp getPDE_wp find_pd_for_asid_inv
| wp (once) hoare_drop_imps)+
apply (fastforce simp: valid_cap_def mask_def
invs_vspace_objs[simplified])
apply (clarsimp simp: valid_cap'_def)
apply fastforce
apply (clarsimp simp: unlessE_whenE liftE_bindE)
apply (rule stronger_corres_guard_imp)
apply (rule corres_symb_exec_r_conj)
apply (rule_tac F="isArchCap isPageTableCap (cteCap cteVal)"
in corres_gen_asm2)
apply (rule corres_split[OF isFinalCapability_corres[where ptr=slot]])
apply (drule mp)
apply (clarsimp simp: isCap_simps final_matters'_def)
apply (rule whenE_throwError_corres)
apply simp
apply simp
apply (rule corres_trivial, simp add: returnOk_def archinv_relation_def
page_table_invocation_map_def)
apply (wp getCTE_wp' | wp (once) hoare_drop_imps)+
apply (clarsimp)
apply (rule no_fail_pre, rule no_fail_getCTE)
apply (erule conjunct2)
apply (clarsimp simp: cte_wp_at_caps_of_state
cap_rights_update_def acap_rights_update_def)
apply (clarsimp simp add: cap_rights_update_def acap_rights_update_def)
apply (clarsimp simp: cte_wp_at_ctes_of
cap_rights_update_def acap_rights_update_def
cte_wp_at_caps_of_state)
apply (drule pspace_relation_ctes_ofI[OF _ caps_of_state_cteD, rotated],
erule invs_pspace_aligned', clarsimp+)
apply (simp add: isCap_simps)
apply (simp add: isCap_simps split del: if_split)
apply (cases "ARM_H.isPDFlushLabel (invocation_type (mi_label mi))")
apply (clarsimp split del: if_split)
apply (cases args, simp)
apply (rename_tac a0 as)
apply (case_tac as, simp)
apply (rename_tac a1 as')
apply clarsimp
apply (rule corres_guard_imp)
apply (rule whenE_throwError_corres, simp)
apply clarsimp
apply (rule whenE_throwError_corres, simp)
apply (clarsimp simp: kernel_base_def pptrBase_def)
apply (rule case_option_corresE)
apply (rule corres_trivial)
apply clarsimp
apply clarsimp
apply (rule corres_splitEE)
apply (rule corres_lookup_error)
apply (rule find_pd_for_asid_corres[OF refl])
apply (rule whenE_throwError_corres, simp)
apply clarsimp
apply (simp add: liftE_bindE)
apply (rule corres_split[OF _ _ resolve_vaddr_valid_mapping_size])
apply clarsimp
apply (rule resolveVAddr_corres[THEN corres_gen_asm])
apply simp
apply (clarsimp simp: not_le)
apply (case_tac rva)
apply clarsimp
apply (rule_tac P'="pspace_aligned' and pspace_distinct'
and valid_global_refs'" in corres_inst[where P="\<top>"])
apply (rule corres_returnOk)
apply (clarsimp simp: archinv_relation_def page_directory_invocation_map_def)
apply (clarsimp simp: Let_def liftE_bindE checkValidMappingSize_def)
apply (rule corres_stateAssert_implied[where P'="\<top>", simplified])
apply (rule corres_guard_imp)
apply (rule whenE_throwError_corres, simp)
apply clarsimp
apply (rule corres_trivial)
apply (rule corres_returnOk)
apply (clarsimp simp: archinv_relation_def page_directory_invocation_map_def
flush_type_map)+
apply (clarsimp simp: state_relation_def)
apply (frule pspace_relation_cte_wp_at,
simp add: cte_wp_at_caps_of_state, simp+)
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (drule(1) valid_global_refsD_with_objSize)
subgoal by (clarsimp simp: is_page_cap_def split: cap.split_asm)
apply (wp hoare_drop_imps)+
apply (clarsimp simp: valid_cap_simps mask_2pm1 linorder_not_le split: option.split)
apply (intro conjI; (clarsimp)?)
apply (clarsimp simp: invs'_def valid_state'_def valid_pspace'_def
split: option.splits)
apply clarsimp
done
lemma arch_performInvocation_corres:
"archinv_relation ai ai' \<Longrightarrow>
corres (dc \<oplus> (=))
(einvs and ct_active and valid_arch_inv ai)
(invs' and ct_active' and valid_arch_inv' ai' and (\<lambda>s. vs_valid_duplicates' (ksPSpace s)))
(arch_perform_invocation ai) (Arch.performInvocation ai')"
apply (clarsimp simp: arch_perform_invocation_def
ARM_H.performInvocation_def
performARMMMUInvocation_def)
apply (cases ai)
apply (clarsimp simp: archinv_relation_def)
apply (rule corres_underlying_split[OF _ corres_return_eq_same[OF refl]])
apply (erule corres_guard_imp [OF performPageTableInvocation_corres])
apply (fastforce simp: valid_arch_inv_def)
apply (fastforce simp: valid_arch_inv'_def)
apply wp
apply wp
apply (clarsimp simp: archinv_relation_def)
apply (rule corres_underlying_split[OF _ corres_return_eq_same[OF refl]])
apply (erule corres_guard_imp [OF performPageDirectoryInvocation_corres])
apply (fastforce simp: valid_arch_inv_def)
apply (fastforce simp: valid_arch_inv'_def)
apply wp
apply wp
apply (clarsimp simp: archinv_relation_def)
apply (erule corres_guard_imp [OF performPageInvocation_corres])
apply (fastforce simp: valid_arch_inv_def)
apply (fastforce simp: valid_arch_inv'_def)
apply (clarsimp simp: archinv_relation_def)
apply (rule corres_underlying_split[OF _ corres_return_eq_same[OF refl]])
apply (rule corres_guard_imp [OF performASIDControlInvocation_corres], rule refl)
apply (fastforce simp: valid_arch_inv_def)
apply (fastforce simp: valid_arch_inv'_def)
apply wp
apply wp
apply (clarsimp simp: archinv_relation_def)
apply (rule corres_underlying_split[OF _ corres_return_eq_same[OF refl]])
apply (rule corres_guard_imp [OF performASIDPoolInvocation_corres], rule refl)
apply (fastforce simp: valid_arch_inv_def)
apply (fastforce simp: valid_arch_inv'_def)
apply wp+
done
lemma asid_pool_typ_at_ext':
"asid_pool_at' = obj_at' (\<top>::asidpool \<Rightarrow> bool)"
apply (rule ext)+
apply (simp add: typ_at_to_obj_at_arches)
done
lemma st_tcb_strg':
"st_tcb_at' P p s \<longrightarrow> tcb_at' p s"
by (auto simp: pred_tcb_at')
lemma performASIDControlInvocation_tcb_at':
"\<lbrace>st_tcb_at' active' p and invs' and ct_active' and valid_aci' aci\<rbrace>
performASIDControlInvocation aci
\<lbrace>\<lambda>y. tcb_at' p\<rbrace>"
apply (rule hoare_name_pre_state)
apply (clarsimp simp: performASIDControlInvocation_def split: asidcontrol_invocation.splits)
apply (clarsimp simp: valid_aci'_def cte_wp_at_ctes_of cong: conj_cong)
apply (wp static_imp_wp |simp add:placeNewObject_def2)+
apply (wp createObjects_orig_obj_at2' updateFreeIndex_pspace_no_overlap' getSlotCap_wp static_imp_wp)+
apply (clarsimp simp: projectKO_opts_defs)
apply (strengthen st_tcb_strg' [where P=\<top>])
apply (wp deleteObjects_invs_derivatives[where p="makePoolParent aci"]
hoare_vcg_ex_lift deleteObjects_cte_wp_at'[where d=False]
deleteObjects_st_tcb_at'[where p="makePoolParent aci"] static_imp_wp
updateFreeIndex_pspace_no_overlap' deleteObject_no_overlap[where d=False])+
apply (case_tac ctea)
apply (clarsimp)
apply (frule ctes_of_valid_cap')
apply (simp add:invs_valid_objs')+
apply (clarsimp simp:valid_cap'_def capAligned_def cte_wp_at_ctes_of)
apply (strengthen refl order_refl
pred_tcb'_weakenE[mk_strg I E])
apply (clarsimp simp: conj_comms invs_valid_pspace' isCap_simps
descendants_range'_def2 empty_descendants_range_in')
apply (frule ctes_of_valid', clarsimp, simp,
drule capFreeIndex_update_valid_cap'[where fb="2 ^ pageBits", rotated -1],
simp_all)
apply (simp add: pageBits_def is_aligned_def minUntypedSizeBits_def)
apply (simp add: valid_cap_simps' range_cover_def objBits_simps archObjSize_def
capAligned_def unat_eq_0 and_mask_eq_iff_shiftr_0[symmetric]
word_bw_assocs untypedBits_defs)
apply clarsimp
apply (drule(1) cte_cap_in_untyped_range,
fastforce simp add: cte_wp_at_ctes_of, assumption, simp_all)
apply (clarsimp simp: invs'_def valid_state'_def if_unsafe_then_cap'_def cte_wp_at_ctes_of)
apply clarsimp
done
lemma invokeArch_tcb_at':
"\<lbrace>invs' and valid_arch_inv' ai and ct_active' and st_tcb_at' active' p\<rbrace>
Arch.performInvocation ai
\<lbrace>\<lambda>rv. tcb_at' p\<rbrace>"
apply (simp add: ARM_H.performInvocation_def performARMMMUInvocation_def)
apply (cases ai, simp_all)
apply (wp, clarsimp simp: pred_tcb_at')
apply (wp, clarsimp simp: pred_tcb_at')
apply (wp, clarsimp simp: st_tcb_strg'[rule_format])
apply (wp performASIDControlInvocation_tcb_at', clarsimp simp: valid_arch_inv'_def)
apply (wp, clarsimp simp: pred_tcb_at')
done
crunch pspace_no_overlap'[wp]: setThreadState "pspace_no_overlap' w s"
(simp: unless_def)
lemma sts_cte_cap_to'[wp]:
"\<lbrace>ex_cte_cap_to' p\<rbrace> setThreadState st t \<lbrace>\<lambda>rv. ex_cte_cap_to' p\<rbrace>"
by (wp ex_cte_cap_to'_pres)
lemma valid_slots_duplicated_lift':
assumes ko_wp_at':
"\<And>P p. \<lbrace>ko_wp_at' (\<lambda>ko. P (vs_entry_align ko)) p \<rbrace> f \<lbrace>\<lambda>rv. ko_wp_at' (\<lambda>ko. P (vs_entry_align ko)) p\<rbrace>"
and pt_at:
"\<And>p. \<lbrace>page_table_at' p \<rbrace> f \<lbrace>\<lambda>rv. page_table_at' p\<rbrace>"
and pd_at:
"\<And>p. \<lbrace>page_directory_at' p\<rbrace> f \<lbrace>\<lambda>rv. page_directory_at' p\<rbrace>"
shows
"\<lbrace>valid_slots_duplicated' x\<rbrace> f \<lbrace>\<lambda>r. valid_slots_duplicated' x\<rbrace>"
apply (simp add:valid_slots_duplicated'_def)
apply (case_tac x)
apply (case_tac a)
apply (case_tac aa)
apply simp_all
apply (rule hoare_pre)
apply simp
apply (wp hoare_vcg_ex_lift ko_wp_at' pt_at pd_at | simp)+
apply (case_tac b)
apply (case_tac a)
apply (wp hoare_vcg_ex_lift ko_wp_at' pt_at pd_at | simp)+
done
lemma setTCB_pdpt_bits'[wp]:
"\<lbrace>\<lambda>s. ko_wp_at' (\<lambda>ko. P (vs_entry_align ko)) p s\<rbrace>
setObject a (tcb::tcb)
\<lbrace>\<lambda>rv. ko_wp_at' (\<lambda>ko. P (vs_entry_align ko)) p\<rbrace>"
apply (clarsimp simp: setObject_def split_def valid_def in_monad
projectKOs pspace_aligned'_def ps_clear_upd
objBits_def[symmetric] lookupAround2_char1
split: if_split_asm)
apply (frule pspace_storable_class.updateObject_type[where v = tcb,simplified])
apply (clarsimp simp:ko_wp_at'_def)
apply (intro conjI)
subgoal by (clarsimp simp:updateObject_default_def assert_def bind_def
alignCheck_def in_monad when_def alignError_def magnitudeCheck_def
assert_opt_def return_def fail_def typeError_def objBits_simps
vs_entry_align_def
split:if_splits option.splits Structures_H.kernel_object.splits,
((erule(1) ps_clear_updE)+))
apply (clarsimp)
apply (erule(1) ps_clear_updE)
done
crunch vs_entry_align'[wp]:
threadSet "ko_wp_at' (\<lambda>ko. P (vs_entry_align ko)) p"
(wp: crunch_wps)
crunch vs_entry_align'[wp]:
addToBitmap "ko_wp_at' (\<lambda>ko. P (vs_entry_align ko)) p"
(wp: crunch_wps)
lemma tcbSchedEnqueue_vs_entry_align[wp]:
"\<lbrace>\<lambda>s. ko_wp_at' (\<lambda>ko. P (vs_entry_align ko)) p s\<rbrace>
tcbSchedEnqueue pa
\<lbrace>\<lambda>rv. ko_wp_at' (\<lambda>ko. P (vs_entry_align ko)) p\<rbrace>"
apply (clarsimp simp: tcbSchedEnqueue_def setQueue_def)
by (wp unless_wp | simp)+
crunch vs_entry_align[wp]:
setThreadState "ko_wp_at' (\<lambda>ko. P (vs_entry_align ko)) p"
(wp: crunch_wps)
lemma sts_valid_arch_inv':
"\<lbrace>valid_arch_inv' ai\<rbrace> setThreadState st t \<lbrace>\<lambda>rv. valid_arch_inv' ai\<rbrace>"
apply (cases ai, simp_all add: valid_arch_inv'_def)
apply (clarsimp simp: valid_pti'_def split: page_table_invocation.splits)
apply (intro allI conjI impI)
apply (wp | simp)+
apply (rename_tac page_invocation)
apply (case_tac page_invocation, simp_all add: valid_page_inv'_def)[1]
apply (wp valid_slots_lift' valid_slots_duplicated_lift'|simp)+
apply (clarsimp simp: valid_aci'_def split: asidcontrol_invocation.splits)
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (rule hoare_pre, wp)
apply clarsimp
apply (clarsimp simp: valid_apinv'_def split: asidpool_invocation.splits)
apply (rule hoare_pre, wp)
apply simp
done
lemma less_pptrBase_valid_pde_offset':
"\<lbrakk> vptr < pptrBase; x = 0 \<or> is_aligned vptr 24; x \<le> 0xF \<rbrakk>
\<Longrightarrow> valid_pde_mapping_offset' (((x * 4) + (vptr >> 20 << 2)) && mask pdBits)"
apply (clarsimp simp: pptrBase_def pdBits_def pageBits_def
valid_pde_mapping_offset'_def pd_asid_slot_def)
apply (drule word_le_minus_one_leq, simp add: pdeBits_def)
apply (drule le_shiftr[where u=vptr and n=20])
apply (subst(asm) iffD2[OF mask_eq_iff_w2p])
apply (simp add: word_size)
apply (simp add: shiftl_t2n unat_arith_simps iffD1[OF unat_mult_lem])
apply (erule disjE)
apply (simp add: shiftl_t2n unat_arith_simps iffD1[OF unat_mult_lem])
apply (frule arg_cong[where f="\<lambda>v. v && mask 6"])
apply (subst(asm) field_simps, subst(asm) is_aligned_add_helper[where n=6],
rule is_aligned_shiftl)
apply (rule is_aligned_shiftr, simp)
apply (simp add: unat_arith_simps iffD1[OF unat_mult_lem])
apply (simp add: mask_def[where n=6])
apply (simp add: shiftl_t2n unat_arith_simps iffD1[OF unat_mult_lem])
done
lemmas less_pptrBase_valid_pde_offset''
= less_pptrBase_valid_pde_offset'[where x=0, simplified]
lemma createMappingEntries_valid_pde_slots':
"\<lbrace>K (vmsz_aligned' vptr sz \<and> is_aligned pd pdBits
\<and> vptr < pptrBase)\<rbrace>
createMappingEntries base vptr sz vm_rights attrib pd
\<lbrace>\<lambda>rv s. valid_pde_slots' rv\<rbrace>,-"
apply (simp add: createMappingEntries_def valid_pde_slots'_def)
apply (cases sz, simp_all)
apply (wp | simp)+
apply (clarsimp simp: lookup_pd_slot_def Let_def mask_add_aligned)
apply (erule less_pptrBase_valid_pde_offset'')
apply (rule hoare_pre, wp)
apply (clarsimp simp: vmsz_aligned'_def superSectionPDEOffsets_def pdeBits_def del: ballI)
apply (subst p_0x3C_shift[symmetric])
apply (simp add: lookup_pd_slot_def Let_def)
apply (erule aligned_add_aligned)
apply (rule is_aligned_shiftl, rule is_aligned_shiftr)
apply simp
apply (simp add: pdBits_def pageBits_def word_bits_def)
apply (simp add: pdBits_def pageBits_def)
apply (clarsimp simp: upto_enum_step_def linorder_not_less pd_bits_def
lookup_pd_slot_def Let_def field_simps
mask_add_aligned pdeBits_def take_bit_Suc)
apply (erule less_pptrBase_valid_pde_offset'
[unfolded pdBits_def pageBits_def pdeBits_def, simplified], simp+)
done
lemma inv_ASIDPool: "inv ASIDPool = (\<lambda>v. case v of ASIDPool a \<Rightarrow> a)"
apply (rule ext)
apply (case_tac v)
apply simp
apply (rule inv_f_f, rule inj_onI)
apply simp
done
lemma findPDForASID_aligned[wp]:
"\<lbrace>valid_objs'\<rbrace> findPDForASID p \<lbrace>\<lambda>rv s. is_aligned rv pdBits\<rbrace>,-"
apply (simp add: findPDForASID_def assertE_def cong: option.case_cong
split del: if_split)
apply (rule hoare_pre)
apply (wp getASID_wp | wpc)+
apply clarsimp
apply (drule(1) obj_at_valid_objs')
apply (clarsimp simp: projectKOs valid_obj'_def inv_ASIDPool ranI
split: asidpool.split_asm)
done
lemma findPDForASID_valid_offset'[wp]:
"\<lbrace>valid_objs' and K (vptr < pptrBase)\<rbrace> findPDForASID p
\<lbrace>\<lambda>rv s. valid_pde_mapping_offset' (rv + (vptr >> 20 << 2) && mask pdBits)\<rbrace>,-"
apply (rule hoare_gen_asmE)
apply (rule hoare_post_imp_R, rule findPDForASID_aligned)
apply (simp add: mask_add_aligned)
apply (erule less_pptrBase_valid_pde_offset'')
done
lemma eq_arch_update':
"ArchObjectCap cp = cteCap cte \<Longrightarrow> is_arch_update' (ArchObjectCap cp) cte"
by (clarsimp simp: is_arch_update'_def isCap_simps)
lemma lookupPTSlot_page_table_at':
"\<lbrace>valid_objs'\<rbrace> lookupPTSlot pd vptr
\<lbrace>\<lambda>rv s. page_table_at' (rv && ~~ mask ptBits) s\<rbrace>,-"
apply (simp add:lookupPTSlot_def)
apply (wp getPDE_wp|wpc|simp add:checkPTAt_def)+
apply (clarsimp simp:ptBits_def lookup_pt_slot_no_fail_def pteBits_def)
apply (subst vaddr_segment_nonsense3[unfolded pt_bits_def pageBits_def,simplified])
apply (simp add:page_table_at'_def ptBits_def pageBits_def pteBits_def)
apply simp
done
lemma findPDForASID_page_directory_at':
notes checkPDAt_inv[wp del]
shows "\<lbrace>\<top>\<rbrace> findPDForASID asiv
\<lbrace>\<lambda>rv s. page_directory_at' (lookup_pd_slot rv vptr && ~~ mask pdBits) s\<rbrace>,-"
apply (simp add:findPDForASID_def)
apply (wp getASID_wp|simp add:checkPDAt_def | wpc)+
apply (clarsimp simp:lookup_pd_slot_def pdBits_def pdeBits_def)
apply (subst vaddr_segment_nonsense[unfolded pd_bits_def pdeBits_def pageBits_def,simplified])
apply (simp add:page_directory_at'_def pdBits_def pageBits_def pdeBits_def)
apply simp
done
definition "slots_duplicated_ensured \<equiv> \<lambda>m s. case m of
Inl (pte, xs) \<Rightarrow> (case pte of
pte.LargePagePTE _ _ _ _ _ \<Rightarrow> \<exists>p. xs = [p, p+4 .e. p + mask 6] \<and> is_aligned p 6
\<and> page_table_at' (p && ~~ mask ptBits) s
| pte.InvalidPTE \<Rightarrow> False
| _ \<Rightarrow> \<exists>p. xs = [p]
\<and> page_table_at' (p && ~~ mask ptBits) s)
| Inr (pde, xs) \<Rightarrow> (case pde of
pde.SuperSectionPDE _ _ _ _ _ _ \<Rightarrow> \<exists>p. xs = [p, p+4 .e. p + mask 6] \<and> is_aligned p 6
\<and> page_directory_at' (p && ~~ mask pdBits) s \<and> is_aligned p 6
| pde.InvalidPDE \<Rightarrow> False
| _ \<Rightarrow> \<exists>p. xs = [p]
\<and> page_directory_at' (p && ~~ mask pdBits) s)"
lemma ensureSafeMapping_valid_slots_duplicated':
"\<lbrace>\<lambda>s. slots_duplicated_ensured entries s\<rbrace>
ensureSafeMapping entries
\<lbrace>\<lambda>rv s. valid_slots_duplicated' entries s\<rbrace>,-"
apply (simp add:ensureSafeMapping_def)
apply (case_tac entries)
apply (case_tac a)
apply (case_tac aa)
apply (rule hoare_pre)
apply (simp add:slots_duplicated_ensured_def | wp)+
apply (rule hoare_pre)
apply (wp mapME_x_inv_wp getPTE_wp| wpc)+
apply clarsimp
apply (clarsimp simp:valid_slots_duplicated'_def)
apply (simp add:slots_duplicated_ensured_def)
apply (rule hoare_pre)
apply (rule_tac P = "\<exists>p. b = [p]" and
P' = "\<lambda>s. \<exists>p. b = [p] \<and> page_table_at' (p && ~~ mask ptBits) s" in hoare_gen_asmE)
apply (clarsimp simp:mapME_singleton)
apply (wp getPTE_wp|wpc)+
apply (clarsimp simp:valid_slots_duplicated'_def obj_at'_real_def split:option.splits)
apply (intro impI conjI)
apply (erule ko_wp_at'_weakenE)
apply (simp add:projectKO_opt_pte vs_entry_align_def
split:Structures_H.kernel_object.splits
arch_kernel_object.splits)
apply (erule ko_wp_at'_weakenE)
apply (simp add:projectKO_opt_pte vs_entry_align_def
split:Structures_H.kernel_object.splits
arch_kernel_object.splits)
apply clarsimp
apply (case_tac b)
apply (case_tac a)
apply (rule hoare_pre)
apply (simp add:slots_duplicated_ensured_def | wp)+
apply (rule hoare_pre)
apply (rule_tac P = "\<exists>p. ba = [p]" and
P' = "\<lambda>s. \<exists>p. ba = [p] \<and> page_directory_at' (p && ~~ mask pdBits) s" in hoare_gen_asmE)
apply (clarsimp simp:mapME_singleton)
apply (wp getPDE_wp|wpc)+
apply (clarsimp simp:valid_slots_duplicated'_def obj_at'_real_def split:option.splits)
apply (intro impI conjI)
apply (erule ko_wp_at'_weakenE)
apply (simp add:projectKO_opt_pde vs_entry_align_def
split:Structures_H.kernel_object.splits
arch_kernel_object.splits)
apply (erule ko_wp_at'_weakenE)
apply (simp add:projectKO_opt_pde vs_entry_align_def
split:Structures_H.kernel_object.splits
arch_kernel_object.splits)
apply clarsimp
apply (simp add:slots_duplicated_ensured_def)
apply (rule hoare_pre)
apply (wp mapME_x_inv_wp getPDE_wp| wpc)+
apply clarsimp
apply (fastforce simp:valid_slots_duplicated'_def)
done
(* FIXME: this lemma is too specific *)
lemma lookupPTSlot_aligned:
"\<lbrace>\<lambda>s. is_aligned vptr 16 \<and> valid_objs' s\<rbrace> lookupPTSlot pd vptr \<lbrace>\<lambda>p s. is_aligned p 6\<rbrace>,-"
apply (simp add:lookupPTSlot_def)
apply (wp getPDE_wp |wpc|simp)+
apply (clarsimp simp:obj_at'_real_def ko_wp_at'_def)
apply (erule(1) valid_objsE')
apply (clarsimp simp:projectKO_opt_pde
split:Structures_H.kernel_object.splits arch_kernel_object.splits)
apply (simp add:valid_obj'_def lookup_pt_slot_no_fail_def)
apply (rule aligned_add_aligned)
apply (erule is_aligned_ptrFromPAddr_n)
apply (simp add: ptBits_def pteBits_def)
apply (rule is_aligned_shiftl,simp)
apply (rule is_aligned_andI1)
apply (rule is_aligned_shiftr)
apply simp
apply (simp add: ptBits_def)
done
lemma createMappingEntires_valid_slots_duplicated'[wp]:
"\<lbrace>\<lambda>s. vs_valid_duplicates' (ksPSpace s) \<and> vmsz_aligned vptr vmsz \<and> valid_objs' s
\<and> page_directory_at' (lookup_pd_slot pd vptr && ~~ mask pdBits) s \<and> is_aligned pd pdBits\<rbrace>
createMappingEntries base vptr vmsz vmrights attrib pd
\<lbrace>\<lambda>rv s. slots_duplicated_ensured rv s\<rbrace>, -"
apply (clarsimp simp:createMappingEntries_def)
apply (rule hoare_pre)
apply (wpc | wp lookupPTSlot_page_table_at'
| simp add: slots_duplicated_ensured_def)+
apply (rule_tac Q' = "\<lambda>p s. is_aligned p 6 \<and> page_table_at' (p && ~~ mask ptBits) s"
in hoare_post_imp_R)
apply (wp lookupPTSlot_aligned lookupPTSlot_page_table_at')
apply (rename_tac rv s)
apply (rule_tac x = rv in exI)
apply (clarsimp simp: largePagePTEOffsets_def pteBits_def)
apply (frule is_aligned_no_wrap'[where off = "0x3c"])
apply simp
apply (drule upto_enum_step_shift[where n = 6 and m = 2,simplified])
apply (clarsimp simp: mask_def add.commute upto_enum_step_def take_bit_Suc)
apply simp
apply wp+
apply (intro conjI impI)
apply ((clarsimp simp: vmsz_aligned_def pageBitsForSize_def
slots_duplicated_ensured_def
split:vmpage_size.splits)+)[8]
apply clarsimp
apply (drule lookup_pd_slot_aligned_6)
apply (simp add:pdBits_def pageBits_def pdeBits_def)
apply (clarsimp simp:slots_duplicated_ensured_def)
apply (rule_tac x = "(lookup_pd_slot pd vptr)" in exI)
apply clarsimp
apply (frule is_aligned_no_wrap'[where off = "0x3c" and sz = 6])
apply simp
apply (drule upto_enum_step_shift[where n = 6 and m = 2,simplified])
apply (clarsimp simp: mask_def add.commute upto_enum_step_def take_bit_Suc
superSectionPDEOffsets_def pdeBits_def)
done
lemma arch_decodeARMPageFlush_wf:
"ARM_H.isPageFlushLabel (invocation_type label) \<Longrightarrow>
\<lbrace>invs' and
valid_cap'
(capability.ArchObjectCap (arch_capability.PageCap d word vmrights vmpage_size option)) and
cte_wp_at'
((=) (capability.ArchObjectCap (arch_capability.PageCap d word vmrights vmpage_size option)) \<circ>
cteCap)
slot and
(\<lambda>s. \<forall>x\<in>set excaps. cte_wp_at' ((=) (fst x) \<circ> cteCap) (snd x) s) and
sch_act_simple and
(\<lambda>s. vs_valid_duplicates' (ksPSpace s))\<rbrace>
decodeARMPageFlush label args (arch_capability.PageCap d word vmrights vmpage_size option)
\<lbrace>valid_arch_inv'\<rbrace>, -"
apply (simp add: decodeARMPageFlush_def)
apply (rule hoare_pre)
apply (wp throwE_R whenE_throwError_wp | wpc | clarsimp simp: if_apply_def2)+
apply (simp add: valid_arch_inv'_def valid_page_inv'_def)
apply fastforce
done
lemma arch_decodeInvocation_wf[wp]:
notes ensureSafeMapping_inv[wp del]
shows "\<lbrace>invs' and valid_cap' (ArchObjectCap arch_cap) and
cte_wp_at' ((=) (ArchObjectCap arch_cap) o cteCap) slot and
(\<lambda>s. \<forall>x \<in> set excaps. cte_wp_at' ((=) (fst x) o cteCap) (snd x) s) and
sch_act_simple and (\<lambda>s. vs_valid_duplicates' (ksPSpace s))\<rbrace>
Arch.decodeInvocation label args cap_index slot arch_cap excaps
\<lbrace>valid_arch_inv'\<rbrace>,-"
apply (cases arch_cap)
apply (simp add: decodeARMMMUInvocation_def ARM_H.decodeInvocation_def
Let_def split_def isCap_simps
cong: if_cong split del: if_split)
apply (rule hoare_pre)
apply ((wp whenE_throwError_wp getASID_wp
| wpc | simp add: valid_arch_inv'_def valid_apinv'_def)+)[1]
apply (clarsimp simp: word_neq_0_conv valid_cap'_def valid_arch_inv'_def valid_apinv'_def)
apply (rule conjI)
apply (erule cte_wp_at_weakenE')
apply (simp, drule_tac t="cteCap c" in sym, simp)
apply (subst (asm) conj_assoc [symmetric])
apply (subst (asm) assocs_empty_dom_comp [symmetric])
apply (drule dom_hd_assocsD)
apply (simp add: capAligned_def)
apply (elim conjE)
apply (subst field_simps, erule is_aligned_add_less_t2n)
apply assumption
apply (simp add: asid_low_bits_def asid_bits_def)
apply assumption
\<comment> \<open>ASIDControlCap\<close>
apply (simp add: decodeARMMMUInvocation_def ARM_H.decodeInvocation_def
Let_def split_def isCap_simps
cong: if_cong invocation_label.case_cong arch_invocation_label.case_cong
list.case_cong prod.case_cong
split del: if_split)
apply (rule hoare_pre)
apply ((wp whenE_throwError_wp ensureEmptySlot_stronger
| wpc
| simp add: valid_arch_inv'_def valid_aci'_def is_aligned_shiftl_self
split del: if_split)+)[1]
apply (rule_tac Q'=
"\<lambda>rv. K (fst (hd [p\<leftarrow>assocs asidTable . fst p \<le> 2 ^ asid_high_bits - 1 \<and> snd p = None])
<< asid_low_bits \<le> 2 ^ asid_bits - 1) and
real_cte_at' rv and
ex_cte_cap_to' rv and
cte_wp_at' (\<lambda>cte. \<exists>idx. cteCap cte = (UntypedCap False frame pageBits idx))
(snd (excaps!0)) and
sch_act_simple and
(\<lambda>s. descendants_of' (snd (excaps!0)) (ctes_of s) = {}) "
in hoare_post_imp_R)
apply (simp add: lookupTargetSlot_def)
apply wp
apply (clarsimp simp: cte_wp_at_ctes_of)
apply (simp split del: if_split)
apply (wp ensureNoChildren_sp whenE_throwError_wp|wpc)+
apply clarsimp
apply (rule conjI)
apply (clarsimp simp: null_def neq_Nil_conv)
apply (drule filter_eq_ConsD)
apply clarsimp
apply (rule shiftl_less_t2n)
apply (simp add: asid_bits_def asid_low_bits_def asid_high_bits_def)
apply unat_arith
apply (simp add: asid_bits_def)
apply clarsimp
apply (rule conjI, fastforce)
apply (clarsimp simp: cte_wp_at_ctes_of objBits_simps archObjSize_def)
apply (rule conjI)
apply (case_tac cteb; clarsimp)
apply (drule ctes_of_valid_cap', fastforce)
apply assumption
apply (simp add: ex_cte_cap_to'_def cte_wp_at_ctes_of)
apply (drule_tac t="cteCap ctea" in sym, simp)
apply (drule_tac t="cteCap cte" in sym, clarsimp)
apply (rule_tac x=ba in exI)
apply simp
\<comment> \<open>PageCap\<close>
apply (simp add: decodeARMMMUInvocation_def ARM_H.decodeInvocation_def
Let_def split_def isCap_simps
cong: if_cong split del: if_split)
apply (cases "invocation_type label = ArchInvocationLabel ARMPageMap")
apply (rename_tac word vmrights vmpage_size option)
apply (simp add: split_def split del: if_split
cong: list.case_cong prod.case_cong)
apply (rule hoare_pre)
apply (wpsimp simp: valid_arch_inv'_def valid_page_inv'_def)
apply (rule hoare_vcg_conj_lift_R,(wp ensureSafeMapping_inv)[1])+
apply (wpsimp wp: whenE_throwError_wp checkVP_wpR hoare_vcg_const_imp_lift_R
hoare_drop_impE_R ensureSafeMapping_valid_slots_duplicated'
createMappingEntries_valid_pde_slots' findPDForASID_page_directory_at'
simp: valid_arch_inv'_def valid_page_inv'_def)+
apply (clarsimp simp: neq_Nil_conv invs_valid_objs' linorder_not_le
cte_wp_at_ctes_of)
apply (drule ctes_of_valid', fastforce)+
apply (case_tac option; clarsimp, drule_tac t="cteCap cte" in sym, simp)
apply (clarsimp simp: valid_cap'_def ptBits_def pageBits_def
is_arch_update'_def isCap_simps capAligned_def vmsz_aligned'_def
cong: conj_cong)
apply (rule conjI)
apply (erule is_aligned_addrFromPPtr_n, case_tac vmpage_size, simp_all)[1]
apply (simp add: vmsz_aligned_def)
apply (rule conjI)
apply (erule order_le_less_trans[rotated])
apply (erule is_aligned_no_overflow'[simplified field_simps])
apply (clarsimp simp: page_directory_at'_def pdBits_eq lookup_pd_slot_eq)+
apply (clarsimp simp: valid_cap'_def ptBits_def pageBits_def
is_arch_update'_def isCap_simps capAligned_def vmsz_aligned'_def
cong: conj_cong)
apply (rule conjI)
apply (erule is_aligned_addrFromPPtr_n, case_tac vmpage_size, simp_all)[1]
apply (simp add: vmsz_aligned_def pd_bits)
apply (clarsimp simp: page_directory_at'_def lookup_pd_slot_eq[simplified pd_bits])
apply (cases "invocation_type label = ArchInvocationLabel ARMPageUnmap")
apply (simp split del: if_split)
apply (rule hoare_pre, wp)
apply (clarsimp simp: valid_arch_inv'_def valid_page_inv'_def)
apply (thin_tac "Ball S P" for S P)
apply (erule cte_wp_at_weakenE')
apply (clarsimp simp: is_arch_update'_def isCap_simps)
apply (cases "ARM_H.isPageFlushLabel (invocation_type label)")
apply (clarsimp simp: ARM_H.isPageFlushLabel_def
split: invocation_label.splits arch_invocation_label.splits)
apply (rule arch_decodeARMPageFlush_wf,
clarsimp simp: ARM_H.isPageFlushLabel_def)+
apply (cases "invocation_type label = ArchInvocationLabel ARMPageGetAddress")
apply (simp split del: if_split)
apply (rule hoare_pre, wp)
apply (clarsimp simp: valid_arch_inv'_def valid_page_inv'_def)
apply (simp add: ARM_H.isPageFlushLabel_def throwError_R'
split: invocation_label.split_asm arch_invocation_label.split_asm)
\<comment> \<open>PageTableCap\<close>
apply (simp add: decodeARMMMUInvocation_def ARM_H.decodeInvocation_def
Let_def split_def isCap_simps vs_entry_align_def
cong: if_cong list.case_cong invocation_label.case_cong
arch_invocation_label.case_cong prod.case_cong
split del: if_split)
apply (rename_tac word option)
apply (rule hoare_pre)
apply ((wp whenE_throwError_wp isFinalCapability_inv getPDE_wp
| wpc | simp add: valid_arch_inv'_def valid_pti'_def unlessE_whenE
| rule_tac x="fst p" in hoare_imp_eq_substR)+)
apply (rule_tac Q'=
"\<lambda>b c. ko_at' ARM_H.pde.InvalidPDE (b + (hd args >> 20 << 2)) c \<longrightarrow>
cte_wp_at'
(is_arch_update'
(capability.ArchObjectCap
(arch_capability.PageTableCap word (Some (snd p, hd args >> 20 << 20)))))
slot c \<and>
c \<turnstile>' capability.ArchObjectCap
(arch_capability.PageTableCap word (Some (snd p, hd args >> 20 << 20))) \<and>
is_aligned (addrFromPPtr word) ptBits \<and>
valid_pde_mapping_offset' (b + (hd args >> 20 << 2) && mask pdBits)
" in hoare_post_imp_R)
apply ((wp whenE_throwError_wp isFinalCapability_inv getPDE_wp
| wpc | simp add: valid_arch_inv'_def valid_pti'_def unlessE_whenE
| rule_tac x="fst p" in hoare_imp_eq_substR
| rule hoare_drop_impE_R)+)
apply (clarsimp simp: ko_wp_at'_def obj_at'_real_def)
apply (clarsimp simp: projectKO_opt_pde vs_entry_align_def
pageBits_def ptBits_def pdeBits_def pteBits_def
split: Structures_H.kernel_object.splits arch_kernel_object.splits)
apply ((wp whenE_throwError_wp isFinalCapability_inv
| wpc | simp add: valid_arch_inv'_def valid_pti'_def if_apply_def2
| rule hoare_drop_imp)+)[15]
apply (clarsimp simp: linorder_not_le isCap_simps cte_wp_at_ctes_of)
apply (frule eq_arch_update')
apply (case_tac option; clarsimp)
apply (drule_tac t="cteCap ctea" in sym, simp)
apply (clarsimp simp: is_arch_update'_def isCap_simps valid_cap'_def capAligned_def)
apply (thin_tac "Ball S P" for S P)+
apply (drule ctes_of_valid', fastforce)+
apply (clarsimp simp: valid_cap'_def ptBits_def is_aligned_addrFromPPtr_n invs_valid_objs'
and_not_mask[symmetric] pteBits_def)
apply (erule order_le_less_trans[rotated])
apply (rule word_and_le2)
apply (simp add: valid_cap'_def capAligned_def)
apply (simp add: decodeARMMMUInvocation_def ARM_H.decodeInvocation_def isCap_simps Let_def)
apply (cases "ARM_H.isPDFlushLabel (invocation_type label)"; simp)
apply (cases args; wpsimp simp: valid_arch_inv'_def)
apply wp
done
crunch nosch[wp]: setMRs "\<lambda>s. P (ksSchedulerAction s)"
(ignore: getRestartPC setRegister transferCapsToSlots
wp: hoare_drop_imps hoare_vcg_split_case_option
mapM_wp'
simp: split_def zipWithM_x_mapM)
crunch nosch [wp]: performARMMMUInvocation "\<lambda>s. P (ksSchedulerAction s)"
(wp: crunch_wps getObject_cte_inv getASID_wp)
lemmas setObject_cte_st_tcb_at' [wp] = setCTE_pred_tcb_at' [unfolded setCTE_def]
crunch st_tcb_at': performPageDirectoryInvocation, performPageTableInvocation, performPageInvocation,
performASIDPoolInvocation "st_tcb_at' P t"
(wp: crunch_wps getASID_wp getObject_cte_inv simp: crunch_simps)
lemmas arch_finalise_cap_aligned' = finaliseCap_aligned'
lemmas arch_finalise_cap_distinct' = finaliseCap_distinct'
crunch st_tcb_at' [wp]: "Arch.finaliseCap" "st_tcb_at' P t"
(wp: crunch_wps getASID_wp simp: crunch_simps)
lemma invs_asid_table_strengthen':
"invs' s \<and> asid_pool_at' ap s \<and> asid \<le> 2 ^ asid_high_bits - 1 \<longrightarrow>
invs' (s\<lparr>ksArchState :=
armKSASIDTable_update (\<lambda>_. (armKSASIDTable \<circ> ksArchState) s(asid \<mapsto> ap)) (ksArchState s)\<rparr>)"
apply (clarsimp simp: invs'_def valid_state'_def)
apply (rule conjI)
apply (clarsimp simp: valid_global_refs'_def global_refs'_def)
apply (clarsimp simp: valid_arch_state'_def)
apply (clarsimp simp: valid_asid_table'_def ran_def)
apply (rule conjI)
apply (clarsimp split: if_split_asm)
apply fastforce
apply (rule conjI)
apply (clarsimp simp: valid_pspace'_def)
apply (simp add: valid_machine_state'_def)
done
lemma ex_cte_not_in_untyped_range:
"\<lbrakk>(ctes_of s) cref = Some (CTE (capability.UntypedCap d ptr bits idx) mnode);
descendants_of' cref (ctes_of s) = {}; invs' s;
ex_cte_cap_wp_to' (\<lambda>_. True) x s; valid_global_refs' s\<rbrakk>
\<Longrightarrow> x \<notin> {ptr .. ptr + 2 ^ bits - 1}"
apply clarsimp
apply (drule(1) cte_cap_in_untyped_range)
apply (fastforce simp:cte_wp_at_ctes_of)+
done
lemma performASIDControlInvocation_invs' [wp]:
"\<lbrace>invs' and ct_active' and valid_aci' aci\<rbrace>
performASIDControlInvocation aci \<lbrace>\<lambda>y. invs'\<rbrace>"
apply (rule hoare_name_pre_state)
apply (clarsimp simp: performASIDControlInvocation_def valid_aci'_def
placeNewObject_def2 cte_wp_at_ctes_of
split: asidcontrol_invocation.splits)
apply (rename_tac w1 w2 w3 w4 cte ctea idx)
apply (case_tac ctea)
apply (clarsimp)
apply (frule ctes_of_valid_cap')
apply fastforce
apply (rule hoare_pre)
apply (wp hoare_vcg_const_imp_lift)
apply (strengthen invs_asid_table_strengthen')
apply (wp cteInsert_simple_invs)
apply (wp createObjects'_wp_subst[OF
createObjects_no_cte_invs [where sz = pageBits and ty="Inl (KOArch (KOASIDPool pool))" for pool]]
createObjects_orig_cte_wp_at'[where sz = pageBits] hoare_vcg_const_imp_lift
|simp add: makeObjectKO_def projectKOs asid_pool_typ_at_ext' valid_cap'_def cong: rev_conj_cong
|strengthen safe_parent_strg'[where idx= "2^ pageBits"])+
apply (rule hoare_vcg_conj_lift)
apply (rule descendants_of'_helper)
apply (wp createObjects_null_filter'
[where sz = pageBits and ty="Inl (KOArch (KOASIDPool ap))" for ap]
createObjects_valid_pspace'
[where sz = pageBits and ty="Inl (KOArch (KOASIDPool ap))" for ap]
| simp add: makeObjectKO_def projectKOs asid_pool_typ_at_ext' valid_cap'_def
cong: rev_conj_cong)+
apply (simp add: objBits_simps archObjSize_def valid_cap'_def capAligned_def range_cover_full)
apply (wp createObjects'_wp_subst[OF createObjects_ex_cte_cap_to[where sz = pageBits]]
createObjects_orig_cte_wp_at'[where sz = pageBits]
hoare_vcg_const_imp_lift
|simp add: makeObjectKO_def projectKOs asid_pool_typ_at_ext' valid_cap'_def cong: rev_conj_cong
|strengthen safe_parent_strg'[where idx = "2^ pageBits"])+
apply (simp add:asid_pool_typ_at_ext'[symmetric])
apply (wp createObject_typ_at')
apply (simp add: objBits_simps archObjSize_def valid_cap'_def
capAligned_def range_cover_full makeObjectKO_def
projectKOs asid_pool_typ_at_ext'
cong: rev_conj_cong)
apply (clarsimp simp:conj_comms
descendants_of_null_filter'
| strengthen invs_pspace_aligned' invs_pspace_distinct'
invs_pspace_aligned' invs_valid_pspace')+
apply (wp updateFreeIndex_forward_invs'
updateFreeIndex_cte_wp_at
updateFreeIndex_pspace_no_overlap'
updateFreeIndex_caps_no_overlap''
updateFreeIndex_descendants_of2
updateFreeIndex_caps_overlap_reserved
updateCap_cte_wp_at_cases static_imp_wp
getSlotCap_wp)+
apply (clarsimp simp:conj_comms ex_disj_distrib is_aligned_mask
| strengthen invs_valid_pspace' invs_pspace_aligned'
invs_pspace_distinct' empty_descendants_range_in')+
apply (wp deleteObjects_invs'[where p="makePoolParent aci"]
hoare_vcg_ex_lift
deleteObjects_caps_no_overlap''[where slot="makePoolParent aci"]
deleteObject_no_overlap
deleteObjects_cap_to'[where p="makePoolParent aci"]
deleteObjects_ct_active'[where cref="makePoolParent aci"]
deleteObjects_descendants[where p="makePoolParent aci"]
deleteObjects_cte_wp_at'
deleteObjects_null_filter[where p="makePoolParent aci"])
apply (frule valid_capAligned)
apply (clarsimp simp: invs_mdb' invs_valid_pspace' capAligned_def
cte_wp_at_ctes_of is_simple_cap'_def isCap_simps)
apply (strengthen refl ctes_of_valid_cap'[mk_strg I E])
apply (clarsimp simp: conj_comms invs_valid_objs')
apply (frule_tac ptr="w1" in descendants_range_caps_no_overlapI'[where sz = pageBits])
apply (fastforce simp: cte_wp_at_ctes_of)
apply (simp add:empty_descendants_range_in')
apply (frule(1) if_unsafe_then_capD'[OF _ invs_unsafe_then_cap',rotated])
apply (fastforce simp:cte_wp_at_ctes_of)
apply (drule ex_cte_not_in_untyped_range[rotated -2])
apply (simp add:invs_valid_global')+
apply (drule ex_cte_not_in_untyped_range[rotated -2])
apply (simp add:invs_valid_global')+
apply (subgoal_tac "is_aligned (2 ^ pageBits) minUntypedSizeBits")
prefer 2
apply (rule is_aligned_weaken)
apply (rule is_aligned_shiftl_self[unfolded shiftl_t2n,where p = 1,simplified])
apply (simp add: pageBits_def minUntypedSizeBits_def)
apply (frule_tac cte="CTE (capability.UntypedCap False a b c) m" for a b c m in valid_global_refsD', clarsimp)
apply (simp add: Int_commute)
by (auto simp:empty_descendants_range_in' objBits_simps max_free_index_def
archObjSize_def asid_low_bits_def word_bits_def pageBits_def
range_cover_full descendants_range'_def2 is_aligned_mask
null_filter_descendants_of'[OF null_filter_simp']
valid_cap_simps' mask_def)+
lemma doFlush_underlying_memory[wp]:
"\<lbrace> \<lambda>m'. underlying_memory m' p = um \<rbrace>
doFlush flush_type vstart vend pstart
\<lbrace> \<lambda>_ m'. underlying_memory m' p = um \<rbrace>"
unfolding doFlush_def by(cases flush_type; wpsimp)
(* FIXME: move *)
lemma dmo_invs'_simple:
"no_irq f \<Longrightarrow>
(\<And>p um. \<lbrace>\<lambda>m'. underlying_memory m' p = um\<rbrace> f \<lbrace>\<lambda>_ m'. underlying_memory m' p = um\<rbrace>) \<Longrightarrow>
\<lbrace> invs' \<rbrace> doMachineOp f \<lbrace> \<lambda>y. invs' \<rbrace>"
by (rule hoare_pre, rule dmo_invs', wp no_irq, simp_all add:valid_def split_def)
(* FIXME: move *)
lemma doFlush_invs[wp]:
"\<lbrace> invs' \<rbrace> doMachineOp (doFlush flush_type vstart vend pstart) \<lbrace> \<lambda>y. invs' \<rbrace>"
by(wp dmo_invs'_simple)
lemma performPageDirectoryInvocation_invs'[wp]:
"\<lbrace> invs' \<rbrace> performPageDirectoryInvocation pdi \<lbrace> \<lambda>rv. invs' \<rbrace>"
by(cases pdi, simp_all add:performPageDirectoryInvocation_def, (wp|simp)+)
lemma arch_performInvocation_invs':
"\<lbrace>invs' and ct_active' and valid_arch_inv' invocation\<rbrace>
Arch.performInvocation invocation
\<lbrace>\<lambda>rv. invs'\<rbrace>"
unfolding ARM_H.performInvocation_def
by (cases invocation,
simp_all add: performARMMMUInvocation_def valid_arch_inv'_def,
(wp|simp)+)
end
end
|
# Covid-19: From model prediction to model predictive control
## A demo of the deterministic and stochastic, national-level, age-stratified modeling framework
*Original code by Ryan S. McGee. Modified by T.W. Alleman in consultation with the BIOMATH research unit headed by prof. Ingmar Nopens.*
Copyright (c) 2020 by T.W. Alleman, BIOMATH, Ghent University. All Rights Reserved.
In `src/covid19model/models.py`, two national-level extended SEIRD compartmental models are coded,
1. COVID19_SEIRD: a deterministic model, using ordinary differential equations (ODEs). The equations are integrated using Scipy's `odeint` with a variable timestep, it is a 'continuous-time' model.
2. COVID19_SEIRD_sto: a stochastic model, using stochastic difference equations (SDEs). The equations are iterated using a fixed timestep of one day and is said to be a 'discrete-time' model.
The deterministic model was used for all results detailed in our first COVID-19 related preprint: *A deterministic, age-stratified, extended SEIRD model for assessing the effect of non-pharmaceutical interventions on SARS-CoV-2 spread in Belgium*, which can be found here: https://www.medrxiv.org/content/10.1101/2020.07.17.20156034v2
The documentation given in this tutorial has been redrafted from the above preprint. References have been omitted for the sake of simplicity.
```python
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import datetime
import scipy
import json
import random
```
Load the covid 19 custom development code
```python
from covid19model.optimization import objective_fcns
from covid19model.models import models
from covid19model.data import google, sciensano, polymod, model_parameters
from covid19model.visualization.output import population_status, infected
from covid19model.visualization.optimization import plot_fit, traceplot
```
```python
# OPTIONAL: Load the "autoreload" extension so that package code can change
%load_ext autoreload
# OPTIONAL: always reload modules so that as you change code in src, it gets loaded
%autoreload 2
```
## Introduction
### Model dynamics
The SEIR(D) model was first proposed in 1929 by two Scottish scientists. It is a compartmental model that subdivides the human population into four groups: 1) susceptible individuals, 2) exposed individuals in the latent phase 1, 3) infectious individuals capable of transmitting the disease and 4) individuals removed from the population either through immunization or death. Despite being a simple and idealized reality, the SEIR(D) dynamics are used extensively to predict the outbreak of infectious diseases and this was no different during the SARS-CoV-2 outbreak earlier this year.
In this work, we extend the SEIRD model to incorporate more expert knowledge on SARS-CoV-2. For that purpose, the infectious compartment is split into four parts. The first is a period of presymptomatic infectiousness because several studies have shown that pre-symptomatic transmission is a dominant transmission mechanism of SARS-CoV-2. After the period of pre-symptomatic transmission, three possible infectious outcomes are modeled: (1) Asymptomatic outcome, for individuals who show no symptoms at all, (2) Mild outcome, for individuals with mild symptoms who recover at home, and (3) Hospitalization, when mild symptoms worsen. Children and young adults have a high propensity to experience an asymptomatic or mild outcome, while older individual have a high propensity to be hospitalized.
In general, Belgian hospitals have two wards for COVID-19 patients: 1) Cohort, where patients are not monitored permanently and 2) Intensive care, for patients with the most severe symptoms. Intensive care includes permanent monitoring, the use of ventilators or the use of extracorporeal membrane oxygenation (ECMO). Patients generally spend limited time in the emergency room and/or in a buffer ward before going to Cohort. After spending limited time in Cohort, some patients are transferred to ICU. Patients can perish in both wards, but mortalities are generally lower in Cohort. After a stay in an ICU, patients return to Cohort for recovery in the hospital. During the recovery stay, mortality is limited. The above is a short summary of hospital dynamics based on interviewing Ghent University hospital staff and examining the hospital data.
### Model framework and equations
#### Age-stratification
We introduced heterogeneity in the deterministic implementation by means of age-stratification. Every population compartment is split into a number of age classes, the age-groups have different contact rates with other age-groups and the disease progresses differently for each age-group, making the model behaviour more realistic. Our age-stratified model consists of 9 age classes, i.e., [0-10[, [10-20[, [20-30[, [30-40[, [40-50[, [50-60[, [60-70[, [70-80[, [80- $\infty$[. The age-stratified implementation provides a good balance between added complexity and computational resources.
#### Deterministic framework
Our extended SEIRD model is implemented using two frameworks: a deterministic and a stochastic framework. The deterministic equations are obtained by writing down the following equation,
`rate of change = in - out`,
for every of the 11 population compartments. This results in the following system of coupled ordinary differential equations,
\begin{eqnarray}
\dot{S_i} &=& - \beta s_i \sum_{j=1}^{N} N_{c,ij} S_j \Big( \frac{I_j+A_j}{T_j} \Big) + \zeta R_i, \label{eq:system1} \\
\dot{E_i} &=& \beta s_i \sum_{j=1}^{N} N_{c,ij} S_j \Big( \frac{I_j+A_j}{T_j} \Big) - (1/\sigma) \cdot E_i, \label{eq:system2} \\
\dot{I_i} &=& (1/\sigma) E_i - (1/\omega) I_i, \label{eq:system3}\\
\dot{A_i} &=& (\text{a}_i/\omega) I_i - (1/d_{\text{a}}) A_i, \label{eq:system4}\\
\dot{M_i} &=& ((1-\text{a}_i) / \omega ) I_i - ( (1-h_i)/d_m + h_i/d_{\text{hospital}} ) M_i,\label{eq:system5} \\
\dot{ER_i} &=& (h_i/d_{\text{hospital}}) M_i - (1/d_{\text{ER}}) ER_i, \label{eq:system6} \\
\dot{C_i} &=& c_i (1/d_{\text{ER}}) ER_i - (m_{C, i}/d_{c,D}) C_i - ((1 - m_{C, i})/d_{c,R}) C_i, \label{eq:system7} \\
\dot{ICU_i} &=& (1-c_i) (1/d_{\text{ER}}) ER_i - (m_{ICU,i}/d_{\text{ICU},D}) ICU_i \label{eq:system8} \\
&& - ((1-m_{ICU,i})/d_{\text{ICU},R}) ICU_i, \label{eq:system9}\\
\dot{C}_{\text{ICU,rec,i}} &=& ((1-m_{ICU,i})/d_{\text{ICU},R}) ICU_i - (1/d_{\text{ICU,rec}}) C_{\text{ICU,rec,i}}, \label{eq:system10}\\
\dot{D_i} &=& (m_{ICU,i}/d_{\text{ICU},D}) ICU_i + (m_{C,i}/d_{\text{c},D}) C_i , \label{eq:system11}\\
\dot{R_i} &=& (1/d_a) A_i + ((1-h_i)/d_m) M_i + ((1-m_{C,i})/d_{c,R}) C_i \\
&& + (1/d_{\text{ICU,rec}}) C_{\text{ICU,rec,i}} - \zeta R_i \label{eq:system13},
\end{eqnarray}
for $i = 1,2,...,9$. Here, $T_i$ stands for total population, $S_i$ stands for susceptible, $E_i$ for exposed, $I_i$ for pre-symptomatic and infectious, $A_i$ for asymptomatic and infectious, $M_i$ for mildly symptomatic and infectious, $ER_i$ for emergency room and/or buffer ward, $C_i$ for cohort, $C_{\text{ICU,rec,i}}$ for a recovery stay in Cohort coming from Intensive Care, $ICU_i$ for Intensive Care Unit, $D_i$ for dead and $R_i$ for recovered. Using the above notation, all model states are 9x1 vectors,
$$ \mathbf{S} = [S_1(t)\ S_2(t)\ ...\ S_i(t)]^T, $$
where $S_i(t)$ denotes the number of susceptibles in age-class i at time t after the introduction of the virus in the population.
These equations are implemented in the function `COVID19_SEIRD` located in `src/covid19model/models.py`. The integration is performed in `_sim_single` located in `src/covid19model/base.py` by using Scipy's `solve_ivp`. The integrator timestep depends on the rate of change of the system and the solver method is thus referred to as a 'continuous-time' solver. The implementation uses non-integer individuals.
#### Stochastic framework
By defining the probabilities of transitioning (propensities) from one state to another, a system of coupled stochastic difference equations (SDEs) can be obtained. The probability to transition from one state to another is assumed to be exponentially distributed. As an example, consider the average time a patient spends in an ICU when recovering, which is $d_{\text{ICU,R}} = 9.9$ days. The chances of survival in ICU are $(1-m_{\text{ICU,i}})$, where $m_{\text{ICU,i}}$ is the mortality in ICU for an individual in age group $i$. The probability of transitioning from state ICU to state $C_{\text{ICU,rec}}$ on any given day and for an individual in age group $i$ is,
\begin{equation}
P(ICU_i \rightarrow C_{\text{ICU,rec,i}}) = 1 - \text{exp} \Bigg[ - \frac{1-m_{\text{ICU},i}}{d_{\text{ICU,R}}}\Bigg].
\end{equation}
If a transitioning between states is defined as "succes", we can regard the number of individuals transitioning from ICU to a Cohort recovery ward as a binomial experiment. On a given day, the number of individuals transitioning is,
\begin{equation}
(\text{ICU}_i \rightarrow C_{\text{ICU,rec,i}})(k) \sim \text{Binomial}\Bigg(\text{ICU}_i(k),\ 1 - \text{exp}\Bigg[- \frac{1-m_{\text{ICU,i}}}{d_{\text{ICU,R}}}\Bigg]\Bigg).
\end{equation}
For a discrete stepsize $l$, there are 15 possible transitions,
\begin{eqnarray}
(S_i \rightarrow E_i) (k) &\sim& \text{Binomial}\Bigg(S_i(k), 1 - \text{exp}\Bigg[- l \beta s_i \sum_{j=1}^{N} N_{c,ij} S_j \Big( \frac{I_j+A_j}{T_j} \Big) \Bigg]\Bigg)\\
(E_i \rightarrow I_i) (k) &\sim& \text{Binomial}\Bigg(E_i(k), 1 - \text{exp}\Bigg[- l\ \frac{1}{\sigma}\Bigg]\Bigg)\\
(I_i \rightarrow A_i) (k) &\sim& \text{Binomial}\Bigg(I_i(k), 1 - \text{exp}\Bigg[- l\ \frac{a_i}{\omega}\Bigg]\Bigg)\\
(I_i \rightarrow M_i) (k) &\sim& \text{Binomial}\Bigg(I_i(k), 1 - \text{exp}\Bigg[- l\ \frac{1-a_i}{\omega}\Bigg]\Bigg)\\
(A_i \rightarrow R_i) (k) &\sim& \text{Binomial}\Bigg(A_i(k), 1 - \text{exp}\Bigg[- l\ \frac{1}{d_a}\Bigg]\Bigg)\\
(M_i \rightarrow R_i) (k) &\sim& \text{Binomial}\Bigg(M_i(k), 1 - \text{exp}\Bigg[- l\ \frac{1-h_i}{d_m}\Bigg]\Bigg)\\
(M_i \rightarrow ER_i) (k) &\sim& \text{Binomial}\Bigg(M_i(k), 1 - \text{exp}\Bigg[- l\ \frac{h_i}{d_{\text{hospital}}}\Bigg]\Bigg)\\
(ER_i \rightarrow C_i) (k) &\sim& \text{Binomial}\Bigg(ER_i(k), 1 - \text{exp}\Bigg[- l\ \frac{c_i}{d_{\text{ER}}}\Bigg]\Bigg)\\
(ER_i \rightarrow ICU_i) (k) &\sim& \text{Binomial}\Bigg(ER_i(k), 1 - \text{exp}\Bigg[- l\ \frac{1-c_i}{d_{\text{ER}}}\Bigg]\Bigg)\\
(C_i \rightarrow R_i) (k) &\sim& \text{Binomial}\Bigg(C_i(k), 1 - \text{exp}\Bigg[- l\ \frac{1-m_{C,i}}{d_{C,R}}\Bigg]\Bigg)\\
(ICU_i \rightarrow C_{\text{ICU,rec,i}}) (k) &\sim& \text{Binomial}\Bigg(ICU_i(k), 1 - \text{exp}\Bigg[- l\ \frac{1-m_{\text{ICU,i}}}{d_{ICU,R}}\Bigg]\Bigg)\\
(C_{\text{ICU,rec,i}} \rightarrow R_i) (k) &\sim& \text{Binomial}\Bigg(C_{\text{ICU,rec,i}}(k), 1 - \text{exp}\Bigg[- l\ \frac{1}{d_{\text{ICU,rec}}}\Bigg]\Bigg)\\
(C_i \rightarrow D_i) (k) &\sim& \text{Binomial}\Bigg(C_i(k), 1 - \text{exp}\Bigg[- l\ \frac{m_{C,i}}{d_{C,D}}\Bigg]\Bigg)\\
(ICU_i \rightarrow D_i) (k) &\sim& \text{Binomial}\Bigg(ICU_i(k), 1 - \text{exp}\Bigg[- l\ \frac{m_{\text{ICU,i}}}{d_{\text{ICU,D}}}\Bigg]\Bigg)\\
(R_i \rightarrow S_i) (k) &\sim& \text{Binomial}\Bigg(R_i(k), 1 - \text{exp}\Bigg[- l\ \zeta \Bigg]\Bigg)\\
\end{eqnarray}
And the system of equations becomes,
\begin{eqnarray}
S_i(k+1) &=& S_i(k) + (R_i \rightarrow S_i) (k) - (S_i \rightarrow E_i) (k) \\
E_i(k+1) &=& E_i(k) + (S_i \rightarrow E_i) (k) - (E_i \rightarrow I_i) (k) \\
I_i(k+1) &=& I_i(k) + (E_i \rightarrow I_i) (k) - (I_i \rightarrow A_i) - (I_i \rightarrow M_i) (k) \\
A_i(k+1) &=& A_i(k) + (I_i \rightarrow A_i) (k) - (A_i \rightarrow R_i) (k) \\
M_i(k+1) &=& M_i(k) + (I_i \rightarrow M_i) (k) - (M_i \rightarrow R_i) (k) - (M_i \rightarrow ER_i) (k) \\
ER_i(k+1) &=& ER_i(k) + (M_i \rightarrow ER_i) (k) - (ER_i \rightarrow C_i) (k) - (ER_i \rightarrow ICU_i) (k) \\
C_i(k+1) &=& C_i(k) + (ER_i \rightarrow C_i) (k) - (C_i \rightarrow R_i) (k) - (C_i \rightarrow D_i) (k) \\
C_{\text{ICU,rec,i}}(k+1) &=& C_{\text{ICU,rec,i}}(k) + (ICU_i \rightarrow C_{\text{ICU,rec,i}}) (k) - (C_{\text{ICU,rec,i}} \rightarrow R_i) (k) \\
R_i(k+1) &=& R_i(k) + (A_i \rightarrow R_i) (k) + (M_i \rightarrow R_i) (k) + (C_i \rightarrow R_i) (k) + (C_{\text{ICU,rec,i}} \rightarrow R_i) (k) - (R_i \rightarrow S_i) (k) \\
D_i(k+1) &=& D_i(k) + (ICU_i \rightarrow D_i) (k) + (C_i \rightarrow D_i) (k) \\
\end{eqnarray}
These equations are implemented in the function `COVID19_SEIRD_sto` located in `src/covid19model/models.py`. The computation itself is performed in the function `solve_discrete` located in `src/covid19model/base.py`. Please note that the deterministic model uses **differentials** in the model defenition and must be integrated, while the stochastic model uses **differences** and must be iterated. The discrete timestep is fixed at one day. The stochastic implementation only uses integer individuals, which is considered an advantage over the deterministic implementation.
### Transmission rate and social contact data
In our model, the transmission rate of the disease depends on the product of four contributions. The first contribution, $(I+A)/T$, is the fraction of contagious individuals in the population. The second contribution, $\mathbf{N}_c$, is the average number of human-to-human interactions per day. The third contribution, $s_i$, is the relative susceptiblity to SARS-CoV-2 infection in age group $i$, and the fourth contribution, $\beta$, is the probability of contracting COVID-19 when encountering a contagious individual under the assumption of 100 \% susceptibility to SARS-CoV-2 infection. We assume that the per contact transmission probability $\beta$ is independent of age and we will infer its distribution by calibrating the model to national Belgian hospitalization data. The number of human-human interactions, $\mathbf{N}_c$, are both place and age-dependent. These matrices assume the form of a 9x9 *interaction matrix* where an entry X, Y denotes the number of social contacts age group X has with age group Y per day. These matrices are available for homes, schools, workplaces, in public transport, and leisure activities, from a survey study by Lander Willem (2012). The total number of social interactions is given by the sum of the contributions in different places,
\begin{equation}\label{eq:interaction_matrices}
\mathbf{N_{\text{c}}} = \mathbf{N_{\text{c, home}}} + \mathbf{N_{\text{c, schools}}} + \mathbf{N_{\text{c, work}}} + \mathbf{N_{\text{c, transport}}} + \mathbf{N_{\text{c, leisure}}} + \mathbf{N_{\text{c, others}}}
\end{equation}
https://lwillem.shinyapps.io/socrates_rshiny/
```python
# Load the interaction matrices (size: 9x9)
initN, Nc_home, Nc_work, Nc_schools, Nc_transport, Nc_leisure, Nc_others, Nc_total = polymod.get_interaction_matrices()
# Define the number of age categories
levels = initN.size
```
The coefficients of the contact matrices in different places can be altered to model a goverment policy. For instance, to model the Belgian lockdown, the mobility reductions deduced from the Google community mobility reports were used as coefficients for the different interaction matrices. We assumed workplace interactions were down to only 40 % of their prepandemic values before the lockdown.
https://www.google.com/covid19/mobility/
Our code has built-in functionality to download an visualize these mobility reports. To do so, simply run the following code:
```python
df_google = google.get_google_mobility_data(update=False, plot=True)
```
### Social interatia
The model takes into account the effect of *social inertia* when measures are taken. In reality, social restrictions or relaxations represent a change in behaviour which is gradual and cannot be modeled using a step-wise change of the social interaction matrix $\mathbf{N_c}$. This can be seen when closely inspecting the *Google community mobility report* above. Multiple functions can be used to model the effects of social compliance, e.g. a delayed or non-delayed ramp, or a logistic function. In our model, we use a delayed ramp to model compliance,
\begin{equation}
\mathbf{N_{c}}^{k} = \mathbf{N_{\text{c, old}}} + f^{k} (\mathbf{N_{\text{c, new}}} - \mathbf{N_{\text{c, old}}})
\end{equation}
where,
\begin{equation}
f^k=
\begin{cases}
0.0,& \text{if } k\leq \tau\\
\frac{k}{l} - \frac{\tau}{l},& \text{if } \tau < k\leq \tau + l\\
1.0, & \text{otherwise}
\end{cases}
\end{equation}
where $\tau$ is the number of days before measures start having an effect and $l$ is the number of additional days after the time delay until full compliance is reached. Both parameters were calibrated to the daily number of hospitalizations in Belgium (notebooks `notebooks/0.1-twallema-calibration-deterministic.ipynb` and `notebooks/0.1-twallema-calibration-stochastic.ipynb`). $k$ denotes the number of days since a change in social policy.
```python
# Load the compliance model
from covid19model.models.compliance import ramp_2
```
### Basic reproduction number
The basic reproduction number $R_0$, defined as the expected number of secondary cases directly generated by one case in a population where all individuals are susceptible to infection, is computed using the next generation matrix (NGM) approach introducted by Diekmann. For our model, the basic reproduction number of age group $i$ is,
\begin{equation}\label{eq:reproduction_number}
R_{0,i} = (a_i d_a + \omega) \beta s_i \sum_{j=1}^{N} N_{c,ij}
\end{equation}
and the population basic reproduction number is calculated as the weighted average over all age groups using the demographics of Belgium. The detailed algebra underlying the computation equation of the basic reproduction number is presented in the supplementary materials of our manuscript (https://www.medrxiv.org/content/10.1101/2020.07.17.20156034v2).
### Model parameters
## Simulations with the deterministic model
### Model initialization
```python
# Load the model parameters using `get_COVID19_SEIRD_parameters()`.
params = model_parameters.get_COVID19_SEIRD_parameters()
# Add the delayed ramp parameters to the parameter dictionary to use compliance.
params.update({'l': 1,
'tau': 5})
# Define the initial condition: one exposed inidividual in every age category
initial_states = {'S': initN, 'E': np.ones(levels)}
# Initialize the model
model = models.COVID19_SEIRD(initial_states, params, compliance=ramp_2)
```
### Load posterior parameter distributions of calibrated parameters
Both the deterministic and stochastic model were calibrated to the national hospitalization data provided by the Scientific Institute of Public Health (Sciensano).
The parameters $\beta$, $l$, $\tau$ and $\Omega$ were calibrated.
The aim of such a calibration is to obtain a parameter set which leads to a good agreement between the model predictions and the experimental data. Five timeseries starting on Sunday, March 15th, 2020 have been made publically available by the Belgian Scientific Institute of Public Health (Sciensano),
- the total number of patients in the hospitals ($H_{\text{tot}}$)
- the total number of patients in ICU ($ICU_{\text{tot}}$)
- the daily hospitalizations ($H_{\text{in}}$)
- the daily hospital discharges ($H_{\text{out}}$)
- the daily number of deaths ($D_{\text{new}}$)
We assume the timeseries are independent and identically distributed (i.d.d.) sequences of normal random variables having a mean $\hat{y}(k)$ and an unknown variance $\hat{\sigma}^2$. The resulting log-likelihood function is,
\begin{equation}
\ln \big( P( y \mid \mathbf{\hat{\theta}}) \big) = - \frac{1}{2} \sum_{k=1}^{N} \Bigg[ \frac{\big(y(k) - \hat{y}(k, \mathbf{\hat{\theta}})\big)^2}{\hat{\sigma}^2} + \ln\big(2 \pi \hat{\sigma}^2\big) \Bigg]\ ,
\end{equation}
where $\mathbf{\hat{\theta}}$ and $\hat{\sigma}^2$ are computed to maximize the log-likelihood function. The fitting procedure is performed in two steps. First, the transmission parameter $\beta$ is calibrated using the daily hospitalizations from March 15th, 2020 until March 22nd, 2020. These data are used because they do not depend on the durations of the hospitalizations, $d_c$ and $d_{\text{ICU}}$, which are computed from the limited and imperfect hospital dataset. In addition to the calibration of the transmission parameter $\beta$, the number of days between the first infectious individuals entering the country and the onset of data collection (March 15th, 2020) must be estimated. The latter is denoted as excess time, $t_e$. Second, the daily hospitalizations ($H_{\text{in}}$) from March 15th, 2020 until April 20th, 2020 were used to infer the slope of the compliance ramp ($l$), as well as the effect of prevention measures and *network* effects in the workplace and on public transport ($\Omega$).
We performed the above optimizations in two steps. First, we used a particle swarm optimization (PSO) algorithm to scan the parameter space and find the global maximum likelihood. We then used the obtained maximum-likelihood estimates as initial values for the ensemble sampler for Markov Chain Monte Carlo (MCMC) proposed by Goodman 2010. For all parameters, uniform prior distributions were used. The sampler was always run on $2n$ parallel chains, were $n$ was the number of parameters to be sampled from the posterior distributions. For each chain, we drew at least 50-fold more samples than the autocorrelation time. Next, we visualised the samples using the scatterplot matrix proposed by Foreman (2016), further referred to as *cornerplot*. In these visualizations, each one- and two-dimensional projection of the sample is plotted to reveal correlations. During each step of the optimization procedure, previously sampled parameters were propagated.
The calibration can be found in the notebook `notebooks/0.1-twallema-calibration-deterministic.ipynb`. The posterior samples of the calibrated parameters can be found in `data/interim/model_parameters/deterministic_22072020.json`.
```python
# Scrape the publically available data from the Scientific institute of Public Health (Sciensano)
df_sciensano = sciensano.get_sciensano_COVID19_data(update=False)
df_sciensano.tail()
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>H_tot</th>
<th>ICU_tot</th>
<th>H_in</th>
<th>H_out</th>
<th>H_tot_cumsum</th>
<th>D_tot</th>
<th>D_25_44</th>
<th>D_45_64</th>
<th>D_65_74</th>
<th>D_75_84</th>
<th>D_85+</th>
</tr>
<tr>
<th>DATE</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<th>2020-08-06</th>
<td>278</td>
<td>65</td>
<td>28</td>
<td>39</td>
<td>687</td>
<td>2</td>
<td>0.0</td>
<td>0.0</td>
<td>0</td>
<td>1.0</td>
<td>1</td>
</tr>
<tr>
<th>2020-08-07</th>
<td>285</td>
<td>69</td>
<td>27</td>
<td>28</td>
<td>686</td>
<td>4</td>
<td>0.0</td>
<td>0.0</td>
<td>0</td>
<td>1.0</td>
<td>3</td>
</tr>
<tr>
<th>2020-08-08</th>
<td>281</td>
<td>67</td>
<td>31</td>
<td>39</td>
<td>678</td>
<td>2</td>
<td>0.0</td>
<td>0.0</td>
<td>0</td>
<td>2.0</td>
<td>0</td>
</tr>
<tr>
<th>2020-08-09</th>
<td>285</td>
<td>69</td>
<td>20</td>
<td>14</td>
<td>684</td>
<td>4</td>
<td>1.0</td>
<td>0.0</td>
<td>0</td>
<td>1.0</td>
<td>2</td>
</tr>
<tr>
<th>2020-08-10</th>
<td>312</td>
<td>73</td>
<td>33</td>
<td>12</td>
<td>705</td>
<td>3</td>
<td>0.0</td>
<td>1.0</td>
<td>1</td>
<td>0.0</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
```python
# Load the dictionary containing the posterior parameter distributions obtained from calibrating the model to Belgian hospitalization data
with open('../../data/interim/model_parameters/deterministic_22072020.json', 'r') as fp:
samples_dict = json.load(fp)
lag_time = samples_dict['lag_time']
model.extraTime = samples_dict['lag_time']
model.parameters['beta'] = np.mean(samples_dict['beta'])
model.parameters['l'] = np.mean(samples_dict['l'])
model.parameters['tau'] = np.mean(samples_dict['tau'])
prevention = np.mean(samples_dict['prevention'])
```
### Simulating
A simulation is run by using the attribute function *sim*, which uses one argument, the simulation time, as its input.
```python
out=model.sim(100)
```
['Nc', 'time']
#### Extracting model output
The output format of the deterministic and stochastic model are an `xarray` dataset. This flexible python package introduces labels in the form of dimensions, coordinates and attributes on top of raw NumPy-like arrays. Relevant to our work are the coordinates,
1. 'stratification': the nine different age groups used in the model.
2. 'time': simulation time
and the data variables, which are the 11 model states (S,E,I,...,R,D). Future work will include a spatial extension, which will simply use a new coordinate 'NIS'.
```python
out
```
As an example of output handling, consider the following simple code snippet. Here, the total number of patients in Belgian ICUs over time is given. Summing over all age groups is simple.
```python
plt.plot(out['time'],out['ICU'].sum(dim='stratification'))
```
#### Visualizing the results using builtin methods
Two custom visualization routines are included in `src/covid19model/visualization/output.py` for rapid prototyping, `infected` and `population_status`. For more details, we refer to the docstring in the aforementioned python script.
```python
infected(out)
population_status(out)
```
#### The use of checkpoints to change parameters on the fly
A cool feature of the original SEIRSplus package by Ryan McGee was the use of so-called *checkpoints* dictionary to change simulation parameters on the fly. In our modification, this feature is preserved. Below you can find an example of a *checkpoints* dictionary. The simulation will be started with the previously initialised parameters. After 55 days, social interaction will be limited by changing the interaction matrx $\mathbf{N_c}$ to home contacts only. On day 100, social restrictions are lifted and beta once more assumes its *business-as-usual* value.
```python
# Create checkpoints dictionary
chk = {'time': [55,100],
'Nc': [Nc_home,Nc_total]
}
# Run simulation
out=model.sim(130,checkpoints=chk)
# Visualise the results
population_status(out)
infected(out)
```
#### Using posterior samples from previously calibrated parameters to quantify uncertainty
```python
fig,ax=plt.subplots()
for i in range(200):
# Draw a paramter value from the dictionary of posterior samples for beta, l and tau (fitted parameters).
model.parameters['beta'] = np.random.choice(samples_dict['beta'],1,replace=False)
# Correlation exists between l, tau and prevention. Thus we must use the same index to ensure we are drawing trios from the posterior distribution!
idx,model.parameters['l'] = random.choice(list(enumerate(samples_dict['l'])))
model.parameters['tau'] = samples_dict['tau'][idx]
prevention = samples_dict['prevention'][idx]
# Perform simulation
out=model.sim(130,checkpoints=chk)
# Visualise the results
infected(out,ax=ax,alpha=0.02)
```
## Simulations with the stochastic model
### Model initialization
When initializing the stochastic model, a flag `discrete` must be used to switch from the integrator to the iterator.
```python
# Load the parameters using `get_COVID19_SEIRD_parameters()`.
params = parameters.get_COVID19_SEIRD_parameters()
# Add the delayed ramp parameters to the parameter dictionary.
params.update({'l': 1,
'tau': 5,
'd': 100}) # overdispersion coefficient (adds variability --> larger value means less influential)
# Delete the following parameters, they are not included in the stochastic implementation
del params['totalTests']
del params['dq']
del params['psi_FP']
del params['psi_PP']
# Define the initial condition: ten exposed inidividual in every age category
# Why 10? When only using one exposed, there is a big chance the chain will go extinct!
initial_states = {'S': initN, 'E': 10*np.ones(levels)}
# Initialize the model, the only difference with the stochastic model is the `discrete` flag
model = models.COVID19_SEIRD_sto(initial_states, params, compliance=ramp_2, discrete=True)
```
### Load posterior parameter distributions of calibrated parameters
The calibration procedure was exactly the same as for the deterministic model. For more details we refer to the calibration notebook, located in `notebooks/0.1-twallema-calibration-stochastic` . The posterior distributions are located in `data/interim/model_parameters/stochastic_15-08-2020.json`.
```python
with open('../../data/interim/model_parameters/stochastic_15-08-2020.json', 'r') as fp:
samples_dict = json.load(fp)
lag_time = samples_dict['lag_time']
model.extraTime = samples_dict['lag_time']
model.parameters['beta'] = np.mean(samples_dict['beta'])
model.parameters['l'] = np.mean(samples_dict['l'])
model.parameters['tau'] = np.mean(samples_dict['tau'])
prevention = np.mean(samples_dict['prevention'])
```
### Simulating
After the model initialization, the code works in the exact same way as the deterministic model.
```python
fig,ax=plt.subplots()
for i in range(200):
# Use posterior samples of fitted parameters
model.parameters['beta'] = np.random.choice(samples_dict['beta'],1,replace=False)
idx,model.parameters['l'] = random.choice(list(enumerate(samples_dict['l'])))
model.parameters['tau'] = samples_dict['tau'][idx]
prevention = samples_dict['prevention'][idx]
# Perform simulation
out=model.sim(130,checkpoints=chk)
# Visualise the results
infected(out,ax=ax,alpha=0.02)
```
|
Require Import Crypto.Specific.Framework.RawCurveParameters.
Require Import Crypto.Util.LetIn.
(***
Modulus : 2^190 - 11
Base: 64
***)
Definition curve : CurveParameters :=
{|
sz := 3%nat;
base := 64;
bitwidth := 64;
s := 2^190;
c := [(1, 11)];
carry_chains := None;
a24 := None;
coef_div_modulus := None;
goldilocks := None;
karatsuba := None;
montgomery := true;
freeze := Some false;
ladderstep := false;
mul_code := None;
square_code := None;
upper_bound_of_exponent_loose := None;
upper_bound_of_exponent_tight := None;
allowable_bit_widths := None;
freeze_extra_allowable_bit_widths := None;
modinv_fuel := None
|}.
Ltac extra_prove_mul_eq _ := idtac.
Ltac extra_prove_square_eq _ := idtac.
|
## ΠΠ°Π΄Π°Π½ΠΈΠ΅ 1
Π Π΅ΡΠΈΡΠ΅ ΡΡΠ°Π²Π½Π΅Π½ΠΈΠ΅
sin(x)/x=0.
```python
from scipy.optimize import fsolve
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
```
```python
def func(x):
return (np.sin(x)/x)
```
```python
x = np.linspace(0.01, 50, 1000)
plt.grid()
plt.plot(x, func(x))
plt.scatter(fsolve(func, 0.01), [0])
plt.show()
```
ΠΡΠ²Π΅Ρ: ΡΡΠ½ΠΊΡΠΈΡ Π·Π°ΡΡΡ
Π°ΡΡΠ°Ρ, ΠΏΡΠ΅Π΄Π΅Π» ΡΡΡΠ΅ΠΌΠΈΡΡΡ ΠΊ Π½ΡΠ»Ρ, ΡΡΠ°Π²Π½Π΅Π½ΠΈΠ΅ ΠΈΠΌΠ΅Π΅Ρ Π±Π΅ΡΠΊΠΎΠ½Π΅ΡΠ½ΠΎΠ΅ ΡΠΈΡΠ»ΠΎ ΡΠ΅ΡΠ΅Π½ΠΈΠΉ (ΠΏΠΎ 3 ΠΊΠΎΡΠ½Ρ Π½Π° ΠΊΠ°ΠΆΠ΄ΡΠ΅ 10Ρ
), ΡΠ°ΡΡΠ½ΠΎΠ΅ ΡΠ΅ΡΠ΅Π½ΠΈΠ΅ - 3.14
## ΠΠ°Π΄Π°Π½ΠΈΠ΅ 2
ΠΠ°Π½Ρ ΡΡΠΈ ΠΏΡΡΠΌΡΠ΅ y=k1*x+b1, y=k2*x+b2, y=k3*x+b3. ΠΠ°ΠΊ ΡΠ·Π½Π°ΡΡ, ΠΏΠ΅ΡΠ΅ΡΠ΅ΠΊΠ°ΡΡΡΡ ΠΎΠ½ΠΈ Π² ΠΎΠ΄Π½ΠΎΠΉ ΡΠΎΡΠΊΠ΅ ΠΈΠ»ΠΈ Π½Π΅Ρ?
ΠΡΠ²Π΅Ρ: ΡΡΠΎΠ±Ρ ΠΏΡΡΠΌΡΠ΅ ΠΏΠ΅ΡΠ΅ΡΠ΅ΠΊΠ°Π»ΠΈΡΡ Π½Π΅ΠΎΠ±Ρ
ΠΎΠ΄ΠΈΠΌΠΎ ΡΡΠΎΠ±Ρ ΡΠ»Π΅Π΄ΡΡΡΠ°Ρ ΡΠΈΡΡΠ΅ΠΌΠ° ΡΡΠ°Π²Π½Π΅Π½ΠΈΠΉ ΠΈΠΌΠ΅Π»Π° ΡΠ΅ΡΠ΅Π½ΠΈΠ΅:
\begin{equation}
\left\{
\begin{array}{ll}
y = k_1x+b_1 \\
y = k_2x+b_2 \\
y = k_3x+b_3
\end{array}
\right.
\end{equation}
## ΠΠ°Π΄Π°Π½ΠΈΠ΅ 3
ΠΠ° Π»ΠΈΡΡΠ΅ ΡΠ΅ΡΡΠ°Π΄ΠΈ Β«Π² Π»ΠΈΠ½Π΅ΠΉΠΊΡΒ» (ΡΠ°ΡΡΡΠΎΡΠ½ΠΈΠ΅ ΠΌΠ΅ΠΆΠ΄Ρ Π»ΠΈΠ½ΠΈΡΠΌΠΈ ΡΠ°Π²Π½ΠΎ Π°) Π»Π΅ΠΆΠΈΡ ΠΈΠ³Π»Π° (Π΄Π»ΠΈΠ½ΠΎΠΉ b). ΠΠΎΠΎΡΠ΄ΠΈΠ½Π°ΡΡ Π½ΠΈΠΆΠ½Π΅ΠΉ ΡΠΎΡΠΊΠΈ ΠΈΠ³Π»Ρ (Ρ
,Ρ), ΠΈΠ³Π»Π° Π»Π΅ΠΆΠΈΡ ΠΏΠΎΠ΄ ΡΠ³Π»ΠΎΠΌ alfa. ΠΠ΅ΡΠ΅ΡΠ΅ΠΊΠ°Π΅Ρ Π»ΠΈ ΠΈΠ³Π»Π° Π»ΠΈΠ½ΠΈΡ ΠΈΠ»ΠΈ Π½Π΅Ρ?
ΠΡΠ²Π΅Ρ: ΠΠ΅ΠΎΠ±Ρ
ΠΎΠ΄ΠΈΠΌΠΎ ΡΡΠΎΠ±Ρ ΠΏΡΠΎΠ΅ΠΊΡΠΈΡ Π½Π° ΠΎΡΡ Y Π±ΡΠ»Π° Π±ΠΎΠ»ΡΡΠ΅ a, Ρ.Π΅. $|b\sin(\alpha)| > a$
## ΠΠ°Π΄Π°Π½ΠΈΠ΅ 4
Π Π΅ΡΠΈΡΠ΅ Π°Π½Π°Π»ΠΈΡΠΈΡΠ΅ΡΠΊΠΈ ΠΈ ΠΏΠΎΡΠΎΠΌ ΡΠΈΡΠ»Π΅Π½Π½ΠΎ (Π² ΠΏΡΠΎΠ³ΡΠ°ΠΌΠΌΠ΅) ΡΡΠ°Π²Π½Π΅Π½ΠΈΠ΅, Π·Π°Π²ΠΈΡΡΡΠ΅Π΅ ΠΎΡ ΠΏΠ°ΡΠ°ΠΌΠ΅ΡΡΠ° Π°:
sin(Π°*x)=0
ΠΏΡΠΈ ΡΡΠ»ΠΎΠ²ΠΈΠΈ: 0.01<a<0.02, 100<Ρ
<500.
Π’.Π΅. Π½Π°Π΄ΠΎ Π½Π°ΠΉΡΠΈ ΡΠ΅ΡΠ΅Π½ΠΈΠ΅ Ρ
ΠΊΠ°ΠΊ ΡΡΠ½ΠΊΡΠΈΡ ΠΏΠ°ΡΠ°ΠΌΠ΅ΡΡΠ° Π° - ΠΏΠΎΡΡΡΠΎΠΈΡΡ Π³ΡΠ°ΡΠΈΠΊ x=x(Π°).
ΠΡΠ»ΠΈ ΡΠΈΡΠ»Π΅Π½Π½ΡΠΌ ΠΌΠ΅ΡΠΎΠ΄ΠΎΠΌ Π½Π΅ ΠΏΠΎΠ»ΡΡΠ°Π΅ΡΡΡ Π½Π°ΠΉΡΠΈ Π²ΡΠ΅ Π²Π΅ΡΠ²ΠΈ ΡΠ΅ΡΠ΅Π½ΠΈΡ x(Π°), ΡΠΎ ΠΎΡΡΡΠΈΡΠ΅ Ρ
ΠΎΡΡ Π±Ρ ΠΎΠ΄Π½Ρ.
`Β―\_(γ)_/Β―`
## ΠΠ°Π΄Π°Π½ΠΈΠ΅ 4
#### ΠΠ°ΠΉΡΠΈ ΡΠ³ΠΎΠ» ΠΌΠ΅ΠΆΠ΄Ρ ΠΏΡΡΠΌΡΠΌΠΈ 4y - 3x + 12 = 0 ΠΈ 7y + x - 14 = 0
$y = \frac{3}{4}x - 3$ ΠΈ $y = -\frac{1}{7}x + 2$
```python
np.tan(3/4)
```
0.9315964599440725
```python
np.tan(-1/7)
```
-0.14383695943619093
ΡΠ³ΠΎΠ» ΠΏΠ΅ΡΠ²ΠΎΠΉ ΠΏΡΡΠΌΠΎΠΉ ΠΏΡΠΈΠΌΠ΅ΡΠ½ΠΎ 43 Π³ΡΠ°Π΄ΡΡΠ°, Π²ΡΠΎΡΠΎΠΉ - ΠΏΡΠΈΠΌΠ΅ΡΠ½ΠΎ 94 Π³ΡΠ°Π΄ΡΡΠ°
ΠΡΠ²Π΅Ρ: ΡΠ³ΠΎΠ» ΠΌΠ΅ΠΆΠ΄Ρ ΠΏΡΡΠΌΡΠΌΠΈ ΠΏΠΎΠ»ΡΡΠ°Π΅ΡΡΡ 94 - 43 = 51 Π³ΡΠ°Π΄ΡΡ
#### ΠΠ°ΠΉΡΠΈ ΡΠ³ΠΎΠ» ΠΌΠ΅ΠΆΠ΄Ρ ΠΏΡΡΠΌΡΠΌΠΈ $x = \sqrt{2}$ ΠΈ $x = -\sqrt{3}$
ΠΡΠ²Π΅Ρ: ΠΎΠ±Π΅ ΠΏΡΡΠΌΡΠ΅ Π²Π΅ΡΡΠΈΠΊΠ°Π»ΡΠ½Ρ ΠΈ ΠΏΠ°ΡΠ°Π»Π»Π΅Π»ΡΠ½Ρ ΠΌΠ΅ΠΆΠ΄Ρ ΡΠΎΠ±ΠΎΠΉ. Π£Π³ΠΎΠ» ΠΌΠ΅ΠΆΠ΄Ρ ΠΏΠ°ΡΠ°Π»Π»Π΅Π»ΡΠ½ΡΠΌΠΈ ΠΏΡΡΠΌΡΠΌΠΈ ΡΠ°Π²Π΅Π½ 0
## ΠΠ°Π΄Π°Π½ΠΈΠ΅ 5. ΠΡΡΡΠ½ΠΈΡΡ ΡΠΈΠΏ ΠΊΡΠΈΠ²ΡΡ
Π²ΡΠΎΡΠΎΠ³ΠΎ ΠΏΠΎΡΡΠ΄ΠΊΠ°, ΠΏΠΎΡΠΎΠΆΠ΄Π΅Π½Π½ΡΡ
ΡΠ»Π΅Π΄ΡΡΡΠΈΠΌΠΈ ΡΡΠ°Π²Π½Π΅Π½ΠΈΡΠΌΠΈ
1. $y^2 - 2x - 2y - 5 =0$
$y^2 - 2y + 1 - 1 - 2x - 5 =0$
$$(y-1)^2 = 2x + 6$$
ΠΡΠ²Π΅Ρ: ΠΏΠ°ΡΠ°Π±ΠΎΠ»Π°
2. $3x^2 + 5y^2 + 12x - 30y + 42 = 0$
$3(x^2 + 4x + 4 - 4) + 5(y^2 -6y + 9 - 9) + 42 = 0$
$3(x+2)^2 + 5(y-3)^2 = 15$
$$\frac{(x+2)^2}{5} + \frac{(y-3)^2}{3} = 1$$
ΠΡΠ²Π΅Ρ: ΡΠ»Π»ΠΈΠΏΡ
3. $2x^2 - y^2 + 6y - 7 = 0$
$-(y^2 -6y + 9 - 9) + 2x^2 - 7 = 0$
$-(y-3)^2 + 9 + 2x^2 -7=0$
$-(y-3)^2 + 2x^2 = -2$
$$\frac{(y-3)^2}{2} - x^2 = 1$$
ΠΡΠ²Π΅Ρ: Π³ΠΈΠΏΠ΅ΡΠ±ΠΎΠ»Π°
4. $2x^2 - 3y^2 - 28x - 42y - 55 = 0$
$2(x^2 - 14x + 49 - 49) - 3(y^2 + 14y + 49 - 49) - 55 = 0$
$2((x-7)^2 - 49) - 3((y+7)^2 - 49) - 55 = 0$
$2(x-7)^2 - 3(y+7)^2 = 6$
$$\frac{(x-7)^2}{3} - \frac{(y + 7)^2}{2} = 1$$
ΠΡΠ²Π΅Ρ: Π³ΠΈΠΏΠ΅ΡΠ±ΠΎΠ»Π°
|
import algebra.ring
namespace my_ring
variables {R : Type*} [ring R]
#check add_zero
#check zero_add
#check add_mul
#check add_right_cancel
-- BEGIN
theorem zero_mul (a : R) : 0 * a = 0 :=
begin
have h : 0 * a + 0 * a = 0 + 0 * a,
{ rw [β add_mul, add_zero,zero_add] },
rw add_right_cancel h,
end
-- END
#check zero_mul
end my_ring
|
The product of the Lebesgue measure on $\mathbb{R}^n$ with itself is the Lebesgue measure on $\mathbb{R}^{2n}$.
|
(** * Typechecking: A Typechecker for STLC *)
(** The [has_type] relation of the STLC defines what it means for a
term to belong to a type (in some context). But it doesn't, by
itself, give us an algorithm for _checking_ whether or not a term
is well typed.
Fortunately, the rules defining [has_type] are _syntax directed_
-- that is, for every syntactic form of the language, there is
just one rule that can be used to give a type to terms of that
form. This makes it straightforward to translate the typing rules
into clauses of a typechecking _function_ that takes a term and a
context and either returns the term's type or else signals that
the term is not typable. *)
(** This short chapter constructs such a function and proves it
correct. *)
Set Warnings "-notation-overridden,-parsing".
Require Import Coq.Bool.Bool.
Require Import Maps.
Require Import Smallstep.
Require Import Stlc.
Require MoreStlc.
Module STLCTypes.
Export STLC.
(* ################################################################# *)
(** * Comparing Types *)
(** First, we need a function to compare two types for equality... *)
Fixpoint beq_ty (T1 T2:ty) : bool :=
match T1,T2 with
| TBool, TBool =>
true
| TArrow T11 T12, TArrow T21 T22 =>
andb (beq_ty T11 T21) (beq_ty T12 T22)
| _,_ =>
false
end.
(** ... and we need to establish the usual two-way connection between
the boolean result returned by [beq_ty] and the logical
proposition that its inputs are equal. *)
Lemma beq_ty_refl : forall T1,
beq_ty T1 T1 = true.
Proof.
intros T1. induction T1; simpl.
reflexivity.
rewrite IHT1_1. rewrite IHT1_2. reflexivity. Qed.
Lemma beq_ty__eq : forall T1 T2,
beq_ty T1 T2 = true -> T1 = T2.
Proof with auto.
intros T1. induction T1; intros T2 Hbeq; destruct T2; inversion Hbeq.
- (* T1=TBool *)
reflexivity.
- (* T1=TArrow T1_1 T1_2 *)
rewrite andb_true_iff in H0. inversion H0 as [Hbeq1 Hbeq2].
apply IHT1_1 in Hbeq1. apply IHT1_2 in Hbeq2. subst... Qed.
End STLCTypes.
(* ################################################################# *)
(** * The Typechecker *)
(** The typechecker works by walking over the structure of the given
term, returning either [Some T] or [None]. Each time we make a
recursive call to find out the types of the subterms, we need to
pattern-match on the results to make sure that they are not
[None]. Also, in the [tapp] case, we use pattern matching to
extract the left- and right-hand sides of the function's arrow
type (and fail if the type of the function is not [TArrow T11 T12]
for some [T11] and [T12]). *)
Module FirstTry.
Import STLCTypes.
Fixpoint type_check (Gamma:context) (t:tm) : option ty :=
match t with
| tvar x =>
Gamma x
| tabs x T11 t12 =>
match type_check (update Gamma x T11) t12 with
| Some T12 => Some (TArrow T11 T12)
| _ => None
end
| tapp t1 t2 =>
match type_check Gamma t1, type_check Gamma t2 with
| Some (TArrow T11 T12),Some T2 =>
if beq_ty T11 T2 then Some T12 else None
| _,_ => None
end
| ttrue =>
Some TBool
| tfalse =>
Some TBool
| tif guard t f =>
match type_check Gamma guard with
| Some TBool =>
match type_check Gamma t, type_check Gamma f with
| Some T1, Some T2 =>
if beq_ty T1 T2 then Some T1 else None
| _,_ => None
end
| _ => None
end
end.
End FirstTry.
(* ################################################################# *)
(** * Digression: Improving the Notation *)
(** Before we consider the properties of this algorithm, let's write
it out again in a cleaner way, using "monadic" notations in the
style of Haskell to streamline the plumbing of options. First, we
define a notation for composing two potentially failing (i.e.,
option-returning) computations: *)
Notation " x <- e1 ;; e2"
:= (match e1 with
| Some x => e2
| None => None
end)
(right associativity, at level 60).
(** Second, we define [return] and [fail] as synonyms for [Some] and
[None]: *)
Notation " 'return' e "
:= (Some e) (at level 60).
Notation " 'fail' "
:= None.
Module STLCChecker.
Import STLCTypes.
(** Now we can write the same type-checking function in a more
"imperative" style using these notations. *)
Fixpoint type_check (Gamma:context) (t:tm) : option ty :=
match t with
| tvar x =>
match Gamma x with
| Some T => return T
| None => fail
end
| tabs x T11 t12 =>
T12 <- type_check (update Gamma x T11) t12 ;;
return (TArrow T11 T12)
| tapp t1 t2 =>
T1 <- type_check Gamma t1 ;;
T2 <- type_check Gamma t2 ;;
match T1 with
| TArrow T11 T12 =>
if beq_ty T11 T2 then return T12 else fail
| _ => fail
end
| ttrue =>
return TBool
| tfalse =>
return TBool
| tif guard t1 t2 =>
Tguard <- type_check Gamma guard ;;
T1 <- type_check Gamma t1 ;;
T2 <- type_check Gamma t2 ;;
match Tguard with
| TBool =>
if beq_ty T1 T2 then return T1 else fail
| _ => fail
end
end.
(* ################################################################# *)
(** * Properties *)
(** To verify that th typechecking algorithm is correct, we show that
it is _sound_ and _complete_ for the original [has_type]
relation -- that is, [type_check] and [has_type] define the same
partial function. *)
Theorem type_checking_sound : forall Gamma t T,
type_check Gamma t = Some T -> has_type Gamma t T.
Proof with eauto.
intros Gamma t. generalize dependent Gamma.
induction t; intros Gamma T Htc; inversion Htc.
- (* tvar *) rename s into x. destruct (Gamma x) eqn:H.
rename t into T'. inversion H0. subst. eauto. solve_by_invert.
- (* tapp *)
remember (type_check Gamma t1) as TO1.
destruct TO1 as [T1|]; try solve_by_invert;
destruct T1 as [|T11 T12]; try solve_by_invert;
remember (type_check Gamma t2) as TO2;
destruct TO2 as [T2|]; try solve_by_invert.
destruct (beq_ty T11 T2) eqn: Heqb.
apply beq_ty__eq in Heqb.
inversion H0; subst...
inversion H0.
- (* tabs *)
rename s into x. rename t into T1.
remember (update Gamma x T1) as G'.
remember (type_check G' t0) as TO2.
destruct TO2; try solve_by_invert.
inversion H0; subst...
- (* ttrue *) eauto.
- (* tfalse *) eauto.
- (* tif *)
remember (type_check Gamma t1) as TOc.
remember (type_check Gamma t2) as TO1.
remember (type_check Gamma t3) as TO2.
destruct TOc as [Tc|]; try solve_by_invert.
destruct Tc; try solve_by_invert;
destruct TO1 as [T1|]; try solve_by_invert;
destruct TO2 as [T2|]; try solve_by_invert.
destruct (beq_ty T1 T2) eqn:Heqb;
try solve_by_invert.
apply beq_ty__eq in Heqb.
inversion H0. subst. subst...
Qed.
Theorem type_checking_complete : forall Gamma t T,
has_type Gamma t T -> type_check Gamma t = Some T.
Proof with auto.
intros Gamma t T Hty.
induction Hty; simpl.
- (* T_Var *) destruct (Gamma x0) eqn:H0; assumption.
- (* T_Abs *) rewrite IHHty...
- (* T_App *)
rewrite IHHty1. rewrite IHHty2.
rewrite (beq_ty_refl T11)...
- (* T_True *) eauto.
- (* T_False *) eauto.
- (* T_If *) rewrite IHHty1. rewrite IHHty2.
rewrite IHHty3. rewrite (beq_ty_refl T)...
Qed.
End STLCChecker.
(* ################################################################# *)
(** * Exercises *)
(** **** Exercise: 5 stars (typechecker_extensions) *)
(** In this exercise we'll extend the typechecker to deal with the
extended features discussed in chapter [MoreStlc]. Your job
is to fill in the omitted cases in the following. *)
Module TypecheckerExtensions.
Import MoreStlc.
Import STLCExtended.
Fixpoint beq_ty (T1 T2: ty) : bool :=
match T1,T2 with
| TNat, TNat =>
true
| TUnit, TUnit =>
true
| TArrow T11 T12, TArrow T21 T22 =>
andb (beq_ty T11 T21) (beq_ty T12 T22)
| TProd T11 T12, TProd T21 T22 =>
andb (beq_ty T11 T21) (beq_ty T12 T22)
| TSum T11 T12, TSum T21 T22 =>
andb (beq_ty T11 T21) (beq_ty T12 T22)
| TList T11, TList T21 =>
beq_ty T11 T21
| _,_ =>
false
end.
Lemma beq_ty_refl : forall T1,
beq_ty T1 T1 = true.
Proof.
intros T1.
induction T1; simpl;
try reflexivity;
try (rewrite IHT1_1; rewrite IHT1_2; reflexivity);
try (rewrite IHT1; reflexivity). Qed.
Lemma beq_ty__eq : forall T1 T2,
beq_ty T1 T2 = true -> T1 = T2.
Proof.
intros T1.
induction T1; intros T2 Hbeq; destruct T2; inversion Hbeq;
try reflexivity;
try (rewrite andb_true_iff in H0; inversion H0 as [Hbeq1 Hbeq2];
apply IHT1_1 in Hbeq1; apply IHT1_2 in Hbeq2; subst; auto);
try (apply IHT1 in Hbeq; subst; auto).
Qed.
Fixpoint type_check (Gamma:context) (t:tm) : option ty :=
match t with
| tvar x =>
match Gamma x with
| Some T => return T
| None => fail
end
| tabs x T11 t12 =>
T12 <- type_check (update Gamma x T11) t12 ;;
return (TArrow T11 T12)
| tapp t1 t2 =>
T1 <- type_check Gamma t1 ;;
T2 <- type_check Gamma t2 ;;
match T1 with
| TArrow T11 T12 =>
if beq_ty T11 T2 then return T12 else fail
| _ => fail
end
| tnat _ =>
return TNat
| tsucc t1 =>
T1 <- type_check Gamma t1 ;;
match T1 with
| TNat => return TNat
| _ => fail
end
| tpred t1 =>
T1 <- type_check Gamma t1 ;;
match T1 with
| TNat => return TNat
| _ => fail
end
| tmult t1 t2 =>
T1 <- type_check Gamma t1 ;;
T2 <- type_check Gamma t2 ;;
match T1, T2 with
| TNat, TNat => return TNat
| _,_ => fail
end
| tif0 guard t f =>
Tguard <- type_check Gamma guard ;;
T1 <- type_check Gamma t ;;
T2 <- type_check Gamma f ;;
match Tguard with
| TNat => if beq_ty T1 T2 then return T1 else fail
| _ => fail
end
(* FILL IN HERE *)
| tlcase t0 t1 x21 x22 t2 =>
match type_check Gamma t0 with
| Some (TList T) =>
match type_check Gamma t1,
type_check (update (update Gamma x22 (TList T)) x21 T) t2 with
| Some T1', Some T2' =>
if beq_ty T1' T2' then Some T1' else None
| _,_ => None
end
| _ => None
end
(* FILL IN HERE *)
| _ => None (* ... and delete this line *)
end.
(** Just for fun, we'll do the soundness proof with just a bit more
automation than above, using these "mega-tactics": *)
Ltac invert_typecheck Gamma t T :=
remember (type_check Gamma t) as TO;
destruct TO as [T|];
try solve_by_invert; try (inversion H0; eauto); try (subst; eauto).
Ltac analyze T T1 T2 :=
destruct T as [T1 T2| | | T1 T2| T1 T2| T1]; try solve_by_invert.
Ltac fully_invert_typecheck Gamma t T T1 T2 :=
let TX := fresh T in
remember (type_check Gamma t) as TO;
destruct TO as [TX|]; try solve_by_invert;
destruct TX as [T1 T2| | | T1 T2| T1 T2| T1];
try solve_by_invert; try (inversion H0; eauto); try (subst; eauto).
Ltac case_equality S T :=
destruct (beq_ty S T) eqn: Heqb;
inversion H0; apply beq_ty__eq in Heqb; subst; subst; eauto.
Theorem type_checking_sound : forall Gamma t T,
type_check Gamma t = Some T -> has_type Gamma t T.
Proof with eauto.
intros Gamma t. generalize dependent Gamma.
induction t; intros Gamma T Htc; inversion Htc.
- (* tvar *) rename s into x. destruct (Gamma x) eqn:H.
rename t into T'. inversion H0. subst. eauto. solve_by_invert.
- (* tapp *)
invert_typecheck Gamma t1 T1.
invert_typecheck Gamma t2 T2.
analyze T1 T11 T12.
case_equality T11 T2.
- (* tabs *)
rename s into x. rename t into T1.
remember (update Gamma x T1) as Gamma'.
invert_typecheck Gamma' t0 T0.
- (* tnat *) eauto.
- (* tsucc *)
rename t into t1.
fully_invert_typecheck Gamma t1 T1 T11 T12.
- (* tpred *)
rename t into t1.
fully_invert_typecheck Gamma t1 T1 T11 T12.
- (* tmult *)
invert_typecheck Gamma t1 T1.
invert_typecheck Gamma t2 T2.
analyze T1 T11 T12; analyze T2 T21 T22.
inversion H0. subst. eauto.
- (* tif0 *)
invert_typecheck Gamma t1 T1.
invert_typecheck Gamma t2 T2.
invert_typecheck Gamma t3 T3.
destruct T1; try solve_by_invert.
case_equality T2 T3.
(* FILL IN HERE *)
- (* tlcase *)
rename s into x31. rename s0 into x32.
fully_invert_typecheck Gamma t1 T1 T11 T12.
invert_typecheck Gamma t2 T2.
remember (update (update Gamma x32 (TList T11)) x31 T11) as Gamma'2.
invert_typecheck Gamma'2 t3 T3.
case_equality T2 T3.
(* FILL IN HERE *)
Qed.
Theorem type_checking_complete : forall Gamma t T,
has_type Gamma t T -> type_check Gamma t = Some T.
Proof.
intros Gamma t T Hty.
induction Hty; simpl;
try (rewrite IHHty);
try (rewrite IHHty1);
try (rewrite IHHty2);
try (rewrite IHHty3);
try (rewrite (beq_ty_refl T));
try (rewrite (beq_ty_refl T1));
try (rewrite (beq_ty_refl T2));
eauto.
- destruct (Gamma x); try solve_by_invert. eauto.
Admitted. (* ... and delete this line *)
(*
Qed. (* ... and uncomment this one *)
*)
End TypecheckerExtensions.
(** [] *)
(** **** Exercise: 5 stars, optional (stlc_step_function) *)
(** Above, we showed how to write a typechecking function and prove it
sound and complete for the typing relation. Do the same for the
operational semantics -- i.e., write a function [stepf] of type
[tm -> option tm] and prove that it is sound and complete with
respect to [step] from chapter [MoreStlc]. *)
Module StepFunction.
Import TypecheckerExtensions.
(* FILL IN HERE *)
End StepFunction.
(** [] *)
(** **** Exercise: 5 stars, optional (stlc_impl) *)
(** Using the Imp parser described in the [ImpParser] chapter
of _Logical Foundations_ as a guide, build a parser for extended
Stlc programs. Combine it with the typechecking and stepping
functions from the above exercises to yield a complete typechecker
and interpreter for this language. *)
Module StlcImpl.
Import StepFunction.
(* FILL IN HERE *)
End StlcImpl.
(** [] *)
(** $Date: 2017-12-04 12:28:02 -0600 (Mon, 04 Dec 2017) $ *)
|
import data.set classical algebra.order data.nat
open set eq.ops
namespace relations
variable {T : Type}
/- [KS]
Given a set S, a partition of S is a set X β β(S) (that is, a set of subsets of S) with the following properties:
1. The union of all sets in X is equal to S.
2. For any S1, S2 β X with S1 β S2, we have that S1 β© S2 = Γ (S1 and S2 are disjoint)
3. Γ β X.
-/
definition pairwise_disjoint (Xs : set (set T)) := β β¦ X1 X2 : set T β¦, X1 β Xs β X2 β Xs β X1 β X2 β X1 β© X2 = β
definition big_union (Xs : set (set T)) : set T := Ξ» x, β xs, xs β Xs β§ x β xs
definition powerset (xs : set T) : set (set T) := Ξ» ys, ys β xs
structure partition (xs : set T) (Xs : set (set T)) :=
mk :: (in_powerset : Xs β powerset xs)
(spans : big_union Xs = xs)
(pdisjoint : pairwise_disjoint Xs)
(ncempty : Β¬ β
β Xs)
open partition
-- Choice functions (not the end of the world)
-- (if we go down this road, we would hide the definitions from students, and just give them (1), (3) and (4))
definition cover {xs : set T} {Xs : set (set T)} (p : partition xs Xs) (x : T) : set T := epsilon (Ξ» ys, ys β Xs β§ x β ys)
definition cover_exists {xs : set T} {Xs : set (set T)} (p : partition xs Xs) (x : T) (x_in_xs : x β xs) : β ys, ys β Xs β§ x β ys :=
(spans p)β»ΒΉ βΈ x_in_xs
lemma x_in_cover_x {xs : set T} {Xs : set (set T)} (p : partition xs Xs) (x : T) (x_in_xs : x β xs) : x β cover p x :=
and.right (epsilon_spec (cover_exists p x x_in_xs))
lemma cover_x_in_Xs {xs : set T} {Xs : set (set T)} (p : partition xs Xs) (x : T) (x_in_xs : x β xs) : cover p x β Xs :=
and.left (epsilon_spec (cover_exists p x x_in_xs))
/- [KS]
Lemma: Let S be a set and X a partition of S. Then every element u β S belongs to exactly one set
Y β X
Proof: Let S be a set and X a partition of S. We will show that every element u β S belongs to at least
one set Y β X and to at most one set Y β X.
To see that every element u β S belongs to at least one set Y β X, note that since X is a partition of S,
the union of all the sets in S must be equal to S. Consequently, there must be at least one set Y β X
such that u β Y, since otherwise the union of all sets contained in X would not be equal to S.
To see that every element u β S belongs to at most one set Y β X, suppose for the sake of contradiction
that u belongs to two sets Y1, Y2 β X with Y1 β Y2. But then x β Y1 β© Y2, meaning that
Y1 β© Y2 β Γ, a contradiction. We have reached a contradiction, so our assumption must have been
wrong.
Thus every element u β S belongs to at most one set Y β X. β
-/
definition exactly_one [reducible] {T : Type} (P : T β Prop) := (β (u : T), P u) β§ (β u v : T, P u β P v β u = v)
-- Lemma: Let S be a set and X a partition of S. Then every element u β S belongs to exactly one set Y β X.
definition unique_set : β {S : set T} {X : set (set T)}, partition S X β β (u : T), u β S β exactly_one (Ξ» (Y : set T), Y β X β§ u β Y) :=
-- Proof: Let S be a set and X a partition of S.
assume (S : set T) (X : set (set T)) (p : partition S X) (u : T) (u_in_S : u β S),
-- We will show that every element u β S belongs to at least one set Y β X and to at most one set Y β X.
show (β (Y : set T), Y β X β§ u β Y) β§ (β (Y1 Y2 : set T), (Y1 β X β§ u β Y1) β (Y2 β X β§ u β Y2) β Y1 = Y2), from
-- To see that every element u β S belongs to at least one set Y β X,
have exists_Y : β (Y : set T), Y β X β§ u β Y, from
-- note that since X is a partition of S, the union of all the sets in S must be equal to S.
-- Consequently, there must be at least one set Y β X such that u β Y,
-- since otherwise the union of all sets contained in X would not be equal to S.
have u_in_bigX : u β big_union X, from (spans p)β»ΒΉ βΈ u_in_S,
u_in_bigX,
-- To see that every element u β S belongs to at most one set Y β X,
have unique : (β (Y1 Y2 : set T), (Y1 β X β§ u β Y1) β (Y2 β X β§ u β Y2) β Y1 = Y2), from
-- suppose for the sake of contradiction that u belongs to two sets Y1, Y2 β X with Y1 β Y2.
assume (Y1 Y2 : set T) (HY1 : Y1 β X β§ u β Y1) (HY2 : Y2 β X β§ u β Y2),
by_contradiction
(assume Y1_neq_Y2 : Y1 β Y2,
show false, from
-- But then u β Y1 β© Y2,
have u_in_Y1capY2 : u β Y1 β© Y2, from and.intro (and.right HY1) (and.right HY2),
-- meaning that Y1 β© Y2 β Γ, a contradiction.
have Y1capY2_nempty : Y1 β© Y2 β β
, from
assume Y1capY2_empty : Y1 β© Y2 = β
,
have u_in_emptyset : u β β
, from Y1capY2_empty βΈ u_in_Y1capY2,
show false, from u_in_emptyset,
-- We have reached a contradiction, so our assumption must have been wrong.
absurd (pdisjoint p (and.left HY1) (and.left HY2) Y1_neq_Y2) Y1capY2_nempty),
-- Thus every element u β S belongs to at most one set Y β X.
show exactly_one (Ξ» (Y : set T), Y β X β§ u β Y), from and.intro exists_Y unique
-- β
definition set_of_sets (f : T β set T) : set (set T) := Ξ» (s : set T), β (u : T), s = f u
definition bigcup (Xs : set (set T)) : set T := Ξ» (v: T), β (X : set T), X β Xs β§ v β X
lemma equiv_spans : β {R : T β T β Prop}, equivalence R β β v, v β bigcup (set_of_sets R) :=
assume (R : T β T β Prop) (R_equiv : equivalence R) (v : T),
show β (X : set T), X β (set_of_sets R) β§ v β X, from
let X := R v in
have X_in_ssR : X β set_of_sets R, from exists.intro v rfl,
have v_in_X : v β X, from and.left R_equiv v,
exists.intro X (and.intro X_in_ssR v_in_X)
end relations
|
C Copyright(C) 1999-2020 National Technology & Engineering Solutions
C of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
C NTESS, the U.S. Government retains certain rights in this software.
C
C See packages/seacas/LICENSE for details
SUBROUTINE GETFRM (MXND, LINES, NL, NXL, NODE, N0, N2, NFROM)
C***********************************************************************
C SUBROUTINE GETFRM = GETS THE NODES THAT THE CURRENT NODE CAME FROM
C***********************************************************************
DIMENSION NXL(2, 3*MXND), LINES(NL)
NFROM = 0
IF (NL .EQ. 3) THEN
DO 100 IL = 1, NL
ILL = LINES (IL)
IF (NXL (1, ILL) .EQ. NODE) THEN
NTEST = NXL (2, ILL)
ELSEIF (NXL (2, ILL) .EQ. NODE) THEN
NTEST = NXL (1, ILL)
ELSE
CALL MESSAGE('** PROBLEMS IN GETFRM **')
GOTO 110
ENDIF
IF ((NTEST .NE. N0) .AND. (NTEST .NE. N2)) THEN
NFROM = NTEST
GOTO 110
ENDIF
100 CONTINUE
ENDIF
110 CONTINUE
RETURN
END
|
import LinearAlgebra: Transpose, opnorm
import LinearAlgebra
import Random: seed!
using SparseArrays
export fill_diag!, diag!
# temporary function. will actually add CUDA barrier function.
function sync()
nothing
end
"""
Allgather_opt(B)
Returns a tuple of proper function and argument for Allgather.
"""
function Allgather_opt(B::MPIVecOrMat{T,AT}) where {T,AT}
if allsame(B.local_lengths)
(Allgather!, B.localarray, B.local_lengths[1])
else
(Allgatherv!, B.localarray, B.local_lengths)
end
end
function Allgather_opt(B::Transpose{T,ATT} where ATT <: MPIVecOrMat{T,AT}) where {T,AT}
B_buf = transpose(B).localarray
tB_local_lengths = transpose(B).local_lengths
if allsame(tB_local_lengths)
(Allgather!, B_buf, tB_local_lengths[1])
else
(Allgatherv!, B_buf, tB_local_lengths)
end
end
@inline get_local(A::MPIVecOrMat{T,AT}) where {T,AT} = A.localarray
@inline get_local(A::Transpose{T,ATT} where ATT <: MPIVecOrMat{T,AT}) where {T,AT} = transpose(transpose(A).localarray)
"""
Scenario a: short and fat matrix multiplied by a fat matrix. Temporary space required
A: r x [p], B: p x [q], C: r x [q]
tmp: r x p: A is Allgather!-ed.
"""
function LinearAlgebra.mul!(C::MPIMatrix{T,AT}, A::MPIMatrix{T,AT}, B::MPIMatrix{T,AT};
tmp::AbstractArray{T,2}=AT{T}(undef, size(A,1), size(A,2))) where {T,AT}
@assert size(C,1) == size(A,1) && size(C,2) == size(B,2)
@assert size(A,1) == size(tmp,1) && size(A, 2) == size(tmp, 2)
localA = get_local(A)
localB = get_local(B)
localC = get_local(C)
#Allgather
sync()
(Allgather_ftn!, sendbuf, count_arg) = Allgather_opt(A)
Allgather_ftn!(sendbuf, tmp, count_arg)
LinearAlgebra.mul!(localC, tmp, localB)
C
end
"""
Scenario h: Scenario 1 transposed.
"""
function LinearAlgebra.mul!(C::Transpose{T,MPIMatrix{T,AT}}, A::Transpose{T,MPIMatrix{T,AT}}, B::Transpose{T,MPIMatrix{T,AT}};
tmp::AbstractArray{T,2}=AT{T}(undef, size(B,2), size(B,1))) where {T,AT}
LinearAlgebra.mul!(transpose(C), transpose(B), transpose(A); tmp=tmp)
C
end
"""
Scenario b: inner product, result distributed, temporary space required
A: r x [p], B: [p] x q, C: r x [q]
tmp: r x q, for local computation
"""
function LinearAlgebra.mul!(C::MPIMatrix{T,AT}, A::MPIMatrix{T,AT}, B::Transpose{T, MPIMatrix{T,AT}};
tmp::AbstractArray{T,2}=AT{T}(undef, size(A,1), size(B,2))) where {T,AT}
@assert size(C,1) == size(A,1) && size(C,2) == size(B,2)
@assert size(A,1) == size(tmp,1) && size(B,2) == size(tmp,2)
localA = get_local(A)
localB = get_local(B)
LinearAlgebra.mul!(tmp, localA, localB)
# Ireduce would fit well here... but is not supported on both PyTorch and MPI.jl.
sync()
for i = 0:Size()-1
# NOTE: an array is set to be contiguous only if the first indices are colon.
Reduce!(@view(tmp[:, C.partitioning[i+1][2]]), C.localarray; root=i)
end
C
end
"""
Scenario c: Scenario 2 transposed.
"""
function LinearAlgebra.mul!(C::Transpose{T,MPIMatrix{T,AT}}, A::MPIMatrix{T,AT},B::Transpose{T,MPIMatrix{T,AT}};
tmp::AbstractArray{T,2}=AT{T}(undef, size(B,2), size(A,1))) where {T,AT}
LinearAlgebra.mul!(transpose(C), transpose(B), transpose(A);tmp=tmp)
end
"""
Scenario d: inner product, result broadcasted
"""
function LinearAlgebra.mul!(C::AbstractMatrix{T}, A::MPIMatrix{T,AT}, B::Transpose{T,MPIMatrix{T,AT}}) where {T,AT}
@assert size(C, 1) == size(A, 1) && size(C, 2) == size(B, 2)
localA = get_local(A)
localB = get_local(B)
LinearAlgebra.mul!(C, localA, localB)
sync()
Allreduce!(C)
C
end
"""
Scenario e: A::MPIMatrix, B, C: broadcast matrix.
"""
function LinearAlgebra.mul!(C::AbstractMatrix{T}, A::MPIMatrix{T,AT}, B::AbstractMatrix{T}) where {T, AT}
localA = get_local(A)
LinearAlgebra.mul!(C, localA, B[A.partitioning[Rank() + 1][2], :])
sync()
Allreduce!(C)
C
end
"""
Scenario f: outer product, temporary space required
transpose(A) is Allgather!-ed.
"""
function LinearAlgebra.mul!(C::MPIMatrix{T,AT}, A::Transpose{T,MPIMatrix{T,AT}}, B::MPIMatrix{T,AT};
tmp::AbstractArray{T,2}=AT{T}(undef,size(A,2),size(A,1))) where {T,AT}
@assert size(C,1) == size(A,1) && size(C,2) == size(B,2)
@assert size(A,2) == size(tmp,1) && size(A,1) == size(tmp,2)
localA = get_local(A)
localB = get_local(B)
localC = get_local(C)
# Allgather
sync()
(Allgather_ftn!, sendbuf, count_arg) = Allgather_opt(A)
Allgather_ftn!(sendbuf, tmp, count_arg)
LinearAlgebra.mul!(localC, transpose(tmp), localB)
C
end
"""
Scenario g: Scenario 3 transposed.
"""
function LinearAlgebra.mul!(C::Transpose{T,MPIMatrix{T,AT}}, A::Transpose{T,MPIMatrix{T,AT}}, B::MPIMatrix{T,AT};
tmp::AbstractArray{T,2}=AT{T}(undef,size(B,1), size(B,2))) where {T,AT}
LinearAlgebra.mul!(transpose(C), transpose(B), transpose(A);tmp=tmp)
C
end
"""
Scenario j: Small, broadcasted matrix multiplied by a distributed matrix.
A: s x r, B: r x [q], C: s x [q].
"""
function LinearAlgebra.mul!(C::MPIMatrix{T,AT}, A::AbstractMatrix{T}, B::MPIMatrix{T,AT}) where {T,AT}
localB = get_local(B)
localC = get_local(C)
LinearAlgebra.mul!(localC, A, localB)
C
end
"""
Scenario i: Scenario 4 transposed.
"""
function LinearAlgebra.mul!(C::Transpose{T,MPIMatrix{T,AT}}, A::Transpose{T,MPIMatrix{T,AT}},
B::AbstractMatrix{T}) where {T,AT}
LinearAlgebra.mul!(transpose(C), transpose(B), transpose(A))
C
end
"""
Scenario k: B transposed MPIMatrix, A, C: broadcast matrix.
"""
function LinearAlgebra.mul!(C::AbstractMatrix{T}, A::AbstractMatrix{T},
B::Transpose{T, MPIMatrix{T,AT}}) where {T, AT}
LinearAlgebra.mul!(transpose(C), transpose(B), transpose(A))
C
end
"""
Distributed matrix x broadcasted vector multiplications
"""
const MPIColVector{T,AT} = Union{MPIVector{T,AT},Transpose{T,MPIMatrix{T,AT}}}
get_MPIArray(m::MPIArray) = m
get_MPIArray(m::Transpose{T,MPIMatrix{T,A}}) where {T,A} = transpose(m)
"""
Scenario l: Col-dist matrix x distributed vector = distributed vector
"""
function LinearAlgebra.mul!(C::MPIColVector{T,AT}, A::MPIMatrix{T,AT}, B::MPIColVector{T,AT};
tmp::AbstractArray{T}=AT{T}(undef, size(C, 1))) where {T,AT}
LinearAlgebra.mul!(tmp, A, B)
localC = get_local(C)
C_mpi = get_MPIArray(C)
localC .= tmp[C_mpi.partitioning[Rank()+1][1]]
end
"""
Scenario m: Inner product
"""
function LinearAlgebra.mul!(C::AbstractVector{T}, A::MPIMatrix{T,AT}, B::MPIColVector{T,AT}) where {T,AT}
localA = get_local(A)
localB = get_local(B)
LinearAlgebra.mul!(C, localA, localB)
sync()
Allreduce!(C)
C
end
"""
Scenario n: no vector distributed, A MPIMatrix
"""
function LinearAlgebra.mul!(C::AbstractVector{T}, A::MPIMatrix{T,AT}, B::AbstractVector{T}) where {T,AT}
localA = get_local(A)
LinearAlgebra.mul!(C, localA, B[A.partitioning[Rank()+1][2]])
sync()
Allreduce!(C)
C
end
"""
Scenario o: Row-dist matrix x distributed vector = distributed vector
"""
function LinearAlgebra.mul!(C::MPIColVector{T,AT}, A::Transpose{T,MPIMatrix{T,AT}},B::MPIColVector{T,AT};
tmp::AbstractArray{T}=AT{T}(undef, size(B,1))) where {T,AT}
localA = get_local(A)
localC = get_local(C)
# Allgather
sync()
(Allgather_ftn!, sendbuf, count_arg) = Allgather_opt(B)
Allgather_ftn!(sendbuf, tmp, count_arg)
LinearAlgebra.mul!(localC, localA, tmp)
C
end
"""
Scenario p: Row-dist matrix x broadcast vector = dist vector
"""
function LinearAlgebra.mul!(C::MPIColVector{T,AT}, A::Transpose{T,MPIMatrix{T,AT}}, B::AbstractVector{T}) where {T,AT}
localA = get_local(A)
localC = get_local(C)
LinearAlgebra.mul!(localC, localA, B)
# undefined in CuArrays: mul!(::Transpose{Float64,CuArray{Float64,2}}, ::Transpose{Float64,CuArray{Float64,2}}, ::CuArray{Float64,1})
C
end
"""
Scenario q: no vector distributed, A transposed MPIMatrix
"""
function LinearAlgebra.mul!(C::AbstractVector{T}, A::Transpose{T, MPIMatrix{T,AT}}, B::AbstractVector{T}) where {T,AT}
localA = get_local(A)
fill!(C, zero(T))
LinearAlgebra.mul!(@view(C[transpose(A).partitioning[Rank()+1][2]]), localA, B[transpose(A).partitioning[Rank()+1][1]])
sync()
Allreduce!(C)
C
end
const AbstractSparseOrTranspose{T} = Union{AbstractSparseMatrix{T, <:Integer},Transpose{T,<:AbstractSparseMatrix}}
"""
Sparse matrix-vector multiplications
"""
#=
function LinearAlgebra.mul!(C::AbstractVector{T}, A::AbstractSparseOrTranspose{T}, B::MPIColVector{T,AT};
tmp::AbstractArray{T}=AT{T}(undef, size(B,1))) where {T,AT}
@assert length(C) == size(A,1) && length(B) == size(A,2)
@assert length(tmp) == length(B)
# Allgather
sync()
(Allgather_ftn!, sendbuf, count_arg) = Allgather_opt(B)
Allgather_ftn!(sendbuf, tmp, count_arg)
LinearAlgebra.mul!(C, A, tmp)
C
end
function LinearAlgebra.mul!(C::MPIColVector{T,AT}, A::AbstractSparseOrTranspose{T}, B::AbstractVector{T};
tmp::AbstractArray{T}=AT{T}(undef, size(A,1))) where {T,AT}
@assert length(C) == size(A,1) && length(B) == size(A,2)
@assert length(tmp) == length(C)
localC = get_local(C)
LinearAlgebra.mul!(tmp, A, B)
C_mpi = get_MPIArray(C)
localC .= tmp[C_mpi.partitioning[Rank()+1][1]]
C
end
function LinearAlgebra.mul!(C::MPIColVector{T,AT}, A::AbstractSparseOrTranspose{T}, B::MPIColVector{T,AT};
tmp_m::AbstractArray{T}=AT{T}(undef, size(A,1)),
tmp_n::AbstractArray{T}=AT{T}(undef, size(B,1))) where {T,AT}
@assert length(C) == size(A,1) && length(B) == size(A,2)
@assert length(tmp_m) == size(A,1) && length(tmp_n) == size(A,2)
LinearAlgebra.mul!(tmp_m, A, B)
localC = get_local(C)
C_mpi = get_MPIArray(C)
localC .= tmp_m[C_mpi.partitioning[Rank()+1][1]]
C
end
=#
"""
LinearAlgebra.dot(A::MPIArray, B::MPIArray)
dot product of two MPI vectors.
"""
@inline function LinearAlgebra.dot(A::MPIArray, B::MPIArray)
c = LinearAlgebra.dot(A.localarray, B.localarray)
MPI.Allreduce(c, MPI.SUM, MPI.COMM_WORLD)
end
"""
LinearAlgebra.diagind(M::MPIMatrix, k)
returns indices of the diagonal with respect to `M.localarray`.
"""
@inline function LinearAlgebra.diagind(M::MPIMatrix, k::Integer=0)
offset = - (M.partitioning[Rank()+1][2][1]-1) + k
return LinearAlgebra.diagind(size(M,1), size(M.localarray,2), offset)
end
"""
LinearAlgebra.diag(M::MPIMatrix{T,A}, k; dist::Bool=false) where {T,A}
returns the diagonal of M. If dist is false, the result is a broadcasted A{T,1}. otherwise, the result is
distributed 1 x n "row vector". Distributed return is only valid for a square matrix (due to current way of distribution).
"""
function LinearAlgebra.diag(M::MPIMatrix{T,A}, k::Integer=0; dist::Bool=false) where {T,A}
# TODO
end
"""
diag!(d::MPIMatrix{T,A}, M::MPIMatrix{T,A})
returns a distributed 1-row matrix.
"""
function diag!(d::MPIMatrix{T,A}, M::MPIMatrix{T,A}) where {T,A}
@assert size(d,1) == 1
@assert size(d,2) == size(M, 2)
@assert size(M,1) == size(M,2)
d.localarray .= reshape(M.localarray[LinearAlgebra.diagind(M)], 1, :)
end
"""
diag!(d::AbstractVector, M::MPIMatrix{T,A})
returns a local col vector.
"""
function diag!(d::AbstractVector, M::MPIMatrix{T,A}) where {T,A}
@assert size(d,1) == size(M, 1)
@assert size(M,1) == size(M,2)
d[M.partitioning[Rank()+1][2]] .= M.localarray[LinearAlgebra.diagind(M)]
counts = reshape(map(x->convert(Cint, length(x[2])), M.partitioning), :)
sync()
MPI.Allgatherv!(MPI.IN_PLACE, d, counts, MPI.COMM_WORLD)
end
"""
fill_diag!(M, x, k=0)
fills the diagonal of M with x.
"""
@inline function fill_diag!(M::MPIMatrix, x, k::Integer=0)
M.localarray[LinearAlgebra.diagind(M, k)] .= x
end
"""
opnorm(A::MPIMatrix; method="power", tol=1e-8)
Estimates operator l2 norm of MPIMatrix A. If `method=="power", it uses the power iteration.
If `method=="quick"`, it computes the product of matrix l1 norm and the matrix l-infty norm.
"""
function opnorm(A::MPIMatrix; method::String="power", tol=1e-6, maxiter=1000, seed=777, verbose=false)
if method == "power"
_opnorm_power(A; tol=tol, maxiter=maxiter, seed=seed, verbose=verbose)
elseif method == "quick"
_opnorm_quick(A)
else
@error("Invalid method. Valid values are: \"power\" and \"quick\".")
end
end
function opnorm(A::MPIMatrix, p::Real; method::String="power", tol=1e-6, maxiter=1000, seed=777, verbose=false)
if p == 1
_opnorm_l1(A)
elseif p == 2
opnorm(A; method=method, tol=tol, maxiter=maxiter, seed=seed, verbose=verbose)
elseif p == Inf
_opnorm_linfty(A)
else
@error("Invalid p for opnorm. Valid values are: 1, 2, and Inf.")
end
end
function _opnorm_l1(A::MPIMatrix)
maximum(sum(abs.(A); dims=1))
end
function _opnorm_linfty(A::MPIMatrix)
maximum(sum(abs.(A); dims=2))
end
function _opnorm_power(A::MPIMatrix{T,AT}; tol=1e-6, maxiter=1000, seed=777, verbose=false) where {T, AT}
verbose && Rank() == 0 && println("computing max singular value...")
m, n = size(A)
seed!(seed)
v = MPIVector{T,AT}(undef, n)
randn!(v)
Av = MPIVector{T,AT}(undef, m)
LinearAlgebra.mul!(Av, A, v)
s, s_prev = -Inf, -Inf
for i in 1:maxiter
LinearAlgebra.mul!(v, transpose(A), Av)
v ./= sqrt(sum(v.^2))
LinearAlgebra.mul!(Av, A, v)
s = sqrt(sum(Av.^2))
if abs((s_prev - s)/s) < tol
break
end
s_prev = s
verbose && Rank() == 0 && i%100 == 0 && println("iteration $i: $s")
end
verbose && Rank() == 0 && println("done computing max singular value: $s")
s
end
function _opnorm_quick(A::MPIMatrix)
l1 = _opnorm_l1(A)
linf = _opnorm_linfty(A)
l1*linf
end
|
State Before: ΞΉ : Type uβ
k : Type uβ
V : Type uβ
P : Type uβ
instββ΅ : AddCommGroup V
instββ΄ : AffineSpace V P
instβΒ³ : DivisionRing k
instβΒ² : Module k V
instβΒΉ : Fintype ΞΉ
instβ : FiniteDimensional k V
h : Fintype.card ΞΉ = FiniteDimensional.finrank k V + 1
β’ Nonempty (AffineBasis ΞΉ k P) State After: case intro.intro
ΞΉ : Type uβ
k : Type uβ
V : Type uβ
P : Type uβ
instββ΅ : AddCommGroup V
instββ΄ : AffineSpace V P
instβΒ³ : DivisionRing k
instβΒ² : Module k V
instβΒΉ : Fintype ΞΉ
instβ : FiniteDimensional k V
h : Fintype.card ΞΉ = FiniteDimensional.finrank k V + 1
s : Set P
b : AffineBasis (βs) k P
hb : βb = Subtype.val
β’ Nonempty (AffineBasis ΞΉ k P) Tactic: obtain β¨s, b, hbβ© := AffineBasis.exists_affineBasis k V P State Before: case intro.intro
ΞΉ : Type uβ
k : Type uβ
V : Type uβ
P : Type uβ
instββ΅ : AddCommGroup V
instββ΄ : AffineSpace V P
instβΒ³ : DivisionRing k
instβΒ² : Module k V
instβΒΉ : Fintype ΞΉ
instβ : FiniteDimensional k V
h : Fintype.card ΞΉ = FiniteDimensional.finrank k V + 1
s : Set P
b : AffineBasis (βs) k P
hb : βb = Subtype.val
β’ Nonempty (AffineBasis ΞΉ k P) State After: case intro.intro.intro
ΞΉ : Type uβ
k : Type uβ
V : Type uβ
P : Type uβ
instββ΅ : AddCommGroup V
instββ΄ : AffineSpace V P
instβΒ³ : DivisionRing k
instβΒ² : Module k V
instβΒΉ : Fintype ΞΉ
instβ : FiniteDimensional k V
h : Fintype.card ΞΉ = FiniteDimensional.finrank k V + 1
s : Finset P
b : AffineBasis (ββs) k P
hb : βb = Subtype.val
β’ Nonempty (AffineBasis ΞΉ k P) Tactic: lift s to Finset P using b.finite_set State Before: case intro.intro.intro
ΞΉ : Type uβ
k : Type uβ
V : Type uβ
P : Type uβ
instββ΅ : AddCommGroup V
instββ΄ : AffineSpace V P
instβΒ³ : DivisionRing k
instβΒ² : Module k V
instβΒΉ : Fintype ΞΉ
instβ : FiniteDimensional k V
h : Fintype.card ΞΉ = FiniteDimensional.finrank k V + 1
s : Finset P
b : AffineBasis (ββs) k P
hb : βb = Subtype.val
β’ Nonempty (AffineBasis ΞΉ k P) State After: case intro.intro.intro
ΞΉ : Type uβ
k : Type uβ
V : Type uβ
P : Type uβ
instββ΅ : AddCommGroup V
instββ΄ : AffineSpace V P
instβΒ³ : DivisionRing k
instβΒ² : Module k V
instβΒΉ : Fintype ΞΉ
instβ : FiniteDimensional k V
h : Fintype.card ΞΉ = FiniteDimensional.finrank k V + 1
s : Finset P
b : AffineBasis (ββs) k P
hb : βb = Subtype.val
β’ Fintype.card ββs = Fintype.card ΞΉ Tactic: refine' β¨b.reindex <| Fintype.equivOfCardEq _β© State Before: case intro.intro.intro
ΞΉ : Type uβ
k : Type uβ
V : Type uβ
P : Type uβ
instββ΅ : AddCommGroup V
instββ΄ : AffineSpace V P
instβΒ³ : DivisionRing k
instβΒ² : Module k V
instβΒΉ : Fintype ΞΉ
instβ : FiniteDimensional k V
h : Fintype.card ΞΉ = FiniteDimensional.finrank k V + 1
s : Finset P
b : AffineBasis (ββs) k P
hb : βb = Subtype.val
β’ Fintype.card ββs = Fintype.card ΞΉ State After: no goals Tactic: rw [h, β b.card_eq_finrank_add_one]
|
<link rel="stylesheet" href="../../styles/theme_style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<table width="100%">
<tr>
<td id="image_td" width="15%" class="header_image_color_4"><div id="image_img" class="header_image_4"></div></td>
<td class="header_text"> Digital Filtering - A Fundamental Pre-Processing Step </td>
</tr>
</table>
<div id="flex-container">
<div id="diff_level" class="flex-item">
<strong>Difficulty Level:</strong> <span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
</div>
<div id="tag" class="flex-item-tag">
<span id="tag_list">
<table id="tag_list_table">
<tr>
<td class="shield_left">Tags</td>
<td class="shield_right" id="tags">pre-process☁filter</td>
</tr>
</table>
</span>
<!-- [OR] Visit https://img.shields.io in order to create a tag badge-->
</div>
</div>
The acquired electrophysiological signals have always two intrinsic components.
The signal we really want to acquire/study and noise, i.e. the acquisition component that is not relevant for the study purposes.
Noise can have different origins, such as in random events or due to voluntary/involuntary movements of the subject under analysis that affect the <a href="https://en.wikipedia.org/wiki/Noise_(signal_processing)" target="_blank">signal acquisition </a>.
So, <a href="https://en.wikipedia.org/wiki/Filter_(signal_processing)" target="_blank">filtering </a> is a fundamental step that needs to be applied to the signal, in order to ensure the maximisation of
<a href="https://en.wikipedia.org/wiki/Signal-to-noise_ratio" target="_blank">signal to noise ratio </a>. Filtering can be achieved by hardware, having the analogical systems a great relevance, or by software using digital filters.
In this <strong><span class="color5">Jupyter Notebook</span></strong> it will be demonstrated how to digital filter the signal.
<hr>
<p class="steps">1 - Importation of the needed packages</p>
```python
# biosignalsnotebooks own package for loading and plotting the acquired data
import biosignalsnotebooks as bsnb
# Scientific package
from numpy import array, mean, average, linspace, where
from numpy.random import normal
```
```python
# Hide warnings.
# https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/h817iNS2twk
from IPython.display import HTML
HTML('''
To toggle on/off output_stderr, click <a href="javascript:code_toggle_err()">here</a>.''')
```
<p class="steps">2 - Load of acquired ECG data</p>
```python
# Load of data
data, header = bsnb.load_signal("ecg_4000_Hz", get_header=True)
```
In the following cell, some relevant information is stored inside variables. This relevant information includes the mac-address of the device, channel number and signal acquisition parameters such as resolution and sampling rate.
For a detailed explanation of how to access this info, the <a href="../Load/signal_loading_preparatory_steps.ipynb" target="_blank">"Signal Loading - Working with File Header"</a> Notebook should be consulted.
```python
ch = "CH1" # Channel
sr = header["sampling rate"] # Sampling rate
resolution = header["resolution"] # Resolution (number of available bits)
```
<p class="steps">3 - Generation of signal power spectrum by <i>Fast Fourier Transform</i> (FFT)</p>
With this step is possible to observe the frequency composition of ECG signal.
<p class="steps">3.1 - Store the desired physiological data (channel 1) int an individual variable</p>
```python
# Acquired data
signal = data[ch]
```
<p class="steps">3.2 - Removal of continuous component from our signal (baseline shift through the subtraction of the average value) </p>
This task ensures more stability of our filtering system.
```python
# Baseline shift.
signal = array(signal) - mean(signal)
```
<p class="steps">3.3 - Generation of the power spectrum </p>
```python
# Power spectrum
freq_axis_1, power_spect_1 = bsnb.plotfft(signal, sr)
```
<p class="steps">4 - The informational content of ECG signal is typically contained below the 40 Hz frequency component</p>
With the next representation we can conclude that exist some unwanted information out of this frequency band.
```python
fig_1 = bsnb.plot_informational_band(freq_axis_1, power_spect_1, signal, sr, band_begin=0.5, band_end=40, legend="ECG Power Spectrum",
x_lim=[0, 100], y_lim=[0, 5e6], show_plot=True)
```
<p class="steps">5 - Application of a low-pass filter in order to be excluded the unwanted information above the 40 Hz frequency component</p>
Some low-frequency noise can be present at [0, 0.5] Hz frequency band. To exclude it we can follow an identical procedure, but, instead of applying a low-pass filter, it should be used a band-pass filter for the frequencies inside [0.5, 40] Hz.
<br>
For now, we focused on the more problematic type of noise, i.e., the high frequency noise
```python
# Digital lowpass filtering with a cutoff frequency f of 40 Hz
filter_signal_1 = bsnb.lowpass(signal, f=40, order=1, fs=sr)
# Power spectrum
freq_axis_2, power_spect_2 = bsnb.plotfft(filter_signal_1, sr)
```
<p class="steps">6 - Comparison of the power spectrum of original and filtered signal</p>
```python
bsnb.plot_before_after_filter(signal, sr, band_begin=0.5, band_end=40, x_lim=[0, 100], y_lim=[0, 5e6], show_plot=True)
```
In this first filtering attempt we used a first order filter (input argument order=1). It can be seen, in the previous figure, that some unwanted information have been removed, unfortunately no filter has an ideal behavior, so despite we specify a high cutoff frequency of 40 Hz, some information above this threshold is maintained after filtering.
The good news are that components greater than 80 Hz are almost completely removed.
The filter performance can be improved by increasing the filter order, because the higher the filter order is, more quickly the transition between the pass and stop band will be. The transition band will be smaller because of a higher attenuation rate (-20 x <strong>order</strong> dB/decade).
However, the filter order must be chosen with precaution in order to avoid system instability. <strong><span class="color4">Magnitude Bode plots</span></strong> are very useful to check the filter response, as can be seen in the figure below, taking into consideration the following Mathematical formulation.
\begin{equation}
G = -20\times\log_{10}\Bigg(\sqrt{1 + \bigg(\frac{f}{f_c}\bigg)^{2.n}}\Bigg)
\end{equation}
<table width="100%">
<tr>
<td width="20%"></td>
<td width="30%" style="text-align:left;vertical-align:top">$G$ - Gain factor (negative values reveal an attenuation)</td>
<td width="30%" style="text-align:left;vertical-align:top">$n$ - Filter order (integer)</td>
<td width="20%"></td>
</tr>
<tr>
<td></td>
<td style="text-align:left;vertical-align:top">$f_{c}$ - Cutoff frequency of the filter (40 Hz, for the current implementation)</td>
<td style="text-align:left;vertical-align:top">$f$ - Independent variable (input frequency to be filtered)</td>
<td></td>
</tr>
</table>
```python
bsnb.plot_low_pass_filter_response()
```
<p class="steps">7 - Repetition of the filtering stage but using a higher filter order</p>
```python
# Digital low-pass filtering with a cutoff frequency f of 40 Hz
filter_signal_2 = bsnb.lowpass(signal, f=40, order=3, fs=sr)
# Power spectrum
freq_axis_3, power_spect_3 = bsnb.plotfft(filter_signal_2, sr)
```
```python
bsnb.plot_before_after_filter(signal, sr, band_begin=0.5, band_end=40, order=3, x_lim=[0, 100], y_lim=[0, 5e6],
orientation="same", show_plot=True)
```
When the noise level is low, it may be difficult to observe its influence in time domain.
In order to the digital filtering stage produce a visual effect in time domain, the noise level needs to be high.
So we will add some artificial noise do the signal and see the great impact of digital filtering.
<hr>
<p class="steps">E1 - Addition of artificial noise</p>
```python
# Noise samples and translation of the baseline
baseline = average(signal)
baseline_shift = 0.50 * baseline
noisy_signal = signal + normal(0, 1000, len(signal)) + baseline_shift
```
<p class="steps">E2 - Noisy signal representation</p>
```python
# Plotting of power spectrum
bsnb.plot(linspace(0, len(noisy_signal) - 1, len(noisy_signal)), noisy_signal, x_axis_label='Sample Number',
y_axis_label='Raw Data', title="Noisy Signal", y_range=(-1e4, 6e4))
```
<p class="steps">E3 - Digital Filtering Stage</p>
```python
# Digital low-pass filtering with a cutoff frequency f of 40 Hz
noisy_signal_filter = bsnb.lowpass(noisy_signal, f=40, order=3, fs=sr)
```
<p class="steps">E4 - Comparison of noisy and filtered signal in time domain</p>
```python
bsnb.plot([linspace(0, len(noisy_signal) - 1, len(noisy_signal))]*2, [noisy_signal, noisy_signal_filter],
grid_plot=True, grid_lines=1, grid_columns=2, x_axis_label='Sample Number', y_axis_label='Raw Data',
title=["Noisy Signal", "Filtered Signal"])
```
As described previously, none filter has an ideal behavior, but, in spite of not ideal the behavior of real filters is predictable.
For example, for the designed 3rd order Butterworth filter with cutoff frequency of 40 Hz, it is expected that after one decade (40 Hz x 10 = 400 Hz) the relative amplitude will be attenuated by -60 dB (assuming a value of 0.1% of the non-filtered signal).
```python
# Power spectrum (Noisy signal)
freq_axis_noisy, power_spect_noisy = bsnb.plotfft(noisy_signal, sr)
# Power spectrum (Filtered signal)
freq_axis_filter, power_spect_filter = bsnb.plotfft(noisy_signal_filter, sr)
# Relative amplitude 1 decade after the 40 Hz cutoff frequency --> 400 Hz
# Taking into consideration that the search is sequential, so, only the
# first sample that meets the criterium is relevant.
index_decade = where(freq_axis_noisy >= 400)[0][0]
power_decade_noisy = power_spect_noisy[index_decade]
power_decade_filter = power_spect_filter[index_decade]
```
```python
from sty import fg, rs
print(fg(98,195,238) + "\033[1mRelative Amplitude/Power at 400 Hz frequency component [Noisy Signal]: \033[0m" + fg.rs + str(round(power_decade_noisy, 4)))
print(fg(148,193,30) + "\033[1mRelative Amplitude/Power at 400 Hz frequency component [Filtered Signal]: \033[0m" + fg.rs +
str(round(power_decade_filter, 4)))
print(fg(232,77,14) + "\033[1m\nRatio between filtered and noisy 400 Hz component [Attenuation]: \033[0m" + fg.rs +
str(round(power_decade_filter/power_decade_noisy, 4)) + " ~ " + str(round(power_decade_filter/power_decade_noisy, 3)) + " = 0.1 %")
```
Taking into consideration the previous demonstration, we can understand that the designed filter presents the desired behavior !
Unfortunately <a href="https://en.wikipedia.org/wiki/Noise_(signal_processing)">noise </a> is everywhere and even physiological data can be classified as noise if we are studying signals with another nature, as a practical example, electromyographic (EMG) data will be noise when doing an electrocardiographic (ECG) acquisition.
But, as demonstrated before, we can face this obstacle with efficient solutions, using analogical (pre-acquisition) or digital (post-acquisition) filters. With this brief tutorial, it can be understood the basic functioning principle of digital filters and how the user should proceed to "design" a widely used <a href="https://en.wikipedia.org/wiki/Butterworth_filter">Butterworth </a> filtering system.
<strong><span class="color7">We hope that you have enjoyed this guide. </span><span class="color2">biosignalsnotebooks</span><span class="color4"> is an environment in continuous expansion, so don't stop your journey and learn more with the remaining <a href="../MainFiles/biosignalsnotebooks.ipynb">Notebooks </a></span></strong> !
<span class="color6">**Auxiliary Code Segment (should not be replicated by the user)**</span>
```python
from biosignalsnotebooks.__notebook_support__ import css_style_apply
css_style_apply()
```
```python
%%html
```
|
#include "get_floor_fHf.h"
#include "ransac_floor_fHf.h"
#include "ransac_data.h"
#include "randperm.h"
#include <Eigen/Geometry>
#include <vector>
using namespace Eigen;
RansacData ransac_floor_fHf(MatrixXd &p1, MatrixXd &p2, Matrix3d &R1, Matrix3d &R2, int nbr_iter, double thresh)
{
// Init RANSAC loop
PoseData best_posedata;
int best_nbr_inliers = 0;
VectorXi best_inliers;
best_inliers.setZero();
int nbr_pts = p1.cols();
MatrixXd reproj1(2, nbr_pts);
MatrixXd reproj2(2, nbr_pts);
MatrixXd reproj(4, nbr_pts);
VectorXd reproj_mean(nbr_pts);
MatrixXd H(3,3);
VectorXi inliers(nbr_pts);
int nbr_inliers;
VectorXi history(nbr_iter);
int nbr_pts_minimal = 3;
for (int i = 0; i < nbr_iter; i++) {
std::vector<int> rands = randperm(nbr_pts_minimal, nbr_pts);
MatrixXd x1(3, nbr_pts_minimal);
MatrixXd x2(3, nbr_pts_minimal);
for (int j = 0; j < nbr_pts_minimal; j++) {
x1.col(j) << p1.col(rands[j]);
x2.col(j) << p2.col(rands[j]);
}
// Get pose
MatrixXd x1h(2,3);
MatrixXd x2h(2,3);
x1h << x1.colwise().hnormalized();
x2h << x2.colwise().hnormalized();
PoseData posedata = get_floor_fHf(x1h, x2h, R1, R2);
// Compute reprojection error, and compare to other solutions.
H = posedata.homography;
reproj1 = p2.colwise().hnormalized() - (H * p1).colwise().hnormalized();
reproj2 = p1.colwise().hnormalized() - (H.lu().solve(p2)).colwise().hnormalized();
reproj << reproj1.cwiseAbs(), reproj2.cwiseAbs();
reproj_mean = reproj.colwise().mean().array();
inliers = (reproj_mean.array() < thresh).cast<int>();
nbr_inliers = inliers.sum();
if (best_nbr_inliers < nbr_inliers) {
best_posedata = posedata;
best_nbr_inliers = nbr_inliers;
best_inliers = inliers;
}
history(i) = best_nbr_inliers;
}
RansacData ransac_data;
ransac_data.posedata = best_posedata;
ransac_data.inliers = best_inliers;
ransac_data.history = history;
return ransac_data;
}
// ---------------- //
// MATLAB interface //
// ---------------- //
#ifdef MATLAB_MEX_FILE
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if (nrhs != 6) {
mexErrMsgIdAndTxt("ransac_floor_fHf:nrhs", "Six input arguments are required.");
}
if (nlhs != 4) {
mexErrMsgIdAndTxt("ransac_floor_fHf:nlhs", "Four output arguments are required.");
}
if (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0])) {
mexErrMsgIdAndTxt("ransac_floor_fHf:notDouble", "Input data must be type double.");
}
if(mxGetNumberOfElements(prhs[0]) % 3 != 0
&& mxGetNumberOfElements(prhs[0]) != mxGetNumberOfElements(prhs[1])
&& mxGetNumberOfElements(prhs[2]) != 9 && mxGetNumberOfElements(prhs[3]) != 9
&& mxGetNumberOfElements(prhs[4]) != 1 && mxGetNumberOfElements(prhs[5]) != 1)
{
mexErrMsgIdAndTxt("ransac_floor_fHf:incorrectSize", "Input dimensions incorrect.");
}
// Convert to expected input
int nbr_pts = mxGetNumberOfElements(prhs[0]) / 3;
VectorXd x1_tmp = Map<VectorXd>(mxGetPr(prhs[0]), mxGetNumberOfElements(prhs[0]));
VectorXd x2_tmp = Map<VectorXd>(mxGetPr(prhs[1]), mxGetNumberOfElements(prhs[1]));
MatrixXd x1 = Map<MatrixXd>(x1_tmp.data(), 3, nbr_pts);
MatrixXd x2 = Map<MatrixXd>(x2_tmp.data(), 3, nbr_pts);
VectorXd R1_tmp = Map<VectorXd>(mxGetPr(prhs[2]), 9);
VectorXd R2_tmp = Map<VectorXd>(mxGetPr(prhs[3]), 9);
Matrix3d R1 = Map<Matrix3d>(R1_tmp.data(), 3, 3);
Matrix3d R2 = Map<Matrix3d>(R2_tmp.data(), 3, 3);
double *nbr_iter_p = mxGetPr(prhs[4]);
double *thresh = mxGetPr(prhs[5]);
int nbr_iter = (int) nbr_iter_p[0];
// Compute output
RansacData ransac_data = ransac_floor_fHf(x1, x2, R1, R2, nbr_iter, thresh[0]);
PoseData posedata = ransac_data.posedata;
// Wrap it up to Matlab compatible output
plhs[0] = mxCreateDoubleMatrix(3, 3, mxREAL);
double* zr = mxGetPr(plhs[0]);
for (Index i = 0; i < posedata.homography.size(); i++) {
zr[i] = posedata.homography(i);
}
plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL);
zr = mxGetPr(plhs[1]);
zr[0] = posedata.focal_length;
plhs[2] = mxCreateDoubleMatrix(nbr_pts, 1, mxREAL);
zr = mxGetPr(plhs[2]);
for (Index i = 0; i < nbr_pts; i++) {
zr[i] = ransac_data.inliers(i);
}
plhs[3] = mxCreateDoubleMatrix(nbr_iter, 1, mxREAL);
zr = mxGetPr(plhs[3]);
for (Index i = 0; i < nbr_iter; i++) {
zr[i] = ransac_data.history(i);
}
}
#endif
|
/-
Copyright (c) 2021 Aaron Anderson, Jesse Michael Han, Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson, Jesse Michael Han, Floris van Doorn
-/
import data.fin.vec_notation
import set_theory.cardinal.basic
/-!
# Basics on First-Order Structures
This file defines first-order languages and structures in the style of the
[Flypitch project](https://flypitch.github.io/), as well as several important maps between
structures.
## Main Definitions
* A `first_order.language` defines a language as a pair of functions from the natural numbers to
`Type l`. One sends `n` to the type of `n`-ary functions, and the other sends `n` to the type of
`n`-ary relations.
* A `first_order.language.Structure` interprets the symbols of a given `first_order.language` in the
context of a given type.
* A `first_order.language.hom`, denoted `M β[L] N`, is a map from the `L`-structure `M` to the
`L`-structure `N` that commutes with the interpretations of functions, and which preserves the
interpretations of relations (although only in the forward direction).
* A `first_order.language.embedding`, denoted `M βͺ[L] N`, is an embedding from the `L`-structure `M`
to the `L`-structure `N` that commutes with the interpretations of functions, and which preserves
the interpretations of relations in both directions.
* A `first_order.language.elementary_embedding`, denoted `M βͺβ[L] N`, is an embedding from the
`L`-structure `M` to the `L`-structure `N` that commutes with the realizations of all formulas.
* A `first_order.language.equiv`, denoted `M β[L] N`, is an equivalence from the `L`-structure `M`
to the `L`-structure `N` that commutes with the interpretations of functions, and which preserves
the interpretations of relations in both directions.
## TODO
Use `[countable L.symbols]` instead of `[L.countable]`.
## References
For the Flypitch project:
- [J. Han, F. van Doorn, *A formal proof of the independence of the continuum hypothesis*]
[flypitch_cpp]
- [J. Han, F. van Doorn, *A formalization of forcing and the unprovability of
the continuum hypothesis*][flypitch_itp]
-/
universes u v u' v' w w'
open_locale cardinal
open cardinal
namespace first_order
/-! ### Languages and Structures -/
/-- A first-order language consists of a type of functions of every natural-number arity and a
type of relations of every natural-number arity. -/
@[nolint check_univs] -- intended to be used with explicit universe parameters
structure language :=
(functions : β β Type u) (relations : β β Type v)
/-- Used to define `first_order.languageβ`. -/
@[simp] def sequenceβ (aβ aβ aβ : Type u) : β β Type u
| 0 := aβ
| 1 := aβ
| 2 := aβ
| _ := pempty
namespace sequenceβ
variables (aβ aβ aβ : Type u)
instance inhabitedβ [h : inhabited aβ] : inhabited (sequenceβ aβ aβ aβ 0) := h
instance inhabitedβ [h : inhabited aβ] : inhabited (sequenceβ aβ aβ aβ 1) := h
instance inhabitedβ [h : inhabited aβ] : inhabited (sequenceβ aβ aβ aβ 2) := h
instance {n : β} : is_empty (sequenceβ aβ aβ aβ (n + 3)) := pempty.is_empty
@[simp] lemma lift_mk {i : β} :
cardinal.lift (# (sequenceβ aβ aβ aβ i)) = # (sequenceβ (ulift aβ) (ulift aβ) (ulift aβ) i) :=
begin
rcases i with (_ | _ | _ | i);
simp only [sequenceβ, mk_ulift, mk_fintype, fintype.card_of_is_empty, nat.cast_zero, lift_zero],
end
@[simp] lemma sum_card :
cardinal.sum (Ξ» i, # (sequenceβ aβ aβ aβ i)) = # aβ + # aβ + # aβ :=
begin
rw [sum_nat_eq_add_sum_succ, sum_nat_eq_add_sum_succ, sum_nat_eq_add_sum_succ],
simp [add_assoc],
end
end sequenceβ
namespace language
/-- A constructor for languages with only constants, unary and binary functions, and
unary and binary relations. -/
@[simps] protected def mkβ (c fβ fβ : Type u) (rβ rβ : Type v) : language :=
β¨sequenceβ c fβ fβ, sequenceβ pempty rβ rββ©
/-- The empty language has no symbols. -/
protected def empty : language := β¨Ξ» _, empty, Ξ» _, emptyβ©
instance : inhabited language := β¨language.emptyβ©
/-- The sum of two languages consists of the disjoint union of their symbols. -/
protected def sum (L : language.{u v}) (L' : language.{u' v'}) : language :=
β¨Ξ»n, L.functions n β L'.functions n, Ξ» n, L.relations n β L'.relations nβ©
variable (L : language.{u v})
/-- The type of constants in a given language. -/
@[nolint has_nonempty_instance] protected def Β«constantsΒ» := L.functions 0
@[simp] lemma constants_mkβ (c fβ fβ : Type u) (rβ rβ : Type v) :
(language.mkβ c fβ fβ rβ rβ).constants = c :=
rfl
/-- The type of symbols in a given language. -/
@[nolint has_nonempty_instance] def symbols := (Ξ£l, L.functions l) β (Ξ£l, L.relations l)
/-- The cardinality of a language is the cardinality of its type of symbols. -/
def card : cardinal := # L.symbols
/-- A language is relational when it has no function symbols. -/
class is_relational : Prop :=
(empty_functions : β n, is_empty (L.functions n))
/-- A language is algebraic when it has no relation symbols. -/
class is_algebraic : Prop :=
(empty_relations : β n, is_empty (L.relations n))
variables {L} {L' : language.{u' v'}}
lemma card_eq_card_functions_add_card_relations :
L.card = cardinal.sum (Ξ» l, (cardinal.lift.{v} (#(L.functions l)))) +
cardinal.sum (Ξ» l, cardinal.lift.{u} (#(L.relations l))) :=
by simp [card, symbols]
instance [L.is_relational] {n : β} : is_empty (L.functions n) := is_relational.empty_functions n
instance [L.is_algebraic] {n : β} : is_empty (L.relations n) := is_algebraic.empty_relations n
instance is_relational_of_empty_functions {symb : β β Type*} : is_relational β¨Ξ» _, empty, symbβ© :=
β¨Ξ» _, empty.is_emptyβ©
instance is_algebraic_of_empty_relations {symb : β β Type*} : is_algebraic β¨symb, Ξ» _, emptyβ© :=
β¨Ξ» _, empty.is_emptyβ©
instance is_relational_empty : is_relational language.empty :=
language.is_relational_of_empty_functions
instance is_algebraic_empty : is_algebraic language.empty :=
language.is_algebraic_of_empty_relations
instance is_relational_sum [L.is_relational] [L'.is_relational] : is_relational (L.sum L') :=
β¨Ξ» n, sum.is_emptyβ©
instance is_algebraic_sum [L.is_algebraic] [L'.is_algebraic] : is_algebraic (L.sum L') :=
β¨Ξ» n, sum.is_emptyβ©
instance is_relational_mkβ {c fβ fβ : Type u} {rβ rβ : Type v}
[h0 : is_empty c] [h1 : is_empty fβ] [h2 : is_empty fβ] :
is_relational (language.mkβ c fβ fβ rβ rβ) :=
β¨Ξ» n, nat.cases_on n h0 (Ξ» n, nat.cases_on n h1 (Ξ» n, nat.cases_on n h2 (Ξ» _, pempty.is_empty)))β©
instance is_algebraic_mkβ {c fβ fβ : Type u} {rβ rβ : Type v}
[h1 : is_empty rβ] [h2 : is_empty rβ] :
is_algebraic (language.mkβ c fβ fβ rβ rβ) :=
β¨Ξ» n, nat.cases_on n pempty.is_empty
(Ξ» n, nat.cases_on n h1 (Ξ» n, nat.cases_on n h2 (Ξ» _, pempty.is_empty)))β©
instance subsingleton_mkβ_functions {c fβ fβ : Type u} {rβ rβ : Type v}
[h0 : subsingleton c] [h1 : subsingleton fβ] [h2 : subsingleton fβ] {n : β} :
subsingleton ((language.mkβ c fβ fβ rβ rβ).functions n) :=
nat.cases_on n h0 (Ξ» n, nat.cases_on n h1 (Ξ» n, nat.cases_on n h2 (Ξ» n, β¨Ξ» x, pempty.elim xβ©)))
instance subsingleton_mkβ_relations {c fβ fβ : Type u} {rβ rβ : Type v}
[h1 : subsingleton rβ] [h2 : subsingleton rβ] {n : β} :
subsingleton ((language.mkβ c fβ fβ rβ rβ).relations n) :=
nat.cases_on n β¨Ξ» x, pempty.elim xβ©
(Ξ» n, nat.cases_on n h1 (Ξ» n, nat.cases_on n h2 (Ξ» n, β¨Ξ» x, pempty.elim xβ©)))
@[simp] lemma empty_card : language.empty.card = 0 :=
by simp [card_eq_card_functions_add_card_relations]
instance is_empty_empty : is_empty language.empty.symbols :=
begin
simp only [language.symbols, is_empty_sum, is_empty_sigma],
exact β¨Ξ» _, infer_instance, Ξ» _, infer_instanceβ©,
end
instance countable.countable_functions [h : countable L.symbols] :
countable (Ξ£l, L.functions l) :=
@function.injective.countable _ _ h _ sum.inl_injective
@[simp] lemma card_functions_sum (i : β) :
#((L.sum L').functions i) = (#(L.functions i)).lift + cardinal.lift.{u} (#(L'.functions i)) :=
by simp [language.sum]
@[simp] lemma card_relations_sum (i : β) :
#((L.sum L').relations i) = (#(L.relations i)).lift + cardinal.lift.{v} (#(L'.relations i)) :=
by simp [language.sum]
@[simp] lemma card_sum :
(L.sum L').card = cardinal.lift.{max u' v'} L.card + cardinal.lift.{max u v} L'.card :=
begin
simp only [card_eq_card_functions_add_card_relations, card_functions_sum, card_relations_sum,
sum_add_distrib', lift_add, lift_sum, lift_lift],
rw [add_assoc, βadd_assoc (cardinal.sum (Ξ» i, (# (L'.functions i)).lift)),
add_comm (cardinal.sum (Ξ» i, (# (L'.functions i)).lift)), add_assoc, add_assoc]
end
@[simp] lemma card_mkβ (c fβ fβ : Type u) (rβ rβ : Type v) :
(language.mkβ c fβ fβ rβ rβ).card =
cardinal.lift.{v} (# c) + cardinal.lift.{v} (# fβ) + cardinal.lift.{v} (# fβ)
+ cardinal.lift.{u} (# rβ) + cardinal.lift.{u} (# rβ) :=
by simp [card_eq_card_functions_add_card_relations, add_assoc]
variables (L) (M : Type w)
/-- A first-order structure on a type `M` consists of interpretations of all the symbols in a given
language. Each function of arity `n` is interpreted as a function sending tuples of length `n`
(modeled as `(fin n β M)`) to `M`, and a relation of arity `n` is a function from tuples of length
`n` to `Prop`. -/
@[ext] class Structure :=
(fun_map : β{n}, L.functions n β (fin n β M) β M)
(rel_map : β{n}, L.relations n β (fin n β M) β Prop)
variables (N : Type w') [L.Structure M] [L.Structure N]
open Structure
/-- Used for defining `first_order.language.Theory.Model.inhabited`. -/
def inhabited.trivial_structure {Ξ± : Type*} [inhabited Ξ±] : L.Structure Ξ± := β¨default, defaultβ©
/-! ### Maps -/
/-- A homomorphism between first-order structures is a function that commutes with the
interpretations of functions and maps tuples in one structure where a given relation is true to
tuples in the second structure where that relation is still true. -/
structure hom :=
(to_fun : M β N)
(map_fun' : β{n} (f : L.functions n) x, to_fun (fun_map f x) = fun_map f (to_fun β x) . obviously)
(map_rel' : β{n} (r : L.relations n) x, rel_map r x β rel_map r (to_fun β x) . obviously)
localized "notation (name := language.hom) A ` β[`:25 L `] ` B :=
first_order.language.hom L A B" in first_order
/-- An embedding of first-order structures is an embedding that commutes with the
interpretations of functions and relations. -/
@[ancestor function.embedding] structure embedding extends M βͺ N :=
(map_fun' : β{n} (f : L.functions n) x, to_fun (fun_map f x) = fun_map f (to_fun β x) . obviously)
(map_rel' : β{n} (r : L.relations n) x, rel_map r (to_fun β x) β rel_map r x . obviously)
localized "notation (name := language.embedding) A ` βͺ[`:25 L `] ` B :=
first_order.language.embedding L A B" in first_order
/-- An equivalence of first-order structures is an equivalence that commutes with the
interpretations of functions and relations. -/
structure equiv extends M β N :=
(map_fun' : β{n} (f : L.functions n) x, to_fun (fun_map f x) = fun_map f (to_fun β x) . obviously)
(map_rel' : β{n} (r : L.relations n) x, rel_map r (to_fun β x) β rel_map r x . obviously)
localized "notation (name := language.equiv) A ` β[`:25 L `] ` B :=
first_order.language.equiv L A B" in first_order
variables {L M N} {P : Type*} [L.Structure P] {Q : Type*} [L.Structure Q]
instance : has_coe_t L.constants M :=
β¨Ξ» c, fun_map c defaultβ©
lemma fun_map_eq_coe_constants {c : L.constants} {x : fin 0 β M} :
fun_map c x = c := congr rfl (funext fin.elim0)
/-- Given a language with a nonempty type of constants, any structure will be nonempty. This cannot
be a global instance, because `L` becomes a metavariable. -/
lemma nonempty_of_nonempty_constants [h : nonempty L.constants] : nonempty M :=
h.map coe
/-- The function map for `first_order.language.Structureβ`. -/
def fun_mapβ {c fβ fβ : Type u} {rβ rβ : Type v}
(c' : c β M) (fβ' : fβ β M β M) (fβ' : fβ β M β M β M) :
β{n}, (language.mkβ c fβ fβ rβ rβ).functions n β (fin n β M) β M
| 0 f _ := c' f
| 1 f x := fβ' f (x 0)
| 2 f x := fβ' f (x 0) (x 1)
| (n + 3) f _ := pempty.elim f
/-- The relation map for `first_order.language.Structureβ`. -/
def rel_mapβ {c fβ fβ : Type u} {rβ rβ : Type v}
(rβ' : rβ β set M) (rβ' : rβ β M β M β Prop) :
β{n}, (language.mkβ c fβ fβ rβ rβ).relations n β (fin n β M) β Prop
| 0 r _ := pempty.elim r
| 1 r x := (x 0) β rβ' r
| 2 r x := rβ' r (x 0) (x 1)
| (n + 3) r _ := pempty.elim r
/-- A structure constructor to match `first_order.languageβ`. -/
protected def Structure.mkβ {c fβ fβ : Type u} {rβ rβ : Type v}
(c' : c β M) (fβ' : fβ β M β M) (fβ' : fβ β M β M β M)
(rβ' : rβ β set M) (rβ' : rβ β M β M β Prop) :
(language.mkβ c fβ fβ rβ rβ).Structure M :=
β¨Ξ» _, fun_mapβ c' fβ' fβ', Ξ» _, rel_mapβ rβ' rβ'β©
namespace Structure
variables {c fβ fβ : Type u} {rβ rβ : Type v}
variables {c' : c β M} {fβ' : fβ β M β M} {fβ' : fβ β M β M β M}
variables {rβ' : rβ β set M} {rβ' : rβ β M β M β Prop}
@[simp] lemma fun_map_applyβ (cβ : c) {x : fin 0 β M} :
@Structure.fun_map _ M (Structure.mkβ c' fβ' fβ' rβ' rβ') 0 cβ x = c' cβ := rfl
@[simp] lemma fun_map_applyβ (f : fβ) (x : M) :
@Structure.fun_map _ M (Structure.mkβ c' fβ' fβ' rβ' rβ') 1 f (![x]) = fβ' f x := rfl
@[simp] lemma fun_map_applyβ (f : fβ) (x y : M) :
@Structure.fun_map _ M (Structure.mkβ c' fβ' fβ' rβ' rβ') 2 f (![x,y]) = fβ' f x y := rfl
@[simp] lemma rel_map_applyβ (r : rβ) (x : M) :
@Structure.rel_map _ M (Structure.mkβ c' fβ' fβ' rβ' rβ') 1 r (![x]) = (x β rβ' r) := rfl
@[simp]
end Structure
/-- `hom_class L F M N` states that `F` is a type of `L`-homomorphisms. You should extend this
typeclass when you extend `first_order.language.hom`. -/
class hom_class (L : out_param language) (F : Type*)
(M N : out_param $ Type*) [fun_like F M (Ξ» _, N)] [L.Structure M] [L.Structure N] :=
(map_fun : β (Ο : F) {n} (f : L.functions n) x, Ο (fun_map f x) = fun_map f (Ο β x))
(map_rel : β (Ο : F) {n} (r : L.relations n) x, rel_map r x β rel_map r (Ο β x))
/-- `strong_hom_class L F M N` states that `F` is a type of `L`-homomorphisms which preserve
relations in both directions. -/
class strong_hom_class (L : out_param language) (F : Type*) (M N : out_param $ Type*)
[fun_like F M (Ξ» _, N)] [L.Structure M] [L.Structure N] :=
(map_fun : β (Ο : F) {n} (f : L.functions n) x, Ο (fun_map f x) = fun_map f (Ο β x))
(map_rel : β (Ο : F) {n} (r : L.relations n) x, rel_map r (Ο β x) β rel_map r x)
@[priority 100] instance strong_hom_class.hom_class
{F M N} [L.Structure M] [L.Structure N] [fun_like F M (Ξ» _, N)] [strong_hom_class L F M N] :
hom_class L F M N :=
{ map_fun := strong_hom_class.map_fun,
map_rel := Ξ» Ο n R x, (strong_hom_class.map_rel Ο R x).2 }
/-- Not an instance to avoid a loop. -/
def hom_class.strong_hom_class_of_is_algebraic [L.is_algebraic]
{F M N} [L.Structure M] [L.Structure N] [fun_like F M (Ξ» _, N)] [hom_class L F M N] :
strong_hom_class L F M N :=
{ map_fun := hom_class.map_fun,
map_rel := Ξ» Ο n R x, (is_algebraic.empty_relations n).elim R }
lemma hom_class.map_constants {F M N} [L.Structure M] [L.Structure N] [fun_like F M (Ξ» _, N)]
[hom_class L F M N]
(Ο : F) (c : L.constants) : Ο (c) = c :=
(hom_class.map_fun Ο c default).trans (congr rfl (funext default))
namespace hom
instance fun_like : fun_like (M β[L] N) M (Ξ» _, N) :=
{ coe := hom.to_fun,
coe_injective' := Ξ» f g h, by {cases f, cases g, cases h, refl} }
instance hom_class : hom_class L (M β[L] N) M N :=
{ map_fun := map_fun',
map_rel := map_rel' }
instance [L.is_algebraic] : strong_hom_class L (M β[L] N) M N :=
hom_class.strong_hom_class_of_is_algebraic
instance has_coe_to_fun : has_coe_to_fun (M β[L] N) (Ξ» _, M β N) := fun_like.has_coe_to_fun
@[simp] lemma to_fun_eq_coe {f : M β[L] N} : f.to_fun = (f : M β N) := rfl
@[ext]
lemma ext β¦f g : M β[L] Nβ¦ (h : β x, f x = g x) : f = g :=
fun_like.ext f g h
lemma ext_iff {f g : M β[L] N} : f = g β β x, f x = g x :=
fun_like.ext_iff
@[simp] lemma map_fun (Ο : M β[L] N) {n : β} (f : L.functions n) (x : fin n β M) :
Ο (fun_map f x) = fun_map f (Ο β x) :=
hom_class.map_fun Ο f x
@[simp] lemma map_constants (Ο : M β[L] N) (c : L.constants) : Ο c = c :=
hom_class.map_constants Ο c
@[simp] lemma map_rel (Ο : M β[L] N) {n : β} (r : L.relations n) (x : fin n β M) :
rel_map r x β rel_map r (Ο β x) :=
hom_class.map_rel Ο r x
variables (L) (M)
/-- The identity map from a structure to itself -/
@[refl] def id : M β[L] M :=
{ to_fun := id }
variables {L} {M}
instance : inhabited (M β[L] M) := β¨id L Mβ©
@[simp] lemma id_apply (x : M) :
id L M x = x := rfl
/-- Composition of first-order homomorphisms -/
@[trans] def comp (hnp : N β[L] P) (hmn : M β[L] N) : M β[L] P :=
{ to_fun := hnp β hmn,
map_rel' := Ξ» _ _ _ h, by simp [h] }
@[simp] lemma comp_apply (g : N β[L] P) (f : M β[L] N) (x : M) :
g.comp f x = g (f x) := rfl
/-- Composition of first-order homomorphisms is associative. -/
lemma comp_assoc (f : M β[L] N) (g : N β[L] P) (h : P β[L] Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
end hom
/-- Any element of a `hom_class` can be realized as a first_order homomorphism. -/
def hom_class.to_hom {F M N} [L.Structure M] [L.Structure N]
[fun_like F M (Ξ» _, N)] [hom_class L F M N] :
F β (M β[L] N) :=
Ξ» Ο, β¨Ο, Ξ» _, hom_class.map_fun Ο, Ξ» _, hom_class.map_rel Οβ©
namespace embedding
instance embedding_like : embedding_like (M βͺ[L] N) M N :=
{ coe := Ξ» f, f.to_fun,
injective' := Ξ» f, f.to_embedding.injective,
coe_injective' := Ξ» f g h, begin
cases f,
cases g,
simp only,
ext x,
exact function.funext_iff.1 h x end }
instance strong_hom_class : strong_hom_class L (M βͺ[L] N) M N :=
{ map_fun := map_fun',
map_rel := map_rel' }
instance has_coe_to_fun : has_coe_to_fun (M βͺ[L] N) (Ξ» _, M β N) :=
fun_like.has_coe_to_fun
@[simp] lemma map_fun (Ο : M βͺ[L] N) {n : β} (f : L.functions n) (x : fin n β M) :
Ο (fun_map f x) = fun_map f (Ο β x) :=
hom_class.map_fun Ο f x
@[simp] lemma map_constants (Ο : M βͺ[L] N) (c : L.constants) : Ο c = c :=
hom_class.map_constants Ο c
@[simp] lemma map_rel (Ο : M βͺ[L] N) {n : β} (r : L.relations n) (x : fin n β M) :
rel_map r (Ο β x) β rel_map r x :=
strong_hom_class.map_rel Ο r x
/-- A first-order embedding is also a first-order homomorphism. -/
def to_hom : (M βͺ[L] N) β M β[L] N := hom_class.to_hom
@[simp]
lemma coe_to_hom {f : M βͺ[L] N} : (f.to_hom : M β N) = f := rfl
lemma coe_injective : @function.injective (M βͺ[L] N) (M β N) coe_fn
| f g h :=
begin
cases f,
cases g,
simp only,
ext x,
exact function.funext_iff.1 h x,
end
@[ext]
lemma ext β¦f g : M βͺ[L] Nβ¦ (h : β x, f x = g x) : f = g :=
coe_injective (funext h)
lemma ext_iff {f g : M βͺ[L] N} : f = g β β x, f x = g x :=
β¨Ξ» h x, h βΈ rfl, Ξ» h, ext hβ©
lemma injective (f : M βͺ[L] N) : function.injective f := f.to_embedding.injective
/-- In an algebraic language, any injective homomorphism is an embedding. -/
@[simps] def of_injective [L.is_algebraic] {f : M β[L] N} (hf : function.injective f) : M βͺ[L] N :=
{ inj' := hf,
map_rel' := Ξ» n r x, strong_hom_class.map_rel f r x,
.. f }
@[simp] lemma coe_fn_of_injective [L.is_algebraic] {f : M β[L] N} (hf : function.injective f) :
(of_injective hf : M β N) = f := rfl
@[simp] lemma of_injective_to_hom [L.is_algebraic] {f : M β[L] N} (hf : function.injective f) :
(of_injective hf).to_hom = f :=
by { ext, simp }
variables (L) (M)
/-- The identity embedding from a structure to itself -/
@[refl] def refl : M βͺ[L] M :=
{ to_embedding := function.embedding.refl M }
variables {L} {M}
instance : inhabited (M βͺ[L] M) := β¨refl L Mβ©
@[simp] lemma refl_apply (x : M) :
refl L M x = x := rfl
/-- Composition of first-order embeddings -/
@[trans] def comp (hnp : N βͺ[L] P) (hmn : M βͺ[L] N) : M βͺ[L] P :=
{ to_fun := hnp β hmn,
inj' := hnp.injective.comp hmn.injective }
@[simp] lemma comp_apply (g : N βͺ[L] P) (f : M βͺ[L] N) (x : M) :
g.comp f x = g (f x) := rfl
/-- Composition of first-order embeddings is associative. -/
lemma comp_assoc (f : M βͺ[L] N) (g : N βͺ[L] P) (h : P βͺ[L] Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
@[simp] lemma comp_to_hom (hnp : N βͺ[L] P) (hmn : M βͺ[L] N) :
(hnp.comp hmn).to_hom = hnp.to_hom.comp hmn.to_hom :=
by { ext, simp only [coe_to_hom, comp_apply, hom.comp_apply] }
end embedding
/-- Any element of an injective `strong_hom_class` can be realized as a first_order embedding. -/
def strong_hom_class.to_embedding {F M N} [L.Structure M] [L.Structure N]
[embedding_like F M N] [strong_hom_class L F M N] :
F β (M βͺ[L] N) :=
Ξ» Ο, β¨β¨Ο, embedding_like.injective Οβ©,
Ξ» _, strong_hom_class.map_fun Ο, Ξ» _, strong_hom_class.map_rel Οβ©
namespace equiv
instance : equiv_like (M β[L] N) M N :=
{ coe := Ξ» f, f.to_fun,
inv := Ξ» f, f.inv_fun,
left_inv := Ξ» f, f.left_inv,
right_inv := Ξ» f, f.right_inv,
coe_injective' := Ξ» f g hβ hβ, begin
cases f,
cases g,
simp only,
ext x,
exact function.funext_iff.1 hβ x,
end, }
instance : strong_hom_class L (M β[L] N) M N :=
{ map_fun := map_fun',
map_rel := map_rel', }
/-- The inverse of a first-order equivalence is a first-order equivalence. -/
@[symm] def symm (f : M β[L] N) : N β[L] M :=
{ map_fun' := Ξ» n f' x, begin
simp only [equiv.to_fun_as_coe],
rw [equiv.symm_apply_eq],
refine eq.trans _ (f.map_fun' f' (f.to_equiv.symm β x)).symm,
rw [β function.comp.assoc, equiv.to_fun_as_coe, equiv.self_comp_symm, function.comp.left_id]
end,
map_rel' := Ξ» n r x, begin
simp only [equiv.to_fun_as_coe],
refine (f.map_rel' r (f.to_equiv.symm β x)).symm.trans _,
rw [β function.comp.assoc, equiv.to_fun_as_coe, equiv.self_comp_symm, function.comp.left_id]
end,
.. f.to_equiv.symm }
instance has_coe_to_fun : has_coe_to_fun (M β[L] N) (Ξ» _, M β N) :=
fun_like.has_coe_to_fun
@[simp]
lemma apply_symm_apply (f : M β[L] N) (a : N) : f (f.symm a) = a := f.to_equiv.apply_symm_apply a
@[simp]
lemma symm_apply_apply (f : M β[L] N) (a : M) : f.symm (f a) = a := f.to_equiv.symm_apply_apply a
@[simp] lemma map_fun (Ο : M β[L] N) {n : β} (f : L.functions n) (x : fin n β M) :
Ο (fun_map f x) = fun_map f (Ο β x) :=
hom_class.map_fun Ο f x
@[simp] lemma map_constants (Ο : M β[L] N) (c : L.constants) : Ο c = c :=
hom_class.map_constants Ο c
@[simp] lemma map_rel (Ο : M β[L] N) {n : β} (r : L.relations n) (x : fin n β M) :
rel_map r (Ο β x) β rel_map r x :=
strong_hom_class.map_rel Ο r x
/-- A first-order equivalence is also a first-order embedding. -/
def to_embedding : (M β[L] N) β M βͺ[L] N := strong_hom_class.to_embedding
/-- A first-order equivalence is also a first-order homomorphism. -/
def to_hom : (M β[L] N) β M β[L] N := hom_class.to_hom
@[simp] lemma to_embedding_to_hom (f : M β[L] N) : f.to_embedding.to_hom = f.to_hom := rfl
@[simp]
lemma coe_to_hom {f : M β[L] N} : (f.to_hom : M β N) = (f : M β N) := rfl
@[simp] lemma coe_to_embedding (f : M β[L] N) : (f.to_embedding : M β N) = (f : M β N) := rfl
lemma coe_injective : @function.injective (M β[L] N) (M β N) coe_fn :=
fun_like.coe_injective
@[ext]
lemma ext β¦f g : M β[L] Nβ¦ (h : β x, f x = g x) : f = g :=
coe_injective (funext h)
lemma ext_iff {f g : M β[L] N} : f = g β β x, f x = g x :=
β¨Ξ» h x, h βΈ rfl, Ξ» h, ext hβ©
lemma bijective (f : M β[L] N) : function.bijective f := equiv_like.bijective f
lemma injective (f : M β[L] N) : function.injective f := equiv_like.injective f
lemma surjective (f : M β[L] N) : function.surjective f := equiv_like.surjective f
variables (L) (M)
/-- The identity equivalence from a structure to itself -/
@[refl] def refl : M β[L] M :=
{ to_equiv := equiv.refl M }
variables {L} {M}
instance : inhabited (M β[L] M) := β¨refl L Mβ©
@[simp] lemma refl_apply (x : M) :
refl L M x = x := rfl
/-- Composition of first-order equivalences -/
@[trans] def comp (hnp : N β[L] P) (hmn : M β[L] N) : M β[L] P :=
{ to_fun := hnp β hmn,
.. (hmn.to_equiv.trans hnp.to_equiv) }
@[simp] lemma comp_apply (g : N β[L] P) (f : M β[L] N) (x : M) :
g.comp f x = g (f x) := rfl
/-- Composition of first-order homomorphisms is associative. -/
lemma comp_assoc (f : M β[L] N) (g : N β[L] P) (h : P β[L] Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
end equiv
/-- Any element of a bijective `strong_hom_class` can be realized as a first_order isomorphism. -/
def strong_hom_class.to_equiv {F M N} [L.Structure M] [L.Structure N]
[equiv_like F M N] [strong_hom_class L F M N] :
F β (M β[L] N) :=
Ξ» Ο, β¨β¨Ο, equiv_like.inv Ο, equiv_like.left_inv Ο, equiv_like.right_inv Οβ©,
Ξ» _, hom_class.map_fun Ο, Ξ» _, strong_hom_class.map_rel Οβ©
section sum_Structure
variables (Lβ Lβ : language) (S : Type*) [Lβ.Structure S] [Lβ.Structure S]
instance sum_Structure :
(Lβ.sum Lβ).Structure S :=
{ fun_map := Ξ» n, sum.elim fun_map fun_map,
rel_map := Ξ» n, sum.elim rel_map rel_map, }
variables {Lβ Lβ S}
@[simp] lemma fun_map_sum_inl {n : β} (f : Lβ.functions n) :
@fun_map (Lβ.sum Lβ) S _ n (sum.inl f) = fun_map f := rfl
@[simp] lemma fun_map_sum_inr {n : β} (f : Lβ.functions n) :
@fun_map (Lβ.sum Lβ) S _ n (sum.inr f) = fun_map f := rfl
@[simp] lemma rel_map_sum_inl {n : β} (R : Lβ.relations n) :
@rel_map (Lβ.sum Lβ) S _ n (sum.inl R) = rel_map R := rfl
@[simp] lemma rel_map_sum_inr {n : β} (R : Lβ.relations n) :
@rel_map (Lβ.sum Lβ) S _ n (sum.inr R) = rel_map R := rfl
end sum_Structure
section empty
section
variables [language.empty.Structure M] [language.empty.Structure N]
@[simp] lemma empty.nonempty_embedding_iff :
nonempty (M βͺ[language.empty] N) β cardinal.lift.{w'} (# M) β€ cardinal.lift.{w} (# N) :=
trans β¨nonempty.map (Ξ» f, f.to_embedding), nonempty.map (Ξ» f, {to_embedding := f})β©
cardinal.lift_mk_le'.symm
@[simp] lemma empty.nonempty_equiv_iff :
nonempty (M β[language.empty] N) β cardinal.lift.{w'} (# M) = cardinal.lift.{w} (# N) :=
trans β¨nonempty.map (Ξ» f, f.to_equiv), nonempty.map (Ξ» f, {to_equiv := f})β©
cardinal.lift_mk_eq'.symm
end
instance empty_Structure : language.empty.Structure M :=
β¨Ξ» _, empty.elim, Ξ» _, empty.elimβ©
instance : unique (language.empty.Structure M) :=
β¨β¨language.empty_Structureβ©, Ξ» a, begin
ext n f,
{ exact empty.elim f },
{ exact subsingleton.elim _ _ },
endβ©
@[priority 100] instance strong_hom_class_empty {F M N} [fun_like F M (Ξ» _, N)] :
strong_hom_class language.empty F M N :=
β¨Ξ» _ _ f, empty.elim f, Ξ» _ _ r, empty.elim rβ©
/-- Makes a `language.empty.hom` out of any function. -/
@[simps] def _root_.function.empty_hom (f : M β N) : (M β[language.empty] N) :=
{ to_fun := f }
/-- Makes a `language.empty.embedding` out of any function. -/
@[simps] def _root_.embedding.empty (f : M βͺ N) : (M βͺ[language.empty] N) :=
{ to_embedding := f }
/-- Makes a `language.empty.equiv` out of any function. -/
@[simps] def _root_.equiv.empty (f : M β N) : (M β[language.empty] N) :=
{ to_equiv := f }
end empty
end language
end first_order
namespace equiv
open first_order first_order.language first_order.language.Structure
open_locale first_order
variables {L : language} {M : Type*} {N : Type*} [L.Structure M]
/-- A structure induced by a bijection. -/
@[simps] def induced_Structure (e : M β N) : L.Structure N :=
β¨Ξ» n f x, e (fun_map f (e.symm β x)), Ξ» n r x, rel_map r (e.symm β x)β©
/-- A bijection as a first-order isomorphism with the induced structure on the codomain. -/
@[simps] def induced_Structure_equiv (e : M β N) :
@language.equiv L M N _ (induced_Structure e) :=
{ map_fun' := Ξ» n f x, by simp [β function.comp.assoc e.symm e x],
map_rel' := Ξ» n r x, by simp [β function.comp.assoc e.symm e x],
.. e }
end equiv
|
r=359.92
https://sandbox.dams.library.ucdavis.edu/fcrepo/rest/collection/sherry-lehmann/catalogs/d7vp48/media/images/d7vp48-010/svc:tesseract/full/full/359.92/default.jpg Accept:application/hocr+xml
|
import data.set.function
open set
variables Ξ± Ξ² : Type
variables A :set Ξ±
variables B :set Ξ²
variable f:Ξ± β Ξ²
variable g:Ξ² β Ξ±
theorem Schroder_Bernstein:
inj_on f A β§ inj_on g B β§ maps_to f A B β§ maps_to g B A β β h:Ξ± β Ξ², bij_on h A B
:=
sorry
|
PROGRAM F024
! Copyright 2021 Melwyn Francis Carlo
IMPLICIT NONE
INTEGER, PARAMETER :: N_MAX = 10
INTEGER, PARAMETER :: I = 1000000
CHARACTER (LEN=1), DIMENSION(N_MAX) :: NUMBERS = &
(/ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" /)
INTEGER :: N = N_MAX
INTEGER (KIND=8) :: N_PRODUCT = N_MAX
INTEGER (KIND=8) :: MAX_PERMUTATION = 1
CHARACTER (LEN=N_MAX) :: DIGITS_VAL
INTEGER :: J, INDEX_VAL
DO J = 2, N_MAX
MAX_PERMUTATION = MAX_PERMUTATION * J
END DO
INDEX_VAL = FLOOR(REAL((I - 1) * N_PRODUCT) / REAL(MAX_PERMUTATION)) + 1
DIGITS_VAL(1:1) = NUMBERS(INDEX_VAL)
DO J = 2, N_MAX
N = N - 1
N_PRODUCT = N_PRODUCT * N
IF (INDEX_VAL < (N_MAX - 1)) NUMBERS(INDEX_VAL:N_MAX) = EOSHIFT( &
NUMBERS(INDEX_VAL:N_MAX), 1, "0")
INDEX_VAL = MOD(FLOOR(REAL((I - 1) * N_PRODUCT) &
/ REAL(MAX_PERMUTATION)), N) + 1
DIGITS_VAL(J:J) = NUMBERS(INDEX_VAL)
END DO
PRINT ('(A)'), DIGITS_VAL
END PROGRAM F024
|
#ifndef TFDH_GSL_WRAPPERS_H
#define TFDH_GSL_WRAPPERS_H
#include <gsl/gsl_spline.h>
#include <vector>
namespace GSL {
// simple functor class to help interfacing with gsl_function.
// derived classes representing a function f(x) should hold any needed
// parameters as member variables, and operator()(double x) should evaluate
// the function f(x).
//
// NOTE: the GSL wrappers below could in principle take C++11 lambdas instead
// of this custom function object, however i did not find an elegant
// way to call these lambdas using GSL's C interfaces...
class FunctionObject {
public:
virtual ~FunctionObject() = default;
virtual double operator()(double x) const = 0;
};
// simple wrapper class around GSL splines
class Spline {
private:
gsl_interp_accel* acc;
gsl_spline* spline;
public:
Spline(const std::vector<double>& x, const std::vector<double>& f);
~Spline();
double eval(double r) const;
};
// find a root of func in the interval x1 to x2
// one of (x1,x2) or (x2,x1) MUST bracket a root
// implemented using GSL's Brent rootfinder method
double findRoot(const GSL::FunctionObject& func, double x1, double x2,
double eps_abs, double eps_rel);
// definite integral of func from x1 to x2
// implemented using GSL's adaptive Gauss quadrature
double integrate(const GSL::FunctionObject& func, double x1, double x2,
double eps_abs, double eps_rel);
}
#endif // TFDH_GSL_WRAPPERS_H
|
[STATEMENT]
lemma vec_contains_count_gt1_iff: "a \<in>$ v \<longleftrightarrow> count_vec v a \<ge> 1"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (a \<in>$ v) = (1 \<le> count_vec v a)
[PROOF STEP]
by (simp add: vec_set_mset_contains_iff)
|
//===------------------------------------------------------------*- C++ -*-===//
//
// This file is distributed under MIT License. See LICENSE.txt for details.
//
//===----------------------------------------------------------------------===//
//
// Copyright (c) 2017 University of Kaiserslautern.
//
#pragma once
#include <nlopt.h>
namespace gosat {
class OptConfig {
public:
OptConfig();
OptConfig(nlopt_algorithm global_alg, nlopt_algorithm local_alg);
virtual ~OptConfig() = default;
int MaxEvalCount;
int MaxLocalEvalCount;
double RelTolerance;
double Bound;
double StepSize;
unsigned InitialPopulation;
};
class NLoptOptimizer {
public:
NLoptOptimizer();
NLoptOptimizer(nlopt_algorithm global_alg,
nlopt_algorithm local_alg = NLOPT_LN_BOBYQA);
virtual ~NLoptOptimizer() = default;
int optimize
(nlopt_func func, unsigned dim, double* x,
double* min) const noexcept;
double eval
(nlopt_func func, unsigned dim, const double* x) const noexcept;
bool existsRoundingError
(nlopt_func func,
unsigned int dim,
const double* x,
const double* min) const noexcept;
void fixRoundingErrorNearZero
(nlopt_func const func,
unsigned dim,
double* x,
double* min) const noexcept;
int refineResult(nlopt_func func, unsigned dim, double* x, double* min);
static bool isSupportedGlobalOptAlg(nlopt_algorithm opt_alg) noexcept;
static bool isSupportedLocalOptAlg(nlopt_algorithm local_opt_alg) noexcept;
static bool isRequireLocalOptAlg(nlopt_algorithm opt_alg) noexcept;
static bool isRequirePopulation(nlopt_algorithm opt_alg) noexcept;
private:
const nlopt_algorithm m_global_opt_alg;
const nlopt_algorithm m_local_opt_alg;
public:
OptConfig Config;
};
}
|
"""
DG Balance Law Discretizations module.
Attempts to provide a reasonable implementation of a discontinuous Galerkin
method (in weak form) on tensor product quadrilateral (2D) and hexahedral (3D)
elements for balance laws of the form
```math
q_{,t} + Ξ£_{i=1,...d} F_{i,i} = s
```
where ``q`` is the state vector, ``F`` is the flux function, and ``s`` is the
source function. ``F`` includes both the "inviscid" and "viscous" fluxes. Note
that this is a space only discretization, time must be advanced using some
ordinary differential equations methods; see [`ODESolvers`](@ref).
The flux function `F_{i}` is taken to be of the form:
```math
F_{i} := F_{i}(q, Ο; a)
Ο = H(q, βG(q; a); a)
```
where ``a`` is a set of parameters and viscous terms enter through ``Ο``
The source term is of the form:
```math
s := s(q; a)
```
In the code and docs the following terminology is used:
- ``q`` is referred to as the state
- ``Ο`` is the viscous state
- ``a`` is the auxiliary state
- ``F`` is the physical flux
- ``H`` is the viscous transform
- ``G`` is the gradient transform
Much of the notation used in this module follows Hesthaven and Warburton (2008).
!!! note
Currently all the functions take the same parameters and the gradient
transform can take a user-specified subset of the state vector.
!!! note
We plan to switch to a skew-symmetric formulation (at which time this note
will be removed)
!!! references
```
@BOOK{HesthavenWarburton2008,
title = {Nodal Discontinuous {G}alerkin Methods: {A}lgorithms, Analysis,
and Applications},
publisher = {Springer-Verlag New York},
year = {2008},
author = {Hesthaven, Jan S. and Warburton, Tim},
volume = {54},
series = {Texts in Applied Mathematics},
doi = {10.1007/978-0-387-72067-8}
}
```
"""
module DGBalanceLawDiscretizations
using MPI
using ..Grids
using ..MPIStateArrays
using StaticArrays
using ..SpaceMethods
using DocStringExtensions
using ..Topologies
using GPUifyLoops
export DGBalanceLaw
include("DGBalanceLawDiscretizations_kernels.jl")
include("NumericalFluxes.jl")
"""
DGBalanceLaw <: AbstractDGMethod
This contains the necessary information for a discontinuous Galerkin method for
balance laws.
See also: Outer constructor [`DGBalanceLaw`](@ref)
# Fields
$(DocStringExtensions.FIELDS)
"""
struct DGBalanceLaw <: AbstractDGMethod
"computational grid / mesh"
grid::DiscontinuousSpectralElementGrid
"number of state"
nstate::Int
"physical flux function"
flux!::Function
"numerical flux function"
numerical_flux!::Function
"numerical boundary flux function"
numerical_boundary_flux!::Union{Nothing, Function}
"storage for the viscous state"
Qvisc::MPIStateArray
"number of out states for gradient_transform!"
number_gradient_states::Int
"number of out states for the viscous_transform!"
number_viscous_states::Int
"tuple of states going into gradient_transform!"
states_for_gradient_transform::Tuple
"transform from state to variables to take gradient of"
gradient_transform!::Union{Nothing, Function}
"transform from Q and gradient state to viscous states"
viscous_transform!::Union{Nothing, Function}
"penalty for the viscous state computation"
viscous_penalty!::Union{Nothing, Function}
"boundary penalty for the viscous state computation (e.g., Dirichlet)"
viscous_boundary_penalty!::Union{Nothing, Function}
"auxiliary state array"
auxstate::MPIStateArray
"source function"
source!::Union{Nothing, Function}
end
"""
DGBalanceLaw(;grid::DiscontinuousSpectralElementGrid,
length_state_vector,
flux!,
numerical_flux!,
numerical_boundary_flux! = nothing,
states_for_gradient_transform = (),
number_gradient_states = 0,
number_viscous_states = 0,
gradient_transform! = nothing,
viscous_transform! = nothing,
viscous_penalty! = nothing,
viscous_boundary_penalty! = nothing,
auxiliary_state_length = 0,
auxiliary_state_initialization! = nothing,
source! = nothing)
Constructs a `DGBalanceLaw` spatial discretization type for the physics defined
by `flux!` and `source!`. The computational domain is defined by `grid`. The
number of state variables is defined by `length_state_vector`. The user may also
specify an auxiliary state which will be unpacked by the compute kernel passed
on to the user-defined flux and numerical flux functions. The source function
`source!` is optional.
The flux function is called with data from a degree of freedom (DOF) as
```
flux!(F, Q, V, aux, t)
```
where
- `F` is an `MArray` of size `(dim, length_state_vector)` to be filled (note
that this is uninitialized so the user must set to zero if is this desired)
- `Q` is the state to evaluate (`MArray`)
- `V` is the viscous state to evaluate (`MArray`)
- `aux` is the user-defined auxiliary state (`MArray`)
- `t` is the current simulation time
Warning: Modifications to `Q` or `aux` may cause side effects and should be
avoided.
The numerical flux function is called with data from two DOFs as
```
numerical_flux!(F, nM, QM, VM, auxM, QP, VP, auxP, t)
```
where
- `F` is an `MVector` of length `length_state_vector` to be filled with the
numerical flux across the face (note that this is uninitialized so user must
set to zero if is this desired)
- `nM` is the unit outward normal to the face with respect to the minus side
(`MVector` of length `3`)
- `QM` and `QP` are the minus and plus side states (`MArray`)
- `VM` and `VP` are the minus and plus viscous side states (`MArray`)
- `auxM` and `auxP` are the auxiliary states (`MArray`)
- `t` is the current simulation time
Warning: Modifications to `nM`, `QM`, `auxM`, `QP`, or `auxP` may cause side
effects and should be avoided.
If `grid.topology` has a boundary then the function
`numerical_boundary_flux!` must be specified. This function is called
with the data from the neighbouring DOF as
```
numerical_boundary_flux!(F, nM, QM, VM, auxM, QP, VP, auxP, bctype, t)
```
where
- `F` is an `MArray` of size `(dim, length_state_vector)` to be filled with the
numerical flux across the face (note that this is uninitialized so user must
set to zero is this desired)
- `nM` is the unit outward normal to the face with respect to the minus side
(`MVector` of length `3`)
- `QM` and `QP` are the minus and plus side states (`MArray`)
- `VM` and `VP` are the minus and plus viscous side states (`MArray`)
- `auxM` and `auxP` are the auxiliary states (`MArray`)
- `bctype` is the boundary condition flag for the connected face and element of
`grid.elemtobndy`
- `t` is the current simulation time
Note: `QP` and `auxP` are filled with values based on degrees of freedom
referenced in `grid.vmapP`; `QP` and `auxP` may be modified by the calling
function.
Warning: Modifications to `nM`, `QM`, or `auxM` may cause side effects and
should be avoided.
If present the source function is called with data from a DOF as
```
source!(S, Q, aux, t)
```
where `S` is an `MVector` of length `length_state_vector` to be filled; other
arguments are the same as `flux!` and the same warning concerning `Q` and `aux`
applies.
When `auxiliary_state_initialization! !== nothing` then this is called on the
auxiliary state (assuming `auxiliary_state_length > 0`) as
```
auxiliary_state_initialization!(aux, x, y, z)
```
where `aux` is an `MArray` to fill with the auxiliary state for a DOF located at
Cartesian coordinate locations `(x, y, z)`; see also
[`grad_auxiliary_state!`](@ref) allows the user to take the gradient of a field
stored in the auxiliary state.
When viscous terms are needed, the user must specify values for the following
keyword arguments:
- `states_for_gradient_transform` (`Tuple`)
- `number_gradient_states` (`Int`)
- `number_viscous_states` (`Int`)
- `gradient_transform!` (`Function`)
- `viscous_transform!` (`Function`)
- `viscous_penalty!` (`Function`)
- `viscous_boundary_penalty!` (`Function`); only required if the topology has a
boundary
The function `gradient_transform!` is the implementation of the function `G` in
the module docs; see [`DGBalanceLawDiscretizations`](@ref). It transforms the
elements of the components of state vector specified by
`states_for_gradient_transform` into the values that should have their gradient
taken. It is called on each DOF as:
```
gradient_transform!(G, Q, aux, t)
```
where `G` is an `MVector` of length `number_gradient_states` to be filled, `Q`
is an `MVector` containing only the states specified by
`states_for_gradient_transform`, `aux` is the full auxiliary state at the DOF,
and `t` is the simulation time.Q
The function `viscous_transform!` is the implementation of the function `H` in
the module docs; see [`DGBalanceLawDiscretizations`](@ref). It transforms the
gradient ``βG`` and ``q`` into the viscous state ``Ο``. It is called on each DOF
as:
```
viscous_transform!(V, gradG, Q, aux, t)
```
where `V` is an `MVector` of length `number_viscous_states` to be filled,
`gradG` is an `MMatrix` containing the DG-gradient of ``G``, `Q` is an `MVector`
containing only the states specified by `states_for_gradient_transform`, `aux`
is the full auxiliary state at the DOF, and `t` is the simulation time. Note
that `V` is a vector not a matrix so that minimal storage can be used if
symmetry can be exploited.
The function `viscous_penalty!` is the penalty terms to be used for the
DG-gradient calculation. It is called with data from two neighbouring degrees of
freedom as
```
viscous_penalty!(V, nM, HM, QM, auxM, HP, QP, auxP, t)
```
where:
- `V` is an `MVector` of length `number_viscous_states` to be filled with the
numerical penalty across the face; see below.
- `nM` is the unit outward normal to the face with respect to the minus side
(`MVector` of length `3`)
- `HM` and `HP` are the minus and plus evaluation of `gradient_transform!` on
either side of the face
- `QM` and `QP` are the minus and plus side states (`MArray`); filled only with
`states_for_gradient_transform` states.
- `auxM` and `auxP` are the auxiliary states (`MArray`)
- `t` is the current simulation time
The viscous penalty function is should compute on the faces
```math
n^{-} \\cdot H^{*} - n^{-} \\cdot H^{-}
```
where ``n^{-} \\cdot H^{*}`` is the "numerical-flux" for the viscous state
computation and ``H^{-}`` is the value of `viscous_transform!` evaluated on the
minus side ``n^{-} \\cdot G^{-}`` as an argument.
If `grid.topology` has a boundary then the function `viscous_boundary_penalty!`
must be specified. This function is called with the data from the neighbouring
DOF as
```
viscous_boundary_penalty!(V, nM, HM, QM, auxM, HP, QP, auxP, bctype, t)
```
where the required behaviour mimics that of `viscous_penalty!` and
`numerical_boundary_flux!`.
!!! note
If `(x, y, z)`, or data derived from this such as spherical coordinates, is
needed in the flux or source the user is responsible to storing this in the
auxiliary state
"""
function DGBalanceLaw(;grid::DiscontinuousSpectralElementGrid,
length_state_vector, flux!,
numerical_flux!,
numerical_boundary_flux! = nothing,
states_for_gradient_transform=(),
number_gradient_states=0,
number_viscous_states=0,
gradient_transform! = nothing,
viscous_transform! = nothing,
viscous_penalty! = nothing,
viscous_boundary_penalty! = nothing,
auxiliary_state_length=0,
auxiliary_state_initialization! = nothing,
source! = nothing)
topology = grid.topology
Np = dofs_per_element(grid)
h_vgeo = Array(grid.vgeo)
DFloat = eltype(h_vgeo)
DA = arraytype(grid)
(Topologies.hasboundary(topology) &&
numerical_boundary_flux! === nothing &&
error("no `numerical_boundary_flux!` given when topology "*
"has boundary"))
if number_viscous_states > 0 || number_gradient_states > 0 ||
length(states_for_gradient_transform) > 0
# These should all be true in this case
@assert number_viscous_states > 0
@assert number_gradient_states > 0
@assert length(states_for_gradient_transform) > 0
@assert gradient_transform! !== nothing
@assert viscous_transform! !== nothing
@assert viscous_penalty! !== nothing
(Topologies.hasboundary(topology)) && (@assert viscous_boundary_penalty! !==
nothing)
end
# TODO: Clean up this MPIStateArray interface...
Qvisc = MPIStateArray{Tuple{Np, number_viscous_states},
DFloat, DA
}(topology.mpicomm,
length(topology.elems),
realelems=topology.realelems,
ghostelems=topology.ghostelems,
sendelems=topology.sendelems,
nabrtorank=topology.nabrtorank,
nabrtorecv=topology.nabrtorecv,
nabrtosend=topology.nabrtosend,
weights=view(h_vgeo, :, grid.Mid, :),
commtag=111)
auxstate = MPIStateArray{Tuple{Np, auxiliary_state_length}, DFloat, DA
}(topology.mpicomm,
length(topology.elems),
realelems=topology.realelems,
ghostelems=topology.ghostelems,
sendelems=topology.sendelems,
nabrtorank=topology.nabrtorank,
nabrtorecv=topology.nabrtorecv,
nabrtosend=topology.nabrtosend,
weights=view(h_vgeo, :, grid.Mid, :),
commtag=222)
if auxiliary_state_initialization! !== nothing
@assert auxiliary_state_length > 0
dim = dimensionality(grid)
N = polynomialorder(grid)
vgeo = grid.vgeo
device = typeof(auxstate.Q) <: Array ? CPU() : CUDA()
nrealelem = length(topology.realelems)
@launch(device, threads=(Np,), blocks=nrealelem,
initauxstate!(Val(dim), Val(N), Val(auxiliary_state_length),
auxiliary_state_initialization!, auxstate.Q, vgeo,
topology.realelems))
MPIStateArrays.start_ghost_exchange!(auxstate)
MPIStateArrays.finish_ghost_exchange!(auxstate)
end
DGBalanceLaw(grid, length_state_vector, flux!,
numerical_flux!, numerical_boundary_flux!,
Qvisc, number_gradient_states, number_viscous_states,
states_for_gradient_transform, gradient_transform!,
viscous_transform!, viscous_penalty!,
viscous_boundary_penalty!, auxstate, source!)
end
"""
MPIStateArray(disc::DGBalanceLaw; nstate=disc.nstate, commtag=888)
Given a discretization `disc` constructs an `MPIStateArrays` for holding a
solution state. The optional 'nstate' arguments allows the user to specify a
specific number of states. The optional `commtag` allows the user to set the tag
to use for communication with this `MPIStateArray`.
"""
function MPIStateArrays.MPIStateArray(disc::DGBalanceLaw; nstate=disc.nstate,
commtag=888)
grid = disc.grid
topology = disc.grid.topology
# FIXME: Remove after updating CUDA
h_vgeo = Array(disc.grid.vgeo)
DFloat = eltype(h_vgeo)
Np = dofs_per_element(grid)
DA = arraytype(grid)
MPIStateArray{Tuple{Np, nstate}, DFloat, DA}(topology.mpicomm,
length(topology.elems),
realelems=topology.realelems,
ghostelems=topology.ghostelems,
sendelems=topology.sendelems,
nabrtorank=topology.nabrtorank,
nabrtorecv=topology.nabrtorecv,
nabrtosend=topology.nabrtosend,
weights=view(h_vgeo, :,
disc.grid.Mid, :),
commtag=commtag)
end
"""
MPIStateArray(disc::DGBalanceLaw, initialization!::Function; commtag=888)
Given a discretization `disc` constructs an `MPIStateArrays` for holding a
solution state. The optional `commtag` allows the user to set the tag to use
for communication with this `MPIStateArray`.
After allocation the `MPIStateArray` is initialized using the function
`initialization!` which will be called as:
```
initialization!(Q, x, y, z, [aux])
```
where `Q` is an `MArray` with the solution state at a single degree of freedom
(DOF) to initialize and `(x,y,z)` is the coordinate point for the allocation. If
`disc` contains an auxiliary data the values of this at the DOF are passed
through as an `MArray` through the `aux` argument
!!! note
`Q` is `undef` at start the function (i.e., not initialized to zero)
!!! note
Modifications of the `aux` array will be discarded.
!!! todo
GPUify this function to remove `host` and `device` data transfers
"""
function MPIStateArrays.MPIStateArray(disc::DGBalanceLaw,
ic!::Function; commtag=888)
Q = MPIStateArray(disc; commtag=commtag)
nvar = disc.nstate
grid = disc.grid
vgeo = grid.vgeo
Np = dofs_per_element(grid)
auxstate = disc.auxstate
nauxstate = size(auxstate, 2)
# FIXME: GPUify me
host_array = Array β typeof(Q).parameters
(h_vgeo, h_Q, h_auxstate) = host_array ? (vgeo, Q, auxstate) :
(Array(vgeo), Array(Q), Array(auxstate))
Qdof = MArray{Tuple{nvar}, eltype(h_Q)}(undef)
auxdof = MArray{Tuple{nauxstate}, eltype(h_Q)}(undef)
@inbounds for e = 1:size(Q, 3), i = 1:Np
(x, y, z) = (h_vgeo[i, grid.xid, e], h_vgeo[i, grid.yid, e],
h_vgeo[i, grid.zid, e])
if nauxstate > 0
for s = 1:nauxstate
auxdof[s] = h_auxstate[i, s, e]
end
ic!(Qdof, x, y, z, auxdof)
else
ic!(Qdof, x, y, z)
end
for n = 1:nvar
h_Q[i, n, e] = Qdof[n]
end
end
if !host_array
Q .= h_Q
end
Q
end
"""
MPIStateArray(initialization!::Function, disc::DGBalanceLaw; commtag=888)
Wrapper function to allow for calls of the form
```
MPIStateArray(disc) do Q, x, y, z
# fill Q
end
```
See also [`MPIStateArray`](@ref)
"""
MPIStateArrays.MPIStateArray(f::Function,
d::DGBalanceLaw; commtag=888
) = MPIStateArray(d, f; commtag=commtag)
"""
odefun!(disc::DGBalanceLaw, dQ::MPIStateArray, Q::MPIStateArray, t)
Evaluates the right-hand side of the discontinuous Galerkin semi-discretization
defined by `disc` at time `t` with state `Q`. The result is added into
`dQ`. Namely, the semi-discretization is of the form
```math
QΜ = F(Q, t)
```
and after the call `dQ += F(Q, t)`
"""
function SpaceMethods.odefun!(disc::DGBalanceLaw, dQ::MPIStateArray,
Q::MPIStateArray, t)
device = typeof(Q.Q) <: Array ? CPU() : CUDA()
grid = disc.grid
topology = grid.topology
dim = dimensionality(grid)
N = polynomialorder(grid)
Nq = N + 1
Nqk = dim == 2 ? 1 : Nq
Nfp = Nq * Nqk
nrealelem = length(topology.realelems)
Qvisc = disc.Qvisc
auxstate = disc.auxstate
nstate = disc.nstate
nviscstate = disc.number_viscous_states
ngradstate = disc.number_gradient_states
nauxstate = size(auxstate, 2)
states_grad = disc.states_for_gradient_transform
Dmat = grid.D
vgeo = grid.vgeo
sgeo = grid.sgeo
vmapM = grid.vmapM
vmapP = grid.vmapP
elemtobndy = grid.elemtobndy
########################
# Gradient Computation #
########################
MPIStateArrays.start_ghost_exchange!(Q)
if nviscstate > 0
@launch(device, threads=(Nq, Nq, Nqk), blocks=nrealelem,
volumeviscterms!(Val(dim), Val(N), Val(nstate), Val(states_grad),
Val(ngradstate), Val(nviscstate), Val(nauxstate),
disc.viscous_transform!, disc.gradient_transform!,
Q.Q, Qvisc.Q, auxstate.Q, vgeo, t, Dmat,
topology.realelems))
MPIStateArrays.finish_ghost_recv!(Q)
@launch(device, threads=Nfp, blocks=nrealelem,
faceviscterms!(Val(dim), Val(N), Val(nstate), Val(states_grad),
Val(ngradstate), Val(nviscstate), Val(nauxstate),
disc.viscous_penalty!,
disc.viscous_boundary_penalty!,
disc.gradient_transform!, Q.Q, Qvisc.Q, auxstate.Q,
vgeo, sgeo, t, vmapM, vmapP, elemtobndy,
topology.realelems))
MPIStateArrays.start_ghost_exchange!(Qvisc)
end
###################
# RHS Computation #
###################
@launch(device, threads=(Nq, Nq, Nqk), blocks=nrealelem,
volumerhs!(Val(dim), Val(N), Val(nstate), Val(nviscstate),
Val(nauxstate), disc.flux!, disc.source!, dQ.Q, Q.Q,
Qvisc.Q, auxstate.Q, vgeo, t, Dmat, topology.realelems))
MPIStateArrays.finish_ghost_recv!(nviscstate > 0 ? Qvisc : Q)
# The main reason for this protection is not for the MPI.Waitall!, but the
# make sure that we do not recopy data to the GPU
nviscstate > 0 && MPIStateArrays.finish_ghost_recv!(Qvisc)
nviscstate == 0 && MPIStateArrays.finish_ghost_recv!(Q)
@launch(device, threads=Nfp, blocks=nrealelem,
facerhs!(Val(dim), Val(N), Val(nstate), Val(nviscstate),
Val(nauxstate), disc.numerical_flux!,
disc.numerical_boundary_flux!, dQ.Q, Q.Q, Qvisc.Q,
auxstate.Q, vgeo, sgeo, t, vmapM, vmapP, elemtobndy,
topology.realelems))
# Just to be safe, we wait on the sends we started.
MPIStateArrays.finish_ghost_send!(Qvisc)
MPIStateArrays.finish_ghost_send!(Q)
end
"""
grad_auxiliary_state!(disc, i, (ix, iy, iz))
Computes the gradient of a the field `i` of the constant auxiliary state of
`disc` and stores the `x, y, z` compoment in fields `ix, iy, iz` of constant
auxiliary state.
!!! note
This only computes the element gradient not a DG gradient. If your constant
auxiliary state is discontinuous this may or may not be what you want!
"""
function grad_auxiliary_state!(disc::DGBalanceLaw, id, (idx, idy, idz))
grid = disc.grid
topology = grid.topology
dim = dimensionality(grid)
N = polynomialorder(grid)
auxstate = disc.auxstate
nauxstate = size(auxstate, 2)
@assert nauxstate >= max(id, idx, idy, idz)
@assert 0 < min(id, idx, idy, idz)
@assert allunique((idx, idy, idz))
Dmat = grid.D
vgeo = grid.vgeo
device = typeof(auxstate.Q) <: Array ? CPU() : CUDA()
nelem = length(topology.elems)
Nq = N + 1
Nqk = dim == 2 ? 1 : Nq
@launch(device, threads=(Nq, Nq, Nqk), blocks=nelem,
elem_grad_field!(Val(dim), Val(N), Val(nauxstate), auxstate.Q, vgeo,
Dmat, topology.elems, id, idx, idy, idz))
end
"""
dof_iteration!(dof_fun!::Function, R::MPIStateArray, disc::DGBalanceLaw,
Q::MPIStateArray)
Iterate over each dof to fill `R` using the `dof_fun!`. The syntax of the
`dof_fun!` is
```
dof_fun!(l_R, l_Q, l_Qvisc, l_aux)
```
where `l_R`, `l_Q`, `l_Qvisc`, and `l_aux` are of type `MArray` filled initially
with the values at a single degree of freedom. After the call the values in
`l_R` will be written back to the degree of freedom of `R`.
"""
function dof_iteration!(dof_fun!::Function, R::MPIStateArray, disc::DGBalanceLaw,
Q::MPIStateArray)
grid = disc.grid
topology = grid.topology
@assert size(R)[end] == size(Q)[end] == size(disc.auxstate)[end]
@assert size(R)[1] == size(Q)[1] == size(disc.auxstate)[1]
dim = dimensionality(grid)
N = polynomialorder(grid)
Qvisc = disc.Qvisc
auxstate = disc.auxstate
nstate = size(Q, 2)
nviscstate = size(Qvisc, 2)
nauxstate = size(auxstate, 2)
nRstate = size(R, 2)
Dmat = grid.D
vgeo = grid.vgeo
device = typeof(auxstate.Q) <: Array ? CPU() : CUDA()
nelem = length(topology.elems)
Nq = N + 1
Nqk = dim == 2 ? 1 : Nq
Np = Nq * Nq * Nqk
nrealelem = length(topology.realelems)
@launch(device, threads=(Np,), blocks=nrealelem,
knl_dof_iteration!(Val(dim), Val(N), Val(nRstate), Val(nstate),
Val(nviscstate), Val(nauxstate), dof_fun!, R.Q,
Q.Q, Qvisc.Q, auxstate.Q, topology.realelems))
end
end
|
The Bronze Age β defined by the use of metal β began around 2500 BC , with technology changing people 's everyday lives during this period through innovations such as the wheel , harnessing oxen , weaving textiles , brewing alcohol , and skilful metalworking , which produced new weapons and tools , along with fine gold decoration and jewellery , such as brooches and torcs . According to John T. Koch and others , Ireland in the Late Bronze Age was part of a maritime trading @-@ networked culture called the Atlantic Bronze Age that also included Britain , western France and Iberia , and that this is where Celtic languages developed . This contrasts with the traditional view that their origin lies in mainland Europe with the Hallstatt culture .
|
module Rationals
data NotZero : Integer -> Type where --Proof that a number is not zero, needed to construct Q
OneNotZero : NotZero 1
NegativeNotZero : ( n: Integer ) -> NotZero n -> NotZero (-n)
PositiveNotZero : ( m: Integer ) -> LTE 1 (fromIntegerNat m) -> NotZero m
rational : (p: Nat) -> (q: Integer) -> NotZero q -> (Integer, Integer)
rational Z q x = (toIntegerNat(0), q)
rational (S k) q x = (toIntegerNat(S k), q)
SecondPart : (Integer, Integer) -> Integer
SecondPart x = (snd x)
InclusionMap : (n : Nat) -> (Integer, Integer) --Includes the naturals in Q
InclusionMap n = rational n 1 OneNotZero
AddRationals : (Integer, Integer) -> (Integer, Integer) -> (Integer, Integer) --Need to implement proof checking for nonzero denominators
AddRationals x y = ((fst x)*(snd y) + (snd x)*(fst y), (snd x)*(snd y))
MultiplyRationals : (Integer, Integer) -> (Integer, Integer) -> (Integer, Integer) --Need to implement proof checking for nonzero denominators
MultiplyRationals x y = ((fst x)*(fst y), (snd x)*(snd y))
--Need to create multiplicative inverses of rationals as well
--A GCD function with proof that it is the GCD would be useful to reduce rationals into simplified form
test : Nat
test = fct 3
|
Base.:*(times::Integer, w::Wire) = Wire(repeat(w.values, outer=times))
function Base.:+{R,S}(lhs::Wire{R}, rhs::Wire{S})
(length(R) == length(S)) || throw(SizeMismatchError())
#for now, disallow bitvectors of length more than 64
if (length(R) > 64)
warn("currently > 64 bit wires not supported.")
throw(SizeMismatchError())
end
#create a new uninitialized wire of the same length
result = Wire{range(length(R))}(BitVector(length(R)), trues(length(R)))
result.values.chunks[1] = lhs.values.chunks[1] + rhs.values.chunks[1]
result
end
function Base.:-{R,S}(lhs::Wire{R}, rhs::Wire{S})
(length(R) == length(S)) || throw(SizeMismatchError())
#for now, disallow bitvectors of length more than 64
if (length(R) > 64)
warn("currently > 64 bit wires not supported.")
throw(SizeMismatchError())
end
#create a new uninitialized wire of the same length
result = Wire{range(length(R))}(BitVector(length(R)), trues(length(R)))
result.values.chunks[1] = lhs.values.chunks[1] - rhs.values.chunks[1]
result
end
function Base.:*{R,S}(lhs::Wire{R}, rhs::Wire{S})
new_length = length(R) + length(S)
if (length(R) + length(S) > 64)
warn("current > 64 bit results not supported.")
throw(SizeMismatchError())
end
result = Wire{range(new_length)}(BitVector(new_length), trues(new_length))
result.values.chunks[1] = lhs.values.chunks[1] * rhs.values.chunks[1]
result
end
function Base.:-{R}(tgt::Wire{R})
#for now, disallow bitvectors of length more than 64
if (length(R) > 64)
warn("currently > 64 bit wires not supported.")
throw(SizeMismatchError())
end
#create a new uninitialized wire of the same length
result = Wire{range(length(R))}(BitVector(length(R)), trues(length(R)))
result.values.chunks[1] = -tgt.values.chunks[1]
result
end
function trimInt64(n::Integer)
~(-(one(UInt64) << n))
end
function Base.:<{R,S}(lhs::Wire{R}, rhs::Wire{S})
(length(R) == length(S)) || throw(SizeMismatchError())
if (length(R) > 64)
warn("currently > 64 bit wires not supported.")
throw(SizeMismatchError())
end
assigned(lhs) && assigned(rhs) || throw(UnassignedError())
mask = trimInt64(length(R))
result = Wire((lhs.values.chunks[1] & mask) < (rhs.values.chunks[1] & mask))
end
# >, <=, >= come for free.
function Base.:(==){R,S}(lhs::Wire{R}, rhs::Wire{S})
(length(R) == length(S)) || throw(SizeMismatchError())
if (length(R) > 64)
warn("currently > 64 bit wires not supported.")
throw(SizeMismatchError())
end
assigned(lhs) && assigned(rhs) || throw(UnassignedError())
mask = trimInt64(length(R))
result = Wire((lhs.values.chunks[1] & mask) == (rhs.values.chunks[1] & mask))
end
################################################################################
## shifters
function Base.:(<<){R,S}(lhs::Wire{R}, rhs::Wire{S})
if (length(R) > 64)
warn("currently > 64 bit wires not supported.")
throw(SizeMismatchError())
end
if (length(S) > 64)
warn("> 64 bit wires for shifter RHS not supported.")
throw(SizeMismatchError())
end
assigned(lhs) && assigned(rhs) || throw(UnassignedError())
result = Wire(lhs.values.chunks[1] << rhs.values.chunks[1], length(R))
end
function Base.:(>>){R,S}(lhs::Wire{R}, rhs::Wire{S})
if (length(R) > 64)
warn("currently > 64 bit wires not supported.")
throw(SizeMismatchError())
end
if (length(S) > 64)
warn("> 64 bit wires for shifter RHS not supported.")
throw(SizeMismatchError())
end
assigned(lhs) && assigned(rhs) || throw(UnassignedError())
result = Wire(lhs.values.chunks[1] >> rhs.values.chunks[1], length(R))
end
function Base.:(>>>){R,S}(lhs::Wire{R}, rhs::Wire{S})
if (length(R) > 64)
warn("currently > 64 bit wires not supported.")
throw(SizeMismatchError())
end
if (length(S) > 64)
warn("> 64 bit wires for shifter RHS not supported.")
throw(SizeMismatchError())
end
assigned(lhs) && assigned(rhs) || throw(UnassignedError())
#if the top value is true, then we'll have to spoof negativity.
#the trimInt64() function can help, by masking those invisible values
#as ones.
if (lhs.values[end] == true)
lhs.values.chunks[1] |= ~trimInt64(length(R))
end
result = Wire(lhs.values.chunks[1] >> rhs.values.chunks[1], length(R))
end
|
// Copyright (c) 2016
// Author: Chrono Law
#include <std.hpp>
using namespace std;
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/array.hpp>
namespace io = boost::iostreams;
using namespace io;
int main()
{
char str[] = "123";
array_source asrc(str, str + 3);
stream<array_source> in(asrc);
char c1, c2, c3;
in >> c1 >> c2;
assert(c1 == '1' && c2 == '2');
in.get(c3);
assert(c3 == '3' && in.good());
assert(in.get(c3).eof());
char str2[10];
array_sink asnk(str2);
stream<array_sink> out(asnk);
out << 'a' << 'b' << 'c';
assert(str2[0] == 'a' && str2[2] == 'c');
}
|
module Test where
open import Pitch
open import Interval
open import Counterpoint
open import Data.Vec using (Vec; []; _β·_; zip)
open import Data.Fin using (zero; suc)
open import Relation.Binary.PropositionalEquality using (refl)
-- Last five notes of Yamanote melody
cantusFirmus : Vec Pitch 5
cantusFirmus = c 5 β· e 5 β· g 5 β· d 6 β· c 6 β· []
counterpoint : Vec Interval 5
counterpoint = maj10 β· min10 β· per8 β· maj6 β· per8 β· []
firstSpecies : Counterpoint 3
firstSpecies = zip cantusFirmus counterpoint
testCorrect : FirstSpecies firstSpecies
testCorrect = fs firstSpecies
(Ξ» { zero β refl ;
(suc zero) β refl ;
(suc (suc zero)) β refl ;
(suc (suc (suc zero))) β refl ;
(suc (suc (suc (suc zero)))) β refl })
(Ξ» { zero β refl ;
(suc zero) β refl ;
(suc (suc zero)) β refl ;
(suc (suc (suc zero))) β refl})
refl
|
Hibachi Grill and Take Out was a Japanese and Korean Restaurants restaurant which featured teriyaki, spicy pork, and bulgogi. They also served Korean BBQ. Do not confuse them with HibachiSan.
20050706 07:05:40 This place offers simple, tasty rice bowls, Chinese chicken salad and even smoothies. They have sushi, but it can be a little funky. Id avoid it, and go for the good old chicken teriyaki bowl. Users/SiennaGrass
20060319 18:08:47 nbsp The owner is one of the nicest owners Ive ever met. He makes friends with all his clients. I highly reccommend the spicy pork. Spicy Pork bowls, while not on the menu, are also available if you ask for it. Their shakes are also superb. Users/KevinRollins
20060516 09:00:51 nbsp The only thing Ive ever tried on the menu is the Chicken Tariyaki rice bowl, but its always been great. I never liked teriyaki very much until I tried Hibachis. Lately, Ive been going here for lunch several times a month. Users/AdamSchneider
20060710 14:36:30 nbsp This place is a little gem. So far, the restaurant is immaculately clean and the food ingredients seem fresh, and the dishes are tasty. (Ive had the chicken teriyaki and the hibap). I concur with previous comments: the owner IS very nice. According to him, the place has been open since about January 2006. Check it out. Users/AnnieSirrah
20060712 23:29:54 nbsp The owner is very, very nice. The food is good. Perhaps the bowls are a bit small. I had the BBQ dinner tonight and it was quite good. Users/MisterProfessor
20061018 16:12:04 nbsp For the amount that you pay, you dont get a lot food. I paid $4.60 plus tax for a dinky chicken salad, and it was mostly lettuce and sauce; barely any chicken in it. Users/MattLow
20061206 09:19:53 nbsp Im coming here again... Users/CarlosOverstreet
20070210 17:31:00 nbsp This place has been closed for a week or more. Is it going to open again? I hope the owners are okay. Users/MisterProfessor
20070211 12:57:03 nbsp I tried the chicken teriyaki here for the first time about a month ago it was pretty good. Id return if I was in the area and was craving some teriyaki. Users/AlexPomeranz
20070228 13:06:52 nbsp I think that this place is closed. Everything was taken down when i tired to eat here on feb. 28th Users/DonGibson
20070818 08:09:14 nbsp do you know what is opening up in it now. there has been a lot of construction. Users/MattHh
20070909 13:26:32 nbsp It looks like its being replaced by Burgers and Brew owned and operated by Crepeville (or so the sign on the front says). Wonder how this will compete with the new 3rd & U Cafe seems like the same kinda food is going to be offered at both locations. Users/ArmyDecoy
20111017 14:02:42 nbsp Ate here so many times from 9498, great marinade on the chicken Users/Jeffrey9
|
eM_box = eMesh_box()
@testset "extensions" begin
@test_throws ErrorException volume(as_tri_eMesh(eM_box))
@test_throws ErrorException area(as_tet_eMesh(eM_box))
end
|
\graphicspath{{Chapter2/Figs/}}
\chapter{Multi-Omics Factor Analysis (MOFA), a Bayesian model for integration of multi-omics data}
The work described in this Chapter results from a collaboration with Wolfgang Huber's group at the EMBL (Heidelberg, Germany). It has been peer-reviewed and published in \cite{Argelaguet2018}. The method was conceived by Florian Buettner, Oliver Stegle and me. I performed most of the mathematical derivations and implementation, but with significant contributions from Damien Arnol and Britta Velten. The CLL data application was led by Britta Velten whereas the single-cell application was led by me, but with joint contributions in either cases. Florian Buettner, Wolfgang Huber and Oliver Stegle supervised the project.\\
The article was jointly written by Britta Velten and me, with contributions from all authors.
\section{Theoretical foundations}
\subsection*{Mathematical notation} \label{section:mathematical_notation}
\begin{itemize}[noitemsep]
\item[--] Matrices are denoted with bold capital letters: $\bfW$
\item[--] Vectors are denoted with bold non-capital letters: $\bfw$. If the vector comes from a matrix, we will use a single index to indicate the row that it comes from. If two indices are used, the first one corresponds to the row and the second one to the column. The symbol '$:$' denotes the entire row/column. For instance, $\bfw_{i}$ refers to the $i$th row from the $\bfW$ matrix, whereas $\bfw_{:,j}$ refers to the $j$th column.
\item[--] Scalars are denoted with non-bold and non-capital letters: $w$. If the scalar comes from a 1-dimensional array (a vector), a single subscript will indicate its position in the vector. If the scalar comes from a 2-dimensional array, two indices will be shown at the bottom: the first one corresponding to the row and the second one to the column. For instance, $w_{i,j}$ refers to the value from the $i$th row and the $j$th column of the matrix $\bfW$, and $w_i$ to the $i$th value of the vector $\bfw$.
\item[--] $\boldzero_k$ is a zero vector of length $k$.
\item[--] $\I_k$ is the identity matrix with rank $k$.
\item[--] $\E_q[x]$ denotes the expectation of $x$ under the distribution $q$. When the expectations are taken with respect to the same distribution many times, we will avoid cluttered notation and we will instead use $\la x \ra$.
\item[--] $\Ndist{x}{\mu,\sigma^2}$: $x$ follows a univariate normal distribution with mean $\mu$ and variance $\sigma^2$.
\item[--] $\Gdist{x}{a,b}$: $x$ follows a gamma distribution with shape and rate parameters $a$ and $b$.
\item[--] $\Bdist{x}{a, b}$: $x$ follows a beta distribution with shape and rate parameters $a$ and $b$.
\item[--] $\text{Ber}(x|\theta)$: $x$ follows a Bernoulli distribution with parameter $\theta$.
\item[--] $\mathds{1}_0$: Dirac delta function centered at 0.
\item[--] $Tr(\bfX)$: Trace of the matrix \bfX
\end{itemize}
\subsection*{Graphical notation for probabilistic models}
Probabilistic models can be represented in a diagrammatic format (i.e. a graph or a network) that offers a compact visual representation of complicated systems of probability distributions \cite{Bishop2006}. In a graphical model the relationship between the nodes becomes more explicit, namely their conditional independence properties which allow the joint distribution over all variables to be factorised into a series of simpler products involving subsets of variables \cite{Bishop2006}. The basic unit of a network is the node, which represents the different types of variables, including observed variables, unobserved probabilistic variables and unobserved parameters. The nodes are connected by unidirectional edges (arrows) which capture the conditional independence relationship between the variables.
For this thesis we adapted the graphical notations from~\cite{Dietz2010-technical-report-graphs}:
\begin{center}
\begin{tabular}{m{8cm} m{2cm}}
Observed variables & \tikz{\node[obs](){$Y$}} \\
Unobserved probabilistic variables & \tikz{\node[latent](){$\theta$}} \\
Unobserved parameters & \tikz{\node[latent,double, double distance=1pt](){$\theta$}} \\
Repetition of node $\theta_n$ for $n\in\llbracket 1;N \rrbracket$ & \tikz{\node[latent](theta){$\theta_n$}; \plate[] {plateN} {(theta)} {$N$};} \\
Conditional dependency between nodes: $p(Y,\theta) = p(Y|\theta)p(\theta)$ & \tikz{%
\node[latent] (theta) {$\theta$};
\node[obs, xshift=1.5cm] (Y) {$Y$};
\edge{theta}{Y}}
\end{tabular}
\end{center}
% For simplicity, fixed hyperparameters are not represented on the graphical model. Unobserved parameters are only represented when optimised together with the unobserved probabilistic variables.
\input{Chapter2/bayes}
\input{Chapter2/factor_analysis}
|
State Before: F : Type ?u.107024
Ξ± : Type ?u.107027
Ξ² : Type ?u.107030
R : Type u_1
instβ : LinearOrderedRing R
a : R
n : β
hn : Even n
ha : a β 0
β’ 0 < a ^ n State After: case intro
F : Type ?u.107024
Ξ± : Type ?u.107027
Ξ² : Type ?u.107030
R : Type u_1
instβ : LinearOrderedRing R
a : R
n : β
ha : a β 0
k : β
hk : n = k + k
β’ 0 < a ^ n Tactic: cases' hn with k hk State Before: case intro
F : Type ?u.107024
Ξ± : Type ?u.107027
Ξ² : Type ?u.107030
R : Type u_1
instβ : LinearOrderedRing R
a : R
n : β
ha : a β 0
k : β
hk : n = k + k
β’ 0 < a ^ n State After: no goals Tactic: simpa only [hk, two_mul] using pow_bit0_pos ha k
|
Bowl Feeders. Bowl feeders are a type of vibratory feeder that consists of a feeder bowl (also known as a vibratory bowl) with a spiral track inside of the bowl and a drive unit. As the drive unit produces vibrations, the feeder bowl vibrates, and the motion of the bowl moves the parts up the spiral track.
Vibratory Bowl Feeder We are one of the leading manufacturers and exporters of vibratory bowl (part) feeder. This equipment is ideal apparatus to get the required, oriented output of the components at specific feed rate.
Vibratory Bowl Feeders, Bowl Feeders, Linear Feeders, Stock Feeders, Conveyors, Parts of SPM, Orientation Machine, Feeder Drive Unit, Stainless Steel Bowl, Cast Aluminium Bowl, Manufacturers, India Content on this page requires a newer version of Adobe Flash Player.
|
function [bias av_bias] = bias_f(x,y)
% Bias calculator
% Formula: 1 - mean(fused image)/mean(original image)
% (Ideal value = 0)
% 07/03/2010 Version 1.0
% 25/06/2010 Version 1.2 - Excel Output option
% 04/08/2011 Version 1.2F - Function Version
% Author: Aristidis D. Vaiopoulos
% Find the number of bands
bands = size(x);
if length(bands) == 3
bands = bands(1,3);
else
bands = 1;
end
% Preallocation
mx = zeros(1,bands);
my = zeros(1,bands);
% Mean value calculation
for i = 1:bands
xt = double(x(:,:,i));
yt = double(y(:,:,i));
mx(i) = mean(xt(:));
my(i) = mean(yt(:));
end
% Bias calculation
bias = 1 - (my./mx);
bias = bias';
av_bias = mean(bias);
end
|
chapter \<open>Future Work\<close>
theory %invisible Future_Work
imports Main
begin
text \<open>\label{chap:future}\<close>
section \<open>Populating the Framework\<close>
text \<open>\label{sec:populate}\<close>
text \<open>Pop-refinement provides a framework,
which must be populated with re-usable
concepts, methodologies, and theorem prover libraries
for full fruition.
The simple examples in \chapref{chap:exampleI} and \chapref{chap:exampleII},
and the discussion in \chapref{chap:general},
suggests a few initial ideas.
Working out examples of increasing complexity should suggest more ideas.\<close>
section \<open>Automated Transformations\<close>
text \<open>\label{sec:xform}\<close>
text \<open>A pop-refinement step from @{term spec\<^sub>i} can be performed manually,
by writing down \<open>spec\<^sub>i\<^sub>+\<^sub>1\<close> and proving \<open>spec\<^sub>i\<^sub>+\<^sub>1 p \<Longrightarrow> spec\<^sub>i p\<close>.
It is sometimes possible to generate \<open>spec\<^sub>i\<^sub>+\<^sub>1\<close> from @{term spec\<^sub>i},
along with a proof of \<open>spec\<^sub>i\<^sub>+\<^sub>1 p \<Longrightarrow> spec\<^sub>i p\<close>,
using automated transformation techniques like
term rewriting,
application of algorithmic templates,
and term construction by witness finding,
e.g.\ \cite{SmithMarktoberdorf,SpecwareWebSite}.
Automated transformations may require
parameters to be provided and applicability conditions to be proved,
but should generally save effort
and make derivations more robust against changes in requirement specifications.
Extending existing theorem provers with automated transformation capabilities
would be advantageous for pop-refinement.\<close>
section \<open>Other Kinds of Design Objects\<close>
text \<open>\label{sec:otherdesign}\<close>
text \<open>It has been suggested~\cite{LambertPrivate}
that pop-refinement could be used
to develop other kinds of design objects than programs,
e.g.\ protocols, digital circuits, and hybrid systems.
Perhaps pop-refinement could be used to develop
engines, cars, buildings, etc.
So long as these design objects can be described
by languages amenable to formalization,
pop-refinement should be applicable.\<close>
end %invisible
|
[STATEMENT]
lemma spies_takeWhile: "spies (takeWhile P evs) \<subseteq> spies evs"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. knows Spy (takeWhile P evs) \<subseteq> knows Spy evs
[PROOF STEP]
apply (induct_tac "evs")
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. knows Spy (takeWhile P []) \<subseteq> knows Spy []
2. \<And>a list. knows Spy (takeWhile P list) \<subseteq> knows Spy list \<Longrightarrow> knows Spy (takeWhile P (a # list)) \<subseteq> knows Spy (a # list)
[PROOF STEP]
apply (rename_tac [2] a b)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. knows Spy (takeWhile P []) \<subseteq> knows Spy []
2. \<And>a b. knows Spy (takeWhile P b) \<subseteq> knows Spy b \<Longrightarrow> knows Spy (takeWhile P (a # b)) \<subseteq> knows Spy (a # b)
[PROOF STEP]
apply (induct_tac [2] "a", auto)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
txt\<open>Resembles \<open>used_subset_append\<close> in theory Event.\<close>
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
|
\chapter{Authentication, Authorization, and Accounting}
% Explain AAA and why we need it
\section{Dependencies}
\subsection{OpenNTPD}
% Talk about a basic OpenNTPD setup
One of the key components to any \gls{aaa} system is time. Determining when a
users' access is valid is integral to maintaining a secure system. This helps
to prevent replay attacks and prevent access using past (or future) expired
credentials.
\gls{openbsd} prefers the \gls{openntpd} implementation of the \gls{ntp} service
because it is a free (as in freedom) and simple implementation. Initially,
\gls{openntpd} will be setup on the \gls{aaa} server in order to keep the
\gls{aaa} services better in sync with the clock. In the future, more advanced
time servers will be setup. At that point, the \gls{openntpd} server on the
\gls{aaa} server will be setup to sync from those time servers.
In order to activate a basic setup of \gls{openntpd} on \gls{openbsd}, the
following line should be entered into the \verb=/etc/rc.conf.local= file:
\begin{verbatim}
ntpd_flags=
\end{verbatim}
Upon reboot, the \gls{openntpd} service will start automatically with the system
and keep the clock in sync with the internet time servers.
% Do I add a subsection here or later on for more advanced OpenNTPD topics?
% Things like alternate time sources: GPS, Atomic Radio, Local Atomic (rubidium)
\subsection{Domain Name Service}
% We'll setup a DNS server on the kerberos domain controller.
Another key component to any \gls{aaa} system is name resolution. Name
resolution allows client machines to find the key server to request credentials
for access. Without being able to find the key server, the key server is rather
useless. A number of people will say that it's better to hard code the IP
address of the key server into the clients, but DNS keeps us from having to
manually update that configuration. Hard set IP addresses are not more secure
than DNS, as both can be spoofed and modified on the network.
% At some future point, move to another server with CARP and management scripts.
\subsection{Dynamic Host Configuration Protocol}
% Basic DHCP setup. Should also make it handle IPv6 and putting the names into
% DNS.
% At some future point, move to another server with CARP and management scripts
% (probably the same servers as DNS)
\section{Kerberos 5}
% Mention that Kerberos serves the Authentication role
% Discuss a basic kerberos setup
% Do I add subsections here for things like redundancy (CARP) here?
\section{Network Information Service}
% Mention that NIS/YP server the Authorization role
% Lets use NIS/YP over LDAP
% Do I add subsections here for things like redundancy (CARP) here?
\section{Accounting - ??}
% Is syslog sufficient?
% Do I add subsections here for things like redundancy (CARP) here?
\section{Certificate Authority}
% Does it make sense to put this here? Most of our connections will be secured
% via SSL, so we should have a CA
|
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
a : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lβ lβ : List Ξ±
p : lβ ~ lβ
sβ : Sorted r lβ
sβ : Sorted r lβ
β’ lβ = lβ
[PROOFSTEP]
induction' sβ with a lβ hβ sβ IH generalizing lβ
[GOAL]
case nil
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
a : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lβ lββ : List Ξ±
pβ : lβ ~ lββ
sββ : Sorted r lββ
lβ : List Ξ±
p : [] ~ lβ
sβ : Sorted r lβ
β’ [] = lβ
[PROOFSTEP]
exact p.nil_eq
[GOAL]
case cons
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lββ lββ : List Ξ±
pβ : lββ ~ lββ
sββ : Sorted r lββ
a : Ξ±
lβ : List Ξ±
hβ : β (a' : Ξ±), a' β lβ β r a a'
sβ : Pairwise r lβ
IH : β {lβ : List Ξ±}, lβ ~ lβ β Sorted r lβ β lβ = lβ
lβ : List Ξ±
p : a :: lβ ~ lβ
sβ : Sorted r lβ
β’ a :: lβ = lβ
[PROOFSTEP]
have : a β lβ := p.subset (mem_cons_self _ _)
[GOAL]
case cons
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lββ lββ : List Ξ±
pβ : lββ ~ lββ
sββ : Sorted r lββ
a : Ξ±
lβ : List Ξ±
hβ : β (a' : Ξ±), a' β lβ β r a a'
sβ : Pairwise r lβ
IH : β {lβ : List Ξ±}, lβ ~ lβ β Sorted r lβ β lβ = lβ
lβ : List Ξ±
p : a :: lβ ~ lβ
sβ : Sorted r lβ
this : a β lβ
β’ a :: lβ = lβ
[PROOFSTEP]
rcases mem_split this with β¨uβ, vβ, rflβ©
[GOAL]
case cons.intro.intro
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lββ lβ : List Ξ±
pβ : lββ ~ lβ
sββ : Sorted r lβ
a : Ξ±
lβ : List Ξ±
hβ : β (a' : Ξ±), a' β lβ β r a a'
sβ : Pairwise r lβ
IH : β {lβ : List Ξ±}, lβ ~ lβ β Sorted r lβ β lβ = lβ
uβ vβ : List Ξ±
p : a :: lβ ~ uβ ++ a :: vβ
sβ : Sorted r (uβ ++ a :: vβ)
this : a β uβ ++ a :: vβ
β’ a :: lβ = uβ ++ a :: vβ
[PROOFSTEP]
have p' := (perm_cons a).1 (p.trans perm_middle)
[GOAL]
case cons.intro.intro
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lββ lβ : List Ξ±
pβ : lββ ~ lβ
sββ : Sorted r lβ
a : Ξ±
lβ : List Ξ±
hβ : β (a' : Ξ±), a' β lβ β r a a'
sβ : Pairwise r lβ
IH : β {lβ : List Ξ±}, lβ ~ lβ β Sorted r lβ β lβ = lβ
uβ vβ : List Ξ±
p : a :: lβ ~ uβ ++ a :: vβ
sβ : Sorted r (uβ ++ a :: vβ)
this : a β uβ ++ a :: vβ
p' : lβ ~ uβ ++ vβ
β’ a :: lβ = uβ ++ a :: vβ
[PROOFSTEP]
obtain rfl := IH p' (sβ.sublist <| by simp)
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lββ lβ : List Ξ±
pβ : lββ ~ lβ
sββ : Sorted r lβ
a : Ξ±
lβ : List Ξ±
hβ : β (a' : Ξ±), a' β lβ β r a a'
sβ : Pairwise r lβ
IH : β {lβ : List Ξ±}, lβ ~ lβ β Sorted r lβ β lβ = lβ
uβ vβ : List Ξ±
p : a :: lβ ~ uβ ++ a :: vβ
sβ : Sorted r (uβ ++ a :: vβ)
this : a β uβ ++ a :: vβ
p' : lβ ~ uβ ++ vβ
β’ uβ ++ vβ <+ uβ ++ a :: vβ
[PROOFSTEP]
simp
[GOAL]
case cons.intro.intro
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lβ lβ : List Ξ±
pβ : lβ ~ lβ
sββ : Sorted r lβ
a : Ξ±
uβ vβ : List Ξ±
sβ : Sorted r (uβ ++ a :: vβ)
this : a β uβ ++ a :: vβ
hβ : β (a' : Ξ±), a' β uβ ++ vβ β r a a'
sβ : Pairwise r (uβ ++ vβ)
IH : β {lβ : List Ξ±}, uβ ++ vβ ~ lβ β Sorted r lβ β uβ ++ vβ = lβ
p : a :: (uβ ++ vβ) ~ uβ ++ a :: vβ
p' : uβ ++ vβ ~ uβ ++ vβ
β’ a :: (uβ ++ vβ) = uβ ++ a :: vβ
[PROOFSTEP]
change a :: uβ ++ vβ = uβ ++ ([a] ++ vβ)
[GOAL]
case cons.intro.intro
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lβ lβ : List Ξ±
pβ : lβ ~ lβ
sββ : Sorted r lβ
a : Ξ±
uβ vβ : List Ξ±
sβ : Sorted r (uβ ++ a :: vβ)
this : a β uβ ++ a :: vβ
hβ : β (a' : Ξ±), a' β uβ ++ vβ β r a a'
sβ : Pairwise r (uβ ++ vβ)
IH : β {lβ : List Ξ±}, uβ ++ vβ ~ lβ β Sorted r lβ β uβ ++ vβ = lβ
p : a :: (uβ ++ vβ) ~ uβ ++ a :: vβ
p' : uβ ++ vβ ~ uβ ++ vβ
β’ a :: uβ ++ vβ = uβ ++ ([a] ++ vβ)
[PROOFSTEP]
rw [β append_assoc]
[GOAL]
case cons.intro.intro
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lβ lβ : List Ξ±
pβ : lβ ~ lβ
sββ : Sorted r lβ
a : Ξ±
uβ vβ : List Ξ±
sβ : Sorted r (uβ ++ a :: vβ)
this : a β uβ ++ a :: vβ
hβ : β (a' : Ξ±), a' β uβ ++ vβ β r a a'
sβ : Pairwise r (uβ ++ vβ)
IH : β {lβ : List Ξ±}, uβ ++ vβ ~ lβ β Sorted r lβ β uβ ++ vβ = lβ
p : a :: (uβ ++ vβ) ~ uβ ++ a :: vβ
p' : uβ ++ vβ ~ uβ ++ vβ
β’ a :: uβ ++ vβ = uβ ++ [a] ++ vβ
[PROOFSTEP]
congr
[GOAL]
case cons.intro.intro.e_a
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lβ lβ : List Ξ±
pβ : lβ ~ lβ
sββ : Sorted r lβ
a : Ξ±
uβ vβ : List Ξ±
sβ : Sorted r (uβ ++ a :: vβ)
this : a β uβ ++ a :: vβ
hβ : β (a' : Ξ±), a' β uβ ++ vβ β r a a'
sβ : Pairwise r (uβ ++ vβ)
IH : β {lβ : List Ξ±}, uβ ++ vβ ~ lβ β Sorted r lβ β uβ ++ vβ = lβ
p : a :: (uβ ++ vβ) ~ uβ ++ a :: vβ
p' : uβ ++ vβ ~ uβ ++ vβ
β’ a :: uβ = uβ ++ [a]
[PROOFSTEP]
have : β (x : Ξ±) (_ : x β uβ), x = a := fun x m =>
antisymm ((pairwise_append.1 sβ).2.2 _ m a (mem_cons_self _ _)) (hβ _ (by simp [m]))
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lβ lβ : List Ξ±
pβ : lβ ~ lβ
sββ : Sorted r lβ
a : Ξ±
uβ vβ : List Ξ±
sβ : Sorted r (uβ ++ a :: vβ)
this : a β uβ ++ a :: vβ
hβ : β (a' : Ξ±), a' β uβ ++ vβ β r a a'
sβ : Pairwise r (uβ ++ vβ)
IH : β {lβ : List Ξ±}, uβ ++ vβ ~ lβ β Sorted r lβ β uβ ++ vβ = lβ
p : a :: (uβ ++ vβ) ~ uβ ++ a :: vβ
p' : uβ ++ vβ ~ uβ ++ vβ
x : Ξ±
m : x β uβ
β’ x β uβ ++ vβ
[PROOFSTEP]
simp [m]
[GOAL]
case cons.intro.intro.e_a
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lβ lβ : List Ξ±
pβ : lβ ~ lβ
sββ : Sorted r lβ
a : Ξ±
uβ vβ : List Ξ±
sβ : Sorted r (uβ ++ a :: vβ)
thisβ : a β uβ ++ a :: vβ
hβ : β (a' : Ξ±), a' β uβ ++ vβ β r a a'
sβ : Pairwise r (uβ ++ vβ)
IH : β {lβ : List Ξ±}, uβ ++ vβ ~ lβ β Sorted r lβ β uβ ++ vβ = lβ
p : a :: (uβ ++ vβ) ~ uβ ++ a :: vβ
p' : uβ ++ vβ ~ uβ ++ vβ
this : β (x : Ξ±), x β uβ β x = a
β’ a :: uβ = uβ ++ [a]
[PROOFSTEP]
rw [(@eq_replicate _ a (length uβ + 1) (a :: uβ)).2, (@eq_replicate _ a (length uβ + 1) (uβ ++ [a])).2]
[GOAL]
case cons.intro.intro.e_a
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lβ lβ : List Ξ±
pβ : lβ ~ lβ
sββ : Sorted r lβ
a : Ξ±
uβ vβ : List Ξ±
sβ : Sorted r (uβ ++ a :: vβ)
thisβ : a β uβ ++ a :: vβ
hβ : β (a' : Ξ±), a' β uβ ++ vβ β r a a'
sβ : Pairwise r (uβ ++ vβ)
IH : β {lβ : List Ξ±}, uβ ++ vβ ~ lβ β Sorted r lβ β uβ ++ vβ = lβ
p : a :: (uβ ++ vβ) ~ uβ ++ a :: vβ
p' : uβ ++ vβ ~ uβ ++ vβ
this : β (x : Ξ±), x β uβ β x = a
β’ length (uβ ++ [a]) = length uβ + 1 β§ β (b : Ξ±), b β uβ ++ [a] β b = a
[PROOFSTEP]
constructor
[GOAL]
case cons.intro.intro.e_a
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lβ lβ : List Ξ±
pβ : lβ ~ lβ
sββ : Sorted r lβ
a : Ξ±
uβ vβ : List Ξ±
sβ : Sorted r (uβ ++ a :: vβ)
thisβ : a β uβ ++ a :: vβ
hβ : β (a' : Ξ±), a' β uβ ++ vβ β r a a'
sβ : Pairwise r (uβ ++ vβ)
IH : β {lβ : List Ξ±}, uβ ++ vβ ~ lβ β Sorted r lβ β uβ ++ vβ = lβ
p : a :: (uβ ++ vβ) ~ uβ ++ a :: vβ
p' : uβ ++ vβ ~ uβ ++ vβ
this : β (x : Ξ±), x β uβ β x = a
β’ length (a :: uβ) = length uβ + 1 β§ β (b : Ξ±), b β a :: uβ β b = a
[PROOFSTEP]
constructor
[GOAL]
case cons.intro.intro.e_a.left
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lβ lβ : List Ξ±
pβ : lβ ~ lβ
sββ : Sorted r lβ
a : Ξ±
uβ vβ : List Ξ±
sβ : Sorted r (uβ ++ a :: vβ)
thisβ : a β uβ ++ a :: vβ
hβ : β (a' : Ξ±), a' β uβ ++ vβ β r a a'
sβ : Pairwise r (uβ ++ vβ)
IH : β {lβ : List Ξ±}, uβ ++ vβ ~ lβ β Sorted r lβ β uβ ++ vβ = lβ
p : a :: (uβ ++ vβ) ~ uβ ++ a :: vβ
p' : uβ ++ vβ ~ uβ ++ vβ
this : β (x : Ξ±), x β uβ β x = a
β’ length (uβ ++ [a]) = length uβ + 1
[PROOFSTEP]
simp [iff_true_intro this, or_comm]
[GOAL]
case cons.intro.intro.e_a.right
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lβ lβ : List Ξ±
pβ : lβ ~ lβ
sββ : Sorted r lβ
a : Ξ±
uβ vβ : List Ξ±
sβ : Sorted r (uβ ++ a :: vβ)
thisβ : a β uβ ++ a :: vβ
hβ : β (a' : Ξ±), a' β uβ ++ vβ β r a a'
sβ : Pairwise r (uβ ++ vβ)
IH : β {lβ : List Ξ±}, uβ ++ vβ ~ lβ β Sorted r lβ β uβ ++ vβ = lβ
p : a :: (uβ ++ vβ) ~ uβ ++ a :: vβ
p' : uβ ++ vβ ~ uβ ++ vβ
this : β (x : Ξ±), x β uβ β x = a
β’ β (b : Ξ±), b β uβ ++ [a] β b = a
[PROOFSTEP]
simp [iff_true_intro this, or_comm]
[GOAL]
case cons.intro.intro.e_a.left
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lβ lβ : List Ξ±
pβ : lβ ~ lβ
sββ : Sorted r lβ
a : Ξ±
uβ vβ : List Ξ±
sβ : Sorted r (uβ ++ a :: vβ)
thisβ : a β uβ ++ a :: vβ
hβ : β (a' : Ξ±), a' β uβ ++ vβ β r a a'
sβ : Pairwise r (uβ ++ vβ)
IH : β {lβ : List Ξ±}, uβ ++ vβ ~ lβ β Sorted r lβ β uβ ++ vβ = lβ
p : a :: (uβ ++ vβ) ~ uβ ++ a :: vβ
p' : uβ ++ vβ ~ uβ ++ vβ
this : β (x : Ξ±), x β uβ β x = a
β’ length (a :: uβ) = length uβ + 1
[PROOFSTEP]
simp [iff_true_intro this, or_comm]
[GOAL]
case cons.intro.intro.e_a.right
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lβ lβ : List Ξ±
pβ : lβ ~ lβ
sββ : Sorted r lβ
a : Ξ±
uβ vβ : List Ξ±
sβ : Sorted r (uβ ++ a :: vβ)
thisβ : a β uβ ++ a :: vβ
hβ : β (a' : Ξ±), a' β uβ ++ vβ β r a a'
sβ : Pairwise r (uβ ++ vβ)
IH : β {lβ : List Ξ±}, uβ ++ vβ ~ lβ β Sorted r lβ β uβ ++ vβ = lβ
p : a :: (uβ ++ vβ) ~ uβ ++ a :: vβ
p' : uβ ++ vβ ~ uβ ++ vβ
this : β (x : Ξ±), x β uβ β x = a
β’ β (b : Ξ±), b β a :: uβ β b = a
[PROOFSTEP]
simp [iff_true_intro this, or_comm]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
a : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lβ lβ : List Ξ±
p : lβ <+~ lβ
sβ : Sorted r lβ
sβ : Sorted r lβ
β’ lβ <+ lβ
[PROOFSTEP]
let β¨_, h, h'β© := p
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
a : Ξ±
l : List Ξ±
instβ : IsAntisymm Ξ± r
lβ lβ : List Ξ±
p : lβ <+~ lβ
sβ : Sorted r lβ
sβ : Sorted r lβ
wβ : List Ξ±
h : wβ ~ lβ
h' : wβ <+ lβ
β’ lβ <+ lβ
[PROOFSTEP]
rwa [β eq_of_perm_of_sorted h (sβ.sublist h') sβ]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
lβ : List Ξ±
instβ : IsRefl Ξ± r
l : List Ξ±
h : Sorted r l
a b : Fin (length l)
hab : a β€ b
β’ r (get l a) (get l b)
[PROOFSTEP]
rcases hab.eq_or_lt with (rfl | hlt)
[GOAL]
case inl
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
lβ : List Ξ±
instβ : IsRefl Ξ± r
l : List Ξ±
h : Sorted r l
a : Fin (length l)
hab : a β€ a
β’ r (get l a) (get l a)
case inr
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
aβ : Ξ±
lβ : List Ξ±
instβ : IsRefl Ξ± r
l : List Ξ±
h : Sorted r l
a b : Fin (length l)
hab : a β€ b
hlt : a < b
β’ r (get l a) (get l b)
[PROOFSTEP]
exacts [refl _, h.rel_get_of_lt hlt]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
a : Ξ±
lβ l : List Ξ±
h : Sorted r l
k : β
x y : Ξ±
hx : x β take k l
hy : y β drop k l
β’ r x y
[PROOFSTEP]
obtain β¨β¨iy, hiyβ©, rflβ© := get_of_mem hy
[GOAL]
case intro.mk
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
a : Ξ±
lβ l : List Ξ±
h : Sorted r l
k : β
x : Ξ±
hx : x β take k l
iy : β
hiy : iy < length (drop k l)
hy : get (drop k l) { val := iy, isLt := hiy } β drop k l
β’ r x (get (drop k l) { val := iy, isLt := hiy })
[PROOFSTEP]
obtain β¨β¨ix, hixβ©, rflβ© := get_of_mem hx
[GOAL]
case intro.mk.intro.mk
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
a : Ξ±
lβ l : List Ξ±
h : Sorted r l
k iy : β
hiy : iy < length (drop k l)
hy : get (drop k l) { val := iy, isLt := hiy } β drop k l
ix : β
hix : ix < length (take k l)
hx : get (take k l) { val := ix, isLt := hix } β take k l
β’ r (get (take k l) { val := ix, isLt := hix }) (get (drop k l) { val := iy, isLt := hiy })
[PROOFSTEP]
rw [get_take', get_drop']
[GOAL]
case intro.mk.intro.mk
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
a : Ξ±
lβ l : List Ξ±
h : Sorted r l
k iy : β
hiy : iy < length (drop k l)
hy : get (drop k l) { val := iy, isLt := hiy } β drop k l
ix : β
hix : ix < length (take k l)
hx : get (take k l) { val := ix, isLt := hix } β take k l
β’ r (get l { val := β{ val := ix, isLt := hix }, isLt := (_ : β{ val := ix, isLt := hix } < length l) })
(get l { val := k + β{ val := iy, isLt := hiy }, isLt := (_ : k + β{ val := iy, isLt := hiy } < length l) })
[PROOFSTEP]
rw [length_take] at hix
[GOAL]
case intro.mk.intro.mk
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
a : Ξ±
lβ l : List Ξ±
h : Sorted r l
k iy : β
hiy : iy < length (drop k l)
hy : get (drop k l) { val := iy, isLt := hiy } β drop k l
ix : β
hixβ : ix < length (take k l)
hix : ix < min k (length l)
hx : get (take k l) { val := ix, isLt := hixβ } β take k l
β’ r (get l { val := β{ val := ix, isLt := hixβ }, isLt := (_ : β{ val := ix, isLt := hixβ } < length l) })
(get l { val := k + β{ val := iy, isLt := hiy }, isLt := (_ : k + β{ val := iy, isLt := hiy } < length l) })
[PROOFSTEP]
exact h.rel_nthLe_of_lt _ _ (ix.lt_add_right _ _ (lt_min_iff.mp hix).left)
[GOAL]
n : β
Ξ± : Type uu
instβ : Preorder Ξ±
f : Fin n β Ξ±
r : Ξ± β Ξ± β Prop
β’ Sorted r (ofFn f) β ((fun x x_1 => x < x_1) β r) f f
[PROOFSTEP]
simp_rw [Sorted, pairwise_iff_get, get_ofFn, Relator.LiftFun]
[GOAL]
n : β
Ξ± : Type uu
instβ : Preorder Ξ±
f : Fin n β Ξ±
r : Ξ± β Ξ± β Prop
β’ (β (i j : Fin (length (ofFn f))),
i < j β r (f (β(Fin.castIso (_ : length (ofFn f) = n)) i)) (f (β(Fin.castIso (_ : length (ofFn f) = n)) j))) β
β β¦a b : Fin nβ¦, a < b β r (f a) (f b)
[PROOFSTEP]
exact Iff.symm (Fin.castIso _).surjective.forallβ
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
hd : Ξ±
tl : List Ξ±
a : Ξ±
β’ length (orderedInsert r a (hd :: tl)) = length (hd :: tl) + 1
[PROOFSTEP]
dsimp [orderedInsert]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
hd : Ξ±
tl : List Ξ±
a : Ξ±
β’ length (if r a hd then a :: hd :: tl else hd :: orderedInsert r a tl) = Nat.succ (length tl) + 1
[PROOFSTEP]
split_ifs
[GOAL]
case pos
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
hd : Ξ±
tl : List Ξ±
a : Ξ±
hβ : r a hd
β’ length (a :: hd :: tl) = Nat.succ (length tl) + 1
[PROOFSTEP]
simp [orderedInsert_length tl]
[GOAL]
case neg
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
hd : Ξ±
tl : List Ξ±
a : Ξ±
hβ : Β¬r a hd
β’ length (hd :: orderedInsert r a tl) = Nat.succ (length tl) + 1
[PROOFSTEP]
simp [orderedInsert_length tl]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l : List Ξ±
β’ orderedInsert r a (b :: l) =
takeWhile (fun b => decide Β¬r a b) (b :: l) ++ a :: dropWhile (fun b => decide Β¬r a b) (b :: l)
[PROOFSTEP]
dsimp only [orderedInsert]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l : List Ξ±
β’ (if r a b then a :: b :: l else b :: orderedInsert r a l) =
takeWhile (fun b => decide Β¬r a b) (b :: l) ++ a :: dropWhile (fun b => decide Β¬r a b) (b :: l)
[PROOFSTEP]
split_ifs with h
[GOAL]
case pos
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l : List Ξ±
h : r a b
β’ a :: b :: l = takeWhile (fun b => decide Β¬r a b) (b :: l) ++ a :: dropWhile (fun b => decide Β¬r a b) (b :: l)
[PROOFSTEP]
simp [takeWhile, dropWhile, *, orderedInsert_eq_take_drop a l]
[GOAL]
case neg
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l : List Ξ±
h : Β¬r a b
β’ b :: orderedInsert r a l =
takeWhile (fun b => decide Β¬r a b) (b :: l) ++ a :: dropWhile (fun b => decide Β¬r a b) (b :: l)
[PROOFSTEP]
simp [takeWhile, dropWhile, *, orderedInsert_eq_take_drop a l]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l : List Ξ±
β’ orderedInsert r a (b :: l) ~ a :: b :: l
[PROOFSTEP]
by_cases h : a βΌ b
[GOAL]
case pos
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l : List Ξ±
h : r a b
β’ orderedInsert r a (b :: l) ~ a :: b :: l
[PROOFSTEP]
simp [orderedInsert, h]
[GOAL]
case neg
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l : List Ξ±
h : Β¬r a b
β’ orderedInsert r a (b :: l) ~ a :: b :: l
[PROOFSTEP]
simpa [orderedInsert, h] using ((perm_orderedInsert a l).cons _).trans (Perm.swap _ _ _)
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒΉ : DecidableRel r
instβ : DecidableEq Ξ±
L : List Ξ±
a b : Ξ±
β’ count a (orderedInsert r b L) = count a L + if a = b then 1 else 0
[PROOFSTEP]
rw [(L.perm_orderedInsert r b).count_eq, count_cons]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒΉ : DecidableRel r
instβ : DecidableEq Ξ±
L : List Ξ±
a b : Ξ±
β’ (if a = b then Nat.succ (count a L) else count a L) = count a L + if a = b then 1 else 0
[PROOFSTEP]
split_ifs
[GOAL]
case pos
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒΉ : DecidableRel r
instβ : DecidableEq Ξ±
L : List Ξ±
a b : Ξ±
hβ : a = b
β’ Nat.succ (count a L) = count a L + 1
[PROOFSTEP]
simp only [Nat.succ_eq_add_one, add_zero]
[GOAL]
case neg
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒΉ : DecidableRel r
instβ : DecidableEq Ξ±
L : List Ξ±
a b : Ξ±
hβ : Β¬a = b
β’ count a L = count a L + 0
[PROOFSTEP]
simp only [Nat.succ_eq_add_one, add_zero]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
b : Ξ±
l : List Ξ±
β’ insertionSort r (b :: l) ~ b :: l
[PROOFSTEP]
simpa [insertionSort] using (perm_orderedInsert _ _ _).trans ((perm_insertionSort l).cons b)
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l : List Ξ±
h : Sorted r (a :: b :: l)
β’ insertionSort r (a :: b :: l) = a :: b :: l
[PROOFSTEP]
rw [insertionSort, Sorted.insertionSort_eq, orderedInsert, if_pos]
[GOAL]
case hc
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l : List Ξ±
h : Sorted r (a :: b :: l)
β’ r a b
Ξ± : Type uu r : Ξ± β Ξ± β Prop instβ : DecidableRel r a b : Ξ± l : List Ξ± h : Sorted r (a :: b :: l) β’ Sorted r (b :: l)
[PROOFSTEP]
exacts [rel_of_sorted_cons h _ (mem_cons_self _ _), h.tail]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a b : Ξ±
l : List Ξ±
h : Sorted r (b :: l)
β’ Sorted r (List.orderedInsert r a (b :: l))
[PROOFSTEP]
by_cases h' : a βΌ b
[GOAL]
case pos
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a b : Ξ±
l : List Ξ±
h : Sorted r (b :: l)
h' : r a b
β’ Sorted r (List.orderedInsert r a (b :: l))
[PROOFSTEP]
rw [List.orderedInsert, if_pos h', sorted_cons]
[GOAL]
case pos
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a b : Ξ±
l : List Ξ±
h : Sorted r (b :: l)
h' : r a b
β’ (β (b_1 : Ξ±), b_1 β b :: l β r a b_1) β§ Sorted r (b :: l)
[PROOFSTEP]
exact β¨forall_mem_cons.2 β¨h', fun c hc => _root_.trans h' (rel_of_sorted_cons h _ hc)β©, hβ©
[GOAL]
case neg
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a b : Ξ±
l : List Ξ±
h : Sorted r (b :: l)
h' : Β¬r a b
β’ Sorted r (List.orderedInsert r a (b :: l))
[PROOFSTEP]
suffices β b' : Ξ±, b' β List.orderedInsert r a l β r b b' by simpa [orderedInsert, h', h.of_cons.orderedInsert a l]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a b : Ξ±
l : List Ξ±
h : Sorted r (b :: l)
h' : Β¬r a b
this : β (b' : Ξ±), b' β List.orderedInsert r a l β r b b'
β’ Sorted r (List.orderedInsert r a (b :: l))
[PROOFSTEP]
simpa [orderedInsert, h', h.of_cons.orderedInsert a l]
[GOAL]
case neg
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a b : Ξ±
l : List Ξ±
h : Sorted r (b :: l)
h' : Β¬r a b
β’ β (b' : Ξ±), b' β List.orderedInsert r a l β r b b'
[PROOFSTEP]
intro b' bm
[GOAL]
case neg
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a b : Ξ±
l : List Ξ±
h : Sorted r (b :: l)
h' : Β¬r a b
b' : Ξ±
bm : b' β List.orderedInsert r a l
β’ r b b'
[PROOFSTEP]
cases' show b' = a β¨ b' β l by simpa using (perm_orderedInsert _ _ _).subset bm with be bm
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a b : Ξ±
l : List Ξ±
h : Sorted r (b :: l)
h' : Β¬r a b
b' : Ξ±
bm : b' β List.orderedInsert r a l
β’ b' = a β¨ b' β l
[PROOFSTEP]
simpa using (perm_orderedInsert _ _ _).subset bm
[GOAL]
case neg.inl
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a b : Ξ±
l : List Ξ±
h : Sorted r (b :: l)
h' : Β¬r a b
b' : Ξ±
bm : b' β List.orderedInsert r a l
be : b' = a
β’ r b b'
[PROOFSTEP]
subst b'
[GOAL]
case neg.inl
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a b : Ξ±
l : List Ξ±
h : Sorted r (b :: l)
h' : Β¬r a b
bm : a β List.orderedInsert r a l
β’ r b a
[PROOFSTEP]
exact (total_of r _ _).resolve_left h'
[GOAL]
case neg.inr
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a b : Ξ±
l : List Ξ±
h : Sorted r (b :: l)
h' : Β¬r a b
b' : Ξ±
bmβ : b' β List.orderedInsert r a l
bm : b' β l
β’ r b b'
[PROOFSTEP]
exact rel_of_sorted_cons h _ bm
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
l lβ lβ : List Ξ±
h : split l = (lβ, lβ)
β’ split (a :: l) = (a :: lβ, lβ)
[PROOFSTEP]
rw [split, h]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
l lβ' lβ' : List Ξ±
h : split (a :: l) = (lβ', lβ')
β’ length lβ' β€ length (a :: l) β§ length lβ' β€ length (a :: l)
[PROOFSTEP]
cases' e : split l with lβ lβ
[GOAL]
case mk
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
l lβ' lβ' : List Ξ±
h : split (a :: l) = (lβ', lβ')
lβ lβ : List Ξ±
e : split l = (lβ, lβ)
β’ length lβ' β€ length (a :: l) β§ length lβ' β€ length (a :: l)
[PROOFSTEP]
injection (split_cons_of_eq _ e).symm.trans h
[GOAL]
case mk
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
l lβ' lβ' : List Ξ±
h : split (a :: l) = (lβ', lβ')
lβ lβ : List Ξ±
e : split l = (lβ, lβ)
fst_eqβ : a :: lβ = lβ'
snd_eqβ : lβ = lβ'
β’ length lβ' β€ length (a :: l) β§ length lβ' β€ length (a :: l)
[PROOFSTEP]
substs lβ' lβ'
[GOAL]
case mk
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
l lβ lβ : List Ξ±
e : split l = (lβ, lβ)
h : split (a :: l) = (a :: lβ, lβ)
β’ length (a :: lβ) β€ length (a :: l) β§ length lβ β€ length (a :: l)
[PROOFSTEP]
cases' length_split_le e with hβ hβ
[GOAL]
case mk.intro
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
l lβ lβ : List Ξ±
e : split l = (lβ, lβ)
h : split (a :: l) = (a :: lβ, lβ)
hβ : length lβ β€ length l
hβ : length lβ β€ length l
β’ length (a :: lβ) β€ length (a :: l) β§ length lβ β€ length (a :: l)
[PROOFSTEP]
exact β¨Nat.succ_le_succ hβ, Nat.le_succ_of_le hββ©
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l lβ lβ : List Ξ±
h : split (a :: b :: l) = (lβ, lβ)
β’ length lβ < length (a :: b :: l) β§ length lβ < length (a :: b :: l)
[PROOFSTEP]
cases' e : split l with lβ' lβ'
[GOAL]
case mk
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l lβ lβ : List Ξ±
h : split (a :: b :: l) = (lβ, lβ)
lβ' lβ' : List Ξ±
e : split l = (lβ', lβ')
β’ length lβ < length (a :: b :: l) β§ length lβ < length (a :: b :: l)
[PROOFSTEP]
injection (split_cons_of_eq _ (split_cons_of_eq _ e)).symm.trans h
[GOAL]
case mk
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l lβ lβ : List Ξ±
h : split (a :: b :: l) = (lβ, lβ)
lβ' lβ' : List Ξ±
e : split l = (lβ', lβ')
fst_eqβ : a :: lβ' = lβ
snd_eqβ : b :: lβ' = lβ
β’ length lβ < length (a :: b :: l) β§ length lβ < length (a :: b :: l)
[PROOFSTEP]
substs lβ lβ
[GOAL]
case mk
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l lβ' lβ' : List Ξ±
e : split l = (lβ', lβ')
h : split (a :: b :: l) = (a :: lβ', b :: lβ')
β’ length (a :: lβ') < length (a :: b :: l) β§ length (b :: lβ') < length (a :: b :: l)
[PROOFSTEP]
cases' length_split_le e with hβ hβ
[GOAL]
case mk.intro
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l lβ' lβ' : List Ξ±
e : split l = (lβ', lβ')
h : split (a :: b :: l) = (a :: lβ', b :: lβ')
hβ : length lβ' β€ length l
hβ : length lβ' β€ length l
β’ length (a :: lβ') < length (a :: b :: l) β§ length (b :: lβ') < length (a :: b :: l)
[PROOFSTEP]
exact β¨Nat.succ_le_succ (Nat.succ_le_succ hβ), Nat.succ_le_succ (Nat.succ_le_succ hβ)β©
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
l lβ' lβ' : List Ξ±
h : split (a :: l) = (lβ', lβ')
β’ a :: l ~ lβ' ++ lβ'
[PROOFSTEP]
cases' e : split l with lβ lβ
[GOAL]
case mk
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
l lβ' lβ' : List Ξ±
h : split (a :: l) = (lβ', lβ')
lβ lβ : List Ξ±
e : split l = (lβ, lβ)
β’ a :: l ~ lβ' ++ lβ'
[PROOFSTEP]
injection (split_cons_of_eq _ e).symm.trans h
[GOAL]
case mk
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
l lβ' lβ' : List Ξ±
h : split (a :: l) = (lβ', lβ')
lβ lβ : List Ξ±
e : split l = (lβ, lβ)
fst_eqβ : a :: lβ = lβ'
snd_eqβ : lβ = lβ'
β’ a :: l ~ lβ' ++ lβ'
[PROOFSTEP]
substs lβ' lβ'
[GOAL]
case mk
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
l lβ lβ : List Ξ±
e : split l = (lβ, lβ)
h : split (a :: l) = (a :: lβ, lβ)
β’ a :: l ~ a :: lβ ++ lβ
[PROOFSTEP]
exact ((perm_split e).trans perm_append_comm).cons a
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l : List Ξ±
β’ List Ξ±
[PROOFSTEP]
let ls := (split (a :: b :: l))
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l : List Ξ±
ls : List Ξ± Γ List Ξ± := split (a :: b :: l)
β’ List Ξ±
[PROOFSTEP]
have e : split (a :: b :: l) = β¨ls.1, ls.2β© := rfl
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l : List Ξ±
ls : List Ξ± Γ List Ξ± := split (a :: b :: l)
e : split (a :: b :: l) = (ls.fst, ls.snd)
β’ List Ξ±
[PROOFSTEP]
have h := length_split_lt e
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l : List Ξ±
ls : List Ξ± Γ List Ξ± := split (a :: b :: l)
e : split (a :: b :: l) = (ls.fst, ls.snd)
h : length ls.fst < length (a :: b :: l) β§ length ls.snd < length (a :: b :: l)
β’ List Ξ±
[PROOFSTEP]
have := h.1
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l : List Ξ±
ls : List Ξ± Γ List Ξ± := split (a :: b :: l)
e : split (a :: b :: l) = (ls.fst, ls.snd)
h : length ls.fst < length (a :: b :: l) β§ length ls.snd < length (a :: b :: l)
this : length ls.fst < length (a :: b :: l)
β’ List Ξ±
[PROOFSTEP]
have := h.2
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l : List Ξ±
ls : List Ξ± Γ List Ξ± := split (a :: b :: l)
e : split (a :: b :: l) = (ls.fst, ls.snd)
h : length ls.fst < length (a :: b :: l) β§ length ls.snd < length (a :: b :: l)
thisβ : length ls.fst < length (a :: b :: l)
this : length ls.snd < length (a :: b :: l)
β’ List Ξ±
[PROOFSTEP]
exact merge r (mergeSort ls.1) (mergeSort ls.2)
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l lβ lβ : List Ξ±
h : split (a :: b :: l) = (lβ, lβ)
β’ mergeSort r (a :: b :: l) = merge r (mergeSort r lβ) (mergeSort r lβ)
[PROOFSTEP]
simp only [mergeSort, h]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
β’ merge r [] [] ~ [] ++ []
[PROOFSTEP]
simp [merge]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
b : Ξ±
l' : List Ξ±
β’ merge r [] (b :: l') ~ [] ++ b :: l'
[PROOFSTEP]
simp [merge]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
l : List Ξ±
β’ merge r (a :: l) [] ~ a :: l ++ []
[PROOFSTEP]
simp [merge]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
β’ merge r (a :: l) (b :: l') ~ a :: l ++ b :: l'
[PROOFSTEP]
by_cases h : a βΌ b
[GOAL]
case pos
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
h : r a b
β’ merge r (a :: l) (b :: l') ~ a :: l ++ b :: l'
[PROOFSTEP]
simpa [merge, h] using perm_merge _ _
[GOAL]
case neg
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
h : Β¬r a b
β’ merge r (a :: l) (b :: l') ~ a :: l ++ b :: l'
[PROOFSTEP]
suffices b :: merge r (a :: l) l' ~ a :: (l ++ b :: l') by simpa [merge, h]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
h : Β¬r a b
this : b :: merge r (a :: l) l' ~ a :: (l ++ b :: l')
β’ merge r (a :: l) (b :: l') ~ a :: l ++ b :: l'
[PROOFSTEP]
simpa [merge, h]
[GOAL]
case neg
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
h : Β¬r a b
β’ b :: merge r (a :: l) l' ~ a :: (l ++ b :: l')
[PROOFSTEP]
exact ((perm_merge _ _).cons _).trans ((swap _ _ _).trans (perm_middle.symm.cons _))
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
β’ mergeSort r [] ~ []
[PROOFSTEP]
simp [mergeSort]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
β’ mergeSort r [a] ~ [a]
[PROOFSTEP]
simp [mergeSort]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l : List Ξ±
β’ mergeSort r (a :: b :: l) ~ a :: b :: l
[PROOFSTEP]
cases' e : split (a :: b :: l) with lβ lβ
[GOAL]
case mk
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l lβ lβ : List Ξ±
e : split (a :: b :: l) = (lβ, lβ)
β’ mergeSort r (a :: b :: l) ~ a :: b :: l
[PROOFSTEP]
cases' length_split_lt e with hβ hβ
[GOAL]
case mk.intro
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l lβ lβ : List Ξ±
e : split (a :: b :: l) = (lβ, lβ)
hβ : length lβ < length (a :: b :: l)
hβ : length lβ < length (a :: b :: l)
β’ mergeSort r (a :: b :: l) ~ a :: b :: l
[PROOFSTEP]
rw [mergeSort_cons_cons r e]
[GOAL]
case mk.intro
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l lβ lβ : List Ξ±
e : split (a :: b :: l) = (lβ, lβ)
hβ : length lβ < length (a :: b :: l)
hβ : length lβ < length (a :: b :: l)
β’ merge r (mergeSort r lβ) (mergeSort r lβ) ~ a :: b :: l
[PROOFSTEP]
apply (perm_merge r _ _).trans
[GOAL]
case mk.intro
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a b : Ξ±
l lβ lβ : List Ξ±
e : split (a :: b :: l) = (lβ, lβ)
hβ : length lβ < length (a :: b :: l)
hβ : length lβ < length (a :: b :: l)
β’ mergeSort r lβ ++ mergeSort r lβ ~ a :: b :: l
[PROOFSTEP]
exact ((perm_mergeSort lβ).append (perm_mergeSort lβ)).trans (perm_split e).symm
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
xβΒΉ xβ : Sorted r []
β’ Sorted r (List.merge r [] [])
[PROOFSTEP]
simp [List.merge]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
b : Ξ±
l' : List Ξ±
xβ : Sorted r []
hβ : Sorted r (b :: l')
β’ Sorted r (List.merge r [] (b :: l'))
[PROOFSTEP]
simpa [List.merge] using hβ
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
hβ : Sorted r (a :: l)
xβ : Sorted r []
β’ Sorted r (List.merge r (a :: l) [])
[PROOFSTEP]
simpa [List.merge] using hβ
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
β’ Sorted r (List.merge r (a :: l) (b :: l'))
[PROOFSTEP]
by_cases h : a βΌ b
[GOAL]
case pos
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : r a b
β’ Sorted r (List.merge r (a :: l) (b :: l'))
[PROOFSTEP]
suffices β (b' : Ξ±) (_ : b' β List.merge r l (b :: l')), r a b' by simpa [List.merge, h, hβ.of_cons.merge hβ]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : r a b
this : β (b' : Ξ±), b' β List.merge r l (b :: l') β r a b'
β’ Sorted r (List.merge r (a :: l) (b :: l'))
[PROOFSTEP]
simpa [List.merge, h, hβ.of_cons.merge hβ]
[GOAL]
case pos
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : r a b
β’ β (b' : Ξ±), b' β List.merge r l (b :: l') β r a b'
[PROOFSTEP]
intro b' bm
[GOAL]
case pos
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : r a b
b' : Ξ±
bm : b' β List.merge r l (b :: l')
β’ r a b'
[PROOFSTEP]
rcases show b' = b β¨ b' β l β¨ b' β l' by simpa [or_left_comm] using (perm_merge _ _ _).subset bm with (be | bl | bl')
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : r a b
b' : Ξ±
bm : b' β List.merge r l (b :: l')
β’ b' = b β¨ b' β l β¨ b' β l'
[PROOFSTEP]
simpa [or_left_comm] using (perm_merge _ _ _).subset bm
[GOAL]
case pos.inl
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : r a b
b' : Ξ±
bm : b' β List.merge r l (b :: l')
be : b' = b
β’ r a b'
[PROOFSTEP]
subst b'
[GOAL]
case pos.inl
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : r a b
bm : b β List.merge r l (b :: l')
β’ r a b
[PROOFSTEP]
assumption
[GOAL]
case pos.inr.inl
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : r a b
b' : Ξ±
bm : b' β List.merge r l (b :: l')
bl : b' β l
β’ r a b'
[PROOFSTEP]
exact rel_of_sorted_cons hβ _ bl
[GOAL]
case pos.inr.inr
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : r a b
b' : Ξ±
bm : b' β List.merge r l (b :: l')
bl' : b' β l'
β’ r a b'
[PROOFSTEP]
exact _root_.trans h (rel_of_sorted_cons hβ _ bl')
[GOAL]
case neg
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : Β¬r a b
β’ Sorted r (List.merge r (a :: l) (b :: l'))
[PROOFSTEP]
suffices β (b' : Ξ±) (_ : b' β List.merge r (a :: l) l'), r b b' by simpa [List.merge, h, hβ.merge hβ.of_cons]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : Β¬r a b
this : β (b' : Ξ±), b' β List.merge r (a :: l) l' β r b b'
β’ Sorted r (List.merge r (a :: l) (b :: l'))
[PROOFSTEP]
simpa [List.merge, h, hβ.merge hβ.of_cons]
[GOAL]
case neg
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : Β¬r a b
β’ β (b' : Ξ±), b' β List.merge r (a :: l) l' β r b b'
[PROOFSTEP]
intro b' bm
[GOAL]
case neg
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : Β¬r a b
b' : Ξ±
bm : b' β List.merge r (a :: l) l'
β’ r b b'
[PROOFSTEP]
have ba : b βΌ a := (total_of r _ _).resolve_left h
[GOAL]
case neg
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : Β¬r a b
b' : Ξ±
bm : b' β List.merge r (a :: l) l'
ba : r b a
β’ r b b'
[PROOFSTEP]
have : b' = a β¨ b' β l β¨ b' β l' := by simpa using (perm_merge _ _ _).subset bm
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : Β¬r a b
b' : Ξ±
bm : b' β List.merge r (a :: l) l'
ba : r b a
β’ b' = a β¨ b' β l β¨ b' β l'
[PROOFSTEP]
simpa using (perm_merge _ _ _).subset bm
[GOAL]
case neg
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : Β¬r a b
b' : Ξ±
bm : b' β List.merge r (a :: l) l'
ba : r b a
this : b' = a β¨ b' β l β¨ b' β l'
β’ r b b'
[PROOFSTEP]
rcases this with (be | bl | bl')
[GOAL]
case neg.inl
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : Β¬r a b
b' : Ξ±
bm : b' β List.merge r (a :: l) l'
ba : r b a
be : b' = a
β’ r b b'
[PROOFSTEP]
subst b'
[GOAL]
case neg.inl
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : Β¬r a b
ba : r b a
bm : a β List.merge r (a :: l) l'
β’ r b a
[PROOFSTEP]
assumption
[GOAL]
case neg.inr.inl
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : Β¬r a b
b' : Ξ±
bm : b' β List.merge r (a :: l) l'
ba : r b a
bl : b' β l
β’ r b b'
[PROOFSTEP]
exact _root_.trans ba (rel_of_sorted_cons hβ _ bl)
[GOAL]
case neg.inr.inr
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
l : List Ξ±
b : Ξ±
l' : List Ξ±
hβ : Sorted r (a :: l)
hβ : Sorted r (b :: l')
h : Β¬r a b
b' : Ξ±
bm : b' β List.merge r (a :: l) l'
ba : r b a
bl' : b' β l'
β’ r b b'
[PROOFSTEP]
exact rel_of_sorted_cons hβ _ bl'
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
β’ Sorted r (mergeSort r [])
[PROOFSTEP]
simp [mergeSort]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a : Ξ±
β’ Sorted r (mergeSort r [a])
[PROOFSTEP]
simp [mergeSort]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a b : Ξ±
l : List Ξ±
β’ Sorted r (mergeSort r (a :: b :: l))
[PROOFSTEP]
cases' e : split (a :: b :: l) with lβ lβ
[GOAL]
case mk
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a b : Ξ±
l lβ lβ : List Ξ±
e : split (a :: b :: l) = (lβ, lβ)
β’ Sorted r (mergeSort r (a :: b :: l))
[PROOFSTEP]
cases' length_split_lt e with hβ hβ
[GOAL]
case mk.intro
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a b : Ξ±
l lβ lβ : List Ξ±
e : split (a :: b :: l) = (lβ, lβ)
hβ : length lβ < length (a :: b :: l)
hβ : length lβ < length (a :: b :: l)
β’ Sorted r (mergeSort r (a :: b :: l))
[PROOFSTEP]
rw [mergeSort_cons_cons r e]
[GOAL]
case mk.intro
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβΒ² : DecidableRel r
instβΒΉ : IsTotal Ξ± r
instβ : IsTrans Ξ± r
a b : Ξ±
l lβ lβ : List Ξ±
e : split (a :: b :: l) = (lβ, lβ)
hβ : length lβ < length (a :: b :: l)
hβ : length lβ < length (a :: b :: l)
β’ Sorted r (merge r (mergeSort r lβ) (mergeSort r lβ))
[PROOFSTEP]
exact (sorted_mergeSort lβ).merge (sorted_mergeSort lβ)
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
β’ mergeSort r [] = []
[PROOFSTEP]
rw [List.mergeSort]
[GOAL]
Ξ± : Type uu
r : Ξ± β Ξ± β Prop
instβ : DecidableRel r
a : Ξ±
β’ mergeSort r [a] = [a]
[PROOFSTEP]
rw [List.mergeSort]
|
β Alternative Back Care Clinic, PC.
from infants to senior citizens.
to improve the health of your body, mind, and soul .
Alternative Back Care Clinic, PC (ABC Clinic, PC) is a chiropractic clinic, owned by Dr. Paul Bunkers, a graduate of Palmer College of Chiropractic in Davenport, Iowa. We specialize in conservative, alternative health care focusing on chiropractic, nutritional, and rehabilitative services. We work hard on dealing with simple and complex musculo-skeletal problems to help the patient get back to proper function and a pain-free lifestyle as soon as possible. We focus on "treating the cause, not just the pain". Your health care should be as easy as ABC β Alternative Back Care Clinic, PC.
Because Dr. Bunkers LOVES his job!
neck and back problems, headaches, joint problems of the arms and legs such as shoulders, knees, etc.
Β© 2019 Alternative Back Care, PC.
|
{-# OPTIONS --cubical --no-import-sorts --safe #-}
module Cubical.Algebra.RingSolver.AlmostRing where
open import Cubical.Foundations.Prelude
open import Cubical.Data.Sigma
open import Cubical.Algebra.Semigroup
open import Cubical.Algebra.Monoid
open import Cubical.Algebra.AbGroup
private
variable
β : Level
record IsAlmostRing {R : Type β}
(0r 1r : R) (_+_ _Β·_ : R β R β R) (-_ : R β R) : Type β where
constructor isalmostring
field
+IsMonoid : IsMonoid 0r _+_
Β·IsMonoid : IsMonoid 1r _Β·_
+Comm : (x y : R) β x + y β‘ y + x
Β·Comm : (x y : R) β x Β· y β‘ y Β· x
Β·DistR+ : (x y z : R) β x Β· (y + z) β‘ (x Β· y) + (x Β· z)
Β·DistL+ : (x y z : R) β (x + y) Β· z β‘ (x Β· z) + (y Β· z)
-CommΒ· : (x y : R) β - (x Β· y) β‘ (- x) Β· y
-Dist+ : (x y : R) β - (x + y) β‘ (- x) + (- y)
open IsMonoid +IsMonoid public
renaming
( assoc to +Assoc
; identity to +Identity
; lid to +Lid
; rid to +Rid
; isSemigroup to +IsSemigroup)
open IsMonoid Β·IsMonoid public
renaming
( assoc to Β·Assoc
; identity to Β·Identity
; lid to Β·Lid
; rid to Β·Rid
; isSemigroup to Β·IsSemigroup )
hiding
( is-set ) -- We only want to export one proof of this
record AlmostRing : Type (β-suc β) where
constructor almostring
field
Carrier : Type β
0r : Carrier
1r : Carrier
_+_ : Carrier β Carrier β Carrier
_Β·_ : Carrier β Carrier β Carrier
-_ : Carrier β Carrier
isAlmostRing : IsAlmostRing 0r 1r _+_ _Β·_ -_
infixl 8 _Β·_
infixl 7 -_
infixl 6 _+_
open IsAlmostRing isAlmostRing public
-- Extractor for the carrier type
β¨_β© : AlmostRing β Type β
β¨_β© = AlmostRing.Carrier
isSetAlmostRing : (R : AlmostRing {β}) β isSet β¨ R β©
isSetAlmostRing R = R .AlmostRing.isAlmostRing .IsAlmostRing.Β·IsMonoid .IsMonoid.isSemigroup .IsSemigroup.is-set
|
module Control.Comonad.Trans
import Control.Comonad
%default total
public export
interface ComonadTrans (0 t : (Type -> Type) -> Type -> Type) where
lower : Comonad w => t w a -> w a
|
using Rsvg
using Cairo
using Printf
using Test
include("test.jl")
pkg_dir = dirname(dirname(@__FILE__))
@testset "dimensions of known images " begin
d = test_get_dimension(joinpath(pkg_dir,"data","mulberry.svg"));
@test d.height == 512
@test d.width == 513
d = test_get_dimension(joinpath(pkg_dir,"data","diag.svg"));
@test d.height == 400
@test d.width == 400
d = test_get_dimension(joinpath(pkg_dir,"data","lotus.svg"));
@test d.height == 720
@test d.width == 576
d = test_get_dimension(joinpath(pkg_dir,"data","star.svg"));
@test d.height == 198
@test d.width == 224
end
@testset "render to png " begin
f = tempname() * ".png"
test_render_to_png(joinpath(pkg_dir,"data","mulberry.svg"),f);
@test stat(f).size > 0
f = tempname() * ".png"
test_render_to_png(joinpath(pkg_dir,"data","diag.svg"),f);
@test stat(f).size > 0
f = tempname() * ".png"
test_render_to_png(joinpath(pkg_dir,"data","lotus.svg"),f);
@test stat(f).size > 0
f = tempname() * ".png"
test_render_to_png(joinpath(pkg_dir,"data","star.svg"),f);
@test stat(f).size > 0
end
@testset "render string to png " begin
f = tempname() * ".png"
test_render_string_to_png(f);
@test stat(f).size > 0
f = tempname() * ".png"
test_render_long_string_to_png(3000,f);
@test stat(f).size > 0
f = tempname() * ".png"
test_render_long_string_to_png(60000,f);
@test stat(f).size > 0
end
@testset "roundtrip, render svg to svg" begin
f = tempname() * ".svg"
test_roundtrip(joinpath(pkg_dir,"data","lotus.svg"),f);
@test stat(f).size > 0
d = test_get_dimension(f);
@test d.height == 720
@test d.width == 576
end
@testset "error handling" begin
@test_throws ErrorException Rsvg.handle_new_from_data("not a valid data input")
try
Rsvg.handle_new_from_data("not a valid data input")
catch err
@test startswith(err.msg, "ccall") == false
end
end
|
[STATEMENT]
lemma weakenpre: "\<lbrakk> \<turnstile>\<^sub>3\<^sub>' {P}c{Q} ; \<And>s. P' s \<Longrightarrow> P s \<rbrakk> \<Longrightarrow>
\<turnstile>\<^sub>3\<^sub>' {P'}c{ Q}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>\<turnstile>\<^sub>3\<^sub>' {P} c { Q}; \<And>s. P' s \<Longrightarrow> P s\<rbrakk> \<Longrightarrow> \<turnstile>\<^sub>3\<^sub>' {P'} c { Q}
[PROOF STEP]
using conseq[where k=1]
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>\<turnstile>\<^sub>3\<^sub>' {?P} ?c { ?Q}; \<And>s n. ?P' (s, n) \<Longrightarrow> ?P (s, 1 * n); \<And>s n. ?Q (s, n) \<Longrightarrow> ?Q' (s, n div 1); 0 < 1\<rbrakk> \<Longrightarrow> \<turnstile>\<^sub>3\<^sub>' {?P'} ?c { ?Q'}
goal (1 subgoal):
1. \<lbrakk>\<turnstile>\<^sub>3\<^sub>' {P} c { Q}; \<And>s. P' s \<Longrightarrow> P s\<rbrakk> \<Longrightarrow> \<turnstile>\<^sub>3\<^sub>' {P'} c { Q}
[PROOF STEP]
by auto
|
module Generic.Test.Elim where
open import Generic.Core
open import Generic.Function.Elim
open import Generic.Test.Data.Vec
-- Is it possible to get rid of these `lift`s?
elimVecβ² : β {n Ξ± Ο} {A : Set Ξ±}
-> (P : β {n} -> Vec A n -> Set Ο)
-> (β {n} {xs : Vec A n} x -> P xs -> P (x β·α΅₯ xs))
-> P []α΅₯
-> (xs : Vec A n)
-> P xs
elimVecβ² P f z = elim P (lift z , Ξ» x r -> lift (f x r))
|
/**
Copyright 2017-2018, Kirit Sælensminde. <https://kirit.com/pgasio/>
*/
#pragma once
#include <pgasio/network.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/local/stream_protocol.hpp>
namespace pgasio {
template<typename S>
class connection;
/// Perform a handshake that assumes to authentication or connection
/// options are needed.
template<typename S, typename Y> inline
connection<S> handshake(
S socket,
const char *user, const char *database,
Y yield
) {
command cmd{0}; // The initial connect doesn't use a message type char
cmd.int32(0x0003'0000);
cmd.c_str("user");
cmd.c_str(user);
if ( database != nullptr && database[0] != 0 ) {
cmd.c_str("database");
cmd.c_str(database);
}
cmd.int8(0);
cmd.send(socket, yield);
std::unordered_map<std::string, std::string> settings;
int32_t process_id{}, secret{};
while ( socket.is_open() ) {
auto header = message_header(socket, yield);
auto body = header.message_body(socket, yield);
decoder decode = byte_view(body);
switch ( header.type ) {
case 'K':
process_id = decode.read_int32();
secret = decode.read_int32();
break;
case 'R': {
auto subcode = decode.read_int32();
if ( subcode != 0 ) {
throw std::runtime_error(
"Don't know how to handle authentication sub-code " +
std::to_string(subcode));
}
}
break; // Do nothing, the authentication was succesful
case 'S': {
auto name = decode.read_string();
auto value = decode.read_string();
settings.insert(std::make_pair(std::move(name), std::move(value)));
}
break;
case 'Z':
return connection<S>(std::move(socket), std::move(settings), process_id, secret);
default:
throw std::runtime_error(
std::string("Unknown connection message type: ") + header.type);
}
}
throw std::runtime_error("The Postgres connection closed during the initial handshake");
}
/// The connection to the database
template<typename S>
class connection {
template<typename Ss, typename Y> friend
connection<Ss> handshake(Ss, const char *, const char *, Y);
connection(
S s, std::unordered_map<std::string, std::string> set,
int32_t pid, int32_t sec
): socket(std::move(s)),
settings(std::move(set)),
process_id(pid),
secret(sec)
{
}
public:
/// The connection socket
S socket;
/// The settings in effect when the connection was first opened
const std::unordered_map<std::string, std::string> settings;
/// The process ID we're connected to
const int32_t process_id;
/// The secret used for cancellations
const int32_t secret;
};
/// Return a unix domain socket for the given location
template<typename L, typename Y> inline
auto unix_domain_socket(
boost::asio::io_service &ios, L loc, Y yield
) {
boost::asio::local::stream_protocol::socket socket{ios};
boost::asio::local::stream_protocol::endpoint ep(loc);
socket.async_connect(ep, yield);
return socket;
}
}
|
/-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.subalgebra
import ring_theory.noetherian
/-!
# Lie submodules of a Lie algebra
In this file we define Lie submodules and Lie ideals, we construct the lattice structure on Lie
submodules and we use it to define various important operations, notably the Lie span of a subset
of a Lie module.
## Main definitions
* `lie_submodule`
* `lie_submodule.well_founded_of_noetherian`
* `lie_submodule.lie_span`
* `lie_submodule.map`
* `lie_submodule.comap`
* `lie_ideal`
* `lie_ideal.map`
* `lie_ideal.comap`
## Tags
lie algebra, lie submodule, lie ideal, lattice structure
-/
universes u v w wβ wβ
section lie_submodule
variables (R : Type u) (L : Type v) (M : Type w)
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]
set_option old_structure_cmd true
/-- A Lie submodule of a Lie module is a submodule that is closed under the Lie bracket.
This is a sufficient condition for the subset itself to form a Lie module. -/
structure lie_submodule extends submodule R M :=
(lie_mem : β {x : L} {m : M}, m β carrier β β
x, mβ β carrier)
attribute [nolint doc_blame] lie_submodule.to_submodule
namespace lie_submodule
variables {R L M} (N N' : lie_submodule R L M)
/-- The zero module is a Lie submodule of any Lie module. -/
instance : has_zero (lie_submodule R L M) :=
β¨{ lie_mem := Ξ» x m h, by { rw ((submodule.mem_bot R).1 h), apply lie_zero, },
..(0 : submodule R M)}β©
instance : inhabited (lie_submodule R L M) := β¨0β©
instance coe_submodule : has_coe (lie_submodule R L M) (submodule R M) := β¨to_submoduleβ©
@[norm_cast]
lemma coe_to_submodule : ((N : submodule R M) : set M) = N := rfl
instance has_mem : has_mem M (lie_submodule R L M) := β¨Ξ» x N, x β (N : set M)β©
@[simp] lemma mem_carrier {x : M} : x β N.carrier β x β (N : set M) :=
iff.rfl
@[simp] lemma mem_coe_submodule {x : M} : x β (N : submodule R M) β x β N := iff.rfl
lemma mem_coe {x : M} : x β (N : set M) β x β N := iff.rfl
@[simp] lemma zero_mem : (0 : M) β N := (N : submodule R M).zero_mem
@[simp] lemma coe_to_set_mk (S : set M) (hβ hβ hβ hβ) :
((β¨S, hβ, hβ, hβ, hββ© : lie_submodule R L M) : set M) = S := rfl
@[simp] lemma coe_to_submodule_mk (p : submodule R M) (h) :
(({lie_mem := h, ..p} : lie_submodule R L M) : submodule R M) = p :=
by { cases p, refl, }
@[ext] lemma ext (h : β m, m β N β m β N') : N = N' :=
by { cases N, cases N', simp only [], ext m, exact h m, }
@[simp] lemma coe_to_submodule_eq_iff : (N : submodule R M) = (N' : submodule R M) β N = N' :=
begin
split; intros h,
{ ext, rw [β mem_coe_submodule, h], simp, },
{ rw h, },
end
/-- Copy of a lie_submodule with a new `carrier` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (s : set M) (hs : s = βN) : lie_submodule R L M :=
{ carrier := s,
zero_mem' := hs.symm βΈ N.zero_mem',
add_mem' := hs.symm βΈ N.add_mem',
smul_mem' := hs.symm βΈ N.smul_mem',
lie_mem := hs.symm βΈ N.lie_mem, }
instance : lie_ring_module L N :=
{ bracket := Ξ» (x : L) (m : N), β¨β
x, m.valβ, N.lie_mem m.propertyβ©,
add_lie := by { intros x y m, apply set_coe.ext, apply add_lie, },
lie_add := by { intros x m n, apply set_coe.ext, apply lie_add, },
leibniz_lie := by { intros x y m, apply set_coe.ext, apply leibniz_lie, }, }
instance : lie_module R L N :=
{ lie_smul := by { intros t x y, apply set_coe.ext, apply lie_smul, },
smul_lie := by { intros t x y, apply set_coe.ext, apply smul_lie, }, }
end lie_submodule
section lie_ideal
variables (L)
/-- An ideal of a Lie algebra is a Lie submodule of the Lie algebra as a Lie module over itself. -/
abbreviation lie_ideal := lie_submodule R L L
lemma lie_mem_right (I : lie_ideal R L) (x y : L) (h : y β I) : β
x, yβ β I := I.lie_mem h
lemma lie_mem_left (I : lie_ideal R L) (x y : L) (h : x β I) : β
x, yβ β I :=
by { rw [βlie_skew, βneg_lie], apply lie_mem_right, assumption, }
/-- An ideal of a Lie algebra is a Lie subalgebra. -/
def lie_ideal_subalgebra (I : lie_ideal R L) : lie_subalgebra R L :=
{ lie_mem' := by { intros x y hx hy, apply lie_mem_right, exact hy, },
..I.to_submodule, }
instance : has_coe (lie_ideal R L) (lie_subalgebra R L) := β¨Ξ» I, lie_ideal_subalgebra R L Iβ©
@[norm_cast] lemma lie_ideal.coe_to_subalgebra (I : lie_ideal R L) :
((I : lie_subalgebra R L) : set L) = I := rfl
@[norm_cast] lemma lie_ideal.coe_to_lie_subalgebra_to_submodule (I : lie_ideal R L) :
((I : lie_subalgebra R L) : submodule R L) = I := rfl
end lie_ideal
variables {R M}
lemma submodule.exists_lie_submodule_coe_eq_iff (p : submodule R M) :
(β (N : lie_submodule R L M), βN = p) β β (x : L) (m : M), m β p β β
x, mβ β p :=
begin
split,
{ rintros β¨N, rflβ©, exact N.lie_mem, },
{ intros h, use { lie_mem := h, ..p }, exact lie_submodule.coe_to_submodule_mk p _, },
end
namespace lie_subalgebra
variables {L}
lemma exists_lie_ideal_coe_eq_iff (K : lie_subalgebra R L):
(β (I : lie_ideal R L), βI = K) β β (x y : L), y β K β β
x, yβ β K :=
begin
simp only [β coe_to_submodule_eq_iff, lie_ideal.coe_to_lie_subalgebra_to_submodule,
submodule.exists_lie_submodule_coe_eq_iff L],
exact iff.rfl,
end
lemma exists_nested_lie_ideal_coe_eq_iff {K K' : lie_subalgebra R L} (h : K β€ K') :
(β (I : lie_ideal R K'), βI = of_le h) β β (x y : L), x β K' β y β K β β
x, yβ β K :=
begin
simp only [exists_lie_ideal_coe_eq_iff, coe_bracket, mem_of_le],
split,
{ intros h' x y hx hy, exact h' β¨x, hxβ© β¨y, h hyβ© hy, },
{ rintros h' β¨x, hxβ© β¨y, hyβ© hy', exact h' x y hx hy', },
end
end lie_subalgebra
end lie_submodule
namespace lie_submodule
variables {R : Type u} {L : Type v} {M : Type w}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]
variables (N N' : lie_submodule R L M) (I J : lie_ideal R L)
section lattice_structure
open set
lemma coe_injective : function.injective (coe : lie_submodule R L M β set M) :=
Ξ» N N' h, by { cases N, cases N', simp only, exact h, }
lemma coe_submodule_injective : function.injective (coe : lie_submodule R L M β submodule R M) :=
Ξ» N N' h, by { ext, rw [β mem_coe_submodule, h], refl, }
instance : partial_order (lie_submodule R L M) :=
{ le := Ξ» N N', β β¦xβ¦, x β N β x β N', -- Overriding `le` like this gives a better defeq.
..partial_order.lift (coe : lie_submodule R L M β set M) coe_injective }
lemma le_def : N β€ N' β (N : set M) β N' := iff.rfl
@[simp, norm_cast] lemma coe_submodule_le_coe_submodule : (N : submodule R M) β€ N' β N β€ N' :=
iff.rfl
instance : has_bot (lie_submodule R L M) := β¨0β©
@[simp] lemma bot_coe : ((β₯ : lie_submodule R L M) : set M) = {0} := rfl
@[simp] lemma bot_coe_submodule : ((β₯ : lie_submodule R L M) : submodule R M) = β₯ := rfl
@[simp] lemma mem_bot (x : M) : x β (β₯ : lie_submodule R L M) β x = 0 := mem_singleton_iff
instance : has_top (lie_submodule R L M) :=
β¨{ lie_mem := Ξ» x m h, mem_univ β
x, mβ,
..(β€ : submodule R M) }β©
@[simp] lemma top_coe : ((β€ : lie_submodule R L M) : set M) = univ := rfl
@[simp] lemma top_coe_submodule : ((β€ : lie_submodule R L M) : submodule R M) = β€ := rfl
@[simp] lemma mem_top (x : M) : x β (β€ : lie_submodule R L M) := mem_univ x
instance : has_inf (lie_submodule R L M) :=
β¨Ξ» N N', { lie_mem := Ξ» x m h, mem_inter (N.lie_mem h.1) (N'.lie_mem h.2),
..(N β N' : submodule R M) }β©
instance : has_Inf (lie_submodule R L M) :=
β¨Ξ» S, { lie_mem := Ξ» x m h, by
{ simp only [submodule.mem_carrier, mem_Inter, submodule.Inf_coe, mem_set_of_eq,
forall_apply_eq_imp_iffβ, exists_imp_distrib] at *,
intros N hN, apply N.lie_mem (h N hN), },
..Inf {(s : submodule R M) | s β S} }β©
@[simp] theorem inf_coe : (β(N β N') : set M) = N β© N' := rfl
@[simp] lemma Inf_coe_to_submodule (S : set (lie_submodule R L M)) :
(β(Inf S) : submodule R M) = Inf {(s : submodule R M) | s β S} := rfl
@[simp] lemma Inf_coe (S : set (lie_submodule R L M)) : (β(Inf S) : set M) = β s β S, (s : set M) :=
begin
rw [β lie_submodule.coe_to_submodule, Inf_coe_to_submodule, submodule.Inf_coe],
ext m,
simpa only [mem_Inter, mem_set_of_eq, forall_apply_eq_imp_iffβ, exists_imp_distrib],
end
lemma Inf_glb (S : set (lie_submodule R L M)) : is_glb S (Inf S) :=
begin
have h : β (N N' : lie_submodule R L M), (N : set M) β€ N' β N β€ N', { intros, apply iff.rfl, },
simp only [is_glb.of_image h, Inf_coe, is_glb_binfi],
end
/-- The set of Lie submodules of a Lie module form a complete lattice.
We provide explicit values for the fields `bot`, `top`, `inf` to get more convenient definitions
than we would otherwise obtain from `complete_lattice_of_Inf`. -/
instance : complete_lattice (lie_submodule R L M) :=
{ bot := β₯,
bot_le := Ξ» N _ h, by { rw mem_bot at h, rw h, exact N.zero_mem', },
top := β€,
le_top := Ξ» _ _ _, trivial,
inf := (β),
le_inf := Ξ» Nβ Nβ Nβ hββ hββ m hm, β¨hββ hm, hββ hmβ©,
inf_le_left := Ξ» _ _ _, and.left,
inf_le_right := Ξ» _ _ _, and.right,
..complete_lattice_of_Inf _ Inf_glb }
instance : add_comm_monoid (lie_submodule R L M) :=
{ add := (β),
add_assoc := Ξ» _ _ _, sup_assoc,
zero := β₯,
zero_add := Ξ» _, bot_sup_eq,
add_zero := Ξ» _, sup_bot_eq,
add_comm := Ξ» _ _, sup_comm, }
@[simp] lemma add_eq_sup : N + N' = N β N' := rfl
@[norm_cast, simp] lemma sup_coe_to_submodule :
(β(N β N') : submodule R M) = (N : submodule R M) β (N' : submodule R M) :=
begin
have aux : β (x : L) m, m β (N β N' : submodule R M) β β
x,mβ β (N β N' : submodule R M),
{ simp only [submodule.mem_sup],
rintro x m β¨y, hy, z, hz, rflβ©,
refine β¨β
x, yβ, N.lie_mem hy, β
x, zβ, N'.lie_mem hz, (lie_add _ _ _).symmβ© },
refine le_antisymm (Inf_le β¨{ lie_mem := aux, ..(N β N' : submodule R M) }, _β©) _,
{ simp only [exists_prop, and_true, mem_set_of_eq, eq_self_iff_true, coe_to_submodule_mk,
β coe_submodule_le_coe_submodule, and_self, le_sup_left, le_sup_right] },
{ simp, },
end
@[norm_cast, simp] lemma inf_coe_to_submodule :
(β(N β N') : submodule R M) = (N : submodule R M) β (N' : submodule R M) := rfl
@[simp] lemma mem_inf (x : M) : x β N β N' β x β N β§ x β N' :=
by rw [β mem_coe_submodule, β mem_coe_submodule, β mem_coe_submodule, inf_coe_to_submodule,
submodule.mem_inf]
lemma mem_sup (x : M) : x β N β N' β β (y β N) (z β N'), y + z = x :=
by { rw [β mem_coe_submodule, sup_coe_to_submodule, submodule.mem_sup], exact iff.rfl, }
lemma eq_bot_iff : N = β₯ β β (m : M), m β N β m = 0 :=
by { rw eq_bot_iff, exact iff.rfl, }
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_bot : subsingleton (lie_submodule R L β₯(β₯ : lie_submodule R L M)) :=
begin
apply subsingleton_of_bot_eq_top,
ext β¨x, hxβ©, change x β β₯ at hx, rw submodule.mem_bot at hx, subst hx,
simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, lie_submodule.mem_bot],
end
instance : is_modular_lattice (lie_submodule R L M) :=
{ sup_inf_le_assoc_of_le := Ξ» Nβ Nβ Nβ,
by { simp only [β coe_submodule_le_coe_submodule, sup_coe_to_submodule, inf_coe_to_submodule],
exact is_modular_lattice.sup_inf_le_assoc_of_le βNβ, }, }
variables (R L M)
lemma well_founded_of_noetherian [is_noetherian R M] :
well_founded ((>) : lie_submodule R L M β lie_submodule R L M β Prop) :=
begin
let f : ((>) : lie_submodule R L M β lie_submodule R L M β Prop) βr
((>) : submodule R M β submodule R M β Prop) :=
{ to_fun := coe,
map_rel' := Ξ» N N' h, h, },
apply f.well_founded, rw β is_noetherian_iff_well_founded, apply_instance,
end
variables {R L M}
section inclusion_maps
/-- The inclusion of a Lie submodule into its ambient space is a morphism of Lie modules. -/
def incl : N βββ
R,Lβ M :=
{ map_lie' := Ξ» x m, rfl,
..submodule.subtype (N : submodule R M) }
@[simp] lemma incl_apply (m : N) : N.incl m = m := rfl
lemma incl_eq_val : (N.incl : N β M) = subtype.val := rfl
variables {N N'} (h : N β€ N')
/-- Given two nested Lie submodules `N β N'`, the inclusion `N βͺ N'` is a morphism of Lie modules.-/
def hom_of_le : N βββ
R,Lβ N' :=
{ map_lie' := Ξ» x m, rfl,
..submodule.of_le h }
@[simp] lemma coe_hom_of_le (m : N) : (hom_of_le h m : M) = m := rfl
lemma hom_of_le_apply (m : N) : hom_of_le h m = β¨m.1, h m.2β© := rfl
lemma hom_of_le_injective : function.injective (hom_of_le h) :=
Ξ» x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe,
subtype.val_eq_coe]
end inclusion_maps
section lie_span
variables (R L) (s : set M)
/-- The `lie_span` of a set `s β M` is the smallest Lie submodule of `M` that contains `s`. -/
def lie_span : lie_submodule R L M := Inf {N | s β N}
variables {R L s}
lemma mem_lie_span {x : M} : x β lie_span R L s β β N : lie_submodule R L M, s β N β x β N :=
by { change x β (lie_span R L s : set M) β _, erw Inf_coe, exact mem_bInter_iff, }
lemma subset_lie_span : s β lie_span R L s :=
by { intros m hm, erw mem_lie_span, intros N hN, exact hN hm, }
lemma submodule_span_le_lie_span : submodule.span R s β€ lie_span R L s :=
by { rw submodule.span_le, apply subset_lie_span, }
lemma lie_span_le {N} : lie_span R L s β€ N β s β N :=
begin
split,
{ exact subset.trans subset_lie_span, },
{ intros hs m hm, rw mem_lie_span at hm, exact hm _ hs, },
end
lemma lie_span_mono {t : set M} (h : s β t) : lie_span R L s β€ lie_span R L t :=
by { rw lie_span_le, exact subset.trans h subset_lie_span, }
lemma lie_span_eq : lie_span R L (N : set M) = N :=
le_antisymm (lie_span_le.mpr rfl.subset) subset_lie_span
lemma coe_lie_span_submodule_eq_iff {p : submodule R M} :
(lie_span R L (p : set M) : submodule R M) = p β β (N : lie_submodule R L M), βN = p :=
begin
rw p.exists_lie_submodule_coe_eq_iff L, split; intros h,
{ intros x m hm, rw [β h, mem_coe_submodule], exact lie_mem _ (subset_lie_span hm), },
{ rw [β coe_to_submodule_mk p h, coe_to_submodule, coe_to_submodule_eq_iff, lie_span_eq], },
end
end lie_span
end lattice_structure
end lie_submodule
section lie_submodule_map_and_comap
variables {R : Type u} {L : Type v} {L' : Type wβ} {M : Type w} {M' : Type wβ}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L']
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
variables [add_comm_group M'] [module R M'] [lie_ring_module L M'] [lie_module R L M']
namespace lie_submodule
variables (f : M βββ
R,Lβ M') (N Nβ : lie_submodule R L M) (N' : lie_submodule R L M')
/-- A morphism of Lie modules `f : M β M'` pushes forward Lie submodules of `M` to Lie submodules
of `M'`. -/
def map : lie_submodule R L M' :=
{ lie_mem := Ξ» x m' h, by
{ rcases h with β¨m, hm, hfmβ©, use β
x, mβ, split,
{ apply N.lie_mem hm, },
{ norm_cast at hfm, simp [hfm], }, },
..(N : submodule R M).map (f : M ββ[R] M') }
/-- A morphism of Lie modules `f : M β M'` pulls back Lie submodules of `M'` to Lie submodules of
`M`. -/
def comap : lie_submodule R L M :=
{ lie_mem := Ξ» x m h, by { suffices : β
x, f mβ β N', { simp [this], }, apply N'.lie_mem h, },
..(N' : submodule R M').comap (f : M ββ[R] M') }
variables {f N Nβ N'}
lemma map_le_iff_le_comap : map f N β€ N' β N β€ comap f N' :=
set.image_subset_iff
variables (f)
lemma gc_map_comap : galois_connection (map f) (comap f) :=
Ξ» N N', map_le_iff_le_comap
variables {f}
@[simp] lemma map_sup : (N β Nβ).map f = N.map f β Nβ.map f :=
(gc_map_comap f).l_sup
lemma mem_map (m' : M') : m' β N.map f β β m, m β N β§ f m = m' :=
submodule.mem_map
end lie_submodule
namespace lie_ideal
variables (f : L βββ
Rβ L') (I Iβ : lie_ideal R L) (J : lie_ideal R L')
@[simp] lemma top_coe_lie_subalgebra : ((β€ : lie_ideal R L) : lie_subalgebra R L) = β€ := rfl
/-- A morphism of Lie algebras `f : L β L'` pushes forward Lie ideals of `L` to Lie ideals of `L'`.
Note that unlike `lie_submodule.map`, we must take the `lie_span` of the image. Mathematically
this is because although `f` makes `L'` into a Lie module over `L`, in general the `L` submodules of
`L'` are not the same as the ideals of `L'`. -/
def map : lie_ideal R L' := lie_submodule.lie_span R L' $ (I : submodule R L).map (f : L ββ[R] L')
/-- A morphism of Lie algebras `f : L β L'` pulls back Lie ideals of `L'` to Lie ideals of `L`.
Note that `f` makes `L'` into a Lie module over `L` (turning `f` into a morphism of Lie modules)
and so this is a special case of `lie_submodule.comap` but we do not exploit this fact. -/
def comap : lie_ideal R L :=
{ lie_mem := Ξ» x y h, by { suffices : β
f x, f yβ β J, { simp [this], }, apply J.lie_mem h, },
..(J : submodule R L').comap (f : L ββ[R] L') }
@[simp] lemma map_coe_submodule (h : β(map f I) = f '' I) :
(map f I : submodule R L') = (I : submodule R L).map f :=
by { rw [set_like.ext'_iff, lie_submodule.coe_to_submodule, h, submodule.map_coe], refl, }
@[simp] lemma comap_coe_submodule : (comap f J : submodule R L) = (J : submodule R L').comap f :=
rfl
lemma map_le : map f I β€ J β f '' I β J := lie_submodule.lie_span_le
variables {f I Iβ J}
lemma mem_map {x : L} (hx : x β I) : f x β map f I :=
by { apply lie_submodule.subset_lie_span, use x, exact β¨hx, rflβ©, }
@[simp] lemma mem_comap {x : L} : x β comap f J β f x β J := iff.rfl
lemma map_le_iff_le_comap : map f I β€ J β I β€ comap f J :=
by { rw map_le, exact set.image_subset_iff, }
variables (f)
lemma gc_map_comap : galois_connection (map f) (comap f) :=
Ξ» I I', map_le_iff_le_comap
variables {f}
@[simp] lemma map_sup : (I β Iβ).map f = I.map f β Iβ.map f :=
(gc_map_comap f).l_sup
lemma map_comap_le : map f (comap f J) β€ J :=
by { rw map_le_iff_le_comap, apply le_refl _, }
/-- See also `lie_ideal.map_comap_eq`. -/
lemma comap_map_le : I β€ comap f (map f I) :=
by { rw β map_le_iff_le_comap, apply le_refl _, }
@[mono] lemma map_mono : monotone (map f) :=
Ξ» Iβ Iβ h,
by { rw lie_submodule.le_def at h, apply lie_submodule.lie_span_mono (set.image_subset βf h), }
@[mono] lemma comap_mono : monotone (comap f) :=
Ξ» Jβ Jβ h, by { rw lie_submodule.le_def at h β’, exact set.preimage_mono h, }
lemma map_of_image (h : f '' I = J) : I.map f = J :=
begin
apply le_antisymm,
{ erw [lie_submodule.lie_span_le, submodule.map_coe, h], },
{ rw [lie_submodule.le_def, β h], exact lie_submodule.subset_lie_span, },
end
/-- Note that this is not a special case of `lie_submodule.subsingleton_of_bot`. Indeed, given
`I : lie_ideal R L`, in general the two lattices `lie_ideal R I` and `lie_submodule R L I` are
different (though the latter does naturally inject into the former).
In other words, in general, ideals of `I`, regarded as a Lie algebra in its own right, are not the
same as ideals of `L` contained in `I`. -/
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_bot : subsingleton (lie_ideal R β₯(β₯ : lie_ideal R L)) :=
begin
apply subsingleton_of_bot_eq_top,
ext β¨x, hxβ©, change x β β₯ at hx, rw submodule.mem_bot at hx, subst hx,
simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, lie_submodule.mem_bot],
end
end lie_ideal
namespace lie_hom
variables (f : L βββ
Rβ L') (I : lie_ideal R L) (J : lie_ideal R L')
/-- The kernel of a morphism of Lie algebras, as an ideal in the domain. -/
def ker : lie_ideal R L := lie_ideal.comap f β₯
/-- The range of a morphism of Lie algebras as an ideal in the codomain. -/
def ideal_range : lie_ideal R L' := lie_submodule.lie_span R L' f.range
lemma ideal_range_eq_lie_span_range :
f.ideal_range = lie_submodule.lie_span R L' f.range := rfl
lemma ideal_range_eq_map :
f.ideal_range = lie_ideal.map f β€ :=
by { ext, simp only [ideal_range, range_eq_map], refl }
/-- The condition that the image of a morphism of Lie algebras is an ideal. -/
def is_ideal_morphism : Prop := (f.ideal_range : lie_subalgebra R L') = f.range
@[simp] lemma is_ideal_morphism_def :
f.is_ideal_morphism β (f.ideal_range : lie_subalgebra R L') = f.range := iff.rfl
lemma is_ideal_morphism_iff :
f.is_ideal_morphism β β (x : L') (y : L), β (z : L), β
x, f yβ = f z :=
begin
simp only [is_ideal_morphism_def, ideal_range_eq_lie_span_range,
β lie_subalgebra.coe_to_submodule_eq_iff, β f.range.coe_to_submodule,
lie_ideal.coe_to_lie_subalgebra_to_submodule, lie_submodule.coe_lie_span_submodule_eq_iff,
lie_subalgebra.mem_coe_submodule, mem_range, exists_imp_distrib,
submodule.exists_lie_submodule_coe_eq_iff],
split,
{ intros h x y, obtain β¨z, hzβ© := h x (f y) y rfl, use z, exact hz.symm, },
{ intros h x y z hz, obtain β¨w, hwβ© := h x z, use w, rw [β hw, hz], },
end
lemma range_subset_ideal_range : (f.range : set L') β f.ideal_range := lie_submodule.subset_lie_span
lemma map_le_ideal_range : I.map f β€ f.ideal_range :=
begin
rw f.ideal_range_eq_map,
exact lie_ideal.map_mono le_top,
end
lemma ker_le_comap : f.ker β€ J.comap f := lie_ideal.comap_mono bot_le
@[simp] lemma ker_coe_submodule : (ker f : submodule R L) = (f : L ββ[R] L').ker := rfl
@[simp] lemma mem_ker {x : L} : x β ker f β f x = 0 :=
show x β (f.ker : submodule R L) β _,
by simp only [ker_coe_submodule, linear_map.mem_ker, coe_to_linear_map]
lemma mem_ideal_range {x : L} : f x β ideal_range f :=
begin
rw ideal_range_eq_map,
exact lie_ideal.mem_map (lie_submodule.mem_top x)
end
@[simp]
lemma le_ker_iff : I β€ f.ker β β x, x β I β f x = 0 :=
begin
split; intros h x hx,
{ specialize h hx, rw mem_ker at h, exact h, },
{ rw mem_ker, apply h x hx, },
end
lemma ker_eq_bot : f.ker = β₯ β function.injective f :=
by rw [β lie_submodule.coe_to_submodule_eq_iff, ker_coe_submodule, lie_submodule.bot_coe_submodule,
linear_map.ker_eq_bot, coe_to_linear_map]
@[simp] lemma range_coe_submodule : (f.range : submodule R L') = (f : L ββ[R] L').range := rfl
lemma range_eq_top : f.range = β€ β function.surjective f :=
begin
rw [β lie_subalgebra.coe_to_submodule_eq_iff, range_coe_submodule,
lie_subalgebra.top_coe_submodule],
exact linear_map.range_eq_top,
end
@[simp] lemma ideal_range_eq_top_of_surjective (h : function.surjective f) : f.ideal_range = β€ :=
begin
rw β f.range_eq_top at h,
rw [ideal_range_eq_lie_span_range, h, β lie_subalgebra.coe_to_submodule,
β lie_submodule.coe_to_submodule_eq_iff, lie_submodule.top_coe_submodule,
lie_subalgebra.top_coe_submodule, lie_submodule.coe_lie_span_submodule_eq_iff],
use β€,
exact lie_submodule.top_coe_submodule,
end
lemma is_ideal_morphism_of_surjective (h : function.surjective f) : f.is_ideal_morphism :=
by rw [is_ideal_morphism_def, f.ideal_range_eq_top_of_surjective h, f.range_eq_top.mpr h,
lie_ideal.top_coe_lie_subalgebra]
end lie_hom
namespace lie_ideal
variables {f : L βββ
Rβ L'} {I : lie_ideal R L} {J : lie_ideal R L'}
@[simp] lemma map_eq_bot_iff : I.map f = β₯ β I β€ f.ker :=
by { rw β le_bot_iff, exact lie_ideal.map_le_iff_le_comap }
lemma coe_map_of_surjective (h : function.surjective f) :
(I.map f : submodule R L') = (I : submodule R L).map f :=
begin
let J : lie_ideal R L' :=
{ lie_mem := Ξ» x y hy,
begin
have hy' : β (x : L), x β I β§ f x = y, { simpa [hy], },
obtain β¨zβ, hzβ, rflβ© := hy',
obtain β¨zβ, rflβ© := h x,
simp only [lie_hom.coe_to_linear_map, set_like.mem_coe, set.mem_image,
lie_submodule.mem_coe_submodule, submodule.mem_carrier, submodule.map_coe],
use β
zβ, zββ,
exact β¨I.lie_mem hzβ, f.map_lie zβ zββ©,
end,
..(I : submodule R L).map (f : L ββ[R] L'), },
erw lie_submodule.coe_lie_span_submodule_eq_iff,
use J,
apply lie_submodule.coe_to_submodule_mk,
end
lemma mem_map_of_surjective {y : L'} (hβ : function.surjective f) (hβ : y β I.map f) :
β (x : I), f x = y :=
begin
rw [β lie_submodule.mem_coe_submodule, coe_map_of_surjective hβ, submodule.mem_map] at hβ,
obtain β¨x, hx, rflβ© := hβ,
use β¨x, hxβ©,
refl,
end
lemma bot_of_map_eq_bot {I : lie_ideal R L} (hβ : function.injective f) (hβ : I.map f = β₯) :
I = β₯ :=
begin
rw β f.ker_eq_bot at hβ, change comap f β₯ = β₯ at hβ,
rw [eq_bot_iff, map_le_iff_le_comap, hβ] at hβ,
rw eq_bot_iff, exact hβ,
end
/-- Given two nested Lie ideals `Iβ β Iβ`, the inclusion `Iβ βͺ Iβ` is a morphism of Lie algebras. -/
def hom_of_le {Iβ Iβ : lie_ideal R L} (h : Iβ β€ Iβ) : Iβ βββ
Rβ Iβ :=
{ map_lie' := Ξ» x y, rfl,
..submodule.of_le h, }
@[simp] lemma coe_hom_of_le {Iβ Iβ : lie_ideal R L} (h : Iβ β€ Iβ) (x : Iβ) :
(hom_of_le h x : L) = x := rfl
lemma hom_of_le_apply {Iβ Iβ : lie_ideal R L} (h : Iβ β€ Iβ) (x : Iβ) :
hom_of_le h x = β¨x.1, h x.2β© := rfl
lemma hom_of_le_injective {Iβ Iβ : lie_ideal R L} (h : Iβ β€ Iβ) :
function.injective (hom_of_le h) :=
Ξ» x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe,
subtype.val_eq_coe]
@[simp] lemma map_sup_ker_eq_map : lie_ideal.map f (I β f.ker) = lie_ideal.map f I :=
begin
suffices : lie_ideal.map f (I β f.ker) β€ lie_ideal.map f I,
{ exact le_antisymm this (lie_ideal.map_mono le_sup_left), },
apply lie_submodule.lie_span_mono,
rintros x β¨y, hyβ, hyββ©, rw β hyβ,
erw lie_submodule.mem_sup at hyβ, obtain β¨zβ, hzβ, zβ, hzβ, hyβ© := hyβ, rw β hy,
rw [f.coe_to_linear_map, f.map_add, f.mem_ker.mp hzβ, add_zero], exact β¨zβ, hzβ, rflβ©,
end
@[simp] lemma map_comap_eq (h : f.is_ideal_morphism) : map f (comap f J) = f.ideal_range β J :=
begin
apply le_antisymm,
{ rw le_inf_iff, exact β¨f.map_le_ideal_range _, map_comap_leβ©, },
{ rw f.is_ideal_morphism_def at h,
rw [lie_submodule.le_def, lie_submodule.inf_coe, β coe_to_subalgebra, h],
rintros y β¨β¨x, hββ©, hββ©, rw β hβ at hβ β’, exact mem_map hβ, },
end
@[simp] lemma comap_map_eq (h : β(map f I) = f '' I) : comap f (map f I) = I β f.ker :=
by rw [β lie_submodule.coe_to_submodule_eq_iff, comap_coe_submodule, I.map_coe_submodule f h,
lie_submodule.sup_coe_to_submodule, f.ker_coe_submodule, linear_map.comap_map_eq]
variables (f I J)
/-- Regarding an ideal `I` as a subalgebra, the inclusion map into its ambient space is a morphism
of Lie algebras. -/
def incl : I βββ
Rβ L := (I : lie_subalgebra R L).incl
@[simp] lemma incl_range : I.incl.range = I := (I : lie_subalgebra R L).incl_range
@[simp] lemma incl_apply (x : I) : I.incl x = x := rfl
@[simp] lemma incl_coe : (I.incl : I ββ[R] L) = (I : submodule R L).subtype := rfl
@[simp] lemma comap_incl_self : comap I.incl I = β€ :=
by { rw β lie_submodule.coe_to_submodule_eq_iff, exact submodule.comap_subtype_self _, }
@[simp] lemma ker_incl : I.incl.ker = β₯ :=
by rw [β lie_submodule.coe_to_submodule_eq_iff, I.incl.ker_coe_submodule,
lie_submodule.bot_coe_submodule, incl_coe, submodule.ker_subtype]
@[simp] lemma incl_ideal_range : I.incl.ideal_range = I :=
begin
rw [lie_hom.ideal_range_eq_lie_span_range, β lie_subalgebra.coe_to_submodule,
β lie_submodule.coe_to_submodule_eq_iff, incl_range, coe_to_lie_subalgebra_to_submodule,
lie_submodule.coe_lie_span_submodule_eq_iff],
use I,
end
lemma incl_is_ideal_morphism : I.incl.is_ideal_morphism :=
begin
rw [I.incl.is_ideal_morphism_def, incl_ideal_range],
exact (I : lie_subalgebra R L).incl_range.symm,
end
end lie_ideal
end lie_submodule_map_and_comap
namespace lie_module_hom
variables {R : Type u} {L : Type v} {M : Type w} {N : Type wβ}
variables [comm_ring R] [lie_ring L] [lie_algebra R L]
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
variables [add_comm_group N] [module R N] [lie_ring_module L N] [lie_module R L N]
variables (f : M βββ
R,Lβ N)
/-- The range of a morphism of Lie modules `f : M β N` is a Lie submodule of `N`.
See Note [range copy pattern]. -/
def range : lie_submodule R L N :=
(lie_submodule.map f β€).copy (set.range f) set.image_univ.symm
@[simp] lemma coe_range : (f.range : set N) = set.range f := rfl
@[simp] lemma coe_submodule_range : (f.range : submodule R N) = (f : M ββ[R] N).range := rfl
@[simp] lemma mem_range (n : N) : n β f.range β β m, f m = n :=
iff.rfl
lemma map_top : lie_submodule.map f β€ = f.range :=
by { ext, simp [lie_submodule.mem_map], }
end lie_module_hom
section top_equiv_self
variables {R : Type u} {L : Type v}
variables [comm_ring R] [lie_ring L] [lie_algebra R L]
/-- The natural equivalence between the 'top' Lie subalgebra and the enclosing Lie algebra. -/
def lie_subalgebra.top_equiv_self : (β€ : lie_subalgebra R L) βββ
Rβ L :=
{ inv_fun := Ξ» x, β¨x, set.mem_univ xβ©,
left_inv := Ξ» x, by { ext, refl, },
right_inv := Ξ» x, rfl,
..(β€ : lie_subalgebra R L).incl, }
@[simp] lemma lie_subalgebra.top_equiv_self_apply (x : (β€ : lie_subalgebra R L)) :
lie_subalgebra.top_equiv_self x = x := rfl
/-- The natural equivalence between the 'top' Lie ideal and the enclosing Lie algebra. -/
def lie_ideal.top_equiv_self : (β€ : lie_ideal R L) βββ
Rβ L :=
lie_subalgebra.top_equiv_self
@[simp] lemma lie_ideal.top_equiv_self_apply (x : (β€ : lie_ideal R L)) :
lie_ideal.top_equiv_self x = x := rfl
end top_equiv_self
|
Interactive Voice Response (IVR) transaction processing reduces your PCI scope over-the-phone payments. Fully customizable and available in different languages, Bankcard Associates IVR acts as a phone-based payment acceptance application that ensures the safety of sensitive customer payment information.
Processing payments just got easier with Bankcard Associates IVR systems, which allow merchants to accept credit cards and manage the payment process through a touch tone phone. Merchants on the go can receive real-time credit card payments in a mobile environment, processing credit cards quickly and easily without the need for an Internet connection or credit card terminal.
With Bankcard Associates IVR capabilities, customers can make payments, check balances and manage accounts from their touchstone phone. Paying bills becomes quick and easy, eliminating lengthy on-hold times for improved customer service. When customers can make credit card payments without the need for an Internet connection, they can pay wherever they go and minimize late payments. Multiple language capabilities simplify the process and ensure clear communication.
At Bankcard Associates, we go to great lengths to protect your business, your customers and sensitive data. Our IVR systems work seamlessly with our PCI certified payment gateway, processing credit cards safely while reducing the risk of credit card fraud.
Customer calls in to a number listed on merchants website/bill to make a payment or Customer Service Agent transfers call to IVR to make payment.
That Phone number is hosted on our gateway server.
IVR digitally connects to the Gateway to securely process the transaction and tokenize the sensitive payment data.
The payment processes securely. Gateway digitally connects to the merchants accounting system or website to return the token and truncated payment data. The transaction can be confirmed in one of three ways.
Real-Time Response: Instant notification to merchants system, confirming payment has been made.
You can reach us at 1-800-921-9584 or you may use the contact form below.
Since BA introduced us to debit technology and low rates, our processing expenses have decreased by 40% and revenues have increased by 20%.
Our experience with BA has been extraordinary. We found the staff to be professional and attentive to our needs. BA has been a valuable member of the Landscape Warehouse team. Thank you BA!
Bankcard Associates, LLC is a registered ISO of Wells Fargo Bank, N.A., Walnut Creek, CA.
Copyright Β© 2004 - 2014 Bankcard Associates LLC, All Rights Reserved.
|
= = = = 2007 = = = =
|
import numpy as np
def explicit_euler(ode_func, y0, x0, stepsize, x_end):
"""
Calculate numeric solution at each step to an ODE using Euler's Method
https://en.wikipedia.org/wiki/Euler_method
Arguments:
ode_func -- The ode as a function of x and y
y0 -- the initial value for y
x0 -- the initial value for x
stepsize -- the increment value for x
x_end -- the end value for x
>>> # the exact solution is math.exp(x)
>>> def f(x, y):
... return y
>>> y0 = 1
>>> y = explicit_euler(f, y0, 0.0, 0.01, 5)
>>> y[-1]
144.77277243257308
"""
N = int(np.ceil((x_end - x0) / stepsize))
y = np.zeros((N + 1,))
y[0] = y0
x = x0
for k in range(N):
y[k + 1] = y[k] + stepsize * ode_func(x, y[k])
x += stepsize
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
|
theory Analyze_Ringofsaturn_com
imports
"../../Primitive_Matchers/Parser"
begin
section\<open>Example: ringofsaturn.com\<close>
(* Based on <http://networking.ringofsaturn.com/Unix/iptables.php> *)
(* Archived at <https://archive.today/3c309> *)
parse_iptables_save saturn_fw="iptables-save"
thm saturn_fw_def
text\<open>The Firewall\<close>
text\<open>Infix pretty-printing for @{const MatchAnd} and @{const MatchNot}.\<close>
abbreviation MatchAndInfix :: "'a match_expr \<Rightarrow> 'a match_expr \<Rightarrow> 'a match_expr" (infixr "MATCHAND" 65) where
"MatchAndInfix m1 m2 \<equiv> MatchAnd m1 m2"
abbreviation MatchNotPrefix :: "'a match_expr \<Rightarrow> 'a match_expr" ("\<not> \<langle>_\<rangle>" 66) where
"MatchNotPrefix m \<equiv> MatchNot m"
(*This syntax can be pretty confusing when mixing it with other theories. Do not use outside this example!*)
value[code] "unfold_ruleset_INPUT saturn_fw_INPUT_default_policy (map_of_string_ipv4 saturn_fw)"
lemma "unfold_ruleset_INPUT saturn_fw_INPUT_default_policy (map_of_string_ipv4 saturn_fw) =
[Rule (Match (CT_State {CT_Related, CT_Established})) action.Accept,
Rule (Match (CT_State {CT_New})) action.Accept,
Rule (Match (Prot (Proto TCP))) action.Drop,
Rule (Match (Prot (Proto UDP))) action.Drop,
Rule MatchAny action.Drop,
Rule (Match (IIface (Iface ''lo''))) action.Accept,
Rule ((Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (0, 0, 0, 0)) 8)) MATCHAND Match (IIface (Iface ''eth0''))) MATCHAND Match (Prot (Proto TCP)))
action.Drop,
Rule ((Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (0, 0, 0, 0)) 8)) MATCHAND Match (IIface (Iface ''eth0''))) MATCHAND Match (Prot (Proto UDP)))
action.Drop,
Rule (Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (0, 0, 0, 0)) 8)) MATCHAND Match (IIface (Iface ''eth0''))) action.Drop,
Rule ((Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (10, 0, 0, 0)) 8)) MATCHAND Match (IIface (Iface ''eth0''))) MATCHAND Match (Prot (Proto TCP)))
action.Drop,
Rule ((Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (10, 0, 0, 0)) 8)) MATCHAND Match (IIface (Iface ''eth0''))) MATCHAND Match (Prot (Proto UDP)))
action.Drop,
Rule (Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (10, 0, 0, 0)) 8)) MATCHAND Match (IIface (Iface ''eth0''))) action.Drop,
Rule ((Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (127, 0, 0, 0)) 8)) MATCHAND Match (IIface (Iface ''eth0''))) MATCHAND Match (Prot (Proto TCP)))
action.Drop,
Rule ((Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (127, 0, 0, 0)) 8)) MATCHAND Match (IIface (Iface ''eth0''))) MATCHAND Match (Prot (Proto UDP)))
action.Drop,
Rule (Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (127, 0, 0, 0)) 8)) MATCHAND Match (IIface (Iface ''eth0''))) action.Drop,
Rule ((Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (169, 254, 0, 0)) 16)) MATCHAND Match (IIface (Iface ''eth0''))) MATCHAND Match (Prot (Proto TCP)))
action.Drop,
Rule ((Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (169, 254, 0, 0)) 16)) MATCHAND Match (IIface (Iface ''eth0''))) MATCHAND Match (Prot (Proto UDP)))
action.Drop,
Rule (Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (169, 254, 0, 0)) 16)) MATCHAND Match (IIface (Iface ''eth0''))) action.Drop,
Rule ((Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (172, 16, 0, 0)) 12)) MATCHAND Match (IIface (Iface ''eth0''))) MATCHAND Match (Prot (Proto TCP)))
action.Drop,
Rule ((Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (172, 16, 0, 0)) 12)) MATCHAND Match (IIface (Iface ''eth0''))) MATCHAND Match (Prot (Proto UDP)))
action.Drop,
Rule (Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (172, 16, 0, 0)) 12)) MATCHAND Match (IIface (Iface ''eth0''))) action.Drop,
Rule ((Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (224, 0, 0, 0)) 3)) MATCHAND Match (IIface (Iface ''eth0''))) MATCHAND Match (Prot (Proto TCP)))
action.Drop,
Rule ((Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (224, 0, 0, 0)) 3)) MATCHAND Match (IIface (Iface ''eth0''))) MATCHAND Match (Prot (Proto UDP)))
action.Drop,
Rule (Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (224, 0, 0, 0)) 3)) MATCHAND Match (IIface (Iface ''eth0''))) action.Drop,
Rule ((Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (240, 0, 0, 0)) 8)) MATCHAND Match (IIface (Iface ''eth0''))) MATCHAND Match (Prot (Proto TCP)))
action.Drop,
Rule ((Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (240, 0, 0, 0)) 8)) MATCHAND Match (IIface (Iface ''eth0''))) MATCHAND Match (Prot (Proto UDP)))
action.Drop,
Rule (Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (240, 0, 0, 0)) 8)) MATCHAND Match (IIface (Iface ''eth0''))) action.Drop,
Rule (Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (160, 86, 0, 0)) 16)) MATCHAND Match (IIface (Iface ''eth1''))) action.Accept,
Rule (Match (IIface (Iface ''eth1''))) action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto ICMP)) MATCHAND Match (Extra ''-m icmp --icmp-type 3'')) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto ICMP)) MATCHAND Match (Extra ''-m icmp --icmp-type 11'')) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto ICMP)) MATCHAND Match (Extra ''-m icmp --icmp-type 0'')) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto ICMP)) MATCHAND Match (Extra ''-m icmp --icmp-type 8'')) action.Accept,
Rule (Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(0x6F, 0x6F)]))) action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(0x71, 0x71)]))) action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(4, 4)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(0x14, 0x14)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(0x15, 0x15)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Dst_Ports (L4Ports UDP [(0x14, 0x14)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Dst_Ports (L4Ports UDP [(0x15, 0x15)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(0x16, 0x16)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Dst_Ports (L4Ports UDP [(0x16, 0x16)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(0x50, 0x50)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Dst_Ports (L4Ports UDP [(0x50, 0x50)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(0x1BB, 0x1BB)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Dst_Ports (L4Ports UDP [(0x1BB, 0x1BB)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Dst_Ports (L4Ports UDP [(0x208, 0x208)]))) action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(0x89, 0x8B)]))) action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Dst_Ports (L4Ports UDP [(0x89, 0x8B)]))) action.Drop,
Rule (Match (Prot (Proto TCP))) action.Drop,
Rule (Match (Prot (Proto UDP))) action.Drop,
Rule MatchAny action.Drop,
Rule MatchAny action.Accept]" by eval
lemma "good_ruleset (unfold_ruleset_INPUT saturn_fw_INPUT_default_policy (map_of_string_ipv4 saturn_fw))" by eval
lemma "simple_ruleset (unfold_ruleset_INPUT saturn_fw_INPUT_default_policy (map_of_string_ipv4 saturn_fw))" by eval
text\<open>Basically, it accepts everything\<close>
lemma "take 2 (unfold_ruleset_INPUT saturn_fw_INPUT_default_policy (map_of_string_ipv4 saturn_fw)) =
[Rule (Match (CT_State {CT_Related, CT_Established})) action.Accept, Rule (Match (CT_State {CT_New})) action.Accept]" by eval
text\<open>The upper closure\<close>
value[code] "upper_closure (unfold_ruleset_INPUT saturn_fw_INPUT_default_policy (map_of_string_ipv4 saturn_fw))"
lemma upper: "upper_closure (unfold_ruleset_INPUT saturn_fw_INPUT_default_policy (map_of_string_ipv4 saturn_fw)) =
[Rule (Match (CT_State {CT_Related, CT_Established})) action.Accept,
Rule (Match (CT_State {CT_New})) action.Accept,
Rule (Match (Prot (Proto TCP))) action.Drop,
Rule (Match (Prot (Proto UDP))) action.Drop,
Rule MatchAny action.Drop
]"
by eval
text\<open>The firewall accepts all NEW packets\<close>
lemma "cut_off_after_match_any (rmMatchFalse (ctstate_assume_new
(unfold_ruleset_INPUT saturn_fw_INPUT_default_policy (map_of_string_ipv4 saturn_fw))))
= [Rule MatchAny action.Accept]"
by eval
text\<open>The firewall also accepts all ESTABLISHED packets. Essentially, it accepts all packets!\<close>
lemma "cut_off_after_match_any (rmMatchFalse (optimize_matches (ctstate_assume_state CT_Established)
(unfold_ruleset_INPUT saturn_fw_INPUT_default_policy (map_of_string_ipv4 saturn_fw))))
= [Rule MatchAny action.Accept]"
by eval
lemma "approximating_bigstep_fun (common_matcher, in_doubt_allow)
\<lparr>p_iiface = ''eth0'', p_oiface = ''eth1'',
p_src = ipv4addr_of_dotdecimal (192,168,2,45), p_dst= ipv4addr_of_dotdecimal (173,194,112,111),
p_proto=TCP, p_sport=2065, p_dport=80, p_tcp_flags = {TCP_SYN},
p_payload='''', p_tag_ctstate = CT_New\<rparr>
(unfold_ruleset_INPUT saturn_fw_INPUT_default_policy (map_of_string_ipv4 saturn_fw))
Undecided
= Decision FinalAllow" by eval
text\<open>We are removing the first call to the @{term "''STATEFUL''"} chain.\<close>
definition "saturn_fw_2 = map (\<lambda> (decl, rs). if decl = ''INPUT'' then (decl, remove1 (Rule MatchAny (Call ''STATEFUL'')) rs) else (decl, rs)) saturn_fw"
lemma "tl (the ((map_of_string_ipv4 saturn_fw) ''INPUT'')) = the ((map_of_string_ipv4 saturn_fw_2) ''INPUT'')" by eval
text\<open>in doubt allow closure\<close>
definition "upper = upper_closure (unfold_ruleset_INPUT saturn_fw_INPUT_default_policy (map_of_string_ipv4 saturn_fw_2))"
text\<open>Now the upper closure looks as expected\<close>
lemma "upper =
[Rule (Match (IIface (Iface ''lo''))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Src (IpAddrNetmask 0 8)))
action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (0, 0, 0, 0)) 8)))
action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (0, 0, 0, 0)) 8))) action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (10, 0, 0, 0)) 8)))
action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (10, 0, 0, 0)) 8)))
action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (10, 0, 0, 0)) 8))) action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (127, 0, 0, 0)) 8)))
action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (127, 0, 0, 0)) 8)))
action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (127, 0, 0, 0)) 8))) action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (169, 254, 0, 0)) 16)))
action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (169, 254, 0, 0)) 16)))
action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (169, 254, 0, 0)) 16))) action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (172, 16, 0, 0)) 12)))
action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (172, 16, 0, 0)) 12)))
action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (172, 16, 0, 0)) 12))) action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (224, 0, 0, 0)) 3)))
action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (224, 0, 0, 0)) 3)))
action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (224, 0, 0, 0)) 3))) action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (240, 0, 0, 0)) 8)))
action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (240, 0, 0, 0)) 8)))
action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (240, 0, 0, 0)) 8))) action.Drop,
Rule (Match (IIface (Iface ''eth1'')) MATCHAND Match (Src (IpAddrNetmask (ipv4addr_of_dotdecimal (160, 86, 0, 0)) 16))) action.Accept,
Rule (Match (IIface (Iface ''eth1''))) action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto ICMP))) action.Accept,
Rule (Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(0x6F, 0x6F)]))) action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(0x71, 0x71)]))) action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(4, 4)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(0x14, 0x14)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(0x15, 0x15)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP))MATCHAND Match (Dst_Ports (L4Ports UDP [(0x14, 0x14)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Dst_Ports (L4Ports UDP [(0x15, 0x15)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(0x16, 0x16)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Dst_Ports (L4Ports UDP [(0x16, 0x16)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(0x50, 0x50)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Dst_Ports (L4Ports UDP [(0x50, 0x50)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(0x1BB, 0x1BB)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Dst_Ports (L4Ports UDP [(0x1BB, 0x1BB)]))) action.Accept,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Dst_Ports (L4Ports UDP [(0x208, 0x208)]))) action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto TCP)) MATCHAND Match (Dst_Ports (L4Ports TCP [(0x89, 0x8B)]))) action.Drop,
Rule (Match (IIface (Iface ''eth0'')) MATCHAND Match (Prot (Proto UDP)) MATCHAND Match (Dst_Ports (L4Ports UDP [(0x89, 0x8B)]))) action.Drop,
Rule (Match (Prot (Proto TCP))) action.Drop,
Rule (Match (Prot (Proto UDP))) action.Drop,
Rule MatchAny action.Drop
]" by eval
value[code] "zip (upto 0 (int (length upper))) upper"
lemma "good_ruleset upper" by eval
lemma "simple_ruleset upper" by eval
lemma "check_simple_fw_preconditions upper \<and> simple_fw_valid (to_simple_firewall upper)" by eval
value "map simple_rule_ipv4_toString (to_simple_firewall upper)"
text\<open>in doubt deny closure\<close>
value[code] "lower_closure (unfold_ruleset_INPUT saturn_fw_INPUT_default_policy (map_of_string_ipv4 saturn_fw_2))"
lemma "simple_fw_valid (to_simple_firewall upper)" by eval
lemma "simple_fw_valid (to_simple_firewall (lower_closure
(unfold_ruleset_INPUT saturn_fw_INPUT_default_policy (map_of_string_ipv4 saturn_fw_2))))" by eval
end
|
proposition locally_connected_im_kleinen: "locally connected S \<longleftrightarrow> (\<forall>v x. openin (top_of_set S) v \<and> x \<in> v \<longrightarrow> (\<exists>u. openin (top_of_set S) u \<and> x \<in> u \<and> u \<subseteq> v \<and> (\<forall>y. y \<in> u \<longrightarrow> (\<exists>c. connected c \<and> c \<subseteq> v \<and> x \<in> c \<and> y \<in> c))))" (is "?lhs = ?rhs")
|
module Control.Comonad
import Control.Monad.Identity
import Data.List1
import Data.Morphisms
import Data.Stream
%default total
--------------------------------------------------------------------------------
-- Comonad
--------------------------------------------------------------------------------
public export
interface Functor w => Comonad w where
extract : w a -> a
duplicate : w a -> w (w a)
duplicate = extend id
extend : (w a -> b) -> w a -> w b
extend f = map f . duplicate
--------------------------------------------------------------------------------
-- Comonad Implementations
--------------------------------------------------------------------------------
public export
Comonad (Pair e) where
extract = snd
duplicate (e,a) = (e, (e, a))
public export
Comonad Identity where
extract = runIdentity
duplicate = Id
public export
Comonad Stream where
extract = head
duplicate xs@(_ :: t) = xs :: duplicate t
public export
Comonad List1 where
extract = head
duplicate (x ::: xs) = (x ::: xs) ::: tails xs
where tails : List a -> List (List1 a)
tails [] = []
tails (x :: xs) = (x ::: xs) :: tails xs
public export
Monoid e => Comonad (Morphism e) where
extract (Mor f) = f neutral
duplicate (Mor f) = Mor $ \e => Mor (\e' => f (e <+> e'))
--------------------------------------------------------------------------------
-- ComonadApply
--------------------------------------------------------------------------------
infixl 4 <@, @>, <@@>, <@>
public export
interface Comonad w => ComonadApply w where
(<@>) : w (a -> b) -> w a -> w b
(@>) : w a -> w b -> w b
(@>) = flip (<@)
(<@) : w a -> w b -> w a
a <@ b = map const a <@> b
--------------------------------------------------------------------------------
-- ComonadApply Implementations
--------------------------------------------------------------------------------
public export
Semigroup m => ComonadApply (Pair m) where
(m, f) <@> (n, a) = (m <+> n, f a)
(m, a) <@ (n, _) = (m <+> n, a)
(m, _) @> (n, b) = (m <+> n, b)
public export
ComonadApply List1 where
(<@>) = (<*>)
public export
ComonadApply Stream where
(<@>) = (<*>)
public export
Monoid m => ComonadApply (Morphism m) where
(<@>) = (<*>)
public export
ComonadApply Identity where
(<@>) = (<*>)
_ @> b = b
b <@ _ = b
--------------------------------------------------------------------------------
-- Utilities
--------------------------------------------------------------------------------
infixl 1 =>>
infixr 1 <<=, =<=, =>=
||| `extend` with the arguments swapped. Dual to `>>=` for a `Monad`.
public export %inline
(=>>) : Comonad w => w a -> (w a -> b) -> w b
(=>>) = flip extend
||| `extend` in operator form
public export %inline
(<<=) : Comonad w => (w a -> b) -> w a -> w b
(<<=) = extend
||| Right-to-left `Cokleisli` composition
public export %inline
(=<=) : Comonad w => (w b -> c) -> (w a -> b) -> w a -> c
f =<= g = f . extend g
||| Left-to-right `Cokleisli` composition
public export %inline
(=>=) : Comonad w => (w a -> b) -> (w b -> c) -> w a -> c
f =>= g = g . extend f
||| Flipped version of `<@>`.
public export %inline
(<@@>) : ComonadApply w => w a -> w (a -> b) -> w b
(<@@>) = flip (<@>)
|
%%*****************************************************************
%% sqlptermcode.m: explains the termination code in sqlp.m
%%*****************************************************************
%% SDPT3: version 4.0
%% Copyright (c) 1997 by
%% Kim-Chuan Toh, Michael J. Todd, Reha H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*****************************************************************
function termcode = sqlptermcode;
fprintf('\n 3: norm(X) or norm(Z) diverging');
fprintf('\n 2: dual problem is suspected to be infeasible')
fprintf('\n 1: primal problem is suspected to be infeasible')
fprintf('\n 0: max(relative gap,infeasibility) < gaptol');
fprintf('\n -1: relative gap < infeasibility');
fprintf('\n -2: lack of progress in predictor or corrector');
fprintf('\n -3: X or Z not positive definite');
fprintf('\n -4: difficulty in computing predictor or corrector direction');
fprintf('\n -5: progress in relative gap or infeasibility is bad');
fprintf('\n -6: maximum number of iterations reached');
fprintf('\n -7: primal infeasibility has deteriorated too much');
fprintf('\n -8: progress in relative gap has deteriorated');
fprintf('\n -9: lack of progress in infeasibility');
fprintf('\n')
%%*************************************************************************
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.