text
stringlengths 0
3.34M
|
---|
lemma infnorm_mul_lemma: "infnorm (a *\<^sub>R x) \<le> \<bar>a\<bar> * infnorm x" |
Formal statement is: lemma is_interval_cbox [simp]: "is_interval (cbox a (b::'a::euclidean_space))" (is ?th1) and is_interval_box [simp]: "is_interval (box a b)" (is ?th2) Informal statement is: The closed box $[a,b]$ and the open box $(a,b)$ are intervals. |
Sean Connery 's then wife Diane Cilento did the swimming scenes for at least five Japanese actresses , including Mie Hama . Martial arts expert Donn F. <unk> provided martial arts training , and also doubled for Connery . Lewis Gilbert 's regular editor , Thelma Connell , was originally hired to edit the film . However , after her initial , almost three @-@ hour cut received a terrible response from test audiences , Peter R. Hunt was asked to re @-@ edit the film . Hunt 's cut proved a much greater success , and he was awarded the director 's chair on the next film as a result .
|
[STATEMENT]
lemma DmdBoxDmd: "\<turnstile> (\<diamond>\<box>\<diamond>F) = (\<box>\<diamond>F)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<turnstile> (\<diamond>\<box>\<diamond>F) = (\<box>\<diamond>F)
[PROOF STEP]
apply (unfold dmd_def)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<turnstile> (\<not> \<box>\<not> \<box>\<not> \<box>\<not> F) = (\<box>\<not> \<box>\<not> F)
[PROOF STEP]
apply (auto simp: BoxDmdBox [unfolded dmd_def, try_rewrite])
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
[STATEMENT]
lemma permutations_complete: (* could generalize with multi-sets *)
assumes "distinct xs" "distinct ys" "set xs = set ys"
shows "ys \<in> set (permutations xs)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ys \<in> set (permutations xs)
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
distinct xs
distinct ys
set xs = set ys
goal (1 subgoal):
1. ys \<in> set (permutations xs)
[PROOF STEP]
proof (induct "length xs" arbitrary: xs ys)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>xs ys. \<lbrakk>0 = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs)
2. \<And>x xs ys. \<lbrakk>\<And>xs ys. \<lbrakk>x = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs); Suc x = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs)
[PROOF STEP]
case 0
[PROOF STATE]
proof (state)
this:
0 = length xs
distinct xs
distinct ys
set xs = set ys
goal (2 subgoals):
1. \<And>xs ys. \<lbrakk>0 = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs)
2. \<And>x xs ys. \<lbrakk>\<And>xs ys. \<lbrakk>x = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs); Suc x = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs)
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
0 = length xs
distinct xs
distinct ys
set xs = set ys
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
0 = length xs
distinct xs
distinct ys
set xs = set ys
goal (1 subgoal):
1. ys \<in> set (permutations xs)
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
ys \<in> set (permutations xs)
goal (1 subgoal):
1. \<And>x xs ys. \<lbrakk>\<And>xs ys. \<lbrakk>x = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs); Suc x = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs)
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x xs ys. \<lbrakk>\<And>xs ys. \<lbrakk>x = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs); Suc x = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs)
[PROOF STEP]
case (Suc n)
[PROOF STATE]
proof (state)
this:
\<lbrakk>n = length ?xs; distinct ?xs; distinct ?ys; set ?xs = set ?ys\<rbrakk> \<Longrightarrow> ?ys \<in> set (permutations ?xs)
Suc n = length xs
distinct xs
distinct ys
set xs = set ys
goal (1 subgoal):
1. \<And>x xs ys. \<lbrakk>\<And>xs ys. \<lbrakk>x = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs); Suc x = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs)
[PROOF STEP]
from Suc.hyps
[PROOF STATE]
proof (chain)
picking this:
\<lbrakk>n = length ?xs; distinct ?xs; distinct ?ys; set ?xs = set ?ys\<rbrakk> \<Longrightarrow> ?ys \<in> set (permutations ?xs)
Suc n = length xs
[PROOF STEP]
have "xs \<noteq> []"
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>n = length ?xs; distinct ?xs; distinct ?ys; set ?xs = set ?ys\<rbrakk> \<Longrightarrow> ?ys \<in> set (permutations ?xs)
Suc n = length xs
goal (1 subgoal):
1. xs \<noteq> []
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
xs \<noteq> []
goal (1 subgoal):
1. \<And>x xs ys. \<lbrakk>\<And>xs ys. \<lbrakk>x = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs); Suc x = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs)
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
xs \<noteq> []
[PROOF STEP]
obtain y ys' where [simp]: "ys = y # ys'" "y \<in> set xs"
[PROOF STATE]
proof (prove)
using this:
xs \<noteq> []
goal (1 subgoal):
1. (\<And>y ys'. \<lbrakk>ys = y # ys'; y \<in> set xs\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using Suc.prems
[PROOF STATE]
proof (prove)
using this:
xs \<noteq> []
distinct xs
distinct ys
set xs = set ys
goal (1 subgoal):
1. (\<And>y ys'. \<lbrakk>ys = y # ys'; y \<in> set xs\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (cases ys) auto
[PROOF STATE]
proof (state)
this:
ys = y # ys'
y \<in> set xs
goal (1 subgoal):
1. \<And>x xs ys. \<lbrakk>\<And>xs ys. \<lbrakk>x = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs); Suc x = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs)
[PROOF STEP]
have "ys' \<in> set (permutations (remove1 y xs))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. ys' \<in> set (permutations (remove1 y xs))
[PROOF STEP]
using Suc.prems \<open>Suc n = _\<close>
[PROOF STATE]
proof (prove)
using this:
distinct xs
distinct ys
set xs = set ys
Suc n = length xs
goal (1 subgoal):
1. ys' \<in> set (permutations (remove1 y xs))
[PROOF STEP]
by (intro Suc.hyps) (simp_all add: length_remove1 )
[PROOF STATE]
proof (state)
this:
ys' \<in> set (permutations (remove1 y xs))
goal (1 subgoal):
1. \<And>x xs ys. \<lbrakk>\<And>xs ys. \<lbrakk>x = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs); Suc x = length xs; distinct xs; distinct ys; set xs = set ys\<rbrakk> \<Longrightarrow> ys \<in> set (permutations xs)
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
ys' \<in> set (permutations (remove1 y xs))
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
ys' \<in> set (permutations (remove1 y xs))
goal (1 subgoal):
1. ys \<in> set (permutations xs)
[PROOF STEP]
using \<open>xs \<noteq> []\<close>
[PROOF STATE]
proof (prove)
using this:
ys' \<in> set (permutations (remove1 y xs))
xs \<noteq> []
goal (1 subgoal):
1. ys \<in> set (permutations xs)
[PROOF STEP]
by (auto simp: set_permutations_step)
[PROOF STATE]
proof (state)
this:
ys \<in> set (permutations xs)
goal:
No subgoals!
[PROOF STEP]
qed |
(* Copyright (c) 2009-2012, 2015, Adam Chlipala
*
* This work is licensed under a
* Creative Commons Attribution-Noncommercial-No Derivative Works 3.0
* Unported License.
* The license text is available at:
* http://creativecommons.org/licenses/by-nc-nd/3.0/
*)
(* begin hide *)
Require Import List Lia.
Hint Extern 2 False => lia.
Hint Extern 2 (@eq nat _ _) => lia.
Require Import DepList Cpdt.CpdtTactics.
Require Extraction.
Set Implicit Arguments.
Set Asymmetric Patterns.
(* end hide *)
(** printing $ %({}*% #(<a/>*# *)
(** printing ^ %*{})% #*<a/>)# *)
(** %\chapter{Universes and Axioms}% *)
(** Many traditional theorems can be proved in Coq without special knowledge of CIC, the logic behind the prover. A development just seems to be using a particular ASCII notation for standard formulas based on %\index{set theory}%set theory. Nonetheless, as we saw in Chapter 4, CIC differs from set theory in starting from fewer orthogonal primitives. It is possible to define the usual logical connectives as derived notions. The foundation of it all is a dependently typed functional programming language, based on dependent function types and inductive type families. By using the facilities of this language directly, we can accomplish some things much more easily than in mainstream math.
%\index{Gallina}%Gallina, which adds features to the more theoretical CIC%~\cite{CIC}%, is the logic implemented in Coq. It has a relatively simple foundation that can be defined rigorously in a page or two of formal proof rules. Still, there are some important subtleties that have practical ramifications. This chapter focuses on those subtleties, avoiding formal metatheory in favor of example code. *)
(** * The [Type] Hierarchy *)
(** %\index{type hierarchy}%Every object in Gallina has a type. *)
Check 0.
(** %\vspace{-.15in}% [[
0
: nat
]]
It is natural enough that zero be considered as a natural number. *)
Check nat.
(** %\vspace{-.15in}% [[
nat
: Set
]]
From a set theory perspective, it is unsurprising to consider the natural numbers as a "set." *)
Check Set.
(** %\vspace{-.15in}% [[
Set
: Type
]]
The type [Set] may be considered as the set of all sets, a concept that set theory handles in terms of%\index{class (in set theory)}% _classes_. In Coq, this more general notion is [Type]. *)
Check Type.
(** %\vspace{-.15in}% [[
Type
: Type
]]
Strangely enough, [Type] appears to be its own type. It is known that polymorphic languages with this property are inconsistent, via %\index{Girard's paradox}%Girard's paradox%~\cite{GirardsParadox}%. That is, using such a language to encode proofs is unwise, because it is possible to "prove" any proposition. What is really going on here?
Let us repeat some of our queries after toggling a flag related to Coq's printing behavior.%\index{Vernacular commands!Set Printing Universes}% *)
Set Printing Universes.
Check nat.
(** %\vspace{-.15in}% [[
nat
: Set
]]
*)
Check Set.
(** %\vspace{-.15in}% [[
Set
: Type $ (0)+1 ^
]]
*)
Check Type.
(** %\vspace{-.15in}% [[
Type $ Top.3 ^
: Type $ (Top.3)+1 ^
]]
Occurrences of [Type] are annotated with some additional information, inside comments. These annotations have to do with the secret behind [Type]: it really stands for an infinite hierarchy of types. The type of [Set] is [Type(0)], the type of [Type(0)] is [Type(1)], the type of [Type(1)] is [Type(2)], and so on. This is how we avoid the "[Type : Type]" paradox. As a convenience, the universe hierarchy drives Coq's one variety of subtyping. Any term whose type is [Type] at level [i] is automatically also described by [Type] at level [j] when [j > i].
In the outputs of our first [Check] query, we see that the type level of [Set]'s type is [(0)+1]. Here [0] stands for the level of [Set], and we increment it to arrive at the level that _classifies_ [Set].
In the third query's output, we see that the occurrence of [Type] that we check is assigned a fresh%\index{universe variable}% _universe variable_ [Top.3]. The output type increments [Top.3] to move up a level in the universe hierarchy. As we write code that uses definitions whose types mention universe variables, unification may refine the values of those variables. Luckily, the user rarely has to worry about the details.
Another crucial concept in CIC is%\index{predicativity}% _predicativity_. Consider these queries. *)
Check forall T : nat, fin T.
(** %\vspace{-.15in}% [[
forall T : nat, fin T
: Set
]]
*)
Check forall T : Set, T.
(** %\vspace{-.15in}% [[
forall T : Set, T
: Type $ max(0, (0)+1) ^
]]
*)
Check forall T : Type, T.
(** %\vspace{-.15in}% [[
forall T : Type $ Top.9 ^ , T
: Type $ max(Top.9, (Top.9)+1) ^
]]
These outputs demonstrate the rule for determining which universe a [forall] type lives in. In particular, for a type [forall x : T1, T2], we take the maximum of the universes of [T1] and [T2]. In the first example query, both [T1] ([nat]) and [T2] ([fin T]) are in [Set], so the [forall] type is in [Set], too. In the second query, [T1] is [Set], which is at level [(0)+1]; and [T2] is [T], which is at level [0]. Thus, the [forall] exists at the maximum of these two levels. The third example illustrates the same outcome, where we replace [Set] with an occurrence of [Type] that is assigned universe variable [Top.9]. This universe variable appears in the places where [0] appeared in the previous query.
The behind-the-scenes manipulation of universe variables gives us predicativity. Consider this simple definition of a polymorphic identity function, where the first argument [T] will automatically be marked as implicit, since it can be inferred from the type of the second argument [x]. *)
Definition id (T : Set) (x : T) : T := x.
Check id 0.
(** %\vspace{-.15in}% [[
id 0
: nat
Check id Set.
]]
<<
Error: Illegal application (Type Error):
...
The 1st term has type "Type (* (Top.15)+1 *)"
which should be coercible to "Set".
>>
The parameter [T] of [id] must be instantiated with a [Set]. The type [nat] is a [Set], but [Set] is not. We can try fixing the problem by generalizing our definition of [id]. *)
Reset id.
Definition id (T : Type) (x : T) : T := x.
Check id 0.
(** %\vspace{-.15in}% [[
id 0
: nat
]]
*)
Check id Set.
(** %\vspace{-.15in}% [[
id Set
: Type $ Top.17 ^
]]
*)
Check id Type.
(** %\vspace{-.15in}% [[
id Type $ Top.18 ^
: Type $ Top.19 ^
]]
*)
(** So far so good. As we apply [id] to different [T] values, the inferred index for [T]'s [Type] occurrence automatically moves higher up the type hierarchy.
[[
Check id id.
]]
<<
Error: Universe inconsistency (cannot enforce Top.16 < Top.16).
>>
%\index{universe inconsistency}%This error message reminds us that the universe variable for [T] still exists, even though it is usually hidden. To apply [id] to itself, that variable would need to be less than itself in the type hierarchy. Universe inconsistency error messages announce cases like this one where a term could only type-check by violating an implied constraint over universe variables. Such errors demonstrate that [Type] is _predicative_, where this word has a CIC meaning closely related to its usual mathematical meaning. A predicative system enforces the constraint that, when an object is defined using some sort of quantifier, none of the quantifiers may ever be instantiated with the object itself. %\index{impredicativity}%Impredicativity is associated with popular paradoxes in set theory, involving inconsistent constructions like "the set of all sets that do not contain themselves" (%\index{Russell's paradox}%Russell's paradox). Similar paradoxes would result from uncontrolled impredicativity in Coq. *)
(** ** Inductive Definitions *)
(** Predicativity restrictions also apply to inductive definitions. As an example, let us consider a type of expression trees that allows injection of any native Coq value. The idea is that an [exp T] stands for an encoded expression of type [T].
[[
Inductive exp : Set -> Set :=
| Const : forall T : Set, T -> exp T
| Pair : forall T1 T2, exp T1 -> exp T2 -> exp (T1 * T2)
| Eq : forall T, exp T -> exp T -> exp bool.
]]
<<
Error: Large non-propositional inductive types must be in Type.
>>
This definition is%\index{large inductive types}% _large_ in the sense that at least one of its constructors takes an argument whose type has type [Type]. Coq would be inconsistent if we allowed definitions like this one in their full generality. Instead, we must change [exp] to live in [Type]. We will go even further and move [exp]'s index to [Type] as well. *)
Inductive exp : Type -> Type :=
| Const : forall T, T -> exp T
| Pair : forall T1 T2, exp T1 -> exp T2 -> exp (T1 * T2)
| Eq : forall T, exp T -> exp T -> exp bool.
(** Note that before we had to include an annotation [: Set] for the variable [T] in [Const]'s type, but we need no annotation now. When the type of a variable is not known, and when that variable is used in a context where only types are allowed, Coq infers that the variable is of type [Type], the right behavior here, though it was wrong for the [Set] version of [exp].
Our new definition is accepted. We can build some sample expressions. *)
Check Const 0.
(** %\vspace{-.15in}% [[
Const 0
: exp nat
]]
*)
Check Pair (Const 0) (Const tt).
(** %\vspace{-.15in}% [[
Pair (Const 0) (Const tt)
: exp (nat * unit)
]]
*)
Check Eq (Const Set) (Const Type).
(** %\vspace{-.15in}% [[
Eq (Const Set) (Const Type $ Top.59 ^ )
: exp bool
]]
We can check many expressions, including fancy expressions that include types. However, it is not hard to hit a type-checking wall.
[[
Check Const (Const O).
]]
<<
Error: Universe inconsistency (cannot enforce Top.42 < Top.42).
>>
We are unable to instantiate the parameter [T] of [Const] with an [exp] type. To see why, it is helpful to print the annotated version of [exp]'s inductive definition. *)
(** [[
Print exp.
]]
%\vspace{-.15in}%[[
Inductive exp
: Type $ Top.8 ^ ->
Type
$ max(0, (Top.11)+1, (Top.14)+1, (Top.15)+1, (Top.19)+1) ^ :=
Const : forall T : Type $ Top.11 ^ , T -> exp T
| Pair : forall (T1 : Type $ Top.14 ^ ) (T2 : Type $ Top.15 ^ ),
exp T1 -> exp T2 -> exp (T1 * T2)
| Eq : forall T : Type $ Top.19 ^ , exp T -> exp T -> exp bool
]]
We see that the index type of [exp] has been assigned to universe level [Top.8]. In addition, each of the four occurrences of [Type] in the types of the constructors gets its own universe variable. Each of these variables appears explicitly in the type of [exp]. In particular, any type [exp T] lives at a universe level found by incrementing by one the maximum of the four argument variables. Therefore, [exp] _must_ live at a higher universe level than any type which may be passed to one of its constructors. This consequence led to the universe inconsistency.
Strangely, the universe variable [Top.8] only appears in one place. Is there no restriction imposed on which types are valid arguments to [exp]? In fact, there is a restriction, but it only appears in a global set of universe constraints that are maintained "off to the side," not appearing explicitly in types. We can print the current database.%\index{Vernacular commands!Print Universes}% *)
Print Universes.
(** %\vspace{-.15in}% [[
Top.19 < Top.9 <= Top.8
Top.15 < Top.9 <= Top.8 <= Coq.Init.Datatypes.38
Top.14 < Top.9 <= Top.8 <= Coq.Init.Datatypes.37
Top.11 < Top.9 <= Top.8
]]
The command outputs many more constraints, but we have collected only those that mention [Top] variables. We see one constraint for each universe variable associated with a constructor argument from [exp]'s definition. Universe variable [Top.19] is the type argument to [Eq]. The constraint for [Top.19] effectively says that [Top.19] must be less than [Top.8], the universe of [exp]'s indices; an intermediate variable [Top.9] appears as an artifact of the way the constraint was generated.
The next constraint, for [Top.15], is more complicated. This is the universe of the second argument to the [Pair] constructor. Not only must [Top.15] be less than [Top.8], but it also comes out that [Top.8] must be less than [Coq.Init.Datatypes.38]. What is this new universe variable? It is from the definition of the [prod] inductive family, to which types of the form [A * B] are desugared. *)
(* begin hide *)
(* begin thide *)
Inductive prod := pair.
Reset prod.
(* end thide *)
(* end hide *)
(** %\vspace{-.3in}%[[
Print prod.
]]
%\vspace{-.15in}%[[
Inductive prod (A : Type $ Coq.Init.Datatypes.37 ^ )
(B : Type $ Coq.Init.Datatypes.38 ^ )
: Type $ max(Coq.Init.Datatypes.37, Coq.Init.Datatypes.38) ^ :=
pair : A -> B -> A * B
]]
We see that the constraint is enforcing that indices to [exp] must not live in a higher universe level than [B]-indices to [prod]. The next constraint above establishes a symmetric condition for [A].
Thus it is apparent that Coq maintains a tortuous set of universe variable inequalities behind the scenes. It may look like some functions are polymorphic in the universe levels of their arguments, but what is really happening is imperative updating of a system of constraints, such that all uses of a function are consistent with a global set of universe levels. When the constraint system may not be evolved soundly, we get a universe inconsistency error.
%\medskip%
The annotated definition of [prod] reveals something interesting. A type [prod A B] lives at a universe that is the maximum of the universes of [A] and [B]. From our earlier experiments, we might expect that [prod]'s universe would in fact need to be _one higher_ than the maximum. The critical difference is that, in the definition of [prod], [A] and [B] are defined as _parameters_; that is, they appear named to the left of the main colon, rather than appearing (possibly unnamed) to the right.
Parameters are not as flexible as normal inductive type arguments. The range types of all of the constructors of a parameterized type must share the same parameters. Nonetheless, when it is possible to define a polymorphic type in this way, we gain the ability to use the new type family in more ways, without triggering universe inconsistencies. For instance, nested pairs of types are perfectly legal. *)
Check (nat, (Type, Set)).
(** %\vspace{-.15in}% [[
(nat, (Type $ Top.44 ^ , Set))
: Set * (Type $ Top.45 ^ * Type $ Top.46 ^ )
]]
The same cannot be done with a counterpart to [prod] that does not use parameters. *)
Inductive prod' : Type -> Type -> Type :=
| pair' : forall A B : Type, A -> B -> prod' A B.
(** %\vspace{-.15in}%[[
Check (pair' nat (pair' Type Set)).
]]
<<
Error: Universe inconsistency (cannot enforce Top.51 < Top.51).
>>
The key benefit parameters bring us is the ability to avoid quantifying over types in the types of constructors. Such quantification induces less-than constraints, while parameters only introduce less-than-or-equal-to constraints.
Coq includes one more (potentially confusing) feature related to parameters. While Gallina does not support real %\index{universe polymorphism}%universe polymorphism, there is a convenience facility that mimics universe polymorphism in some cases. We can illustrate what this means with a simple example. *)
Inductive foo (A : Type) : Type :=
| Foo : A -> foo A.
(* begin hide *)
Unset Printing Universes.
(* end hide *)
Check foo nat.
(** %\vspace{-.15in}% [[
foo nat
: Set
]]
*)
Check foo Set.
(** %\vspace{-.15in}% [[
foo Set
: Type
]]
*)
Check foo True.
(** %\vspace{-.15in}% [[
foo True
: Prop
]]
The basic pattern here is that Coq is willing to automatically build a "copied-and-pasted" version of an inductive definition, where some occurrences of [Type] have been replaced by [Set] or [Prop]. In each context, the type-checker tries to find the valid replacements that are lowest in the type hierarchy. Automatic cloning of definitions can be much more convenient than manual cloning. We have already taken advantage of the fact that we may re-use the same families of tuple and list types to form values in [Set] and [Type].
Imitation polymorphism can be confusing in some contexts. For instance, it is what is responsible for this weird behavior. *)
Inductive bar : Type := Bar : bar.
Check bar.
(** %\vspace{-.15in}% [[
bar
: Prop
]]
The type that Coq comes up with may be used in strictly more contexts than the type one might have expected. *)
(** ** Deciphering Baffling Messages About Inability to Unify *)
(** One of the most confusing sorts of Coq error messages arises from an interplay between universes, syntax notations, and %\index{implicit arguments}%implicit arguments. Consider the following innocuous lemma, which is symmetry of equality for the special case of types. *)
Theorem symmetry : forall A B : Type,
A = B
-> B = A.
intros ? ? H; rewrite H; reflexivity.
Qed.
(** Let us attempt an admittedly silly proof of the following theorem. *)
Theorem illustrative_but_silly_detour : unit = unit.
(** %\vspace{-.25in}%[[
apply symmetry.
]]
<<
Error: Impossible to unify "?35 = ?34" with "unit = unit".
>>
Coq tells us that we cannot, in fact, apply our lemma [symmetry] here, but the error message seems defective. In particular, one might think that [apply] should unify [?35] and [?34] with [unit] to ensure that the unification goes through. In fact, the issue is in a part of the unification problem that is _not_ shown to us in this error message!
The following command is the secret to getting better error messages in such cases:%\index{Vernacular commands!Set Printing All}% *)
Set Printing All.
(** %\vspace{-.15in}%[[
apply symmetry.
]]
<<
Error: Impossible to unify "@eq Type ?46 ?45" with "@eq Set unit unit".
>>
Now we can see the problem: it is the first, _implicit_ argument to the underlying equality function [eq] that disagrees across the two terms. The universe [Set] may be both an element and a subtype of [Type], but the two are not definitionally equal. *)
Abort.
(** A variety of changes to the theorem statement would lead to use of [Type] as the implicit argument of [eq]. Here is one such change. *)
Theorem illustrative_but_silly_detour : (unit : Type) = unit.
apply symmetry; reflexivity.
Qed.
(** There are many related issues that can come up with error messages, where one or both of notations and implicit arguments hide important details. The [Set Printing All] command turns off all such features and exposes underlying CIC terms.
For completeness, we mention one other class of confusing error message about inability to unify two terms that look obviously unifiable. Each unification variable has a scope; a unification variable instantiation may not mention variables that were not already defined within that scope, at the point in proof search where the unification variable was introduced. Consider this illustrative example: *)
Unset Printing All.
Theorem ex_symmetry : (exists x, x = 0) -> (exists x, 0 = x).
eexists.
(** %\vspace{-.15in}%[[
H : exists x : nat, x = 0
============================
0 = ?98
]]
*)
destruct H.
(** %\vspace{-.15in}%[[
x : nat
H : x = 0
============================
0 = ?99
]]
*)
(** %\vspace{-.2in}%[[
symmetry; exact H.
]]
<<
Error: In environment
x : nat
H : x = 0
The term "H" has type "x = 0" while it is expected to have type
"?99 = 0".
>>
The problem here is that variable [x] was introduced by [destruct] _after_ we introduced [?99] with [eexists], so the instantiation of [?99] may not mention [x]. A simple reordering of the proof solves the problem. *)
Restart.
destruct 1 as [x]; apply ex_intro with x; symmetry; assumption.
Qed.
(** This restriction for unification variables may seem counterintuitive, but it follows from the fact that CIC contains no concept of unification variable. Rather, to construct the final proof term, at the point in a proof where the unification variable is introduced, we replace it with the instantiation we eventually find for it. It is simply syntactically illegal to refer there to variables that are not in scope. Without such a restriction, we could trivially "prove" such non-theorems as [exists n : nat, forall m : nat, n = m] by [econstructor; intro; reflexivity]. *)
(** * The [Prop] Universe *)
(** In Chapter 4, we saw parallel versions of useful datatypes for "programs" and "proofs." The convention was that programs live in [Set], and proofs live in [Prop]. We gave little explanation for why it is useful to maintain this distinction. There is certainly documentation value from separating programs from proofs; in practice, different concerns apply to building the two types of objects. It turns out, however, that these concerns motivate formal differences between the two universes in Coq.
Recall the types [sig] and [ex], which are the program and proof versions of existential quantification. Their definitions differ only in one place, where [sig] uses [Type] and [ex] uses [Prop]. *)
Print sig.
(** %\vspace{-.15in}% [[
Inductive sig (A : Type) (P : A -> Prop) : Type :=
exist : forall x : A, P x -> sig P
]]
*)
Print ex.
(** %\vspace{-.15in}% [[
Inductive ex (A : Type) (P : A -> Prop) : Prop :=
ex_intro : forall x : A, P x -> ex P
]]
It is natural to want a function to extract the first components of data structures like these. Doing so is easy enough for [sig]. *)
Definition projS A (P : A -> Prop) (x : sig P) : A :=
match x with
| exist v _ => v
end.
(* begin hide *)
(* begin thide *)
Definition projE := O.
(* end thide *)
(* end hide *)
(** We run into trouble with a version that has been changed to work with [ex].
[[
Definition projE A (P : A -> Prop) (x : ex P) : A :=
match x with
| ex_intro v _ => v
end.
]]
<<
Error:
Incorrect elimination of "x" in the inductive type "ex":
the return type has sort "Type" while it should be "Prop".
Elimination of an inductive object of sort Prop
is not allowed on a predicate in sort Type
because proofs can be eliminated only to build proofs.
>>
In formal Coq parlance, %\index{elimination}%"elimination" means "pattern-matching." The typing rules of Gallina forbid us from pattern-matching on a discriminee whose type belongs to [Prop], whenever the result type of the [match] has a type besides [Prop]. This is a sort of "information flow" policy, where the type system ensures that the details of proofs can never have any effect on parts of a development that are not also marked as proofs.
This restriction matches informal practice. We think of programs and proofs as clearly separated, and, outside of constructive logic, the idea of computing with proofs is ill-formed. The distinction also has practical importance in Coq, where it affects the behavior of extraction.
Recall that %\index{program extraction}%extraction is Coq's facility for translating Coq developments into programs in general-purpose programming languages like OCaml. Extraction _erases_ proofs and leaves programs intact. A simple example with [sig] and [ex] demonstrates the distinction. *)
Definition sym_sig (x : sig (fun n => n = 0)) : sig (fun n => 0 = n) :=
match x with
| exist n pf => exist _ n (sym_eq pf)
end.
Extraction sym_sig.
(** <<
(** val sym_sig : nat -> nat **)
let sym_sig x = x
>>
Since extraction erases proofs, the second components of [sig] values are elided, making [sig] a simple identity type family. The [sym_sig] operation is thus an identity function. *)
Definition sym_ex (x : ex (fun n => n = 0)) : ex (fun n => 0 = n) :=
match x with
| ex_intro n pf => ex_intro _ n (sym_eq pf)
end.
Extraction sym_ex.
(** <<
(** val sym_ex : __ **)
let sym_ex = __
>>
In this example, the [ex] type itself is in [Prop], so whole [ex] packages are erased. Coq extracts every proposition as the (Coq-specific) type <<__>>, whose single constructor is <<__>>. Not only are proofs replaced by [__], but proof arguments to functions are also removed completely, as we see here.
Extraction is very helpful as an optimization over programs that contain proofs. In languages like Haskell, advanced features make it possible to program with proofs, as a way of convincing the type checker to accept particular definitions. Unfortunately, when proofs are encoded as values in GADTs%~\cite{GADT}%, these proofs exist at runtime and consume resources. In contrast, with Coq, as long as all proofs are kept within [Prop], extraction is guaranteed to erase them.
Many fans of the %\index{Curry-Howard correspondence}%Curry-Howard correspondence support the idea of _extracting programs from proofs_. In reality, few users of Coq and related tools do any such thing. Instead, extraction is better thought of as an optimization that reduces the runtime costs of expressive typing.
%\medskip%
We have seen two of the differences between proofs and programs: proofs are subject to an elimination restriction and are elided by extraction. The remaining difference is that [Prop] is%\index{impredicativity}% _impredicative_, as this example shows. *)
Check forall P Q : Prop, P \/ Q -> Q \/ P.
(** %\vspace{-.15in}% [[
forall P Q : Prop, P \/ Q -> Q \/ P
: Prop
]]
We see that it is possible to define a [Prop] that quantifies over other [Prop]s. This is fortunate, as we start wanting that ability even for such basic purposes as stating propositional tautologies. In the next section of this chapter, we will see some reasons why unrestricted impredicativity is undesirable. The impredicativity of [Prop] interacts crucially with the elimination restriction to avoid those pitfalls.
Impredicativity also allows us to implement a version of our earlier [exp] type that does not suffer from the weakness that we found. *)
Inductive expP : Type -> Prop :=
| ConstP : forall T, T -> expP T
| PairP : forall T1 T2, expP T1 -> expP T2 -> expP (T1 * T2)
| EqP : forall T, expP T -> expP T -> expP bool.
Check ConstP 0.
(** %\vspace{-.15in}% [[
ConstP 0
: expP nat
]]
*)
Check PairP (ConstP 0) (ConstP tt).
(** %\vspace{-.15in}% [[
PairP (ConstP 0) (ConstP tt)
: expP (nat * unit)
]]
*)
Check EqP (ConstP Set) (ConstP Type).
(** %\vspace{-.15in}% [[
EqP (ConstP Set) (ConstP Type)
: expP bool
]]
*)
Check ConstP (ConstP O).
(** %\vspace{-.15in}% [[
ConstP (ConstP 0)
: expP (expP nat)
]]
In this case, our victory is really a shallow one. As we have marked [expP] as a family of proofs, we cannot deconstruct our expressions in the usual programmatic ways, which makes them almost useless for the usual purposes. Impredicative quantification is much more useful in defining inductive families that we really think of as judgments. For instance, this code defines a notion of equality that is strictly more permissive than the base equality [=]. *)
Inductive eqPlus : forall T, T -> T -> Prop :=
| Base : forall T (x : T), eqPlus x x
| Func : forall dom ran (f1 f2 : dom -> ran),
(forall x : dom, eqPlus (f1 x) (f2 x))
-> eqPlus f1 f2.
Check (Base 0).
(** %\vspace{-.15in}% [[
Base 0
: eqPlus 0 0
]]
*)
Check (Func (fun n => n) (fun n => 0 + n) (fun n => Base n)).
(** %\vspace{-.15in}% [[
Func (fun n : nat => n) (fun n : nat => 0 + n) (fun n : nat => Base n)
: eqPlus (fun n : nat => n) (fun n : nat => 0 + n)
]]
*)
Check (Base (Base 1)).
(** %\vspace{-.15in}% [[
Base (Base 1)
: eqPlus (Base 1) (Base 1)
]]
*)
(** Stating equality facts about proofs may seem baroque, but we have already seen its utility in the chapter on reasoning about equality proofs. *)
(** * Axioms *)
(** While the specific logic Gallina is hardcoded into Coq's implementation, it is possible to add certain logical rules in a controlled way. In other words, Coq may be used to reason about many different refinements of Gallina where strictly more theorems are provable. We achieve this by asserting%\index{axioms}% _axioms_ without proof.
We will motivate the idea by touring through some standard axioms, as enumerated in Coq's online FAQ. I will add additional commentary as appropriate. *)
(** ** The Basics *)
(** One simple example of a useful axiom is the %\index{law of the excluded middle}%law of the excluded middle. *)
Require Import Classical_Prop.
Print classic.
(** %\vspace{-.15in}% [[
*** [ classic : forall P : Prop, P \/ ~ P ]
]]
In the implementation of module [Classical_Prop], this axiom was defined with the command%\index{Vernacular commands!Axiom}% *)
Axiom classic : forall P : Prop, P \/ ~ P.
(** An [Axiom] may be declared with any type, in any of the universes. There is a synonym %\index{Vernacular commands!Parameter}%[Parameter] for [Axiom], and that synonym is often clearer for assertions not of type [Prop]. For instance, we can assert the existence of objects with certain properties. *)
Parameter num : nat.
Axiom positive : num > 0.
Reset num.
(** This kind of "axiomatic presentation" of a theory is very common outside of higher-order logic. However, in Coq, it is almost always preferable to stick to defining your objects, functions, and predicates via inductive definitions and functional programming.
In general, there is a significant burden associated with any use of axioms. It is easy to assert a set of axioms that together is%\index{inconsistent axioms}% _inconsistent_. That is, a set of axioms may imply [False], which allows any theorem to be proved, which defeats the purpose of a proof assistant. For example, we could assert the following axiom, which is consistent by itself but inconsistent when combined with [classic]. *)
Axiom not_classic : ~ forall P : Prop, P \/ ~ P.
Theorem uhoh : False.
generalize classic not_classic; tauto.
Qed.
Theorem uhoh_again : 1 + 1 = 3.
destruct uhoh.
Qed.
Reset not_classic.
(** On the subject of the law of the excluded middle itself, this axiom is usually quite harmless, and many practical Coq developments assume it. It has been proved metatheoretically to be consistent with CIC. Here, "proved metatheoretically" means that someone proved on paper that excluded middle holds in a _model_ of CIC in set theory%~\cite{SetsInTypes}%. All of the other axioms that we will survey in this section hold in the same model, so they are all consistent together.
Recall that Coq implements%\index{constructive logic}% _constructive_ logic by default, where the law of the excluded middle is not provable. Proofs in constructive logic can be thought of as programs. A [forall] quantifier denotes a dependent function type, and a disjunction denotes a variant type. In such a setting, excluded middle could be interpreted as a decision procedure for arbitrary propositions, which computability theory tells us cannot exist. Thus, constructive logic with excluded middle can no longer be associated with our usual notion of programming.
Given all this, why is it all right to assert excluded middle as an axiom? The intuitive justification is that the elimination restriction for [Prop] prevents us from treating proofs as programs. An excluded middle axiom that quantified over [Set] instead of [Prop] _would_ be problematic. If a development used that axiom, we would not be able to extract the code to OCaml (soundly) without implementing a genuine universal decision procedure. In contrast, values whose types belong to [Prop] are always erased by extraction, so we sidestep the axiom's algorithmic consequences.
Because the proper use of axioms is so precarious, there are helpful commands for determining which axioms a theorem relies on.%\index{Vernacular commands!Print Assumptions}% *)
Theorem t1 : forall P : Prop, P -> ~ ~ P.
tauto.
Qed.
Print Assumptions t1.
(** <<
Closed under the global context
>>
*)
Theorem t2 : forall P : Prop, ~ ~ P -> P.
(** %\vspace{-.25in}%[[
tauto.
]]
<<
Error: tauto failed.
>>
*)
intro P; destruct (classic P); tauto.
Qed.
Print Assumptions t2.
(** %\vspace{-.15in}% [[
Axioms:
classic : forall P : Prop, P \/ ~ P
]]
It is possible to avoid this dependence in some specific cases, where excluded middle _is_ provable, for decidable families of propositions. *)
Theorem nat_eq_dec : forall n m : nat, n = m \/ n <> m.
induction n; destruct m; intuition; generalize (IHn m); intuition.
Qed.
Theorem t2' : forall n m : nat, ~ ~ (n = m) -> n = m.
intros n m; destruct (nat_eq_dec n m); tauto.
Qed.
Print Assumptions t2'.
(** <<
Closed under the global context
>>
%\bigskip%
Mainstream mathematical practice assumes excluded middle, so it can be useful to have it available in Coq developments, though it is also nice to know that a theorem is proved in a simpler formal system than classical logic. There is a similar story for%\index{proof irrelevance}% _proof irrelevance_, which simplifies proof issues that would not even arise in mainstream math. *)
Require Import ProofIrrelevance.
Print proof_irrelevance.
(** %\vspace{-.15in}% [[
*** [ proof_irrelevance : forall (P : Prop) (p1 p2 : P), p1 = p2 ]
]]
This axiom asserts that any two proofs of the same proposition are equal. Recall this example function from Chapter 6. *)
(* begin hide *)
Lemma zgtz : 0 > 0 -> False.
crush.
Qed.
(* end hide *)
Definition pred_strong1 (n : nat) : n > 0 -> nat :=
match n with
| O => fun pf : 0 > 0 => match zgtz pf with end
| S n' => fun _ => n'
end.
(** We might want to prove that different proofs of [n > 0] do not lead to different results from our richly typed predecessor function. *)
Theorem pred_strong1_irrel : forall n (pf1 pf2 : n > 0), pred_strong1 pf1 = pred_strong1 pf2.
destruct n; crush.
Qed.
(** The proof script is simple, but it involved peeking into the definition of [pred_strong1]. For more complicated function definitions, it can be considerably more work to prove that they do not discriminate on details of proof arguments. This can seem like a shame, since the [Prop] elimination restriction makes it impossible to write any function that does otherwise. Unfortunately, this fact is only true metatheoretically, unless we assert an axiom like [proof_irrelevance]. With that axiom, we can prove our theorem without consulting the definition of [pred_strong1]. *)
Theorem pred_strong1_irrel' : forall n (pf1 pf2 : n > 0), pred_strong1 pf1 = pred_strong1 pf2.
intros; f_equal; apply proof_irrelevance.
Qed.
(** %\bigskip%
In the chapter on equality, we already discussed some axioms that are related to proof irrelevance. In particular, Coq's standard library includes this axiom: *)
Require Import Eqdep.
Import Eq_rect_eq.
Print eq_rect_eq.
(** %\vspace{-.15in}% [[
*** [ eq_rect_eq :
forall (U : Type) (p : U) (Q : U -> Type) (x : Q p) (h : p = p),
x = eq_rect p Q x p h ]
]]
This axiom says that it is permissible to simplify pattern matches over proofs of equalities like [e = e]. The axiom is logically equivalent to some simpler corollaries. In the theorem names, "UIP" stands for %\index{unicity of identity proofs}%"unicity of identity proofs", where "identity" is a synonym for "equality." *)
Corollary UIP_refl : forall A (x : A) (pf : x = x), pf = eq_refl x.
intros; replace pf with (eq_rect x (eq x) (eq_refl x) x pf); [
symmetry; apply eq_rect_eq
| exact (match pf as pf' return match pf' in _ = y return x = y with
| eq_refl => eq_refl x
end = pf' with
| eq_refl => eq_refl _
end) ].
Qed.
Corollary UIP : forall A (x y : A) (pf1 pf2 : x = y), pf1 = pf2.
intros; generalize pf1 pf2; subst; intros;
match goal with
| [ |- ?pf1 = ?pf2 ] => rewrite (UIP_refl pf1); rewrite (UIP_refl pf2); reflexivity
end.
Qed.
(* begin hide *)
(* begin thide *)
Require Eqdep_dec.
(* end thide *)
(* end hide *)
(** These corollaries are special cases of proof irrelevance. In developments that only need proof irrelevance for equality, there is no need to assert full irrelevance.
Another facet of proof irrelevance is that, like excluded middle, it is often provable for specific propositions. For instance, [UIP] is provable whenever the type [A] has a decidable equality operation. The module [Eqdep_dec] of the standard library contains a proof. A similar phenomenon applies to other notable cases, including less-than proofs. Thus, it is often possible to use proof irrelevance without asserting axioms.
%\bigskip%
There are two more basic axioms that are often assumed, to avoid complications that do not arise in set theory. *)
Require Import FunctionalExtensionality.
Print functional_extensionality_dep.
(** %\vspace{-.15in}% [[
*** [ functional_extensionality_dep :
forall (A : Type) (B : A -> Type) (f g : forall x : A, B x),
(forall x : A, f x = g x) -> f = g ]
]]
This axiom says that two functions are equal if they map equal inputs to equal outputs. Such facts are not provable in general in CIC, but it is consistent to assume that they are.
A simple corollary shows that the same property applies to predicates. *)
Corollary predicate_extensionality : forall (A : Type) (B : A -> Prop) (f g : forall x : A, B x),
(forall x : A, f x = g x) -> f = g.
intros; apply functional_extensionality_dep; assumption.
Qed.
(** In some cases, one might prefer to assert this corollary as the axiom, to restrict the consequences to proofs and not programs. *)
(** ** Axioms of Choice *)
(** Some Coq axioms are also points of contention in mainstream math. The most prominent example is the %\index{axiom of choice}%axiom of choice. In fact, there are multiple versions that we might consider, and, considered in isolation, none of these versions means quite what it means in classical set theory.
First, it is possible to implement a choice operator _without_ axioms in some potentially surprising cases. *)
Require Import ConstructiveEpsilon.
Check constructive_definite_description.
(** %\vspace{-.15in}% [[
constructive_definite_description
: forall (A : Set) (f : A -> nat) (g : nat -> A),
(forall x : A, g (f x) = x) ->
forall P : A -> Prop,
(forall x : A, {P x} + { ~ P x}) ->
(exists! x : A, P x) -> {x : A | P x}
]]
*)
Print Assumptions constructive_definite_description.
(** <<
Closed under the global context
>>
This function transforms a decidable predicate [P] into a function that produces an element satisfying [P] from a proof that such an element exists. The functions [f] and [g], in conjunction with an associated injectivity property, are used to express the idea that the set [A] is countable. Under these conditions, a simple brute force algorithm gets the job done: we just enumerate all elements of [A], stopping when we find one satisfying [P]. The existence proof, specified in terms of _unique_ existence [exists!], guarantees termination. The definition of this operator in Coq uses some interesting techniques, as seen in the implementation of the [ConstructiveEpsilon] module.
Countable choice is provable in set theory without appealing to the general axiom of choice. To support the more general principle in Coq, we must also add an axiom. Here is a functional version of the axiom of unique choice. *)
Require Import ClassicalUniqueChoice.
Check dependent_unique_choice.
(** %\vspace{-.15in}% [[
dependent_unique_choice
: forall (A : Type) (B : A -> Type) (R : forall x : A, B x -> Prop),
(forall x : A, exists! y : B x, R x y) ->
exists f : forall x : A, B x,
forall x : A, R x (f x)
]]
This axiom lets us convert a relational specification [R] into a function implementing that specification. We need only prove that [R] is truly a function. An alternate, stronger formulation applies to cases where [R] maps each input to one or more outputs. We also simplify the statement of the theorem by considering only non-dependent function types. *)
(* begin hide *)
(* begin thide *)
Require RelationalChoice.
(* end thide *)
(* end hide *)
Require Import ClassicalChoice.
Check choice.
(** %\vspace{-.15in}% [[
choice
: forall (A B : Type) (R : A -> B -> Prop),
(forall x : A, exists y : B, R x y) ->
exists f : A -> B, forall x : A, R x (f x)
]]
This principle is proved as a theorem, based on the unique choice axiom and an additional axiom of relational choice from the [RelationalChoice] module.
In set theory, the axiom of choice is a fundamental philosophical commitment one makes about the universe of sets. In Coq, the choice axioms say something weaker. For instance, consider the simple restatement of the [choice] axiom where we replace existential quantification by its Curry-Howard analogue, subset types. *)
Definition choice_Set (A B : Type) (R : A -> B -> Prop) (H : forall x : A, {y : B | R x y})
: {f : A -> B | forall x : A, R x (f x)} :=
exist (fun f => forall x : A, R x (f x))
(fun x => proj1_sig (H x)) (fun x => proj2_sig (H x)).
(** %\smallskip{}%Via the Curry-Howard correspondence, this "axiom" can be taken to have the same meaning as the original. It is implemented trivially as a transformation not much deeper than uncurrying. Thus, we see that the utility of the axioms that we mentioned earlier comes in their usage to build programs from proofs. Normal set theory has no explicit proofs, so the meaning of the usual axiom of choice is subtly different. In Gallina, the axioms implement a controlled relaxation of the restrictions on information flow from proofs to programs.
However, when we combine an axiom of choice with the law of the excluded middle, the idea of "choice" becomes more interesting. Excluded middle gives us a highly non-computational way of constructing proofs, but it does not change the computational nature of programs. Thus, the axiom of choice is still giving us a way of translating between two different sorts of "programs," but the input programs (which are proofs) may be written in a rich language that goes beyond normal computability. This combination truly is more than repackaging a function with a different type.
%\bigskip%
The Coq tools support a command-line flag %\index{impredicative Set}%<<-impredicative-set>>, which modifies Gallina in a more fundamental way by making [Set] impredicative. A term like [forall T : Set, T] has type [Set], and inductive definitions in [Set] may have constructors that quantify over arguments of any types. To maintain consistency, an elimination restriction must be imposed, similarly to the restriction for [Prop]. The restriction only applies to large inductive types, where some constructor quantifies over a type of type [Type]. In such cases, a value in this inductive type may only be pattern-matched over to yield a result type whose type is [Set] or [Prop]. This rule contrasts with the rule for [Prop], where the restriction applies even to non-large inductive types, and where the result type may only have type [Prop].
In old versions of Coq, [Set] was impredicative by default. Later versions make [Set] predicative to avoid inconsistency with some classical axioms. In particular, one should watch out when using impredicative [Set] with axioms of choice. In combination with excluded middle or predicate extensionality, inconsistency can result. Impredicative [Set] can be useful for modeling inherently impredicative mathematical concepts, but almost all Coq developments get by fine without it. *)
(** ** Axioms and Computation *)
(** One additional axiom-related wrinkle arises from an aspect of Gallina that is very different from set theory: a notion of _computational equivalence_ is central to the definition of the formal system. Axioms tend not to play well with computation. Consider this example. We start by implementing a function that uses a type equality proof to perform a safe type-cast. *)
Definition cast (x y : Set) (pf : x = y) (v : x) : y :=
match pf with
| eq_refl => v
end.
(** Computation over programs that use [cast] can proceed smoothly. *)
Eval compute in (cast (eq_refl (nat -> nat)) (fun n => S n)) 12.
(** %\vspace{-.15in}%[[
= 13
: nat
]]
*)
(** Things do not go as smoothly when we use [cast] with proofs that rely on axioms. *)
Theorem t3 : (forall n : nat, fin (S n)) = (forall n : nat, fin (n + 1)).
change ((forall n : nat, (fun n => fin (S n)) n) = (forall n : nat, (fun n => fin (n + 1)) n));
rewrite (functional_extensionality (fun n => fin (n + 1)) (fun n => fin (S n))); crush.
Qed.
Eval compute in (cast t3 (fun _ => First)) 12.
(** %\vspace{-.15in}%[[
= match t3 in (_ = P) return P with
| eq_refl => fun n : nat => First
end 12
: fin (12 + 1)
]]
Computation gets stuck in a pattern-match on the proof [t3]. The structure of [t3] is not known, so the match cannot proceed. It turns out a more basic problem leads to this particular situation. We ended the proof of [t3] with [Qed], so the definition of [t3] is not available to computation. That mistake is easily fixed. *)
Reset t3.
Theorem t3 : (forall n : nat, fin (S n)) = (forall n : nat, fin (n + 1)).
change ((forall n : nat, (fun n => fin (S n)) n) = (forall n : nat, (fun n => fin (n + 1)) n));
rewrite (functional_extensionality (fun n => fin (n + 1)) (fun n => fin (S n))); crush.
Defined.
Eval compute in (cast t3 (fun _ => First)) 12.
(** %\vspace{-.15in}%[[
= match
match
match
functional_extensionality
....
]]
We elide most of the details. A very unwieldy tree of nested matches on equality proofs appears. This time evaluation really _is_ stuck on a use of an axiom.
If we are careful in using tactics to prove an equality, we can still compute with casts over the proof. *)
Lemma plus1 : forall n, S n = n + 1.
induction n; simpl; intuition.
Defined.
Theorem t4 : forall n, fin (S n) = fin (n + 1).
intro; f_equal; apply plus1.
Defined.
Eval compute in cast (t4 13) First.
(** %\vspace{-.15in}% [[
= First
: fin (13 + 1)
]]
This simple computational reduction hides the use of a recursive function to produce a suitable [eq_refl] proof term. The recursion originates in our use of [induction] in [t4]'s proof. *)
(** ** Methods for Avoiding Axioms *)
(** The last section demonstrated one reason to avoid axioms: they interfere with computational behavior of terms. A further reason is to reduce the philosophical commitment of a theorem. The more axioms one assumes, the harder it becomes to convince oneself that the formal system corresponds appropriately to one's intuitions. A refinement of this last point, in applications like %\index{proof-carrying code}%proof-carrying code%~\cite{PCC}% in computer security, has to do with minimizing the size of a%\index{trusted code base}% _trusted code base_. To convince ourselves that a theorem is true, we must convince ourselves of the correctness of the program that checks the theorem. Axioms effectively become new source code for the checking program, increasing the effort required to perform a correctness audit.
An earlier section gave one example of avoiding an axiom. We proved that [pred_strong1] is agnostic to details of the proofs passed to it as arguments, by unfolding the definition of the function. A "simpler" proof keeps the function definition opaque and instead applies a proof irrelevance axiom. By accepting a more complex proof, we reduce our philosophical commitment and trusted base. (By the way, the less-than relation that the proofs in question here prove turns out to admit proof irrelevance as a theorem provable within normal Gallina!)
One dark secret of the [dep_destruct] tactic that we have used several times is reliance on an axiom. Consider this simple case analysis principle for [fin] values: *)
Theorem fin_cases : forall n (f : fin (S n)), f = First \/ exists f', f = Next f'.
intros; dep_destruct f; eauto.
Qed.
(* begin hide *)
Require Import JMeq.
(* begin thide *)
Definition jme := (JMeq, JMeq_eq).
(* end thide *)
(* end hide *)
Print Assumptions fin_cases.
(** %\vspace{-.15in}%[[
Axioms:
JMeq_eq : forall (A : Type) (x y : A), JMeq x y -> x = y
]]
The proof depends on the [JMeq_eq] axiom that we met in the chapter on equality proofs. However, a smarter tactic could have avoided an axiom dependence. Here is an alternate proof via a slightly strange looking lemma. *)
(* begin thide *)
Lemma fin_cases_again' : forall n (f : fin n),
match n return fin n -> Prop with
| O => fun _ => False
| S n' => fun f => f = First \/ exists f', f = Next f'
end f.
destruct f; eauto.
Qed.
(** We apply a variant of the %\index{convoy pattern}%convoy pattern, which we are used to seeing in function implementations. Here, the pattern helps us state a lemma in a form where the argument to [fin] is a variable. Recall that, thanks to basic typing rules for pattern-matching, [destruct] will only work effectively on types whose non-parameter arguments are variables. The %\index{tactics!exact}%[exact] tactic, which takes as argument a literal proof term, now gives us an easy way of proving the original theorem. *)
Theorem fin_cases_again : forall n (f : fin (S n)), f = First \/ exists f', f = Next f'.
intros; exact (fin_cases_again' f).
Qed.
(* end thide *)
Print Assumptions fin_cases_again.
(** %\vspace{-.15in}%
<<
Closed under the global context
>>
*)
(* begin thide *)
(** As the Curry-Howard correspondence might lead us to expect, the same pattern may be applied in programming as in proving. Axioms are relevant in programming, too, because, while Coq includes useful extensions like [Program] that make dependently typed programming more straightforward, in general these extensions generate code that relies on axioms about equality. We can use clever pattern matching to write our code axiom-free.
As an example, consider a [Set] version of [fin_cases]. We use [Set] types instead of [Prop] types, so that return values have computational content and may be used to guide the behavior of algorithms. Beside that, we are essentially writing the same "proof" in a more explicit way. *)
Definition finOut n (f : fin n) : match n return fin n -> Type with
| O => fun _ => Empty_set
| _ => fun f => {f' : _ | f = Next f'} + {f = First}
end f :=
match f with
| First _ => inright _ (eq_refl _)
| Next _ f' => inleft _ (exist _ f' (eq_refl _))
end.
(* end thide *)
(** As another example, consider the following type of formulas in first-order logic. The intent of the type definition will not be important in what follows, but we give a quick intuition for the curious reader. Our formulas may include [forall] quantification over arbitrary [Type]s, and we index formulas by environments telling which variables are in scope and what their types are; such an environment is a [list Type]. A constructor [Inject] lets us include any Coq [Prop] as a formula, and [VarEq] and [Lift] can be used for variable references, in what is essentially the de Bruijn index convention. (Again, the detail in this paragraph is not important to understand the discussion that follows!) *)
Inductive formula : list Type -> Type :=
| Inject : forall Ts, Prop -> formula Ts
| VarEq : forall T Ts, T -> formula (T :: Ts)
| Lift : forall T Ts, formula Ts -> formula (T :: Ts)
| Forall : forall T Ts, formula (T :: Ts) -> formula Ts
| And : forall Ts, formula Ts -> formula Ts -> formula Ts.
(** This example is based on my own experiences implementing variants of a program logic called XCAP%~\cite{XCAP}%, which also includes an inductive predicate for characterizing which formulas are provable. Here I include a pared-down version of such a predicate, with only two constructors, which is sufficient to illustrate certain tricky issues. *)
Inductive proof : formula nil -> Prop :=
| PInject : forall (P : Prop), P -> proof (Inject nil P)
| PAnd : forall p q, proof p -> proof q -> proof (And p q).
(** Let us prove a lemma showing that a "[P /\ Q -> P]" rule is derivable within the rules of [proof]. *)
Theorem proj1 : forall p q, proof (And p q) -> proof p.
destruct 1.
(** %\vspace{-.15in}%[[
p : formula nil
q : formula nil
P : Prop
H : P
============================
proof p
]]
*)
(** We are reminded that [induction] and [destruct] do not work effectively on types with non-variable arguments. The first subgoal, shown above, is clearly unprovable. (Consider the case where [p = Inject nil False].)
An application of the %\index{tactics!dependent destruction}%[dependent destruction] tactic (the basis for [dep_destruct]) solves the problem handily. We use a shorthand with the %\index{tactics!intros}%[intros] tactic that lets us use question marks for variable names that do not matter. *)
Restart.
Require Import Program.
intros ? ? H; dependent destruction H; auto.
Qed.
Print Assumptions proj1.
(** %\vspace{-.15in}%[[
Axioms:
eq_rect_eq : forall (U : Type) (p : U) (Q : U -> Type) (x : Q p) (h : p = p),
x = eq_rect p Q x p h
]]
Unfortunately, that built-in tactic appeals to an axiom. It is still possible to avoid axioms by giving the proof via another odd-looking lemma. Here is a first attempt that fails at remaining axiom-free, using a common equality-based trick for supporting induction on non-variable arguments to type families. The trick works fine without axioms for datatypes more traditional than [formula], but we run into trouble with our current type. *)
Lemma proj1_again' : forall r, proof r
-> forall p q, r = And p q -> proof p.
destruct 1; crush.
(** %\vspace{-.15in}%[[
H0 : Inject [] P = And p q
============================
proof p
]]
The first goal looks reasonable. Hypothesis [H0] is clearly contradictory, as [discriminate] can show. *)
try discriminate. (* Note: Coq 8.6 is now solving this subgoal automatically!
* This line left here to keep everything working in
* 8.4 and 8.5. *)
(** %\vspace{-.15in}%[[
H : proof p
H1 : And p q = And p0 q0
============================
proof p0
]]
It looks like we are almost done. Hypothesis [H1] gives [p = p0] by injectivity of constructors, and then [H] finishes the case. *)
injection H1; intros.
(* begin hide *)
(* begin thide *)
Definition existT' := existT.
(* end thide *)
(* end hide *)
(** Unfortunately, the "equality" that we expected between [p] and [p0] comes in a strange form:
[[
H3 : existT (fun Ts : list Type => formula Ts) []%list p =
existT (fun Ts : list Type => formula Ts) []%list p0
============================
proof p0
]]
It may take a bit of tinkering, but, reviewing Chapter 3's discussion of writing injection principles manually, it makes sense that an [existT] type is the most direct way to express the output of [injection] on a dependently typed constructor. The constructor [And] is dependently typed, since it takes a parameter [Ts] upon which the types of [p] and [q] depend. Let us not dwell further here on why this goal appears; the reader may like to attempt the (impossible) exercise of building a better injection lemma for [And], without using axioms.
How exactly does an axiom come into the picture here? Let us ask [crush] to finish the proof. *)
crush.
Qed.
Print Assumptions proj1_again'.
(** %\vspace{-.15in}%[[
Axioms:
eq_rect_eq : forall (U : Type) (p : U) (Q : U -> Type) (x : Q p) (h : p = p),
x = eq_rect p Q x p h
]]
It turns out that this familiar axiom about equality (or some other axiom) is required to deduce [p = p0] from the hypothesis [H3] above. The soundness of that proof step is neither provable nor disprovable in Gallina.
Hope is not lost, however. We can produce an even stranger looking lemma, which gives us the theorem without axioms. As always when we want to do case analysis on a term with a tricky dependent type, the key is to refactor the theorem statement so that every term we [match] on has _variables_ as its type indices; so instead of talking about proofs of [And p q], we talk about proofs of an arbitrary [r], but we only conclude anything interesting when [r] is an [And]. *)
Lemma proj1_again'' : forall r, proof r
-> match r with
| And Ps p _ => match Ps return formula Ps -> Prop with
| nil => fun p => proof p
| _ => fun _ => True
end p
| _ => True
end.
destruct 1; auto.
Qed.
Theorem proj1_again : forall p q, proof (And p q) -> proof p.
intros ? ? H; exact (proj1_again'' H).
Qed.
Print Assumptions proj1_again.
(** <<
Closed under the global context
>>
This example illustrates again how some of the same design patterns we learned for dependently typed programming can be used fruitfully in theorem statements.
%\medskip%
To close the chapter, we consider one final way to avoid dependence on axioms. Often this task is equivalent to writing definitions such that they _compute_. That is, we want Coq's normal reduction to be able to run certain programs to completion. Here is a simple example where such computation can get stuck. In proving properties of such functions, we would need to apply axioms like %\index{axiom K}%K manually to make progress.
Imagine we are working with %\index{deep embedding}%deeply embedded syntax of some programming language, where each term is considered to be in the scope of a number of free variables that hold normal Coq values. To enforce proper typing, we will need to model a Coq typing environment somehow. One natural choice is as a list of types, where variable number [i] will be treated as a reference to the [i]th element of the list. *)
Section withTypes.
Variable types : list Set.
(** To give the semantics of terms, we will need to represent value environments, which assign each variable a term of the proper type. *)
Variable values : hlist (fun x : Set => x) types.
(** Now imagine that we are writing some procedure that operates on a distinguished variable of type [nat]. A hypothesis formalizes this assumption, using the standard library function [nth_error] for looking up list elements by position. *)
Variable natIndex : nat.
Variable natIndex_ok : nth_error types natIndex = Some nat.
(** It is not hard to use this hypothesis to write a function for extracting the [nat] value in position [natIndex] of [values], starting with two helpful lemmas, each of which we finish with [Defined] to mark the lemma as transparent, so that its definition may be expanded during evaluation. *)
Lemma nth_error_nil : forall A n x,
nth_error (@nil A) n = Some x
-> False.
destruct n; simpl; unfold error; congruence.
Defined.
Arguments nth_error_nil [A n x] _.
Lemma Some_inj : forall A (x y : A),
Some x = Some y
-> x = y.
congruence.
Defined.
Fixpoint getNat (types' : list Set) (values' : hlist (fun x : Set => x) types')
(natIndex : nat) : (nth_error types' natIndex = Some nat) -> nat :=
match values' with
| HNil => fun pf => match nth_error_nil pf with end
| HCons t ts x values'' =>
match natIndex return nth_error (t :: ts) natIndex = Some nat -> nat with
| O => fun pf =>
match Some_inj pf in _ = T return T with
| eq_refl => x
end
| S natIndex' => getNat values'' natIndex'
end
end.
End withTypes.
(** The problem becomes apparent when we experiment with running [getNat] on a concrete [types] list. *)
Definition myTypes := unit :: nat :: bool :: nil.
Definition myValues : hlist (fun x : Set => x) myTypes :=
tt ::: 3 ::: false ::: HNil.
Definition myNatIndex := 1.
Theorem myNatIndex_ok : nth_error myTypes myNatIndex = Some nat.
reflexivity.
Defined.
Eval compute in getNat myValues myNatIndex myNatIndex_ok.
(** %\vspace{-.15in}%[[
= 3
]]
We have not hit the problem yet, since we proceeded with a concrete equality proof for [myNatIndex_ok]. However, consider a case where we want to reason about the behavior of [getNat] _independently_ of a specific proof. *)
Theorem getNat_is_reasonable : forall pf, getNat myValues myNatIndex pf = 3.
intro; compute.
(**
<<
1 subgoal
>>
%\vspace{-.3in}%[[
pf : nth_error myTypes myNatIndex = Some nat
============================
match
match
pf in (_ = y)
return (nat = match y with
| Some H => H
| None => nat
end)
with
| eq_refl => eq_refl
end in (_ = T) return T
with
| eq_refl => 3
end = 3
]]
Since the details of the equality proof [pf] are not known, computation can proceed no further. A rewrite with axiom K would allow us to make progress, but we can rethink the definitions a bit to avoid depending on axioms. *)
Abort.
(** Here is a definition of a function that turns out to be useful, though no doubt its purpose will be mysterious for now. A call [update ls n x] overwrites the [n]th position of the list [ls] with the value [x], padding the end of the list with extra [x] values as needed to ensure sufficient length. *)
Fixpoint copies A (x : A) (n : nat) : list A :=
match n with
| O => nil
| S n' => x :: copies x n'
end.
Fixpoint update A (ls : list A) (n : nat) (x : A) : list A :=
match ls with
| nil => copies x n ++ x :: nil
| y :: ls' => match n with
| O => x :: ls'
| S n' => y :: update ls' n' x
end
end.
(** Now let us revisit the definition of [getNat]. *)
Section withTypes'.
Variable types : list Set.
Variable natIndex : nat.
(** Here is the trick: instead of asserting properties about the list [types], we build a "new" list that is _guaranteed by construction_ to have those properties. *)
Definition types' := update types natIndex nat.
Variable values : hlist (fun x : Set => x) types'.
(** Now a bit of dependent pattern matching helps us rewrite [getNat] in a way that avoids any use of equality proofs. *)
Fixpoint skipCopies (n : nat)
: hlist (fun x : Set => x) (copies nat n ++ nat :: nil) -> nat :=
match n with
| O => fun vs => hhd vs
| S n' => fun vs => skipCopies n' (htl vs)
end.
Fixpoint getNat' (types'' : list Set) (natIndex : nat)
: hlist (fun x : Set => x) (update types'' natIndex nat) -> nat :=
match types'' with
| nil => skipCopies natIndex
| t :: types0 =>
match natIndex return hlist (fun x : Set => x)
(update (t :: types0) natIndex nat) -> nat with
| O => fun vs => hhd vs
| S natIndex' => fun vs => getNat' types0 natIndex' (htl vs)
end
end.
End withTypes'.
(** Now the surprise comes in how easy it is to _use_ [getNat']. While typing works by modification of a types list, we can choose parameters so that the modification has no effect. *)
Theorem getNat_is_reasonable : getNat' myTypes myNatIndex myValues = 3.
reflexivity.
Qed.
(** The same parameters as before work without alteration, and we avoid use of axioms. *)
|
module ExerciseOne
import Data.Vect
%default total
-- | Ex1
-- | Write a function:
-- | > repeat : (n : Nat) -> a -> Vect n a
-- | which constructs a vector of n copies of an item.
repeat : (n : Nat) -> a -> Vect n a
repeat Z _ = []
repeat (S k) e = e :: repeat k e
--------------------------------------------------------------------------------
-- 2. Consider the following functions over Lists:
-- take : Nat -> List a -> List a
-- drop : Nat -> List a -> List a
-- (a) What are the types of the corresponding functions for Vect, vtake and vdrop?
-- Hint: What are the invariants? i.e. how many items need to be in the vector in each case?
-- (b) Implement vtake and vdrop
-- | A. Types for Vect, vtake and vdrop
vtake : (n : Nat) -> Vect (n + m) t -> Vect n t
vtake Z _ = []
vtake (S k) (x :: xs) = x :: vtake k xs
vdrop : (n : Nat) -> Vect (n + m) t -> Vect m t
vdrop Z xs = xs
vdrop (S k) (x :: xs) = vdrop k xs
--------------------------------------------------------------------------------
-- 3. A matrix is a 2-dimensional vector, and could be defined as follows:
Matrix : Nat -> Nat -> Type -> Type
Matrix n m a = Vect n (Vect m a)
-- (a) Using repeat, above, and Vect.zipWith, write a function which transposes a matrix.
-- Hints: Remember to think carefully about its type first! zipWith for vectors is defined as follows:
-- zipWith : (a -> b -> c) -> Vect a n -> Vect b n -> Vect c n
-- zipWith f [] [] = []
-- zipWith f (x::xs) (y::ys) = f x y :: zipWith f xs ys
transpose' : Matrix x y t -> Matrix y x t
transpose' {x = Z} [] = repeat _ []
transpose' (x::xs) = zipWith (::) x (transpose' xs)
-- (b) Write a function to multiply two matrices.
matX : Num t => Matrix x y t -> Matrix y z t -> Matrix x z t
matX [] _ = []
matX (x::xs) ys = (map (sum . zipWith (*) x) $ transpose' ys) :: (matX xs ys)
--------------------------------------------------------------------------------
-- 4. The following view describes a pair of numbers as a difference:
data Cmp : Nat -> Nat -> Type where
cmpLT : (y : _) -> Cmp x (x + S y)
cmpEQ : Cmp x x
cmpGT : (x : _) -> Cmp (y + S x) y
-- (a) Write the function cmp : (n : Nat) -> (m : Nat) -> Cmp n m
-- which proves that every pair of numbers can be expressed in this way.
-- Hint: recall parity from the lecture. You will find the with construct very useful!
cmp' : (n : Nat) -> (m : Nat) -> Cmp n m
cmp' Z Z = cmpEQ {x = Z}
cmp' Z (S k) = cmpLT k
cmp' (S k) Z = cmpGT k
cmp' (S k) (S j) with (cmp' k j)
cmp' (S k) (S k) | cmpEQ = cmpEQ {x = S k}
cmp' (S k) (S (k + S h)) | cmpLT h = cmpLT h
cmp' (S (j + S h)) (S j) | cmpGT h = cmpGT h
-- (b) Assume you have a vector xs : Vect a n, where n is unknown.
-- How could you use cmp to construct a suitable input to vtake and vdrop from xs?
-- >>> Huh? What is this even asking?
--------------------------------------------------------------------------------
-- 5. Implement the following functions:
-- plus_nSm : (n : Nat) -> (m : Nat) -> n + S m = S (n + m)
-- plus_commutes : (n : Nat) -> (m : Nat) -> n + m = m + n
-- plus_assoc : (n : Nat) -> (m : Nat) -> (p : Nat) ->
-- n + (m + p) = (n + m) + p
--------------------------------------------------------------------------------
-- 6. One way to define a reverse function for lists is as follows:
-- reverse : List a -> List a
-- reverse xs = revAcc [] xs where
-- revAcc : List a -> List a -> List a
-- revAcc acc [] = acc
-- revAcc acc (x :: xs) = revAcc (x :: acc) xs
-- Write the equivalent function for vectors, vect reverse : Vect a
-- n ->
-- Hint: You can use the same structure as the definition for List, but you will need to think carefully
-- Vect a n
-- about the type for revAcc, and may need to do some theorem proving.
--------------------------------------------------------------------------------
-- 7. You are given the following definition of binary trees:
-- data Tree a = Leaf | Node (Tree a) a (Tree a)
-- Define a membership predicate ElemTree and a function elemInTree which calculates whether a
-- value in in the tree, and a corresponding proof.
-- data ElemTree : a -> Tree a -> Type where ...
-- elemInTree : DecEq a =>
-- (x : a) -> (t : Tree a) -> Maybe (ElemTree x t)
|
import .atom
import ...common.lnq ...common.ldq ...common.predicates
variables {α β : Type}
namespace lia
lemma down_closed_fnormal : @down_closed (lia.atom) (fnormal int)
| ⊤' _ hd _ := by cases hd
| ⊥' _ hd _ := by cases hd
| (A' a) _ hd _ := by cases hd
| (p ∧' q) r hd hn :=
by {unfold fnormal at hn, cases hn, cases hd; assumption}
| (p ∨' q) r hd hn :=
by {unfold fnormal at hn, cases hn, cases hd; assumption}
| (¬' p) r hd hn := by {cases hd, apply hn}
| (∃' p) r hd hn := by {cases hd, apply hn}
lemma prop_up_closed_fnormal : @prop_up_closed (lia.atom) (fnormal int)
| ⊤' := trivial
| ⊥' := trivial
| (A' a) := trivial
| (p ∧' q) := begin intros hp hq, apply and.intro hp hq end
| (p ∨' q) := begin intros hp hq, apply and.intro hp hq end
| (¬' p) := id
| (∃' p) := trivial
lemma fnormal_and_o : ∀ (p q : fm atom), fnormal int p → fnormal int q → fnormal int (and_o p q)
:= pred_and_o (fnormal int) prop_up_closed_fnormal
lemma fnormal_or_o : ∀ (p q : fm atom), fnormal int p → fnormal int q → fnormal int (or_o p q)
:= pred_or_o (fnormal int) prop_up_closed_fnormal
lemma fnormal_list_disj : ∀ (ps : list (fm atom)), (∀ p ∈ ps, fnormal int p) → fnormal int (list_disj ps) :=
pred_list_disj _ prop_up_closed_fnormal
lemma fnormal_disj : ∀ (bs : list β) (f : β → fm atom), (∀ b ∈ bs, fnormal int (f b)) → fnormal int (disj bs f) :=
pred_disj _ prop_up_closed_fnormal
meta def nnf_closed_fnormal_aux :=
`[unfold nnf, unfold fnormal,
unfold fnormal at hn, cases hn with hnp hnq,
cases (nnf_closed_fnormal_core hnp) with hnp1 hnp2,
cases (nnf_closed_fnormal_core hnq) with hnq1 hnq2,
apply and.intro; apply and.intro; assumption]
lemma nnf_closed_fnormal_core : ∀ {p : fm lia.atom},
fnormal int p → fnormal int (nnf int p) ∧ fnormal int (nnf int (¬' p))
| ⊤' hn := and.intro trivial trivial
| ⊥' hn := and.intro trivial trivial
| (A' a) hn :=
begin
unfold nnf, apply and.intro,
apply hn, rewrite fnormal_iff_fnormal_alt,
apply atom_type.neg_prsv_normal, apply hn
end
| (p ∧' q) hn := by nnf_closed_fnormal_aux
| (p ∨' q) hn := by nnf_closed_fnormal_aux
| (¬' p) hn :=
begin
apply and.symm, unfold fnormal at hn,
unfold nnf, apply nnf_closed_fnormal_core hn
end
| (∃' p) hn :=
begin unfold nnf, apply and.intro; trivial end
lemma nnf_closed_fnormal : preserves (@nnf lia.atom int _) (fnormal int) :=
λ p hn, (nnf_closed_fnormal_core hn)^.elim_left
lemma atoms_and_o_subset {p q : fm lia.atom} :
atoms (and_o p q) ⊆ atoms p ∪ atoms q :=
begin
apply cases_and_o' (λ p' q' r, atoms r ⊆ atoms p' ∪ atoms q') p q;
intros a ha,
apply list.mem_union_right, apply ha,
apply list.mem_union_left, apply ha,
apply list.mem_union_left, apply ha,
apply list.mem_union_right, apply ha,
apply ha
end
lemma lnq_closed_fnormal (f : fm atom → fm atom)
(hc : preserves f (fnormal ℤ)) : preserves (lift_nnf_qe ℤ f) (fnormal ℤ)
| ⊤' hn := trivial
| ⊥' hn := trivial
| (A' a) hn := by {unfold lift_nnf_qe, apply hn}
| (p ∧' q) hn :=
begin
unfold fnormal at hn , cases hn with hnp hnq,
unfold lift_nnf_qe, apply cases_and_o, trivial,
apply lnq_closed_fnormal, apply hnp,
apply lnq_closed_fnormal, apply hnq,
apply and.intro; apply lnq_closed_fnormal; assumption,
end
| (p ∨' q) hn :=
begin
unfold fnormal at hn , cases hn with hnp hnq,
unfold lift_nnf_qe, apply cases_or_o, trivial,
apply lnq_closed_fnormal, apply hnp,
apply lnq_closed_fnormal, apply hnq,
apply and.intro; apply lnq_closed_fnormal; assumption,
end
| (¬' p) hn :=
begin
unfold fnormal at hn, unfold lift_nnf_qe, apply cases_not_o,
trivial, trivial, apply lnq_closed_fnormal, apply hn
end
| (∃' p) hn :=
begin
unfold lift_nnf_qe, apply hc,
apply nnf_closed_fnormal,
apply lnq_closed_fnormal, apply hn
end
theorem lnq_prsv
(qe : fm lia.atom → fm lia.atom)
(hqe : preserves qe (fnormal int))
(hqf : qfree_res_of_nqfree_arg qe)
(hi : ∀ p, nqfree p → fnormal int p → ∀ (bs : list int), I (qe p) bs ↔ ∃ b, (I p (b::bs))) :
∀ p, fnormal int p → ∀ (bs : list int), I (lift_nnf_qe int qe p) bs ↔ I p bs :=
@lnq_prsv_gen lia.atom int lia.atom_type
qe hqf (fnormal int) down_closed_fnormal hqe
nnf_closed_fnormal lnq_closed_fnormal hi
theorem ldq_prsv
(qe : list lia.atom → fm lia.atom)
(hqf : ∀ as, (∀ a ∈ as, dep0 a) → qfree (qe as))
(hn : ∀ as, (∀ a ∈ as, dep0 a) → (∀ a ∈ as, normal a) → fnormal int (qe as))
(he : ∀ as, (∀ a ∈ as, dep0 a) → (∀ a ∈ as, normal a) → qe_prsv int qe as) :
∀ p, fnormal int p → ∀ (bs : list int), I (lift_dnf_qe int qe p) bs ↔ I p bs :=
@ldq_prsv_gen lia.atom int lia.atom_type _ hqf hn he
end lia
|
bigfib(n) = ((BigInt[1 1; 1 0])^n)[2,1]
bigfib(20)
|
Formal statement is: lemma power2_i [simp]: "\<i>\<^sup>2 = -1" Informal statement is: $\i^2 = -1$. |
-- Andreas, 2018-11-23, issue #3304, report and test case by Nisse
open import Agda.Builtin.Equality
open import Agda.Builtin.Sigma
map : {A B : Set} {P : A → Set} {Q : B → Set} →
(f : A → B) → (∀ {x} → P x → Q (f x)) →
Σ A P → Σ B Q
map f g (x , y) = (f x , g y)
postulate
F : Set → Set → Set
apply : {A B : Set} → F A B → A → B
construct : {A B : Set} → (A → B) → F A B
A : Set
B : A → Set
f : A → A
g : ∀ {x} → B x → B (f x)
mutual
k : Σ A B → Σ A _
k = map f g
h : F (Σ A B) (Σ A B)
h = construct k
P : ∀ {x y} → k x ≡ k y → Set₁
P refl = Set
-- WAS: internal error in
-- TypeChecking.Rules.Term.catchIlltypedPatternBlockedOnMeta
--
-- EXPECTED:
-- I'm not sure if there should be a case for the constructor refl,
-- because I get stuck when trying to solve the following unification
-- problems (inferred index ≟ expected index):
-- k x ≟ k y
-- when checking that the pattern refl has type k x ≡ k y
|
Formal statement is: lemma is_nth_power_nth_power [simp, intro]: "is_nth_power n (x ^ n)" Informal statement is: If $x$ is an integer, then $x^n$ is an $n$th power. |
*----------------------------------------------------------------------*
subroutine set_Xcontrib(flist,ansatz,approx,
& irsq,irdag,irbar,ihartree,ixmat,iham,
& idx_intm,idx_op,nop,op_info,orb_info)
*----------------------------------------------------------------------*
* set X type contributions to B matrix
* no GBC assumed:
* B : assemble Xbar from r^2(f+k) and r+ and rbar
* C : r^2(f+k) and r+ and rbar+
* GBC assumed (A' and B only)
* assemble Xbar_F from X and Fock matrix
* if approx B: assemble Xbar_K from r+ and rbar (contains K only)
*----------------------------------------------------------------------*
implicit none
include 'opdim.h'
include 'stdunit.h'
include 'def_contraction.h'
include 'mdef_operator_info.h'
include 'def_formula_item.h'
include 'def_formula.h'
include 'def_orbinf.h'
integer, parameter ::
& ntest = 00
character(6), parameter ::
& op_scr_f = '_SCR_F'
type(formula_item), intent(inout), target ::
& flist
character*(*) ::
& approx
integer, intent(in) ::
& ansatz,nop,irsq,irdag,irbar,ixmat,ihartree,iham,
& idx_intm,idx_op(nop)
type(operator_info), intent(inout) ::
& op_info
type(orbinf), intent(in) ::
& orb_info
type(formula_item), pointer ::
& flist_pnt, flist_pnt0
logical ::
& GBC, assume_rsqbar
integer ::
& idx_1, idx_2, idx_prj, idx_f, ndef,
& njoined_intm, njoined_op
type(operator), pointer ::
& opf_pnt, op_pnt
integer ::
& occ_def(ngastp,2)
integer, external ::
& idx_oplist2
if (approx(1:2).eq.'A ') return
njoined_intm = op_info%op_arr(idx_intm)%op%njoined
GBC = approx(4:6).eq.'GBC'.or.approx(1:2).eq.'A'''
if (GBC.and.approx(1:2).eq.'C ')
& call quit(1,'set_Xcontrib','no GBC for approximation C')
if (approx(1:1).ne.'A') then
if (irdag.gt.nop.or.
& irbar.gt.nop.or.
& irsq.gt.nop.or.
& ihartree.gt.nop) then
write(lulog,*) 'idx: ',irdag,irbar,irsq,ihartree
write(lulog,*) 'nop: ',nop
call quit(1,'set_Xcontrib',
& 'not enough operators on input list')
end if
flist_pnt => flist
do while(associated(flist_pnt%next))
flist_pnt => flist_pnt%next
end do
flist_pnt0 => flist_pnt
! if no hartree operator was given, we assume that
! the modified R.R integral was imported
assume_rsqbar = idx_op(ihartree).le.0
if (idx_op(irdag).le.0.or.
& idx_op(irbar).le.0.or.
& idx_op(irsq) .le.0) then
write(lulog,*) 'idx: ',idx_op(irdag),idx_op(irbar),
& idx_op(irsq),idx_op(ihartree)
call quit(1,'set_Xcontrib',
& 'operator(s) not on input list')
end if
!-----------------!
! R12^{2} * (f+k) !
!-----------------!
if (.not.assume_rsqbar) then
c call quit(1,'set_Xcontrib',
c & 'unused route. how did you get here?')
idx_1 = idx_op(irsq)
idx_2 = idx_op(ihartree)
! go to end of list
flist_pnt => flist
do while(associated(flist_pnt%next))
flist_pnt => flist_pnt%next
end do
if (njoined_intm.eq.1) then
call expand_op_product2(flist_pnt,idx_intm,
& 1d0,5,3,
& (/idx_intm,idx_2,idx_1,idx_1,idx_intm/),
& (/1 ,2 ,3 ,3 ,1 /),
& -1, -1,
& 0,0,
& 0,0,
& (/2,3,1,0/),1, ! def. of projector
& .false.,op_info)
else if (njoined_intm.eq.2) then
call expand_op_product2(flist_pnt,idx_intm,
& 1d0,7,3,
& (/idx_intm,idx_1,idx_intm,idx_intm,idx_2,idx_1,idx_intm/),
& (/1 ,2 ,1 ,1 ,3 ,2 ,1 /),
& -1, -1,
& 0,0,
& (/2,7, 1,5, 1,6/),3, ! avoid cross contrib. to external lines
& (/4,5,1,0/),1, ! def. of projector
& .false.,op_info)
else
call quit(1,'set_Xcontrib','not prepared for this case !')
end if
else
idx_1 = idx_op(irsq)
flist_pnt => flist
do while(associated(flist_pnt%next))
flist_pnt => flist_pnt%next
end do
njoined_op = op_info%op_arr(idx_1)%op%njoined
if (njoined_intm.eq.njoined_op) then
call set_primitive_formula(flist_pnt,idx_1,
& 1d0,idx_intm,.false.,op_info)
else if (njoined_intm.lt.njoined_op) then
! generate the appropriate self-contraction
call expand_op_product2(flist_pnt,idx_intm,
& 1d0,4,2,
& (/idx_intm,idx_1,idx_1,idx_intm/),
& (/1 ,2 , 2, 1 /),
& -1, -1,
& 0,0,
& 0,0,
& 0,0,
& .false.,op_info)
else
call quit(1,'set_Xcontrib','not prepared for this case !')
end if
end if
!----------------------------------!
! - R12+ RBAR (C: - R12+ RBREVE) !
!----------------------------------!
idx_1 = idx_op(irdag)
idx_2 = idx_op(irbar)
! go to end of list
flist_pnt => flist
do while(associated(flist_pnt%next))
flist_pnt => flist_pnt%next
end do
idx_prj = 2
if (ansatz.gt.1) idx_prj = 4
if (njoined_intm.eq.1) then
c call expand_op_product2(flist_pnt,idx_intm,
c & -1d0,4,3,
c & (/idx_intm,-idx_1,idx_2,idx_intm/),
c & (/1 ,2 ,3 ,1 /),
c & -1, -1,
c & (/2,3/),1, ! force additional contraction
c & 0,0,
c & (/2,3,2,idx_prj/),1, ! def. of projector
c & .false.,op_info)
c ! this gives the terms with ONLY the projector as contraction
c do while(associated(flist_pnt%next))
c flist_pnt => flist_pnt%next
c end do
call expand_op_product2(flist_pnt,idx_intm,
& -1d0,4,3,
& (/idx_intm,-idx_1,idx_2,idx_intm/),
& (/1 ,2 ,3 ,1 /),
& -1, -1,
& 0,0,
& 0,0,
& (/2,3,2,idx_prj/),1, ! def. of projector
& .false.,op_info)
else if (njoined_intm.eq.2) then
call expand_op_product2(flist_pnt,idx_intm,
& -1d0,6,3,
& (/idx_intm,-idx_1,idx_intm,idx_intm,idx_2,idx_intm/),
& (/1 ,2 ,1 ,1 ,3 ,1 /),
& -1, -1,
& 0,0,
& (/2,6, 1,5/),2, ! avoid cross contrib. to external lines
& (/2,5,2,idx_prj/),1, ! def. of projector
& .false.,op_info)
else
call quit(1,'set_Xcontrib','unexpected: njoined_intm>2')
end if
if (ntest.ge.100) then
write(lulog,*) 'Xbar contribution'
call print_form_list(lulog,flist_pnt,op_info)
end if
end if
if (GBC) then
if (iham.gt.nop.or.
& ixmat.gt.nop) then
write(lulog,*) 'idx: ',iham,ixmat
write(lulog,*) 'nop: ',nop
call quit(1,'set_Xcontrib',
& 'not enough operators on input list')
end if
if (idx_op(iham).le.0.or.
& idx_op(ixmat).le.0) then
write(lulog,*) 'idx: ',idx_op(iham),idx_op(ixmat)
call quit(1,'set_Xcontrib',
& 'operator(s) not on input list')
end if
! dummy operator: 1 particle part of H
call add_operator(op_scr_f,op_info)
idx_f = idx_oplist2(op_scr_f,op_info)
opf_pnt => op_info%op_arr(idx_f)%op
ndef = 1
occ_def = 0
occ_def(1,1:2) = 1
call set_uop(opf_pnt,op_scr_f,.false.,
& occ_def,ndef,orb_info)
idx_1 = idx_op(ixmat)
idx_2 = idx_op(iham)
! go to end of list
flist_pnt => flist
do while(associated(flist_pnt%next))
flist_pnt => flist_pnt%next
end do
idx_prj = ansatz*2
call expand_op_product2(flist_pnt,idx_intm,
& -1d0,7,3,
& (/idx_intm,idx_1,idx_intm,idx_intm,idx_f,idx_1,idx_intm/),
& (/1 ,2 ,1 ,1 ,3 ,2 ,1 /),
& -1, -1,
& 0,0,
& (/2,7, 1,5, 1,6/),3, ! avoid cross contrib. to external lines
& 0,0,
& .false.,op_info)
! F -> H replacement:
op_pnt => op_info%op_arr(idx_2)%op
call form_op_replace(opf_pnt%name,op_pnt%name,
& .true.,flist_pnt,op_info)
if (ntest.ge.100) then
write(lulog,*) 'XF contribution:'
call print_form_list(lulog,flist_pnt0,op_info)
end if
call del_operator(op_scr_f,op_info)
end if
return
end
|
/* histogram/add.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_histogram.h>
#include "find.c"
int
gsl_histogram_increment (gsl_histogram * h, double x)
{
int status = gsl_histogram_accumulate (h, x, 1.0);
return status;
}
int
gsl_histogram_accumulate (gsl_histogram * h, double x, double weight)
{
const size_t n = h->n;
size_t index = 0;
int status = find (h->n, h->range, x, &index);
if (status)
{
return GSL_EDOM;
}
if (index >= n)
{
GSL_ERROR ("index lies outside valid range of 0 .. n - 1",
GSL_ESANITY);
}
h->bin[index] += weight;
return GSL_SUCCESS;
}
|
using TiledIteration
### Construction of loop expressions in type domain
### This is the fallback implementation for AbstractArrays
function arrayop_body{A<:AbstractArray, L,R,F,E}(name, ::Type{A},
op::Type{Assign{L,R,F,E}})
acc = kernel_expr(:($name.lhs), L) # :() will be ignored
rhs_inner = kernel_expr(:($name.rhs), R)
if hasreduceddims(op)
# we need to wrap the expression in a call to the reducer
expr = :($acc = $name.reducefn($acc, $rhs_inner))
else
expr = :($acc = $rhs_inner)
end
checks = :()
input_ranges = Any[]
simded = false
for (sym, spaces) in index_spaces(name, op) # sort this based on # of potential cache misses
if length(spaces) > 1
# check dimensions for equality
equal_dims = [:(indices($(d[3]), $(d[2]))) for d in spaces]
checks = :($checks; @assert allequal($(equal_dims...),))
end
T,dim,nm = first(spaces)
sym_range = Symbol("$(sym)_range")
push!(input_ranges, sym_range => :(indices($nm, $dim)))
expr = :(for $sym in $sym_range
$expr
end)
if !simded
# innermost loop
expr = :(@simd $expr)
simded = true
end
end
expr = quote
ranges = ($(map(last, input_ranges)...),)
@inbounds for tile in TileIterator(ranges, tilesize(ranges))
($(map(first, input_ranges)...),) = tile
$expr
end
end
:($checks; $expr; $name.lhs.array)
end
# constructs Dict
# Keys: indexing symbol
# Value: a list of (array type, dimension, expr) tuples which correspond to that
# indexing symbol
# Generate the expression corresponding to a type
function kernel_expr(name, itr)
kernel_expr(name, arraytype(itr), itr)
end
function kernel_expr{X, Idx, A<:AbstractArray}(name, ::Type{A},
itr::Type{Indexing{X, Idx}})
idx = get_subscripts(name, itr)
:($name.array[$(idx...)])
end
function kernel_expr{A<:AbstractArray, F, Ts}(name, ::Type{A},
itr::Type{Map{F, Ts}})
inner_kernels = [kernel_expr(:($name.arrays[$i]), arraytype(T), T)
for (i, T) in enumerate(Ts.parameters)]
:($name.f($(inner_kernels...)))
end
allequal(x) = true
function allequal(x, xs...)
x == xs[1] && allequal(xs...)
end
function tilesize(ranges)
map(x->16, ranges)
end
@inline @generated function arrayop!{L,R,A<:AbstractArray}(::Type{A}, t::Assign{L,R})
arrayop_body(:t, arraytype(L), t)
end
|
[STATEMENT]
lemma submonoid_nonempty: \<^marker>\<open>contributor \<open>Martin Baillon\<close>\<close>
"~ submonoid {} G"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<not> submonoid {} G
[PROOF STEP]
by (blast dest: submonoid.one_closed) |
lemma nth_root_nat_code_naive': "nth_root_nat k n = (if k = 0 then 0 else Max (Set.filter (\<lambda>m. m ^ k \<le> n) {..n}))" |
using DifferentialEquations
using Statistics
using StatsBase
using Plots
using LinearAlgebra
using Distributions
using HDF5
using JLD2
using GaussianMixtures
using Logging
logger = SimpleLogger(stdout, Logging.Error) # Quiet GaussianMixtures output
global_logger(logger);
# Compute total mRNA at each timepoint in each cell (for MMI2-SSB state)
function reduce_mmi(sol)
popsize = size(sol)[3]
mT = sum(sol[2:5,:,:], dims=1)
return reshape(mT[:,:,:], (size(sol)[2], popsize))
end
# Get mRNA 1 concentration at each timepoint in each cell (for repressilator or genetic oscillator state)
function reduce_repressilator(sim)
return sim[1, :, :]
end
function reduce_geneosc(sim)
return sim[1, :, :]
end
# Heatmap of state distributions at (final) timepoint across a range of signals
function perturbed_results_heatmap(results; reduction=reduce_mmi, time=nothing, signame="σR", statelabel="[Rtot]", maxrna=5, binwidth=0.25, kwargs...)
sR_values = keys(results) |> collect |> sort
bins = 0:binwidth:maxrna
final_histograms = map(sR_values) do sR
mTs = reduction(results[sR])
if isnothing(time)
states = mTs[end, :]
else
states = mTs[time, :]
end
fit(Histogram, states, bins).weights
end
matrix = hcat(final_histograms...)
heatmap(sR_values, collect(bins)[begin:(end - 1)] .+ Float64(bins.step / 2), matrix;
xlabel=signame, ylabel=statelabel, colorbar_title="Cells", xminorticks=10, tick_direction=:out, kwargs...)
end
# Separation (D) of two modes in a one-dimensional dataset
function bimode_distinguishability(data)
return bimode_distinguishability(GMM(2, reshape(data, length(data), 1)))
end
function bimode_distinguishability(model::GMM)
# "Separation of means relative to their widths"
# "D > 2 is required for a clean separation between the modes"
# --Oleg Y. Gnedin, http://www-personal.umich.edu/~ognedin/gmm/gmm_user_guide.pdf
μ = means(model)
return abs(μ[1] - μ[2]) / sqrt(sum(covars(model)) / 2)
end
# Bayesian Information Criterion for a GMM fit to a 1D dataset
function bic(model::GMM, data)
# https://github.com/scikit-learn/scikit-learn/blob/0d378913b/sklearn/mixture/_gaussian_mixture.py#L821-L823
average_log_likelihood = avll(model, reshape(data, length(data), 1))
nparams = length(means(model)) * 3 - 1 # mean, variance, weight (but weights must sum to 1)
return nparams * log(length(data)) - 2 * average_log_likelihood * length(data)
end
# ΔBIC, the advantage of a 2-Gaussian fit over a 1-Gaussian fit for a 1D dataset
function bic_bimodal_advantage(data)
data_reshaped = reshape(data, length(data), 1)
bic1 = bic(GMM(1, data_reshaped), data_reshaped)
bic2 = bic(GMM(2, data_reshaped), data_reshaped)
return bic1 - bic2 # Positive if bimodality allows a better model
end
# Time index at which a population timecourse reached equilibrium
function equilibriumindex(results, savedat=0.1, reduction=reduce_mmi; stabletime=100.0, checktime=5.0, maxrna=10, binwidth=0.25, mainspecies=2)
timesteps = collect(axes(results)[2])
bins = 0:binwidth:maxrna
histograms = map(t -> fit(Histogram, results[mainspecies, t, :], bins).weights, timesteps)
stableindex = stabletime / savedat |> round |> Int
final = dropdims(mean(hcat(histograms[stableindex:end]...); dims=2); dims=2)
rmsds = map(t -> sqrt(mean((histograms[t] .- final) .^ 2.0)), timesteps)
maxrmsd = maximum(rmsds[stableindex:end])
mTs = reduction(results)
totalmeans = dropdims(mean(mTs, dims=2); dims=2)
equilibriummean = mean(totalmeans[stableindex:end])
equilibriummaxmean = maximum(totalmeans[stableindex:end])
equilibriumminmean = minimum(totalmeans[stableindex:end])
ok_rmsd = false
ok_mean = false
candidate = missing
for index in 2:stableindex
cleared = false
if rmsds[index] > maxrmsd * 1.1
ok_rmsd = false
cleared = true
end
if !(equilibriumminmean < totalmeans[index] < equilibriummaxmean)
ok_mean = false
cleared = true
end
if cleared
candidate = missing
continue
end
if rmsds[index] < maxrmsd / 2
ok_rmsd = true
end
if sign(totalmeans[index - 1] - equilibriummean) != sign(totalmeans[index] - equilibriummean)
ok_mean = true
end
if ok_rmsd && ok_mean
if ismissing(candidate)
candidate = index
elseif (index - candidate) * savedat >= checktime
return candidate
end
end
end
return candidate
end
# Timecourse of population state mean and state distribution for a population
function timecourse_heatmap(results; startindex=first(axes(results)[2]), endindex=last(axes(results)[2]), savedat=0.1, stabletime=100.0, reduction=reduce_mmi, statename="[Rtot]", maxrna=10, binwidth=0.25, kwargs...)
mTs = reduction(results)
timesteps = collect(startindex:endindex)
bins = 0:binwidth:maxrna
step_histograms = map(timesteps) do time
fit(Histogram, mTs[time, :], bins).weights
end
matrix = hcat(step_histograms...)
diagram = heatmap(timesteps * savedat, collect(bins)[begin:(end - 1)] .+ Float64(bins.step / 2), matrix; xlabel="Time", ylabel=statename, colorbar_title="Cells", kwargs...)
means = dropdims(mean(mTs, dims=2); dims=2)
plot!(diagram, (timesteps .- 1) * savedat, means[timesteps], color=:white, legend=nothing)
stableindex = stabletime / savedat |> round |> Int
hline!(diagram, [mean(mTs[stableindex:end, :]), maximum(means[stableindex:end]), minimum(means[stableindex:end])], color=:gray, legend=nothing)
equilibriumstart = equilibriumindex(results, savedat, reduction; stabletime)
vline!(diagram, [(equilibriumstart - 1) * savedat], color=:green, legend=nothing)
xaxis!(diagram, xminorticks=10, tick_direction=:out, xlims=(0, (endindex - 1) * savedat))
yaxis!(diagram, ylims=(0, maxrna))
end
# Create a wrapper function that runs the original several times and produces the minimum (counters nondeterminism in GMM fit)
function takemin(wrap, runs)
function wrapper(args...)
results = map(_ -> wrap(args...), 1:runs)
return minimum(results)
end
return wrapper
end
# ΔBIC and separation line plot(s) for a set of signals (and different noise levels and initial conditions)
function perturbed_reestablishment_subplot(record, title; reduction=reduce_mmi, separation_lim=Inf, linekws=Dict())
sR_values = keys(record) |> collect |> sort
endpoints = map(sR_values) do sR
mTs = reduction(record[sR])
mTs[end, :]
end
distinguishabilities = map(takemin(bimode_distinguishability, 4), endpoints)
bicadvantages = map(takemin(bic_bimodal_advantage, 4), endpoints)
titlekws = Dict()
if ~isnothing(title)
titlekws = Dict(:title => title, :titlefontsize => 11)
end
subplot = plot(sR_values, bicadvantages; legend=nothing, ylabel="ΔBIC", yguidefontcolor=:blue, titlekws..., linekws...)
hline!(subplot, [0.0], color=:darkblue, legend=nothing)
twin = twinx(subplot)
plot!(twin, sR_values, distinguishabilities; color=:orange, xticks=:none, legend=nothing, ylabel="Separation", yguidefontcolor=:orange, linekws...)
hline!(twin, [2.0], color=:brown, legend=nothing)
yaxis!(twin, ylims=(0, separation_lim))
return subplot
end
function perturbed_reestablishment_plot(records; noiselabel="Noise", kwargs...)
subplots = map(noise -> perturbed_reestablishment_subplot(records[noise], "$noiselabel = $noise"; kwargs...), keys(records) |> collect |> sort)
plot(subplots..., layout=(length(keys(records)), 1), size=(600, 400), right_margin=15*Plots.mm)
end
function perturbed_reestablishment_plot(records::AbstractVector; noiselabel="Noise", size=(1000, 400), kwargs...)
columns = map(run -> map(noise ->
perturbed_reestablishment_subplot(run[noise], isnothing(noiselabel) ? nothing : "$noiselabel = $noise"; kwargs...),
keys(run) |> collect |> sort), records)
subplots = hcat(columns...)
plot(permutedims(subplots)..., layout=grid(length(columns[1]), length(columns)), size=size, left_margin=5*Plots.mm, right_margin=15*Plots.mm)
end
# Plot time to equilibrium for a set of signals (and different noise levels and initial conditions)
function perturbed_equilibrium_plot(records::Dict{T, Array{T, 3}}; savedat=0.1, kwargs...) where T <: Real
sR_values = keys(records) |> collect |> sort
equilibriumtimes = map(sR -> (equilibriumindex(records[sR]) - 1) * savedat, sR_values)
plot(sR_values, equilibriumtimes, xlabel="sR", ylabel="Time", legend=nothing; kwargs...)
end
function perturbed_equilibrium_plot(records::Dict{T, Dict{T, Array{T, 3}}}; kwargs...) where T <: Real
noises = keys(records) |> collect |> sort
subplots = map(noise -> perturbed_equilibrium_plot(records[noise]; title="Noise = $noise", titlefontsize=11, kwargs...), noises)
plot(subplots..., layout=(length(noises), 1))
end
function perturbed_equilibrium_plot(records::AbstractVector; kwargs...)
columns = map(run -> map(noise -> perturbed_equilibrium_plot(run[noise]; title="Noise = $noise", titlefontsize=11, kwargs...), keys(run) |> collect |> sort), records)
subplots = hcat(columns...)
plot(permutedims(subplots)..., layout=grid(length(columns[1]), length(columns)), link=:all, size=(1000, 450), left_margin=5*Plots.mm, bottom_margin=5*Plots.mm)
end
# Print maximum and median equilibrium times for populations in a range of signals (missing or 1000 if ET is too long to determine)
function eqtimestats(desc, records, span)
eqtimes = map(sR -> (equilibriumindex(records[sR]) - 1) * 0.1, span)
filled = replace(eqtimes, missing => 1000.0)
println(desc, "\tMax: ", maximum(eqtimes), "\t", "Avg: ", median(filled))
end
# Load a set of loose Python Gillespie results (filenames under "gillespie" directory, specified by regex) into a noise -> signal -> array dict to match Julia SDE outputs
function loadgillespies(re)
results = Dict{Float64, Dict{Float64, Array{Float64, 3}}}()
for filename in filter(f -> match(re, f) !== nothing, readdir("gillespie"))
file = h5open("gillespie/$filename")
noise = read(attributes(file)["V"])
if noise ∉ keys(results)
results[noise] = Dict{Float64, Array{Float64, 3}}()
end
signal = read(attributes(file)["s_m"])
data = read(file["results"])
results[noise][signal] = permutedims(data, reverse(1:ndims(data)))
close(file)
end
return results
end
|
Add LoadPath "." as OPAT.
Inductive day : Type :=
| monday : day
| tuesday : day
| wednesday : day
| thursday : day
| friday : day
| saturday : day
| sunday : day.
Theorem fridayIsFriday : friday = friday.
Proof.
reflexivity.
Qed.
|
lemmas Zfun_mult_right = bounded_bilinear.Zfun_right [OF bounded_bilinear_mult] |
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// test_simple_class.cpp
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// should pass compilation and execution
// invoke header for a custom archive test.
#include <cstddef> // NULL
#include <cstdio> // remove
#include <fstream>
#include <cmath>
#include <boost/math/special_functions/next.hpp>
#include <boost/config.hpp>
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std{
using ::remove;
}
#endif
#include "test_tools.hpp"
#include "A.hpp"
#include "A.ipp"
bool A::check_equal(const A &rhs) const
{
BOOST_CHECK_EQUAL(b, rhs.b);
BOOST_CHECK_EQUAL(l, rhs.l);
#ifndef BOOST_NO_INT64_T
BOOST_CHECK_EQUAL(f, rhs.f);
BOOST_CHECK_EQUAL(g, rhs.g);
#endif
BOOST_CHECK_EQUAL(m, rhs.m);
BOOST_CHECK_EQUAL(n, rhs.n);
BOOST_CHECK_EQUAL(o, rhs.o);
BOOST_CHECK_EQUAL(p, rhs.p);
BOOST_CHECK_EQUAL(q, rhs.q);
#ifndef BOOST_NO_CWCHAR
BOOST_CHECK_EQUAL(r, rhs.r);
#endif
BOOST_CHECK_EQUAL(c, rhs.c);
BOOST_CHECK_EQUAL(s, rhs.s);
BOOST_CHECK_EQUAL(t, rhs.t);
BOOST_CHECK_EQUAL(u, rhs.u);
BOOST_CHECK_EQUAL(v, rhs.v);
BOOST_CHECK_EQUAL(l, rhs.l);
BOOST_CHECK(std::abs( boost::math::float_distance(w, rhs.w)) < 2);
BOOST_CHECK(std::abs( boost::math::float_distance(x, rhs.x)) < 2);
BOOST_CHECK(!(0 != y.compare(rhs.y)));
#ifndef BOOST_NO_STD_WSTRING
BOOST_CHECK(!(0 != z.compare(rhs.z)));
#endif
return true;
}
int
test_main( int /* argc */, char* /* argv */[] )
{
const char * testfile = boost::archive::tmpnam(NULL);
BOOST_REQUIRE(NULL != testfile);
A a, a1;
{
test_ostream os(testfile, TEST_STREAM_FLAGS);
test_oarchive oa(os, TEST_ARCHIVE_FLAGS);
oa << boost::serialization::make_nvp("a", a);
}
{
test_istream is(testfile, TEST_STREAM_FLAGS);
test_iarchive ia(is, TEST_ARCHIVE_FLAGS);
ia >> boost::serialization::make_nvp("a", a1);
}
a.check_equal(a1);
std::remove(testfile);
return 0;
}
|
module L.Base.Coproduct.Properties where
-- There are no properties yet.
|
{-# LANGUAGE FlexibleContexts #-}
-----------------------------------------------------------------------------
{- |
Module : Numeric.LinearAlgebra.Util.Convolution
Copyright : (c) Alberto Ruiz 2012
License : GPL
Maintainer : Alberto Ruiz (aruiz at um dot es)
Stability : provisional
-}
-----------------------------------------------------------------------------
module Numeric.LinearAlgebra.Util.Convolution(
corr, conv, corrMin,
corr2, conv2, separable
) where
import Numeric.LinearAlgebra
vectSS :: Element t => Int -> Vector t -> Matrix t
vectSS n v = fromRows [ subVector k n v | k <- [0 .. dim v - n] ]
corr :: Product t => Vector t -- ^ kernel
-> Vector t -- ^ source
-> Vector t
{- ^ correlation
>>> corr (fromList[1,2,3]) (fromList [1..10])
fromList [14.0,20.0,26.0,32.0,38.0,44.0,50.0,56.0]
-}
corr ker v | dim ker <= dim v = vectSS (dim ker) v <> ker
| otherwise = error $ "corr: dim kernel ("++show (dim ker)++") > dim vector ("++show (dim v)++")"
conv :: (Product t, Num t) => Vector t -> Vector t -> Vector t
{- ^ convolution ('corr' with reversed kernel and padded input, equivalent to polynomial product)
>>> conv (fromList[1,1]) (fromList [-1,1])
fromList [-1.0,0.0,1.0]
-}
conv ker v = corr ker' v'
where
ker' = (flatten.fliprl.asRow) ker
v' | dim ker > 1 = join [z,v,z]
| otherwise = v
z = constant 0 (dim ker -1)
corrMin :: (Container Vector t, RealElement t, Product t)
=> Vector t
-> Vector t
-> Vector t
-- ^ similar to 'corr', using 'min' instead of (*)
corrMin ker v = minEvery ss (asRow ker) <> ones
where
minEvery a b = cond a b a a b
ss = vectSS (dim ker) v
ones = konst' 1 (dim ker)
matSS :: Element t => Int -> Matrix t -> [Matrix t]
matSS dr m = map (reshape c) [ subVector (k*c) n v | k <- [0 .. r - dr] ]
where
v = flatten m
c = cols m
r = rows m
n = dr*c
corr2 :: Product a => Matrix a -> Matrix a -> Matrix a
-- ^ 2D correlation
corr2 ker mat = dims
. concatMap (map ((<.> ker') . flatten) . matSS c . trans)
. matSS r $ mat
where
r = rows ker
c = cols ker
ker' = flatten (trans ker)
rr = rows mat - r + 1
rc = cols mat - c + 1
dims | rr > 0 && rc > 0 = (rr >< rc)
| otherwise = error $ "corr2: dim kernel ("++sz ker++") > dim matrix ("++sz mat++")"
sz m = show (rows m)++"x"++show (cols m)
conv2 :: (Num a, Product a) => Matrix a -> Matrix a -> Matrix a
-- ^ 2D convolution
conv2 k m = corr2 (fliprl . flipud $ k) pm
where
pm | r == 0 && c == 0 = m
| r == 0 = fromBlocks [[z3,m,z3]]
| c == 0 = fromBlocks [[z2],[m],[z2]]
| otherwise = fromBlocks [[z1,z2,z1]
,[z3, m,z3]
,[z1,z2,z1]]
r = rows k - 1
c = cols k - 1
h = rows m
w = cols m
z1 = konst' 0 (r,c)
z2 = konst' 0 (r,w)
z3 = konst' 0 (h,c)
-- TODO: could be simplified using future empty arrays
separable :: Element t => (Vector t -> Vector t) -> Matrix t -> Matrix t
-- ^ matrix computation implemented as separated vector operations by rows and columns.
separable f = fromColumns . map f . toColumns . fromRows . map f . toRows
|
-- Find the numbers in a list that are greater than a given number.
greater : Int -> List Int -> List Int
greater number list = filter (> number) list
-- Create data types representing even and odd numbers such that:
-- – The successor to an even number is an odd number, and
-- – The successor to an odd number is an even number.
data EvenOdd = Even Nat | Odd Nat
succ : EvenOdd -> EvenOdd
succ (Even n) = Odd (S n)
succ (Odd n) = Even (S n)
-- Build a parameterized data type representing a binary tree.
data BinaryTree a = Leaf a | Node (BinaryTree a) (BinaryTree a)
-- Reverse the elements of a list. (Hint: You may need some helper functions.)
reverse : List a -> List a
reverse = reverse' []
where
reverse' : List a -> List a -> List a
reverse' acc [] = acc
reverse' acc (x::xs) = reverse' (x::acc) xs
|
Festival of lights, Diwali is very big in India. It signifies victory of good over evil and light over darkness. Markets are bustling with mouth-watering sweets during this festival. I remember my mother working in the kitchen all day and preparing a feast for us which also involved making different sweets. Nariyal ki barfi, kheer-anand (thick rice pudding) and daal ki chaki was always on the menu. Sweets are also offered to friends and relatives who come to visit the following days.
It is always so hectic during Diwali. There is just so much to do - decorating the house, distributing sweets, making a lavish meal, sorting out clothes to wear, socializing. I wasn't sure if I would be able to share this recipe but I am happy I managed.
Today I am sharing a recipe which is a fusion between western and Indian dessert- "Pistachio-yoghurt cupcakes with cardamom frosting"! You know how elders just taste baked goodies because they don't quite enjoy flavor of vanilla and chocolate. This dessert is going to cater to elders as well as kids. My father-in-law flipped over these cupcakes.You can make them in advance, they won't get spoilt for 2-3 days. Drizzle frosting right before serving.
Indian sweets hardly bear any resemblance to Western desserts. Unlike Western desserts, most of the Indian desserts are either deep fried or cooked on an open flame. Mithai is usually made by combining milk and ingredients like semolina, chickpea flour, desiccated coconut and dried-fruit together. Flavored with saffron, cardamom and rose water, mithiais are very aromatic. I have always had a weakness for crisp jalebis and daal ka halwa!
This is actually a mithai( Indian sweet) disguised as a cupcake. Pistachio and aromatic cardamom pods create a beautiful flavour which reminds you of Indian sweets as soon as you taste it! Use of yoghurt does wonders with baking powder and makes cupcakes very moist. Cupcakes just melt in your mouth!
Preheat oven for 10 minutes at 180 degrees Celsius - Golden rule!
Strain flour, baking powder and baking soda together and keep aside.
Now fold dry ingredients, ground pistachio and yoghurt lightly in the creamed butter-sugar mixture. Make sure to not over-beat. You just have to incorporate all the ingredients together.
Pour batter in the cupcake tray and bake at 180 degrees for 15-20 minutes till skewer or knife comes out clean.
Mix icing sugar and a pinch of cardamom powder with few drops of water. If sugar doesn't come together, add more.
Drizzle over cupcakes and garnish with chopped pistachios.
Don't forget to try other desserts and snacks from the blog. Wishing everyone a very happy and safe Diwali!!
Looking for more recipes to satisfy your sweet tooth?? |
infix 5 ^
(^) : Nat -> %static Nat -> Nat
(^) x Z = 1
(^) x (S k) = mult x (x ^ k)
powFn : Nat -> Nat
powFn x = (x ^ 2) + 1
calc : Int -> Int
calc x = (x * x) + x
myMap : %static (a -> b) -> List a -> List b
myMap f [] = []
myMap f (x :: xs) = f x :: myMap f xs
doubleAll : List Int -> List Int
doubleAll xs = myMap (* 2) xs
|
The sets of the interval measure $F$ are the same as the sets of the Borel measure. |
At the Wedding Car Hire People, we have the largest and most varied fleet of wedding transport available in Underwood and surrounding areas of Devon. You can browse the various types of Underwood wedding cars by clicking in a category below. We have something for everybody at the most competitive prices. We specialise in traditional vintage wedding cars, luxury modern wedding cars and unique wedding cars, some of the popular bridal car models include VW Campervans & VW Beetles, Jaguar, Mercedes, Rolls Royce, Bentley, Beauford, Austin, Daimler, Range Rover and more.
We have a variety of vintage and classic wedding cars available to hire in Underwood, models include, Rolls Royce, Bentley, Austin & Beauford.
We have many modern executive style luxury wedding cars for hire in Underwood, including Mercedes, Jaguars, Range Rovers and Chryslers.
We have a vast selection of unique wedding transport available to hire in Underwood, including VW campervans & Beetles, character vehicles & American cars.
We have taken care to offer you only the best wedding cars in Underwood. We are proud to present a selection of classic, vintage, modern and retro wedding day transport.
Booking your wedding car through The Wedding Car Hire People in Underwood, ensures that you will receive the highest quality car and service. All of the bridal rental cars have been meticulously maintained to the highest of standards in accordance with the National Association of Wedding Car Professionals. You can be confident that the premium wedding car service booked through us will be an extra special part of your big day. Every wedding is different, so although we have a standard package all bookings placed with us, will always include a smartly dressed chauffeur, ribbons & bows, a fully detailed itinerary with the actual service delivered on the day is tailored to your specific requirements. We can cater for all your wedding day requirements with bridal cars, bridesmaids’ cars, grooms’ cars and even cars to carry the whole of your wedding party.
Our 'Prices & Availability' page shows LIVE availability, showing you what cars are available in Underwood.
We have a great team of people to deal with all your questions about wedding car rental in Underwood, Devon. We have specialist knowledge and can help you make the perfect choice of wedding day transportation and assist you in understanding your itinerary requirements. Whether it’s just a fancy car to get you from A to B or whether it’s a fleet of vintage wedding cars you need to wow your wedding guests, our dedicated team will always be happy to help. We pride ourselves of delivering great customer service every time, so every wedding day transport quote we send, enquiry we deal with and booking we take are handled quickly, efficiently and professionally by one of team members. Our support team are on hand to help you make the right choice and guide you through the wedding car quotation and booking process. Our website offers you the ability to browse through the fleet of wedding cars for hire and display photos, videos and many testimonials from our valued customers. See LIVE vehicle availability in Underwood on our Instant quote page.
We have the only best wedding cars in Underwood. We offer an award-winning service and an amazing Instant quotation system that displays the actual cars that are available near you in Underwood and sends you an instant email with accurate wedding car prices, based on your unique transport requirements. You have 24hr access to your LIVE itinerary and are able to make secure online payments by credit or debit card. Underwood Wedding cars booked through us will always, be chauffeur driven by a smartly dressed driver, follow the itinerary we agree together, be dressed in ribbon and bows and be fully valeted prior to your wedding.
Kitley House Hotel in Plymouth, Langdon Court Hotel in Plymouth, The Orangery in Cornwall are all places were we deliver our Wedding car service whether it’s for the wedding ceremony or the reception in Underwood. If you have not chosen your wedding venue yet, check out some of the links below to get some inspiration – don’t forget to come back to us for all your Wedding car needs. |
{-# OPTIONS --without-K --safe #-}
module Categories.Category.Instance.Rels where
open import Data.Product
open import Function hiding (_⇔_)
open import Level
open import Relation.Binary
open import Relation.Binary.Construct.Composition
open import Relation.Binary.PropositionalEquality
open import Categories.Category.Core
-- the category whose objects are sets and whose morphisms are binary relations.
Rels : ∀ o ℓ → Category (suc o) (suc (o ⊔ ℓ)) (o ⊔ ℓ)
Rels o ℓ = record
{ Obj = Set o
; _⇒_ = λ A B → REL A B (o ⊔ ℓ)
; _≈_ = λ L R → L ⇔ R
; id = λ x y → Lift ℓ (x ≡ y)
; _∘_ = λ L R → R ; L
; assoc = (λ { (b , fxb , c , gbc , hcy) → c , ((b , (fxb , gbc)) , hcy)})
, λ { (c , (b , fxb , gbc) , hcy) → b , fxb , c , gbc , hcy}
; sym-assoc = (λ { (c , (b , fxb , gbc) , hcy) → b , fxb , c , gbc , hcy})
, (λ { (b , fxb , c , gbc , hcy) → c , ((b , (fxb , gbc)) , hcy)})
; identityˡ = (λ { (b , fxb , lift refl) → fxb}) , λ {_} {y} fxy → y , fxy , lift refl
; identityʳ = (λ { (a , lift refl , fxy) → fxy}) , λ {x} {_} fxy → x , lift refl , fxy
; identity² = (λ { (_ , lift p , lift q) → lift (trans p q)}) , λ { (lift refl) → _ , lift refl , lift refl }
; equiv = record
{ refl = id , id
; sym = swap
; trans = λ { (p₁ , p₂) (q₁ , q₂) → (q₁ ∘′ p₁) , p₂ ∘′ q₂}
}
; ∘-resp-≈ = λ f⇔h g⇔i →
(λ { (b , gxb , fky) → b , proj₁ g⇔i gxb , proj₁ f⇔h fky }) ,
λ { (b , ixb , hby) → b , proj₂ g⇔i ixb , proj₂ f⇔h hby }
}
|
[STATEMENT]
lemma sqrt_without_multiplication: "VARS u w r
{x=X}
u := 1; w := 1; r := (0::nat);
WHILE w <= X
INV {u = r+r+1 & w = (r+1)*(r+1) & r*r <= X}
DO r := r + 1; w := w + u + 2; u := u + 2 OD
{r*r <= X & X < (r+1)*(r+1)}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. {x = X}
u := 1; w := 1; r := 0; WHILE w \<le> X INV {u = r + r + 1 \<and> w = (r + 1) * (r + 1) \<and> r * r \<le> X} VAR {0}
DO r := r + 1; w := w + u + 2; u := u + 2 OD
{r * r \<le> X \<and> X < (r + 1) * (r + 1)}
[PROOF STEP]
apply vcg_simp
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
(* Copyright (c) 2012-2015, Robbert Krebbers. *)
(* This file is distributed under the terms of the BSD license. *)
Require Import memory_separation assignments.
Lemma assign_sem_subseteq `{EnvSpec K} Γ Δ m1 m2 a v ass va v' τ1 τ2 :
✓ Γ → ✓{Γ,Δ} m1 → assign_typed τ1 τ2 ass →
(Γ,Δ) ⊢ a : TType τ1 → (Γ,Δ) ⊢ v : τ2 →
assign_sem Γ m1 a v ass va v' → m1 ⊆ m2 → assign_sem Γ m2 a v ass va v'.
Proof.
destruct 3; inversion 3; econstructor; simplify_type_equality'; eauto 8 using
mem_lookup_subseteq, val_cast_ok_weaken, val_binop_ok_weaken,
cmap_subseteq_index_alive, mem_lookup_typed, val_binop_typed.
Qed. |
lemma closure_halfspace_lt [simp]: assumes "a \<noteq> 0" shows "closure {x. a \<bullet> x < b} = {x. a \<bullet> x \<le> b}" |
------------------------------------------------------------------------
-- The Agda standard library
--
-- M-types (the dual of W-types)
------------------------------------------------------------------------
{-# OPTIONS --without-K --guardedness --sized-types #-}
module Codata.Musical.M where
open import Codata.Musical.Notation
open import Level
open import Data.Product hiding (map)
open import Data.Container.Core as C hiding (map)
-- The family of M-types.
data M {s p} (C : Container s p) : Set (s ⊔ p) where
inf : ⟦ C ⟧ (∞ (M C)) → M C
-- Projections.
module _ {s p} (C : Container s p) where
head : M C → Shape C
head (inf (x , _)) = x
tail : (x : M C) → Position C (head x) → M C
tail (inf (x , f)) b = ♭ (f b)
-- map
module _ {s₁ s₂ p₁ p₂} {C₁ : Container s₁ p₁} {C₂ : Container s₂ p₂}
(m : C₁ ⇒ C₂) where
map : M C₁ → M C₂
map (inf (x , f)) = inf (shape m x , λ p → ♯ map (♭ (f (position m p))))
-- unfold
module _ {s p ℓ} {C : Container s p} (open Container C)
{S : Set ℓ} (alg : S → ⟦ C ⟧ S) where
unfold : S → M C
unfold seed = let (x , f) = alg seed in
inf (x , λ p → ♯ unfold (f p))
------------------------------------------------------------------------
-- Legacy
import Codata.M as M
open import Codata.Thunk
import Size
module _ {s p} {C : Container s p} where
fromMusical : ∀ {i} → M C → M.M C i
fromMusical (inf t) = M.inf (C.map rec t) where
rec = λ x → λ where .force → fromMusical (♭ x)
toMusical : M.M C Size.∞ → M C
toMusical (M.inf (s , f)) = inf (s , λ p → ♯ toMusical (f p .force))
|
lemma convex_translation_eq [simp]: "convex ((+) a ` s) \<longleftrightarrow> convex s" |
The 10th Republican debate is set for tonight just five days before Super Tuesday.
There is only one Savior, Marco Rubio said at Thursday night’s debate.
Donald Trump has stated that he is boycotting this evening’s debate because he believes moderator Megyn Kelly will not treat him fairly.
CNN News is giving Thursday’s debate win to Donald Trump, Ted Cruz and Chris Christie.
Republican presidential candidates are preparing for Thursday’s debate in South Carolina.
The fifth Republican presidential debate focused on the threat of radical Islamic terrorism and how each candidate proposes to keep the U.S. safe if elected president. |
module Main
import Data.Vect
%flag C "-g3"
%flag C "-ggdb"
%flag C "-O0"
rep : (n : Nat) -> Char -> Vect n Char
rep Z x = []
rep (S k) x = x :: rep k x
data RLE : Vect n Char -> Type where
REnd : RLE []
RChar : .{k : Nat}
-> {xs : Vect k Char}
-> (n : Nat)
-> (x : Char)
-> RLE xs
-> RLE (rep (S n) x ++ xs)
eq : (x : Char) -> (y : Char) -> Maybe (x = y)
eq x y = if x == y then Just (believe_me (Refl {x})) else Nothing
------------
rle : (xs : Vect n Char) -> RLE xs
rle [] = REnd
rle (x :: xs) with (rle xs)
rle (x :: Vect.Nil) | REnd = RChar Z x REnd
rle (x :: rep (S n) yvar ++ ys) | RChar n yvar rs with (eq x yvar)
rle (x :: rep (S n) x ++ ys) | RChar n x rs | Just Refl
= RChar (S n) x rs
rle (x :: rep (S n) y ++ ys) | RChar n y rs | Nothing
= RChar Z x (RChar n y rs)
compress : Vect n Char -> String
compress xs with (rle xs)
compress Nil | REnd = ""
compress (rep (S n) x ++ xs) | RChar _ _ rs
= let ni : Integer = cast (S n) in
show ni ++ strCons x (compress xs)
{-
fmt : {xs : Vect n Char} -> RLE xs -> String
fmt REnd = ""
fmt (RChar n c xs) = show n ++ show c ++ fmt xs
-}
compressString : String -> String
compressString xs = compress (fromList (unpack xs))
main : IO ()
main = putStrLn (compressString "foooobaaaarbaaaz")
|
[STATEMENT]
lemma num_stl[simp]:
assumes "ev (\<lambda>xs. P (shd xs)) xs" and "\<not> P (shd xs)"
shows "num P xs = Suc (num P (stl xs))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. num P xs = Suc (num P (stl xs))
[PROOF STEP]
unfolding num_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (LEAST n. list_all (Not \<circ> P) (stake n xs) \<and> P (xs !! n)) = Suc (LEAST n. list_all (Not \<circ> P) (stake n (stl xs)) \<and> P (stl xs !! n))
[PROOF STEP]
by (rule trans[OF Least_Suc[of _ "num P xs"]])
(auto simp: num[OF assms(1)] assms(2)) |
lemma quot_of_fract_to_fract [simp]: "quot_of_fract (to_fract x) = (x, 1)" |
------------------------------------------------------------------------
-- An up-to technique for weak similarity
------------------------------------------------------------------------
{-# OPTIONS --sized-types #-}
open import Labelled-transition-system
module Similarity.Weak.Up-to {ℓ} (lts : LTS ℓ) where
open import Logical-equivalence using (_⇔_)
open import Prelude
open import Prelude.Size
open import Equational-reasoning
open import Expansion lts using (Expansion)
open import Relation
open import Similarity.Weak lts
import Similarity.Weak.Equational-reasoning-instances
import Up-to
open LTS lts
------------------------------------------------------------------------
-- The general up-to machinery, instantiated with the StepC container
open Up-to StepC public
------------------------------------------------------------------------
-- An example
-- Up to expansion to the left and weak similarity to the right.
--
-- This is a generalisation of the non-symmetric up-to technique
-- presented by Pous and Sangiorgi in Section 6.5.2.4 of "Enhancements
-- of the bisimulation proof method".
Up-to-expansion-and-weak-similarity : Trans₂ ℓ Proc
Up-to-expansion-and-weak-similarity R =
Expansion ∞ ⊙ R ⊙ Weak-similarity ∞
-- The relation transformer is monotone.
up-to-expansion-and-weak-similarity-monotone :
Monotone Up-to-expansion-and-weak-similarity
up-to-expansion-and-weak-similarity-monotone R⊆S =
Σ-map id (Σ-map id (Σ-map id (Σ-map R⊆S id)))
-- The relation transformer is size-preserving.
up-to-expansion-and-weak-similarity-size-preserving :
Size-preserving Up-to-expansion-and-weak-similarity
up-to-expansion-and-weak-similarity-size-preserving =
_⇔_.from (monotone→⇔ up-to-expansion-and-weak-similarity-monotone)
(λ where
{x = p , q} (r , p≳r , s , r≼s , s≼q) →
p ∼⟨ p≳r ⟩
r ∼′⟨ r≼s ⟩ ≼:
s ∼⟨ s≼q ⟩■
q)
|
section \<open>Maximal Path Tries\<close>
text \<open>Drastically reduced implementation of tries that consider only maximum length sequences as elements.
Inserting a sequence that is prefix of some already contained sequence does not alter the trie.
Intended to store IO-sequences to apply in testing, as in this use-case proper prefixes need not be applied separately.\<close>
theory Maximal_Path_Trie
imports Util
begin
subsection \<open>Utils for Updating Associative Lists\<close>
fun update_assoc_list_with_default :: "'a \<Rightarrow> ('b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> ('a \<times> 'b) list \<Rightarrow> ('a \<times> 'b) list" where
"update_assoc_list_with_default k f d [] = [(k,f d)]" |
"update_assoc_list_with_default k f d ((x,y)#xys) = (if k = x
then ((x,f y)#xys)
else (x,y) # (update_assoc_list_with_default k f d xys))"
lemma update_assoc_list_with_default_key_found :
assumes "distinct (map fst xys)"
and "i < length xys"
and "fst (xys ! i) = k"
shows "update_assoc_list_with_default k f d xys =
((take i xys) @ [(k, f (snd (xys ! i)))] @ (drop (Suc i) xys))"
using assms proof (induction xys arbitrary: i)
case Nil
then show ?case by auto
next
case (Cons a xys)
show ?case
proof (cases i)
case 0
then have "fst a = k" using Cons.prems(3) by auto
then have "update_assoc_list_with_default k f d (a#xys) = (k, f (snd a)) # xys"
unfolding 0 by (metis prod.collapse update_assoc_list_with_default.simps(2))
then show ?thesis unfolding 0 by auto
next
case (Suc j)
then have "fst a \<noteq> k"
using Cons.prems by auto
have "distinct (map fst xys)"
and "j < length xys"
and "fst (xys ! j) = k"
using Cons.prems unfolding Suc by auto
then have "update_assoc_list_with_default k f d xys = take j xys @ [(k, f (snd (xys ! j)))] @ drop (Suc j) xys"
using Cons.IH[of j] by auto
then show ?thesis unfolding Suc using \<open>fst a \<noteq> k\<close>
by (metis append_Cons drop_Suc_Cons nth_Cons_Suc prod.collapse take_Suc_Cons update_assoc_list_with_default.simps(2))
qed
qed
lemma update_assoc_list_with_default_key_not_found :
assumes "distinct (map fst xys)"
and "k \<notin> set (map fst xys)"
shows "update_assoc_list_with_default k f d xys = xys @ [(k,f d)]"
using assms by (induction xys; auto)
lemma update_assoc_list_with_default_key_distinct :
assumes "distinct (map fst xys)"
shows "distinct (map fst (update_assoc_list_with_default k f d xys))"
proof (cases "k \<in> set (map fst xys)")
case True
then obtain i where "i < length xys" and "fst (xys ! i) = k"
by (metis in_set_conv_nth length_map nth_map)
then have *: "(map fst (take i xys @ [(k, f (snd (xys ! i)))] @ drop (Suc i) xys)) = (map fst xys)"
proof -
have "xys ! i # drop (Suc i) xys = drop i xys"
using Cons_nth_drop_Suc \<open>i < length xys\<close> by blast
then show ?thesis
by (metis (no_types) \<open>fst (xys ! i) = k\<close> append_Cons append_self_conv2 append_take_drop_id fst_conv list.simps(9) map_append)
qed
show ?thesis
unfolding update_assoc_list_with_default_key_found[OF assms \<open>i < length xys\<close> \<open>fst (xys ! i) = k\<close>] *
using assms by assumption
next
case False
have *: "(map fst (xys @ [(k, f d)])) = (map fst xys)@[k]" by auto
show ?thesis
using assms False
unfolding update_assoc_list_with_default_key_not_found[OF assms False] * by auto
qed
subsection \<open>Maximum Path Trie Implementation\<close>
datatype 'a mp_trie = MP_Trie "('a \<times> 'a mp_trie) list"
fun mp_trie_invar :: "'a mp_trie \<Rightarrow> bool" where
"mp_trie_invar (MP_Trie ts) = (distinct (map fst ts) \<and> (\<forall> t \<in> set (map snd ts) . mp_trie_invar t))"
definition empty :: "'a mp_trie" where
"empty = MP_Trie []"
lemma empty_invar : "mp_trie_invar empty" unfolding empty_def by auto
fun height :: "'a mp_trie \<Rightarrow> nat" where
"height (MP_Trie []) = 0" |
"height (MP_Trie (xt#xts)) = Suc (foldr (\<lambda> t m . max (height t) m) (map snd (xt#xts)) 0)"
lemma height_0 :
assumes "height t = 0"
shows "t = empty"
proof (rule ccontr)
assume "t \<noteq> empty"
then obtain xt xts where "t = MP_Trie (xt#xts)"
by (metis empty_def height.cases)
have "height t > 0"
unfolding \<open>t = MP_Trie (xt#xts)\<close> height.simps
by simp
then show "False"
using assms by simp
qed
lemma height_inc :
assumes "t \<in> set (map snd ts)"
shows "height t < height (MP_Trie ts)"
proof -
obtain xt xts where "ts = xt#xts"
using assms
by (metis list.set_cases list_map_source_elem)
have "height t < Suc (foldr (\<lambda> t m . max (height t) m) (map snd (xt#xts)) 0)"
using assms unfolding \<open>ts = xt#xts\<close> using max_by_foldr[of t "(map snd (xt#xts))" height]
by blast
then show ?thesis unfolding \<open>ts = xt#xts\<close> by auto
qed
fun insert :: "'a list \<Rightarrow> 'a mp_trie \<Rightarrow> 'a mp_trie" where
"insert [] t = t" |
"insert (x#xs) (MP_Trie ts) = (MP_Trie (update_assoc_list_with_default x (\<lambda> t . insert xs t) empty ts))"
lemma insert_invar : "mp_trie_invar t \<Longrightarrow> mp_trie_invar (insert xs t)"
proof (induction xs arbitrary: t)
case Nil
then show ?case by auto
next
case (Cons x xs)
obtain ts where "t = MP_Trie ts"
using mp_trie_invar.cases by auto
then have "distinct (map fst ts)"
and "\<And> t . t \<in> set (map snd ts) \<Longrightarrow> mp_trie_invar t"
using Cons.prems by auto
show ?case proof (cases "x \<in> set (map fst ts)")
case True
then obtain i where "i < length ts" and "fst (ts ! i) = x"
by (metis in_set_conv_nth length_map nth_map)
have "insert (x#xs) (MP_Trie ts) = (MP_Trie (take i ts @ [(x, insert xs (snd (ts ! i)))] @ drop (Suc i) ts))"
unfolding insert.simps empty_def
unfolding update_assoc_list_with_default_key_found[OF \<open>distinct (map fst ts)\<close> \<open>i < length ts\<close> \<open>fst (ts ! i) = x\<close>
,of "(\<lambda> t . insert xs t)" "(MP_Trie [])"]
by simp
have "\<And> t . t \<in> set (map snd (take i ts @ [(x, insert xs (snd (ts ! i)))] @ drop (Suc i) ts)) \<Longrightarrow> mp_trie_invar t"
proof -
fix t assume "t \<in> set (map snd (take i ts @ [(x, insert xs (snd (ts ! i)))] @ drop (Suc i) ts))"
then consider (a) "t \<in> set (map snd (take i ts @ drop (Suc i) ts))" |
(b) "t = insert xs (snd (ts ! i))"
by auto
then show "mp_trie_invar t" proof cases
case a
then have "t \<in> set (map snd ts)"
by (metis drop_map in_set_dropD in_set_takeD list_concat_non_elem map_append take_map)
then show ?thesis using \<open>\<And> t . t \<in> set (map snd ts) \<Longrightarrow> mp_trie_invar t\<close> by blast
next
case b
have "(snd (ts ! i)) \<in> set (map snd ts)"
using \<open>i < length ts\<close> by auto
then have "mp_trie_invar (snd (ts ! i))" using \<open>\<And> t . t \<in> set (map snd ts) \<Longrightarrow> mp_trie_invar t\<close> by blast
then show ?thesis using Cons.IH unfolding b by blast
qed
qed
moreover have "distinct (map fst (take i ts @ [(x, insert xs (snd (ts ! i)))] @ drop (Suc i) ts))"
using update_assoc_list_with_default_key_distinct[OF \<open>distinct (map fst ts)\<close>]
by (metis \<open>distinct (map fst ts)\<close> \<open>fst (ts ! i) = x\<close> \<open>i < length ts\<close> update_assoc_list_with_default_key_found)
ultimately show ?thesis
unfolding \<open>t = MP_Trie ts\<close> \<open>insert (x#xs) (MP_Trie ts) = (MP_Trie (take i ts @ [(x, insert xs (snd (ts ! i)))] @ drop (Suc i) ts))\<close>
by auto
next
case False
have "mp_trie_invar (insert xs empty)"
by (simp add: empty_invar Cons.IH)
then show ?thesis
using Cons.prems update_assoc_list_with_default_key_distinct[OF \<open>distinct (map fst ts)\<close>, of x "(insert xs)" "(MP_Trie [])"]
unfolding \<open>t = MP_Trie ts\<close> insert.simps
unfolding update_assoc_list_with_default_key_not_found[OF \<open>distinct (map fst ts)\<close> False]
by auto
qed
qed
fun paths :: "'a mp_trie \<Rightarrow> 'a list list" where
"paths (MP_Trie []) = [[]]" |
"paths (MP_Trie (t#ts)) = concat (map (\<lambda> (x,t) . map ((#) x) (paths t)) (t#ts))"
value "insert [1,2,3,4] (empty :: nat mp_trie)"
value "insert [1,2,5,6] (insert [1,2,3,4] (empty :: nat mp_trie))"
value "insert [1,2,5,7] (insert [1,2,5,6] (insert [1,2,3,4] (empty :: nat mp_trie)))"
value "paths (insert [1,2,5,7] (insert [1,2,5,6] (insert [1,2,3,4] (empty :: nat mp_trie))))"
lemma paths_empty :
assumes "[] \<in> set (paths t)"
shows "t = empty"
proof (rule ccontr)
assume "t \<noteq> empty"
then obtain xt xts where "t = MP_Trie (xt#xts)"
by (metis empty_def height.cases)
then have "[] \<in> set (concat (map (\<lambda> (x,t) . map ((#) x) (paths t)) (xt#xts)))"
using assms by auto
then show "False" by auto
qed
lemma paths_nonempty :
assumes "[] \<notin> set (paths t)"
shows "set (paths t) \<noteq> {}"
using assms proof (induction t rule: mp_trie_invar.induct)
case (1 ts)
have "ts \<noteq> []" using "1.prems" by auto
then obtain x t xts where "ts = ((x,t)#xts)"
using linear_order_from_list_position'.cases
by (metis old.prod.exhaust)
then have "t \<in> set (map snd ts)" by auto
show ?case
proof (cases "[] \<in> set (paths t)")
case True
then show ?thesis
unfolding \<open>ts = ((x,t)#xts)\<close> paths.simps by auto
next
case False
show ?thesis
using "1.IH"[OF \<open>t \<in> set (map snd ts)\<close> False]
unfolding \<open>ts = ((x,t)#xts)\<close> paths.simps by auto
qed
qed
lemma paths_maximal: "mp_trie_invar t \<Longrightarrow> xs' \<in> set (paths t) \<Longrightarrow> \<not> (\<exists> xs'' . xs'' \<noteq> [] \<and> xs'@xs'' \<in> set (paths t))"
proof (induction xs' arbitrary: t)
case Nil
then have "t = empty"
using paths_empty by blast
then have "paths t = [[]]"
by (simp add: empty_def)
then show ?case by auto
next
case (Cons x xs')
then have "t \<noteq> empty" unfolding empty_def by auto
then obtain xt xts where "t = MP_Trie (xt#xts)"
by (metis empty_def height.cases)
obtain t' where "(x,t') \<in> set (xt#xts)"
and "xs' \<in> set (paths t')"
using Cons.prems(2)
unfolding \<open>t = MP_Trie (xt#xts)\<close> paths.simps
by force
have "mp_trie_invar t'"
using Cons.prems(1) \<open>(x,t') \<in> set (xt#xts)\<close> unfolding \<open>t = MP_Trie (xt#xts)\<close> by auto
show ?case
proof
assume "\<exists>xs''. xs'' \<noteq> [] \<and> (x # xs') @ xs'' \<in> set (paths t)"
then obtain xs'' where "xs'' \<noteq> []" and "(x # (xs' @ xs'')) \<in> set (paths (MP_Trie (xt # xts)))"
unfolding \<open>t = MP_Trie (xt#xts)\<close> by force
obtain t'' where "(x,t'') \<in> set (xt#xts)"
and "(xs' @ xs'') \<in> set (paths t'')"
using \<open>(x # (xs' @ xs'')) \<in> set (paths (MP_Trie (xt # xts)))\<close>
unfolding \<open>t = MP_Trie (xt#xts)\<close> paths.simps
by force
have "distinct (map fst (xt#xts))"
using Cons.prems(1) unfolding \<open>t = MP_Trie (xt#xts)\<close> by simp
then have "t'' = t'"
using \<open>(x,t') \<in> set (xt#xts)\<close> \<open>(x,t'') \<in> set (xt#xts)\<close>
by (meson eq_key_imp_eq_value)
then have "xs'@xs'' \<in> set (paths t')"
using \<open>(xs' @ xs'') \<in> set (paths t'')\<close> by auto
then show "False"
using \<open>xs'' \<noteq> []\<close> Cons.IH[OF \<open>mp_trie_invar t'\<close> \<open>xs' \<in> set (paths t')\<close>] by blast
qed
qed
lemma paths_insert_empty :
"paths (insert xs empty) = [xs]"
proof (induction xs)
case Nil
then show ?case unfolding empty_def by auto
next
case (Cons x xs)
then show ?case unfolding empty_def insert.simps by auto
qed
lemma paths_order :
assumes "set ts = set ts'"
and "length ts = length ts'" (* length requirement not actually necessary *)
shows "set (paths (MP_Trie ts)) = set (paths (MP_Trie ts'))"
using assms(2,1) proof (induction ts ts' rule: list_induct2)
case Nil
then show ?case by auto
next
case (Cons x xs y ys)
have scheme: "\<And> f xs ys . set xs = set ys \<Longrightarrow> set (concat (map f xs)) = set (concat (map f ys))"
by auto
show ?case
using scheme[OF Cons.prems(1), of "(\<lambda>(x, t). map ((#) x) (paths t))"] by simp
qed
lemma paths_insert_maximal :
assumes "mp_trie_invar t"
shows "set (paths (insert xs t)) = (if (\<exists> xs' . xs@xs' \<in> set (paths t))
then set (paths t)
else Set.insert xs (set (paths t) - {xs' . \<exists> xs'' . xs'@xs'' = xs}))"
using assms proof (induction xs arbitrary: t)
case Nil
then show ?case
using paths_nonempty by force
next
case (Cons x xs)
show ?case proof (cases "t = empty")
case True
show ?thesis
unfolding True
unfolding paths_insert_empty
unfolding empty_def paths.simps by auto
next
case False
then obtain xt xts where "t = MP_Trie (xt#xts)"
by (metis empty_def height.cases)
then have "t = MP_Trie ((fst xt, snd xt)#xts)"
by auto
have "distinct (map fst (xt#xts))"
using Cons.prems \<open>t = MP_Trie (xt#xts)\<close> by auto
have "(paths t) = concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (xt # xts))"
unfolding \<open>t = MP_Trie ((fst xt, snd xt)#xts)\<close> by simp
then have "set (paths t) = {x#xs | x xs t . (x,t) \<in> set (xt#xts) \<and> xs \<in> set (paths t)}"
by auto
then have "Set.insert (x#xs) (set (paths t)) = Set.insert (x#xs) {x#xs | x xs t . (x,t) \<in> set (xt#xts) \<and> xs \<in> set (paths t)}"
by blast
show ?thesis proof (cases "x \<in> set (map fst (xt#xts))")
case True
case True
then obtain i where "i < length (xt#xts)" and "fst ((xt#xts) ! i) = x"
by (metis in_set_conv_nth list_map_source_elem)
then have "((xt#xts) ! i) = (x,snd ((xt#xts) ! i))" by auto
have "mp_trie_invar (snd ((xt # xts) ! i))"
using Cons.prems \<open>i < length (xt#xts)\<close> unfolding \<open>t = MP_Trie (xt#xts)\<close>
by (metis \<open>(xt # xts) ! i = (x, snd ((xt # xts) ! i))\<close> in_set_zipE mp_trie_invar.simps nth_mem zip_map_fst_snd)
have "insert (x#xs) t = MP_Trie (take i (xt # xts) @ [(x, insert xs (snd ((xt # xts) ! i)))] @ drop (Suc i) (xt # xts))"
unfolding \<open>t = MP_Trie (xt#xts)\<close> insert.simps
unfolding update_assoc_list_with_default_key_found[OF \<open>distinct (map fst (xt#xts))\<close> \<open>i < length (xt#xts)\<close> \<open>fst ((xt#xts) ! i) = x\<close>]
by simp
then have "set (paths (insert (x#xs) t))
= set (paths (MP_Trie (take i (xt # xts) @ [(x, insert xs (snd ((xt # xts) ! i)))] @ drop (Suc i) (xt # xts))))"
by simp
also have "... = set (paths (MP_Trie ((x, insert xs (snd ((xt # xts) ! i))) # (take i (xt # xts) @ drop (Suc i) (xt # xts)))))"
using paths_order[of "(take i (xt # xts) @ [(x, insert xs (snd ((xt # xts) ! i)))] @ drop (Suc i) (xt # xts))"
"((x, insert xs (snd ((xt # xts) ! i))) # (take i (xt # xts) @ drop (Suc i) (xt # xts)))"]
by force
also have "... = set ((map ((#) x) (paths (insert xs (snd ((xt # xts) ! i))))) @ (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (take i (xt # xts) @ drop (Suc i) (xt # xts)))))"
unfolding paths.simps by force
finally have "set (paths (insert (x#xs) t)) =
set (map ((#) x) (paths (insert xs (snd ((xt # xts) ! i)))))
\<union> set (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (take i (xt # xts) @ drop (Suc i) (xt # xts))))"
by force
also have "\<dots> = (image ((#) x) (set (paths (insert xs (snd ((xt # xts) ! i))))))
\<union> set (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (take i (xt # xts) @ drop (Suc i) (xt # xts))))"
by auto
finally have pi1: "set (paths (insert (x#xs) t)) =
image ((#) x) (if \<exists>xs'. xs @ xs' \<in> set (paths (snd ((xt # xts) ! i))) then set (paths (snd ((xt # xts) ! i)))
else Set.insert xs (set (paths (snd ((xt # xts) ! i))) - {xs'. \<exists>xs''. xs' @ xs'' = xs}))
\<union> set (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (take i (xt # xts) @ drop (Suc i) (xt # xts))))"
unfolding Cons.IH[OF \<open>mp_trie_invar (snd ((xt # xts) ! i))\<close>] by blast
have po1: "set (xt#xts) = set ((x,snd ((xt#xts) ! i)) # ((take i (xt # xts) @ drop (Suc i) (xt # xts))))"
using list_index_split_set[OF \<open>i < length (xt#xts)\<close>]
unfolding \<open>((xt#xts) ! i) = (x,snd ((xt#xts) ! i))\<close>[symmetric] by assumption
have po2: "length (xt#xts) = length ((x,snd ((xt#xts) ! i)) # ((take i (xt # xts) @ drop (Suc i) (xt # xts))))"
using \<open>i < length (xt#xts)\<close> by auto
have "set (paths t) = set (paths (MP_Trie ((x,snd ((xt#xts) ! i)) # ((take i (xt # xts) @ drop (Suc i) (xt # xts))))))"
unfolding \<open>t = MP_Trie (xt#xts)\<close>
using paths_order[OF po1 po2] by assumption
also have "\<dots> = set ((map ((#) x) (paths (snd ((xt # xts) ! i)))) @ (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (take i (xt # xts) @ drop (Suc i) (xt # xts)))))"
unfolding paths.simps by auto
finally have "set (paths t) =
set (map ((#) x) (paths (snd ((xt # xts) ! i))))
\<union> set (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (take i (xt # xts) @ drop (Suc i) (xt # xts))))"
by force
then have pi2: "set (paths t) = (image ((#) x) (set (paths (snd ((xt # xts) ! i)))))
\<union> set (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (take i (xt # xts) @ drop (Suc i) (xt # xts))))"
by auto
show ?thesis proof (cases "\<exists>xs'. xs @ xs' \<in> set (paths (snd ((xt # xts) ! i)))")
case True
then have pi1': "set (paths (insert (x#xs) t)) = image ((#) x) (set (paths (snd ((xt # xts) ! i))))
\<union> set (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (take i (xt # xts) @ drop (Suc i) (xt # xts))))"
using pi1 by auto
have "set (paths (insert (x # xs) t)) = set (paths t)"
unfolding pi1' pi2 by simp
moreover have "\<exists>xs'. (x # xs) @ xs' \<in> set (paths t)"
using True unfolding pi2 by force
ultimately show ?thesis by simp
next
case False
then have pi1': "set (paths (insert (x#xs) t)) = image ((#) x) (Set.insert xs (set (paths (snd ((xt # xts) ! i))) - {xs'. \<exists>xs''. xs' @ xs'' = xs}))
\<union> set (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (take i (xt # xts) @ drop (Suc i) (xt # xts))))"
using pi1 by auto
have x1: "((#) x ` Set.insert xs (set (paths (snd ((xt # xts) ! i))) - {xs'. \<exists>xs''. xs' @ xs'' = xs}))
= Set.insert (x # xs) ((#) x ` set (paths (snd ((xt # xts) ! i))) - {xs'. \<exists>xs''. xs' @ xs'' = x # xs})"
proof -
have "\<And> a . a \<in> ((#) x ` Set.insert xs (set (paths (snd ((xt # xts) ! i))) - {xs'. \<exists>xs''. xs' @ xs'' = xs})) \<Longrightarrow>
a \<in> Set.insert (x # xs) ((#) x ` set (paths (snd ((xt # xts) ! i))) - {xs'. \<exists>xs''. xs' @ xs'' = x # xs})"
by fastforce
moreover have "\<And> a . a \<in> Set.insert (x # xs) ((#) x ` set (paths (snd ((xt # xts) ! i))) - {xs'. \<exists>xs''. xs' @ xs'' = x # xs}) \<Longrightarrow>
a \<in> ((#) x ` Set.insert xs (set (paths (snd ((xt # xts) ! i))) - {xs'. \<exists>xs''. xs' @ xs'' = xs}))"
proof -
fix a assume "a \<in> Set.insert (x # xs) ((#) x ` set (paths (snd ((xt # xts) ! i))) - {xs'. \<exists>xs''. xs' @ xs'' = x # xs})"
then consider (a) "a = (x#xs)" |
(b) "a \<in> ((#) x ` set (paths (snd ((xt # xts) ! i))) - {xs'. \<exists>xs''. xs' @ xs'' = x # xs})" by blast
then show "a \<in> ((#) x ` Set.insert xs (set (paths (snd ((xt # xts) ! i))) - {xs'. \<exists>xs''. xs' @ xs'' = xs}))"
proof cases
case a
then show ?thesis by blast
next
case b
then show ?thesis by force
qed
qed
ultimately show ?thesis by blast
qed
have x2: "set (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (take i (xt # xts) @ drop (Suc i) (xt # xts))))
= (set (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (take i (xt # xts) @ drop (Suc i) (xt # xts)))) - {xs'. \<exists>xs''. xs' @ xs'' = x # xs})"
and x3: "\<not>(\<exists>xs'. (x # xs) @ xs' \<in> set (paths t))"
proof -
have "\<And> j . j < length (xt#xts) \<Longrightarrow> j \<noteq> i \<Longrightarrow> fst ((xt#xts) ! j) \<noteq> x"
using \<open>i < length (xt#xts)\<close> \<open>fst ((xt#xts) ! i) = x\<close> \<open>distinct (map fst (xt#xts))\<close>
by (metis (no_types, lifting) length_map nth_eq_iff_index_eq nth_map)
have "\<And> xt' . xt' \<in> set (take i (xt # xts) @ drop (Suc i) (xt # xts)) \<Longrightarrow> fst xt' \<noteq> x"
proof -
fix xt' assume "xt' \<in> set (take i (xt # xts) @ drop (Suc i) (xt # xts))"
then consider (a) "xt' \<in> set (take i (xt # xts))" |
(b) "xt' \<in> set (drop (Suc i) (xt # xts))"
by auto
then show "fst xt' \<noteq> x" proof cases
case a
then obtain j where "j < length (take i (xt#xts))" "(take i (xt#xts)) ! j = xt'"
by (meson in_set_conv_nth)
have "j < length (xt#xts)" and "j < i"
using \<open>j < length (take i (xt#xts))\<close> by auto
moreover have "(xt#xts) ! j = xt'"
using \<open>(take i (xt#xts)) ! j = xt'\<close> \<open>j < i\<close> by auto
ultimately show ?thesis using \<open>\<And> j . j < length (xt#xts) \<Longrightarrow> j \<noteq> i \<Longrightarrow> fst ((xt#xts) ! j) \<noteq> x\<close> by blast
next
case b
then obtain j where "j < length (drop (Suc i) (xt#xts))" "(drop (Suc i) (xt#xts)) ! j = xt'"
by (meson in_set_conv_nth)
have "(Suc i) + j < length (xt#xts)" and "(Suc i) + j > i"
using \<open>j < length (drop (Suc i) (xt#xts))\<close> by auto
moreover have "(xt#xts) ! ((Suc i) + j) = xt'"
using \<open>(drop (Suc i) (xt#xts)) ! j = xt'\<close>
using \<open>i < length (xt # xts)\<close> by auto
ultimately show ?thesis using \<open>\<And> j . j < length (xt#xts) \<Longrightarrow> j \<noteq> i \<Longrightarrow> fst ((xt#xts) ! j) \<noteq> x\<close>[of "(Suc i) + j"]
by auto
qed
qed
then show "set (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (take i (xt # xts) @ drop (Suc i) (xt # xts))))
= (set (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (take i (xt # xts) @ drop (Suc i) (xt # xts)))) - {xs'. \<exists>xs''. xs' @ xs'' = x # xs})"
by force
show "\<not>(\<exists>xs'. (x # xs) @ xs' \<in> set (paths t))"
proof
assume "\<exists>xs'. (x # xs) @ xs' \<in> set (paths t)"
then obtain xs' where "(x # (xs @ xs')) \<in> ((#) x ` set (paths (snd ((xt # xts) ! i)))) \<union>
set (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (take i (xt # xts) @ drop (Suc i) (xt # xts))))"
unfolding pi2 by force
then consider (a) "(x # (xs @ xs')) \<in> ((#) x ` set (paths (snd ((xt # xts) ! i))))" |
(b) "(x # (xs @ xs')) \<in> set (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (take i (xt # xts) @ drop (Suc i) (xt # xts))))"
by blast
then show False proof cases
case a
then show ?thesis using False by force
next
case b
then show ?thesis using \<open>\<And> xt' . xt' \<in> set (take i (xt # xts) @ drop (Suc i) (xt # xts)) \<Longrightarrow> fst xt' \<noteq> x\<close> by force
qed
qed
qed
have *: "Set.insert (x # xs) ((#) x ` set (paths (snd ((xt # xts) ! i))) \<union> set (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (take i (xt # xts) @ drop (Suc i) (xt # xts)))) - {xs'. \<exists>xs''. xs' @ xs'' = x # xs})
= Set.insert (x # xs) (((#) x ` set (paths (snd ((xt # xts) ! i)))) - {xs'. \<exists>xs''. xs' @ xs'' = x # xs}) \<union> set (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (take i (xt # xts) @ drop (Suc i) (xt # xts))))"
using x2 by blast
have "set (paths (insert (x # xs) t)) = Set.insert (x # xs) (set (paths t) - {xs'. \<exists>xs''. xs' @ xs'' = x # xs})"
unfolding pi1' pi2 x1 * by blast
then show ?thesis
using x3 by simp
qed
next
case False
have "insert (x#xs) t = MP_Trie (xt # (xts @ [(x, insert xs empty)]))"
unfolding \<open>t = MP_Trie (xt#xts)\<close> insert.simps
unfolding update_assoc_list_with_default_key_not_found[OF \<open>distinct (map fst (xt#xts))\<close> False]
by simp
have "(paths (MP_Trie (xt # (xts @ [(x, insert xs empty)])))) = concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (xt # xts @ [(x, insert xs empty)]))"
unfolding paths.simps empty_def by simp
also have "... = (concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (xt # xts))) @ (map ((#) x) (paths (insert xs empty))) "
by auto
finally have "paths (insert (x#xs) t) = (paths t) @ [x#xs]"
unfolding \<open>insert (x#xs) t = MP_Trie (xt # (xts @ [(x, insert xs empty)]))\<close>
\<open>(paths t) = concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (xt # xts))\<close>[symmetric]
paths_insert_empty
by auto
then have "set (paths (insert (x#xs) t)) = Set.insert (x#xs) (set (paths t))"
by force
have "\<And> p . p \<in> set (paths t) \<Longrightarrow> p \<noteq> [] \<and> hd p \<noteq> x"
using False
unfolding \<open>(paths t) = concat (map (\<lambda>(x, t). map ((#) x) (paths t)) (xt # xts))\<close> by force
then have "\<And> xs' . xs' \<in> set (paths t) \<Longrightarrow> \<not>(\<exists> xs'' . xs'@xs'' = x#xs)"
by (metis hd_append2 list.sel(1))
then have "set (paths t) = (set (paths t) - {xs' . \<exists> xs'' . xs'@xs'' = x#xs})"
by blast
then show ?thesis
unfolding \<open>set (paths (insert (x#xs) t)) = Set.insert (x#xs) (set (paths t))\<close>
using \<open>\<And>p. p \<in> set (paths t) \<Longrightarrow> p \<noteq> [] \<and> hd p \<noteq> x\<close> by force
qed
qed
qed
fun from_list :: "'a list list \<Rightarrow> 'a mp_trie" where
"from_list seqs = foldr insert seqs empty"
lemma from_list_invar : "mp_trie_invar (from_list xs)"
using empty_invar insert_invar by (induction xs; auto)
lemma from_list_paths :
"set (paths (from_list (x#xs))) = {y. y \<in> set (x#xs) \<and> \<not>(\<exists> y' . y' \<noteq> [] \<and> y@y' \<in> set (x#xs))}"
proof (induction xs arbitrary: x)
case Nil
have *: "paths (from_list [x]) = paths (insert x empty)" by auto
show ?case
unfolding *
unfolding paths_insert_maximal[OF empty_invar, of "x"]
unfolding empty_def
by (cases x ; auto)
next
case (Cons x' xs)
have "from_list (x#x'#xs) = insert x (insert x' (from_list xs))" by auto
have "from_list (x#x'#xs) = insert x (from_list (x'#xs))" by auto
have "mp_trie_invar (insert x' (from_list xs))"
using from_list_invar insert_invar by metis
have "(insert x' (from_list xs)) = from_list (x'#xs)" by auto
thm paths_insert_maximal[OF \<open>mp_trie_invar (insert x' (from_list xs))\<close>, of x]
show ?case proof (cases "\<exists>xs'. x @ xs' \<in> set (paths (insert x' (from_list xs)))")
case True
then have "set (paths (insert x (insert x' (from_list xs)))) = set (paths (insert x' (from_list xs)))"
using paths_insert_maximal[OF \<open>mp_trie_invar (insert x' (from_list xs))\<close>, of x] by simp
then have "set (paths (insert x (from_list (x' # xs)))) = set (paths (from_list (x' # xs)))"
unfolding \<open>(insert x' (from_list xs)) = from_list (x'#xs)\<close>
by assumption
then have "set (paths (from_list (x#x'#xs))) = {y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)}"
unfolding Cons \<open>from_list (x#x'#xs) = insert x (from_list (x'#xs))\<close>
by assumption
show ?thesis proof (cases "x \<in> set (paths (insert x' (from_list xs)))")
case True
then have "x \<in> set (x'#xs)"
using \<open>set (paths (insert x (insert x' (from_list xs)))) = set (paths (insert x' (from_list xs)))\<close> \<open>set (paths (from_list (x # x' # xs))) = {y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)}\<close> by auto
then show ?thesis
unfolding \<open>set (paths (from_list (x#x'#xs))) = {y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)}\<close> by auto
next
case False
have "{y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)} = {y \<in> set (x # x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x # x' # xs)}"
proof -
obtain xs' where "xs' \<noteq> []" and "x @ xs' \<in> {y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)}"
using True False
by (metis \<open>from_list (x # x' # xs) = insert x (insert x' (from_list xs))\<close> \<open>set (paths (insert x (insert x' (from_list xs)))) = set (paths (insert x' (from_list xs)))\<close> \<open>set (paths (from_list (x # x' # xs))) = {y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)}\<close> append_Nil2)
then have s1: "{y \<in> set (x # x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x # x' # xs)} = {y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x # x' # xs)}"
by auto
have "\<And> y . (\<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)) \<Longrightarrow> (\<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x # x' # xs))"
proof -
fix y assume "(\<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs))"
show "(\<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x # x' # xs))"
proof
assume "\<exists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x # x' # xs)"
then have "\<exists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x # x' # xs) - set (x' # xs)"
using \<open>(\<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs))\<close> by auto
then have "\<exists>y' . y' \<noteq> [] \<and> y @ y' = x"
by auto
then show "False"
by (metis (no_types, lifting) Nil_is_append_conv \<open>\<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)\<close> \<open>x @ xs' \<in> {y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)}\<close> append.assoc mem_Collect_eq)
qed
qed
then have s2: "{y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)} = {y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x # x' # xs)}"
by auto
show ?thesis
unfolding s1 s2 by simp
qed
then show ?thesis
using \<open>set (paths (from_list (x # x' # xs))) = {y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)}\<close> by auto
qed
next
case False
then have *: "set (paths (insert x (insert x' (from_list xs))))
= Set.insert x (set (paths (insert x' (from_list xs))) - {xs'. \<exists>xs''. xs' @ xs'' = x})"
using paths_insert_maximal[OF \<open>mp_trie_invar (insert x' (from_list xs))\<close>, of x] by simp
have f: "\<nexists>xs'. x @ xs' \<in> {y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)}"
using False
unfolding \<open>(insert x' (from_list xs)) = from_list (x'#xs)\<close> Cons
by assumption
then have "x \<notin> {y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)}"
by (metis (no_types, lifting) append_Nil2)
have "x \<notin> set (x' # xs)"
proof
assume "x \<in> set (x' # xs)"
then have "\<exists>y'. y' \<noteq> [] \<and> x @ y' \<in> set (x' # xs)"
using \<open>x \<notin> {y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)}\<close> by auto
let ?xms = "{xs' . xs' \<noteq> [] \<and> x @ xs' \<in> set (x' # xs)}"
have "?xms \<noteq> {}"
using \<open>\<exists>y'. y' \<noteq> [] \<and> x @ y' \<in> set (x' # xs)\<close>
by simp
moreover have "finite ?xms"
proof -
have "?xms \<subseteq> image (drop (length x)) (set (x'#xs))" by force
then show ?thesis by (meson List.finite_set finite_surj)
qed
ultimately have "\<exists> xs' \<in> ?xms . \<forall> xs'' \<in> ?xms . length xs'' \<le> length xs'"
by (meson max_length_elem not_le_imp_less)
then obtain xs' where "xs' \<noteq> []"
and "x@xs' \<in> set (x'#xs)"
and "\<And> xs'' . xs'' \<noteq> [] \<Longrightarrow> x@xs'' \<in> set (x'#xs) \<Longrightarrow> length xs'' \<le> length xs'"
by blast
have "\<nexists>y'. y' \<noteq> [] \<and> (x@xs') @ y' \<in> set (x' # xs)"
proof
assume "\<exists>y'. y' \<noteq> [] \<and> (x @ xs') @ y' \<in> set (x' # xs)"
then obtain xs'' where "xs'' \<noteq> []" and "(x @ xs') @ xs'' \<in> set (x' # xs)"
by blast
then have "xs'@xs'' \<noteq> []" and "x @ (xs' @ xs'') \<in> set (x' # xs)"
by auto
then have "length (xs'@xs'') \<le> length xs'"
using \<open>\<And> xs'' . xs'' \<noteq> [] \<Longrightarrow> x@xs'' \<in> set (x'#xs) \<Longrightarrow> length xs'' \<le> length xs'\<close> by blast
then show "False"
using \<open>xs'' \<noteq> []\<close> by auto
qed
then have "x @ xs' \<in> {y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)}"
using \<open>x@xs' \<in> set (x'#xs)\<close> by blast
then show "False" using \<open>\<nexists>xs'. x @ xs' \<in> {y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)}\<close>
by blast
qed
have "\<nexists>y'. y' \<noteq> [] \<and> x @ y' \<in> set (x # x' # xs)"
proof
assume "\<exists>y'. y' \<noteq> [] \<and> x @ y' \<in> set (x # x' # xs)"
then obtain y' where "y' \<noteq> []" and "x@y' \<in> set (x#x'#xs)"
by blast
then have "x@y' \<in> set (x'#xs)"
by auto
let ?xms = "{xs' . xs' \<noteq> [] \<and> x @ xs' \<in> set (x # x' # xs)}"
have "?xms \<noteq> {}"
using \<open>\<exists>y'. y' \<noteq> [] \<and> x @ y' \<in> set (x # x' # xs)\<close>
by simp
moreover have "finite ?xms"
proof -
have "?xms \<subseteq> image (drop (length x)) (set (x'#xs))" by force
then show ?thesis by (meson List.finite_set finite_surj)
qed
ultimately have "\<exists> xs' \<in> ?xms . \<forall> xs'' \<in> ?xms . length xs'' \<le> length xs'"
by (meson max_length_elem not_le_imp_less)
then obtain xs' where "xs' \<noteq> []"
and "x@xs' \<in> set (x#x'#xs)"
and "\<And> xs'' . xs'' \<noteq> [] \<Longrightarrow> x@xs'' \<in> set (x#x'#xs) \<Longrightarrow> length xs'' \<le> length xs'"
by blast
have "\<nexists>y'. y' \<noteq> [] \<and> (x@xs') @ y' \<in> set (x # x' # xs)"
proof
assume "\<exists>y'. y' \<noteq> [] \<and> (x @ xs') @ y' \<in> set (x # x' # xs)"
then obtain xs'' where "xs'' \<noteq> []" and "(x @ xs') @ xs'' \<in> set (x # x' # xs)"
by blast
then have "xs'@xs'' \<noteq> []" and "x @ (xs' @ xs'') \<in> set (x # x' # xs)"
by auto
then have "length (xs'@xs'') \<le> length xs'"
using \<open>\<And> xs'' . xs'' \<noteq> [] \<Longrightarrow> x@xs'' \<in> set (x#x'#xs) \<Longrightarrow> length xs'' \<le> length xs'\<close> by blast
then show "False"
using \<open>xs'' \<noteq> []\<close> by auto
qed
then have "x @ xs' \<in> {y \<in> set (x # x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x # x' # xs)}"
using \<open>x@xs' \<in> set (x # x'#xs)\<close> by blast
then have "x @ xs' \<in> set (x' # xs)" and "\<nexists>y'. y' \<noteq> [] \<and> (x@xs') @ y' \<in> set (x' # xs)"
using \<open>xs' \<noteq> []\<close> by auto
then have "x @ xs' \<in> {y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)}"
by blast
then show "False" using \<open>\<nexists>xs'. x @ xs' \<in> {y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)}\<close>
by blast
qed
have "Set.insert x ({y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)} - {xs'. \<exists>xs''. xs' @ xs'' = x})
= {y \<in> set (x # x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x # x' # xs)}"
proof -
have "\<And> y . y \<in> Set.insert x ({y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)} - {xs'. \<exists>xs''. xs' @ xs'' = x}) \<Longrightarrow> y \<in> {y \<in> set (x # x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x # x' # xs)}"
proof -
fix y assume "y \<in> Set.insert x ({y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)} - {xs'. \<exists>xs''. xs' @ xs'' = x})"
then consider (a) "y = x" |
(b) "y \<in> ({y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)} - {xs'. \<exists>xs''. xs' @ xs'' = x})"
by blast
then show "y \<in> {y \<in> set (x # x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x # x' # xs)}"
proof cases
case a
show ?thesis
using \<open>\<nexists>y'. y' \<noteq> [] \<and> x @ y' \<in> set (x # x' # xs)\<close> unfolding a by auto
next
case b
then have "y \<in> set (x' # xs)" and "\<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)" and "\<not>(\<exists>xs''. y @ xs'' = x)"
by blast+
have "y \<in> set (x#x'#xs)"
using \<open>y \<in> set (x' # xs)\<close> by auto
moreover have "\<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x # x' # xs)"
using \<open>\<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)\<close> \<open>\<not>(\<exists>xs''. y @ xs'' = x)\<close>
by auto
ultimately show ?thesis by blast
qed
qed
moreover have "\<And> y .y \<in> {y \<in> set (x # x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x # x' # xs)} \<Longrightarrow> y \<in> Set.insert x ({y \<in> set (x' # xs). \<nexists>y'. y' \<noteq> [] \<and> y @ y' \<in> set (x' # xs)} - {xs'. \<exists>xs''. xs' @ xs'' = x})"
by auto
ultimately show ?thesis by blast
qed
then show ?thesis
using "*" Cons.IH by auto
qed
qed
subsubsection \<open>New Code Generation for @{text "remove_proper_prefixes"}\<close>
declare [[code drop: remove_proper_prefixes]]
lemma remove_proper_prefixes_code_trie[code] :
"remove_proper_prefixes (set xs) = (case xs of [] \<Rightarrow> {} | (x#xs') \<Rightarrow> set (paths (from_list (x#xs'))))"
unfolding from_list_paths remove_proper_prefixes_def by (cases xs; auto)
end |
-- | An attempt at writing QuickHull in quintessential Haskell.
-- | I am just writing the simple 2D version for now.
module QuickHull (qhull2D) where
import Control.Arrow
import Control.Monad
import Data.DList (DList)
import qualified Data.DList as D
import Data.Foldable (asum)
import qualified Data.List as L (splitAt)
import Data.Maybe
import Data.Ord
import qualified Data.Vector as V
import Data.Vector.Algorithms.Intro as I
import qualified Data.Vector.Unboxed as UV
import Numeric.LinearAlgebra (peps)
data Region2D
= R021
| R201
| R012
deriving (Show,Eq,Ord)
qhull2D
:: V.Vector (UV.Vector Double)
-> [UV.Vector Double]
qhull2D vecs
| V.length vecs < 4 = V.toList vecs
| otherwise =
D.toList $ D.fromList [ax, bx, ay, by] `mappend`
qhull2DHelper ax by regU021 `mappend`
qhull2DHelper by bx regU201 `mappend`
qhull2DHelper bx ay regB201 `mappend`
qhull2DHelper ax ay regB021
where
((regU021, regU201), (regB021, regB201)) =
(assignTwoRegions *** assignTwoRegions) . splitValidQuad ax by bx ay $
vecs
[ax, bx, ay, by] = qhull2DInit vecs
qhull2DInit :: V.Vector (UV.Vector Double) -> [UV.Vector Double]
qhull2DInit points =
[ V.unsafeIndex points ax
, V.unsafeIndex points bx
, V.unsafeIndex points ay
, V.unsafeIndex points by
]
where
(ax, bx) = minMaxXIndexes points
(ay, by) = minMaxYIndexes points
qhull2DHelper :: UV.Vector Double -> UV.Vector Double -> V.Vector (UV.Vector Double) -> DList (UV.Vector Double)
qhull2DHelper v w vecs
| V.length vecs > 1 =
D.cons maxP $
qhull2DHelper w0 w1 r021 `mappend`
qhull2DHelper w0 w2 r012 `mappend`
qhull2DHelper w1 w2 r201
| V.length vecs == 1 =
D.singleton $
V.unsafeHead vecs
| otherwise = D.empty
where
(r021, r201, r012) = assignThreeRegions $ splitValidTri w0 w1 w2 testpts
[w0, w1, w2] = V.toList . sortTriangle v w $ maxP
testpts = V.ifilter (\i _ -> i /= maxInd) vecs
(maxInd, maxP) = maxDistPt v w vecs
assignTwoRegions :: V.Vector (Region2D, UV.Vector Double)
-> (V.Vector (UV.Vector Double), V.Vector (UV.Vector Double))
assignTwoRegions = (,) <$> rMap R021 <*> rMap R201
assignThreeRegions
:: V.Vector (Region2D, UV.Vector Double)
-> (V.Vector (UV.Vector Double), V.Vector (UV.Vector Double), V.Vector (UV.Vector Double))
assignThreeRegions = (,,) <$> rMap R021 <*> rMap R201 <*> rMap R012
rMap
:: Eq b
=> b -> V.Vector (b, UV.Vector Double) -> V.Vector (UV.Vector Double)
rMap r = V.map snd . V.filter ((== r) . fst)
-- Sorts points by their x-coordinates
sortTriangle
:: UV.Vector Double
-> UV.Vector Double
-> UV.Vector Double
-> V.Vector (UV.Vector Double)
sortTriangle u v w = V.modify (I.sortBy (comparing UV.unsafeHead)) r
where
r = V.fromList [u, v, w]
inTriangleInterior
:: UV.Vector Double
-> UV.Vector Double
-> UV.Vector Double
-> UV.Vector Double
-> (Bool, Double, [Double])
inTriangleInterior a b c p = (,,) <$> same' . sum <*> signum . sum <*> id $ vv
where
vv = [test' ab aP, test' bc bp, test' ca cp]
ab = diff b a
bc = diff c b
ca = diff a c
aP = diff p a
bp = diff p b
cp = diff p c
diff = UV.zipWith (-)
same' = (||) <$> (== 3) <*> (== -3)
test' u v = signum $ UV.foldl1' (-) $ UV.zipWith (*) u (UV.reverse v)
inQuadInterior
:: UV.Vector Double
-> UV.Vector Double
-> UV.Vector Double
-> UV.Vector Double
-> UV.Vector Double
-> (Bool, Double, [Double])
inQuadInterior a b c d p = (,,) <$> same' . sum <*> signum . sum <*> id $ vv
where
vv = [test' ab aP, test' bc bp, test' cd cp, test' da dp]
ab = diff b a
bc = diff c b
cd = diff d c
da = diff a d
aP = diff p a
bp = diff p b
cp = diff p c
dp = diff p d
diff = UV.zipWith (-)
same' = (||) <$> (== 4) <*> (== (-4))
test' u v = signum $ UV.foldl1' (-) $ UV.zipWith (*) u (UV.reverse v)
testInRegionQuad
:: UV.Vector Double
-> UV.Vector Double
-> UV.Vector Double
-> UV.Vector Double
-> UV.Vector Double
-> (Maybe Region2D, Maybe Region2D)
testInRegionQuad v0 v1 v2 v3 p = reg
where
(inQuad,signSum,regs) = inQuadInterior v0 v1 v2 v3 p
reg =
if inQuad
then (Nothing, Nothing)
else (asum *** asum) . L.splitAt 2 . zipWith ($) regAssign $ regs
regAssign =
[ toMaybe R021 . (/= signSum)
, toMaybe R201 . (/= signSum)
, toMaybe R021 . (/= signSum)
, toMaybe R201 . (/= signSum)]
splitValidQuad
:: UV.Vector Double
-> UV.Vector Double
-> UV.Vector Double
-> UV.Vector Double
-> V.Vector (UV.Vector Double)
-> (V.Vector (Region2D, UV.Vector Double), V.Vector (Region2D, UV.Vector Double))
splitValidQuad u v w x =
(V.map fromJust . V.filter isJust *** V.map fromJust . V.filter isJust) .
V.unzip .
V.map
((\v' (a,b) ->
(flip (,) v' <$> a, flip (,) v' <$> b)) `ap`
testInRegionQuad u v w x)
toMaybe :: a -> Bool -> Maybe a
toMaybe a pred' =
if pred'
then Just a
else Nothing
testInRegionTri
:: UV.Vector Double
-> UV.Vector Double
-> UV.Vector Double
-> UV.Vector Double
-> Maybe Region2D
testInRegionTri v0 v1 v2 p = reg
where
(inTriangle,signSum,regs) = inTriangleInterior v0 v1 v2 p
reg =
if inTriangle
then Nothing
else asum . zipWith ($) regAssign $ regs
regAssign =
[ toMaybe R021 . (/= signSum)
, toMaybe R201 . (/= signSum)
, toMaybe R012 . (/= signSum)]
splitValidTri
:: UV.Vector Double
-> UV.Vector Double
-> UV.Vector Double
-> V.Vector (UV.Vector Double)
-> V.Vector (Region2D, UV.Vector Double)
splitValidTri u v w =
V.map fromJust .
V.filter isJust . V.map ((fmap . flip (,)) `ap` testInRegionTri u v w)
minMaxXIndexes :: V.Vector (UV.Vector Double) -> (Int, Int)
minMaxXIndexes = minmax . sortOnFirst . vzip . V.map UV.unsafeHead
where
vzip v = V.zip v (V.enumFromN 0 $ V.length v)
minMaxYIndexes :: V.Vector (UV.Vector Double) -> (Int, Int)
minMaxYIndexes = minmax . sortOnFirst . vzip . V.map UV.unsafeLast
where
vzip v = V.zip v (V.enumFromN 0 $ V.length v)
minmax :: V.Vector (Double, Int) -> (Int, Int)
minmax = uncurry (,) . (snd . V.unsafeHead &&& snd . V.unsafeLast)
sortOnFirst
:: Ord a
=> V.Vector (a, b) -> V.Vector (a, b)
sortOnFirst = V.modify (I.sortBy (comparing fst))
maxDistPt
:: UV.Vector Double
-> UV.Vector Double
-> V.Vector (UV.Vector Double)
-> (Int, UV.Vector Double)
maxDistPt mn mx =
getMax . ap V.zip (V.map $ internalBisect mn mx . snd) . V.indexed
where
getMax = fst . V.maximumBy (comparing snd)
internalBisect :: UV.Vector Double
-> UV.Vector Double
-> UV.Vector Double
-> Double
internalBisect u v w = 2 * sqrt (b * c * s * (b + c)) / (b + c + peps)
where
dist' x = sqrt . UV.sum . UV.map (join (*)) . UV.zipWith (-) x
a = dist' u v
b = dist' v w
c = dist' u w
s = a + b + c
|
[STATEMENT]
lemma analz_insert_Nonce [simp]:
"analz (insert (Nonce N) H) = insert (Nonce N) (analz H)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. analz (insert (Nonce N) H) = insert (Nonce N) (analz H)
[PROOF STEP]
apply (rule analz_insert_eq_I)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>x. x \<in> analz (insert (Nonce N) H) \<Longrightarrow> x \<in> insert (Nonce N) (analz H)
[PROOF STEP]
apply (erule analz.induct, auto)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
Theo: Why are ants black?
Theo: Mama, why did you kill the Christmas tree?
Mabel: Why are tomatoes so complicated?
Theo: Do crabs think we walk sideways?
Theo: Whose idea was it to put corn in a can? |
# 3D Reconstruction and Structure from Motion
Suppose we are given a series of images from a disaster situation. How can we begin to make sense of the contents of the image? Typically this involves answering two questions:
- _What_ is in an image (e.g. debris, buildings, etc.)?
- _Where_ are these things located _in 3D space_ ?
We are first going to set the first question aside and focus entirely on the second. This will be the first in two lectures on so called "structure from motion", which is the idea that you can recreate a 3D scene from a series of 2D images by taking those images from a moving camera. Today's lecture will focus on the theory of 3D reconstruction and how to implement it. Tomorrow's lecture will focus on a real world example of structure from motion, and we will work to assign GPS coordinates to pixels on an image.
We will first start with two images and work our way up to multiple images.
## The Camera Model:
Let's first introduce the model that we will be basing our analysis on. For this session, we will be using the _pinhole model_ of a camera, depicted in the following picture:
In this model of the camera, light rays are reflected off of an object (in this case a kettle), they pass through an infinitesimally small pinhole, and arrive at the opposite wall of the camera, creating a photo-negative (think upside down) image of the object. The pinhole is located at a point called the _center of projection_. Because the image on the actual camera is a photo-negative, we typically instead center our reference frame on the center of projection and work as if the image were on the opposite side, which we will call the _image plane_. The distance _f_ between the center of projection and the image plane is called the _focal length_ which is usually measured in millimeters. On the image plane, the center of the plane is called the _principal point_ and the line that connects the center of projection and the principal point is called the _principal axis_.
We can align our coordinate frame as follows: let's center our coordinate system such that the origin is the center of projection, let's align the Z-axis such that it passes through principal axis, and let's align the X- and Y-axis such that the X-axis goes along the horizonal direction of the image plane and the Y-axis goes along the vertical direction of the image plane. Note that X increases to the right, but Y increases *downward*. This is shown in the following image:
The image plane is given by a _uv-plane_ that is centered on the principal point and is orthogonal to the principal axis. Note that cameras typically measure coordinates starting from the upper-left corner, and increasing to the left and downwards (which motivates our decision to align our Y axis downwards). Furthermore, note that cameras cannot capture an image with perfect precision. Rather, they are composed of small elements called _pixels_ that vary in intensity in order to capture the scene. Therefore, we would rather operate on the discrete pixel plane, which we will call the lowercase xy-plane. You can compare both planes in the image below:
All objects create a projection on the xy-plane, which is what we actually see on the image. For example, the point $M$ on the kettle is projected onto the xy-plane on the point _m_. Suppose we have the coordinates ($X$, $Y$, $Z$) of the point $M$. **What are the coordinates on the xy-plane of the point $m$?** State your answer in terms of $\alpha$ (the focal length measured in pixels, not millimeters), $p_x$ and $p_y$ (the coordinates of the principal point $p$ in the xy-plane), and $X$, $Y$ and $Z$, the coordinates of the point $M$.
<details>
<summary>ANSWER</summary>
We can use geometry to arrive at the answer. Note that $C$, $p$ and $m$ form a similar triangle with $C$, $Z$ and $M$. Therefore, $\frac{x-p_x}{\alpha} = \frac{X}{Z}$ and $\frac{y-p_y}{\alpha} = \frac{Y}{Z}$. Now it's a matter of solving: $x = \alpha\frac{X}{Z} + p_x$ and $y = \alpha\frac{Y}{Z} + p_y$
</details>
### List of variables used in this lesson
| Variable | Meaning |
|:--------:|:--------------------------------------------------------------------------------------------------:|
| M | A point in 3D space |
| m1, m2 | Projection of M on image 1 and 2 |
| C1, C2 | Center of camera 1, 2 (a point in 3D space) |
| p | A point on the z axis of C (directly in front of it) at the center of a given photo |
| a | Focal length of a camera |
| R | Rotation of a camera image |
| t | Translation of a camera image |
| K | A intrinsic matrix used to calculate a camera's offset, a function of its focal length and point p |
## The Problem: Depth Ambiguity
Scene reconstruction requires us to go the other way around: we know the coordinates ($x$, $y$) of $m$ and we want the ($X$, $Y$, $Z$) coordinates of the point $M$. This presents a problem: we have two equations and three unknowns. Specifically, there is an ambiguity in the depth $Z$ that is impossible to resolve with just one image. Therefore, the point $M$ can be anywhere along the ray connecting the center of projection and the point $m$. This is shown in the image below:
However, this can be remediated by adding a second image into the equation. This is because, assuming we have perfect cameras*, the rays connecting both centers of projection to the point $M$ should only intersect at one point, as is shown in the image below:
Let's assume that $C_1$ and $C_2$ are both from the same camera but different locations. Furthermore, let's center our coordinate system such that $C_1$ is at the origin. What do we need in order to find the coordinates of point $M$ ?
- The corresponding points $m_1$ and $m_2$
- The focal length $\alpha$ and the coordinates $p_x$ and $p_y$. Because these are internal to the camera, we call these the _intrinsic parameters_.
- The relative rotation $R$ and translation $t$ of $C_2$ with respect to $C_1$. Here, $R$ is a 3x3 matrix and $t$ is a 3x1 vector. We call $R$ and $t$ the _extrinsic parameters_.
\* The perfect cameras assumption is actually critical. To see why, imagine if by some measurement error (imperfect lens, pixel accuracy, etc), $m_2$ is slightly off. **What would happen in the previous example?**
<details>
<summary>ANSWER</summary>
The rays corresponding to points $m_1$ and $m_2$ will not intersect, so there is no solution to this problem!
</details>
In practice, no camera is actually perfect. There are tools that work under the hood to mitigate this. We will briefly discuss them, but will not go in depth.
Let's get started!
```python
import cv2
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
import os
import sys
```
```python
%matplotlib inline
# Load and display the two images
img1 = cv2.imread("kitchen_example/images/img1.jpg", cv2.IMREAD_GRAYSCALE)
plt.imshow(img1, cmap='gray')
plt.show()
img2 = cv2.imread("kitchen_example/images/img2.jpg", cv2.IMREAD_GRAYSCALE)
plt.imshow(img2, cmap='gray')
plt.show()
```
## Corresponding points
Our first task is to find the points $m_1$ and $m_2$. Note that it's not just a matter of finding arbitrary points, but also of ensuring the $m_1$ is actually pointing to the same object $M$ as $m_2$. Of course, one way to do this is to manually go through both images and match points on one image with points on the other. This is not a scalable solution as you increase the number of images. To this end, experts in computer vision work with the concept of _features_ which represent points of interest within an image. To understand how features work, consider the image below. **Which of the options, A through F are most easily identifiable in the image?**
<details>
<summary>ANSWER</summary>
A and B are the hardest because they could be anywhere on the surface, so surfaces are not good. C and D are a bit easier, because edges are more immediately recognizable. However, the points can still be anywhere along the edge. E and F are the easiest, since there is only one corner that looks like them. What this shows is that corners are good points to track, followed by edges and finally surfaces.
</details>
Features, therefore, are typically corners that are automatically extracted based on color differences around the corner. Features are composed of both the _coordinates_ of the point of interest as well as a _descriptor_ of what those points look like.
There are all sorts of features that will do the job. Here, we will show ORB features, which were created by the makers of OpenCV. We first extract the features and then match them with a feature in the opposite image that has the closest descriptor. It's worth noting that most of these matches will not be very good, so we only want to keep the best matches we have.
### Feature extraction
```python
MAX_FEATURES = 5000
# creating the ORB feature extractor
orb = cv2.ORB_create(MAX_FEATURES)
# creating feature points for first and second images
kp1, dc1 = orb.detectAndCompute(img1, None)
kp2, dc2 = orb.detectAndCompute(img2, None)
img1_ORB = cv2.drawKeypoints(img1, kp1, None, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
plt.imshow(img1_ORB)
plt.show()
```
### Feature matching
```python
# most matches are not very good, so we want to keep only the best ones.
# here, we keep only the top 20%
GOOD_MATCH_PERCENT = 0.2
# create BFMatcher object
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck = True)
# match descriptors
matches = bf.match(dc1, dc2)
# Sort matches by score
matches.sort(key=lambda x: x.distance, reverse=False)
# Remove worst matches
numGoodMatches = int(len(matches) * GOOD_MATCH_PERCENT)
matches = matches[:numGoodMatches]
img_match = cv2.drawMatches(img1,kp1,img2,kp2,matches,None, flags=2)
plt.imshow(img_match)
plt.show()
pts1 = np.float32([ kp1[m.queryIdx].pt for m in matches ]).reshape(-1,1,2)
pts2 = np.float32([ kp2[m.trainIdx].pt for m in matches ]).reshape(-1,1,2)
```
## Intrinsic parameters
We now proceed to obtain the intrinsic parameters. We have already seen that we can gather important data about the image by looking at its metadata. We can do something similar here:
```python
import exifread
with open("kitchen_example/images/img1.jpg", 'rb') as image_file:
tags = exifread.process_file(image_file, details=False)
print(tags["EXIF FocalLength"])
print(img1.shape)
```
951/200
(3000, 4000)
It might seem tempting to take the focal length as is, and to take the height and width of the image, divide by two and call that the coordinates of the principal point. While this might certainly be a start if you have no other options, there are some limitations to take into account. First, recall that the focal length here is measured in millimeters, but we need the length in pixels $\alpha = m*f$, where $m$ is the size in millimeters of each pixel. This information is rarely found in the metadata. Usually, if you want to get the focal length in pixels just from the metadata, you would have to find the camera specifications online and make the conversion of millimeters to pixels. Also, the focal length is typically rounded to the nearest integer in the metadata, further complicating matters.
Second, because of manufacturing constraints in positioning the sensor the principal point is always off from the middle of an image by a few pixels. While the middle of an image is most likely a good approximation, the error will continue to add up as you go farther away from the camera center.
Finally, even if you have the focal length and principal point coordinates, the reconstruction must account for _distortion_. Distortion typically comes from imperfect lenses. The most well known form of distortion is _radial distortion_. This has the effect of making straight lines bulge outwards the farther away you are from the center. The figure below shows an example of this:
Distortion is rarely in the image metadata. Sometimes cameras have distortion control that corrects for distortion when it's taking the image, so you don't have to worry about it. Still, this is relatively rare and it does not show up in the metadata whether distortion control was applied. So if you're not familiar with the camera you're using, you're still in the dark.
One way to get around this is to perform explicit camera calibration. A common way to do this is to map points with a known 3D-to-2D correspondence (like a chessboard) and perform an optimization to correct for the distortion. How this typically works is by assigning coordinates to the inner corners of the camera (e.g. the top left corner will be (0, 0, 0), the one on the right might be (1, 0, 0), the one below would be (0, 1, 0)), and then choosing the focal length, principal point and distortion parameters that best explain deviations in the expected 2D coordinates. Typically you have to take something on the order of 20-30 images of a chessboard from slightly varying locations for this procedure to work.
```python
# # termination criteria
# criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
# objp = np.zeros((6*9,3), np.float32)
# objp[:,:2] = np.mgrid[0:6,0:9].T.reshape(-1,2)
# # Arrays to store object points and image points from all the images.
# objpoints = [] # 3d point in real world space
# imgpoints = [] # 2d points in image plane.
# images = glob.glob('chessboard/*.jpg')
# for fname in images:
# img = cv2.imread(fname)
# gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# # Find the chess board corners
# ret, corners = cv2.findChessboardCorners(gray, (6,9),None)
# # If found, add object points, image points (after refining them)
# if ret == True:
# print("corners found!")
# objpoints.append(objp)
# corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
# imgpoints.append(corners2)
# # Draw and display the corners
# img = cv2.drawChessboardCorners(img, (6,9), corners2,ret)
# plt.imshow(img, cmap="gray")
# plt.show()
# else:
# print("corners not found, trying next image.")
# ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)
# print(mtx)
# np.save('camera_mat.npy', mtx)
# print(dist)
```
Usually the intrinsic parameters are stored as a matrix, called the *intrinsic matrix*. The form of the intrinsic matrix is as follows:
\begin{equation}
K = \begin{bmatrix}
\alpha_x & 0 & p_x\\
0 & \alpha_y & p_y\\
0 & 0 & 1
\end{bmatrix}
\end{equation}
I loaded the camera matrix from my phone below. Notice that the coordinates of the principal point are close to, but not quite, the middle of the image. Also notice that we introduced $\alpha_x$ and $\alpha_y$, even though we've only worked with $\alpha$ thus far. This is a more general notation, and it takes into account the possibility that cameras might not have square pixels. If one side of a pixel is larger than the other, it makes more sense to talk about focal length measured in pixel width or height. Still, cameras typically have square pixels, and this is reflected in the fact that $\alpha_x$ is very close to $\alpha_y$, so we can chalk up the discrepancy to measurement error.
As a final note, some very specialized cameras have non-rectangular pixels. It turns out $K$ can account for that by changing the value of $K_{1, 2}$, otherwise known as the skew. For most cameras, you can assume it equals 0.
```python
# the cell above takes a very long time to run. I already ran it and saved the matrix.
K = np.load('camera_mat.npy')
print(K)
```
[[3.19477917e+03 0.00000000e+00 2.01374563e+03]
[0.00000000e+00 3.20259509e+03 1.47622334e+03]
[0.00000000e+00 0.00000000e+00 1.00000000e+00]]
### Exercise
Print out the chessboard that was provided to you in chessboard_original/ (or use your own chessboard). Using your phone (or whatever other camera), take 20 or so photos of the chessboard lying on a flat surface and upload them to the chessboard/ directory.
Uncomment the cell with the callibration code and run the callibration with your images. Compare the values in the estimated camera matrix with the values you would have expected. How similar are they to the expected values? What is the size of a pixel in your camera in millimeters?
```python
```
## Extrinsic parameters
We now need to find the rotation and translation $R$ and $t$ of both cameras. To reiterate, $t$ is a 3x1 vector that denotes the distance from the origin in $X$, $Y$ and $Z$\*. $R$ is a 3x3 matrix that encodes the rotation of the camera. We made our lives a bit easier by centering the coordinate system on the first camera, such that $t_1 = [0, 0, 0]'$ and $R_1$ is the identity matrix. Remember that we also aligned the coordinate system such that the vector $[0, 0, 1]'$ is in the direction that the camera is pointing. One way to interpret the rotation matrix $R_2$ is by saying that it is the matrix that rotates the vector $[0, 0, 1]'$ into the vector that is aligned with the direction of the second camera.
One of the most amazing results in multiview geometry is that $R_2$ and $t_2$ can both be recovered (up to scale, in the case of $t_2$) just by knowing the corresponding points and the intrinsic parameters. At a very high level, this is a key tenet of something called _epipolar geometry_. Consider images (a) and (b) below. On the image you will find random corresponding points between the two images. On image (a), clearly the camera that took (b) is somewhere to the right. Imagine we could extend (a) so much that you could actually see the camera that took (b), and let's draw a line between the camera that took (b) and all of the corresponding points. What you would find is a series of lines, called epipolar lines, that all converge at the camera that took (b), whose point is called the epipole. This is what we see in (c) and (d).
(source: https://www.youtube.com/watch?v=QzYn0OPO0Yw)
It turns out there is a matrix called the _fundamental matrix_ that encodes this information. This matrix can be estimated using the corresponding points we got before. Furthermore, by combining it with the intrinsic parameters, we get another matrix called the _essential matrix_ which can then be decomposed into a relative rotation and translation $R_2$ and $t_2$, which is what we're after! This is of course a criminally high level summary of how this works. For more information, this is an excellent source: https://www.youtube.com/watch?v=QzYn0OPO0Yw.
\* This is actually a bit incorrect. $t$ represents the vector connecting the center of projection to the origin *from the point of view of the camera being considered*, not the first camera. Still, the general idea is that it denotes displacement.
```python
# converting to pixel coordinates
pts1 = np.int32(pts1)
pts2 = np.int32(pts2)
# Estimate the essential matrix
E, mask = cv2.findEssentialMat(pts1,pts2,K)
# We select only inlier points
pts1_inliers = (pts1[mask.ravel()==1])
pts2_inliers = (pts2[mask.ravel()==1])
```
```python
# Recover pose using what we've learned so far
retval, R, t, mask = cv2.recoverPose(E, pts1_inliers, pts2_inliers, K)
print(R)
print(t)
```
[[ 0.94945422 -0.09603048 0.29885588]
[ 0.0832821 0.99499955 0.05513607]
[-0.30265621 -0.02745983 0.95270414]]
[[-0.97932551]
[-0.06854215]
[ 0.19032476]]
## Finalizing the reconstruction
We now have everything we need to reconstruct the scene in 3D! We have corresponding points in two images, the intrinsic parameters of the camera and the extrinsic parameters as the camera took the two images. There is just one caveat. Remember that the value $t_2$ that we obtained was up to scale. It turns out that our entire scene is scaled such that the length of $t_2 = 1$. This means that while the relative distances between the reconstructed points are conserved, the absolute positions are not.
Because we want to take advantage of visualization software that currently exists, we will use a package called OpenSfM (https://github.com/mapillary/OpenSfM). OpenSfM automatically goes through the trouble of extracting the features, matching them, finding the poses of the cameras and doing the triangulation. One thing it does not do, however, is the camera calibration. We can either provide our own intrinsic camera parameters or we can let the algorithm take its best guess through a process called _bundle adjustment_. Bundle adjustment essentially works by identifying the _reprojection error_ (the error in reprojecting the reconstructed 3D features back onto the image) and slightly modifying the camera positions and parameters, as well as the positions of the features, so that the error is minimized.
As a final note, what do we do when we have more than three images? Clearly if you can find the camera pose of image 2 relative to image 1, then it's possible to find the pose of image 3 relative to image 2. Therefore, multiple images can take part in a reconstruction. Here, bundle adjustment is very important to ensure that errors in the reconstruction do not keep adding up.
Here are the steps to reconstruct a scene:
- Extract the focal length from the metadata
- Detect features from images (in this particular case, we are using so called HAHOG features)
- Match features across images
- Reconstruct the scene using the inferred rotations and translations
- Visualize the scene
OpenSfM has a very good command line interface, so we'll move to the terminal for this portion. However, the commands are on the following cell in case you want to refer back to them.
```python
# Take initial guess of intrinsic parameters through metadata
!opensfm extract_metadata kitchen_example/
# Detect features points
!opensfm detect_features kitchen_example/
# Match feature points across images
!opensfm match_features kitchen_example/
# This creates "tracks" for the features. That is to say, if a feature in image 1 is matched with one in image 2,
# and in turn that one is matched with one in image 3, then it links the matches between 1 and 3. In this case,
# it does not matter since we only have two images
!opensfm create_tracks kitchen_example/
# Calculates the essential matrix, the camera pose and the reconstructed feature points
!opensfm reconstruct kitchen_example/
# For visualization using Open3D
!opensfm export_ply kitchen_example/
```
2020-07-16 16:39:27,049 INFO: Loading existing EXIF for img1.jpg
2020-07-16 16:39:27,049 INFO: Loading existing EXIF for img2.jpg
2020-07-16 16:39:28,967 INFO: Skip recomputing ROOT_HAHOG features for image img1.jpg
2020-07-16 16:39:28,968 INFO: Skip recomputing ROOT_HAHOG features for image img2.jpg
2020-07-16 16:39:30,859 INFO: Matching 1 image pairs
2020-07-16 16:39:30,865 INFO: Computing pair matching with 1 processes
2020-07-16 16:39:30,890 DEBUG: No segmentation for img1.jpg, no features masked.
2020-07-16 16:39:30,891 DEBUG: No segmentation for img2.jpg, no features masked.
2020-07-16 16:39:31,399 DEBUG: Matching img1.jpg and img2.jpg. Matcher: FLANN (symmetric) T-desc: 0.507 T-robust: 0.001 T-total: 0.508 Matches: 389 Robust: 344 Success: True
2020-07-16 16:39:31,399 DEBUG: Image img1.jpg matches: 1 out of 1
2020-07-16 16:39:31,399 DEBUG: Image img2.jpg matches: 0 out of 0
2020-07-16 16:39:31,399 INFO: Matched 1 pairs for 2 ref_images (perspective-perspective: 1) in 0.5405021099995793 seconds (0.5405025999989448 seconds/pair).
2020-07-16 16:39:33,292 INFO: reading features
2020-07-16 16:39:33,320 DEBUG: Merging features onto tracks
2020-07-16 16:39:33,323 DEBUG: Good tracks: 344
2020-07-16 16:39:35,244 INFO: Starting incremental reconstruction
2020-07-16 16:39:35,248 INFO: Starting reconstruction with img1.jpg and img2.jpg
2020-07-16 16:39:35,267 INFO: Two-view reconstruction inliers: 344 / 344
2020-07-16 16:39:35,289 INFO: Triangulated: 344
2020-07-16 16:39:35,295 DEBUG: Ceres Solver Report: Iterations: 3, Initial cost: 5.705338e+00, Final cost: 5.400423e+00, Termination: CONVERGENCE
2020-07-16 16:39:35,325 DEBUG: Ceres Solver Report: Iterations: 3, Initial cost: 5.469469e+00, Final cost: 5.380886e+00, Termination: CONVERGENCE
Align plane: [-3.97585049e-02 -9.98882488e-01 -2.55545678e-02 1.30665764e-16]
2020-07-16 16:39:35,359 DEBUG: Ceres Solver Report: Iterations: 10, Initial cost: 1.878363e+01, Final cost: 1.507083e+01, Termination: CONVERGENCE
2020-07-16 16:39:35,361 INFO: Removed outliers: 0
2020-07-16 16:39:35,361 INFO: -------------------------------------------------------
Align plane: [-4.08431106e-02 -2.32552687e-02 9.98894906e-01 2.97289317e-18]
2020-07-16 16:39:35,393 DEBUG: Ceres Solver Report: Iterations: 10, Initial cost: 1.829925e+01, Final cost: 1.507083e+01, Termination: CONVERGENCE
2020-07-16 16:39:35,396 INFO: Removed outliers: 0
2020-07-16 16:39:35,402 INFO: {'points_count': 344, 'cameras_count': 2, 'observations_count': 688, 'average_track_length': 2.0, 'average_track_length_notwo': -1}
2020-07-16 16:39:35,403 INFO: Reconstruction 0: 2 images, 344 points
2020-07-16 16:39:35,403 INFO: 1 partial reconstructions in total.
```python
import open3d as o3d
from open3d import JVisualizer
pcd = o3d.io.read_point_cloud("kitchen_example/reconstruction.ply")
visualizer = JVisualizer()
visualizer.add_geometry(pcd)
visualizer.show()
# UNCOMMENT ONLY IF RUNNING LOCALLY
# o3d.visualization.draw_geometries([pcd])
```
JVisualizer with 1 geometries
### Exercise
We will now let you try out 3D reconstruction for yourself using OpenSfM! First, we need to make sure you have the proper file structure to make this work. Create a directory called "workspace/" (or whatever else you want). In that directory, create a directory called "images/". From the kitchen_example/ directory, copy "config.yaml" and paste it in workspace/. Take two or more images of your work space and upload them to workspace/images. Now run the commands above to reconstruct the scene and visualize it. Is the reconstruction accurate? What about your scene might make it difficult for the reconstruction to work well?
Go to workspace/reports and examine the files there. They will give you a sense of how many features were extracted, how many features were matched, and whether some reconstructions are only partial. Do you have multiple partial reconstructions or one larger reconstruction? If you have partial reconstructions, why do you think that is?
```python
```
|
The Aga Much Wenlock Classic Multifuel / Woodburning Stove is a fantastic medium sized stove suitable for over-night burning. The Much Wenlock Classic has a nominal heat output of 5.5kW (maximum 8.3kW) and incredible fuel efficiency of 77%.
The Aga Much Wenlock Classic can burn a variety of fuels including wood, coal, anthracite and peat briquettes. This cast iron Aga stove has a removal shaker grate, ash pan, fire fence and front ash tray and is simple and easy to operate. Like the standard Much Wenlock it has the same black wire handle and air inlet control and will complete traditional or contemporary home. |
import tactic --hide
/-
#Combining logical statements
We can combine basic statements to create new ones. For example, we can write `¬P` for the
statement "Not `P`" and if we have two statements `P Q : Prop`
we can write `P → Q` to mean `P` implies `Q`.
Say we have the following state of our lemma:
```
P Q : Prop
h : P → Q
p : P
⊢ Q
```
As in level one, the first line says `P` and `Q` are logical statements and the third line says
that `P` has a proof `p`.
In the second line we have the implication `P → Q`,
which we have called `h`. We think of `h` as a one-way road from the statement `P` to the
statement `Q` in `Prop`. In Maths, we would call `h` a function or a map.
Finally, our goal is to prove `Q` is true.
Using <mark style ="background-color : #ebdef0 ">`exact h(p),`</mark> will prove our lemma.
Why does this work? We know that `P` is true, since we have a proof of it `p` and `h` tells us that
if `P` is true then `Q` is true. So combining `h` and `p` results in a proof of `Q`.
**Note: We use `h(p)` rather than `h(P)`, because we want to transform the proof of `P` into
a proof of `Q`.**
-/
/- Lemma
Let $P,Q$ be logical statements and $P$ implies $Q$. If $P$ is true, then so is $Q$.
-/
lemma implications_one (P Q : Prop) (h : P → Q) (p : P) : Q :=
begin
exact h(p),
end |
module Fail.NonCopatternInstance where
record HasId (a : Set) : Set where
field id : a → a
open HasId ⦃ ... ⦄
{-# COMPILE AGDA2HS HasId class #-}
data Unit : Set where
MkUnit : Unit
{-# COMPILE AGDA2HS Unit #-}
instance
UnitHasId : HasId Unit
UnitHasId = record { id = λ x → x } -- NOT CORRECT
-- UnitHasId .id x = x -- CORRECT
{-# COMPILE AGDA2HS UnitHasId #-}
|
theory Map_Interface
imports
"Lookup/Lookup"
"Insert/Alloc_Optimized/Insert_Opt"
"Delete/Alloc_Optimized/Delete_Opt"
"Separation_Logic_Solver/Methods"
begin
locale rbt_map = rbt_impl keyabs_t key_t valueabs_t value_t
for
keyabs_t :: "'k :: linorder itself" and
key_t :: "'ki :: llvm_rep itself" and
valueabs_t :: "'v itself" and
value_t :: "'vi :: llvm_rep itself"
+
fixes value_copy :: "'vi \<Rightarrow> 'vi llM"
assumes
value_copy_rule [vcg_rules]:
"
llvm_htriple
(\<upharpoonleft>value_assn v vi)
(value_copy vi)
(\<lambda>r. \<upharpoonleft>value_assn v vi ** \<upharpoonleft>value_assn v r)
"
begin
fun rbt_map_assn :: "('k \<rightharpoonup> 'v) \<Rightarrow> ('ki, 'vi) rbti \<Rightarrow> ll_assn" where
"rbt_map_assn m ti = (EXS t. rbt_assn_full t ti ** \<up>(rbt_lookup t = m))"
lemma empty_map_rule:
"
llvm_htriple
\<box>
empty
(\<lambda>r. rbt_map_assn Map.empty r)
" by vcg
lemma free_map_rule:
"
llvm_htriple
(rbt_map_assn m ti)
(free ti)
(\<lambda>_. \<box>)
" by vcg
lemma lookup_map_rule:
"
llvm_htriple
(rbt_map_assn m ti ** \<upharpoonleft>key_assn k ki)
(lookup value_copy ki ti)
(\<lambda>opt. \<upharpoonleft>value_option_assn (m k) opt ** rbt_map_assn m ti ** \<upharpoonleft>key_assn k ki)
" by vcg
lemma insert_map_rule:
"
llvm_htriple
(rbt_map_assn m ti ** \<upharpoonleft>key_assn k ki ** \<upharpoonleft>value_assn v vi)
(insert ki vi ti)
(\<lambda>r. rbt_map_assn (m(k \<mapsto> v)) r)
"
apply vcg
apply vcg_compat
apply (sepEwith simp)
apply (simp_all add: rbt_lookup_rbt_insert)
done
lemma insert_opt_map_rule:
"
llvm_htriple
(rbt_map_assn m ti ** \<upharpoonleft>key_assn k ki ** \<upharpoonleft>value_assn v vi)
(insert_opt ki vi ti)
(\<lambda>r. rbt_map_assn (m(k \<mapsto> v)) r)
"
apply vcg
apply vcg_compat
apply (sepEwith simp)
apply (simp_all add: rbt_lookup_rbt_insert)
done
lemma delete_map_rule:
"
llvm_htriple
(rbt_map_assn m ti ** \<upharpoonleft>key_assn k ki)
(delete ki ti)
(\<lambda>r. rbt_map_assn (m |` (-{k})) r ** \<upharpoonleft>key_assn k ki)
"
apply vcg
apply vcg_compat
apply (sepEwith simp)
apply (simp_all add: rbt_lookup_rbt_delete)
done
lemma delete_opt_map_rule:
"
llvm_htriple
(rbt_map_assn m ti ** \<upharpoonleft>key_assn k ki)
(delete_opt ki ti)
(\<lambda>r. rbt_map_assn (m |` (-{k})) r ** \<upharpoonleft>key_assn k ki)
"
supply is_rbt_def[simp]
apply vcg
apply vcg_compat
apply (sepE | find_sep)+
using is_rbt_def rbt_delete_is_rbt apply blast
apply (simp add: rbt_lookup_rbt_delete)
done
lemmas rbt_map_rules[vcg_rules] =
empty_map_rule
free_map_rule
lookup_map_rule
insert_map_rule
delete_map_rule
insert_opt_map_rule
delete_opt_map_rule
lemmas rbt_tree_rules[vcg_rules del] =
empty_correct
free_correct
lookup_correct
insert_correct
delete_correct
insert_opt_correct
delete_opt_correct
lemma pure_part_exE:
assumes "pure_part (\<lambda>s. \<exists>x. P x s)"
obtains x where "pure_part (P x)"
using assms unfolding pure_part_def by blast
lemma rbt_map_finite:
"pure_part(rbt_map_assn m ti) \<Longrightarrow> finite (dom m)"
by (auto elim!: pure_part_exE pure_part_split_conjE)
declare rbt_map_assn.simps[simp del]
end
end |
lemma (in sigma_algebra) sets_measure_of_eq[simp]: "sets (measure_of \<Omega> M \<mu>) = M" |
At that time of the assassination of Archduke Franz Ferdinand of Austria on 28 June 1914 , the battleships in the Austro @-@ Hungarian Navy consisted of the Radetzky class , the Tegetthoff class ( which still had one ship , SMS Szent István , under construction ) , the Erzherzog Karl class and finally , the older Habsburg class . Along with the remainder of the Austro @-@ Hungarian Navy , Zrínyi was mobilized in late July 1914 to support the flight of SMS Goeben and SMS Breslau . The two German ships broke out of Messina , which was surrounded by the British navy and reached Turkey . The flotilla had advanced as far south as Brindisi in southeastern Italy when news of the successful breakout reached Vienna . The Austro @-@ Hungarian ships were then recalled before seeing action .
|
# Quantum pipeline using JAX backend
This performs an exact classical simulation.
```python
from jax import numpy as np
def read_data(filename):
labels, sentences = [], []
with open(filename) as f:
for line in f:
labels.append([1, 0] if line[0] == '1' else [0, 1])
sentences.append(line[1:].strip())
return np.array(labels), sentences
train_labels, train_data = read_data('datasets/mc_train_data.txt')
dev_labels, dev_data = read_data('datasets/mc_dev_data.txt')
test_labels, test_data = read_data('datasets/mc_test_data.txt')
```
### Create diagrams
```python
from lambeq.ccg2discocat import DepCCGParser
reader = DepCCGParser(possible_root_cats=['S[dcl]'])
raw_train_diagrams = reader.sentences2diagrams(train_data)
raw_dev_diagrams = reader.sentences2diagrams(dev_data)
raw_test_diagrams = reader.sentences2diagrams(test_data)
```
```python
from discopy.rigid import Id
def remove_cups(diagram):
# Remove cups to reduce post-selection in the circuit, for faster execution
diags = []
for box, offset in zip(diagram.boxes, diagram.offsets):
if not box.dom: # word box
diags.insert(offset, box)
else: # cup (the only other type of box in these diagrams)
i = 0
off = offset
while off != len(diags[i].cod) - 1:
assert off > 0
off -= len(diags[i].cod)
i += 1
left, right = diags[i:i+2]
if len(left.cod) == 1:
new_diag = right >> (left.r.dagger() @ Id(right.cod[1:]))
else:
assert len(right.cod) == 1
new_diag = left >> (Id(left.cod[:-1]) @ right.l.dagger())
diags[i:i+2] = [new_diag]
assert len(diags) == 1
return diags[0]
train_diagrams = [remove_cups(diagram) for diagram in raw_train_diagrams]
dev_diagrams = [remove_cups(diagram) for diagram in raw_dev_diagrams]
test_diagrams = [remove_cups(diagram) for diagram in raw_test_diagrams]
train_diagrams[0].draw()
```
### Create circuits
```python
from lambeq.circuit import IQPAnsatz
from lambeq.core.types import AtomicType
ansatz = IQPAnsatz({AtomicType.NOUN: 1, AtomicType.SENTENCE: 1},
n_layers=1, n_single_qubit_params=3)
train_circuits = [ansatz(diagram) for diagram in train_diagrams]
dev_circuits = [ansatz(diagram) for diagram in dev_diagrams]
test_circuits = [ansatz(diagram) for diagram in test_diagrams]
train_circuits[0].draw(figsize=(9, 12))
```
### Parameterise
```python
from sympy import default_sort_key
all_circuits = train_circuits + dev_circuits + test_circuits
# sort the symbols since they are returned as a set
parameters = sorted(
{s for circ in all_circuits for s in circ.free_symbols},
key=default_sort_key)
```
```python
from discopy.quantum import Circuit
from discopy.tensor import Tensor
from jax import jit
Tensor.np = np
def normalise(predictions):
# apply smoothing to predictions
predictions = np.abs(predictions) + 1e-9
return predictions / predictions.sum()
def make_pred_fn(circuits):
circuit_fns = [c.lambdify(*parameters) for c in circuits]
def predict(params):
outputs = Circuit.eval(*(c(*params) for c in circuit_fns))
return np.array([normalise(output.array) for output in outputs])
return predict
train_pred_fn = jit(make_pred_fn(train_circuits))
dev_pred_fn = jit(make_pred_fn(dev_circuits))
test_pred_fn = make_pred_fn(test_circuits)
```
### Train
```python
from noisyopt import minimizeSPSA
import numpy
def make_cost_fn(pred_fn, labels):
def cost_fn(params, **kwargs):
predictions = pred_fn(params)
cost = -np.sum(labels * np.log(predictions)) / len(labels) # binary cross-entropy loss
costs.append(cost)
acc = np.sum(np.round(predictions) == labels) / len(labels) / 2 # half due to double-counting
accuracies.append(acc)
return cost
costs, accuracies = [], []
return cost_fn, costs, accuracies
train_cost_fn, train_costs, train_accs = make_cost_fn(train_pred_fn, train_labels)
dev_cost_fn, dev_costs, dev_accs = make_cost_fn(dev_pred_fn, dev_labels)
SEED = 0
rng = numpy.random.default_rng(SEED)
x0 = np.array(rng.random(len(parameters)))
numpy.random.seed(SEED)
result = minimizeSPSA(train_cost_fn, x0=x0, a=0.2, c=0.06, niter=80, callback=dev_cost_fn)
```
### Show results
```python
import matplotlib.pyplot as plt
fig, ((ax_tl, ax_tr), (ax_bl, ax_br)) = plt.subplots(2, 2, sharex=True, sharey='row', figsize=(10, 6))
ax_tl.set_title('Training set')
ax_tr.set_title('Development set')
ax_bl.set_xlabel('Iterations')
ax_br.set_xlabel('Iterations')
ax_bl.set_ylabel('Accuracy')
ax_tl.set_ylabel('Loss')
colours = iter(plt.rcParams['axes.prop_cycle'].by_key()['color'])
ax_tl.plot(train_costs[1::2], color=next(colours)) # training evaluates twice per iteration
ax_bl.plot(train_accs[1::2], color=next(colours)) # so take every other entry
ax_tr.plot(dev_costs, color=next(colours))
ax_br.plot(dev_accs, color=next(colours))
# print test accuracy
test_cost_fn, _, test_accs = make_cost_fn(test_pred_fn, test_labels)
test_cost_fn(result.x)
print('Test accuracy:', test_accs[0])
```
|
classdef MimEditCyan < MimGuiPlugin
% MimEditCyan. Gui Plugin for setting paint colour
%
% You should not use this class within your own code. It is intended to
% be used by the gui of the TD MIM Toolkit.
%
% MimEditCyan is a Gui Plugin for the MIM Toolkit.
%
%
% Licence
% -------
% Part of the TD MIM Toolkit. https://github.com/tomdoel
% Author: Tom Doel, Copyright Tom Doel 2014. www.tomdoel.com
% Distributed under the MIT licence. Please see website for details.
%
properties
ButtonText = 'Cyan'
SelectedText = 'Cyan'
ToolTip = 'Edit with cyan label'
Category = 'Segmentation label'
Visibility = 'Dataset'
Mode = 'Edit'
HidePluginInDisplay = false
PTKVersion = '1'
ButtonWidth = 5
ButtonHeight = 1
Icon = 'paint.png'
IconColour = GemMarkerPoint.DefaultColours{4}
Location = 34
end
methods (Static)
function RunGuiPlugin(gui_app)
gui_app.ImagePanel.PaintBrushColour = 4;
end
function enabled = IsEnabled(gui_app)
enabled = gui_app.IsDatasetLoaded && gui_app.ImagePanel.OverlayImage.ImageExists && ...
isequal(gui_app.ImagePanel.SelectedControl, 'Paint');
end
function is_selected = IsSelected(gui_app)
is_selected = gui_app.ImagePanel.PaintBrushColour == 4;
end
end
end |
lemma (in sigma_algebra) space_measure_of_eq[simp]: "space (measure_of \<Omega> M \<mu>) = \<Omega>" |
theory "WideMouthFrog_cert_auto"
imports
"../ESPLogic"
begin
(* section: Wide Mouthed Frog *)
(* text:
The protocol is modeled after the description in the SPORE library:
http://www.lsv.ens-cachan.fr/Software/spore/wideMouthedFrog.html
Note that we cannot reason about the timestamps in our current model.
Furthermore, our current calculus for backwards reasoning is too weak
to reason about the original protocol
1: I -> S: I, {TimeI, R, kIR}k(I,S)
2: R <- S: {TimeS, I, kIR}k(R,S)
because the server S could receive the message {TimeI, R, kIR}k(I,S)
arbitrarily many times from himself. Therefore, we added global constants
identifying the different steps.
*)
role I
where "I =
[ Send ''1'' <| sAV ''I'', sAV ''R'',
PEnc <| sC ''step1'', sN ''TimeI'', sAV ''R'', sN ''kIR'' |>
( sK ''I'' ''S'' )
|>
]"
role R
where "R =
[ Recv ''2'' <| sMV ''S'', sMV ''I'',
PEnc <| sC ''step2'', sMV ''TimeS'', sMV ''I'', sMV ''kIR'' |>
( PSymK ( sAV ''R'' ) ( sMV ''S'' ) )
|>
]"
role S
where "S =
[ Recv ''1'' <| sMV ''I'', sMV ''R'',
PEnc <| sC ''step1'', sMV ''TimeI'', sMV ''R'', sMV ''kIR'' |>
( PSymK ( sMV ''I'' ) ( sAV ''S'' ) )
|>
, Send ''2'' <| sAV ''S'', sMV ''I'',
PEnc <| sC ''step2'', sN ''TimeS'', sMV ''I'', sMV ''kIR'' |>
( PSymK ( sMV ''R'' ) ( sAV ''S'' ) )
|>
]"
protocol WMF
where "WMF = { I, R, S }"
locale restricted_WMF_state = WMF_state
type_invariant WMF_msc_typing for WMF
where "WMF_msc_typing = mk_typing
[ ((R, ''I''), (KnownT R_2))
, ((S, ''I''), (KnownT S_1))
, ((S, ''R''), (KnownT S_1))
, ((R, ''S''), (KnownT R_2))
, ((S, ''TimeI''), (SumT (KnownT S_1) (NonceT I ''TimeI'')))
, ((R, ''TimeS''), (SumT (KnownT R_2) (NonceT S ''TimeS'')))
, ((R, ''kIR''), (SumT (KnownT R_2) (NonceT I ''kIR'')))
, ((S, ''kIR''), (SumT (KnownT S_1) (NonceT I ''kIR'')))
]"
sublocale WMF_state < WMF_msc_typing_state
proof -
have "(t,r,s) : approx WMF_msc_typing"
proof(cases rule: reachable_in_approxI_ext
[OF WMF_msc_typing.monoTyp, completeness_cases_rule])
case (R_2_I t r s tid0) note facts = this
then interpret state: WMF_msc_typing_state t r s
by unfold_locales auto
show ?case using facts
by (fastsimp intro: event_predOrdI split: if_splits)
next
case (R_2_S t r s tid0) note facts = this
then interpret state: WMF_msc_typing_state t r s
by unfold_locales auto
show ?case using facts
by (fastsimp intro: event_predOrdI split: if_splits)
next
case (R_2_TimeS t r s tid0) note facts = this
then interpret state: WMF_msc_typing_state t r s
by unfold_locales auto
show ?case using facts
proof(sources! "
Enc {| LC ''step2'', s(MV ''TimeS'' tid0), s(MV ''I'' tid0),
s(MV ''kIR'' tid0)
|}
( K ( s(AV ''R'' tid0) ) ( s(MV ''S'' tid0) ) ) ")
qed (insert facts, ((fastsimp intro: event_predOrdI split: if_splits))+)?
next
case (R_2_kIR t r s tid0) note facts = this
then interpret state: WMF_msc_typing_state t r s
by unfold_locales auto
show ?case using facts
proof(sources! "
Enc {| LC ''step2'', s(MV ''TimeS'' tid0), s(MV ''I'' tid0),
s(MV ''kIR'' tid0)
|}
( K ( s(AV ''R'' tid0) ) ( s(MV ''S'' tid0) ) ) ")
case (S_2_enc tid1) note_unified facts = this facts
thus ?thesis proof(sources! "
Enc {| LC ''step1'', s(MV ''TimeI'' tid1), s(AV ''R'' tid0),
s(MV ''kIR'' tid0)
|}
( K ( s(MV ''I'' tid0) ) ( s(AV ''S'' tid1) ) ) ")
qed (insert facts, ((fastsimp intro: event_predOrdI split: if_splits))+)?
qed (insert facts, ((fastsimp intro: event_predOrdI split: if_splits))+)?
next
case (S_1_I t r s tid0) note facts = this
then interpret state: WMF_msc_typing_state t r s
by unfold_locales auto
show ?case using facts
by (fastsimp intro: event_predOrdI split: if_splits)
next
case (S_1_R t r s tid0) note facts = this
then interpret state: WMF_msc_typing_state t r s
by unfold_locales auto
show ?case using facts
by (fastsimp intro: event_predOrdI split: if_splits)
next
case (S_1_TimeI t r s tid0) note facts = this
then interpret state: WMF_msc_typing_state t r s
by unfold_locales auto
show ?case using facts
proof(sources! "
Enc {| LC ''step1'', s(MV ''TimeI'' tid0), s(MV ''R'' tid0),
s(MV ''kIR'' tid0)
|}
( K ( s(MV ''I'' tid0) ) ( s(AV ''S'' tid0) ) ) ")
qed (insert facts, ((fastsimp intro: event_predOrdI split: if_splits))+)?
next
case (S_1_kIR t r s tid0) note facts = this
then interpret state: WMF_msc_typing_state t r s
by unfold_locales auto
show ?case using facts
proof(sources! "
Enc {| LC ''step1'', s(MV ''TimeI'' tid0), s(MV ''R'' tid0),
s(MV ''kIR'' tid0)
|}
( K ( s(MV ''I'' tid0) ) ( s(AV ''S'' tid0) ) ) ")
qed (insert facts, ((fastsimp intro: event_predOrdI split: if_splits))+)?
qed
thus "WMF_msc_typing_state t r s" by unfold_locales auto
qed
text{* Prove secrecy of long-term keys. *}
context WMF_state begin
(* This rule is unsafe in general, but OK here,
as we are only reasoning about static compromise.
*)
lemma static_longterm_key_reveal[dest!]:
"predOrd t (LKR a) e ==> RLKR a : reveals t"
by (auto intro: compr_predOrdI)
lemma longterm_private_key_secrecy:
assumes facts:
"SK m : knows t"
"RLKR m ~: reveals t"
shows "False"
using facts by (sources "SK m")
lemma longterm_sym_ud_key_secrecy:
assumes facts:
"K m1 m2 : knows t"
"RLKR m1 ~: reveals t"
"RLKR m2 ~: reveals t"
shows "False"
using facts by (sources "K m1 m2")
lemma longterm_sym_bd_key_secrecy:
assumes facts:
"Kbd m1 m2 : knows t"
"RLKR m1 ~: reveals t"
"RLKR m2 ~: reveals t"
"m1 : Agent"
"m2 : Agent"
shows "False"
proof -
from facts
have "KShr (agents {m1, m2}) : knows t"
by (auto simp: Kbd_def)
thus ?thesis using facts
proof (sources "KShr (agents {m1, m2})")
qed (auto simp: agents_def Agent_def)
qed
lemmas ltk_secrecy =
longterm_sym_ud_key_secrecy
longterm_sym_ud_key_secrecy[OF in_knows_predOrd1]
longterm_sym_bd_key_secrecy
longterm_sym_bd_key_secrecy[OF in_knows_predOrd1]
longterm_private_key_secrecy
longterm_private_key_secrecy[OF in_knows_predOrd1]
end
(* subsection: Secrecy Properties *)
lemma (in restricted_WMF_state) I_kIR_sec:
assumes facts:
"roleMap r tid0 = Some I"
"RLKR(s(AV ''I'' tid0)) ~: reveals t"
"RLKR(s(AV ''R'' tid0)) ~: reveals t"
"RLKR(s(AV ''S'' tid0)) ~: reveals t"
"LN ''kIR'' tid0 : knows t"
shows "False"
using facts proof(sources! " LN ''kIR'' tid0 ")
case I_1_kIR note_unified facts = this facts
thus ?thesis by (fastsimp dest!: ltk_secrecy)
next
case (S_2_kIR tid1) note_unified facts = this facts
thus ?thesis proof(sources! "
Enc {| LC ''step1'', s(MV ''TimeI'' tid1), s(MV ''R'' tid1),
LN ''kIR'' tid0
|}
( K ( s(MV ''I'' tid1) ) ( s(AV ''S'' tid1) ) ) ")
case (I_1_enc tid2) note_unified facts = this facts
thus ?thesis by (fastsimp dest!: ltk_secrecy)
qed (insert facts, (((clarsimp, order?) | order))+)?
qed (insert facts, fastsimp+)?
lemma (in restricted_WMF_state) S_kIR_sec:
assumes facts:
"roleMap r tid0 = Some S"
"RLKR(s(AV ''S'' tid0)) ~: reveals t"
"RLKR(s(MV ''I'' tid0)) ~: reveals t"
"RLKR(s(MV ''R'' tid0)) ~: reveals t"
"( tid0, S_1 ) : steps t"
"s(MV ''kIR'' tid0) : knows t"
shows "False"
proof -
note_prefix_closed facts = facts
thus ?thesis proof(sources! "
Enc {| LC ''step1'', s(MV ''TimeI'' tid0), s(MV ''R'' tid0),
s(MV ''kIR'' tid0)
|}
( K ( s(MV ''I'' tid0) ) ( s(AV ''S'' tid0) ) ) ")
case fake note_unified facts = this facts
thus ?thesis by (fastsimp dest!: ltk_secrecy)
next
case (I_1_enc tid1) note_unified facts = this facts
thus ?thesis by (fastsimp dest: I_kIR_sec intro: event_predOrdI)
qed (insert facts, fastsimp+)?
qed
lemma (in restricted_WMF_state) R_kIR_sec:
assumes facts:
"roleMap r tid0 = Some R"
"RLKR(s(AV ''R'' tid0)) ~: reveals t"
"RLKR(s(MV ''I'' tid0)) ~: reveals t"
"RLKR(s(MV ''S'' tid0)) ~: reveals t"
"( tid0, R_2 ) : steps t"
"s(MV ''kIR'' tid0) : knows t"
shows "False"
proof -
note_prefix_closed facts = facts
thus ?thesis proof(sources! "
Enc {| LC ''step2'', s(MV ''TimeS'' tid0), s(MV ''I'' tid0),
s(MV ''kIR'' tid0)
|}
( K ( s(AV ''R'' tid0) ) ( s(MV ''S'' tid0) ) ) ")
case fake note_unified facts = this facts
thus ?thesis by (fastsimp dest!: ltk_secrecy)
next
case (S_2_enc tid1) note_unified facts = this facts
thus ?thesis by (fastsimp dest: S_kIR_sec intro: event_predOrdI)
qed (insert facts, fastsimp+)?
qed
(* subsection: Authentication Properties *)
(* text:
The authentication guarantee for the initiator is trivial because it does not
receive any confirmation that the responder received the new session-key.
*)
lemma (in restricted_WMF_state) S_ni_synch:
assumes facts:
"roleMap r tid3 = Some S"
"RLKR(s(AV ''S'' tid3)) ~: reveals t"
"RLKR(s(MV ''I'' tid3)) ~: reveals t"
"( tid3, S_1 ) : steps t"
shows
"(? tid1.
roleMap r tid1 = Some I &
s(AV ''I'' tid1) = s(MV ''I'' tid3) &
s(AV ''R'' tid1) = s(MV ''R'' tid3) &
s(AV ''S'' tid1) = s(AV ''S'' tid3) &
LN ''TimeI'' tid1 = s(MV ''TimeI'' tid3) &
LN ''kIR'' tid1 = s(MV ''kIR'' tid3) &
predOrd t (St( tid1, I_1 )) (St( tid3, S_1 )))"
proof -
note_prefix_closed facts = facts
thus ?thesis proof(sources! "
Enc {| LC ''step1'', s(MV ''TimeI'' tid3), s(MV ''R'' tid3),
s(MV ''kIR'' tid3)
|}
( K ( s(MV ''I'' tid3) ) ( s(AV ''S'' tid3) ) ) ")
case fake note_unified facts = this facts
thus ?thesis by (fastsimp dest!: ltk_secrecy)
next
case (I_1_enc tid4) note_unified facts = this facts
thus ?thesis by (fastsimp intro: event_predOrdI split: if_splits)
qed (insert facts, fastsimp+)?
qed
lemma (in restricted_WMF_state) R_ni_synch:
assumes facts:
"roleMap r tid2 = Some R"
"RLKR(s(AV ''R'' tid2)) ~: reveals t"
"RLKR(s(MV ''I'' tid2)) ~: reveals t"
"RLKR(s(MV ''S'' tid2)) ~: reveals t"
"( tid2, R_2 ) : steps t"
shows
"(? tid1.
(? tid3.
roleMap r tid1 = Some I &
roleMap r tid3 = Some S &
s(AV ''I'' tid1) = s(MV ''I'' tid2) &
s(MV ''I'' tid2) = s(MV ''I'' tid3) &
s(AV ''R'' tid1) = s(AV ''R'' tid2) &
s(AV ''R'' tid2) = s(MV ''R'' tid3) &
s(AV ''S'' tid1) = s(MV ''S'' tid2) &
s(MV ''S'' tid2) = s(AV ''S'' tid3) &
LN ''TimeI'' tid1 = s(MV ''TimeI'' tid3) &
s(MV ''TimeS'' tid2) = LN ''TimeS'' tid3 &
LN ''kIR'' tid1 = s(MV ''kIR'' tid2) &
s(MV ''kIR'' tid2) = s(MV ''kIR'' tid3) &
predOrd t (St( tid1, I_1 )) (St( tid3, S_1 )) &
predOrd t (St( tid3, S_1 )) (St( tid3, S_2 )) &
predOrd t (St( tid3, S_2 )) (St( tid2, R_2 ))))"
proof -
note_prefix_closed facts = facts
thus ?thesis proof(sources! "
Enc {| LC ''step2'', s(MV ''TimeS'' tid2), s(MV ''I'' tid2),
s(MV ''kIR'' tid2)
|}
( K ( s(AV ''R'' tid2) ) ( s(MV ''S'' tid2) ) ) ")
case fake note_unified facts = this facts
thus ?thesis by (fastsimp dest!: ltk_secrecy)
next
case (S_2_enc tid3) note_unified facts = this facts
thus ?thesis proof(sources! "
Enc {| LC ''step1'', s(MV ''TimeI'' tid3), s(AV ''R'' tid2),
s(MV ''kIR'' tid2)
|}
( K ( s(MV ''I'' tid2) ) ( s(AV ''S'' tid3) ) ) ")
case fake note_unified facts = this facts
thus ?thesis by (fastsimp dest!: ltk_secrecy)
next
case (I_1_enc tid4) note_unified facts = this facts
thus ?thesis by (fastsimp intro: event_predOrdI split: if_splits)
qed (insert facts, fastsimp+)?
qed (insert facts, fastsimp+)?
qed
end |
{-# LANGUAGE MonoLocalBinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE StrictData #-}
module FourierPinwheel.Array where
import qualified Data.Array.Accelerate as A
import qualified Data.Array.Accelerate.LLVM.PTX as A
import Data.Array.Repa as R
import Data.Complex
import Data.List as L
import Data.Vector.Generic as VG
import Data.Vector.Storable as VS
import DFT.Plan
import Filter.Utils
import Graphics.Rendering.Chart.Backend.Cairo
import Graphics.Rendering.Chart.Easy
import Image.IO
import Text.Printf
import Utils.Array
import Utils.BLAS
import Utils.Parallel
import FourierMethod.FourierSeries2D
data FPArray vector = FPArray
{ getFPArrayNumXFreq :: Int
, getFPArrayNumYFreq :: Int
, getFPArrayNumRFreq :: Int
, getFPArrayNumThetaFreq :: Int
, getFPArrayNumRhoFreq :: Int
, getFPArrayNumPhiFreq :: Int
, getFPArray :: [vector]
}
{-# INLINE toMatrixAcc #-}
toMatrixAcc ::
(VG.Vector vector e, A.Elt e) => FPArray (vector e) -> A.Acc (A.Array A.DIM2 e)
toMatrixAcc (FPArray numXFreq numYFreq numRFreq numThetaFreq _ _ arr) =
A.use .
A.fromList (A.Z A.:. (numRFreq * numThetaFreq) A.:. (numXFreq * numYFreq)) .
VG.toList . VG.concat $
arr
{-# INLINE parMapFPArray #-}
parMapFPArray ::
(NFData vector) => (vector -> vector) -> FPArray vector -> FPArray vector
parMapFPArray f (FPArray numXFreq numYFreq numRFreq numThetaFreq numRhoFreq numPhiFreq vecs) =
FPArray numXFreq numYFreq numRFreq numThetaFreq numRhoFreq numPhiFreq .
parMap rdeepseq f $
vecs
{-# INLINE parZipWithFPArray #-}
parZipWithFPArray ::
(NFData vector)
=> (vector -> vector -> vector)
-> FPArray vector
-> FPArray vector
-> FPArray vector
parZipWithFPArray f (FPArray numXFreq numYFreq numRFreq numThetaFreq numRhoFreq numPhiFreq vecs1) =
FPArray numXFreq numYFreq numRFreq numThetaFreq numRhoFreq numPhiFreq .
parZipWith rdeepseq f vecs1 . getFPArray
plotFPArray ::
DFTPlan
-> FilePath
-> FPArray (VS.Vector (Complex Double))
-> IO (R.Array R.U R.DIM4 (Complex Double))
plotFPArray plan filePath arr = do
let planIDBackward =
DFTPlanID
IDFT1DG
[ getFPArrayNumThetaFreq arr
, getFPArrayNumXFreq arr
, getFPArrayNumYFreq arr
]
[1, 2]
vecsR2 <- dftExecuteBatchP plan planIDBackward . getFPArray $ arr
arrR2 <-
R.computeUnboxedP .
makeFilter2DInverse .
R.fromUnboxed
(R.Z R.:. getFPArrayNumRFreq arr R.:. getFPArrayNumThetaFreq arr R.:.
getFPArrayNumXFreq arr R.:.
getFPArrayNumYFreq arr) .
VS.convert . VS.concat $
vecsR2
arr1 <-
R.sumP . R.sumS . R.map (\x -> magnitude x Prelude.^ 2) . rotate4D2 $ arrR2
plotImageRepa filePath .
ImageRepa 8 .
R.fromUnboxed
(R.Z R.:. (1 :: Int) R.:. getFPArrayNumXFreq arr R.:.
getFPArrayNumYFreq arr) .
-- VG.map (\x -> log (x + 1)) .
R.toUnboxed $ arr1
return arrR2
plotFPArrayAcc ::
(A.Elt (Complex Double))
=> [A.PTX]
-> FilePath
-> Int
-> Double
-> Double
-> Int
-> FPArray (VS.Vector (Complex Double))
-> IO (R.Array R.U R.DIM4 (Complex Double))
plotFPArrayAcc ptxs filePath numPoints delta periodR2 numBatch arr@(FPArray numXFreq numYFreq numRFreq numThetaFreq _ _ vecs) = do
let rows = numRFreq * numThetaFreq
cols = numXFreq * numYFreq
arrMat =
A.transpose .
A.use .
A.fromList (A.Z A.:. rows A.:. cols) .
R.toList .
makeFilter2DInverse .
fromUnboxed (Z :. rows :. numXFreq :. numXFreq) . VG.convert . VG.concat $
vecs
arrR2 <-
computeFourierSeriesR2StreamAcc
ptxs
numXFreq
numPoints
rows
periodR2
delta
numBatch
arrMat
(sumP . R.map (\x -> magnitude x ** 2) . rotate3D $ arrR2) >>=
plotImageRepa filePath .
ImageRepa 8 .
fromUnboxed (Z :. (1 :: Int) :. numPoints :. numPoints) . toUnboxed
return .
computeS .
R.reshape (Z :. numRFreq :. numThetaFreq :. numPoints :. numPoints) $
arrR2
plotFPArrayFreqency ::
FilePath
-> FPArray (VS.Vector (Complex Double))
-> IO ()
plotFPArrayFreqency filePath arr = do
arr1 <-
R.sumP .
R.sumS .
R.map (\x -> magnitude x Prelude.^ 2) .
rotate4D2 .
makeFilter2DInverse .
R.fromUnboxed
(R.Z R.:. getFPArrayNumRFreq arr R.:. getFPArrayNumThetaFreq arr R.:.
getFPArrayNumXFreq arr R.:.
getFPArrayNumYFreq arr) .
VS.convert . VS.concat . getFPArray $
arr
plotImageRepa filePath .
ImageRepa 8 .
R.fromUnboxed
(R.Z R.:. (1 :: Int) R.:. getFPArrayNumXFreq arr R.:.
getFPArrayNumYFreq arr) .
-- VG.map (\x -> x^2) .
R.toUnboxed $
arr1
plotRThetaDist ::
FilePath
-> FilePath
-> Int
-> Int
-> Int
-> Double
-> (Int, Int)
-> R.Array R.U R.DIM4 (Complex Double)
-> IO ()
plotRThetaDist filePathTheta filePathR numPoints numTheta numR periodEnv (x, y) arr = do
let (Z :. numRFreq :. numThetaFreq :. _ :. _) = extent arr
center = div numPoints 2
centerR = div numR 2
centerTheta = div numTheta 2
centerRFreq = div numRFreq 2
centerThetaFreq = div numThetaFreq 2
vecRTheta =
VG.convert . R.toUnboxed . R.computeUnboxedS . R.slice arr $
(R.Z R.:. R.All R.:. R.All R.:. (x + center) R.:. (y + center))
deltaTheta = 2 * pi / Prelude.fromIntegral numTheta
deltaLogR = log periodEnv / Prelude.fromIntegral numR
matrix =
VG.convert .
R.toUnboxed .
R.computeUnboxedS .
R.fromFunction (R.Z R.:. numR R.:. numTheta :. numRFreq :. numThetaFreq) $ \(Z :. r :. t :. rf :. tf) ->
cis
(fromIntegral ((r - centerR) * (rf - centerRFreq)) * 2 * pi /
log periodEnv *
deltaLogR +
fromIntegral ((t - centerTheta) * (tf - centerThetaFreq)) *
deltaTheta)
m = numR * numTheta
n = 1
k = numRFreq * numThetaFreq
vec <- VS.map magnitude <$> gemmBLAS m n k matrix vecRTheta
let outputArr = fromUnboxed (Z :. numR :. numTheta) . VG.convert $ vec
outputR = R.toList . sumS $ outputArr
outputTheta =
R.toList .
sumS .
R.backpermute (Z :. numTheta :. numR) (\(Z :. i :. j) -> (Z :. j :. i)) $
outputArr
toFile def filePathTheta $ do
layout_title .= printf "Theta (%d , %d)" x y
plot
(line
""
[ L.zip
[ fromIntegral (i - centerTheta) * deltaTheta
| i <- [0 .. numTheta - 1]
]
outputTheta
])
toFile def filePathR $ do
layout_title .= printf "LogR (%d , %d)" x y
plot
(line
""
[ L.zip
[fromIntegral (i - centerR) * deltaLogR | i <- [0 .. numR - 1]]
outputR
])
|
Why must a mixer look like a garage power tool?! Designer Elisabeth Morris asked herself this question when designing the CILO Hand Mixer. Modeled after the OXO brand language and philosophy, the CILO concept foregoes the power tool aesthetic for a more minimal, elegant design. Its low-profile footprint and sophisticated aesthetic mean you can leave it out on the counter as a kind of sculptural piece without taking up much space.
It also eliminates 3 common problems with standard mixers: cleaning, comfort, and clarity. To make it easy to clean, a metalized plastic cover overhangs before the ventilation channel and is a cinch to wipe clean. For enhanced ergonomics, it features a handleless design – simply wrap your hand around CILO in whatever orientation feels most comfortable whether that be from below, from the side perpendicular to yourself, or on the top. Unlike other mixers with loads of confusing switches and buttons, the CILO makes it easy to operate by using a standard OXO light-up rotating switch. The single release button is positioned directly over the whisks to make its function intuitive.
Additional features of the CILO design include a swivel back that rotates the cord to get it out of your way, a non-slip silicone rubber grip that covers the length of the mixer, and a detachable rear cover that makes repairs and maintenance possible. The motor is housed at an angle for optimum balance and bowl overhang. When you are done, you can quickly wrap and clip the cord around the body of the mixer for consolidated storage. |
\begin{savequote}[120mm]
Welcome to the Hotel California \\
Such a lovely place (Such a lovely place) \\
Such a lovely face \\
Plenty of room at the Hotel California \\
Any time of year (Any time of year) \\
You can find it here
\qauthor{--- Eagles, \textit{Hotel California}, 1977}
\end{savequote}
\chapter{An appendix}
\label{appendix1}
\thispagestyle{fancy}
\textit{\lipsum[1]}
%{\chapHeadFont
\paragraph{Paragraph 1}
\lipsum[2]
\section{Section}
\label{sectionA}
\begin{remark}[Name]
\lipsum[1]
\begin{equation}
E = mc^2 \, .
\end{equation}
\end{remark}
\lipsum[4-7]
|
{-# OPTIONS --no-unicode #-}
module Issue2749 where
-- testing ascii only lambda and arrow
id : {A : Set} -> A -> A
id = {!!}
-- testing ascii only double braces
it : {A : Set} {{a : A}} → A → A
it = {!!}
data B : Set where
mkB : B → B → B
-- testing ascii only suffixes
left : B → B
left b1 = {!!}
open import Agda.Builtin.Equality
-- testing ascii only forall
allq : (∀ m n → m ≡ n) ≡ {!!}
allq = refl
|
import algebra.group -- for is_add_group_hom
import group_theory.subgroup -- for kernels
import algebra.module
import tactic.linarith
import tactic.omega
import tactic.fin_cases
import add_group_hom.basic
import algebra.pi_instances
class G_module (G : Type*) [group G] (M : Type*) [add_comm_group M]
extends has_scalar G M :=
(id : ∀ m : M, (1 : G) • m = m)
(mul : ∀ g h : G, ∀ m : M, g • (h • m) = (g * h) • m)
(linear : ∀ g : G, ∀ m n : M, g • (m + n) = g • m + g • n)
attribute [simp] G_module.linear G_module.mul
@[simp] lemma G_module.G_neg {G : Type*} [group G] {M : Type*} [add_comm_group M]
[G_module G M]
(g : G) (m : M) : g • (-m) = -(g • m) :=
begin
-- h1: g • (m+(-m))=(0:M),
--norm_num,
-- have h: g• (0:M)+g• (0:M)=g• ((0:M)+(0:M)),
--rw G_module.linear,
-- rw add_zero at h,
--exact add_left_eq_self.mp h,
--rw G_module.linear at h1,
--have h2:g • m + g • -m -(g• m)= -(g• m),
-- exact add_left_eq_self.mpr h1,
-- have h3:g • m + g • -m -(g• m)= g • -m,
-- exact add_sub_cancel' _ _,
-- exact (eq.congr rfl h2).mp (eq.symm h3),
have h:g • -m +g • m= -(g • m)+g • m,
rw <-G_module.linear,
norm_num,
have h: g• (0:M)+g• (0:M)=g• ((0:M)+(0:M)),
rw G_module.linear,
rw add_zero at h,
exact add_left_eq_self.mp h,
exact (add_right_inj (g • m)).mp h,
end
lemma G_module.G_sum_smul {G : Type*} [group G] {M : Type*} [add_comm_group M]
[G_module G M] (n:ℕ )(g : G)(f: ℕ → M):finset.sum (finset.range (n+1))(λ (x : ℕ ), g • f x) = g • finset.sum (finset.range(n+1)) f:=
begin
induction n with d hd,
norm_num,
rw finset.sum_range_succ,
rw hd,
rw <-G_module.linear,
rw <-finset.sum_range_succ _ (d+1),
end
lemma G_module.neg_one_pow_mul_comm {G : Type*} [group G] {M : Type*} [add_comm_group M]
[G_module G M] (n:ℕ )(g:G)(m:M): (-1:ℤ )^n • g • m = g • (-1:ℤ)^n • m:=
begin
induction n with d hd,
norm_num,
rw nat.succ_eq_add_one,
rw pow_add,
norm_num,
exact hd,
end |
program bucle_simultaneo
implicit none
real, parameter :: pi =3.14159265
integer, parameter :: n=10
real :: resultado_sin(n)
integer :: i
do concurrent (i=1:n) !Cuidado la sintaxis es ligeramente diferente
resultado_sin(i)=sin(i*pi/4.)
end do
print *, resultado_sin
end program bucle_simultaneo
|
[STATEMENT]
theorem br'_pref_br: "wa_precise_refine (br'_algo \<delta>) (br_algo \<delta>) br'_\<alpha>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. wa_precise_refine (br'_algo \<delta>) (br_algo \<delta>) br'_\<alpha>
[PROOF STEP]
apply unfold_locales
[PROOF STATE]
proof (prove)
goal (5 subgoals):
1. \<And>s. \<lbrakk>s \<in> wa_invar (br'_algo \<delta>); s \<in> wa_cond (br'_algo \<delta>)\<rbrakk> \<Longrightarrow> br'_\<alpha> s \<in> wa_cond (br_algo \<delta>)
2. \<And>s s'. \<lbrakk>s \<in> wa_invar (br'_algo \<delta>); s \<in> wa_cond (br'_algo \<delta>); (s, s') \<in> wa_step (br'_algo \<delta>)\<rbrakk> \<Longrightarrow> (br'_\<alpha> s, br'_\<alpha> s') \<in> wa_step (br_algo \<delta>)
3. br'_\<alpha> ` wa_initial (br'_algo \<delta>) \<subseteq> wa_initial (br_algo \<delta>)
4. br'_\<alpha> ` wa_invar (br'_algo \<delta>) \<subseteq> wa_invar (br_algo \<delta>)
5. \<forall>s. s \<in> wa_invar (br'_algo \<delta>) \<and> br'_\<alpha> s \<in> wa_cond (br_algo \<delta>) \<longrightarrow> s \<in> wa_cond (br'_algo \<delta>)
[PROOF STEP]
apply (simp_all add: br'_algo_def br_algo_def)
[PROOF STATE]
proof (prove)
goal (5 subgoals):
1. \<And>s. \<lbrakk>s \<in> br'_invar \<delta>; s \<in> br'_cond\<rbrakk> \<Longrightarrow> br'_\<alpha> s \<in> br_cond
2. \<And>s s'. \<lbrakk>s \<in> br'_invar \<delta>; s \<in> br'_cond; (s, s') \<in> br'_step \<delta>\<rbrakk> \<Longrightarrow> (br'_\<alpha> s, br'_\<alpha> s') \<in> br_step \<delta>
3. br'_\<alpha> ` br'_initial \<delta> \<subseteq> {br_initial \<delta>}
4. br'_\<alpha> ` br'_invar \<delta> \<subseteq> br_invar \<delta>
5. \<forall>a aa b. (a, aa, b) \<in> br'_invar \<delta> \<and> br'_\<alpha> (a, aa, b) \<in> br_cond \<longrightarrow> (a, aa, b) \<in> br'_cond
[PROOF STEP]
apply (simp_all add: br'_cond_abs br'_step_abs br'_invar_abs br'_initial_abs)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
module mod_common_mpi
use mpi
use mod_param, only: dims
implicit none
integer :: myid
integer :: left,right,front,back
integer, dimension(2) :: coord
integer :: comm_cart,ierr
integer :: xhalo,yhalo
integer :: status(MPI_STATUS_SIZE)
end module mod_common_mpi
|
\chapter{Several stuff unfinished}
%---------------------------------------------
%---------------------------------------------
%---------------------------------------------
%\section{Co-variance propagation}
|
if true 1 elseif true 2 end
|
SUBROUTINE DPTTRF( N, D, E, INFO )
*
* -- LAPACK routine (version 2.0) --
* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
* Courant Institute, Argonne National Lab, and Rice University
* March 31, 1993
*
* .. Scalar Arguments ..
INTEGER INFO, N
* ..
* .. Array Arguments ..
DOUBLE PRECISION D( * ), E( * )
* ..
*
* Purpose
* =======
*
* DPTTRF computes the factorization of a real symmetric positive
* definite tridiagonal matrix A.
*
* If the subdiagonal elements of A are supplied in the array E, the
* factorization has the form A = L*D*L**T, where D is diagonal and L
* is unit lower bidiagonal; if the superdiagonal elements of A are
* supplied, it has the form A = U**T*D*U, where U is unit upper
* bidiagonal. (The two forms are equivalent if A is real.)
*
* Arguments
* =========
*
* N (input) INTEGER
* The order of the matrix A. N >= 0.
*
* D (input/output) DOUBLE PRECISION array, dimension (N)
* On entry, the n diagonal elements of the tridiagonal matrix
* A. On exit, the n diagonal elements of the diagonal matrix
* D from the L*D*L**T factorization of A.
*
* E (input/output) DOUBLE PRECISION array, dimension (N-1)
* On entry, the (n-1) off-diagonal elements of the tridiagonal
* matrix A.
* On exit, the (n-1) off-diagonal elements of the unit
* bidiagonal factor L or U from the factorization of A.
*
* INFO (output) INTEGER
* = 0: successful exit
* < 0: if INFO = -i, the i-th argument had an illegal value
* > 0: if INFO = i, the leading minor of order i is not
* positive definite; if i < N, the factorization could
* not be completed, while if i = N, the factorization was
* completed, but D(N) = 0.
*
* =====================================================================
*
* .. Parameters ..
DOUBLE PRECISION ZERO
PARAMETER ( ZERO = 0.0D+0 )
* ..
* .. Local Scalars ..
INTEGER I
DOUBLE PRECISION DI, EI
* ..
* .. External Subroutines ..
EXTERNAL XERBLA
* ..
* .. Executable Statements ..
*
* Test the input parameters.
*
INFO = 0
IF( N.LT.0 ) THEN
INFO = -1
CALL XERBLA( 'DPTTRF', -INFO )
RETURN
END IF
*
* Quick return if possible
*
IF( N.EQ.0 )
$ RETURN
*
* Compute the L*D*L' (or U'*D*U) factorization of A.
*
DO 10 I = 1, N - 1
*
* Drop out of the loop if d(i) <= 0: the matrix is not positive
* definite.
*
DI = D( I )
IF( DI.LE.ZERO )
$ GO TO 20
*
* Solve for e(i) and d(i+1).
*
EI = E( I )
E( I ) = EI / DI
D( I+1 ) = D( I+1 ) - E( I )*EI
10 CONTINUE
*
* Check d(n) for positive definiteness.
*
I = N
IF( D( I ).GT.ZERO )
$ GO TO 30
*
20 CONTINUE
INFO = I
*
30 CONTINUE
RETURN
*
* End of DPTTRF
*
END
SUBROUTINE SPTTRF( N, D, E, INFO )
*
* -- LAPACK routine (version 2.0) --
* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
* Courant Institute, Argonne National Lab, and Rice University
* March 31, 1993
*
* .. Scalar Arguments ..
INTEGER INFO, N
* ..
* .. Array Arguments ..
REAL D( * ), E( * )
* ..
*
* Purpose
* =======
*
* SPTTRF computes the factorization of a real symmetric positive
* definite tridiagonal matrix A.
*
* If the subdiagonal elements of A are supplied in the array E, the
* factorization has the form A = L*D*L**T, where D is diagonal and L
* is unit lower bidiagonal; if the superdiagonal elements of A are
* supplied, it has the form A = U**T*D*U, where U is unit upper
* bidiagonal. (The two forms are equivalent if A is real.)
*
* Arguments
* =========
*
* N (input) INTEGER
* The order of the matrix A. N >= 0.
*
* D (input/output) REAL array, dimension (N)
* On entry, the n diagonal elements of the tridiagonal matrix
* A. On exit, the n diagonal elements of the diagonal matrix
* D from the L*D*L**T factorization of A.
*
* E (input/output) REAL array, dimension (N-1)
* On entry, the (n-1) off-diagonal elements of the tridiagonal
* matrix A.
* On exit, the (n-1) off-diagonal elements of the unit
* bidiagonal factor L or U from the factorization of A.
*
* INFO (output) INTEGER
* = 0: successful exit
* < 0: if INFO = -i, the i-th argument had an illegal value
* > 0: if INFO = i, the leading minor of order i is not
* positive definite; if i < N, the factorization could
* not be completed, while if i = N, the factorization was
* completed, but D(N) = 0.
*
* =====================================================================
*
* .. Parameters ..
REAL ZERO
PARAMETER ( ZERO = 0.0E+0 )
* ..
* .. Local Scalars ..
INTEGER I
REAL DI, EI
* ..
* .. External Subroutines ..
EXTERNAL XERBLA
* ..
* .. Executable Statements ..
*
* Test the input parameters.
*
INFO = 0
IF( N.LT.0 ) THEN
INFO = -1
CALL XERBLA( 'SPTTRF', -INFO )
RETURN
END IF
*
* Quick return if possible
*
IF( N.EQ.0 )
$ RETURN
*
* Compute the L*D*L' (or U'*D*U) factorization of A.
*
DO 10 I = 1, N - 1
*
* Drop out of the loop if d(i) <= 0: the matrix is not positive
* definite.
*
DI = D( I )
IF( DI.LE.ZERO )
$ GO TO 20
*
* Solve for e(i) and d(i+1).
*
EI = E( I )
E( I ) = EI / DI
D( I+1 ) = D( I+1 ) - E( I )*EI
10 CONTINUE
*
* Check d(n) for positive definiteness.
*
I = N
IF( D( I ).GT.ZERO )
$ GO TO 30
*
20 CONTINUE
INFO = I
*
30 CONTINUE
RETURN
*
* End of SPTTRF
*
END
|
(* Default settings (from HsToCoq.Coq.Preamble) *)
Generalizable All Variables.
Unset Implicit Arguments.
Set Maximal Implicit Insertion.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Require Coq.Program.Tactics.
Require Coq.Program.Wf.
(* Preamble *)
(* Fix the type parameter of Const *)
Implicit Type b : Type.
(* A hack to make a few kind-polymorpic definitions go through *)
Class unit_class.
Instance unit_class_instance : unit_class := {}.
Implicit Type inst_k: unit_class.
(* Converted imports: *)
Require Coq.Program.Basics.
Require Data.Foldable.
Require Data.SemigroupInternal.
Require GHC.Base.
Require GHC.Num.
Require GHC.Prim.
Require HsToCoq.Unpeel.
Import GHC.Base.Notations.
Import GHC.Num.Notations.
(* Converted type declarations: *)
Inductive Const {k : Type} (a : Type) (b : k) : Type :=
| Mk_Const (getConst : a) : Const a b.
Arguments Mk_Const {_} {_} {_} _.
Definition getConst {k : Type} {a : Type} {b : k} (arg_0__ : Const a b) :=
let 'Mk_Const getConst := arg_0__ in
getConst.
(* Converted value declarations: *)
(* Skipping all instances of class `Data.Bits.Bits', including
`Data.Functor.Const.Bits__Const' *)
(* Skipping all instances of class `GHC.Enum.Bounded', including
`Data.Functor.Const.Bounded__Const' *)
(* Skipping all instances of class `GHC.Enum.Enum', including
`Data.Functor.Const.Enum__Const' *)
Instance Unpeel_Const (k a : Type) (b : k)
: HsToCoq.Unpeel.Unpeel (Const a b) a :=
HsToCoq.Unpeel.Build_Unpeel _ _ getConst Mk_Const.
Local Definition Eq___Const_op_zeze__ {inst_a : Type} {inst_k : Type} {inst_b
: inst_k} `{GHC.Base.Eq_ inst_a}
: Const inst_a inst_b -> Const inst_a inst_b -> bool :=
GHC.Prim.coerce _GHC.Base.==_.
Local Definition Eq___Const_op_zsze__ {inst_a : Type} {inst_k : Type} {inst_b
: inst_k} `{GHC.Base.Eq_ inst_a}
: Const inst_a inst_b -> Const inst_a inst_b -> bool :=
GHC.Prim.coerce _GHC.Base./=_.
Program Instance Eq___Const {a : Type} {k : Type} {b : k} `{GHC.Base.Eq_ a}
: GHC.Base.Eq_ (Const a b) :=
fun _ k__ =>
k__ {| GHC.Base.op_zeze____ := Eq___Const_op_zeze__ ;
GHC.Base.op_zsze____ := Eq___Const_op_zsze__ |}.
(* Skipping all instances of class `Data.Bits.FiniteBits', including
`Data.Functor.Const.FiniteBits__Const' *)
(* Skipping all instances of class `GHC.Float.Floating', including
`Data.Functor.Const.Floating__Const' *)
(* Skipping all instances of class `GHC.Real.Fractional', including
`Data.Functor.Const.Fractional__Const' *)
(* Skipping all instances of class `GHC.Generics.Generic', including
`Data.Functor.Const.Generic__Const' *)
(* Skipping all instances of class `GHC.Generics.Generic1', including
`Data.Functor.Const.Generic1__Const__5' *)
(* Skipping all instances of class `GHC.Real.Integral', including
`Data.Functor.Const.Integral__Const' *)
(* Skipping all instances of class `GHC.Arr.Ix', including
`Data.Functor.Const.Ix__Const' *)
Local Definition Semigroup__Const_op_zlzlzgzg__ {inst_a : Type} {inst_k : Type}
{inst_b : inst_k} `{GHC.Base.Semigroup inst_a}
: Const inst_a inst_b -> Const inst_a inst_b -> Const inst_a inst_b :=
GHC.Prim.coerce _GHC.Base.<<>>_.
Program Instance Semigroup__Const {a : Type} {k : Type} {b : k}
`{GHC.Base.Semigroup a}
: GHC.Base.Semigroup (Const a b) :=
fun _ k__ =>
k__ {| GHC.Base.op_zlzlzgzg____ := Semigroup__Const_op_zlzlzgzg__ |}.
Local Definition Monoid__Const_mappend {inst_a : Type} {inst_k : Type} {inst_b
: inst_k} `{GHC.Base.Monoid inst_a}
: Const inst_a inst_b -> Const inst_a inst_b -> Const inst_a inst_b :=
GHC.Prim.coerce GHC.Base.mappend.
Local Definition Monoid__Const_mconcat {inst_a : Type} {inst_k : Type} {inst_b
: inst_k} `{GHC.Base.Monoid inst_a}
: list (Const inst_a inst_b) -> Const inst_a inst_b :=
GHC.Prim.coerce GHC.Base.mconcat.
Local Definition Monoid__Const_mempty {inst_a : Type} {inst_k : Type} {inst_b
: inst_k} `{GHC.Base.Monoid inst_a}
: Const inst_a inst_b :=
GHC.Prim.coerce GHC.Base.mempty.
Program Instance Monoid__Const {a : Type} {k : Type} {b : k} `{GHC.Base.Monoid
a}
: GHC.Base.Monoid (Const a b) :=
fun _ k__ =>
k__ {| GHC.Base.mappend__ := Monoid__Const_mappend ;
GHC.Base.mconcat__ := Monoid__Const_mconcat ;
GHC.Base.mempty__ := Monoid__Const_mempty |}.
(* Skipping all instances of class `GHC.Num.Num', including
`Data.Functor.Const.Num__Const' *)
Local Definition Ord__Const_op_zl__ {inst_a : Type} {inst_k : Type} {inst_b
: inst_k} `{GHC.Base.Ord inst_a}
: Const inst_a inst_b -> Const inst_a inst_b -> bool :=
GHC.Prim.coerce _GHC.Base.<_.
Local Definition Ord__Const_op_zlze__ {inst_a : Type} {inst_k : Type} {inst_b
: inst_k} `{GHC.Base.Ord inst_a}
: Const inst_a inst_b -> Const inst_a inst_b -> bool :=
GHC.Prim.coerce _GHC.Base.<=_.
Local Definition Ord__Const_op_zg__ {inst_a : Type} {inst_k : Type} {inst_b
: inst_k} `{GHC.Base.Ord inst_a}
: Const inst_a inst_b -> Const inst_a inst_b -> bool :=
GHC.Prim.coerce _GHC.Base.>_.
Local Definition Ord__Const_op_zgze__ {inst_a : Type} {inst_k : Type} {inst_b
: inst_k} `{GHC.Base.Ord inst_a}
: Const inst_a inst_b -> Const inst_a inst_b -> bool :=
GHC.Prim.coerce _GHC.Base.>=_.
Local Definition Ord__Const_compare {inst_a : Type} {inst_k : Type} {inst_b
: inst_k} `{GHC.Base.Ord inst_a}
: Const inst_a inst_b -> Const inst_a inst_b -> comparison :=
GHC.Prim.coerce GHC.Base.compare.
Local Definition Ord__Const_max {inst_a : Type} {inst_k : Type} {inst_b
: inst_k} `{GHC.Base.Ord inst_a}
: Const inst_a inst_b -> Const inst_a inst_b -> Const inst_a inst_b :=
GHC.Prim.coerce GHC.Base.max.
Local Definition Ord__Const_min {inst_a : Type} {inst_k : Type} {inst_b
: inst_k} `{GHC.Base.Ord inst_a}
: Const inst_a inst_b -> Const inst_a inst_b -> Const inst_a inst_b :=
GHC.Prim.coerce GHC.Base.min.
Program Instance Ord__Const {a : Type} {k : Type} {b : k} `{GHC.Base.Ord a}
: GHC.Base.Ord (Const a b) :=
fun _ k__ =>
k__ {| GHC.Base.op_zl____ := Ord__Const_op_zl__ ;
GHC.Base.op_zlze____ := Ord__Const_op_zlze__ ;
GHC.Base.op_zg____ := Ord__Const_op_zg__ ;
GHC.Base.op_zgze____ := Ord__Const_op_zgze__ ;
GHC.Base.compare__ := Ord__Const_compare ;
GHC.Base.max__ := Ord__Const_max ;
GHC.Base.min__ := Ord__Const_min |}.
(* Skipping all instances of class `GHC.Real.Real', including
`Data.Functor.Const.Real__Const' *)
(* Skipping all instances of class `GHC.Real.RealFrac', including
`Data.Functor.Const.RealFrac__Const' *)
(* Skipping all instances of class `GHC.Float.RealFloat', including
`Data.Functor.Const.RealFloat__Const' *)
(* Skipping all instances of class `Foreign.Storable.Storable', including
`Data.Functor.Const.Storable__Const' *)
(* Skipping all instances of class `GHC.Read.Read', including
`Data.Functor.Const.Read__Const' *)
(* Skipping all instances of class `GHC.Show.Show', including
`Data.Functor.Const.Show__Const' *)
Local Definition Foldable__Const_foldMap {inst_m : Type}
: forall {m : Type},
forall {a : Type},
forall `{GHC.Base.Monoid m}, (a -> m) -> Const inst_m a -> m :=
fun {m : Type} {a : Type} `{GHC.Base.Monoid m} =>
fun arg_0__ arg_1__ => GHC.Base.mempty.
Local Definition Foldable__Const_fold {inst_m : Type}
: forall {m : Type}, forall `{GHC.Base.Monoid m}, Const inst_m m -> m :=
fun {m : Type} `{GHC.Base.Monoid m} => Foldable__Const_foldMap GHC.Base.id.
Local Definition Foldable__Const_foldl {inst_m : Type}
: forall {b : Type},
forall {a : Type}, (b -> a -> b) -> b -> Const inst_m a -> b :=
fun {b : Type} {a : Type} =>
fun f z t =>
Data.SemigroupInternal.appEndo (Data.SemigroupInternal.getDual
(Foldable__Const_foldMap (Data.SemigroupInternal.Mk_Dual GHC.Base.∘
(Data.SemigroupInternal.Mk_Endo GHC.Base.∘
GHC.Base.flip f)) t)) z.
Local Definition Foldable__Const_foldr {inst_m : Type}
: forall {a : Type},
forall {b : Type}, (a -> b -> b) -> b -> Const inst_m a -> b :=
fun {a : Type} {b : Type} =>
fun f z t =>
Data.SemigroupInternal.appEndo (Foldable__Const_foldMap
(Coq.Program.Basics.compose Data.SemigroupInternal.Mk_Endo f) t) z.
Local Definition Foldable__Const_foldl' {inst_m : Type}
: forall {b : Type},
forall {a : Type}, (b -> a -> b) -> b -> Const inst_m a -> b :=
fun {b : Type} {a : Type} =>
fun f z0 xs =>
let f' := fun x k z => k (f z x) in Foldable__Const_foldr f' GHC.Base.id xs z0.
Local Definition Foldable__Const_foldr' {inst_m : Type}
: forall {a : Type},
forall {b : Type}, (a -> b -> b) -> b -> Const inst_m a -> b :=
fun {a : Type} {b : Type} =>
fun f z0 xs =>
let f' := fun k x z => k (f x z) in Foldable__Const_foldl f' GHC.Base.id xs z0.
Local Definition Foldable__Const_length {inst_m : Type}
: forall {a : Type}, Const inst_m a -> GHC.Num.Int :=
fun {a : Type} =>
Foldable__Const_foldl' (fun arg_0__ arg_1__ =>
match arg_0__, arg_1__ with
| c, _ => c GHC.Num.+ #1
end) #0.
Local Definition Foldable__Const_null {inst_m : Type}
: forall {a : Type}, Const inst_m a -> bool :=
fun {a : Type} => Foldable__Const_foldr (fun arg_0__ arg_1__ => false) true.
Local Definition Foldable__Const_product {inst_m : Type}
: forall {a : Type}, forall `{GHC.Num.Num a}, Const inst_m a -> a :=
fun {a : Type} `{GHC.Num.Num a} =>
Coq.Program.Basics.compose Data.SemigroupInternal.getProduct
(Foldable__Const_foldMap Data.SemigroupInternal.Mk_Product).
Local Definition Foldable__Const_sum {inst_m : Type}
: forall {a : Type}, forall `{GHC.Num.Num a}, Const inst_m a -> a :=
fun {a : Type} `{GHC.Num.Num a} =>
Coq.Program.Basics.compose Data.SemigroupInternal.getSum
(Foldable__Const_foldMap Data.SemigroupInternal.Mk_Sum).
Local Definition Foldable__Const_toList {inst_m : Type}
: forall {a : Type}, Const inst_m a -> list a :=
fun {a : Type} =>
fun t => GHC.Base.build' (fun _ => (fun c n => Foldable__Const_foldr c n t)).
Program Instance Foldable__Const {m : Type}
: Data.Foldable.Foldable (Const m) :=
fun _ k__ =>
k__ {| Data.Foldable.fold__ := fun {m : Type} `{GHC.Base.Monoid m} =>
Foldable__Const_fold ;
Data.Foldable.foldMap__ := fun {m : Type} {a : Type} `{GHC.Base.Monoid m} =>
Foldable__Const_foldMap ;
Data.Foldable.foldl__ := fun {b : Type} {a : Type} => Foldable__Const_foldl ;
Data.Foldable.foldl'__ := fun {b : Type} {a : Type} => Foldable__Const_foldl' ;
Data.Foldable.foldr__ := fun {a : Type} {b : Type} => Foldable__Const_foldr ;
Data.Foldable.foldr'__ := fun {a : Type} {b : Type} => Foldable__Const_foldr' ;
Data.Foldable.length__ := fun {a : Type} => Foldable__Const_length ;
Data.Foldable.null__ := fun {a : Type} => Foldable__Const_null ;
Data.Foldable.product__ := fun {a : Type} `{GHC.Num.Num a} =>
Foldable__Const_product ;
Data.Foldable.sum__ := fun {a : Type} `{GHC.Num.Num a} => Foldable__Const_sum ;
Data.Foldable.toList__ := fun {a : Type} => Foldable__Const_toList |}.
Local Definition Functor__Const_fmap {inst_m : Type}
: forall {a : Type},
forall {b : Type}, (a -> b) -> Const inst_m a -> Const inst_m b :=
fun {a : Type} {b : Type} =>
fun arg_0__ arg_1__ =>
match arg_0__, arg_1__ with
| _, Mk_Const v => Mk_Const v
end.
Local Definition Functor__Const_op_zlzd__ {inst_m : Type}
: forall {a : Type},
forall {b : Type}, a -> Const inst_m b -> Const inst_m a :=
fun {a : Type} {b : Type} => Functor__Const_fmap GHC.Base.∘ GHC.Base.const.
Program Instance Functor__Const {m : Type} : GHC.Base.Functor (Const m) :=
fun _ k__ =>
k__ {| GHC.Base.fmap__ := fun {a : Type} {b : Type} => Functor__Const_fmap ;
GHC.Base.op_zlzd____ := fun {a : Type} {b : Type} =>
Functor__Const_op_zlzd__ |}.
Local Definition Applicative__Const_liftA2 {inst_m : Type} `{GHC.Base.Monoid
inst_m}
: forall {a : Type},
forall {b : Type},
forall {c : Type},
(a -> b -> c) -> Const inst_m a -> Const inst_m b -> Const inst_m c :=
fun {a : Type} {b : Type} {c : Type} =>
fun arg_0__ arg_1__ arg_2__ =>
match arg_0__, arg_1__, arg_2__ with
| _, Mk_Const x, Mk_Const y => Mk_Const (GHC.Base.mappend x y)
end.
Local Definition Applicative__Const_op_zlztzg__ {inst_m : Type}
`{GHC.Base.Monoid inst_m}
: forall {a : Type},
forall {b : Type}, Const inst_m (a -> b) -> Const inst_m a -> Const inst_m b :=
fun {a : Type} {b : Type} =>
GHC.Prim.coerce (GHC.Base.mappend : inst_m -> inst_m -> inst_m).
Local Definition Applicative__Const_op_ztzg__ {inst_m : Type} `{GHC.Base.Monoid
inst_m}
: forall {a : Type},
forall {b : Type}, Const inst_m a -> Const inst_m b -> Const inst_m b :=
fun {a : Type} {b : Type} =>
fun a1 a2 => Applicative__Const_op_zlztzg__ (GHC.Base.id GHC.Base.<$ a1) a2.
Local Definition Applicative__Const_pure {inst_m : Type} `{GHC.Base.Monoid
inst_m}
: forall {a : Type}, a -> Const inst_m a :=
fun {a : Type} => fun arg_0__ => Mk_Const GHC.Base.mempty.
Program Instance Applicative__Const {m : Type} `{GHC.Base.Monoid m}
: GHC.Base.Applicative (Const m) :=
fun _ k__ =>
k__ {| GHC.Base.liftA2__ := fun {a : Type} {b : Type} {c : Type} =>
Applicative__Const_liftA2 ;
GHC.Base.op_zlztzg____ := fun {a : Type} {b : Type} =>
Applicative__Const_op_zlztzg__ ;
GHC.Base.op_ztzg____ := fun {a : Type} {b : Type} =>
Applicative__Const_op_ztzg__ ;
GHC.Base.pure__ := fun {a : Type} => Applicative__Const_pure |}.
(* External variables:
Type bool comparison false list true Coq.Program.Basics.compose
Data.Foldable.Foldable Data.Foldable.foldMap__ Data.Foldable.fold__
Data.Foldable.foldl'__ Data.Foldable.foldl__ Data.Foldable.foldr'__
Data.Foldable.foldr__ Data.Foldable.length__ Data.Foldable.null__
Data.Foldable.product__ Data.Foldable.sum__ Data.Foldable.toList__
Data.SemigroupInternal.Mk_Dual Data.SemigroupInternal.Mk_Endo
Data.SemigroupInternal.Mk_Product Data.SemigroupInternal.Mk_Sum
Data.SemigroupInternal.appEndo Data.SemigroupInternal.getDual
Data.SemigroupInternal.getProduct Data.SemigroupInternal.getSum
GHC.Base.Applicative GHC.Base.Eq_ GHC.Base.Functor GHC.Base.Monoid GHC.Base.Ord
GHC.Base.Semigroup GHC.Base.build' GHC.Base.compare GHC.Base.compare__
GHC.Base.const GHC.Base.flip GHC.Base.fmap__ GHC.Base.id GHC.Base.liftA2__
GHC.Base.mappend GHC.Base.mappend__ GHC.Base.max GHC.Base.max__ GHC.Base.mconcat
GHC.Base.mconcat__ GHC.Base.mempty GHC.Base.mempty__ GHC.Base.min GHC.Base.min__
GHC.Base.op_z2218U__ GHC.Base.op_zeze__ GHC.Base.op_zeze____ GHC.Base.op_zg__
GHC.Base.op_zg____ GHC.Base.op_zgze__ GHC.Base.op_zgze____ GHC.Base.op_zl__
GHC.Base.op_zl____ GHC.Base.op_zlzd__ GHC.Base.op_zlzd____ GHC.Base.op_zlze__
GHC.Base.op_zlze____ GHC.Base.op_zlzlzgzg__ GHC.Base.op_zlzlzgzg____
GHC.Base.op_zlztzg____ GHC.Base.op_zsze__ GHC.Base.op_zsze____
GHC.Base.op_ztzg____ GHC.Base.pure__ GHC.Num.Int GHC.Num.Num GHC.Num.fromInteger
GHC.Num.op_zp__ GHC.Prim.coerce HsToCoq.Unpeel.Build_Unpeel
HsToCoq.Unpeel.Unpeel
*)
|
Lorenzo Ganganelli , <unk> ( September 24 , 1759 ) – Cardinal @-@ Priest of SS . XII Apostoli
|
{-# OPTIONS --without-K #-}
module algebra.group.morphism where
open import level
open import algebra.group.core
open import algebra.monoid.morphism
module _ {i}{j}
{X : Set i}⦃ sX : IsGroup X ⦄
{Y : Set j}⦃ sY : IsGroup Y ⦄ where
open IsGroup ⦃ ... ⦄
IsGroupMorphism : (X → Y) → Set (i ⊔ j)
IsGroupMorphism f = IsMonoidMorphism f
|
# by default, MLJType objects are `==` if: (i) they have ==
# type, AND (ii) they have the same set of *defined* fields AND (iii)
# their defined field values are `==` OR the values are both
# AbstractRNG objects.
import Base.==
function ==(m1::M1, m2::M2) where {M1<:MLJType,M2<:MLJType}
if typeof(m1) != typeof(m2)
return false
end
defined1 = filter(fieldnames(M1)|>collect) do fld
isdefined(m1, fld)
end
defined2 = filter(fieldnames(M1)|>collect) do fld
isdefined(m2, fld)
end
if defined1 != defined2
return false
end
same_values = true
for fld in defined1
same_values = same_values &&
(getfield(m1, fld) == getfield(m2, fld) ||
getfield(m1, fld) isa AbstractRNG)
end
return same_values
end
# for using `replace` or `replace!` on collections of MLJType objects
# (eg, Model objects in a learning network) we need a stricter
# equality:
MLJBase.isequal(m1::MLJType, m2::MLJType) = (m1 === m2)
## TODO: Do we need to overload hash here?
function Base.in(x::MLJType, itr::Set)
anymissing = false
for y in itr
v = (y === x)
if ismissing(v)
anymissing = true
elseif v
return true
end
end
return anymissing ? missing : false
end
|
C
C
real*4 function ct_enh_col( rgb, ci, cimin, cimax )
C ---------------------------------------------------
C
C Function defining an enhanced colour-scale.
C
C defining:
C x = (ci-cimin)/(cimax-cimin)
C then:
C ct_enh_col = ((x-start_colour)/(upper_bound-lower_bound))**power_law
C
C for:
C lower_bound,start_colour <= x <= upper_bound
C
C otherwise:
C ct_enh_col = 0.0 or 1.0
C
C Where the parameters upper_bound, lower_bound and power_law are passed
C in common and depend on the colour index
*-
include '../include/tv_modify.inc'
integer rgb, ci, cimin, cimax
real*4 x
x = (float(ci-cimin)/float(cimax-cimin))
if (x.ge.lower_bound .and. x.le.upper_bound) then
if ((x-lower_bound).ge.col_starts(rgb)) then
ct_enh_col = ( (x-col_starts(rgb))
* /(upper_bound-col_starts(rgb))
* )**col_power_law(rgb)
else
ct_enh_col = 0.0
end if
else if (x.lt.lower_bound) then
ct_enh_col = 0.0
else
ct_enh_col = 1.0
end if
end
|
theory qemu_malloc
imports "../../../isabelle/VCG/HTriple"
begin
locale "qemu_img_xen" = execution_context + exec_code +
fixes abort_0x3710_retval\<^sub>v malloc_0x5974_retval\<^sub>v abort_addr malloc_addr :: \<open>64 word\<close>
and abort_acode malloc_acode :: ACode
assumes fetch:
"fetch 0x3710 \<equiv> (Unary (IS_8088 Call) (Immediate SixtyFour (ImmLabel ''abort'')), 5)"
"fetch 0x5970 \<equiv> (Binary (IS_8088 Sub) (Reg (General SixtyFour rsp)) (Immediate SixtyFour (ImmVal 8)), 4)"
"fetch 0x5974 \<equiv> (Unary (IS_8088 Call) (Immediate SixtyFour (ImmLabel ''malloc'')), 5)"
"fetch 0x5979 \<equiv> (Binary (IS_8088 Test) (Reg (General SixtyFour rax)) (Storage (Reg (General SixtyFour rax))), 3)"
"fetch 0x597c \<equiv> (Unary (IS_8088 Je) (Immediate SixtyFour (ImmVal 14096)), 6)"
"fetch 0x5982 \<equiv> (Binary (IS_8088 Add) (Reg (General SixtyFour rsp)) (Immediate SixtyFour (ImmVal 8)), 4)"
"fetch 0x5986 \<equiv> (Nullary (IS_8088 Ret), 1)"
and \<alpha>_def: \<open>\<alpha> = \<lparr>text_sections = [], data_sections = [], labels_to_offsets = [], binary_offset = 0\<rparr>\<close>
and abort\<^sub>a\<^sub>d\<^sub>d\<^sub>r[simp]: \<open>the (label_to_address \<alpha> ''abort'') = abort_addr\<close>
and malloc\<^sub>a\<^sub>d\<^sub>d\<^sub>r[simp]: \<open>the (label_to_address \<alpha> ''malloc'') = malloc_addr\<close>
begin
text \<open>Using definitions that don't get unfolded immediately prevents locale argument issues.\<close>
definition \<open>abort_0x3710_retval \<equiv> abort_0x3710_retval\<^sub>v\<close>
definition \<open>malloc_0x5974_retval \<equiv> malloc_0x5974_retval\<^sub>v\<close>
text \<open>
Going with a binary offset of 0 for now to make things easier. (We do want to keep that field
around, though, for future more generic usage.)
\<close>
lemma \<alpha>_boffset[simp]: \<open>binary_offset \<alpha> = 0\<close>
unfolding \<alpha>_def
by simp
named_theorems blocks and Ps and Qs
method step uses add del =
subst exec_block.simps,
rewrite_one_let',
rewrite_one_let' add: fetch,
rewrite_one_let',
auto simp add: simp_rules Let'_def read_region'_def write_block'_def get'_def set'_def step_def exec_instr_def presimplify add simp del: del
method steps uses pre post regionset add del =
auto simp: pred_logic pre regionset,
(step add: add del: del)+,
auto simp: block_usage_def eq_def setcc_def simp_rules Let'_def read_region'_def write_block'_def get'_def set'_def post regionset
method vcg_step uses assms =
((rule htriples)+, rule blocks)+,
(simp add: assms pred_logic Ps Qs)?,
(((auto simp: eq_def)[])+)?
method vcg uses acode assms =
subst acode,
(vcg_step assms: assms)+
end
locale "qemu_malloc_cold_0" = "qemu_img_xen" +
fixes RAX\<^sub>0\<^sub>v RSP\<^sub>0\<^sub>v ret_address\<^sub>v :: \<open>64 word\<close>
begin
text \<open>Using definitions that don't get unfolded immediately prevents locale argument issues.\<close>
definition \<open>RAX\<^sub>0 \<equiv> RAX\<^sub>0\<^sub>v\<close>
definition \<open>RSP\<^sub>0 \<equiv> RSP\<^sub>0\<^sub>v\<close>
definition \<open>ret_address \<equiv> ret_address\<^sub>v\<close>
definition P_0x3710_0 :: state_pred where
\<open>P_0x3710_0 \<sigma> \<equiv> RIP \<sigma> = 0x3710 \<and> RAX \<sigma> = RAX\<^sub>0 \<and> RSP \<sigma> = RSP\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address\<close>
declare P_0x3710_0_def[Ps]
definition P_0x3710_0_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x3710_0_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((RSP\<^sub>0::64 word) - 0x8), 8)
}\<close>
definition P_0x3710_0_regions :: state_pred where
\<open>P_0x3710_0_regions \<sigma> \<equiv> \<exists>regions. P_0x3710_0_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_abort_addr_0x3710_0 :: state_pred where
\<open>Q_abort_addr_0x3710_0 \<sigma> \<equiv> RSP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> RIP \<sigma> = abort_addr \<and> RAX \<sigma> = RAX\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x8),8]::64 word) = 0x3715\<close>
declare Q_abort_addr_0x3710_0_def[Qs]
schematic_goal qemu_malloc_cold_0_0_1_0x3710_0x3710_0[blocks]:
assumes \<open>(P_0x3710_0 && P_0x3710_0_regions) \<sigma>\<close>
shows \<open>exec_block (Suc 0) 0x3710 0 \<sigma> \<triangleq> ?\<sigma> \<and> Q_abort_addr_0x3710_0 ?\<sigma> \<and> block_usage P_0x3710_0_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x3710_0_def P_0x3710_0_regions_def post: Q_abort_addr_0x3710_0_def regionset: P_0x3710_0_regions_set_def)
definition qemu_malloc_cold_0_acode :: ACode where
\<open>qemu_malloc_cold_0_acode =
Block (Suc 0) 0x3710 0;
CALL abort_acode
\<close>
schematic_goal "qemu_malloc_cold_0":
assumes
[blocks]: \<open>{{Q_abort_addr_0x3710_0}} \<box>abort_acode {{Q_fail;M_0x3710}}\<close>
shows \<open>{{?P}} qemu_malloc_cold_0_acode {{?Q;?M}}\<close>
by (vcg acode: qemu_malloc_cold_0_acode_def assms: assms)
end
locale "qemu_malloc" = "qemu_img_xen" +
fixes RAX\<^sub>0\<^sub>v RSP\<^sub>0\<^sub>v ret_address\<^sub>v :: \<open>64 word\<close>
begin
text \<open>Using definitions that don't get unfolded immediately prevents locale argument issues.\<close>
definition \<open>RAX\<^sub>0 \<equiv> RAX\<^sub>0\<^sub>v\<close>
definition \<open>RSP\<^sub>0 \<equiv> RSP\<^sub>0\<^sub>v\<close>
definition \<open>ret_address \<equiv> ret_address\<^sub>v\<close>
definition P_0x5970_0 :: state_pred where
\<open>P_0x5970_0 \<sigma> \<equiv> RIP \<sigma> = 0x5970 \<and> RAX \<sigma> = RAX\<^sub>0 \<and> RSP \<sigma> = RSP\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address\<close>
declare P_0x5970_0_def[Ps]
definition P_0x5970_0_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x5970_0_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8)
}\<close>
definition P_0x5970_0_regions :: state_pred where
\<open>P_0x5970_0_regions \<sigma> \<equiv> \<exists>regions. P_0x5970_0_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_0x5974_0 :: state_pred where
\<open>Q_0x5974_0 \<sigma> \<equiv> RIP \<sigma> = 0x5974 \<and> RAX \<sigma> = RAX\<^sub>0 \<and> RSP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address\<close>
declare Q_0x5974_0_def[Qs]
schematic_goal qemu_malloc_0_1_0x5970_0x5970_0[blocks]:
assumes \<open>(P_0x5970_0 && P_0x5970_0_regions) \<sigma>\<close>
shows \<open>exec_block (Suc 0) 0x5970 0 \<sigma> \<triangleq> ?\<sigma> \<and> Q_0x5974_0 ?\<sigma> \<and> block_usage P_0x5970_0_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x5970_0_def P_0x5970_0_regions_def post: Q_0x5974_0_def regionset: P_0x5970_0_regions_set_def)
definition P_0x5974_1 :: state_pred where
\<open>P_0x5974_1 \<sigma> \<equiv> RIP \<sigma> = 0x5974 \<and> RAX \<sigma> = RAX\<^sub>0 \<and> RSP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address\<close>
declare P_0x5974_1_def[Ps]
definition P_0x5974_1_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x5974_1_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((RSP\<^sub>0::64 word) - 0x10), 8)
}\<close>
definition P_0x5974_1_regions :: state_pred where
\<open>P_0x5974_1_regions \<sigma> \<equiv> \<exists>regions. P_0x5974_1_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_malloc_addr_0x5974_1 :: state_pred where
\<open>Q_malloc_addr_0x5974_1 \<sigma> \<equiv> RSP \<sigma> = ((RSP\<^sub>0::64 word) - 0x10) \<and> RIP \<sigma> = malloc_addr \<and> RAX \<sigma> = RAX\<^sub>0 \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = 0x5979\<close>
declare Q_malloc_addr_0x5974_1_def[Qs]
schematic_goal qemu_malloc_0_1_0x5974_0x5974_1[blocks]:
assumes \<open>(P_0x5974_1 && P_0x5974_1_regions) \<sigma>\<close>
shows \<open>exec_block (Suc 0) 0x5974 (Suc 0) \<sigma> \<triangleq> ?\<sigma> \<and> Q_malloc_addr_0x5974_1 ?\<sigma> \<and> block_usage P_0x5974_1_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x5974_1_def P_0x5974_1_regions_def post: Q_malloc_addr_0x5974_1_def regionset: P_0x5974_1_regions_set_def)
definition P_0x5979_2 :: state_pred where
\<open>P_0x5979_2 \<sigma> \<equiv> RIP \<sigma> = 0x5979 \<and> RAX \<sigma> = malloc_0x5974_retval \<and> RSP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = 0x5979\<close>
declare P_0x5979_2_def[Ps]
definition P_0x5979_2_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x5979_2_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((RSP\<^sub>0::64 word) - 0x10), 8)
}\<close>
definition P_0x5979_2_regions :: state_pred where
\<open>P_0x5979_2_regions \<sigma> \<equiv> \<exists>regions. P_0x5979_2_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_0x597c_2 :: state_pred where
\<open>Q_0x597c_2 \<sigma> \<equiv> RIP \<sigma> = 0x597c \<and> RAX \<sigma> = malloc_0x5974_retval \<and> RSP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = 0x5979\<close>
declare Q_0x597c_2_def[Qs]
schematic_goal qemu_malloc_0_1_0x5979_0x5979_2[blocks]:
assumes \<open>(P_0x5979_2 && P_0x5979_2_regions) \<sigma>\<close>
shows \<open>exec_block (Suc 0) 0x5979 2 \<sigma> \<triangleq> ?\<sigma> \<and> Q_0x597c_2 ?\<sigma> \<and> block_usage P_0x5979_2_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x5979_2_def P_0x5979_2_regions_def post: Q_0x597c_2_def regionset: P_0x5979_2_regions_set_def)
definition P_0x597c_true_3 :: state_pred where
\<open>P_0x597c_true_3 \<sigma> \<equiv> RIP \<sigma> = 0x597c \<and> RAX \<sigma> = malloc_0x5974_retval \<and> RSP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = 0x5979\<close>
declare P_0x597c_true_3_def[Ps]
definition P_0x597c_true_3_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x597c_true_3_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((RSP\<^sub>0::64 word) - 0x10), 8)
}\<close>
definition P_0x597c_true_3_regions :: state_pred where
\<open>P_0x597c_true_3_regions \<sigma> \<equiv> \<exists>regions. P_0x597c_true_3_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_0x3710_3 :: state_pred where
\<open>Q_0x3710_3 \<sigma> \<equiv> RIP \<sigma> = 0x3710 \<and> RAX \<sigma> = malloc_0x5974_retval \<and> RSP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = 0x5979\<close>
declare Q_0x3710_3_def[Qs]
schematic_goal qemu_malloc_0_1_0x597c_0x597c_3[blocks]:
assumes \<open>(P_0x597c_true_3 && P_0x597c_true_3_regions && ZF) \<sigma>\<close>
shows \<open>exec_block (Suc 0) 0x597c 3 \<sigma> \<triangleq> ?\<sigma> \<and> Q_0x3710_3 ?\<sigma> \<and> block_usage P_0x597c_true_3_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x597c_true_3_def P_0x597c_true_3_regions_def post: Q_0x3710_3_def regionset: P_0x597c_true_3_regions_set_def)
definition P_0x3710_4 :: state_pred where
\<open>P_0x3710_4 \<sigma> \<equiv> RIP \<sigma> = 0x3710 \<and> RAX \<sigma> = malloc_0x5974_retval \<and> RSP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = 0x5979\<close>
declare P_0x3710_4_def[Ps]
definition P_0x3710_4_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x3710_4_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((RSP\<^sub>0::64 word) - 0x10), 8)
}\<close>
definition P_0x3710_4_regions :: state_pred where
\<open>P_0x3710_4_regions \<sigma> \<equiv> \<exists>regions. P_0x3710_4_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_abort_addr_0x3710_4 :: state_pred where
\<open>Q_abort_addr_0x3710_4 \<sigma> \<equiv> RSP \<sigma> = ((RSP\<^sub>0::64 word) - 0x10) \<and> RIP \<sigma> = abort_addr \<and> RAX \<sigma> = malloc_0x5974_retval \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address\<close>
declare Q_abort_addr_0x3710_4_def[Qs]
schematic_goal qemu_malloc_0_1_0x3710_0x3710_4[blocks]:
assumes \<open>(P_0x3710_4 && P_0x3710_4_regions) \<sigma>\<close>
shows \<open>exec_block (Suc 0) 0x3710 4 \<sigma> \<triangleq> ?\<sigma> \<and> Q_abort_addr_0x3710_4 ?\<sigma> \<and> block_usage P_0x3710_4_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x3710_4_def P_0x3710_4_regions_def post: Q_abort_addr_0x3710_4_def regionset: P_0x3710_4_regions_set_def)
definition P_0x597c_false_5 :: state_pred where
\<open>P_0x597c_false_5 \<sigma> \<equiv> RIP \<sigma> = 0x597c \<and> RAX \<sigma> = malloc_0x5974_retval \<and> RSP \<sigma> = ((RSP\<^sub>0::64 word) - 0x8) \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address \<and> (\<sigma> \<turnstile> *[((RSP\<^sub>0::64 word) - 0x10),8]::64 word) = 0x5979\<close>
declare P_0x597c_false_5_def[Ps]
definition P_0x597c_false_5_regions_set :: \<open>state \<Rightarrow> (nat \<times> 64 word \<times> nat) set\<close> where
\<open>P_0x597c_false_5_regions_set \<sigma> \<equiv> {
(0, RSP\<^sub>0, 8),
(1, ((RSP\<^sub>0::64 word) - 0x10), 8)
}\<close>
definition P_0x597c_false_5_regions :: state_pred where
\<open>P_0x597c_false_5_regions \<sigma> \<equiv> \<exists>regions. P_0x597c_false_5_regions_set \<sigma> \<subseteq> regions
\<and> (\<forall>i r. (i, r) \<in> regions \<longrightarrow> no_block_overflow r)
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<sqsubseteq> r' = (i = i' \<or> (i, i') \<in> {}))
\<and> (\<forall>i r i' r'. (i, r) \<in> regions \<longrightarrow> (i', r') \<in> regions \<longrightarrow> r \<bowtie> r' = (i \<noteq> i' \<and> (i, i') \<notin> {}))
\<close>
definition Q_ret_address_5 :: state_pred where
\<open>Q_ret_address_5 \<sigma> \<equiv> RIP \<sigma> = ret_address \<and> (\<sigma> \<turnstile> *[RSP\<^sub>0,8]::64 word) = ret_address\<close>
declare Q_ret_address_5_def[Qs]
schematic_goal qemu_malloc_0_3_0x597c_0x5986_5[blocks]:
assumes \<open>(P_0x597c_false_5 && P_0x597c_false_5_regions && ! ZF) \<sigma>\<close>
shows \<open>exec_block 3 0x5986 5 \<sigma> \<triangleq> ?\<sigma> \<and> Q_ret_address_5 ?\<sigma> \<and> block_usage P_0x597c_false_5_regions_set \<sigma> ?\<sigma>\<close>
using assms
by (steps pre: P_0x597c_false_5_def P_0x597c_false_5_regions_def post: Q_ret_address_5_def regionset: P_0x597c_false_5_regions_set_def)
definition qemu_malloc_acode :: ACode where
\<open>qemu_malloc_acode =
Block (Suc 0) 0x5970 0;
Block (Suc 0) 0x5974 (Suc 0);
CALL malloc_acode;
Block (Suc 0) 0x5979 2;
IF ZF THEN
Block (Suc 0) 0x597c 3;
Block (Suc 0) 0x3710 4;
CALL abort_acode
ELSE
Block 3 0x5986 5
FI
\<close>
schematic_goal "qemu_malloc":
assumes
\<open>\<forall>\<sigma>. RIP \<sigma> = 0x5974 \<longrightarrow> P_0x5974_1_regions \<sigma>\<close>
and \<open>\<forall>\<sigma>. RIP \<sigma> = 0x5979 \<longrightarrow> P_0x5979_2_regions \<sigma>\<close>
and \<open>\<forall>\<sigma>. RIP \<sigma> = 0x597c \<longrightarrow> P_0x597c_true_3_regions \<sigma>\<close>
and \<open>\<forall>\<sigma>. RIP \<sigma> = 0x3710 \<longrightarrow> P_0x3710_4_regions \<sigma>\<close>
and \<open>\<forall>\<sigma>. RIP \<sigma> = 0x597c \<longrightarrow> P_0x597c_false_5_regions \<sigma>\<close>
and [blocks]: \<open>{{Q_malloc_addr_0x5974_1}} \<box>malloc_acode {{P_0x5979_2;M_0x5974}}\<close>
and [blocks]: \<open>{{Q_abort_addr_0x3710_4}} \<box>abort_acode {{Q_fail;M_0x3710}}\<close>
shows \<open>{{?P}} qemu_malloc_acode {{?Q;?M}}\<close>
by (vcg acode: qemu_malloc_acode_def assms: assms)
end
|
(*
* Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
*
* SPDX-License-Identifier: BSD-2-Clause
*)
theory global_array_update imports "AutoCorres.AutoCorres" begin
external_file "global_array_update.c"
install_C_file "global_array_update.c"
autocorres "global_array_update.c"
context global_array_update begin
thm bar'_def bar2'_def
lemma "\<lbrace> \<lambda>s. \<forall>a\<in>set (array_addrs (Ptr (symbol_table ''foo'')
:: 32 signed word ptr) 1024).
is_valid_w32 s (ptr_coerce a) \<rbrace>
bar'
\<lbrace> \<lambda>_ s. heap_w32 s (ptr_coerce (Ptr (symbol_table ''foo'') +\<^sub>p 3
:: 32 signed word ptr)) = 42 \<rbrace>!"
unfolding bar'_def
apply wp
apply (clarsimp simp: set_array_addrs fun_upd_apply)
done
end
end
|
/- Copyright (c) 2022 Sina Hazratpour. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
----------------
# Cats: Universal Properties
😺 🐈 😼 🐈⬛ 😸 🐈 🙀 😻 🐈 😹
Sina Hazratpour
Introduction to Proof
MATH 301, Johns Hopkins University, Fall 2022
-/
/-
The most important concept in category theory is that of __universal property__. We already have seen an example of univeral property in construction of fake integers from fake natural numbers by __quotient__ in lecture 15. The quotient construction in the category of types. We will generalize the quotient construction to any category.
The further you go in mathematics, especially pure mathematics, the more universal properties you will meet. We will spend most of our time studying different manifestations of this concept.
-/
-- import tactic.basic
import ..prooflab
import lectures.lec16_categories_basic
open PROOFS.STR
/-! # Terminal Object
-/
/-
Product
-/
#check prod
|
####script file found in /nas40t2/hwheeler/PrediXcan_CV/GTEx_2014-06013_release/
####by Heather E. Wheeler 20140602####
args <- commandArgs(trailingOnly=T)
date <- Sys.Date()
"%&%" = function(a,b) paste(a,b,sep="")
###############################################
### Directories & Variables
cri = T #on cri cluster?
if(cri) precri = "/group/dolan-lab/hwheeler/" else precri = '/'
tis <- "GTEx-NT"
k <- 10 ### k-fold CV
n <- 10 #number of k-fold CV replicates
my.dir <- precri %&% "nas40t2/hwheeler/PrediXcan_CV/GTEx_2014-06013_release/"
poly.dir <- precri %&% "nas40t2/hwheeler/PrediXcan_CV/Polyscore/hapmap2/transcriptome-" %&% tis %&% "/"
gencodefile <- my.dir %&% "gencode.v18.genes.patched_contigs.summary.protein." %&% args[1]
gencodeset <- args[1]
################################################
### Functions & Libraries
library(glmnet)
stderr <- function(x) sqrt(var(x,na.rm=TRUE)/length(x))
lower <- function(x) quantile(x,0.025,na.rm=TRUE)
upper <- function(x) quantile(x,0.975,na.rm=TRUE)
## fit betas by Vasa edited by Heather to get pvals
fit.betas <- function(G, Y) {
require(RcppGSL)
betas <- rep(NA, ncol(G))
stderrs <- rep(NA, ncol(G))
dfs <- rep(NA, ncol(G))
for (i in 1:ncol(G)) {
res <- fastLmPure(y=Y, X=matrix(G[,i]))
betas[i] <- res$coefficients
stderrs[i] <- res$stderr
dfs[i] <- res$df
}
t <- betas/stderrs
pvals <- 2*pt(-abs(t),df=dfs)
output <- cbind(betas,pvals)
return(output)
}
################################################
###input adjusted expression data###
expidfile <- my.dir %&% tis %&% ".exp.adj.15PEERfactors.3PCs.gender.ID.list"
expgenefile <- my.dir %&% tis %&% ".exp.adj.15PEERfactors.3PCs.gender.GENE.list"
expfile <- my.dir %&% tis %&% ".exp.adj.15PEERfactors.3PCs.gender.IDxGENE"
expidlist <- scan(expidfile,"character")
expgenelist <- scan(expgenefile,"character")
exp <- scan(expfile)
expdata <- matrix(exp, ncol=length(expgenelist), byrow=T)
rownames(expdata) <- expidlist
colnames(expdata) <- expgenelist
#gencodefile <- my.dir %&% "gencode.v18.genes.patched_contigs.summary.protein"
gencode <- read.table(gencodefile) ##split into 10 files, call each from run_1_CV_GTEx_polyscore_PrediXcan_subset*.sh
rownames(gencode) <- gencode[,5]
tissue.exp <- expdata[,intersect(colnames(expdata),rownames(gencode))] ###pull protein coding gene expression data
###input genotype data###
gtfile <- my.dir %&% "GTEx.IDxSNP.rds"
X <- readRDS(gtfile)
X <- X[expidlist,]
samplelist<-expidlist
bimfile <- my.dir %&% "GTEx_Analysis_2014-06-13.hapmapSnpsCEU.bim"
bim <- read.table(bimfile)
rownames(bim) <- bim$V2
exp.w.geno <- tissue.exp
explist <- colnames(exp.w.geno)
###create results array
resultsarray <- array(NA,c(n,6,length(explist)))
dimnames(resultsarray)[[3]] <- explist
finalresults <- matrix(NA,nrow=length(explist),ncol=7)
rownames(finalresults) <- explist
colnames(finalresults) <- c("gene","R2.mean","R2.se","R2.lci","R2.uci","mean.n.snps","P.mean")
###run polyscore CV
set.seed(1001)
for(j in 1:length(explist)){
cat(j,"/",length(explist),"\n")
gene <- explist[j]
genename <- as.character(gencode[gene,6])
geneinfo <- gencode[gene,]
chr <- geneinfo[1]
c <- substr(chr$V1,4,5)
start <- geneinfo$V3 - 1e6 ### 1Mb lower bound for cis-eQTLS
end <- geneinfo$V4 + 1e6 ### 1Mb upper bound for cis-eQTLs
chrsnps <- subset(bim,bim[,1]==c) ### pull snps on same chr
cissnps <- subset(chrsnps,chrsnps[,4]>=start & chrsnps[,4]<=end) ### pull cis-SNP info
cisgenos <- X[,intersect(colnames(X),cissnps[,2])] ### pull cis-SNP genotypes
cisgenos[cisgenos >= 3] <- NA ###.gds files have missing=3
if(is.null(dim(cisgenos))){###effectively skips genes with <2 cis-SNPs
finalresults[gene,1] <- genename
finalresults[gene,2:6] <- rep(NA,5)
}else{
minorsnps <- subset(colMeans(cisgenos), colMeans(cisgenos,na.rm=TRUE)>0) ###pull snps with at least 1 minor allele###
minorsnps <- names(minorsnps)
cisgenos <- cisgenos[,minorsnps]
cisgenos <- scale(cisgenos, center=T, scale=T) ##need to scale for fastLmPure to work properly
cisgenos[is.na(cisgenos)] <- 0
if(is.null(dim(cisgenos)) | dim(cisgenos)[2] == 0){###effectively skips genes with <2 cis-SNPs after removing those with no minor alleles
finalresults[gene,1] <- genename
finalresults[gene,2:6] <- rep(NA,5)
}else{
exppheno <- exp.w.geno[,gene] ### pull expression data for gene
exppheno <- scale(exppheno, center=T, scale=T)
exppheno[is.na(exppheno)] <- 0
rownames(exppheno) <- rownames(exp.w.geno)
### run k-fold CV n times
for(i in 1:n){
###randomize samples into CV groups
samplelength <- length(exppheno)
g <- 1:k ##k-fold CV
groupid <- sample(g,samplelength,replace=T)
newiddata <- data.frame(groupid,samplelist)
### create empty matrix to fill in with polyscore vals
cvset <- data.frame(samplelist,matrix(NA,samplelength,1),exppheno)
rownames(cvset) <- samplelist
names(cvset) <- c("ID","Pred","Exp")
for(idsubset in 1:k){
trainset <- data.frame(newiddata$samplelist[newiddata$groupid != idsubset])
testset <- data.frame(newiddata$samplelist[newiddata$groupid == idsubset])
### pull trainset genos and phenos
traingenos <- cisgenos[intersect(trainset[,1],rownames(cisgenos)),]
trainexp <- exppheno[match(trainset[,1],rownames(exppheno))] ###if scaled, use rownames
### calculate betas and pvals from training set
betares <- fit.betas(traingenos,trainexp) ###~30sec/gene
rownames(betares) <- colnames(traingenos)
topres <- subset(betares,betares[,2] < 0.05) ###pull snps with P<0.05
betas <- topres[,1]
if(length(betas) <= 1){
names(betas) <- rownames(topres)
}
### polyscore
### multiply betas by test genotypes and take sum
testgenos <- cisgenos[intersect(testset[,1],rownames(cisgenos)),intersect(names(betas),colnames(cisgenos))]
if(is.array(testgenos)=='FALSE'){ ### calcs polyscore if only one individual in test set, happens when expression sample size is low (<100)
if(dim(testset)[1] < 2){ ### calcs polyscore if only one individual in test set, happens when expression sample size is low (<100)
pred.polyscore <- sum(testgenos * betas)
names(pred.polyscore)<-testset[,1]
}else{ ### calcs polyscore if only one beta with p<0.05
pred.polyscore <- testgenos * betas
}
cvset$Pred[match(names(pred.polyscore),rownames(cvset))] <- pred.polyscore
}else{
testsweep <- sweep(testgenos, 2, betas, "*")
pred.polyscore <- as.vector(rowSums(testsweep))
names(pred.polyscore) <- rownames(testsweep)
### add predictions to cvset
cvset$Pred[match(names(pred.polyscore),rownames(cvset))] <- pred.polyscore
}
}
### calculate correlation between predicted and observed expression
res<-summary(lm(cvset$Pred~cvset$Exp))
resultsarray[i,1:4,gene] <- coef(res)[2,]
resultsarray[i,5,gene] <- res$r.squared
resultsarray[i,6,gene] <- length(betas)
}
finalresults[gene,1] <- genename
finalresults[gene,2] <- mean(resultsarray[,5,gene],na.rm=TRUE)
finalresults[gene,3] <- stderr(resultsarray[,5,gene])
finalresults[gene,4] <- lower(resultsarray[,5,gene])
finalresults[gene,5] <- upper(resultsarray[,5,gene])
finalresults[gene,6] <- as.integer(mean(resultsarray[,6,gene],na.rm=TRUE))
finalresults[gene,7] <- mean(resultsarray[,4,gene],na.rm=TRUE)
### output bestbetas for PrediXcan
allbetares <- fit.betas(cisgenos,exppheno) ###~30sec/gene
rownames(allbetares) <- colnames(cisgenos)
alltopres <- subset(allbetares,allbetares[,2] < 0.05) ###pull snps with P<0.05
allbetas <- alltopres[,1]
if(length(allbetas) <= 1){
names(allbetas) <- rownames(alltopres)
}
allbetalist <- names(allbetas)
allbetainfo <- bim[allbetalist,]
allbetatable <- as.matrix(cbind(allbetainfo,alltopres))
betafile <- cbind(allbetatable[,2],allbetatable[,6],allbetatable[,7],allbetatable[,8])
colnames(betafile) <- c("SNP","eff.allele","beta","p.value")
write.table(betafile, file=poly.dir %&% genename %&% "-" %&% tis %&% ".txt",quote=F,row.names=F,sep="\t")
}
}
}
date <- Sys.Date()
write.table(finalresults,file=tis %&% ".adj.exp." %&% k %&% "-fold.CV." %&% n %&% "-reps.polyscore.p0.05.PrediXcan.subset." %&% gencodeset %&% "." %&% date %&% ".txt",quote=F)
|
{-# OPTIONS --sized-types #-}
open import Relation.Binary.Core
module Mergesort.Impl1.Correctness.Order {A : Set}
(_≤_ : A → A → Set)
(tot≤ : Total _≤_) where
open import Data.List
open import Function using (_∘_)
open import List.Sorted _≤_
open import Mergesort.Impl1 _≤_ tot≤
open import SList
open import SOList.Lower _≤_
open import SOList.Lower.Properties _≤_
theorem-mergesort-sorted : (xs : List A) → Sorted (forget (mergesort (size A xs)))
theorem-mergesort-sorted = lemma-solist-sorted ∘ mergesort ∘ (size A)
|
[STATEMENT]
lemma hcomplex_mult_minus_one: "- 1 * z = - z"
for z :: hcomplex
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. - 1 * z = - z
[PROOF STEP]
by simp |
lemma homeomorphic_empty [iff]: "S homeomorphic {} \<longleftrightarrow> S = {}" "{} homeomorphic S \<longleftrightarrow> S = {}" |
\chapter{Conclusion \label{chap:Conclusion}}
This is some concluding text |
Require Import EquivDec Equivalence List Program.
Require Import Relation_Definitions.
Import ListNotations.
Generalizable All Variables.
Fixpoint removeV `{eqDecV : @EqDec V eqV equivV}`(x : V) (l : list V) : list V
:=
match l with
| nil => nil
| y::tl => if (equiv_dec x y) then removeV x tl else y::(removeV x tl)
end.
Lemma remove_le {V:Type}{eqV:relation V}{equivV:@Equivalence V eqV}{eqDecV :
@EqDec V eqV equivV} (xs : list V) (x : V) :
length (removeV x xs) < length (x :: xs).
Proof. Admitted.
(* Function version *)
Set Printing Universes.
Require Import Recdef.
Function nubV {V:Type}{eqV:relation V}{equivV:@Equivalence V eqV}{eqDecV :
@EqDec V eqV equivV} (l : list V) { measure length l} :=
match l with
| nil => nil
| x::xs => x :: @nubV V eqV equivV eqDecV (removeV x xs)
end.
Proof. intros. apply remove_le. Qed.
(* Program version *)
Program Fixpoint nubV `{eqDecV : @EqDec V eqV equivV} (l : list V)
{ measure (@length V l) lt } :=
match l with
| nil => nil
| x::xs => x :: @nubV V eqV equivV eqDecV (removeV x xs) _
end.
|
data ⊥ : Set where
data Bool : Set where
false true : Bool
data _≡_ (x : Bool) : Bool → Set where
refl : x ≡ x
true≠false : false ≡ true → ⊥
true≠false ()
data Maybe (A : Set) : Set where
nothing : Maybe A
just : A → Maybe A
data Eq {A : Set} (_≈_ : A → A → Set) : Maybe A → Maybe A → Set where
just : ∀ {x y} (x≈y : x ≈ y) → Eq _≈_ (just x) (just y)
nothing : Eq _≈_ nothing nothing
drop-just : ∀ {A : Set} {_≈_ : A → A → Set} {x y : A} →
Eq _≈_ (just x) (just y) → x ≈ y
drop-just (just x≈y) = x≈y
|
import data.padics.padic_norm data.nat.binomial
universes u v
theorem inv_pow' {α : Type u} [discrete_field α] {x : α} {n : ℕ} : (x⁻¹)^n = (x^n)⁻¹ :=
decidable.by_cases
(assume H : x = 0, or.cases_on (nat.eq_zero_or_pos n)
(λ hn, by rw [H, hn, pow_zero, pow_zero, inv_one])
(λ hn, by rw [H, zero_pow hn, inv_zero, zero_pow hn]))
(λ H, division_ring.inv_pow H n)
theorem pow_eq_zero {α : Type u} [domain α] {x : α} {n : ℕ} (H : x^n = 0) : x = 0 :=
begin
induction n with n ih,
{ rw pow_zero at H,
rw [← mul_one x, H, mul_zero] },
exact or.cases_on (mul_eq_zero.1 H) id ih
end
class char_p (α : Type u) [semiring α] (p : ℕ) : Prop :=
(cast_eq_zero_iff : ∀ x:ℕ, (x:α) = 0 ↔ p ∣ x)
theorem char_p.cast_eq_zero (α : Type u) [semiring α] (p : ℕ) [char_p α p] : (p:α) = 0 :=
(char_p.cast_eq_zero_iff α p p).2 (dvd_refl p)
theorem char_p.eq (α : Type u) [semiring α] {p q : ℕ} (c1 : char_p α p) (c2 : char_p α q) : p = q :=
nat.dvd_antisymm
((char_p.cast_eq_zero_iff α p q).1 (char_p.cast_eq_zero _ _))
((char_p.cast_eq_zero_iff α q p).1 (char_p.cast_eq_zero _ _))
instance char_p.of_char_zero (α : Type u) [semiring α] [char_zero α] : char_p α 0 :=
⟨λ x, by rw [zero_dvd_iff, ← nat.cast_zero, nat.cast_inj]⟩
theorem char_p.exists (α : Type u) [semiring α] : ∃ p, char_p α p :=
by letI := classical.dec_eq α; exact
classical.by_cases
(assume H : ∀ p:ℕ, (p:α) = 0 → p = 0, ⟨0,
⟨λ x, by rw [zero_dvd_iff]; exact ⟨H x, by rintro rfl; refl⟩⟩⟩)
(λ H, ⟨nat.find (classical.not_forall.1 H), ⟨λ x,
⟨λ H1, nat.dvd_of_mod_eq_zero (by_contradiction $ λ H2,
nat.find_min (classical.not_forall.1 H)
(nat.mod_lt x $ nat.pos_of_ne_zero $ not_of_not_imp $
nat.find_spec (classical.not_forall.1 H))
(not_imp_of_and_not ⟨by rwa [← nat.mod_add_div x (nat.find (classical.not_forall.1 H)),
nat.cast_add, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)),
zero_mul, add_zero] at H1, H2⟩)),
λ H1, by rw [← nat.mul_div_cancel' H1, nat.cast_mul,
of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)), zero_mul]⟩⟩⟩)
theorem char_p.exists_unique (α : Type u) [semiring α] : ∃! p, char_p α p :=
let ⟨c, H⟩ := char_p.exists α in ⟨c, H, λ y H2, char_p.eq α H2 H⟩
noncomputable def ring_char (α : Type u) [semiring α] : ℕ :=
classical.some (char_p.exists_unique α)
theorem ring_char.spec (α : Type u) [semiring α] : ∀ x:ℕ, (x:α) = 0 ↔ ring_char α ∣ x :=
by letI := (classical.some_spec (char_p.exists_unique α)).1;
unfold ring_char; exact char_p.cast_eq_zero_iff α (ring_char α)
theorem ring_char.eq (α : Type u) [semiring α] {p : ℕ} (C : char_p α p) : p = ring_char α :=
(classical.some_spec (char_p.exists_unique α)).2 p C
theorem add_pow_char (α : Type u) [comm_ring α] {p : ℕ} (hp : nat.prime p)
[char_p α p] (x y : α) : (x + y)^p = x^p + y^p :=
begin
rw [add_pow, finset.sum_range_succ, nat.sub_self, pow_zero, choose_self],
rw [nat.cast_one, mul_one, mul_one, add_left_inj],
transitivity,
{ refine finset.sum_eq_single 0 _ _,
{ intros b h1 h2,
have := nat.prime.dvd_choose (nat.pos_of_ne_zero h2) (finset.mem_range.1 h1) hp,
rw [← nat.div_mul_cancel this, nat.cast_mul, char_p.cast_eq_zero α p],
simp only [mul_zero] },
{ intro H, exfalso, apply H, exact finset.mem_range.2 hp.pos } },
rw [pow_zero, nat.sub_zero, one_mul, choose_zero_right, nat.cast_one, mul_one]
end
theorem nat.iterate₀ {α : Type u} {op : α → α} {x : α} (H : op x = x) {n : ℕ} :
op^[n] x = x :=
by induction n; [simp only [nat.iterate_zero], simp only [nat.iterate_succ', H, *]]
theorem nat.iterate₁ {α : Type u} {β : Type v} {op : α → α} {op' : β → β} {op'' : α → β}
(H : ∀ x, op' (op'' x) = op'' (op x)) {n : ℕ} {x : α} :
op'^[n] (op'' x) = op'' (op^[n] x) :=
by induction n; [simp only [nat.iterate_zero], simp only [nat.iterate_succ', H, *]]
theorem nat.iterate₂ {α : Type u} {op : α → α} {op' : α → α → α} (H : ∀ x y, op (op' x y) = op' (op x) (op y)) {n : ℕ} {x y : α} :
op^[n] (op' x y) = op' (op^[n] x) (op^[n] y) :=
by induction n; [simp only [nat.iterate_zero], simp only [nat.iterate_succ', H, *]]
theorem nat.iterate_cancel {α : Type u} {op op' : α → α} (H : ∀ x, op (op' x) = x) {n : ℕ} {x : α} : op^[n] (op'^[n] x) = x :=
by induction n; [refl, rwa [nat.iterate_succ, nat.iterate_succ', H]]
theorem nat.iterate_inj {α : Type u} {op : α → α} (Hinj : function.injective op) (n : ℕ) (x y : α)
(H : (op^[n] x) = (op^[n] y)) : x = y :=
by induction n with n ih; simp only [nat.iterate_zero, nat.iterate_succ'] at H;
[exact H, exact ih (Hinj H)]
def frobenius (α : Type u) [monoid α] (p : ℕ) (x : α) : α := x^p
theorem frobenius_def (α : Type u) [monoid α] (p : ℕ) (x : α) : frobenius α p x = x ^ p := rfl
theorem frobenius_mul (α : Type u) [comm_monoid α] (p : ℕ) (x y : α) :
frobenius α p (x * y) = frobenius α p x * frobenius α p y := mul_pow x y p
theorem frobenius_one (α : Type u) [monoid α] (p : ℕ) :
frobenius α p 1 = 1 := one_pow _
theorem is_monoid_hom.map_frobenius {α : Type u} {β : Type v} [monoid α] [monoid β] (f : α → β) [is_monoid_hom f]
(p : ℕ) (x : α) : f (frobenius α p x) = frobenius β p (f x) :=
by unfold frobenius; induction p; simp only [pow_zero, pow_succ,
is_monoid_hom.map_one f, is_monoid_hom.map_mul f, *]
instance {α : Type u} [comm_ring α] (p : ℕ) [hp : nat.prime p] [char_p α p] : is_ring_hom (frobenius α p) :=
{ map_one := frobenius_one α p,
map_mul := frobenius_mul α p,
map_add := add_pow_char α hp }
section
variables (α : Type u) [comm_ring α] (p : ℕ) [hp : nat.prime p]
theorem frobenius_zero : frobenius α p 0 = 0 := zero_pow hp.pos
variables [char_p α p] (x y : α)
include hp
theorem frobenius_add : frobenius α p (x + y) = frobenius α p x + frobenius α p y := is_ring_hom.map_add _
theorem frobenius_neg : frobenius α p (-x) = -frobenius α p x := is_ring_hom.map_neg _
theorem frobenius_sub : frobenius α p (x - y) = frobenius α p x - frobenius α p y := is_ring_hom.map_sub _
end
theorem frobenius_inj (α : Type u) [integral_domain α] (p : ℕ) [nat.prime p] [char_p α p] (x y : α)
(H : frobenius α p x = frobenius α p y) : x = y :=
by rw ← sub_eq_zero at H ⊢; rw ← frobenius_sub at H; exact pow_eq_zero H
theorem frobenius_nat_cast (α : Type u) [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (x : ℕ) :
frobenius α p x = x :=
by induction x; simp only [nat.cast_zero, nat.cast_succ, frobenius_zero, frobenius_one, frobenius_add, *]
class perfect_field (α : Type u) [field α] (p : ℕ) [char_p α p] : Type u :=
(pth_root : α → α)
(frobenius_pth_root : ∀ x, frobenius α p (pth_root x) = x)
theorem frobenius_pth_root (α : Type u) [field α] (p : ℕ) [char_p α p] [perfect_field α p] (x : α) :
frobenius α p (perfect_field.pth_root p x) = x :=
perfect_field.frobenius_pth_root p x
theorem pth_root_frobenius (α : Type u) [field α] (p : ℕ) [nat.prime p] [char_p α p] [perfect_field α p] (x : α) :
perfect_field.pth_root p (frobenius α p x) = x :=
frobenius_inj α p _ _ (by rw frobenius_pth_root)
instance pth_root.is_ring_hom (α : Type u) [field α] (p : ℕ) [nat.prime p] [char_p α p] [perfect_field α p] :
is_ring_hom (@perfect_field.pth_root α _ p _ _) :=
{ map_one := frobenius_inj α p _ _ (by rw [frobenius_pth_root, frobenius_one]),
map_mul := λ x y, frobenius_inj α p _ _ (by simp only [frobenius_pth_root, frobenius_mul]),
map_add := λ x y, frobenius_inj α p _ _ (by simp only [frobenius_pth_root, frobenius_add]) }
theorem is_ring_hom.pth_root {α : Type u} [field α] (p : ℕ) [nat.prime p] [char_p α p] [perfect_field α p]
{β : Type v} [field β] [char_p β p] [perfect_field β p] (f : α → β) [is_ring_hom f] {x : α} :
f (perfect_field.pth_root p x) = perfect_field.pth_root p (f x) :=
frobenius_inj β p _ _ (by rw [← is_monoid_hom.map_frobenius f, frobenius_pth_root, frobenius_pth_root])
inductive perfect_closure.r (α : Type u) [monoid α] (p : ℕ) : (ℕ × α) → (ℕ × α) → Prop
| intro : ∀ n x, perfect_closure.r (n, x) (n+1, frobenius α p x)
run_cmd tactic.mk_iff_of_inductive_prop `perfect_closure.r `perfect_closure.r_iff
def perfect_closure (α : Type u) [monoid α] (p : ℕ) : Type u :=
quot (perfect_closure.r α p)
namespace perfect_closure
variables (α : Type u)
private lemma mul_aux_left [comm_monoid α] (p : ℕ) (x1 x2 y : ℕ × α) (H : r α p x1 x2) :
quot.mk (r α p) (x1.1 + y.1, ((frobenius α p)^[y.1] x1.2) * ((frobenius α p)^[x1.1] y.2)) =
quot.mk (r α p) (x2.1 + y.1, ((frobenius α p)^[y.1] x2.2) * ((frobenius α p)^[x2.1] y.2)) :=
match x1, x2, H with
| _, _, r.intro _ n x := quot.sound $ by rw [← nat.iterate_succ, nat.iterate_succ',
nat.iterate_succ', ← frobenius_mul, nat.succ_add]; apply r.intro
end
private lemma mul_aux_right [comm_monoid α] (p : ℕ) (x y1 y2 : ℕ × α) (H : r α p y1 y2) :
quot.mk (r α p) (x.1 + y1.1, ((frobenius α p)^[y1.1] x.2) * ((frobenius α p)^[x.1] y1.2)) =
quot.mk (r α p) (x.1 + y2.1, ((frobenius α p)^[y2.1] x.2) * ((frobenius α p)^[x.1] y2.2)) :=
match y1, y2, H with
| _, _, r.intro _ n y := quot.sound $ by rw [← nat.iterate_succ, nat.iterate_succ',
nat.iterate_succ', ← frobenius_mul]; apply r.intro
end
instance [comm_monoid α] (p : ℕ) : has_mul (perfect_closure α p) :=
⟨quot.lift (λ x:ℕ×α, quot.lift (λ y:ℕ×α, quot.mk (r α p)
(x.1 + y.1, ((frobenius α p)^[y.1] x.2) * ((frobenius α p)^[x.1] y.2))) (mul_aux_right α p x))
(λ x1 x2 (H : r α p x1 x2), funext $ λ e, quot.induction_on e $ λ y,
mul_aux_left α p x1 x2 y H)⟩
instance [comm_monoid α] (p : ℕ) : comm_monoid (perfect_closure α p) :=
{ mul_assoc := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩,
quot.induction_on g $ λ ⟨s, z⟩, congr_arg (quot.mk _) $
by simp only [add_assoc, mul_assoc, nat.iterate₂ (frobenius_mul _ _),
(nat.iterate_add _ _ _ _).symm, add_comm, add_left_comm],
one := quot.mk _ (0, 1),
one_mul := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $
by simp only [nat.iterate₀ (frobenius_one _ _), nat.iterate_zero, one_mul, zero_add]),
mul_one := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $
by simp only [nat.iterate₀ (frobenius_one _ _), nat.iterate_zero, mul_one, add_zero]),
mul_comm := λ e f, quot.induction_on e (λ ⟨m, x⟩, quot.induction_on f (λ ⟨n, y⟩,
congr_arg (quot.mk _) $ by simp only [add_comm, mul_comm])),
.. (infer_instance : has_mul (perfect_closure α p)) }
private lemma add_aux_left [comm_ring α] (p : ℕ) (hp : nat.prime p) [char_p α p]
(x1 x2 y : ℕ × α) (H : r α p x1 x2) :
quot.mk (r α p) (x1.1 + y.1, ((frobenius α p)^[y.1] x1.2) + ((frobenius α p)^[x1.1] y.2)) =
quot.mk (r α p) (x2.1 + y.1, ((frobenius α p)^[y.1] x2.2) + ((frobenius α p)^[x2.1] y.2)) :=
match x1, x2, H with
| _, _, r.intro _ n x := quot.sound $ by rw [← nat.iterate_succ, nat.iterate_succ',
nat.iterate_succ', ← frobenius_add, nat.succ_add]; apply r.intro
end
private lemma add_aux_right [comm_ring α] (p : ℕ) (hp : nat.prime p) [char_p α p]
(x y1 y2 : ℕ × α) (H : r α p y1 y2) :
quot.mk (r α p) (x.1 + y1.1, ((frobenius α p)^[y1.1] x.2) + ((frobenius α p)^[x.1] y1.2)) =
quot.mk (r α p) (x.1 + y2.1, ((frobenius α p)^[y2.1] x.2) + ((frobenius α p)^[x.1] y2.2)) :=
match y1, y2, H with
| _, _, r.intro _ n y := quot.sound $ by rw [← nat.iterate_succ, nat.iterate_succ',
nat.iterate_succ', ← frobenius_add]; apply r.intro
end
instance [comm_ring α] (p : ℕ) [hp : nat.prime p] [char_p α p] : has_add (perfect_closure α p) :=
⟨quot.lift (λ x:ℕ×α, quot.lift (λ y:ℕ×α, quot.mk (r α p)
(x.1 + y.1, ((frobenius α p)^[y.1] x.2) + ((frobenius α p)^[x.1] y.2))) (add_aux_right α p hp x))
(λ x1 x2 (H : r α p x1 x2), funext $ λ e, quot.induction_on e $ λ y,
add_aux_left α p hp x1 x2 y H)⟩
instance [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : has_neg (perfect_closure α p) :=
⟨quot.lift (λ x:ℕ×α, quot.mk (r α p) (x.1, -x.2)) (λ x y (H : r α p x y), match x, y, H with
| _, _, r.intro _ n x := quot.sound $ by rw ← frobenius_neg; apply r.intro
end)⟩
theorem mk_zero [comm_ring α] (p : ℕ) [nat.prime p] (n : ℕ) : quot.mk (r α p) (n, 0) = quot.mk (r α p) (0, 0) :=
by induction n with n ih; [refl, rw ← ih]; symmetry; apply quot.sound;
have := r.intro p n (0:α); rwa [frobenius_zero α p] at this
theorem r.sound [monoid α] (p m n : ℕ) (x y : α) (H : frobenius α p^[m] x = y) :
quot.mk (r α p) (n, x) = quot.mk (r α p) (m + n, y) :=
by subst H; induction m with m ih; [simp only [zero_add, nat.iterate_zero],
rw [ih, nat.succ_add, nat.iterate_succ']]; apply quot.sound; apply r.intro
instance [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : comm_ring (perfect_closure α p) :=
{ add_assoc := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩,
quot.induction_on g $ λ ⟨s, z⟩, congr_arg (quot.mk _) $
by simp only [add_assoc, nat.iterate₂ (frobenius_add α p),
(nat.iterate_add _ _ _ _).symm, add_comm, add_left_comm],
zero := quot.mk _ (0, 0),
zero_add := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $
by simp only [nat.iterate₀ (frobenius_zero α p), nat.iterate_zero, zero_add]),
add_zero := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $
by simp only [nat.iterate₀ (frobenius_zero α p), nat.iterate_zero, add_zero]),
add_left_neg := λ e, quot.induction_on e (λ ⟨n, x⟩, show quot.mk _ _ = _,
by simp only [nat.iterate₁ (frobenius_neg α p), add_left_neg, mk_zero]; refl),
add_comm := λ e f, quot.induction_on e (λ ⟨m, x⟩, quot.induction_on f (λ ⟨n, y⟩,
congr_arg (quot.mk _) $ by simp only [add_comm])),
left_distrib := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩,
quot.induction_on g $ λ ⟨s, z⟩, show quot.mk _ _ = quot.mk _ _,
by simp only [add_assoc, add_comm, add_left_comm]; apply r.sound;
simp only [nat.iterate₂ (frobenius_mul α p), nat.iterate₂ (frobenius_add α p),
(nat.iterate_add _ _ _ _).symm, mul_add, add_comm, add_left_comm],
right_distrib := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩,
quot.induction_on g $ λ ⟨s, z⟩, show quot.mk _ _ = quot.mk _ _,
by simp only [add_assoc, add_comm _ s, add_left_comm _ s]; apply r.sound;
simp only [nat.iterate₂ (frobenius_mul α p), nat.iterate₂ (frobenius_add α p),
(nat.iterate_add _ _ _ _).symm, add_mul, add_comm, add_left_comm],
.. (infer_instance : has_add (perfect_closure α p)),
.. (infer_instance : has_neg (perfect_closure α p)),
.. (infer_instance : comm_monoid (perfect_closure α p)) }
instance [discrete_field α] (p : ℕ) [nat.prime p] [char_p α p] : has_inv (perfect_closure α p) :=
⟨quot.lift (λ x:ℕ×α, quot.mk (r α p) (x.1, x.2⁻¹)) (λ x y (H : r α p x y), match x, y, H with
| _, _, r.intro _ n x := quot.sound $ by simp only [frobenius]; rw [← inv_pow']; apply r.intro
end)⟩
theorem eq_iff' [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p]
(x y : ℕ × α) : quot.mk (r α p) x = quot.mk (r α p) y ↔
∃ z, (frobenius α p^[y.1 + z] x.2) = (frobenius α p^[x.1 + z] y.2) :=
begin
split,
{ intro H,
replace H := quot.exact _ H,
induction H,
case eqv_gen.rel : x y H
{ cases H with n x, exact ⟨0, rfl⟩ },
case eqv_gen.refl : H
{ exact ⟨0, rfl⟩ },
case eqv_gen.symm : x y H ih
{ cases ih with w ih, exact ⟨w, ih.symm⟩ },
case eqv_gen.trans : x y z H1 H2 ih1 ih2
{ cases ih1 with z1 ih1,
cases ih2 with z2 ih2,
existsi z2+(y.1+z1),
rw [← add_assoc, nat.iterate_add, ih1],
rw [← nat.iterate_add, add_comm, nat.iterate_add, ih2],
rw [← nat.iterate_add],
simp only [add_comm, add_left_comm] } },
intro H,
cases x with m x,
cases y with n y,
cases H with z H, dsimp only at H,
rw [r.sound α p (n+z) m x _ rfl, r.sound α p (m+z) n y _ rfl, H],
rw [add_assoc, add_comm, add_comm z]
end
theorem eq_iff [integral_domain α] (p : ℕ) [nat.prime p] [char_p α p]
(x y : ℕ × α) : quot.mk (r α p) x = quot.mk (r α p) y ↔
(frobenius α p^[y.1] x.2) = (frobenius α p^[x.1] y.2) :=
(eq_iff' α p x y).trans ⟨λ ⟨z, H⟩, nat.iterate_inj (frobenius_inj α p) z _ _ $
by simpa only [add_comm, nat.iterate_add] using H,
λ H, ⟨0, H⟩⟩
instance [discrete_field α] (p : ℕ) [nat.prime p] [char_p α p] : discrete_field (perfect_closure α p) :=
{ zero_ne_one := λ H, zero_ne_one ((eq_iff _ _ _ _).1 H),
mul_inv_cancel := λ e, quot.induction_on e $ λ ⟨m, x⟩ H,
have _ := mt (eq_iff _ _ _ _).2 H, (eq_iff _ _ _ _).2
(by simp only [nat.iterate₀ (frobenius_one _ _), nat.iterate₀ (frobenius_zero α p),
nat.iterate_zero, (nat.iterate₂ (frobenius_mul α p)).symm] at this ⊢;
rw [mul_inv_cancel this, nat.iterate₀ (frobenius_one _ _)]),
inv_mul_cancel := λ e, quot.induction_on e $ λ ⟨m, x⟩ H,
have _ := mt (eq_iff _ _ _ _).2 H, (eq_iff _ _ _ _).2
(by simp only [nat.iterate₀ (frobenius_one _ _), nat.iterate₀ (frobenius_zero α p),
nat.iterate_zero, (nat.iterate₂ (frobenius_mul α p)).symm] at this ⊢;
rw [inv_mul_cancel this, nat.iterate₀ (frobenius_one _ _)]),
has_decidable_eq := λ e f, quot.rec_on_subsingleton e $ λ ⟨m, x⟩,
quot.rec_on_subsingleton f $ λ ⟨n, y⟩,
decidable_of_iff' _ (eq_iff α p _ _),
inv_zero := congr_arg (quot.mk (r α p)) (by rw [inv_zero]),
.. (infer_instance : has_inv (perfect_closure α p)),
.. (infer_instance : comm_ring (perfect_closure α p)) }
theorem frobenius_mk [comm_monoid α] (p : ℕ) (x : ℕ × α) :
frobenius (perfect_closure α p) p (quot.mk (r α p) x) = quot.mk _ (x.1, x.2^p) :=
begin
unfold frobenius, cases x with n x, dsimp only,
suffices : ∀ p':ℕ, (quot.mk (r α p) (n, x) ^ p' : perfect_closure α p) = quot.mk (r α p) (n, x ^ p'),
{ apply this },
intro p, induction p with p ih,
case nat.zero { apply r.sound, rw [nat.iterate₀ (frobenius_one _ _), pow_zero] },
case nat.succ {
rw [pow_succ, ih],
symmetry,
apply r.sound,
simp only [pow_succ, nat.iterate₂ (frobenius_mul _ _)]
}
end
def frobenius_equiv [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] :
perfect_closure α p ≃ perfect_closure α p :=
{ to_fun := frobenius (perfect_closure α p) p,
inv_fun := λ e, quot.lift_on e (λ x, quot.mk (r α p) (x.1 + 1, x.2)) (λ x y H,
match x, y, H with
| _, _, r.intro _ n x := quot.sound (r.intro _ _ _)
end),
left_inv := λ e, quot.induction_on e (λ ⟨m, x⟩, by rw frobenius_mk;
symmetry; apply quot.sound; apply r.intro),
right_inv := λ e, quot.induction_on e (λ ⟨m, x⟩, by rw frobenius_mk;
symmetry; apply quot.sound; apply r.intro) }
theorem frobenius_equiv_apply [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] {x : perfect_closure α p} :
frobenius_equiv α p x = frobenius _ p x :=
rfl
theorem nat_cast [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (n x : ℕ) :
(x : perfect_closure α p) = quot.mk (r α p) (n, x) :=
begin
induction n with n ih,
{ induction x with x ih, {refl},
rw [nat.cast_succ, nat.cast_succ, ih], refl },
rw ih, apply quot.sound,
conv {congr, skip, skip, rw ← frobenius_nat_cast α p x},
apply r.intro
end
theorem int_cast [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (x : ℤ) :
(x : perfect_closure α p) = quot.mk (r α p) (0, x) :=
by induction x; simp only [int.cast_of_nat, int.cast_neg_succ_of_nat, nat_cast α p 0]; refl
theorem nat_cast_eq_iff [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (x y : ℕ) :
(x : perfect_closure α p) = y ↔ (x : α) = y :=
begin
split; intro H,
{ rw [nat_cast α p 0, nat_cast α p 0, eq_iff'] at H,
cases H with z H,
simpa only [zero_add, nat.iterate₀ (frobenius_nat_cast α p _)] using H },
rw [nat_cast α p 0, nat_cast α p 0, H]
end
instance [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : char_p (perfect_closure α p) p :=
begin
constructor, intro x, rw ← char_p.cast_eq_zero_iff α,
rw [← nat.cast_zero, nat_cast_eq_iff, nat.cast_zero]
end
instance [discrete_field α] (p : ℕ) [nat.prime p] [char_p α p] : perfect_field (perfect_closure α p) p :=
{ pth_root := (frobenius_equiv α p).symm,
frobenius_pth_root := (frobenius_equiv α p).apply_inverse_apply }
def of [monoid α] (p : ℕ) (x : α) : perfect_closure α p :=
quot.mk _ (0, x)
instance [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : is_ring_hom (of α p) :=
{ map_one := rfl,
map_mul := λ x y, rfl,
map_add := λ x y, rfl }
theorem eq_pth_root [discrete_field α] (p : ℕ) [nat.prime p] [char_p α p] (m : ℕ) (x : α) :
quot.mk (r α p) (m, x) = (perfect_field.pth_root p^[m] (of α p x) : perfect_closure α p) :=
begin
unfold of,
induction m with m ih, {refl},
rw [nat.iterate_succ', ← ih]; refl
end
def UMP [discrete_field α] (p : ℕ) [nat.prime p] [char_p α p]
(β : Type v) [discrete_field β] [char_p β p] [perfect_field β p] :
{ f : α → β // is_ring_hom f } ≃ { f : perfect_closure α p → β // is_ring_hom f } :=
{ to_fun := λ f, ⟨λ e, quot.lift_on e (λ x, perfect_field.pth_root p^[x.1] (f.1 x.2))
(λ x y H, match x, y, H with | _, _, r.intro _ n x := by letI := f.2;
simp only [is_monoid_hom.map_frobenius f.1, nat.iterate_succ, pth_root_frobenius]
end),
show f.1 1 = 1, from f.2.1,
λ j k, quot.induction_on j $ λ ⟨m, x⟩, quot.induction_on k $ λ ⟨n, y⟩,
show (perfect_field.pth_root p^[_] _) = (perfect_field.pth_root p^[_] _) * (perfect_field.pth_root p^[_] _),
by letI := f.2; simp only [is_ring_hom.map_mul f.1, (nat.iterate₁ (λ x, (is_monoid_hom.map_frobenius f.1 p x).symm)).symm,
@nat.iterate₂ β _ (*) (λ x y, is_ring_hom.map_mul (perfect_field.pth_root p))];
rw [nat.iterate_add, nat.iterate_cancel (pth_root_frobenius β p),
add_comm, nat.iterate_add, nat.iterate_cancel (pth_root_frobenius β p)],
λ j k, quot.induction_on j $ λ ⟨m, x⟩, quot.induction_on k $ λ ⟨n, y⟩,
show (perfect_field.pth_root p^[_] _) = (perfect_field.pth_root p^[_] _) + (perfect_field.pth_root p^[_] _),
by letI := f.2; simp only [is_ring_hom.map_add f.1, (nat.iterate₁ (λ x, (is_monoid_hom.map_frobenius f.1 p x).symm)).symm,
@nat.iterate₂ β _ (+) (λ x y, is_ring_hom.map_add (perfect_field.pth_root p))];
rw [nat.iterate_add, nat.iterate_cancel (pth_root_frobenius β p),
add_comm m, nat.iterate_add, nat.iterate_cancel (pth_root_frobenius β p)]⟩,
inv_fun := λ f, ⟨f.1 ∘ of α p, @@is_ring_hom.comp _ _ _ _ _ _ f.2⟩,
left_inv := λ ⟨f, hf⟩, subtype.eq rfl,
right_inv := λ ⟨f, hf⟩, subtype.eq $ funext $ λ i, quot.induction_on i $ λ ⟨m, x⟩,
show perfect_field.pth_root p^[m] (f _) = f _,
by resetI; rw [eq_pth_root, @nat.iterate₁ _ _ _ _ f (λ x:perfect_closure α p, (is_ring_hom.pth_root p f).symm)] }
end perfect_closure
|
If $p$ divides $q$, then either $p$ has degree less than or equal to $q$ or $q = 0$. |
lemma monom_eq_iff [simp]: "monom a n = monom b n \<longleftrightarrow> a = b" |
And purple @-@ <unk> mouth ;
|
module Haskell.Prim.Eq where
open import Agda.Builtin.Nat as Nat hiding (_==_)
open import Agda.Builtin.Char
open import Agda.Builtin.Unit
open import Agda.Builtin.List
open import Haskell.Prim
open import Haskell.Prim.Bool
open import Haskell.Prim.Integer
open import Haskell.Prim.Int
open import Haskell.Prim.Word
open import Haskell.Prim.Double
open import Haskell.Prim.Tuple
open import Haskell.Prim.Maybe
open import Haskell.Prim.Either
--------------------------------------------------
-- Eq
record Eq (a : Set) : Set where
infix 4 _==_ _/=_
field
_==_ : a → a → Bool
_/=_ : a → a → Bool
x /= y = not (x == y)
open Eq ⦃ ... ⦄ public
{-# COMPILE AGDA2HS Eq existing-class #-}
instance
iEqNat : Eq Nat
iEqNat ._==_ = Nat._==_
iEqInteger : Eq Integer
iEqInteger ._==_ = eqInteger
iEqInt : Eq Int
iEqInt ._==_ = eqInt
iEqWord : Eq Word
iEqWord ._==_ = eqWord
iEqDouble : Eq Double
iEqDouble ._==_ = primFloatNumericalEquality
iEqBool : Eq Bool
iEqBool ._==_ false false = true
iEqBool ._==_ true true = true
iEqBool ._==_ _ _ = false
iEqChar : Eq Char
iEqChar ._==_ = primCharEquality
iEqUnit : Eq ⊤
iEqUnit ._==_ _ _ = true
iEqTuple₀ : Eq (Tuple [])
iEqTuple₀ ._==_ _ _ = true
iEqTuple : ∀ {as} → ⦃ Eq a ⦄ → ⦃ Eq (Tuple as) ⦄ → Eq (Tuple (a ∷ as))
iEqTuple ._==_ (x ∷ xs) (y ∷ ys) = x == y && xs == ys
iEqList : ⦃ Eq a ⦄ → Eq (List a)
iEqList ._==_ [] [] = true
iEqList ._==_ (x ∷ xs) (y ∷ ys) = x == y && xs == ys
iEqList ._==_ _ _ = false
iEqMaybe : ⦃ Eq a ⦄ → Eq (Maybe a)
iEqMaybe ._==_ Nothing Nothing = true
iEqMaybe ._==_ (Just x) (Just y) = x == y
iEqMaybe ._==_ _ _ = false
iEqEither : ⦃ Eq a ⦄ → ⦃ Eq b ⦄ → Eq (Either a b)
iEqEither ._==_ (Left x) (Left y) = x == y
iEqEither ._==_ (Right x) (Right y) = x == y
iEqEither ._==_ _ _ = false
|
Require Export XR_Rinv_0_lt_compat.
Require Export XR_Ropp_lt_cancel.
Require Export XR_Ropp_inv_permute.
Local Open Scope R_scope.
Lemma Rinv_lt_0_compat : forall r, r < R0 -> / r < R0.
Proof.
intros x h.
apply Ropp_lt_cancel.
rewrite Ropp_0.
rewrite Ropp_inv_permute.
{
apply Rinv_0_lt_compat.
rewrite <- Ropp_0.
apply Ropp_lt_contravar.
exact h.
}
{
apply Rlt_not_eq.
exact h.
}
Qed. |
lemma continuous_prod [continuous_intros]: fixes f :: "'a \<Rightarrow> 'b::t2_space \<Rightarrow> 'c::{real_normed_algebra,comm_ring_1}" shows "(\<And>i. i \<in> S \<Longrightarrow> continuous F (f i)) \<Longrightarrow> continuous F (\<lambda>x. \<Prod>i\<in>S. f i x)" |
module FunClause where
f
: {A : Set}
→ A
→ A
f x
= y
where
y = x
z = x
data List
(A : Set)
: Set
where
nil
: List A
cons
: A
→ List A
→ List A
snoc
: {A : Set}
→ List A
→ A
→ List A
snoc nil y
= cons y nil
snoc (cons x xs) y
= cons x (snoc xs y)
|
In Warsaw , there were over 70 underground schools , with 2 @,@ 000 teachers and 21 @,@ 000 students . Underground Warsaw University educated 3 @,@ 700 students , issuing 64 masters and 7 doctoral degrees . Warsaw <unk> under occupation educated 3 @,@ 000 students , issuing 186 engineering degrees , 18 doctoral ones and 16 <unk> . Jagiellonian University issued 468 masters and 62 doctoral degrees , employed over 100 professors and teachers , and served more than 1 @,@ 000 students per year . Throughout Poland , many other universities and institutions of higher education ( of music , theater , arts , and others ) continued their classes throughout the war . Even some academic research was carried out ( for example , by Władysław Tatarkiewicz , a leading Polish philosopher , and Zenon <unk> , a linguist ) . Nearly 1 @,@ 000 Polish scientists received funds from the Underground State , enabling them to continue their research .
|
State Before: case mpr
μ ν : YoungDiagram
⊢ μ = transpose ν → transpose μ = ν State After: case mpr
ν : YoungDiagram
⊢ transpose (transpose ν) = ν Tactic: rintro rfl State Before: case mpr
ν : YoungDiagram
⊢ transpose (transpose ν) = ν State After: no goals Tactic: simp |
theory Simple_Network_Language_Export_Code
imports
Parsing.JSON_Parsing
Simple_Networks.Simple_Network_Language_Renaming
Simple_Networks.Simple_Network_Language_Deadlock_Checking
Shortest_SCC_Paths
TA_Library.Error_List_Monad
begin
datatype result =
Renaming_Failed | Preconds_Unsat | Sat | Unsat
abbreviation "renum_automaton \<equiv> Simple_Network_Rename_Defs.renum_automaton"
locale Simple_Network_Rename_Formula_String_Defs =
Simple_Network_Rename_Defs_int where automata = automata for automata ::
"(nat list \<times> nat list \<times>
(String.literal act, nat, String.literal, int, String.literal, int) transition list
\<times> (nat \<times> (String.literal, int) cconstraint) list) list"
begin
definition check_renaming where "check_renaming urge \<Phi> L\<^sub>0 s\<^sub>0 \<equiv> combine [
assert (\<forall>i<n_ps. \<forall>x\<in>loc_set. \<forall>y\<in>loc_set. renum_states i x = renum_states i y \<longrightarrow> x = y)
STR ''Location renamings are injective'',
assert (inj_on renum_clocks (insert urge clk_set'))
STR ''Clock renaming is injective'',
assert (inj_on renum_vars var_set)
STR ''Variable renaming is injective'',
assert (inj_on renum_acts act_set)
STR ''Action renaming is injective'',
assert (fst ` set bounds' = var_set)
STR ''Bound set is exactly the variable set'',
assert (\<Union> ((\<lambda>g. fst ` set g) ` set (map (snd o snd o snd) automata)) \<subseteq> loc_set)
STR ''Invariant locations are contained in the location set'',
assert (\<Union> ((set o fst) ` set automata) \<subseteq> loc_set)
STR ''Broadcast locations are containted in the location set'',
assert ((\<Union>x\<in>set automata. set (fst (snd x))) \<subseteq> loc_set)
STR ''Urgent locations are containted in the location set'',
assert (urge \<notin> clk_set')
STR ''Urge not in clock set'',
assert (L\<^sub>0 \<in> states)
STR ''Initial location is in the state set'',
assert (fst ` set s\<^sub>0 = var_set)
STR ''Initial state has the correct domain'',
assert (distinct (map fst s\<^sub>0))
STR ''Initial state is unambiguous'',
assert (set2_formula \<Phi> \<subseteq> loc_set)
STR ''Formula locations are contained in the location set'',
assert (locs_of_formula \<Phi> \<subseteq> {0..<n_ps})
STR ''Formula automata are contained in the automata set'',
assert (vars_of_formula \<Phi> \<subseteq> var_set)
STR ''Variables of the formula are contained in the variable set''
]
"
end (* Simple_Network_Rename_Formula_String_Defs *)
locale Simple_Network_Rename_Formula_String =
Simple_Network_Rename_Formula_String_Defs +
fixes urge :: String.literal
fixes \<Phi> :: "(nat, nat, String.literal, int) formula"
and s\<^sub>0 :: "(String.literal \<times> int) list"
and L\<^sub>0 :: "nat list"
assumes renum_states_inj:
"\<forall>i<n_ps. \<forall>x\<in>loc_set. \<forall>y\<in>loc_set. renum_states i x = renum_states i y \<longrightarrow> x = y"
and renum_clocks_inj: "inj_on renum_clocks (insert urge clk_set')"
and renum_vars_inj: "inj_on renum_vars var_set"
and renum_acts_inj: "inj_on renum_acts act_set"
and bounds'_var_set: "fst ` set bounds' = var_set"
and loc_set_invs: "\<Union> ((\<lambda>g. fst ` set g) ` set (map (snd o snd o snd) automata)) \<subseteq> loc_set"
and loc_set_broadcast: "\<Union> ((set o fst) ` set automata) \<subseteq> loc_set"
and loc_set_urgent: "\<Union> ((set o (fst o snd)) ` set automata) \<subseteq> loc_set"
and urge_not_in_clk_set: "urge \<notin> clk_set'"
assumes L\<^sub>0_states: "L\<^sub>0 \<in> states"
and s\<^sub>0_dom: "fst ` set s\<^sub>0 = var_set" and s\<^sub>0_distinct: "distinct (map fst s\<^sub>0)"
assumes formula_dom:
"set2_formula \<Phi> \<subseteq> loc_set"
"locs_of_formula \<Phi> \<subseteq> {0..<n_ps}"
"vars_of_formula \<Phi> \<subseteq> var_set"
begin
interpretation Simple_Network_Rename_Formula
by (standard;
rule renum_states_inj renum_clocks_inj renum_vars_inj bounds'_var_set renum_acts_inj
loc_set_invs loc_set_broadcast loc_set_urgent urge_not_in_clk_set
infinite_literal infinite_UNIV_nat L\<^sub>0_states s\<^sub>0_dom s\<^sub>0_distinct formula_dom
)+
lemmas Simple_Network_Rename_intro = Simple_Network_Rename_Formula_axioms
end
term Simple_Network_Rename_Formula_String
print_statement Simple_Network_Rename_Formula_String_def
lemma is_result_assert_iff:
"is_result (assert b m) \<longleftrightarrow> b"
unfolding assert_def by auto
lemma is_result_combine_Cons_iff:
"is_result (combine (x # xs)) \<longleftrightarrow> is_result x \<and> is_result (combine xs)"
by (cases x; cases "combine xs") auto
lemma is_result_combine_iff:
"is_result (a <|> b) \<longleftrightarrow> is_result a \<and> is_result b"
by (cases a; cases b) (auto simp: combine2_def)
context Simple_Network_Rename_Formula_String_Defs
begin
lemma check_renaming:
"Simple_Network_Rename_Formula_String
broadcast bounds'
renum_acts renum_vars renum_clocks renum_states
automata urge \<Phi> s\<^sub>0 L\<^sub>0 \<longleftrightarrow>
is_result (check_renaming urge \<Phi> L\<^sub>0 s\<^sub>0)
"
unfolding check_renaming_def Simple_Network_Rename_Formula_String_def
by (simp add: is_result_combine_Cons_iff is_result_assert_iff del: combine.simps(2))
end
context Simple_Network_Impl_nat_defs
begin
definition check_precond1 where
"check_precond1 =
combine [
assert (m > 0)
(STR ''At least one clock''),
assert (0 < length automata)
(STR ''At least one automaton''),
assert (\<forall>i<n_ps. let (_, _, trans, _) = (automata ! i) in \<forall> (l, _, _, _, _, _, l') \<in> set trans.
l < num_states i \<and> l' < num_states i)
(STR ''Number of states is correct (transitions)''),
assert (\<forall>i < n_ps. let (_, _, _, inv) = (automata ! i) in \<forall> (x, _) \<in> set inv. x < num_states i)
(STR ''Number of states is correct (invariants)''),
assert (\<forall>(_, _, trans, _) \<in> set automata. \<forall>(_, _, _, _, f, _, _) \<in> set trans.
\<forall>(x, upd) \<in> set f. x < n_vs \<and> (\<forall>i \<in> vars_of_exp upd. i < n_vs))
(STR ''Variable set bounded (updates)''),
assert (\<forall>(_, _, trans, _) \<in> set automata. \<forall>(_, b, _, _, _, _, _) \<in> set trans.
\<forall>i \<in> vars_of_bexp b. i < n_vs)
(STR ''Variable set bounded (guards)''),
assert (\<forall> i < n_vs. fst (bounds' ! i) = i)
(STR ''Bounds first index''),
assert (\<forall>a \<in> set broadcast. a < num_actions)
(STR ''Broadcast actions bounded''),
assert (\<forall>(_, _, trans, _) \<in> set automata. \<forall>(_, _, _, a, _, _, _) \<in> set trans.
pred_act (\<lambda>a. a < num_actions) a)
(STR ''Actions bounded (transitions)''),
assert (\<forall>(_, _, trans, _) \<in> set automata. \<forall>(_, _, g, _, _, r, _) \<in> set trans.
(\<forall>c \<in> set r. 0 < c \<and> c \<le> m) \<and>
(\<forall> (c, x) \<in> collect_clock_pairs g. 0 < c \<and> c \<le> m \<and> x \<in> \<nat>))
(STR ''Clock set bounded (transitions)''),
assert (\<forall>(_, _, _, inv) \<in> set automata. \<forall>(l, g) \<in> set inv.
(\<forall> (c, x) \<in> collect_clock_pairs g. 0 < c \<and> c \<le> m \<and> x \<in> \<nat>))
(STR ''Clock set bounded (invariants)''),
assert (\<forall>(_, _, trans, _) \<in> set automata. \<forall>(_, _, g, a, _, _, _) \<in> set trans.
case a of In a \<Rightarrow> a \<in> set broadcast \<longrightarrow> g = [] | _ \<Rightarrow> True)
(STR ''Broadcast receivers are unguarded''),
assert (\<forall>(_, U, _, _)\<in>set automata. U = [])
STR ''Urgency was removed''
]
"
lemma check_precond1:
"is_result check_precond1
\<longleftrightarrow> Simple_Network_Impl_nat_urge broadcast bounds' automata m num_states num_actions"
unfolding check_precond1_def Simple_Network_Impl_nat_def Simple_Network_Impl_nat_urge_def
Simple_Network_Impl_nat_urge_axioms_def
by (simp add: is_result_combine_Cons_iff is_result_assert_iff del: combine.simps(2))
context
fixes k :: "nat list list list"
and L\<^sub>0 :: "nat list"
and s\<^sub>0 :: "(nat \<times> int) list"
and formula :: "(nat, nat, nat, int) formula"
begin
definition check_precond2 where
"check_precond2 \<equiv>
combine [
assert (\<forall>i < n_ps. \<forall>(l, g) \<in> set ((snd o snd o snd) (automata ! i)).
\<forall>(x, m) \<in> collect_clock_pairs g. m \<le> int (k ! i ! l ! x))
(STR ''Ceiling invariants''),
assert (\<forall>i < n_ps. \<forall>(l, _, g, _) \<in> set ((fst o snd o snd) (automata ! i)).
(\<forall>(x, m) \<in> collect_clock_pairs g. m \<le> int (k ! i ! l ! x)))
(STR ''Ceiling transitions''),
assert (\<forall>i < n_ps. \<forall> (l, b, g, a, upd, r, l') \<in> set ((fst o snd o snd) (automata ! i)).
\<forall>c \<in> {0..<m+1} - set r. k ! i ! l' ! c \<le> k ! i ! l ! c)
(STR ''Ceiling resets''),
assert (length k = n_ps)
(STR ''Ceiling length''),
assert (\<forall> i < n_ps. length (k ! i) = num_states i)
(STR ''Ceiling length automata)''),
assert (\<forall> xs \<in> set k. \<forall> xxs \<in> set xs. length xxs = m + 1)
(STR ''Ceiling length clocks''),
assert (\<forall>i < n_ps. \<forall>l < num_states i. k ! i ! l ! 0 = 0)
(STR ''Ceiling zero clock''),
assert (\<forall>(_, _, _, inv) \<in> set automata. distinct (map fst inv))
(STR ''Unambiguous invariants''),
assert (bounded bounds (map_of s\<^sub>0))
(STR ''Initial state bounded''),
assert (length L\<^sub>0 = n_ps)
(STR ''Length of initial state''),
assert (\<forall>i < n_ps. L\<^sub>0 ! i \<in> fst ` set ((fst o snd o snd) (automata ! i)))
(STR ''Initial state has outgoing transitions''),
assert (vars_of_formula formula \<subseteq> {0..<n_vs})
(STR ''Variable set of formula'')
]"
lemma check_precond2:
"is_result check_precond2 \<longleftrightarrow>
Simple_Network_Impl_nat_ceiling_start_state_axioms broadcast bounds' automata m num_states
k L\<^sub>0 s\<^sub>0 formula"
unfolding check_precond2_def Simple_Network_Impl_nat_ceiling_start_state_axioms_def
by (simp add: is_result_combine_Cons_iff is_result_assert_iff del: combine.simps(2))
end
definition
"check_precond k L\<^sub>0 s\<^sub>0 formula \<equiv> check_precond1 <|> check_precond2 k L\<^sub>0 s\<^sub>0 formula"
lemma check_precond:
"Simple_Network_Impl_nat_ceiling_start_state broadcast bounds' automata m num_states
num_actions k L\<^sub>0 s\<^sub>0 formula \<longleftrightarrow> is_result (check_precond k L\<^sub>0 s\<^sub>0 formula)"
unfolding check_precond_def is_result_combine_iff check_precond1 check_precond2
Simple_Network_Impl_nat_ceiling_start_state_def
..
end
derive "show" acconstraint act sexp formula
fun shows_exp and shows_bexp where
"shows_exp (const c) = show c" |
"shows_exp (var v) = show v" |
"shows_exp (if_then_else b e1 e2) =
shows_bexp b @ '' ? '' @ shows_exp e1 @ '' : '' @ shows_exp e2" |
"shows_exp (binop _ e1 e2) = ''binop '' @ shows_exp e1 @ '' '' @ shows_exp e2" |
"shows_exp (unop _ e) = ''unop '' @ shows_exp e" |
"shows_bexp (bexp.lt a b) = shows_exp a @ '' < '' @ shows_exp b" |
"shows_bexp (bexp.le a b) = shows_exp a @ '' <= '' @ shows_exp b" |
"shows_bexp (bexp.eq a b) = shows_exp a @ '' = '' @ shows_exp b" |
"shows_bexp (bexp.ge a b) = shows_exp a @ '' >= '' @ shows_exp b" |
"shows_bexp (bexp.gt a b) = shows_exp a @ '' > '' @ shows_exp b" |
"shows_bexp bexp.true = ''true''" |
"shows_bexp (bexp.not b) = ''! '' @ shows_bexp b" |
"shows_bexp (bexp.and a b) = shows_bexp a @ '' && '' @ shows_bexp b" |
"shows_bexp (bexp.or a b) = shows_bexp a @ '' || '' @ shows_bexp b" |
"shows_bexp (bexp.imply a b) = shows_bexp a @ '' -> '' @ shows_bexp b"
instantiation bexp :: ("show", "show") "show"
begin
definition "shows_prec p (e :: (_, _) bexp) rest = shows_bexp e @ rest" for p
definition "shows_list (es) s =
map shows_bexp es |> intersperse '', '' |> (\<lambda>xs. ''['' @ concat xs @ '']'' @ s)"
instance
by standard (simp_all add: shows_prec_bexp_def shows_list_bexp_def show_law_simps)
end
instantiation exp :: ("show", "show") "show"
begin
definition "shows_prec p (e :: (_, _) exp) rest = shows_exp e @ rest" for p
definition "shows_list (es) s =
map shows_exp es |> intersperse '', '' |> (\<lambda>xs. ''['' @ concat xs @ '']'' @ s)"
instance
by standard (simp_all add: shows_prec_exp_def shows_list_exp_def show_law_simps)
end
definition
"pad m s = replicate m CHR '' '' @ s"
definition "shows_rat r \<equiv> case r of fract.Rat s f b \<Rightarrow>
(if s then '''' else ''-'') @ show f @ (if b \<noteq> 0 then ''.'' @ show b else '''')"
fun shows_json :: "nat \<Rightarrow> JSON \<Rightarrow> string" where
"shows_json n (Nat m) = show m |> pad n"
| "shows_json n (Rat r) = shows_rat r |> pad n"
| "shows_json n (JSON.Int r) = show r |> pad n"
| "shows_json n (Boolean b) = (if b then ''true'' else ''false'') |> pad n"
| "shows_json n Null = ''null'' |> pad n"
| "shows_json n (String s) = pad n (''\"'' @ s @ ''\"'')"
| "shows_json n (JSON.Array xs) = (
if xs = Nil then
pad n ''[]''
else
pad n ''[\<newline>''
@ concat (map (shows_json (n + 2)) xs |> intersperse '',\<newline>'')
@ ''\<newline>''
@ pad n '']''
)"
| "shows_json n (JSON.Object xs) = (
if xs = Nil then
pad n ''{}''
else
pad n ''{\<newline>''
@ concat (
map (\<lambda>(k, v). pad (n + 2) (''\"'' @ k @ ''\"'') @ '':\<newline>'' @ shows_json (n + 4) v) xs
|> intersperse '',\<newline>''
)
@ ''\<newline>''
@ pad n ''}''
)"
instantiation JSON :: "show"
begin
definition "shows_prec p (x :: JSON) rest = shows_json 0 x @ rest" for p
definition "shows_list jsons s =
map (shows_json 0) jsons |> intersperse '', '' |> (\<lambda>xs. ''['' @ concat xs @ '']'' @ s)"
instance
by standard (simp_all add: shows_prec_JSON_def shows_list_JSON_def show_law_simps)
end
definition rename_network where
"rename_network broadcast bounds' automata renum_acts renum_vars renum_clocks renum_states \<equiv>
let
automata = map_index (renum_automaton renum_acts renum_vars renum_clocks renum_states) automata;
broadcast = map renum_acts broadcast;
bounds' = map (\<lambda>(a,b,c). (renum_vars a, b, c)) bounds'
in
(broadcast, automata, bounds')
"
definition
"show_clock inv_renum_clocks = show o inv_renum_clocks"
definition
"show_locs inv_renum_states = show o map_index inv_renum_states"
definition
"show_vars inv_renum_vars = show o map_index (\<lambda>i v. show (inv_renum_vars i) @ ''='' @ show v)"
definition
"show_state inv_renum_states inv_renum_vars \<equiv> \<lambda>(L, vs).
let L = show_locs inv_renum_states L; vs = show_vars inv_renum_vars vs in
''<'' @ L @ ''>, <'' @ vs @ ''>''"
definition do_rename_mc where
"do_rename_mc f dc broadcast bounds' automata k urge L\<^sub>0 s\<^sub>0 formula
m num_states num_actions renum_acts renum_vars renum_clocks renum_states
inv_renum_states inv_renum_vars inv_renum_clocks
\<equiv>
let
_ = println (STR ''Checking renaming'');
formula = (if dc then formula.EX (not sexp.true) else formula);
renaming_valid = Simple_Network_Rename_Formula_String_Defs.check_renaming
broadcast bounds' renum_acts renum_vars renum_clocks renum_states automata urge formula L\<^sub>0 s\<^sub>0;
_ = println (STR ''Renaming network'');
(broadcast, automata, bounds') = rename_network
broadcast bounds' (map (conv_urge urge) automata)
renum_acts renum_vars renum_clocks renum_states;
_ = trace_level 4 (\<lambda>_. return (STR ''Automata after renaming''));
_ = map (\<lambda>a. show a |> String.implode |> (\<lambda>s. trace_level 4 (\<lambda>_. return s))) automata;
_ = println (STR ''Renaming formula'');
formula =
(if dc then formula.EX (not sexp.true) else map_formula renum_states renum_vars id formula);
_ = println (STR ''Renaming state'');
L\<^sub>0 = map_index renum_states L\<^sub>0;
s\<^sub>0 = map (\<lambda>(x, v). (renum_vars x, v)) s\<^sub>0;
show_clock = show o inv_renum_clocks;
show_state = show_state inv_renum_states inv_renum_vars
in
if is_result renaming_valid then do {
let _ = println (STR ''Checking preconditions'');
let r = Simple_Network_Impl_nat_defs.check_precond
broadcast bounds' automata m num_states num_actions k L\<^sub>0 s\<^sub>0 formula;
let _ = (case r of Result _ \<Rightarrow> ()
| Error es \<Rightarrow>
let
_ = println STR '''';
_ = println STR ''The following pre-conditions were not satisified:''
in
let _ = map println es in println STR '''');
let _ = println (STR ''Running precond_mc'');
let r = f show_clock show_state
broadcast bounds' automata m num_states num_actions k L\<^sub>0 s\<^sub>0 formula;
Some r
}
else do {
let _ = println (STR ''The following conditions on the renaming were not satisfied:'');
let _ = the_errors renaming_valid |> map println;
None}
"
definition rename_mc where
"rename_mc dc broadcast bounds' automata k urge L\<^sub>0 s\<^sub>0 formula
m num_states num_actions renum_acts renum_vars renum_clocks renum_states
inv_renum_states inv_renum_vars inv_renum_clocks
\<equiv>
do {
let r = do_rename_mc (if dc then precond_dc else precond_mc)
dc broadcast bounds' automata k urge L\<^sub>0 s\<^sub>0 formula
m num_states num_actions renum_acts renum_vars renum_clocks renum_states
inv_renum_states inv_renum_vars inv_renum_clocks;
case r of Some r \<Rightarrow> do {
r \<leftarrow> r;
case r of
None \<Rightarrow> return Preconds_Unsat
| Some False \<Rightarrow> return Unsat
| Some True \<Rightarrow> return Sat
}
| None \<Rightarrow> return Renaming_Failed
}
"
(*
definition rename_mc where
"rename_mc dc broadcast bounds' automata k L\<^sub>0 s\<^sub>0 formula
m num_states num_actions renum_acts renum_vars renum_clocks renum_states
inv_renum_states inv_renum_vars inv_renum_clocks
\<equiv>
let
_ = println (STR ''Checking renaming'');
formula = (if dc then formula.EX (not sexp.true) else formula);
renaming_valid = Simple_Network_Rename_Formula_String_Defs.check_renaming
broadcast bounds' renum_vars renum_clocks renum_states automata formula L\<^sub>0 s\<^sub>0;
_ = println (STR ''Renaming network'');
(broadcast, automata, bounds') = rename_network
broadcast bounds' automata renum_acts renum_vars renum_clocks renum_states;
_ = println (STR ''Automata after renaming'');
_ = map (\<lambda>a. show a |> String.implode |> println) automata;
_ = println (STR ''Renaming formula'');
formula =
(if dc then formula.EX (not sexp.true) else map_formula renum_states renum_vars id formula);
_ = println (STR ''Renaming state'');
L\<^sub>0 = map_index renum_states L\<^sub>0;
s\<^sub>0 = map (\<lambda>(x, v). (renum_vars x, v)) s\<^sub>0;
show_clock = show o inv_renum_clocks;
show_state = show_state inv_renum_states inv_renum_vars
in
if is_result renaming_valid then do {
let _ = println (STR ''Checking preconditions'');
let r = Simple_Network_Impl_nat_defs.check_precond
broadcast bounds' automata m num_states num_actions k L\<^sub>0 s\<^sub>0 formula;
let _ = (case r of Result _ \<Rightarrow> [()]
| Error es \<Rightarrow> let _ = println (STR ''The following pre-conditions were not satisified'') in
map println es);
let _ = println (STR ''Running precond_mc'');
r \<leftarrow> (if dc
then precond_dc show_clock show_state
broadcast bounds' automata m num_states num_actions k L\<^sub>0 s\<^sub>0 formula
else precond_mc show_clock show_state
broadcast bounds' automata m num_states num_actions k L\<^sub>0 s\<^sub>0 formula);
case r of
None \<Rightarrow> return Preconds_Unsat
| Some False \<Rightarrow> return Unsat
| Some True \<Rightarrow> return Sat
}
else do {
let _ = println (STR ''The following conditions on the renaming were not satisfied:'');
let _ = the_errors renaming_valid |> map println;
return Renaming_Failed}
"
*)
theorem model_check_rename:
"<emp> rename_mc False broadcast bounds automata k urge L\<^sub>0 s\<^sub>0 formula
m num_states num_actions renum_acts renum_vars renum_clocks renum_states
inv_renum_states inv_renum_vars inv_renum_clocks
<\<lambda> Sat \<Rightarrow> \<up>(
(\<not> has_deadlock (N broadcast automata bounds) (L\<^sub>0, map_of s\<^sub>0, \<lambda>_ . 0) \<longrightarrow>
N broadcast automata bounds,(L\<^sub>0, map_of s\<^sub>0, \<lambda>_ . 0) \<Turnstile> formula
))
| Unsat \<Rightarrow> \<up>(
(\<not> has_deadlock (N broadcast automata bounds) (L\<^sub>0, map_of s\<^sub>0, \<lambda>_ . 0) \<longrightarrow>
\<not> N broadcast automata bounds,(L\<^sub>0, map_of s\<^sub>0, \<lambda>_ . 0) \<Turnstile> formula
))
| Renaming_Failed \<Rightarrow> \<up>(\<not> Simple_Network_Rename_Formula
broadcast bounds renum_acts renum_vars renum_clocks renum_states urge s\<^sub>0 L\<^sub>0 automata formula)
| Preconds_Unsat \<Rightarrow> \<up>(\<not> Simple_Network_Impl_nat_ceiling_start_state
(map renum_acts broadcast)
(map (\<lambda>(a,p). (renum_vars a, p)) bounds)
(map_index (renum_automaton renum_acts renum_vars renum_clocks renum_states)
(map (conv_urge urge) automata))
m num_states num_actions k
(map_index renum_states L\<^sub>0) (map (\<lambda>(x, v). (renum_vars x, v)) s\<^sub>0)
(map_formula renum_states renum_vars id formula))
>\<^sub>t"
proof -
have *: "
Simple_Network_Rename_Formula_String
broadcast bounds renum_acts renum_vars renum_clocks renum_states automata urge formula s\<^sub>0 L\<^sub>0
= Simple_Network_Rename_Formula
broadcast bounds renum_acts renum_vars renum_clocks renum_states urge s\<^sub>0 L\<^sub>0 automata formula
"
unfolding
Simple_Network_Rename_Formula_String_def Simple_Network_Rename_Formula_def
Simple_Network_Rename_Start_def Simple_Network_Rename_Start_axioms_def
Simple_Network_Rename_def Simple_Network_Rename_Formula_axioms_def
using infinite_literal by auto
define A where "A \<equiv> N broadcast automata bounds"
define check where "check \<equiv> A,(L\<^sub>0, map_of s\<^sub>0, \<lambda>_ . 0) \<Turnstile> formula"
define A' where "A' \<equiv> N
(map renum_acts broadcast)
(map_index (renum_automaton renum_acts renum_vars renum_clocks renum_states)
(map (conv_urge urge) automata))
(map (\<lambda>(a,p). (renum_vars a, p)) bounds)"
define check' where "check' \<equiv>
A',(map_index renum_states L\<^sub>0, map_of (map (\<lambda>(x, v). (renum_vars x, v)) s\<^sub>0), \<lambda>_ . 0) \<Turnstile>
map_formula renum_states renum_vars id formula"
define preconds_sat where "preconds_sat \<equiv>
Simple_Network_Impl_nat_ceiling_start_state
(map renum_acts broadcast)
(map (\<lambda>(a,p). (renum_vars a, p)) bounds)
(map_index (renum_automaton renum_acts renum_vars renum_clocks renum_states)
(map (conv_urge urge) automata))
m num_states num_actions k
(map_index renum_states L\<^sub>0) (map (\<lambda>(x, v). (renum_vars x, v)) s\<^sub>0)
(map_formula renum_states renum_vars id formula)"
define renaming_valid where "renaming_valid \<equiv>
Simple_Network_Rename_Formula
broadcast bounds renum_acts renum_vars renum_clocks renum_states urge s\<^sub>0 L\<^sub>0 automata formula
"
have [simp]: "check \<longleftrightarrow> check'"
if renaming_valid
using that unfolding check_def check'_def A_def A'_def renaming_valid_def
by (rule Simple_Network_Rename_Formula.models_iff'[symmetric])
have test[symmetric, simp]:
"Simple_Network_Language_Model_Checking.has_deadlock A (L\<^sub>0, map_of s\<^sub>0, \<lambda>_. 0)
\<longleftrightarrow>Simple_Network_Language_Model_Checking.has_deadlock A'
(map_index renum_states L\<^sub>0, map_of (map (\<lambda>(x, y). (renum_vars x, y)) s\<^sub>0), \<lambda>_. 0)
" if renaming_valid
using that unfolding check_def check'_def A_def A'_def renaming_valid_def
unfolding Simple_Network_Rename_Formula_def
by (elim conjE) (rule Simple_Network_Rename_Start.has_deadlock_iff'[symmetric])
note [sep_heap_rules] =
model_check[
of _ _
"map renum_acts broadcast" "map (\<lambda>(a,p). (renum_vars a, p)) bounds"
"map_index (renum_automaton renum_acts renum_vars renum_clocks renum_states)
(map (conv_urge urge) automata)"
m num_states num_actions k "map_index renum_states L\<^sub>0" "map (\<lambda>(x, v). (renum_vars x, v)) s\<^sub>0"
"map_formula renum_states renum_vars id formula",
folded A'_def preconds_sat_def renaming_valid_def, folded check'_def, simplified
]
show ?thesis
unfolding rename_mc_def do_rename_mc_def rename_network_def
unfolding if_False
unfolding Simple_Network_Rename_Formula_String_Defs.check_renaming[symmetric] * Let_def
unfolding
A_def[symmetric] check_def[symmetric]
preconds_sat_def[symmetric] renaming_valid_def[symmetric]
by (sep_auto simp: model_checker.refine[symmetric] split: bool.splits)
qed
theorem deadlock_check_rename:
"<emp> rename_mc True broadcast bounds automata k urge L\<^sub>0 s\<^sub>0 formula
m num_states num_actions renum_acts renum_vars renum_clocks renum_states
inv_renum_states inv_renum_vars inv_renum_clocks
<\<lambda> Sat \<Rightarrow> \<up>( has_deadlock (N broadcast automata bounds) (L\<^sub>0, map_of s\<^sub>0, \<lambda>_. 0))
| Unsat \<Rightarrow> \<up>(\<not> has_deadlock (N broadcast automata bounds) (L\<^sub>0, map_of s\<^sub>0, \<lambda>_. 0))
| Renaming_Failed \<Rightarrow> \<up>(\<not> Simple_Network_Rename_Formula
broadcast bounds renum_acts renum_vars renum_clocks renum_states urge s\<^sub>0 L\<^sub>0 automata
(formula.EX (not sexp.true)))
| Preconds_Unsat \<Rightarrow> \<up>(\<not> Simple_Network_Impl_nat_ceiling_start_state
(map renum_acts broadcast)
(map (\<lambda>(a,p). (renum_vars a, p)) bounds)
(map_index (renum_automaton renum_acts renum_vars renum_clocks renum_states)
(map (conv_urge urge) automata))
m num_states num_actions k
(map_index renum_states L\<^sub>0) (map (\<lambda>(x, v). (renum_vars x, v)) s\<^sub>0)
(formula.EX (not sexp.true)))
>\<^sub>t"
proof -
have *: "
Simple_Network_Rename_Formula_String
broadcast bounds renum_acts renum_vars renum_clocks renum_states automata urge
(formula.EX (not sexp.true)) s\<^sub>0 L\<^sub>0
= Simple_Network_Rename_Formula
broadcast bounds renum_acts renum_vars renum_clocks renum_states urge s\<^sub>0 L\<^sub>0 automata
(formula.EX (not sexp.true))
"
unfolding
Simple_Network_Rename_Formula_String_def Simple_Network_Rename_Formula_def
Simple_Network_Rename_Start_def Simple_Network_Rename_Start_axioms_def
Simple_Network_Rename_def Simple_Network_Rename_Formula_axioms_def
using infinite_literal by auto
define A where "A \<equiv> N broadcast automata bounds"
define A' where "A' \<equiv> N
(map renum_acts broadcast)
(map_index (renum_automaton renum_acts renum_vars renum_clocks renum_states)
(map (conv_urge urge) automata))
(map (\<lambda>(a,p). (renum_vars a, p)) bounds)"
define preconds_sat where "preconds_sat \<equiv>
Simple_Network_Impl_nat_ceiling_start_state
(map renum_acts broadcast)
(map (\<lambda>(a,p). (renum_vars a, p)) bounds)
(map_index (renum_automaton renum_acts renum_vars renum_clocks renum_states)
(map (conv_urge urge) automata))
m num_states num_actions k
(map_index renum_states L\<^sub>0) (map (\<lambda>(x, v). (renum_vars x, v)) s\<^sub>0)
(formula.EX (not sexp.true))"
define renaming_valid where "renaming_valid \<equiv>
Simple_Network_Rename_Formula
broadcast bounds renum_acts renum_vars renum_clocks renum_states urge s\<^sub>0 L\<^sub>0 automata
(formula.EX (not sexp.true))"
have test[symmetric, simp]:
"Simple_Network_Language_Model_Checking.has_deadlock A (L\<^sub>0, map_of s\<^sub>0, \<lambda>_. 0)
\<longleftrightarrow>Simple_Network_Language_Model_Checking.has_deadlock A'
(map_index renum_states L\<^sub>0, map_of (map (\<lambda>(x, y). (renum_vars x, y)) s\<^sub>0), \<lambda>_. 0)
" if renaming_valid
using that unfolding check_def A_def A'_def renaming_valid_def Simple_Network_Rename_Formula_def
by (elim conjE) (rule Simple_Network_Rename_Start.has_deadlock_iff'[symmetric])
note [sep_heap_rules] =
deadlock_check[
of _ _
"map renum_acts broadcast" "map (\<lambda>(a,p). (renum_vars a, p)) bounds"
"map_index (renum_automaton renum_acts renum_vars renum_clocks renum_states)
(map (conv_urge urge) automata)"
m num_states num_actions k "map_index renum_states L\<^sub>0" "map (\<lambda>(x, v). (renum_vars x, v)) s\<^sub>0",
folded preconds_sat_def A'_def renaming_valid_def,
simplified
]
show ?thesis
unfolding rename_mc_def do_rename_mc_def rename_network_def
unfolding if_True
unfolding Simple_Network_Rename_Formula_String_Defs.check_renaming[symmetric] * Let_def
unfolding A_def[symmetric] preconds_sat_def[symmetric] renaming_valid_def[symmetric]
by (sep_auto simp: deadlock_checker.refine[symmetric] split: bool.splits)
qed
paragraph \<open>Code Setup for the Model Checker\<close>
lemmas [code] =
reachability_checker_def
Alw_ev_checker_def
leadsto_checker_def
model_checker_def[unfolded PR_CONST_def]
lemmas [code] =
Prod_TA_Defs.n_ps_def
Simple_Network_Impl_Defs.n_vs_def
automaton_of_def
Simple_Network_Impl_nat_defs.pairs_by_action_impl_def
Simple_Network_Impl_nat_defs.all_actions_from_vec_def
Simple_Network_Impl_nat_defs.all_actions_by_state_def
Simple_Network_Impl_nat_defs.compute_upds_impl_def
Simple_Network_Impl_nat_defs.actions_by_state_def
Simple_Network_Impl_nat_defs.check_boundedi_def
Simple_Network_Impl_nat_defs.get_committed_def
Simple_Network_Impl_nat_defs.make_combs_def
Simple_Network_Impl_nat_defs.trans_map_def
Simple_Network_Impl_nat_defs.actions_by_state'_def
Simple_Network_Impl_nat_defs.bounds_map_def
Simple_Network_Impl_nat_defs.bin_actions_def
mk_updsi_def
lemma (in Simple_Network_Impl_nat_defs) bounded_s\<^sub>0_iff:
"bounded bounds (map_of s\<^sub>0) \<longleftrightarrow> bounded (map_of bounds') (map_of s\<^sub>0)"
unfolding bounds_def snd_conv ..
lemma int_Nat_range_iff:
"(n :: int) \<in> \<nat> \<longleftrightarrow> n \<ge> 0" for n
using zero_le_imp_eq_int unfolding Nats_def by auto
lemmas [code] =
Simple_Network_Impl_nat_ceiling_start_state_def
Simple_Network_Impl_nat_ceiling_start_state_axioms_def[
unfolded Simple_Network_Impl_nat_defs.bounded_s\<^sub>0_iff]
Simple_Network_Impl_nat_def[unfolded int_Nat_range_iff]
Simple_Network_Impl_nat_urge_def
Simple_Network_Impl_nat_urge_axioms_def
lemmas [code_unfold] = bounded_def dom_map_of_conv_image_fst
export_code Simple_Network_Impl_nat_ceiling_start_state_axioms
export_code precond_mc in SML module_name Test
export_code precond_dc checking SML
paragraph \<open>Code Setup for Renaming\<close>
lemmas [code] =
Simple_Network_Rename_Formula_String_def
Simple_Network_Impl.clk_set'_def
Simple_Network_Impl.clkp_set'_def
lemmas [code] =
Simple_Network_Rename_Defs.renum_automaton_def
Simple_Network_Rename_Defs.renum_cconstraint_def
Simple_Network_Rename_Defs.map_cconstraint_def
Simple_Network_Rename_Defs.renum_reset_def
Simple_Network_Rename_Defs.renum_upd_def
Simple_Network_Rename_Defs.renum_act_def
Simple_Network_Rename_Defs.renum_exp_def
Simple_Network_Rename_Defs.renum_bexp_def
Simple_Network_Rename_Formula_String_Defs.check_renaming_def
Simple_Network_Impl_nat_defs.check_precond_def
Simple_Network_Impl_nat_defs.check_precond1_def[unfolded int_Nat_range_iff]
Simple_Network_Impl_nat_defs.check_precond2_def[
unfolded Simple_Network_Impl_nat_defs.bounded_s\<^sub>0_iff]
lemma (in Prod_TA_Defs) states_mem_iff:
"L \<in> states \<longleftrightarrow> length L = n_ps \<and> (\<forall> i. i < n_ps \<longrightarrow>
(\<exists> (l, b, g, a, r, u, l') \<in> fst (snd (snd (fst (snd A) ! i))). L ! i = l \<or> L ! i = l'))"
unfolding states_def trans_def N_def by (auto split: prod.split)
lemmas [code_unfold] =
Prod_TA_Defs.states_mem_iff
Simple_Network_Impl.act_set_compute
Simple_Network_Impl_Defs.var_set_compute
Simple_Network_Impl_Defs.loc_set_compute
setcompr_eq_image
Simple_Network_Impl.length_automata_eq_n_ps[symmetric]
export_code rename_mc in SML module_name Test
paragraph \<open>Calculating the Clock Ceiling\<close>
context Simple_Network_Impl_nat_defs
begin
definition "clkp_inv i l \<equiv>
\<Union>g \<in> set (filter (\<lambda>(a, b). a = l) (snd (snd (snd (automata ! i))))). collect_clock_pairs (snd g)"
definition "clkp_set'' i l \<equiv>
clkp_inv i l \<union> (\<Union> (l', b, g, _) \<in> set (fst (snd (snd (automata ! i)))).
if l' = l then collect_clock_pairs g else {})"
definition
"collect_resets i l = (\<Union> (l', b, g, a, f, r, _) \<in> set (fst (snd (snd (automata ! i)))).
if l' = l then set r else {})"
context
fixes q c :: nat
begin
definition "n \<equiv> num_states q"
definition "V \<equiv> \<lambda> v. v \<le> n"
definition "
bound_g l \<equiv>
Max ({0} \<union> \<Union> ((\<lambda> (x, d). if x = c then {d} else {}) ` clkp_set'' q l))
"
definition "
bound_inv l \<equiv>
Max ({0} \<union> \<Union> ((\<lambda> (x, d). if x = c then {d} else {}) ` clkp_inv q l))
"
definition "
bound l \<equiv> max (bound_g l) (bound_inv l)
"
definition "
resets l \<equiv>
fold
(\<lambda> (l1, b, g, a, f, r, l') xs. if l1 \<noteq> l \<or> l' \<in> set xs \<or> c \<in> set r then xs else (l' # xs))
(fst (snd (snd (automata ! q))))
[]
"
text \<open>
Edges in the direction nodes to single sink.
\<close>
definition "
E' l \<equiv> resets l
"
text \<open>
Turning around the edges to obtain a single source shortest paths problem.
\<close>
(* XXX Tune for efficiency *)
definition "
E l \<equiv> if l = n then [0..<n] else filter (\<lambda> l'. l \<in> set (E' l')) [0..<n]
"
text \<open>
Weights already turned around.
\<close>
definition "
W l l' \<equiv> if l = n then - bound l' else 0
"
definition G where "
G \<equiv> \<lparr> gi_V = V, gi_E = E, gi_V0 = [n], \<dots> = W \<rparr>
"
definition "
local_ceiling_single \<equiv>
let
w = calc_shortest_scc_paths G n
in
map (\<lambda> x. case x of None \<Rightarrow> 0 | Some x \<Rightarrow> nat(-x)) w
"
end
definition "
local_ceiling \<equiv>
rev $
fold
(\<lambda> q xs.
(\<lambda> x. rev x # xs) $
fold
(\<lambda> l xs.
(\<lambda> x. (0 # rev x) # xs) $
fold
(\<lambda> c xs. local_ceiling_single q c ! l # xs)
[1..<Suc m]
[]
)
[0..<n q]
[]
)
[0..<n_ps]
[]
"
end
lemmas [code] =
Simple_Network_Impl_nat_defs.local_ceiling_def
Simple_Network_Impl_nat_defs.local_ceiling_single_def
Simple_Network_Impl_nat_defs.n_def
Simple_Network_Impl_nat_defs.G_def
Simple_Network_Impl_nat_defs.W_def
Simple_Network_Impl_nat_defs.V_def
Simple_Network_Impl_nat_defs.E'_def
Simple_Network_Impl_nat_defs.E_def
Simple_Network_Impl_nat_defs.resets_def
Simple_Network_Impl_nat_defs.bound_def
Simple_Network_Impl_nat_defs.bound_inv_def
Simple_Network_Impl_nat_defs.bound_g_def
Simple_Network_Impl_nat_defs.collect_resets_def
Simple_Network_Impl_nat_defs.clkp_set''_def
Simple_Network_Impl_nat_defs.clkp_inv_def
export_code Simple_Network_Impl_nat_defs.local_ceiling checking SML_imp
paragraph \<open>Calculating the Renaming\<close>
definition "mem_assoc x = list_ex (\<lambda>(y, _). x = y)"
definition "mk_renaming str xs \<equiv>
do {
mapping \<leftarrow> fold_error
(\<lambda>x m.
if mem_assoc x m then Error [STR ''Duplicate name: '' + str x] else (x,length m) # m |> Result
) xs [];
Result (let
m = map_of mapping;
f = (\<lambda>x.
case m x of
None \<Rightarrow> let _ = println (STR ''Key error: '' + str x) in undefined
| Some v \<Rightarrow> v);
m = map_of (map prod.swap mapping);
f_inv = (\<lambda>x.
case m x of
None \<Rightarrow> let _ = println (STR ''Key error: '' + String.implode (show x)) in undefined
| Some v \<Rightarrow> v)
in (f, f_inv)
)
}"
definition
"extend_domain m d n \<equiv>
let
(i, xs) = fold
(\<lambda>x (i, xs). if x \<in> set d then (i + 1, (x, i + 1) # xs) else (i, xs)) d (n, []);
m' = map_of xs
in
(\<lambda>x. if x \<in> set d then the (m' x) else m x)"
(* Unused *)
(* Unused *)
lemma is_result_assert_msg_iff[simp]:
"is_result (assert_msg b m r) \<longleftrightarrow> is_result r \<and> b"
unfolding assert_msg_def by simp
(* Unused *)
lemma
"is_result (e |> assert_msg b1 m |> assert_msg b2 m2) \<longleftrightarrow> is_result e \<and> b1 \<and> b2"
by simp
context Simple_Network_Impl
begin
definition action_set where
"action_set \<equiv>
(\<Union>(_, _, trans, _) \<in> set automata. \<Union>(_, _, _, a, _, _, _) \<in> set trans. set_act a)
\<union> set broadcast"
definition loc_set' where
"loc_set' p = (\<Union>(l, _, _, _, _, _, l')\<in>set (fst (snd (snd (automata ! p)))). {l, l'})" for p
end
definition
"concat_str = String.implode o concat o map String.explode"
paragraph \<open>Unsafe Glue Code\<close>
definition list_of_set' :: "'a set \<Rightarrow> 'a list" where
"list_of_set' xs = undefined"
definition list_of_set :: "'a set \<Rightarrow> 'a list" where
"list_of_set xs = list_of_set' xs |> remdups"
code_printing
constant list_of_set' \<rightharpoonup> (SML) "(fn Set xs => xs) _"
and (OCaml) "(fun x -> match x with Set xs -> xs) _"
definition
"mk_renaming' xs \<equiv> mk_renaming (String.implode o show) xs"
definition "make_renaming \<equiv> \<lambda> broadcast automata bounds.
let
action_set = Simple_Network_Impl.action_set automata broadcast |> list_of_set;
clk_set = Simple_Network_Impl.clk_set' automata |> list_of_set;
clk_set = clk_set @ [STR ''_urge''];
loc_set' = (\<lambda>i. Simple_Network_Impl.loc_set' automata i |> list_of_set);
loc_set = Prod_TA_Defs.loc_set
(set broadcast, map automaton_of automata, map_of bounds);
loc_set_diff = (\<lambda>i. loc_set - Simple_Network_Impl.loc_set' automata i |> list_of_set);
loc_set = list_of_set loc_set;
var_set = Prod_TA_Defs.var_set
(set broadcast, map automaton_of automata, map_of bounds) |> list_of_set;
n_ps = length automata;
num_actions = length action_set;
m = length (remdups clk_set);
num_states_list = map (\<lambda>i. loc_set' i |> remdups |> length) [0..<n_ps];
num_states = (\<lambda>i. num_states_list ! i);
mk_renaming = mk_renaming (\<lambda>x. x)
in do {
((renum_acts, _), (renum_clocks, inv_renum_clocks), (renum_vars, inv_renum_vars)) \<leftarrow>
mk_renaming action_set <|> mk_renaming clk_set <|> mk_renaming var_set;
let renum_clocks = Suc o renum_clocks;
let inv_renum_clocks = (\<lambda>c. if c = 0 then STR ''0'' else inv_renum_clocks (c - 1));
renum_states_list' \<leftarrow> combine_map (\<lambda>i. mk_renaming' (loc_set' i)) [0..<n_ps];
let renum_states_list = map fst renum_states_list';
let renum_states_list = map_index
(\<lambda>i m. extend_domain m (loc_set_diff i) (length (loc_set' i))) renum_states_list;
let renum_states = (\<lambda>i. renum_states_list ! i);
let inv_renum_states = (\<lambda>i. map snd renum_states_list' ! i);
assert (fst ` set bounds \<subseteq> set var_set)
STR ''State variables are declared but do not appear in model'';
Result (m, num_states, num_actions, renum_acts, renum_vars, renum_clocks, renum_states,
inv_renum_states, inv_renum_vars, inv_renum_clocks)
}"
definition "preproc_mc \<equiv> \<lambda>dc ids_to_names (broadcast, automata, bounds) L\<^sub>0 s\<^sub>0 formula.
let _ = println (STR ''Make renaming'') in
case make_renaming broadcast automata bounds of
Error e \<Rightarrow> return (Error e)
| Result (m, num_states, num_actions, renum_acts, renum_vars, renum_clocks, renum_states,
inv_renum_states, inv_renum_vars, inv_renum_clocks) \<Rightarrow> do {
let _ = println (STR ''Renaming'');
let (broadcast', automata', bounds') = rename_network
broadcast bounds automata renum_acts renum_vars renum_clocks renum_states;
let _ = println (STR ''Calculating ceiling'');
let k = Simple_Network_Impl_nat_defs.local_ceiling broadcast' bounds' automata' m num_states;
let _ = println (STR ''Running model checker'');
let inv_renum_states = (\<lambda>i. ids_to_names i o inv_renum_states i);
r \<leftarrow> rename_mc dc broadcast bounds automata k STR ''_urge'' L\<^sub>0 s\<^sub>0 formula
m num_states num_actions renum_acts renum_vars renum_clocks renum_states
inv_renum_states inv_renum_vars inv_renum_clocks;
return (Result r)
}
"
definition
"err s = Error [s]"
definition
"do_preproc_mc \<equiv> \<lambda>dc ids_to_names (broadcast, automata, bounds) L\<^sub>0 s\<^sub>0 formula. do {
r \<leftarrow> preproc_mc dc ids_to_names (broadcast, automata, bounds) L\<^sub>0 s\<^sub>0 formula;
return (case r of
Error es \<Rightarrow>
intersperse (STR ''\<newline>'') es
|> concat_str
|> (\<lambda>e. STR ''Error during preprocessing:\<newline>'' + e)
|> err
| Result Renaming_Failed \<Rightarrow> STR ''Renaming failed'' |> err
| Result Preconds_Unsat \<Rightarrow> STR ''Input invalid'' |> err
| Result Unsat \<Rightarrow>
(if dc then STR ''Model has no deadlock!'' else STR ''Property is not satisfied!'') |> Result
| Result Sat \<Rightarrow>
(if dc then STR ''Model has a deadlock!'' else STR ''Property is satisfied!'') |> Result
)
}"
lemmas [code] =
Simple_Network_Impl.action_set_def
Simple_Network_Impl.loc_set'_def
export_code do_preproc_mc in SML module_name Main
definition parse where
"parse parser s \<equiv> case parse_all lx_ws parser s of
Inl e \<Rightarrow> Error [e () ''Parser: '' |> String.implode]
| Inr r \<Rightarrow> Result r"
definition get_nat :: "string \<Rightarrow> JSON \<Rightarrow> nat Error_List_Monad.result" where
"get_nat s json \<equiv> case json of
Object as \<Rightarrow> Error []
| _ \<Rightarrow> Error [STR ''JSON Get: expected object'']
" for json
definition of_object :: "JSON \<Rightarrow> (string \<rightharpoonup> JSON) Error_List_Monad.result" where
"of_object json \<equiv> case json of
Object as \<Rightarrow> map_of as |> Result
| _ \<Rightarrow> Error [STR ''json_to_map: expected object'']
" for json
definition get where
"get m x \<equiv> case m x of
None \<Rightarrow> Error [STR ''(Get) key not found: '' + String.implode (show x)]
| Some a \<Rightarrow> Result a"
definition
"get_default def m x \<equiv> case m x of None \<Rightarrow> def | Some a \<Rightarrow> a"
definition default where
"default def x \<equiv> case x of Result s \<Rightarrow> s | Error e \<Rightarrow> def"
definition of_array where
"of_array json \<equiv> case json of
JSON.Array s \<Rightarrow> Result s
| _ \<Rightarrow> Error [STR ''of_array: expected sequence'']
" for json
definition of_string where
"of_string json \<equiv> case json of
JSON.String s \<Rightarrow> Result (String.implode s)
| _ \<Rightarrow> Error [STR ''of_array: expected sequence'']
" for json
definition of_nat where
"of_nat json \<equiv> case json of
JSON.Nat n \<Rightarrow> Result n
| _ \<Rightarrow> Error [STR ''of_nat: expected natural number'']
" for json
definition of_int where
"of_int json \<equiv> case json of
JSON.Int n \<Rightarrow> Result n
| _ \<Rightarrow> Error [STR ''of_int: expected integral number'']
" for json
definition [consuming]:
"lx_underscore = exactly ''_'' with (\<lambda>_. CHR ''_'')"
definition [consuming]:
"lx_hyphen = exactly ''-'' with (\<lambda>_. CHR ''-'')"
definition [consuming]:
"ta_var_ident \<equiv>
(lx_alphanum \<parallel> lx_underscore)
-- Parser_Combinator.repeat (lx_alphanum \<parallel> lx_underscore \<parallel> lx_hyphen)
with uncurry (#)
"
definition [consuming]:
"parse_bound \<equiv> ta_var_ident --
exactly ''['' *-- lx_int -- exactly '':'' *-- lx_int --* exactly '']''"
definition "parse_bounds \<equiv> parse_list' (lx_ws *-- parse_bound with (\<lambda>(s,p). (String.implode s, p)))"
lemma
"parse parse_bounds (STR ''id[-1:2], id[-1:0]'')
= Result [(STR ''id'', -1, 2), (STR ''id'', -1, 0)]"
by eval
lemma "parse parse_bounds (STR '''') = Result []"
by eval
definition [consuming]:
"scan_var = ta_var_ident"
abbreviation seq_ignore_left_ws (infixr "**--" 60)
where "p **-- q \<equiv> token p *-- q" for p q
abbreviation seq_ignore_right_ws (infixr "--**" 60)
where "p --** q \<equiv> token p --* q" for p q
abbreviation seq_ws (infixr "---" 60)
where "seq_ws p q \<equiv> token p -- q" for p q
definition scan_acconstraint where [unfolded Let_def, consuming]:
"scan_acconstraint \<equiv>
let scan =
(\<lambda>s c. scan_var --- exactly s **-- token lx_int with (\<lambda>(x, y). c (String.implode x) y)) in
(
scan ''<'' lt \<parallel>
scan ''<='' le \<parallel>
scan ''=='' eq \<parallel>
scan ''='' eq \<parallel>
scan ''>='' ge \<parallel>
scan ''>'' gt
)
"
definition [consuming]:
"scan_parens lparen rparen inner \<equiv> exactly lparen **-- inner --** token (exactly rparen)"
definition [consuming]: "scan_loc \<equiv>
(scan_var --- (exactly ''.'' *-- scan_var))
with (\<lambda> (p, s). loc (String.implode p) (String.implode s))"
definition [consuming]: "scan_bexp_elem \<equiv> scan_acconstraint \<parallel> scan_loc"
abbreviation "scan_parens' \<equiv> scan_parens ''('' '')''"
definition [consuming]: "scan_infix_pair a b s \<equiv> a --- exactly s **-- token b"
lemma [fundef_cong]:
assumes "\<And>l2. ll_fuel l2 \<le> ll_fuel l' \<Longrightarrow> A l2 = A' l2"
assumes "\<And>l2. ll_fuel l2 + (if length s > 0 then 1 else 0) \<le> ll_fuel l' \<Longrightarrow> B l2 = B' l2"
assumes "s = s'" "l=l'"
shows "scan_infix_pair A B s l = scan_infix_pair A' B' s' l'"
using assms unfolding scan_infix_pair_def gen_token_def
by (cases s; intro Parser_Combinator.bind_cong repeat_cong assms) auto
lemma [fundef_cong]:
assumes "\<And>l2. ll_fuel l2 < ll_fuel l \<Longrightarrow> A l2 = A' l2" "l = l'"
shows "scan_parens' A l = scan_parens' A' l'"
using assms unfolding scan_parens_def gen_token_def
by (intro Parser_Combinator.bind_cong repeat_cong assms) auto
lemma token_cong[fundef_cong]:
assumes "\<And>l2. ll_fuel l2 \<le> ll_fuel l \<Longrightarrow> A l2 = A' l2" "l = l'"
shows "token A l = token A' l'"
using assms unfolding scan_parens_def gen_token_def
by (intro Parser_Combinator.bind_cong repeat_cong assms) auto
lemma is_cparser_scan_parens'[parser_rules]:
"is_cparser (scan_parens' a)"
unfolding scan_parens_def by simp
fun aexp and mexp and scan_exp and scan_7 and scan_6 and scan_0 where
"aexp ::=
token lx_int with exp.const \<parallel> token scan_var with exp.var o String.implode \<parallel>
scan_parens' (scan_exp --- exactly ''?'' **-- scan_7 --- exactly '':'' **-- scan_exp)
with (\<lambda> (e1, b, e2). exp.if_then_else b e1 e2) \<parallel>
tk_lparen **-- scan_exp --** tk_rparen"
| "mexp ::= chainL1 aexp (multiplicative_op with (\<lambda>f a b. exp.binop f a b))"
| "scan_exp ::= chainL1 mexp (additive_op with (\<lambda>f a b. exp.binop f a b))"
| "scan_7 ::=
scan_infix_pair scan_6 scan_7 ''->'' with uncurry bexp.imply \<parallel>
scan_infix_pair scan_6 scan_7 ''||'' with uncurry bexp.or \<parallel>
scan_6" |
"scan_6 ::=
scan_infix_pair scan_0 scan_6 ''&&'' with uncurry bexp.and \<parallel>
scan_0" |
"scan_0 ::=
(exactly ''~'' \<parallel> exactly ''!'') **-- scan_parens' scan_7 with bexp.not \<parallel>
token (exactly ''true'') with (\<lambda>_. bexp.true) \<parallel>
scan_infix_pair aexp aexp ''<='' with uncurry bexp.le \<parallel>
scan_infix_pair aexp aexp ''<'' with uncurry bexp.lt \<parallel>
scan_infix_pair aexp aexp ''=='' with uncurry bexp.eq \<parallel>
scan_infix_pair aexp aexp ''>'' with uncurry bexp.gt \<parallel>
scan_infix_pair aexp aexp ''>='' with uncurry bexp.ge \<parallel>
scan_parens' scan_7"
context
fixes elem :: "(char, 'bexp) parser"
and Imply Or And :: "'bexp \<Rightarrow> 'bexp \<Rightarrow> 'bexp"
and Not :: "'bexp \<Rightarrow> 'bexp"
begin
fun scan_7' and scan_6' and scan_0' where
"scan_7' ::=
scan_infix_pair scan_6' scan_7' ''->'' with uncurry Imply \<parallel>
scan_infix_pair scan_6' scan_7' ''||'' with uncurry Or \<parallel>
scan_6'" |
"scan_6' ::=
scan_infix_pair scan_0' scan_6' ''&&'' with uncurry And \<parallel>
scan_0'" |
"scan_0' ::=
(exactly ''~'' \<parallel> exactly ''!'') **-- scan_parens' scan_7' with Not \<parallel>
elem \<parallel>
scan_parens' scan_7'"
context
assumes [parser_rules]: "is_cparser elem"
begin
lemma [parser_rules]:
"is_cparser scan_0'"
by (simp add: scan_0'.simps[abs_def])
lemma [parser_rules]:
"is_cparser scan_6'"
by (subst scan_6'.simps[abs_def]) simp
end
end
abbreviation "scan_bexp \<equiv> scan_7' scan_bexp_elem sexp.imply sexp.or sexp.and sexp.not"
lemma [parser_rules]:
"is_cparser scan_bexp"
by (subst scan_7'.simps[abs_def]) simp
lemma "parse scan_bexp (STR ''a < 3 && b>=2 || ~ (c <= 4)'')
= Result (sexp.or (and (lt STR ''a'' 3) (ge STR ''b'' 2)) (not (sexp.le STR ''c'' 4)))"
by eval
definition [consuming]: "scan_prefix p head = exactly head **-- p" for p
definition [consuming]: "scan_formula \<equiv>
scan_prefix scan_bexp ''E<>'' with formula.EX \<parallel>
scan_prefix scan_bexp ''E[]'' with EG \<parallel>
scan_prefix scan_bexp ''A<>'' with AX \<parallel>
scan_prefix scan_bexp ''A[]'' with AG \<parallel>
scan_infix_pair scan_bexp scan_bexp ''-->'' with uncurry Leadsto"
(* unused *)
lemma is_cparser_token[parser_rules]:
"is_cparser (token a)" if "is_cparser a"
using that unfolding gen_token_def by simp
definition [consuming]: "scan_action \<equiv>
(scan_var --* token (exactly ''?'')) with In o String.implode \<parallel>
(scan_var --* token (exactly ''!'')) with Out o String.implode \<parallel>
scan_var with Sil o String.implode"
abbreviation orelse (infix "orelse" 58) where
"a orelse b \<equiv> default b a"
definition
"parse_action s \<equiv> parse scan_action s orelse Sil (STR '''')"
fun chop_sexp where
"chop_sexp clocks (and a b) (cs, es) =
chop_sexp clocks a (cs, es) |> chop_sexp clocks b" |
"chop_sexp clocks (eq a b) (cs, es) =
(if a \<in> set clocks then (eq a b # cs, es) else (cs, eq a b # es))" |
"chop_sexp clocks (le a b) (cs, es) =
(if a \<in> set clocks then (le a b # cs, es) else (cs, le a b # es))" |
"chop_sexp clocks (lt a b) (cs, es) =
(if a \<in> set clocks then (lt a b # cs, es) else (cs, lt a b # es))" |
"chop_sexp clocks (ge a b) (cs, es) =
(if a \<in> set clocks then (ge a b # cs, es) else (cs, ge a b # es))" |
"chop_sexp clocks (gt a b) (cs, es) =
(if a \<in> set clocks then (gt a b # cs, es) else (cs, gt a b # es))" |
"chop_sexp clocks a (cs, es) = (cs, a # es)"
fun sexp_to_acconstraint :: "(String.literal, String.literal, String.literal, int) sexp \<Rightarrow> _" where
"sexp_to_acconstraint (lt a (b :: int)) = acconstraint.LT a b" |
"sexp_to_acconstraint (le a b) = acconstraint.LE a b" |
"sexp_to_acconstraint (eq a b) = acconstraint.EQ a b" |
"sexp_to_acconstraint (ge a b) = acconstraint.GE a b" |
"sexp_to_acconstraint (gt a b) = acconstraint.GT a b"
no_notation top_assn ("true")
fun sexp_to_bexp :: "(String.literal, String.literal, String.literal, int) sexp \<Rightarrow> _" where
"sexp_to_bexp (lt a (b :: int)) = bexp.lt (exp.var a) (exp.const b) |> Result" |
"sexp_to_bexp (le a b) = bexp.le (exp.var a) (exp.const b) |> Result" |
"sexp_to_bexp (eq a b) = bexp.eq (exp.var a) (exp.const b) |> Result" |
"sexp_to_bexp (ge a b) = bexp.ge (exp.var a) (exp.const b) |> Result" |
"sexp_to_bexp (gt a b) = bexp.gt (exp.var a) (exp.const b) |> Result" |
"sexp_to_bexp (and a b) =
do {a \<leftarrow> sexp_to_bexp a; b \<leftarrow> sexp_to_bexp b; bexp.and a b |> Result}" |
"sexp_to_bexp (sexp.or a b) =
do {a \<leftarrow> sexp_to_bexp a; b \<leftarrow> sexp_to_bexp b; bexp.or a b |> Result}" |
"sexp_to_bexp (imply a b) =
do {a \<leftarrow> sexp_to_bexp a; b \<leftarrow> sexp_to_bexp b; bexp.imply a b |> Result}" |
"sexp_to_bexp x = Error [STR ''Illegal construct in binary operation'']"
(*
definition [consuming]: "scan_bexp_elem' \<equiv>
token (exactly ''true'') with (\<lambda>_. bexp.true) \<parallel>
scan_acconstraint with (\<lambda>b. case sexp_to_bexp b of Result b \<Rightarrow> b)"
abbreviation "scan_bexp' \<equiv> scan_7 scan_bexp_elem' bexp.imply bexp.or bexp.and bexp.not"
lemma [parser_rules]:
"is_cparser scan_bexp'"
by (subst scan_7.simps[abs_def]) simp
lemma token_cong[fundef_cong]:
assumes "\<And>l2. ll_fuel l2 \<le> ll_fuel l \<Longrightarrow> A l2 = A' l2" "l = l'"
shows "token A l = token A' l'"
using assms unfolding scan_parens_def gen_token_def
by (intro Parser_Combinator.bind_cong repeat_cong assms) auto
*)
(*
abbreviation additive_op where "additive_op \<equiv>
tk_plus \<then> Parser_Combinator.return (+)
\<parallel> tk_minus \<then> Parser_Combinator.return (-)"
abbreviation "multiplicative_op \<equiv>
tk_times \<then> return ( * )
\<parallel> tk_div \<then> return (div)"
abbreviation "power_op \<equiv>
tk_power \<then> return (\<lambda>a b. a^nat b)" \<comment> \<open>Note: Negative powers are treated as \<open>x\<^sup>0\<close>\<close>
*)
definition [consuming]:
"scan_update \<equiv>
scan_var --- (exactly ''='' \<parallel> exactly '':='') **-- scan_exp
with (\<lambda>(s, x). (String.implode s, x))"
abbreviation "scan_updates \<equiv> parse_list scan_update"
value "parse scan_updates (STR '' y2 := 0'')"
(* = Result [(STR ''y2'', exp.const (0 :: int))] *)
value "parse scan_updates (STR ''y2 := 0, x2 := 0'')"
(* = Result [(STR ''y2'', exp.const 0), (STR ''x2'', exp.const 0)]" *)
value "parse scan_exp (STR ''( 1 ? L == 0 : 0 )'')"
(* = Result (if_then_else (bexp.eq STR ''L'' 0) (exp.const 1) (exp.const 0)) *)
definition compile_invariant where
"compile_invariant clocks vars inv \<equiv>
let
(cs, es) = chop_sexp clocks inv ([], []);
g = map sexp_to_acconstraint cs
in
if es = []
then Result (g, bexp.true)
else do {
let e = fold (and) (tl es) (hd es);
b \<leftarrow> sexp_to_bexp e;
assert (set_bexp b \<subseteq> set vars) (String.implode (''Unknown variable in bexp: '' @ show b));
Result (g, b)
}" for inv
definition compile_invariant' where
"compile_invariant' clocks vars inv \<equiv>
if inv = STR '''' then
Result ([], bexp.true)
else do {
inv \<leftarrow> parse scan_bexp inv |> err_msg (STR ''Failed to parse guard in '' + inv);
compile_invariant clocks vars inv
}
" for inv
definition convert_node where
"convert_node clocks vars n \<equiv> do {
n \<leftarrow> of_object n;
ID \<leftarrow> get n ''id'' \<bind> of_nat;
name \<leftarrow> get n ''name'' \<bind> of_string;
inv \<leftarrow> get n ''invariant'' \<bind> of_string;
(inv, inv_vars) \<leftarrow>
compile_invariant' clocks vars inv |> err_msg (STR ''Failed to parse invariant!'');
assert (case inv_vars of bexp.true \<Rightarrow> True | _ \<Rightarrow> False)
(STR ''State invariants on nodes are not supported'');
Result ((name, ID), inv)
}"
definition convert_edge where
"convert_edge clocks vars e \<equiv> do {
e \<leftarrow> of_object e;
source \<leftarrow> get e ''source'' \<bind> of_nat;
target \<leftarrow> get e ''target'' \<bind> of_nat;
guard \<leftarrow> get e ''guard'' \<bind> of_string;
label \<leftarrow> get e ''label'' \<bind> of_string;
update \<leftarrow> get e ''update'' \<bind> of_string;
label \<leftarrow> if label = STR '''' then STR '''' |> Sil |> Result else
parse scan_action label |> err_msg (STR ''Failed to parse label in '' + label);
(g, check) \<leftarrow> compile_invariant' clocks vars guard |> err_msg (STR ''Failed to parse guard!'');
upd \<leftarrow> if update = STR '''' then Result [] else
parse scan_updates update |> err_msg (STR ''Failed to parse update in '' + update);
let resets = filter (\<lambda>x. fst x \<in> set clocks) upd;
assert
(list_all (\<lambda>(_, d). case d of exp.const x \<Rightarrow> x = 0 | _ \<Rightarrow> undefined) resets)
(STR ''Clock resets to values different from zero are not supported'');
let resets = map fst resets;
let upds = filter (\<lambda>x. fst x \<notin> set clocks) upd;
assert
(list_all (\<lambda>(x, _). x \<in> set vars) upds)
(STR ''Unknown variable in update: '' + update);
Result (source, check, g, label, upds, resets, target)
}"
definition convert_automaton where
"convert_automaton clocks vars a \<equiv> do {
nodes \<leftarrow> get a ''nodes'' \<bind> of_array;
edges \<leftarrow> get a ''edges'' \<bind> of_array;
nodes \<leftarrow> combine_map (convert_node clocks vars) nodes;
let invs = map (\<lambda> ((_, n), g). (n, g)) nodes;
let names_to_ids = map fst nodes;
assert (map fst names_to_ids |> filter (\<lambda>s. s \<noteq> STR '''') |> distinct)
(STR ''Node names are ambiguous'' + (show (map fst names_to_ids) |> String.implode));
assert (map snd names_to_ids |> distinct) (STR ''Duplicate node id'');
let ids_to_names = map_of (map prod.swap names_to_ids);
let names_to_ids = map_of names_to_ids;
let committed = default [] (get a ''committed'' \<bind> of_array);
committed \<leftarrow> combine_map of_nat committed;
let urgent = default [] (get a ''urgent'' \<bind> of_array);
urgent \<leftarrow> combine_map of_nat urgent;
edges \<leftarrow> combine_map (convert_edge clocks vars) edges;
Result (names_to_ids, ids_to_names, (committed, urgent, edges, invs))
}"
fun rename_locs_sexp where
"rename_locs_sexp f (not a) =
do {a \<leftarrow> rename_locs_sexp f a; not a |> Result}" |
"rename_locs_sexp f (imply a b) =
do {a \<leftarrow> rename_locs_sexp f a; b \<leftarrow> rename_locs_sexp f b; imply a b |> Result}" |
"rename_locs_sexp f (sexp.or a b) =
do {a \<leftarrow> rename_locs_sexp f a; b \<leftarrow> rename_locs_sexp f b; sexp.or a b |> Result}" |
"rename_locs_sexp f (and a b) =
do {a \<leftarrow> rename_locs_sexp f a; b \<leftarrow> rename_locs_sexp f b; and a b |> Result}" |
"rename_locs_sexp f (loc n x) = do {x \<leftarrow> f n x; loc n x |> Result}" |
"rename_locs_sexp f (eq a b) = Result (eq a b)" |
"rename_locs_sexp f (lt a b) = Result (lt a b)" |
"rename_locs_sexp f (le a b) = Result (le a b)" |
"rename_locs_sexp f (ge a b) = Result (ge a b)" |
"rename_locs_sexp f (gt a b) = Result (gt a b)"
fun rename_locs_formula where
"rename_locs_formula f (formula.EX \<phi>) = rename_locs_sexp f \<phi> \<bind> Result o formula.EX" |
"rename_locs_formula f (EG \<phi>) = rename_locs_sexp f \<phi> \<bind> Result o EG" |
"rename_locs_formula f (AX \<phi>) = rename_locs_sexp f \<phi> \<bind> Result o AX" |
"rename_locs_formula f (AG \<phi>) = rename_locs_sexp f \<phi> \<bind> Result o AG" |
"rename_locs_formula f (Leadsto \<phi> \<psi>) =
do {\<phi> \<leftarrow> rename_locs_sexp f \<phi>; \<psi> \<leftarrow> rename_locs_sexp f \<psi>; Leadsto \<phi> \<psi> |> Result}"
definition convert :: "JSON \<Rightarrow>
((nat \<Rightarrow> nat \<Rightarrow> String.literal) \<times> (String.literal \<Rightarrow> nat) \<times> String.literal list \<times>
(nat list \<times> nat list \<times>
(String.literal act, nat, String.literal, int, String.literal, int) transition list
\<times> (nat \<times> (String.literal, int) cconstraint) list) list \<times>
(String.literal \<times> int \<times> int) list \<times>
(nat, nat, String.literal, int) formula \<times> nat list \<times> (String.literal \<times> int) list
) Error_List_Monad.result" where
"convert json \<equiv> do {
all \<leftarrow> of_object json;
automata \<leftarrow> get all ''automata'';
automata \<leftarrow> of_array automata;
let broadcast = default [] (do {x \<leftarrow> get all ''broadcast''; of_array x});
broadcast \<leftarrow> combine_map of_string broadcast;
let _ = trace_level 3
(\<lambda>_. return (STR ''Broadcast channels '' + String.implode (show broadcast)));
let bounds = default (STR '''') (do {
x \<leftarrow> get all ''vars''; of_string x}
);
bounds \<leftarrow> parse parse_bounds bounds |> err_msg (STR ''Failed to parse bounds'');
clocks \<leftarrow> get all ''clocks'';
clocks \<leftarrow> of_string clocks;
clocks \<leftarrow> parse (parse_list (lx_ws *-- ta_var_ident with String.implode)) clocks
|> err_msg (STR ''Failed to parse clocks'');
formula \<leftarrow> get all ''formula'';
formula \<leftarrow> of_string formula;
formula \<leftarrow> parse scan_formula formula |> err_msg (STR ''Failed to parse formula'');
automata \<leftarrow> combine_map of_object automata;
process_names \<leftarrow> combine_map (\<lambda>a. get a ''name'' \<bind> of_string) automata;
assert (distinct process_names) (STR ''Process names are ambiguous'');
assert (locs_of_formula formula \<subseteq> set process_names) (STR ''Unknown process name in formula'');
let process_names_to_index = List_Index.index process_names;
init_locs \<leftarrow> combine_map
(\<lambda>a. do {x \<leftarrow> get a ''initial''; x \<leftarrow> of_nat x; x |> Result})
automata;
let formula = formula.map_formula process_names_to_index id id id formula;
let vars = map fst bounds;
let init_vars = map (\<lambda>x. (x, 0::int)) vars;
names_automata \<leftarrow> combine_map (convert_automaton clocks vars) automata;
let automata = map (snd o snd) names_automata;
let names = map fst names_automata;
let ids_to_names = map (fst o snd) names_automata;
let ids_to_names =
(\<lambda>p i. case (ids_to_names ! p) i of Some n \<Rightarrow> n | None \<Rightarrow> String.implode (show i));
formula \<leftarrow> rename_locs_formula (\<lambda>i. get (names ! i)) formula;
Result
(ids_to_names, process_names_to_index,
broadcast, automata, bounds, formula, init_locs, init_vars)
}" for json
paragraph \<open>Unsafe Glue Code for Printing\<close>
code_printing
constant print \<rightharpoonup> (SML) "writeln _"
and (OCaml) "print'_string _"
code_printing
constant println \<rightharpoonup> (SML) "writeln _"
and (OCaml) "print'_string _"
definition parse_convert_run_print where
"parse_convert_run_print dc s \<equiv>
case parse json s \<bind> convert of
Error es \<Rightarrow> do {let _ = map println es; return ()}
| Result (ids_to_names, _, broadcast, automata, bounds, formula, L\<^sub>0, s\<^sub>0) \<Rightarrow> do {
r \<leftarrow> do_preproc_mc dc ids_to_names (broadcast, automata, bounds) L\<^sub>0 s\<^sub>0 formula;
case r of
Error es \<Rightarrow> do {let _ = map println es; return ()}
| Result s \<Rightarrow> do {let _ = println s; return ()}
}"
definition parse_convert_run where
"parse_convert_run dc s \<equiv>
case
parse json s \<bind> (\<lambda>r.
let
s' = show r |> String.implode;
_ = trace_level 2 (\<lambda>_. return s')
in parse json s' \<bind> (\<lambda>r'.
assert (r = r') STR ''Parse-print-parse loop failed!'' \<bind> (\<lambda>_. convert r)))
of
Error es \<Rightarrow> return (Error es)
| Result (ids_to_names, _, broadcast, automata, bounds, formula, L\<^sub>0, s\<^sub>0) \<Rightarrow>
do_preproc_mc dc ids_to_names (broadcast, automata, bounds) L\<^sub>0 s\<^sub>0 formula
"
definition convert_run where
"convert_run dc json_data \<equiv>
case (
let
s' = show json_data |> String.implode;
_ = trace_level 2 (\<lambda>_. return s')
in parse json s' \<bind> (\<lambda>r'.
assert (json_data = r') STR ''Parse-print-parse loop failed!'' \<bind> (\<lambda>_. convert json_data)))
of
Error es \<Rightarrow> return (Error es)
| Result (ids_to_names, _, broadcast, automata, bounds, formula, L\<^sub>0, s\<^sub>0) \<Rightarrow>
do_preproc_mc dc ids_to_names (broadcast, automata, bounds) L\<^sub>0 s\<^sub>0 formula
"
text \<open>Eliminate Gabow statistics\<close>
code_printing
code_module Gabow_Skeleton_Statistics \<rightharpoonup> (SML) \<open>\<close>
code_printing
code_module AStatistics \<rightharpoonup> (SML) \<open>\<close>
text \<open>Delete ``junk''\<close>
code_printing code_module Bits_Integer \<rightharpoonup> (SML) \<open>\<close>
code_printing
constant stat_newnode \<rightharpoonup> (SML) "(fn x => ()) _"
| constant stat_start \<rightharpoonup> (SML) "(fn x => ()) _"
| constant stat_stop \<rightharpoonup> (SML) "(fn x => ()) _"
(* XXX Add this fix to IArray theory *)
code_printing
constant IArray.sub' \<rightharpoonup> (SML) "(Vector.sub o (fn (a, b) => (a, IntInf.toInt b)))"
code_thms Show_State_Defs.tracei
code_printing code_module "Logging" \<rightharpoonup> (SML)
\<open>
structure Logging : sig
val set_level : int -> unit
val trace : int -> (unit -> string) -> unit
val get_trace: unit -> (int * string) list
end = struct
val level = Unsynchronized.ref 0;
val messages : (int * string) list ref = Unsynchronized.ref [];
fun set_level i = level := i;
fun get_trace () = !messages;
fun trace i f =
if i > !level
then ()
else
let
val s = f ();
val _ = messages := (i, s) :: !messages;
in () end;
end
\<close>
and (Eval) \<open>\<close>
code_reserved Eval Logging
code_reserved SML Logging
code_printing constant trace_level \<rightharpoonup> (SML)
"Logging.trace (IntInf.toInt (integer'_of'_int _)) (_ ())"
and (Eval)
"(fn '_ => fn s => writeln (s ())) _ (_ ())"
text \<open>To disable state tracing:\<close>
(* code_printing
constant "Show_State_Defs.tracei" \<rightharpoonup>
(SML) "(fn n => fn show_state => fn show_clock => fn typ => fn x => ()) _ _ _"
and (OCaml) "(fun n show_state show_clock ty x -> -> ()) _ _ _" *)
export_code parse_convert_run Result Error
in SML module_name Model_Checker file "../ML/Simple_Model_Checker.sml"
export_code
convert_run Result Error String.explode int_of_integer nat_of_integer
JSON.Object JSON.Array JSON.String JSON.Int JSON.Nat JSON.Rat JSON.Boolean JSON.Null fract.Rat
in OCaml module_name Model_Checker file "../OCaml/Simple_Model_Checker.ml"
definition parse_convert_run_test where
"parse_convert_run_test dc s \<equiv> do {
x \<leftarrow> parse_convert_run dc s;
case x of
Error es \<Rightarrow> do {let _ = map println es; return (STR ''Fail'')}
| Result r \<Rightarrow> return r
}"
ML \<open>
fun assert comp exp =
if comp = exp then () else error ("Assertion failed! expected: " ^ exp ^ " but got: " ^ comp)
fun test dc file =
let
val s = file_to_string file;
in
@{code parse_convert_run_test} dc s end
\<close>
ML_val \<open>assert
(test false "/Users/wimmers/Formalizations/Timed_Automata/benchmarks/HDDI_02.muntax" ())
"Property is not satisfied!"\<close>
ML_val \<open>assert
(test true "/Users/wimmers/Formalizations/Timed_Automata/benchmarks/HDDI_02.muntax" ())
"Model has no deadlock!"\<close>
ML_val \<open>assert
(test false "/Users/wimmers/Formalizations/Timed_Automata/benchmarks/simple.muntax" ())
"Property is satisfied!"\<close>
ML_val \<open>assert
(test true "/Users/wimmers/Formalizations/Timed_Automata/benchmarks/simple.muntax" ())
"Model has no deadlock!"\<close>
ML_val \<open>assert
(test false "/Users/wimmers/Formalizations/Timed_Automata/benchmarks/light_switch.muntax" ())
"Property is satisfied!"\<close>
ML_val \<open>assert
(test true "/Users/wimmers/Formalizations/Timed_Automata/benchmarks/light_switch.muntax" ())
"Model has no deadlock!"\<close>
ML_val \<open>assert
(test false "/Users/wimmers/Formalizations/Timed_Automata/benchmarks/PM_test.muntax" ())
"Property is not satisfied!"\<close>
ML_val \<open>assert
(test true "/Users/wimmers/Formalizations/Timed_Automata/benchmarks/PM_test.muntax" ())
"Model has a deadlock!"\<close>
ML_val \<open>assert
(test false "/Users/wimmers/Formalizations/Timed_Automata/benchmarks/bridge.muntax" ())
"Property is satisfied!"\<close>
ML_val \<open>assert
(test true "/Users/wimmers/Formalizations/Timed_Automata/benchmarks/bridge.muntax" ())
"Model has no deadlock!"\<close>
ML_val \<open>assert
(test false "/Users/wimmers/Formalizations/Timed_Automata/benchmarks/fischer.muntax" ())
"Property is satisfied!"\<close>
ML_val \<open>assert
(test true "/Users/wimmers/Formalizations/Timed_Automata/benchmarks/fischer.muntax" ())
"Model has no deadlock!"\<close>
ML_val \<open>assert
(test false "/Users/wimmers/Formalizations/Timed_Automata/benchmarks/PM_all_4.muntax" ())
"Property is not satisfied!"\<close>
ML_val \<open>assert
(test true "/Users/wimmers/Formalizations/Timed_Automata/benchmarks/PM_all_4.muntax" ())
"Model has no deadlock!"\<close>
ML_val \<open>assert
(test false "/Users/wimmers/Formalizations/Timed_Automata/benchmarks/PM_3b.muntax" ())
"Property is not satisfied!"\<close>
ML_val \<open>assert
(test true "/Users/wimmers/Formalizations/Timed_Automata/benchmarks/PM_3b.muntax" ())
"Model has no deadlock!"\<close>
ML_val \<open>assert
(test true "/Users/wimmers/Formalizations/Timed_Automata/benchmarks/PM_all_1_urgent.muntax" ())
"Model has no deadlock!"\<close>
end |
function pdinv(M::AbstractMatrix; warnonfail::Bool=false) where Tv
@assert size(M,1) == size(M,2)
try
return cholesky(M)\I
catch err
warnonfail && @warn("pdinv cholesky failed ($err), trying other techniques")
end
try
return svd(M)\I
catch err
warnonfail && @warn("pdinv svd failed ($err), trying other techniques")
end
try
return pinv(M)
catch err
warnonfail && @warn("pinv failed ($err)")
end
error("Inversion failed.")
end
#for whatever reason, it seems only qr decomposition methods work for inverting a pd submatrix
#try qr, then fallback on alternate techniques
function pdinv(M::SubArray; warnonfail::Bool = false)
@assert size(M,1) == size(M,2)
try
return qr(M)\I
catch err
warnonfail && @warn("pdinv qr failed ($err), trying other techniques")
end
return pdinv(M|>typeof(parent(M)); warnonfail)
end
function pdlsq(M::TM, v::TV, ::Type{T}=eltype(M);
MtM::TMtM = M'*M, warnonfail::Bool=false) where {TM,TV,T, TMtM}
b = similar(v, size(M,2))
try
b .= cholesky(MtM)\(M'*v)
return b
catch err
warnonfail && @warn("lsq cholesky failed ($err), trying other techniques")
end
try
b .= svd(M)\v
return b
catch err
warnonfail && @warn("lsq svd failed ($err), trying other techniques")
end
try
b .= pdinv(MtM; warnonfail)*(M'*v)
return b
catch err
error("pdinv failed ($err), least squares failed!!!")
end
end
#TODO create ṽ from ω, define the correct zsections
function updateA₀!(Θ::AbstractVolumePartsMCMC{TM,TV,T};
mcmcdebug::Bool=true,
Nthreads::Int = Threads.nthreads()) where {TM<:Matrix,TV<:Vector,T}
@unpack Ψ, Ã, expand, xsection = Θ
@unpack σ², A₀, G, ω = Ψ
@unpack μA₀, VA₀inv = Θ.cc.hyper[:A₀]
dims = (K=size(Ã,1), T=size(Ã,2))
#first form a matrix for the cumulative product of G
à .= hcat(ones(T, dims.K), cumprod(G,dims=2))
#compute the precisions
τₜ = 1 ./ σ²
#Λₜ = Vector{TM}(undef, dims.T-1)
#allocate for the cross-sectional precision matrices and means
Λₜ::Vector{Matrix{T}} = [Matrix{T}(undef, dims.K, dims.K) for t in 1:(dims.T-1)]
ΛₜĀₜ::Vector{Vector{T}} = [Vector{T}(undef, dims.K) for t in 1:(dims.T-1)]
#pre-allocate for better threading
XtX::Vector{Matrix{T}} = [Matrix{T}(undef, dims.K, dims.K) for i ∈ 1:Nthreads]
Â::Vector{Vector{T}} = [Vector{T}(undef, dims.K) for i ∈ 1:Nthreads]
#ΛₜĀₜ = Vector{TV}(undef, dims.T-1)
#cache the following calculation for repeated use
VA₀invmat = Matrix(VA₀inv, dims.K, dims.K)
Vinvμ = VA₀inv*fill(μA₀, dims.K)
vMω(v,ω) = v - ω
Threads.@threads for t ∈ 1:(dims.T-1)
n::Int = Threads.threadid()
#Xₜ = genabsμₖ.(xsection[:Ã,t]', xsection[:LÃ,t]', xsection[:ws,t], xsection[:RLws,t])
#XtX[n] = Xₜ' * Xₜ
#mul!(XtX[n], Xₜ', Xₜ)
X̃ₜ = broadcast!(genabsμₖ,
xsection[:X̃, t], xsection[:Ã,t]', xsection[:LÃ,t]', xsection[:ws,t], xsection[:RLws,t])
mul!(XtX[n], X̃ₜ', X̃ₜ)
#BLAS.gemm!('T', 'N', 1.0, X̃ₜ, X̃ₜ, 0.0, XtX[n])
ṽ = broadcast!(vMω, xsection[:ṽ,t], xsection[:v,t], xsection[:ω,t])
#ṽ = xsection[:v,t] .- xsection[:ω,t]
Â[n] = pdlsq(X̃ₜ, ṽ, MtM=XtX[n], warnonfail=mcmcdebug)
Λₜ[t] .= τₜ[t] .* (XtX[n] .+ VA₀invmat)
#Āₜ[t] = pdinv(XtX .+ VA₀invmat, XtX*Â .+ Vinvμ, warnonfail=mcmcdebug)
#Āₜ = pdinv(XtX .+ VA₀invmat, warnonfail=mcmcdebug) *(XtX*Â .+ Vinvμ)
#ΛₜĀₜ[t] .= Λₜ[t] * Āₜ
ΛₜĀₜ[t] .= τₜ[t] .* (XtX[n]*Â[n] .+ Vinvμ)
#Ā[t] = (XtX + VA₀inv)\(XtX
end
#compute the multivariate parameters of the distribution
#Λ = sum(τₜ .* Λₜ)
Λ = sum(Λₜ)
Σ = pdinv(Λ, warnonfail=mcmcdebug)
if Σ ≈ Σ' #fixes some roundoff error
Σ .= (Σ .+ Σ') ./ 2
else
printmln(Σ)
error("something is wrong with Σ: !(Σ ≈ Σ')")
end
Ā = Σ * sum(ΛₜĀₜ)
#now draw conditionally
#=NOTE: from wikipedia, given vectors x₁ and x₂, x₁|x₂~N(μ,Σ) s.t.
μ = μ₁+ Σ₁₂ (Σ₂₂)⁻¹ (x₂-μ₂)
Σ = Σ₁₁-Σ₁₂ (Σ₂₂)⁻¹ Σ₂₁
"This matrix is the Schur complement of Σ22 in Σ. This means that to calculate the conditional
covariance matrix, one inverts the overall covariance matrix, drops the rows and columns
corresponding to the variables being conditioned upon, and then inverts back to get the
conditional covariance matrix." - Wikipedia
=#
#WARNING- uncomment below
for k ∈ shuffle(1:dims.K)
notk = 1:dims.K .≠ k
σ²k = Λ[k,k]^-1
#ΛMkk = pdinv(@view(Σ[notk, notk]), warnonfail=mcmcdebug)
#ΛMkk = pdinv(Σ[notk, notk], warnonfail=mcmcdebug)
ΛMkk = cholesky(Σ[notk, notk])\I
μk = Ā[k] + (Σ[k:k,notk]*ΛMkk*(A₀[notk] .- Ā[notk]))[] #unwraps a 1x1 array
A₀[k] = rand(Normal(μk, σ²k))
end
return A₀
#=WARNING- below is temporary
if Σ ≈ Σ' #fixes some roundoff error
Σ .= (Σ .+ Σ') ./ 2
else
printmln(Σ)
error("something is wrong with Σ: !(Σ ≈ Σ')")
end
#??? maybe this is the issue Ā = Σ*ΛĀ
#@info sum(abs.(Σ .- Σ'))
d = MvNormal(Ā, Σ)
return rand(d)=#
end
|
[GOAL]
C : Type u_1
inst✝ : Category.{?u.873, u_1} C
X Y : C
f : Y ⟶ X
⊢ ∀ {Y_1 Z : C} {f_1 : Y_1 ⟶ X},
(fun Z => {g | ∃ e, e ≫ f = g}) Y_1 f_1 → ∀ (g : Z ⟶ Y_1), (fun Z => {g | ∃ e, e ≫ f = g}) Z (g ≫ f_1)
[PROOFSTEP]
rintro W Z g ⟨e, rfl⟩ q
[GOAL]
case intro
C : Type u_1
inst✝ : Category.{?u.873, u_1} C
X Y : C
f : Y ⟶ X
W Z : C
e : W ⟶ Y
q : Z ⟶ W
⊢ setOf (fun g => ∃ e, e ≫ f = g) (q ≫ e ≫ f)
[PROOFSTEP]
refine ⟨q ≫ e, by simp⟩
[GOAL]
C : Type u_1
inst✝ : Category.{?u.873, u_1} C
X Y : C
f : Y ⟶ X
W Z : C
e : W ⟶ Y
q : Z ⟶ W
⊢ (q ≫ e) ≫ f = q ≫ e ≫ f
[PROOFSTEP]
simp
[GOAL]
C : Type u_1
inst✝ : Category.{u_2, u_1} C
X Y : C
f : Y ⟶ X
⊢ generate (Presieve.singleton f) = generateSingleton f
[PROOFSTEP]
ext Z g
[GOAL]
case h
C : Type u_1
inst✝ : Category.{u_2, u_1} C
X Y : C
f : Y ⟶ X
Z : C
g : Z ⟶ X
⊢ (generate (Presieve.singleton f)).arrows g ↔ (generateSingleton f).arrows g
[PROOFSTEP]
constructor
[GOAL]
case h.mp
C : Type u_1
inst✝ : Category.{u_2, u_1} C
X Y : C
f : Y ⟶ X
Z : C
g : Z ⟶ X
⊢ (generate (Presieve.singleton f)).arrows g → (generateSingleton f).arrows g
[PROOFSTEP]
rintro ⟨W, i, p, ⟨⟩, rfl⟩
[GOAL]
case h.mp.intro.intro.intro.intro.mk
C : Type u_1
inst✝ : Category.{u_2, u_1} C
X Y✝ : C
f : Y✝ ⟶ X
Z Y : C
i : Z ⟶ Y✝
⊢ (generateSingleton f).arrows (i ≫ f)
[PROOFSTEP]
exact ⟨i, rfl⟩
[GOAL]
case h.mpr
C : Type u_1
inst✝ : Category.{u_2, u_1} C
X Y : C
f : Y ⟶ X
Z : C
g : Z ⟶ X
⊢ (generateSingleton f).arrows g → (generate (Presieve.singleton f)).arrows g
[PROOFSTEP]
rintro ⟨g, h⟩
[GOAL]
case h.mpr.intro
C : Type u_1
inst✝ : Category.{u_2, u_1} C
X Y : C
f : Y ⟶ X
Z : C
g✝ : Z ⟶ X
g : Z ⟶ Y
h : g ≫ f = g✝
⊢ (generate (Presieve.singleton f)).arrows g✝
[PROOFSTEP]
exact ⟨Y, g, f, ⟨⟩, h⟩
[GOAL]
C : Type u_1
inst✝¹ : Category.{?u.7498, u_1} C
X Y : C
f : Y ⟶ X
inst✝ : EffectiveEpi f
⊢ Epi f
[PROOFSTEP]
constructor
[GOAL]
case left_cancellation
C : Type u_1
inst✝¹ : Category.{?u.7498, u_1} C
X Y : C
f : Y ⟶ X
inst✝ : EffectiveEpi f
⊢ ∀ {Z : C} (g h : X ⟶ Z), f ≫ g = f ≫ h → g = h
[PROOFSTEP]
intro W m₁ m₂ h
[GOAL]
case left_cancellation
C : Type u_1
inst✝¹ : Category.{?u.7498, u_1} C
X Y : C
f : Y ⟶ X
inst✝ : EffectiveEpi f
W : C
m₁ m₂ : X ⟶ W
h : f ≫ m₁ = f ≫ m₂
⊢ m₁ = m₂
[PROOFSTEP]
have : m₂ = EffectiveEpi.desc f (f ≫ m₂) (fun {Z} g₁ g₂ h => by simp only [← Category.assoc, h]) :=
EffectiveEpi.uniq _ _ _ _ rfl
[GOAL]
C : Type u_1
inst✝¹ : Category.{?u.7498, u_1} C
X Y : C
f : Y ⟶ X
inst✝ : EffectiveEpi f
W : C
m₁ m₂ : X ⟶ W
h✝ : f ≫ m₁ = f ≫ m₂
Z : C
g₁ g₂ : Z ⟶ Y
h : g₁ ≫ f = g₂ ≫ f
⊢ g₁ ≫ f ≫ m₂ = g₂ ≫ f ≫ m₂
[PROOFSTEP]
simp only [← Category.assoc, h]
[GOAL]
case left_cancellation
C : Type u_1
inst✝¹ : Category.{?u.7498, u_1} C
X Y : C
f : Y ⟶ X
inst✝ : EffectiveEpi f
W : C
m₁ m₂ : X ⟶ W
h : f ≫ m₁ = f ≫ m₂
this : m₂ = EffectiveEpi.desc f (f ≫ m₂) (_ : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ f ≫ m₂ = g₂ ≫ f ≫ m₂)
⊢ m₁ = m₂
[PROOFSTEP]
rw [this]
[GOAL]
case left_cancellation
C : Type u_1
inst✝¹ : Category.{?u.7498, u_1} C
X Y : C
f : Y ⟶ X
inst✝ : EffectiveEpi f
W : C
m₁ m₂ : X ⟶ W
h : f ≫ m₁ = f ≫ m₂
this : m₂ = EffectiveEpi.desc f (f ≫ m₂) (_ : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ f ≫ m₂ = g₂ ≫ f ≫ m₂)
⊢ m₁ = EffectiveEpi.desc f (f ≫ m₂) (_ : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ f ≫ m₂ = g₂ ≫ f ≫ m₂)
[PROOFSTEP]
exact EffectiveEpi.uniq _ _ _ _ h
[GOAL]
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
⊢ 𝟙 ((𝟭 C).obj (Over.mk f).left) ≫ f = (Over.mk f).hom
[PROOFSTEP]
simp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
⊢ ∀ {Z : C} (g₁ g₂ : Z ⟶ Y),
g₁ ≫ f = g₂ ≫ f →
g₁ ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
[PROOFSTEP]
intro Z g₁ g₂ h
[GOAL]
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
Z : C
g₁ g₂ : Z ⟶ Y
h : g₁ ≫ f = g₂ ≫ f
⊢ g₁ ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
[PROOFSTEP]
let Y' : D := ⟨Over.mk f, 𝟙 _, by simp⟩
[GOAL]
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
Z : C
g₁ g₂ : Z ⟶ Y
h : g₁ ≫ f = g₂ ≫ f
⊢ 𝟙 ((𝟭 C).obj (Over.mk f).left) ≫ f = (Over.mk f).hom
[PROOFSTEP]
simp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
Z : C
g₁ g₂ : Z ⟶ Y
h : g₁ ≫ f = g₂ ≫ f
Y' : D := { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
⊢ g₁ ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
[PROOFSTEP]
let Z' : D := ⟨Over.mk (g₁ ≫ f), g₁, rfl⟩
[GOAL]
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
Z : C
g₁ g₂ : Z ⟶ Y
h : g₁ ≫ f = g₂ ≫ f
Y' : D := { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
Z' : D := { obj := Over.mk (g₁ ≫ f), property := (_ : ∃ e, e ≫ f = (Over.mk (g₁ ≫ f)).hom) }
⊢ g₁ ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
[PROOFSTEP]
let g₁' : Z' ⟶ Y' := Over.homMk g₁
[GOAL]
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
Z : C
g₁ g₂ : Z ⟶ Y
h : g₁ ≫ f = g₂ ≫ f
Y' : D := { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
Z' : D := { obj := Over.mk (g₁ ≫ f), property := (_ : ∃ e, e ≫ f = (Over.mk (g₁ ≫ f)).hom) }
g₁' : Z' ⟶ Y' := Over.homMk g₁
⊢ g₁ ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
[PROOFSTEP]
let g₂' : Z' ⟶ Y' := Over.homMk g₂ (by simp [h])
[GOAL]
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
Z : C
g₁ g₂ : Z ⟶ Y
h : g₁ ≫ f = g₂ ≫ f
Y' : D := { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
Z' : D := { obj := Over.mk (g₁ ≫ f), property := (_ : ∃ e, e ≫ f = (Over.mk (g₁ ≫ f)).hom) }
g₁' : Z' ⟶ Y' := Over.homMk g₁
⊢ g₂ ≫ Y'.obj.hom = Z'.obj.hom
[PROOFSTEP]
simp [h]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
Z : C
g₁ g₂ : Z ⟶ Y
h : g₁ ≫ f = g₂ ≫ f
Y' : D := { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
Z' : D := { obj := Over.mk (g₁ ≫ f), property := (_ : ∃ e, e ≫ f = (Over.mk (g₁ ≫ f)).hom) }
g₁' : Z' ⟶ Y' := Over.homMk g₁
g₂' : Z' ⟶ Y' := Over.homMk g₂
⊢ g₁ ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
[PROOFSTEP]
change F.map g₁' ≫ _ = F.map g₂' ≫ _
[GOAL]
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
Z : C
g₁ g₂ : Z ⟶ Y
h : g₁ ≫ f = g₂ ≫ f
Y' : D := { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
Z' : D := { obj := Over.mk (g₁ ≫ f), property := (_ : ∃ e, e ≫ f = (Over.mk (g₁ ≫ f)).hom) }
g₁' : Z' ⟶ Y' := Over.homMk g₁
g₂' : Z' ⟶ Y' := Over.homMk g₂
⊢ F.map g₁' ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) } =
F.map g₂' ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
[PROOFSTEP]
simp only [S.w]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
⊢ ∀ (s : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows))
(j : FullSubcategory fun f_1 => (Sieve.generateSingleton f).arrows f_1.hom),
NatTrans.app (Presieve.cocone (Sieve.generateSingleton f).arrows).ι j ≫
(fun S =>
EffectiveEpiStruct.desc Hf
(NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) })
(_ :
∀ {Z : C} (g₁ g₂ : Z ⟶ Y) (h : g₁ ≫ f = g₂ ≫ f),
let Y' := { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) };
let Z' := { obj := Over.mk (g₁ ≫ f), property := (_ : ∃ e, e ≫ f = (Over.mk (g₁ ≫ f)).hom) };
let g₁' := Over.homMk g₁;
let g₂' := Over.homMk g₂;
F.map g₁' ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) } =
F.map g₂' ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }))
s =
NatTrans.app s.ι j
[PROOFSTEP]
rintro S ⟨T, g, hT⟩
[GOAL]
case mk.intro
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
T : Over X
g : (𝟭 C).obj T.left ⟶ Y
hT : g ≫ f = T.hom
⊢ NatTrans.app (Presieve.cocone (Sieve.generateSingleton f).arrows).ι
{ obj := T, property := (_ : ∃ e, e ≫ f = T.hom) } ≫
(fun S =>
EffectiveEpiStruct.desc Hf
(NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) })
(_ :
∀ {Z : C} (g₁ g₂ : Z ⟶ Y) (h : g₁ ≫ f = g₂ ≫ f),
let Y' := { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) };
let Z' := { obj := Over.mk (g₁ ≫ f), property := (_ : ∃ e, e ≫ f = (Over.mk (g₁ ≫ f)).hom) };
let g₁' := Over.homMk g₁;
let g₂' := Over.homMk g₂;
F.map g₁' ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) } =
F.map g₂' ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }))
S =
NatTrans.app S.ι { obj := T, property := (_ : ∃ e, e ≫ f = T.hom) }
[PROOFSTEP]
dsimp
[GOAL]
case mk.intro
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
T : Over X
g : (𝟭 C).obj T.left ⟶ Y
hT : g ≫ f = T.hom
⊢ T.hom ≫
EffectiveEpiStruct.desc Hf (NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = f) })
(_ :
∀ {Z : C} (g₁ g₂ : Z ⟶ Y),
g₁ ≫ f = g₂ ≫ f →
g₁ ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = f) } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = f) }) =
NatTrans.app S.ι { obj := T, property := (_ : ∃ e, e ≫ f = T.hom) }
[PROOFSTEP]
nth_rewrite 1 [← hT, Category.assoc, Hf.fac]
[GOAL]
case mk.intro
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
T : Over X
g : (𝟭 C).obj T.left ⟶ Y
hT : g ≫ f = T.hom
⊢ g ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = f) } =
NatTrans.app S.ι { obj := T, property := (_ : ∃ e, e ≫ f = T.hom) }
[PROOFSTEP]
let y : D := ⟨Over.mk f, 𝟙 _, by simp⟩
[GOAL]
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
T : Over X
g : (𝟭 C).obj T.left ⟶ Y
hT : g ≫ f = T.hom
⊢ 𝟙 ((𝟭 C).obj (Over.mk f).left) ≫ f = (Over.mk f).hom
[PROOFSTEP]
simp
[GOAL]
case mk.intro
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
T : Over X
g : (𝟭 C).obj T.left ⟶ Y
hT : g ≫ f = T.hom
y : D := { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
⊢ g ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = f) } =
NatTrans.app S.ι { obj := T, property := (_ : ∃ e, e ≫ f = T.hom) }
[PROOFSTEP]
let x : D := ⟨Over.mk T.hom, g, hT⟩
[GOAL]
case mk.intro
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
T : Over X
g : (𝟭 C).obj T.left ⟶ Y
hT : g ≫ f = T.hom
y : D := { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
x : D := { obj := Over.mk T.hom, property := (_ : ∃ e, e ≫ f = (Over.mk T.hom).hom) }
⊢ g ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = f) } =
NatTrans.app S.ι { obj := T, property := (_ : ∃ e, e ≫ f = T.hom) }
[PROOFSTEP]
let g' : x ⟶ y := Over.homMk g
[GOAL]
case mk.intro
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
T : Over X
g : (𝟭 C).obj T.left ⟶ Y
hT : g ≫ f = T.hom
y : D := { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
x : D := { obj := Over.mk T.hom, property := (_ : ∃ e, e ≫ f = (Over.mk T.hom).hom) }
g' : x ⟶ y := Over.homMk g
⊢ g ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = f) } =
NatTrans.app S.ι { obj := T, property := (_ : ∃ e, e ≫ f = T.hom) }
[PROOFSTEP]
change F.map g' ≫ _ = _
[GOAL]
case mk.intro
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
T : Over X
g : (𝟭 C).obj T.left ⟶ Y
hT : g ≫ f = T.hom
y : D := { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
x : D := { obj := Over.mk T.hom, property := (_ : ∃ e, e ≫ f = (Over.mk T.hom).hom) }
g' : x ⟶ y := Over.homMk g
⊢ F.map g' ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = f) } =
NatTrans.app S.ι { obj := T, property := (_ : ∃ e, e ≫ f = T.hom) }
[PROOFSTEP]
rw [S.w]
[GOAL]
case mk.intro
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
T : Over X
g : (𝟭 C).obj T.left ⟶ Y
hT : g ≫ f = T.hom
y : D := { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
x : D := { obj := Over.mk T.hom, property := (_ : ∃ e, e ≫ f = (Over.mk T.hom).hom) }
g' : x ⟶ y := Over.homMk g
⊢ NatTrans.app S.ι x = NatTrans.app S.ι { obj := T, property := (_ : ∃ e, e ≫ f = T.hom) }
[PROOFSTEP]
rfl
[GOAL]
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
⊢ ∀ (s : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows))
(m : (Presieve.cocone (Sieve.generateSingleton f).arrows).pt ⟶ s.pt),
(∀ (j : FullSubcategory fun f_1 => (Sieve.generateSingleton f).arrows f_1.hom),
NatTrans.app (Presieve.cocone (Sieve.generateSingleton f).arrows).ι j ≫ m = NatTrans.app s.ι j) →
m =
(fun S =>
EffectiveEpiStruct.desc Hf
(NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) })
(_ :
∀ {Z : C} (g₁ g₂ : Z ⟶ Y) (h : g₁ ≫ f = g₂ ≫ f),
let Y' := { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) };
let Z' := { obj := Over.mk (g₁ ≫ f), property := (_ : ∃ e, e ≫ f = (Over.mk (g₁ ≫ f)).hom) };
let g₁' := Over.homMk g₁;
let g₂' := Over.homMk g₂;
F.map g₁' ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) } =
F.map g₂' ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }))
s
[PROOFSTEP]
intro S m hm
[GOAL]
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
m : (Presieve.cocone (Sieve.generateSingleton f).arrows).pt ⟶ S.pt
hm :
∀ (j : FullSubcategory fun f_1 => (Sieve.generateSingleton f).arrows f_1.hom),
NatTrans.app (Presieve.cocone (Sieve.generateSingleton f).arrows).ι j ≫ m = NatTrans.app S.ι j
⊢ m =
(fun S =>
EffectiveEpiStruct.desc Hf
(NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) })
(_ :
∀ {Z : C} (g₁ g₂ : Z ⟶ Y) (h : g₁ ≫ f = g₂ ≫ f),
let Y' := { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) };
let Z' := { obj := Over.mk (g₁ ≫ f), property := (_ : ∃ e, e ≫ f = (Over.mk (g₁ ≫ f)).hom) };
let g₁' := Over.homMk g₁;
let g₂' := Over.homMk g₂;
F.map g₁' ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) } =
F.map g₂' ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }))
S
[PROOFSTEP]
dsimp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
m : (Presieve.cocone (Sieve.generateSingleton f).arrows).pt ⟶ S.pt
hm :
∀ (j : FullSubcategory fun f_1 => (Sieve.generateSingleton f).arrows f_1.hom),
NatTrans.app (Presieve.cocone (Sieve.generateSingleton f).arrows).ι j ≫ m = NatTrans.app S.ι j
⊢ m =
EffectiveEpiStruct.desc Hf (NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = f) })
(_ :
∀ {Z : C} (g₁ g₂ : Z ⟶ Y),
g₁ ≫ f = g₂ ≫ f →
g₁ ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = f) } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk f, property := (_ : ∃ e, e ≫ f = f) })
[PROOFSTEP]
generalize_proofs h1 h2
[GOAL]
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
m : (Presieve.cocone (Sieve.generateSingleton f).arrows).pt ⟶ S.pt
hm :
∀ (j : FullSubcategory fun f_1 => (Sieve.generateSingleton f).arrows f_1.hom),
NatTrans.app (Presieve.cocone (Sieve.generateSingleton f).arrows).ι j ≫ m = NatTrans.app S.ι j
h1 : ∃ e, e ≫ f = f
h2 :
∀ {Z : C} (g₁ g₂ : Z ⟶ Y),
g₁ ≫ f = g₂ ≫ f →
g₁ ≫ NatTrans.app S.ι { obj := Over.mk f, property := h1 } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk f, property := h1 }
⊢ m = EffectiveEpiStruct.desc Hf (NatTrans.app S.ι { obj := Over.mk f, property := h1 }) h2
[PROOFSTEP]
apply Hf.uniq _ h2
[GOAL]
case a
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
m : (Presieve.cocone (Sieve.generateSingleton f).arrows).pt ⟶ S.pt
hm :
∀ (j : FullSubcategory fun f_1 => (Sieve.generateSingleton f).arrows f_1.hom),
NatTrans.app (Presieve.cocone (Sieve.generateSingleton f).arrows).ι j ≫ m = NatTrans.app S.ι j
h1 : ∃ e, e ≫ f = f
h2 :
∀ {Z : C} (g₁ g₂ : Z ⟶ Y),
g₁ ≫ f = g₂ ≫ f →
g₁ ≫ NatTrans.app S.ι { obj := Over.mk f, property := h1 } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk f, property := h1 }
⊢ f ≫ m = NatTrans.app S.ι { obj := Over.mk f, property := h1 }
[PROOFSTEP]
exact hm ⟨Over.mk f, 𝟙 _, by simp⟩
[GOAL]
C : Type u_1
inst✝ : Category.{?u.8526, u_1} C
X Y : C
f : Y ⟶ X
Hf : EffectiveEpiStruct f
D : Type (max u_1 ?u.8526) := FullSubcategory fun T => (Sieve.generateSingleton f).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateSingleton f).arrows
S : Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows)
m : (Presieve.cocone (Sieve.generateSingleton f).arrows).pt ⟶ S.pt
hm :
∀ (j : FullSubcategory fun f_1 => (Sieve.generateSingleton f).arrows f_1.hom),
NatTrans.app (Presieve.cocone (Sieve.generateSingleton f).arrows).ι j ≫ m = NatTrans.app S.ι j
h1 : ∃ e, e ≫ f = f
h2 :
∀ {Z : C} (g₁ g₂ : Z ⟶ Y),
g₁ ≫ f = g₂ ≫ f →
g₁ ≫ NatTrans.app S.ι { obj := Over.mk f, property := h1 } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk f, property := h1 }
⊢ 𝟙 ((𝟭 C).obj (Over.mk f).left) ≫ f = (Over.mk f).hom
[PROOFSTEP]
simp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
⊢ ∀ ⦃X_1 Y_1 : FullSubcategory fun f_1 => (Sieve.generateSingleton f).arrows f_1.hom⦄ (f_1 : X_1 ⟶ Y_1),
(Presieve.diagram (Sieve.generateSingleton f).arrows).map f_1 ≫
(fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e)
Y_1 =
(fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e)
X_1 ≫
((Functor.const (FullSubcategory fun f_2 => (Sieve.generateSingleton f).arrows f_2.hom)).obj W).map f_1
[PROOFSTEP]
rintro ⟨A, hA⟩ ⟨B, hB⟩ (q : A ⟶ B)
[GOAL]
case mk.mk
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
A : Over X
hA : (Sieve.generateSingleton f).arrows A.hom
B : Over X
hB : (Sieve.generateSingleton f).arrows B.hom
q : A ⟶ B
⊢ (Presieve.diagram (Sieve.generateSingleton f).arrows).map q ≫
(fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e)
{ obj := B, property := hB } =
(fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e)
{ obj := A, property := hA } ≫
((Functor.const (FullSubcategory fun f_1 => (Sieve.generateSingleton f).arrows f_1.hom)).obj W).map q
[PROOFSTEP]
dsimp
[GOAL]
case mk.mk
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
A : Over X
hA : (Sieve.generateSingleton f).arrows A.hom
B : Over X
hB : (Sieve.generateSingleton f).arrows B.hom
q : A ⟶ B
⊢ q.left ≫ Exists.choose hB ≫ e = (Exists.choose hA ≫ e) ≫ 𝟙 W
[PROOFSTEP]
simp only [← Category.assoc, Category.comp_id]
[GOAL]
case mk.mk
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
A : Over X
hA : (Sieve.generateSingleton f).arrows A.hom
B : Over X
hB : (Sieve.generateSingleton f).arrows B.hom
q : A ⟶ B
⊢ (q.left ≫ Exists.choose hB) ≫ e = Exists.choose hA ≫ e
[PROOFSTEP]
apply h
[GOAL]
case mk.mk.a
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
A : Over X
hA : (Sieve.generateSingleton f).arrows A.hom
B : Over X
hB : (Sieve.generateSingleton f).arrows B.hom
q : A ⟶ B
⊢ (q.left ≫ Exists.choose hB) ≫ f = Exists.choose hA ≫ f
[PROOFSTEP]
rw [Category.assoc, hB.choose_spec, hA.choose_spec, Over.w]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
⊢ ∀ {W : C} (e : Y ⟶ W) (h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e),
f ≫
(fun {W} e h => IsColimit.desc Hf (aux e (_ : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e))) e
(_ : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) =
e
[PROOFSTEP]
intro W e h
[GOAL]
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
⊢ f ≫
(fun {W} e h => IsColimit.desc Hf (aux e (_ : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e))) e
(_ : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) =
e
[PROOFSTEP]
dsimp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
⊢ f ≫
IsColimit.desc Hf
{ pt := W, ι := NatTrans.mk fun x => Exists.choose (_ : (Sieve.generateSingleton f).arrows x.obj.hom) ≫ e } =
e
[PROOFSTEP]
have := Hf.fac (aux e h) ⟨Over.mk f, 𝟙 _, by simp⟩
[GOAL]
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
⊢ 𝟙 ((𝟭 C).obj (Over.mk f).left) ≫ f = (Over.mk f).hom
[PROOFSTEP]
simp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
this :
NatTrans.app (Presieve.cocone (Sieve.generateSingleton f).arrows).ι
{ obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) } ≫
IsColimit.desc Hf (aux e (_ : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e)) =
NatTrans.app (aux e (_ : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e)).ι
{ obj := Over.mk f, property := (_ : ∃ e, e ≫ f = (Over.mk f).hom) }
⊢ f ≫
IsColimit.desc Hf
{ pt := W, ι := NatTrans.mk fun x => Exists.choose (_ : (Sieve.generateSingleton f).arrows x.obj.hom) ≫ e } =
e
[PROOFSTEP]
dsimp at this
[GOAL]
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
this :
f ≫
IsColimit.desc Hf
{ pt := W, ι := NatTrans.mk fun x => Exists.choose (_ : (Sieve.generateSingleton f).arrows x.obj.hom) ≫ e } =
Exists.choose (_ : ∃ e, e ≫ f = f) ≫ e
⊢ f ≫
IsColimit.desc Hf
{ pt := W, ι := NatTrans.mk fun x => Exists.choose (_ : (Sieve.generateSingleton f).arrows x.obj.hom) ≫ e } =
e
[PROOFSTEP]
rw [this]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
this :
f ≫
IsColimit.desc Hf
{ pt := W, ι := NatTrans.mk fun x => Exists.choose (_ : (Sieve.generateSingleton f).arrows x.obj.hom) ≫ e } =
Exists.choose (_ : ∃ e, e ≫ f = f) ≫ e
⊢ Exists.choose (_ : ∃ e, e ≫ f = f) ≫ e = e
[PROOFSTEP]
clear this
[GOAL]
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
⊢ Exists.choose (_ : ∃ e, e ≫ f = f) ≫ e = e
[PROOFSTEP]
nth_rewrite 2 [← Category.id_comp e]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
⊢ Exists.choose (_ : ∃ e, e ≫ f = f) ≫ e = 𝟙 Y ≫ e
[PROOFSTEP]
apply h
[GOAL]
case a
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
⊢ Exists.choose (_ : ∃ e, e ≫ f = f) ≫ f = 𝟙 Y ≫ f
[PROOFSTEP]
generalize_proofs hh
[GOAL]
case a
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
hh : ∃ e, e ≫ f = f
⊢ Exists.choose hh ≫ f = 𝟙 Y ≫ f
[PROOFSTEP]
rw [hh.choose_spec, Category.id_comp]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
⊢ ∀ {W : C} (e : Y ⟶ W) (h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) (m : X ⟶ W),
f ≫ m = e →
m =
(fun {W} e h => IsColimit.desc Hf (aux e (_ : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e))) e
(_ : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e)
[PROOFSTEP]
intro W e h m hm
[GOAL]
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
m : X ⟶ W
hm : f ≫ m = e
⊢ m =
(fun {W} e h => IsColimit.desc Hf (aux e (_ : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e))) e
(_ : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e)
[PROOFSTEP]
dsimp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
m : X ⟶ W
hm : f ≫ m = e
⊢ m =
IsColimit.desc Hf
{ pt := W, ι := NatTrans.mk fun x => Exists.choose (_ : (Sieve.generateSingleton f).arrows x.obj.hom) ≫ e }
[PROOFSTEP]
apply Hf.uniq (aux e h)
[GOAL]
case x
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
m : X ⟶ W
hm : f ≫ m = e
⊢ ∀ (j : FullSubcategory fun f_1 => (Sieve.generateSingleton f).arrows f_1.hom),
NatTrans.app (Presieve.cocone (Sieve.generateSingleton f).arrows).ι j ≫ m =
NatTrans.app (aux e (_ : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e)).ι j
[PROOFSTEP]
rintro ⟨A, g, hA⟩
[GOAL]
case x.mk.intro
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
m : X ⟶ W
hm : f ≫ m = e
A : Over X
g : (𝟭 C).obj A.left ⟶ Y
hA : g ≫ f = A.hom
⊢ NatTrans.app (Presieve.cocone (Sieve.generateSingleton f).arrows).ι
{ obj := A, property := (_ : ∃ e, e ≫ f = A.hom) } ≫
m =
NatTrans.app (aux e (_ : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e)).ι
{ obj := A, property := (_ : ∃ e, e ≫ f = A.hom) }
[PROOFSTEP]
dsimp
[GOAL]
case x.mk.intro
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
m : X ⟶ W
hm : f ≫ m = e
A : Over X
g : (𝟭 C).obj A.left ⟶ Y
hA : g ≫ f = A.hom
⊢ A.hom ≫ m = Exists.choose (_ : ∃ e, e ≫ f = A.hom) ≫ e
[PROOFSTEP]
nth_rewrite 1 [← hA, Category.assoc, hm]
[GOAL]
case x.mk.intro
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
m : X ⟶ W
hm : f ≫ m = e
A : Over X
g : (𝟭 C).obj A.left ⟶ Y
hA : g ≫ f = A.hom
⊢ g ≫ e = Exists.choose (_ : ∃ e, e ≫ f = A.hom) ≫ e
[PROOFSTEP]
apply h
[GOAL]
case x.mk.intro.a
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
m : X ⟶ W
hm : f ≫ m = e
A : Over X
g : (𝟭 C).obj A.left ⟶ Y
hA : g ≫ f = A.hom
⊢ g ≫ f = Exists.choose (_ : ∃ e, e ≫ f = A.hom) ≫ f
[PROOFSTEP]
generalize_proofs hh
[GOAL]
case x.mk.intro.a
C : Type u_1
inst✝ : Category.{?u.20742, u_1} C
X Y : C
f : Y ⟶ X
Hf : IsColimit (Presieve.cocone (Sieve.generateSingleton f).arrows)
aux : {W : C} →
(e : Y ⟶ W) →
(∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e) →
Cocone (Presieve.diagram (Sieve.generateSingleton f).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } => Exists.choose hT ≫ e }
W : C
e : Y ⟶ W
h : ∀ {Z : C} (g₁ g₂ : Z ⟶ Y), g₁ ≫ f = g₂ ≫ f → g₁ ≫ e = g₂ ≫ e
m : X ⟶ W
hm : f ≫ m = e
A : Over X
g : (𝟭 C).obj A.left ⟶ Y
hA : g ≫ f = A.hom
hh : ∃ e, e ≫ f = A.hom
⊢ g ≫ f = Exists.choose hh ≫ f
[PROOFSTEP]
rwa [hh.choose_spec]
[GOAL]
C : Type u_1
inst✝ : Category.{u_2, u_1} C
X Y : C
f : Y ⟶ X
⊢ Presieve.EffectiveEpimorphic (Presieve.singleton f) ↔ EffectiveEpi f
[PROOFSTEP]
constructor
[GOAL]
case mp
C : Type u_1
inst✝ : Category.{u_2, u_1} C
X Y : C
f : Y ⟶ X
⊢ Presieve.EffectiveEpimorphic (Presieve.singleton f) → EffectiveEpi f
[PROOFSTEP]
intro (h : Nonempty _)
[GOAL]
case mp
C : Type u_1
inst✝ : Category.{u_2, u_1} C
X Y : C
f : Y ⟶ X
h : Nonempty (IsColimit (Presieve.cocone (generate (Presieve.singleton f)).arrows))
⊢ EffectiveEpi f
[PROOFSTEP]
rw [Sieve.generateSingleton_eq] at h
[GOAL]
case mp
C : Type u_1
inst✝ : Category.{u_2, u_1} C
X Y : C
f : Y ⟶ X
h : Nonempty (IsColimit (Presieve.cocone (generateSingleton f).arrows))
⊢ EffectiveEpi f
[PROOFSTEP]
constructor
[GOAL]
case mp.effectiveEpi
C : Type u_1
inst✝ : Category.{u_2, u_1} C
X Y : C
f : Y ⟶ X
h : Nonempty (IsColimit (Presieve.cocone (generateSingleton f).arrows))
⊢ Nonempty (EffectiveEpiStruct f)
[PROOFSTEP]
apply Nonempty.map (effectiveEpiStructOfIsColimit _) h
[GOAL]
case mpr
C : Type u_1
inst✝ : Category.{u_2, u_1} C
X Y : C
f : Y ⟶ X
⊢ EffectiveEpi f → Presieve.EffectiveEpimorphic (Presieve.singleton f)
[PROOFSTEP]
rintro ⟨h⟩
[GOAL]
case mpr.mk
C : Type u_1
inst✝ : Category.{u_2, u_1} C
X Y : C
f : Y ⟶ X
h : Nonempty (EffectiveEpiStruct f)
⊢ Presieve.EffectiveEpimorphic (Presieve.singleton f)
[PROOFSTEP]
show Nonempty _
[GOAL]
case mpr.mk
C : Type u_1
inst✝ : Category.{u_2, u_1} C
X Y : C
f : Y ⟶ X
h : Nonempty (EffectiveEpiStruct f)
⊢ Nonempty (IsColimit (Presieve.cocone (generate (Presieve.singleton f)).arrows))
[PROOFSTEP]
rw [Sieve.generateSingleton_eq]
[GOAL]
case mpr.mk
C : Type u_1
inst✝ : Category.{u_2, u_1} C
X Y : C
f : Y ⟶ X
h : Nonempty (EffectiveEpiStruct f)
⊢ Nonempty (IsColimit (Presieve.cocone (generateSingleton f).arrows))
[PROOFSTEP]
apply Nonempty.map (isColimitOfEffectiveEpiStruct _) h
[GOAL]
C : Type u_1
inst✝ : Category.{?u.36898, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
⊢ ∀ {Y Z : C} {f : Y ⟶ B},
(fun Y => {f | ∃ a g, g ≫ π a = f}) Y f → ∀ (g : Z ⟶ Y), (fun Y => {f | ∃ a g, g ≫ π a = f}) Z (g ≫ f)
[PROOFSTEP]
rintro Y₁ Y₂ g₁ ⟨a, q, rfl⟩ e
[GOAL]
case intro.intro
C : Type u_1
inst✝ : Category.{?u.36898, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
Y₁ Y₂ : C
a : α
q : Y₁ ⟶ X a
e : Y₂ ⟶ Y₁
⊢ setOf (fun f => ∃ a g, g ≫ π a = f) (e ≫ q ≫ π a)
[PROOFSTEP]
refine ⟨a, e ≫ q, by simp⟩
[GOAL]
C : Type u_1
inst✝ : Category.{?u.36898, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
Y₁ Y₂ : C
a : α
q : Y₁ ⟶ X a
e : Y₂ ⟶ Y₁
⊢ (e ≫ q) ≫ π a = e ≫ q ≫ π a
[PROOFSTEP]
simp
[GOAL]
C : Type u_1
inst✝ : Category.{u_3, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
⊢ generate (Presieve.ofArrows X π) = generateFamily X π
[PROOFSTEP]
ext Y g
[GOAL]
case h
C : Type u_1
inst✝ : Category.{u_3, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
Y : C
g : Y ⟶ B
⊢ (generate (Presieve.ofArrows X π)).arrows g ↔ (generateFamily X π).arrows g
[PROOFSTEP]
constructor
[GOAL]
case h.mp
C : Type u_1
inst✝ : Category.{u_3, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
Y : C
g : Y ⟶ B
⊢ (generate (Presieve.ofArrows X π)).arrows g → (generateFamily X π).arrows g
[PROOFSTEP]
rintro ⟨W, g, f, ⟨a⟩, rfl⟩
[GOAL]
case h.mp.intro.intro.intro.intro.mk
C : Type u_1
inst✝ : Category.{u_3, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
Y✝ Y : C
a : α
g : Y✝ ⟶ X a
⊢ (generateFamily X π).arrows (g ≫ π a)
[PROOFSTEP]
exact ⟨a, g, rfl⟩
[GOAL]
case h.mpr
C : Type u_1
inst✝ : Category.{u_3, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
Y : C
g : Y ⟶ B
⊢ (generateFamily X π).arrows g → (generate (Presieve.ofArrows X π)).arrows g
[PROOFSTEP]
rintro ⟨a, g, rfl⟩
[GOAL]
case h.mpr.intro.intro
C : Type u_1
inst✝ : Category.{u_3, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
Y : C
a : α
g : Y ⟶ X a
⊢ (generate (Presieve.ofArrows X π)).arrows (g ≫ π a)
[PROOFSTEP]
refine ⟨_, g, π a, ⟨a⟩, rfl⟩
[GOAL]
C : Type u_1
inst✝ : Category.{?u.43458, u_1} C
α : Unit → C
⊢ ∀ {W : C} (e : (a : Unit) → α a ⟶ W)
(h :
∀ {Z : C} (a₁ a₂ : Unit) (g₁ : Z ⟶ α a₁) (g₂ : Z ⟶ α a₂), g₁ ≫ 𝟙 (α ()) = g₂ ≫ 𝟙 (α ()) → g₁ ≫ e a₁ = g₂ ≫ e a₂)
(a : Unit),
𝟙 (α ()) ≫
(fun {W} e x => e ()) e
(_ :
∀ {Z : C} (a₁ a₂ : Unit) (g₁ : Z ⟶ α a₁) (g₂ : Z ⟶ α a₂),
g₁ ≫ 𝟙 (α ()) = g₂ ≫ 𝟙 (α ()) → g₁ ≫ e a₁ = g₂ ≫ e a₂) =
e a
[PROOFSTEP]
aesop_cat
[GOAL]
C : Type u_1
inst✝ : Category.{?u.43458, u_1} C
α : Unit → C
⊢ ∀ {W : C} (e : (a : Unit) → α a ⟶ W)
(h :
∀ {Z : C} (a₁ a₂ : Unit) (g₁ : Z ⟶ α a₁) (g₂ : Z ⟶ α a₂), g₁ ≫ 𝟙 (α ()) = g₂ ≫ 𝟙 (α ()) → g₁ ≫ e a₁ = g₂ ≫ e a₂)
(m : α () ⟶ W),
(∀ (a : Unit), 𝟙 (α ()) ≫ m = e a) →
m =
(fun {W} e x => e ()) e
(_ :
∀ {Z : C} (a₁ a₂ : Unit) (g₁ : Z ⟶ α a₁) (g₂ : Z ⟶ α a₂),
g₁ ≫ 𝟙 (α ()) = g₂ ≫ 𝟙 (α ()) → g₁ ≫ e a₁ = g₂ ≫ e a₂)
[PROOFSTEP]
aesop_cat
[GOAL]
C : Type u_1
inst✝¹ : Category.{?u.51706, u_1} C
B W : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
inst✝ : EffectiveEpiFamily X π
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
a : α
⊢ π a ≫
EffectiveEpiFamily.desc X π e
(_ : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) =
e a
[PROOFSTEP]
simp
[GOAL]
C : Type u_1
inst✝¹ : Category.{?u.52695, u_1} C
B W Q : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
inst✝ : EffectiveEpiFamily X π
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
a : α
q : W ⟶ Q
⊢ π a ≫
EffectiveEpiFamily.desc X π e
(_ : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) ≫
q =
e a ≫ q
[PROOFSTEP]
simp
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_3, u_1} C
B W : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
inst✝ : EffectiveEpiFamily X π
m₁ m₂ : B ⟶ W
h : ∀ (a : α), π a ≫ m₁ = π a ≫ m₂
⊢ m₁ = m₂
[PROOFSTEP]
have : m₂ = EffectiveEpiFamily.desc X π (fun a => π a ≫ m₂) (fun a₁ a₂ g₁ g₂ h => by simp only [← Category.assoc, h]) :=
by apply EffectiveEpiFamily.uniq; intro; rfl
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_3, u_1} C
B W : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
inst✝ : EffectiveEpiFamily X π
m₁ m₂ : B ⟶ W
h✝ : ∀ (a : α), π a ≫ m₁ = π a ≫ m₂
Z✝ : C
a₁ a₂ : α
g₁ : Z✝ ⟶ X a₁
g₂ : Z✝ ⟶ X a₂
h : g₁ ≫ π a₁ = g₂ ≫ π a₂
⊢ g₁ ≫ (fun a => π a ≫ m₂) a₁ = g₂ ≫ (fun a => π a ≫ m₂) a₂
[PROOFSTEP]
simp only [← Category.assoc, h]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_3, u_1} C
B W : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
inst✝ : EffectiveEpiFamily X π
m₁ m₂ : B ⟶ W
h : ∀ (a : α), π a ≫ m₁ = π a ≫ m₂
⊢ m₂ =
desc X π (fun a => π a ≫ m₂)
(_ :
∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ π a₁ ≫ m₂ = g₂ ≫ π a₂ ≫ m₂)
[PROOFSTEP]
apply EffectiveEpiFamily.uniq
[GOAL]
case hm
C : Type u_1
inst✝¹ : Category.{u_3, u_1} C
B W : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
inst✝ : EffectiveEpiFamily X π
m₁ m₂ : B ⟶ W
h : ∀ (a : α), π a ≫ m₁ = π a ≫ m₂
⊢ ∀ (a : α), π a ≫ m₂ = π a ≫ m₂
[PROOFSTEP]
intro
[GOAL]
case hm
C : Type u_1
inst✝¹ : Category.{u_3, u_1} C
B W : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
inst✝ : EffectiveEpiFamily X π
m₁ m₂ : B ⟶ W
h : ∀ (a : α), π a ≫ m₁ = π a ≫ m₂
a✝ : α
⊢ π a✝ ≫ m₂ = π a✝ ≫ m₂
[PROOFSTEP]
rfl
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_3, u_1} C
B W : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
inst✝ : EffectiveEpiFamily X π
m₁ m₂ : B ⟶ W
h : ∀ (a : α), π a ≫ m₁ = π a ≫ m₂
this :
m₂ =
desc X π (fun a => π a ≫ m₂)
(_ :
∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ π a₁ ≫ m₂ = g₂ ≫ π a₂ ≫ m₂)
⊢ m₁ = m₂
[PROOFSTEP]
rw [this]
[GOAL]
C : Type u_1
inst✝¹ : Category.{u_3, u_1} C
B W : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
inst✝ : EffectiveEpiFamily X π
m₁ m₂ : B ⟶ W
h : ∀ (a : α), π a ≫ m₁ = π a ≫ m₂
this :
m₂ =
desc X π (fun a => π a ≫ m₂)
(_ :
∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ π a₁ ≫ m₂ = g₂ ≫ π a₂ ≫ m₂)
⊢ m₁ =
desc X π (fun a => π a ≫ m₂)
(_ :
∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ π a₁ ≫ m₂ = g₂ ≫ π a₂ ≫ m₂)
[PROOFSTEP]
exact EffectiveEpiFamily.uniq _ _ _ _ _ h
[GOAL]
C : Type u_1
inst✝² : Category.{?u.55691, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
inst✝¹ : EffectiveEpiFamily X π
inst✝ : HasCoproduct X
⊢ Epi (Sigma.desc π)
[PROOFSTEP]
constructor
[GOAL]
case left_cancellation
C : Type u_1
inst✝² : Category.{?u.55691, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
inst✝¹ : EffectiveEpiFamily X π
inst✝ : HasCoproduct X
⊢ ∀ {Z : C} (g h : B ⟶ Z), Sigma.desc π ≫ g = Sigma.desc π ≫ h → g = h
[PROOFSTEP]
intro Z g h H
[GOAL]
case left_cancellation
C : Type u_1
inst✝² : Category.{?u.55691, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
inst✝¹ : EffectiveEpiFamily X π
inst✝ : HasCoproduct X
Z : C
g h : B ⟶ Z
H : Sigma.desc π ≫ g = Sigma.desc π ≫ h
⊢ g = h
[PROOFSTEP]
apply EffectiveEpiFamily.hom_ext X π
[GOAL]
case left_cancellation.h
C : Type u_1
inst✝² : Category.{?u.55691, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
inst✝¹ : EffectiveEpiFamily X π
inst✝ : HasCoproduct X
Z : C
g h : B ⟶ Z
H : Sigma.desc π ≫ g = Sigma.desc π ≫ h
⊢ ∀ (a : α), π a ≫ g = π a ≫ h
[PROOFSTEP]
intro a
[GOAL]
case left_cancellation.h
C : Type u_1
inst✝² : Category.{?u.55691, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
inst✝¹ : EffectiveEpiFamily X π
inst✝ : HasCoproduct X
Z : C
g h : B ⟶ Z
H : Sigma.desc π ≫ g = Sigma.desc π ≫ h
a : α
⊢ π a ≫ g = π a ≫ h
[PROOFSTEP]
suffices (Sigma.ι _ a ≫ Sigma.desc π) ≫ g = (Sigma.ι _ a ≫ Sigma.desc π) ≫ h by simpa only [colimit.ι_desc] using this
[GOAL]
C : Type u_1
inst✝² : Category.{?u.55691, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
inst✝¹ : EffectiveEpiFamily X π
inst✝ : HasCoproduct X
Z : C
g h : B ⟶ Z
H : Sigma.desc π ≫ g = Sigma.desc π ≫ h
a : α
this : (Sigma.ι (fun b => X b) a ≫ Sigma.desc π) ≫ g = (Sigma.ι (fun b => X b) a ≫ Sigma.desc π) ≫ h
⊢ π a ≫ g = π a ≫ h
[PROOFSTEP]
simpa only [colimit.ι_desc] using this
[GOAL]
case left_cancellation.h
C : Type u_1
inst✝² : Category.{?u.55691, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
inst✝¹ : EffectiveEpiFamily X π
inst✝ : HasCoproduct X
Z : C
g h : B ⟶ Z
H : Sigma.desc π ≫ g = Sigma.desc π ≫ h
a : α
⊢ (Sigma.ι (fun b => X b) a ≫ Sigma.desc π) ≫ g = (Sigma.ι (fun b => X b) a ≫ Sigma.desc π) ≫ h
[PROOFSTEP]
simp only [Category.assoc, H]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
a : α
⊢ 𝟙 ((𝟭 C).obj (Over.mk (π a)).left) ≫ π a = (Over.mk (π a)).hom
[PROOFSTEP]
simp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
⊢ ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂),
g₁ ≫ π a₁ = g₂ ≫ π a₂ →
g₁ ≫
(fun a =>
NatTrans.app S.ι { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) })
a₁ =
g₂ ≫
(fun a =>
NatTrans.app S.ι { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) })
a₂
[PROOFSTEP]
intro Z a₁ a₂ g₁ g₂ h
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
Z : C
a₁ a₂ : α
g₁ : Z ⟶ X a₁
g₂ : Z ⟶ X a₂
h : g₁ ≫ π a₁ = g₂ ≫ π a₂
⊢ g₁ ≫
(fun a => NatTrans.app S.ι { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) })
a₁ =
g₂ ≫
(fun a => NatTrans.app S.ι { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) })
a₂
[PROOFSTEP]
dsimp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
Z : C
a₁ a₂ : α
g₁ : Z ⟶ X a₁
g₂ : Z ⟶ X a₂
h : g₁ ≫ π a₁ = g₂ ≫ π a₂
⊢ g₁ ≫ NatTrans.app S.ι { obj := Over.mk (π a₁), property := (_ : ∃ a g, g ≫ π a = π a₁) } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk (π a₂), property := (_ : ∃ a g, g ≫ π a = π a₂) }
[PROOFSTEP]
let A₁ : D := ⟨Over.mk (π a₁), a₁, 𝟙 _, by simp⟩
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
Z : C
a₁ a₂ : α
g₁ : Z ⟶ X a₁
g₂ : Z ⟶ X a₂
h : g₁ ≫ π a₁ = g₂ ≫ π a₂
⊢ 𝟙 ((𝟭 C).obj (Over.mk (π a₁)).left) ≫ π a₁ = (Over.mk (π a₁)).hom
[PROOFSTEP]
simp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
Z : C
a₁ a₂ : α
g₁ : Z ⟶ X a₁
g₂ : Z ⟶ X a₂
h : g₁ ≫ π a₁ = g₂ ≫ π a₂
A₁ : D := { obj := Over.mk (π a₁), property := (_ : ∃ a g, g ≫ π a = (Over.mk (π a₁)).hom) }
⊢ g₁ ≫ NatTrans.app S.ι { obj := Over.mk (π a₁), property := (_ : ∃ a g, g ≫ π a = π a₁) } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk (π a₂), property := (_ : ∃ a g, g ≫ π a = π a₂) }
[PROOFSTEP]
let A₂ : D := ⟨Over.mk (π a₂), a₂, 𝟙 _, by simp⟩
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
Z : C
a₁ a₂ : α
g₁ : Z ⟶ X a₁
g₂ : Z ⟶ X a₂
h : g₁ ≫ π a₁ = g₂ ≫ π a₂
A₁ : D := { obj := Over.mk (π a₁), property := (_ : ∃ a g, g ≫ π a = (Over.mk (π a₁)).hom) }
⊢ 𝟙 ((𝟭 C).obj (Over.mk (π a₂)).left) ≫ π a₂ = (Over.mk (π a₂)).hom
[PROOFSTEP]
simp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
Z : C
a₁ a₂ : α
g₁ : Z ⟶ X a₁
g₂ : Z ⟶ X a₂
h : g₁ ≫ π a₁ = g₂ ≫ π a₂
A₁ : D := { obj := Over.mk (π a₁), property := (_ : ∃ a g, g ≫ π a = (Over.mk (π a₁)).hom) }
A₂ : D := { obj := Over.mk (π a₂), property := (_ : ∃ a g, g ≫ π a = (Over.mk (π a₂)).hom) }
⊢ g₁ ≫ NatTrans.app S.ι { obj := Over.mk (π a₁), property := (_ : ∃ a g, g ≫ π a = π a₁) } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk (π a₂), property := (_ : ∃ a g, g ≫ π a = π a₂) }
[PROOFSTEP]
let Z' : D := ⟨Over.mk (g₁ ≫ π a₁), a₁, g₁, rfl⟩
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
Z : C
a₁ a₂ : α
g₁ : Z ⟶ X a₁
g₂ : Z ⟶ X a₂
h : g₁ ≫ π a₁ = g₂ ≫ π a₂
A₁ : D := { obj := Over.mk (π a₁), property := (_ : ∃ a g, g ≫ π a = (Over.mk (π a₁)).hom) }
A₂ : D := { obj := Over.mk (π a₂), property := (_ : ∃ a g, g ≫ π a = (Over.mk (π a₂)).hom) }
Z' : D := { obj := Over.mk (g₁ ≫ π a₁), property := (_ : ∃ a g, g ≫ π a = (Over.mk (g₁ ≫ π a₁)).hom) }
⊢ g₁ ≫ NatTrans.app S.ι { obj := Over.mk (π a₁), property := (_ : ∃ a g, g ≫ π a = π a₁) } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk (π a₂), property := (_ : ∃ a g, g ≫ π a = π a₂) }
[PROOFSTEP]
let i₁ : Z' ⟶ A₁ := Over.homMk g₁
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
Z : C
a₁ a₂ : α
g₁ : Z ⟶ X a₁
g₂ : Z ⟶ X a₂
h : g₁ ≫ π a₁ = g₂ ≫ π a₂
A₁ : D := { obj := Over.mk (π a₁), property := (_ : ∃ a g, g ≫ π a = (Over.mk (π a₁)).hom) }
A₂ : D := { obj := Over.mk (π a₂), property := (_ : ∃ a g, g ≫ π a = (Over.mk (π a₂)).hom) }
Z' : D := { obj := Over.mk (g₁ ≫ π a₁), property := (_ : ∃ a g, g ≫ π a = (Over.mk (g₁ ≫ π a₁)).hom) }
i₁ : Z' ⟶ A₁ := Over.homMk g₁
⊢ g₁ ≫ NatTrans.app S.ι { obj := Over.mk (π a₁), property := (_ : ∃ a g, g ≫ π a = π a₁) } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk (π a₂), property := (_ : ∃ a g, g ≫ π a = π a₂) }
[PROOFSTEP]
let i₂ : Z' ⟶ A₂ := Over.homMk g₂
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
Z : C
a₁ a₂ : α
g₁ : Z ⟶ X a₁
g₂ : Z ⟶ X a₂
h : g₁ ≫ π a₁ = g₂ ≫ π a₂
A₁ : D := { obj := Over.mk (π a₁), property := (_ : ∃ a g, g ≫ π a = (Over.mk (π a₁)).hom) }
A₂ : D := { obj := Over.mk (π a₂), property := (_ : ∃ a g, g ≫ π a = (Over.mk (π a₂)).hom) }
Z' : D := { obj := Over.mk (g₁ ≫ π a₁), property := (_ : ∃ a g, g ≫ π a = (Over.mk (g₁ ≫ π a₁)).hom) }
i₁ : Z' ⟶ A₁ := Over.homMk g₁
i₂ : Z' ⟶ A₂ := Over.homMk g₂
⊢ g₁ ≫ NatTrans.app S.ι { obj := Over.mk (π a₁), property := (_ : ∃ a g, g ≫ π a = π a₁) } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk (π a₂), property := (_ : ∃ a g, g ≫ π a = π a₂) }
[PROOFSTEP]
change F.map i₁ ≫ _ = F.map i₂ ≫ _
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
Z : C
a₁ a₂ : α
g₁ : Z ⟶ X a₁
g₂ : Z ⟶ X a₂
h : g₁ ≫ π a₁ = g₂ ≫ π a₂
A₁ : D := { obj := Over.mk (π a₁), property := (_ : ∃ a g, g ≫ π a = (Over.mk (π a₁)).hom) }
A₂ : D := { obj := Over.mk (π a₂), property := (_ : ∃ a g, g ≫ π a = (Over.mk (π a₂)).hom) }
Z' : D := { obj := Over.mk (g₁ ≫ π a₁), property := (_ : ∃ a g, g ≫ π a = (Over.mk (g₁ ≫ π a₁)).hom) }
i₁ : Z' ⟶ A₁ := Over.homMk g₁
i₂ : Z' ⟶ A₂ := Over.homMk g₂
⊢ F.map i₁ ≫ NatTrans.app S.ι { obj := Over.mk (π a₁), property := (_ : ∃ a g, g ≫ π a = π a₁) } =
F.map i₂ ≫ NatTrans.app S.ι { obj := Over.mk (π a₂), property := (_ : ∃ a g, g ≫ π a = π a₂) }
[PROOFSTEP]
simp only [S.w]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
⊢ ∀ (s : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows))
(j : FullSubcategory fun f => (Sieve.generateFamily X π).arrows f.hom),
NatTrans.app (Presieve.cocone (Sieve.generateFamily X π).arrows).ι j ≫
(fun S =>
EffectiveEpiFamilyStruct.desc H
(fun a =>
NatTrans.app S.ι { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) })
(_ :
∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂),
g₁ ≫ π a₁ = g₂ ≫ π a₂ →
g₁ ≫
(fun a =>
NatTrans.app S.ι
{ obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) })
a₁ =
g₂ ≫
(fun a =>
NatTrans.app S.ι
{ obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) })
a₂))
s =
NatTrans.app s.ι j
[PROOFSTEP]
intro S ⟨T, a, (g : T.left ⟶ X a), hT⟩
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
T : Over B
a : α
g : T.left ⟶ X a
hT : g ≫ π a = T.hom
⊢ NatTrans.app (Presieve.cocone (Sieve.generateFamily X π).arrows).ι
{ obj := T, property := (_ : ∃ a g, g ≫ π a = T.hom) } ≫
(fun S =>
EffectiveEpiFamilyStruct.desc H
(fun a =>
NatTrans.app S.ι { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) })
(_ :
∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂),
g₁ ≫ π a₁ = g₂ ≫ π a₂ →
g₁ ≫
(fun a =>
NatTrans.app S.ι
{ obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) })
a₁ =
g₂ ≫
(fun a =>
NatTrans.app S.ι
{ obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) })
a₂))
S =
NatTrans.app S.ι { obj := T, property := (_ : ∃ a g, g ≫ π a = T.hom) }
[PROOFSTEP]
dsimp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
T : Over B
a : α
g : T.left ⟶ X a
hT : g ≫ π a = T.hom
⊢ T.hom ≫
EffectiveEpiFamilyStruct.desc H
(fun a => NatTrans.app S.ι { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = π a) })
(_ :
∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂),
g₁ ≫ π a₁ = g₂ ≫ π a₂ →
g₁ ≫ NatTrans.app S.ι { obj := Over.mk (π a₁), property := (_ : ∃ a g, g ≫ π a = π a₁) } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk (π a₂), property := (_ : ∃ a g, g ≫ π a = π a₂) }) =
NatTrans.app S.ι { obj := T, property := (_ : ∃ a g, g ≫ π a = T.hom) }
[PROOFSTEP]
nth_rewrite 1 [← hT, Category.assoc, H.fac]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
T : Over B
a : α
g : T.left ⟶ X a
hT : g ≫ π a = T.hom
⊢ g ≫ NatTrans.app S.ι { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = π a) } =
NatTrans.app S.ι { obj := T, property := (_ : ∃ a g, g ≫ π a = T.hom) }
[PROOFSTEP]
let A : D := ⟨Over.mk (π a), a, 𝟙 _, by simp⟩
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
T : Over B
a : α
g : T.left ⟶ X a
hT : g ≫ π a = T.hom
⊢ 𝟙 ((𝟭 C).obj (Over.mk (π a)).left) ≫ π a = (Over.mk (π a)).hom
[PROOFSTEP]
simp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
T : Over B
a : α
g : T.left ⟶ X a
hT : g ≫ π a = T.hom
A : D := { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) }
⊢ g ≫ NatTrans.app S.ι { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = π a) } =
NatTrans.app S.ι { obj := T, property := (_ : ∃ a g, g ≫ π a = T.hom) }
[PROOFSTEP]
let B : D := ⟨Over.mk T.hom, a, g, hT⟩
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B✝ : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B✝
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
T : Over B✝
a : α
g : T.left ⟶ X a
hT : g ≫ π a = T.hom
A : D := { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) }
B : D := { obj := Over.mk T.hom, property := (_ : ∃ a g, g ≫ π a = (Over.mk T.hom).hom) }
⊢ g ≫ NatTrans.app S.ι { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = π a) } =
NatTrans.app S.ι { obj := T, property := (_ : ∃ a g, g ≫ π a = T.hom) }
[PROOFSTEP]
let i : B ⟶ A := Over.homMk g
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B✝ : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B✝
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
T : Over B✝
a : α
g : T.left ⟶ X a
hT : g ≫ π a = T.hom
A : D := { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) }
B : D := { obj := Over.mk T.hom, property := (_ : ∃ a g, g ≫ π a = (Over.mk T.hom).hom) }
i : B ⟶ A := Over.homMk g
⊢ g ≫ NatTrans.app S.ι { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = π a) } =
NatTrans.app S.ι { obj := T, property := (_ : ∃ a g, g ≫ π a = T.hom) }
[PROOFSTEP]
change F.map i ≫ _ = _
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B✝ : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B✝
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
T : Over B✝
a : α
g : T.left ⟶ X a
hT : g ≫ π a = T.hom
A : D := { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) }
B : D := { obj := Over.mk T.hom, property := (_ : ∃ a g, g ≫ π a = (Over.mk T.hom).hom) }
i : B ⟶ A := Over.homMk g
⊢ F.map i ≫ NatTrans.app S.ι { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = π a) } =
NatTrans.app S.ι { obj := T, property := (_ : ∃ a g, g ≫ π a = T.hom) }
[PROOFSTEP]
rw [S.w]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B✝ : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B✝
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
T : Over B✝
a : α
g : T.left ⟶ X a
hT : g ≫ π a = T.hom
A : D := { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) }
B : D := { obj := Over.mk T.hom, property := (_ : ∃ a g, g ≫ π a = (Over.mk T.hom).hom) }
i : B ⟶ A := Over.homMk g
⊢ NatTrans.app S.ι B = NatTrans.app S.ι { obj := T, property := (_ : ∃ a g, g ≫ π a = T.hom) }
[PROOFSTEP]
rfl
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
⊢ ∀ (s : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows))
(m : (Presieve.cocone (Sieve.generateFamily X π).arrows).pt ⟶ s.pt),
(∀ (j : FullSubcategory fun f => (Sieve.generateFamily X π).arrows f.hom),
NatTrans.app (Presieve.cocone (Sieve.generateFamily X π).arrows).ι j ≫ m = NatTrans.app s.ι j) →
m =
(fun S =>
EffectiveEpiFamilyStruct.desc H
(fun a =>
NatTrans.app S.ι { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) })
(_ :
∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂),
g₁ ≫ π a₁ = g₂ ≫ π a₂ →
g₁ ≫
(fun a =>
NatTrans.app S.ι
{ obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) })
a₁ =
g₂ ≫
(fun a =>
NatTrans.app S.ι
{ obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) })
a₂))
s
[PROOFSTEP]
intro S m hm
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
m : (Presieve.cocone (Sieve.generateFamily X π).arrows).pt ⟶ S.pt
hm :
∀ (j : FullSubcategory fun f => (Sieve.generateFamily X π).arrows f.hom),
NatTrans.app (Presieve.cocone (Sieve.generateFamily X π).arrows).ι j ≫ m = NatTrans.app S.ι j
⊢ m =
(fun S =>
EffectiveEpiFamilyStruct.desc H
(fun a =>
NatTrans.app S.ι { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) })
(_ :
∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂),
g₁ ≫ π a₁ = g₂ ≫ π a₂ →
g₁ ≫
(fun a =>
NatTrans.app S.ι
{ obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) })
a₁ =
g₂ ≫
(fun a =>
NatTrans.app S.ι
{ obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) })
a₂))
S
[PROOFSTEP]
dsimp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
m : (Presieve.cocone (Sieve.generateFamily X π).arrows).pt ⟶ S.pt
hm :
∀ (j : FullSubcategory fun f => (Sieve.generateFamily X π).arrows f.hom),
NatTrans.app (Presieve.cocone (Sieve.generateFamily X π).arrows).ι j ≫ m = NatTrans.app S.ι j
⊢ m =
EffectiveEpiFamilyStruct.desc H
(fun a => NatTrans.app S.ι { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = π a) })
(_ :
∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂),
g₁ ≫ π a₁ = g₂ ≫ π a₂ →
g₁ ≫ NatTrans.app S.ι { obj := Over.mk (π a₁), property := (_ : ∃ a g, g ≫ π a = π a₁) } =
g₂ ≫ NatTrans.app S.ι { obj := Over.mk (π a₂), property := (_ : ∃ a g, g ≫ π a = π a₂) })
[PROOFSTEP]
apply H.uniq
[GOAL]
case a
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
m : (Presieve.cocone (Sieve.generateFamily X π).arrows).pt ⟶ S.pt
hm :
∀ (j : FullSubcategory fun f => (Sieve.generateFamily X π).arrows f.hom),
NatTrans.app (Presieve.cocone (Sieve.generateFamily X π).arrows).ι j ≫ m = NatTrans.app S.ι j
⊢ ∀ (a : α), π a ≫ m = NatTrans.app S.ι { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = π a) }
[PROOFSTEP]
intro a
[GOAL]
case a
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
m : (Presieve.cocone (Sieve.generateFamily X π).arrows).pt ⟶ S.pt
hm :
∀ (j : FullSubcategory fun f => (Sieve.generateFamily X π).arrows f.hom),
NatTrans.app (Presieve.cocone (Sieve.generateFamily X π).arrows).ι j ≫ m = NatTrans.app S.ι j
a : α
⊢ π a ≫ m = NatTrans.app S.ι { obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = π a) }
[PROOFSTEP]
exact hm ⟨Over.mk (π a), a, 𝟙 _, by simp⟩
[GOAL]
C : Type u_1
inst✝ : Category.{?u.59810, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : EffectiveEpiFamilyStruct X π
D : Type (max u_1 ?u.59810) := FullSubcategory fun T => (Sieve.generateFamily X π).arrows T.hom
F : D ⥤ C := Presieve.diagram (Sieve.generateFamily X π).arrows
S : Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows)
m : (Presieve.cocone (Sieve.generateFamily X π).arrows).pt ⟶ S.pt
hm :
∀ (j : FullSubcategory fun f => (Sieve.generateFamily X π).arrows f.hom),
NatTrans.app (Presieve.cocone (Sieve.generateFamily X π).arrows).ι j ≫ m = NatTrans.app S.ι j
a : α
⊢ 𝟙 ((𝟭 C).obj (Over.mk (π a)).left) ≫ π a = (Over.mk (π a)).hom
[PROOFSTEP]
simp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
⊢ ∀ ⦃X_1 Y : FullSubcategory fun f => (Sieve.generateFamily X π).arrows f.hom⦄ (f : X_1 ⟶ Y),
(Presieve.diagram (Sieve.generateFamily X π).arrows).map f ≫
(fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT))
Y =
(fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT))
X_1 ≫
((Functor.const (FullSubcategory fun f => (Sieve.generateFamily X π).arrows f.hom)).obj W).map f
[PROOFSTEP]
intro ⟨A, a, (g₁ : A.left ⟶ _), ha⟩ ⟨B, b, (g₂ : B.left ⟶ _), hb⟩ (q : A ⟶ B)
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B✝ : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B✝
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
A : Over B✝
a : α
g₁ : A.left ⟶ X a
ha : g₁ ≫ π a = A.hom
B : Over B✝
b : α
g₂ : B.left ⟶ X b
hb : g₂ ≫ π b = B.hom
q : A ⟶ B
⊢ (Presieve.diagram (Sieve.generateFamily X π).arrows).map q ≫
(fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT))
{ obj := B, property := (_ : ∃ a g, g ≫ π a = B.hom) } =
(fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT))
{ obj := A, property := (_ : ∃ a g, g ≫ π a = A.hom) } ≫
((Functor.const (FullSubcategory fun f => (Sieve.generateFamily X π).arrows f.hom)).obj W).map q
[PROOFSTEP]
dsimp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B✝ : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B✝
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
A : Over B✝
a : α
g₁ : A.left ⟶ X a
ha : g₁ ≫ π a = A.hom
B : Over B✝
b : α
g₂ : B.left ⟶ X b
hb : g₂ ≫ π b = B.hom
q : A ⟶ B
⊢ q.left ≫
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose (_ : ∃ a g, g ≫ π a = B.hom)) = B.hom) ≫
e (Exists.choose (_ : ∃ a g, g ≫ π a = B.hom)) =
(Exists.choose (_ : ∃ g, g ≫ π (Exists.choose (_ : ∃ a g, g ≫ π a = A.hom)) = A.hom) ≫
e (Exists.choose (_ : ∃ a g, g ≫ π a = A.hom))) ≫
𝟙 W
[PROOFSTEP]
rw [Category.comp_id, ← Category.assoc]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B✝ : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B✝
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
A : Over B✝
a : α
g₁ : A.left ⟶ X a
ha : g₁ ≫ π a = A.hom
B : Over B✝
b : α
g₂ : B.left ⟶ X b
hb : g₂ ≫ π b = B.hom
q : A ⟶ B
⊢ (q.left ≫ Exists.choose (_ : ∃ g, g ≫ π (Exists.choose (_ : ∃ a g, g ≫ π a = B.hom)) = B.hom)) ≫
e (Exists.choose (_ : ∃ a g, g ≫ π a = B.hom)) =
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose (_ : ∃ a g, g ≫ π a = A.hom)) = A.hom) ≫
e (Exists.choose (_ : ∃ a g, g ≫ π a = A.hom))
[PROOFSTEP]
apply h
[GOAL]
case a
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B✝ : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B✝
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
A : Over B✝
a : α
g₁ : A.left ⟶ X a
ha : g₁ ≫ π a = A.hom
B : Over B✝
b : α
g₂ : B.left ⟶ X b
hb : g₂ ≫ π b = B.hom
q : A ⟶ B
⊢ (q.left ≫ Exists.choose (_ : ∃ g, g ≫ π (Exists.choose (_ : ∃ a g, g ≫ π a = B.hom)) = B.hom)) ≫
π (Exists.choose (_ : ∃ a g, g ≫ π a = B.hom)) =
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose (_ : ∃ a g, g ≫ π a = A.hom)) = A.hom) ≫
π (Exists.choose (_ : ∃ a g, g ≫ π a = A.hom))
[PROOFSTEP]
rw [Category.assoc]
[GOAL]
case a
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B✝ : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B✝
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
A : Over B✝
a : α
g₁ : A.left ⟶ X a
ha : g₁ ≫ π a = A.hom
B : Over B✝
b : α
g₂ : B.left ⟶ X b
hb : g₂ ≫ π b = B.hom
q : A ⟶ B
⊢ q.left ≫
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose (_ : ∃ a g, g ≫ π a = B.hom)) = B.hom) ≫
π (Exists.choose (_ : ∃ a g, g ≫ π a = B.hom)) =
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose (_ : ∃ a g, g ≫ π a = A.hom)) = A.hom) ≫
π (Exists.choose (_ : ∃ a g, g ≫ π a = A.hom))
[PROOFSTEP]
generalize_proofs h1 h2 h3 h4
[GOAL]
case a
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B✝ : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B✝
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
A : Over B✝
a : α
g₁ : A.left ⟶ X a
ha : g₁ ≫ π a = A.hom
B : Over B✝
b : α
g₂ : B.left ⟶ X b
hb : g₂ ≫ π b = B.hom
q : A ⟶ B
h1 : ∃ a g, g ≫ π a = B.hom
h2 : ∃ g, g ≫ π (Exists.choose h1) = B.hom
h3 : ∃ a g, g ≫ π a = A.hom
h4 : ∃ g, g ≫ π (Exists.choose h3) = A.hom
⊢ q.left ≫ Exists.choose h2 ≫ π (Exists.choose h1) = Exists.choose h4 ≫ π (Exists.choose h3)
[PROOFSTEP]
rw [h2.choose_spec, h4.choose_spec, Over.w]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
⊢ ∀ {W : C} (e : (a : α) → X a ⟶ W)
(h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) (a : α),
π a ≫
(fun {W} e h =>
IsColimit.desc H
(aux e
(_ :
∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂),
g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂)))
e (_ : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) =
e a
[PROOFSTEP]
intro W e h a
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
a : α
⊢ π a ≫
(fun {W} e h =>
IsColimit.desc H
(aux e
(_ :
∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂)))
e (_ : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) =
e a
[PROOFSTEP]
dsimp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
a : α
⊢ π a ≫
IsColimit.desc H
{ pt := W,
ι :=
NatTrans.mk fun x =>
Exists.choose
(_ : ∃ g, g ≫ π (Exists.choose (_ : (Sieve.generateFamily X π).arrows x.obj.hom)) = x.obj.hom) ≫
e (Exists.choose (_ : (Sieve.generateFamily X π).arrows x.obj.hom)) } =
e a
[PROOFSTEP]
have := H.fac (aux e h) ⟨Over.mk (π a), a, 𝟙 _, by simp⟩
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
a : α
⊢ 𝟙 ((𝟭 C).obj (Over.mk (π a)).left) ≫ π a = (Over.mk (π a)).hom
[PROOFSTEP]
simp
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
a : α
this :
NatTrans.app (Presieve.cocone (Sieve.generateFamily X π).arrows).ι
{ obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) } ≫
IsColimit.desc H
(aux e
(_ : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂)) =
NatTrans.app
(aux e
(_ : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂)).ι
{ obj := Over.mk (π a), property := (_ : ∃ a_1 g, g ≫ π a_1 = (Over.mk (π a)).hom) }
⊢ π a ≫
IsColimit.desc H
{ pt := W,
ι :=
NatTrans.mk fun x =>
Exists.choose
(_ : ∃ g, g ≫ π (Exists.choose (_ : (Sieve.generateFamily X π).arrows x.obj.hom)) = x.obj.hom) ≫
e (Exists.choose (_ : (Sieve.generateFamily X π).arrows x.obj.hom)) } =
e a
[PROOFSTEP]
dsimp at this
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
a : α
this :
π a ≫
IsColimit.desc H
{ pt := W,
ι :=
NatTrans.mk fun x =>
Exists.choose
(_ : ∃ g, g ≫ π (Exists.choose (_ : (Sieve.generateFamily X π).arrows x.obj.hom)) = x.obj.hom) ≫
e (Exists.choose (_ : (Sieve.generateFamily X π).arrows x.obj.hom)) } =
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose (_ : ∃ a_1 g, g ≫ π a_1 = π a)) = π a) ≫
e (Exists.choose (_ : ∃ a_1 g, g ≫ π a_1 = π a))
⊢ π a ≫
IsColimit.desc H
{ pt := W,
ι :=
NatTrans.mk fun x =>
Exists.choose
(_ : ∃ g, g ≫ π (Exists.choose (_ : (Sieve.generateFamily X π).arrows x.obj.hom)) = x.obj.hom) ≫
e (Exists.choose (_ : (Sieve.generateFamily X π).arrows x.obj.hom)) } =
e a
[PROOFSTEP]
rw [this]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
a : α
this :
π a ≫
IsColimit.desc H
{ pt := W,
ι :=
NatTrans.mk fun x =>
Exists.choose
(_ : ∃ g, g ≫ π (Exists.choose (_ : (Sieve.generateFamily X π).arrows x.obj.hom)) = x.obj.hom) ≫
e (Exists.choose (_ : (Sieve.generateFamily X π).arrows x.obj.hom)) } =
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose (_ : ∃ a_1 g, g ≫ π a_1 = π a)) = π a) ≫
e (Exists.choose (_ : ∃ a_1 g, g ≫ π a_1 = π a))
⊢ Exists.choose (_ : ∃ g, g ≫ π (Exists.choose (_ : ∃ a_1 g, g ≫ π a_1 = π a)) = π a) ≫
e (Exists.choose (_ : ∃ a_1 g, g ≫ π a_1 = π a)) =
e a
[PROOFSTEP]
clear this
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
a : α
⊢ Exists.choose (_ : ∃ g, g ≫ π (Exists.choose (_ : ∃ a_1 g, g ≫ π a_1 = π a)) = π a) ≫
e (Exists.choose (_ : ∃ a_1 g, g ≫ π a_1 = π a)) =
e a
[PROOFSTEP]
conv_rhs => rw [← Category.id_comp (e a)]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
a : α
| e a
[PROOFSTEP]
rw [← Category.id_comp (e a)]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
a : α
| e a
[PROOFSTEP]
rw [← Category.id_comp (e a)]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
a : α
| e a
[PROOFSTEP]
rw [← Category.id_comp (e a)]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
a : α
⊢ Exists.choose (_ : ∃ g, g ≫ π (Exists.choose (_ : ∃ a_1 g, g ≫ π a_1 = π a)) = π a) ≫
e (Exists.choose (_ : ∃ a_1 g, g ≫ π a_1 = π a)) =
𝟙 (X a) ≫ e a
[PROOFSTEP]
apply h
[GOAL]
case a
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
a : α
⊢ Exists.choose (_ : ∃ g, g ≫ π (Exists.choose (_ : ∃ a_1 g, g ≫ π a_1 = π a)) = π a) ≫
π (Exists.choose (_ : ∃ a_1 g, g ≫ π a_1 = π a)) =
𝟙 (X a) ≫ π a
[PROOFSTEP]
generalize_proofs h1 h2
[GOAL]
case a
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
a : α
h1 : ∃ a_1 g, g ≫ π a_1 = π a
h2 : ∃ g, g ≫ π (Exists.choose h1) = π a
⊢ Exists.choose h2 ≫ π (Exists.choose h1) = 𝟙 (X a) ≫ π a
[PROOFSTEP]
rw [h2.choose_spec, Category.id_comp]
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
⊢ ∀ {W : C} (e : (a : α) → X a ⟶ W)
(h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂)
(m : B ⟶ W),
(∀ (a : α), π a ≫ m = e a) →
m =
(fun {W} e h =>
IsColimit.desc H
(aux e
(_ :
∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂),
g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂)))
e (_ : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂)
[PROOFSTEP]
intro W e h m hm
[GOAL]
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
m : B ⟶ W
hm : ∀ (a : α), π a ≫ m = e a
⊢ m =
(fun {W} e h =>
IsColimit.desc H
(aux e
(_ : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂)))
e (_ : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂)
[PROOFSTEP]
apply H.uniq (aux e h)
[GOAL]
case x
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
m : B ⟶ W
hm : ∀ (a : α), π a ≫ m = e a
⊢ ∀ (j : FullSubcategory fun f => (Sieve.generateFamily X π).arrows f.hom),
NatTrans.app (Presieve.cocone (Sieve.generateFamily X π).arrows).ι j ≫ m =
NatTrans.app
(aux e
(_ :
∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂)).ι
j
[PROOFSTEP]
rintro ⟨T, a, (g : T.left ⟶ _), ha⟩
[GOAL]
case x.mk.intro.intro
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
m : B ⟶ W
hm : ∀ (a : α), π a ≫ m = e a
T : Over B
a : α
g : T.left ⟶ X a
ha : g ≫ π a = T.hom
⊢ NatTrans.app (Presieve.cocone (Sieve.generateFamily X π).arrows).ι
{ obj := T, property := (_ : ∃ a g, g ≫ π a = T.hom) } ≫
m =
NatTrans.app
(aux e
(_ : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂)).ι
{ obj := T, property := (_ : ∃ a g, g ≫ π a = T.hom) }
[PROOFSTEP]
dsimp
[GOAL]
case x.mk.intro.intro
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
m : B ⟶ W
hm : ∀ (a : α), π a ≫ m = e a
T : Over B
a : α
g : T.left ⟶ X a
ha : g ≫ π a = T.hom
⊢ T.hom ≫ m =
Exists.choose (_ : ∃ g_1, g_1 ≫ π (Exists.choose (_ : ∃ a g, g ≫ π a = T.hom)) = T.hom) ≫
e (Exists.choose (_ : ∃ a g, g ≫ π a = T.hom))
[PROOFSTEP]
nth_rewrite 1 [← ha, Category.assoc, hm]
[GOAL]
case x.mk.intro.intro
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
m : B ⟶ W
hm : ∀ (a : α), π a ≫ m = e a
T : Over B
a : α
g : T.left ⟶ X a
ha : g ≫ π a = T.hom
⊢ g ≫ e a =
Exists.choose (_ : ∃ g_1, g_1 ≫ π (Exists.choose (_ : ∃ a g, g ≫ π a = T.hom)) = T.hom) ≫
e (Exists.choose (_ : ∃ a g, g ≫ π a = T.hom))
[PROOFSTEP]
apply h
[GOAL]
case x.mk.intro.intro.a
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
m : B ⟶ W
hm : ∀ (a : α), π a ≫ m = e a
T : Over B
a : α
g : T.left ⟶ X a
ha : g ≫ π a = T.hom
⊢ g ≫ π a =
Exists.choose (_ : ∃ g_1, g_1 ≫ π (Exists.choose (_ : ∃ a g, g ≫ π a = T.hom)) = T.hom) ≫
π (Exists.choose (_ : ∃ a g, g ≫ π a = T.hom))
[PROOFSTEP]
generalize_proofs h1 h2
[GOAL]
case x.mk.intro.intro.a
C : Type u_1
inst✝ : Category.{?u.74817, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
H : IsColimit (Presieve.cocone (Sieve.generateFamily X π).arrows)
aux : {W : C} →
(e : (a : α) → X a ⟶ W) →
(∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂) →
Cocone (Presieve.diagram (Sieve.generateFamily X π).arrows) :=
fun {W} e h =>
{ pt := W,
ι :=
NatTrans.mk fun x =>
match x with
| { obj := T, property := hT } =>
Exists.choose (_ : ∃ g, g ≫ π (Exists.choose hT) = T.hom) ≫ e (Exists.choose hT) }
W : C
e : (a : α) → X a ⟶ W
h : ∀ {Z : C} (a₁ a₂ : α) (g₁ : Z ⟶ X a₁) (g₂ : Z ⟶ X a₂), g₁ ≫ π a₁ = g₂ ≫ π a₂ → g₁ ≫ e a₁ = g₂ ≫ e a₂
m : B ⟶ W
hm : ∀ (a : α), π a ≫ m = e a
T : Over B
a : α
g : T.left ⟶ X a
ha : g ≫ π a = T.hom
h1 : ∃ a g, g ≫ π a = T.hom
h2 : ∃ g, g ≫ π (Exists.choose h1) = T.hom
⊢ g ≫ π a = Exists.choose h2 ≫ π (Exists.choose h1)
[PROOFSTEP]
rwa [h2.choose_spec]
[GOAL]
C : Type u_1
inst✝ : Category.{u_3, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
⊢ Presieve.EffectiveEpimorphic (Presieve.ofArrows X π) ↔ EffectiveEpiFamily X π
[PROOFSTEP]
constructor
[GOAL]
case mp
C : Type u_1
inst✝ : Category.{u_3, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
⊢ Presieve.EffectiveEpimorphic (Presieve.ofArrows X π) → EffectiveEpiFamily X π
[PROOFSTEP]
intro (h : Nonempty _)
[GOAL]
case mp
C : Type u_1
inst✝ : Category.{u_3, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
h : Nonempty (IsColimit (Presieve.cocone (generate (Presieve.ofArrows X π)).arrows))
⊢ EffectiveEpiFamily X π
[PROOFSTEP]
rw [Sieve.generateFamily_eq] at h
[GOAL]
case mp
C : Type u_1
inst✝ : Category.{u_3, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
h : Nonempty (IsColimit (Presieve.cocone (generateFamily X π).arrows))
⊢ EffectiveEpiFamily X π
[PROOFSTEP]
constructor
[GOAL]
case mp.effectiveEpiFamily
C : Type u_1
inst✝ : Category.{u_3, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
h : Nonempty (IsColimit (Presieve.cocone (generateFamily X π).arrows))
⊢ Nonempty (EffectiveEpiFamilyStruct X π)
[PROOFSTEP]
apply Nonempty.map (effectiveEpiFamilyStructOfIsColimit _ _) h
[GOAL]
case mpr
C : Type u_1
inst✝ : Category.{u_3, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
⊢ EffectiveEpiFamily X π → Presieve.EffectiveEpimorphic (Presieve.ofArrows X π)
[PROOFSTEP]
rintro ⟨h⟩
[GOAL]
case mpr.mk
C : Type u_1
inst✝ : Category.{u_3, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
h : Nonempty (EffectiveEpiFamilyStruct X π)
⊢ Presieve.EffectiveEpimorphic (Presieve.ofArrows X π)
[PROOFSTEP]
show Nonempty _
[GOAL]
case mpr.mk
C : Type u_1
inst✝ : Category.{u_3, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
h : Nonempty (EffectiveEpiFamilyStruct X π)
⊢ Nonempty (IsColimit (Presieve.cocone (generate (Presieve.ofArrows X π)).arrows))
[PROOFSTEP]
rw [Sieve.generateFamily_eq]
[GOAL]
case mpr.mk
C : Type u_1
inst✝ : Category.{u_3, u_1} C
B : C
α : Type u_2
X : α → C
π : (a : α) → X a ⟶ B
h : Nonempty (EffectiveEpiFamilyStruct X π)
⊢ Nonempty (IsColimit (Presieve.cocone (generateFamily X π).arrows))
[PROOFSTEP]
apply Nonempty.map (isColimitOfEffectiveEpiFamilyStruct _ _) h
|
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License,Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#include <boost/mpl/next.hpp>
#include <boost/mpl/prior.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/aux_/test.hpp>
MPL_TEST_CASE()
{
typedef int_<0> _0;
typedef int_<1> _1;
typedef int_<2> _2;
MPL_ASSERT(( is_same< next<_0>::type, _1 > ));
MPL_ASSERT(( is_same< next<_1>::type, _2 > ));
MPL_ASSERT(( is_same< prior<_1>::type, _0 > ));
MPL_ASSERT(( is_same< prior<_2>::type, _1 > ));
}
|
lemma sgn_zero [simp]: "sgn (0::'a::real_normed_vector) = 0" |
(* Title: HOL/Algebra/Group.thy
Author: Clemens Ballarin, started 4 February 2003
Based on work by Florian Kammueller, L C Paulson and Markus Wenzel.
With additional contributions from Martin Baillon and Paulo Emílio de Vilhena.
*)
theory Group
imports Complete_Lattice "HOL-Library.FuncSet"
begin
section \<open>Monoids and Groups\<close>
subsection \<open>Definitions\<close>
text \<open>
Definitions follow @{cite "Jacobson:1985"}.
\<close>
record 'a monoid = "'a partial_object" +
mult :: "['a, 'a] \<Rightarrow> 'a" (infixl "\<otimes>\<index>" 70)
one :: 'a ("\<one>\<index>")
definition
m_inv :: "('a, 'b) monoid_scheme => 'a => 'a" ("inv\<index> _" [81] 80)
where "inv\<^bsub>G\<^esub> x = (THE y. y \<in> carrier G \<and> x \<otimes>\<^bsub>G\<^esub> y = \<one>\<^bsub>G\<^esub> \<and> y \<otimes>\<^bsub>G\<^esub> x = \<one>\<^bsub>G\<^esub>)"
definition
Units :: "_ => 'a set"
\<comment> \<open>The set of invertible elements\<close>
where "Units G = {y. y \<in> carrier G \<and> (\<exists>x \<in> carrier G. x \<otimes>\<^bsub>G\<^esub> y = \<one>\<^bsub>G\<^esub> \<and> y \<otimes>\<^bsub>G\<^esub> x = \<one>\<^bsub>G\<^esub>)}"
locale monoid =
fixes G (structure)
assumes m_closed [intro, simp]:
"\<lbrakk>x \<in> carrier G; y \<in> carrier G\<rbrakk> \<Longrightarrow> x \<otimes> y \<in> carrier G"
and m_assoc:
"\<lbrakk>x \<in> carrier G; y \<in> carrier G; z \<in> carrier G\<rbrakk>
\<Longrightarrow> (x \<otimes> y) \<otimes> z = x \<otimes> (y \<otimes> z)"
and one_closed [intro, simp]: "\<one> \<in> carrier G"
and l_one [simp]: "x \<in> carrier G \<Longrightarrow> \<one> \<otimes> x = x"
and r_one [simp]: "x \<in> carrier G \<Longrightarrow> x \<otimes> \<one> = x"
lemma monoidI:
fixes G (structure)
assumes m_closed:
"!!x y. [| x \<in> carrier G; y \<in> carrier G |] ==> x \<otimes> y \<in> carrier G"
and one_closed: "\<one> \<in> carrier G"
and m_assoc:
"!!x y z. [| x \<in> carrier G; y \<in> carrier G; z \<in> carrier G |] ==>
(x \<otimes> y) \<otimes> z = x \<otimes> (y \<otimes> z)"
and l_one: "!!x. x \<in> carrier G ==> \<one> \<otimes> x = x"
and r_one: "!!x. x \<in> carrier G ==> x \<otimes> \<one> = x"
shows "monoid G"
by (fast intro!: monoid.intro intro: assms)
lemma (in monoid) Units_closed [dest]:
"x \<in> Units G ==> x \<in> carrier G"
by (unfold Units_def) fast
lemma (in monoid) one_unique:
assumes "u \<in> carrier G"
and "\<And>x. x \<in> carrier G \<Longrightarrow> u \<otimes> x = x"
shows "u = \<one>"
using assms(2)[OF one_closed] r_one[OF assms(1)] by simp
lemma (in monoid) inv_unique:
assumes eq: "y \<otimes> x = \<one>" "x \<otimes> y' = \<one>"
and G: "x \<in> carrier G" "y \<in> carrier G" "y' \<in> carrier G"
shows "y = y'"
proof -
from G eq have "y = y \<otimes> (x \<otimes> y')" by simp
also from G have "... = (y \<otimes> x) \<otimes> y'" by (simp add: m_assoc)
also from G eq have "... = y'" by simp
finally show ?thesis .
qed
lemma (in monoid) Units_m_closed [simp, intro]:
assumes x: "x \<in> Units G" and y: "y \<in> Units G"
shows "x \<otimes> y \<in> Units G"
proof -
from x obtain x' where x: "x \<in> carrier G" "x' \<in> carrier G" and xinv: "x \<otimes> x' = \<one>" "x' \<otimes> x = \<one>"
unfolding Units_def by fast
from y obtain y' where y: "y \<in> carrier G" "y' \<in> carrier G" and yinv: "y \<otimes> y' = \<one>" "y' \<otimes> y = \<one>"
unfolding Units_def by fast
from x y xinv yinv have "y' \<otimes> (x' \<otimes> x) \<otimes> y = \<one>" by simp
moreover from x y xinv yinv have "x \<otimes> (y \<otimes> y') \<otimes> x' = \<one>" by simp
moreover note x y
ultimately show ?thesis unfolding Units_def
by simp (metis m_assoc m_closed)
qed
lemma (in monoid) Units_one_closed [intro, simp]:
"\<one> \<in> Units G"
by (unfold Units_def) auto
lemma (in monoid) Units_inv_closed [intro, simp]:
"x \<in> Units G ==> inv x \<in> carrier G"
apply (simp add: Units_def m_inv_def)
by (metis (mono_tags, lifting) inv_unique the_equality)
lemma (in monoid) Units_l_inv_ex:
"x \<in> Units G ==> \<exists>y \<in> carrier G. y \<otimes> x = \<one>"
by (unfold Units_def) auto
lemma (in monoid) Units_r_inv_ex:
"x \<in> Units G ==> \<exists>y \<in> carrier G. x \<otimes> y = \<one>"
by (unfold Units_def) auto
lemma (in monoid) Units_l_inv [simp]:
"x \<in> Units G ==> inv x \<otimes> x = \<one>"
apply (unfold Units_def m_inv_def, simp)
by (metis (mono_tags, lifting) inv_unique the_equality)
lemma (in monoid) Units_r_inv [simp]:
"x \<in> Units G ==> x \<otimes> inv x = \<one>"
by (metis (full_types) Units_closed Units_inv_closed Units_l_inv Units_r_inv_ex inv_unique)
lemma (in monoid) inv_one [simp]:
"inv \<one> = \<one>"
by (metis Units_one_closed Units_r_inv l_one monoid.Units_inv_closed monoid_axioms)
lemma (in monoid) Units_inv_Units [intro, simp]:
"x \<in> Units G ==> inv x \<in> Units G"
proof -
assume x: "x \<in> Units G"
show "inv x \<in> Units G"
by (auto simp add: Units_def
intro: Units_l_inv Units_r_inv x Units_closed [OF x])
qed
lemma (in monoid) Units_l_cancel [simp]:
"[| x \<in> Units G; y \<in> carrier G; z \<in> carrier G |] ==>
(x \<otimes> y = x \<otimes> z) = (y = z)"
proof
assume eq: "x \<otimes> y = x \<otimes> z"
and G: "x \<in> Units G" "y \<in> carrier G" "z \<in> carrier G"
then have "(inv x \<otimes> x) \<otimes> y = (inv x \<otimes> x) \<otimes> z"
by (simp add: m_assoc Units_closed del: Units_l_inv)
with G show "y = z" by simp
next
assume eq: "y = z"
and G: "x \<in> Units G" "y \<in> carrier G" "z \<in> carrier G"
then show "x \<otimes> y = x \<otimes> z" by simp
qed
lemma (in monoid) Units_inv_inv [simp]:
"x \<in> Units G ==> inv (inv x) = x"
proof -
assume x: "x \<in> Units G"
then have "inv x \<otimes> inv (inv x) = inv x \<otimes> x" by simp
with x show ?thesis by (simp add: Units_closed del: Units_l_inv Units_r_inv)
qed
lemma (in monoid) inv_inj_on_Units:
"inj_on (m_inv G) (Units G)"
proof (rule inj_onI)
fix x y
assume G: "x \<in> Units G" "y \<in> Units G" and eq: "inv x = inv y"
then have "inv (inv x) = inv (inv y)" by simp
with G show "x = y" by simp
qed
lemma (in monoid) Units_inv_comm:
assumes inv: "x \<otimes> y = \<one>"
and G: "x \<in> Units G" "y \<in> Units G"
shows "y \<otimes> x = \<one>"
proof -
from G have "x \<otimes> y \<otimes> x = x \<otimes> \<one>" by (auto simp add: inv Units_closed)
with G show ?thesis by (simp del: r_one add: m_assoc Units_closed)
qed
lemma (in monoid) carrier_not_empty: "carrier G \<noteq> {}"
by auto
(* Jacobson defines submonoid here. *)
(* Jacobson defines the order of a monoid here. *)
subsection \<open>Groups\<close>
text \<open>
A group is a monoid all of whose elements are invertible.
\<close>
locale group = monoid +
assumes Units: "carrier G <= Units G"
lemma (in group) is_group [iff]: "group G" by (rule group_axioms)
lemma (in group) is_monoid [iff]: "monoid G"
by (rule monoid_axioms)
theorem groupI:
fixes G (structure)
assumes m_closed [simp]:
"!!x y. [| x \<in> carrier G; y \<in> carrier G |] ==> x \<otimes> y \<in> carrier G"
and one_closed [simp]: "\<one> \<in> carrier G"
and m_assoc:
"!!x y z. [| x \<in> carrier G; y \<in> carrier G; z \<in> carrier G |] ==>
(x \<otimes> y) \<otimes> z = x \<otimes> (y \<otimes> z)"
and l_one [simp]: "!!x. x \<in> carrier G ==> \<one> \<otimes> x = x"
and l_inv_ex: "!!x. x \<in> carrier G ==> \<exists>y \<in> carrier G. y \<otimes> x = \<one>"
shows "group G"
proof -
have l_cancel [simp]:
"!!x y z. [| x \<in> carrier G; y \<in> carrier G; z \<in> carrier G |] ==>
(x \<otimes> y = x \<otimes> z) = (y = z)"
proof
fix x y z
assume eq: "x \<otimes> y = x \<otimes> z"
and G: "x \<in> carrier G" "y \<in> carrier G" "z \<in> carrier G"
with l_inv_ex obtain x_inv where xG: "x_inv \<in> carrier G"
and l_inv: "x_inv \<otimes> x = \<one>" by fast
from G eq xG have "(x_inv \<otimes> x) \<otimes> y = (x_inv \<otimes> x) \<otimes> z"
by (simp add: m_assoc)
with G show "y = z" by (simp add: l_inv)
next
fix x y z
assume eq: "y = z"
and G: "x \<in> carrier G" "y \<in> carrier G" "z \<in> carrier G"
then show "x \<otimes> y = x \<otimes> z" by simp
qed
have r_one:
"!!x. x \<in> carrier G ==> x \<otimes> \<one> = x"
proof -
fix x
assume x: "x \<in> carrier G"
with l_inv_ex obtain x_inv where xG: "x_inv \<in> carrier G"
and l_inv: "x_inv \<otimes> x = \<one>" by fast
from x xG have "x_inv \<otimes> (x \<otimes> \<one>) = x_inv \<otimes> x"
by (simp add: m_assoc [symmetric] l_inv)
with x xG show "x \<otimes> \<one> = x" by simp
qed
have inv_ex:
"\<And>x. x \<in> carrier G \<Longrightarrow> \<exists>y \<in> carrier G. y \<otimes> x = \<one> \<and> x \<otimes> y = \<one>"
proof -
fix x
assume x: "x \<in> carrier G"
with l_inv_ex obtain y where y: "y \<in> carrier G"
and l_inv: "y \<otimes> x = \<one>" by fast
from x y have "y \<otimes> (x \<otimes> y) = y \<otimes> \<one>"
by (simp add: m_assoc [symmetric] l_inv r_one)
with x y have r_inv: "x \<otimes> y = \<one>"
by simp
from x y show "\<exists>y \<in> carrier G. y \<otimes> x = \<one> \<and> x \<otimes> y = \<one>"
by (fast intro: l_inv r_inv)
qed
then have carrier_subset_Units: "carrier G \<subseteq> Units G"
by (unfold Units_def) fast
show ?thesis
by standard (auto simp: r_one m_assoc carrier_subset_Units)
qed
lemma (in monoid) group_l_invI:
assumes l_inv_ex:
"!!x. x \<in> carrier G ==> \<exists>y \<in> carrier G. y \<otimes> x = \<one>"
shows "group G"
by (rule groupI) (auto intro: m_assoc l_inv_ex)
lemma (in group) Units_eq [simp]:
"Units G = carrier G"
proof
show "Units G \<subseteq> carrier G" by fast
next
show "carrier G \<subseteq> Units G" by (rule Units)
qed
lemma (in group) inv_closed [intro, simp]:
"x \<in> carrier G ==> inv x \<in> carrier G"
using Units_inv_closed by simp
lemma (in group) l_inv_ex [simp]:
"x \<in> carrier G ==> \<exists>y \<in> carrier G. y \<otimes> x = \<one>"
using Units_l_inv_ex by simp
lemma (in group) r_inv_ex [simp]:
"x \<in> carrier G ==> \<exists>y \<in> carrier G. x \<otimes> y = \<one>"
using Units_r_inv_ex by simp
lemma (in group) l_inv [simp]:
"x \<in> carrier G ==> inv x \<otimes> x = \<one>"
by simp
subsection \<open>Cancellation Laws and Basic Properties\<close>
lemma (in group) inv_eq_1_iff [simp]:
assumes "x \<in> carrier G" shows "inv\<^bsub>G\<^esub> x = \<one>\<^bsub>G\<^esub> \<longleftrightarrow> x = \<one>\<^bsub>G\<^esub>"
proof -
have "x = \<one>" if "inv x = \<one>"
proof -
have "inv x \<otimes> x = \<one>"
using assms l_inv by blast
then show "x = \<one>"
using that assms by simp
qed
then show ?thesis
by auto
qed
lemma (in group) r_inv [simp]:
"x \<in> carrier G ==> x \<otimes> inv x = \<one>"
by simp
lemma (in group) right_cancel [simp]:
"[| x \<in> carrier G; y \<in> carrier G; z \<in> carrier G |] ==>
(y \<otimes> x = z \<otimes> x) = (y = z)"
by (metis inv_closed m_assoc r_inv r_one)
lemma (in group) inv_inv [simp]:
"x \<in> carrier G ==> inv (inv x) = x"
using Units_inv_inv by simp
lemma (in group) inv_inj:
"inj_on (m_inv G) (carrier G)"
using inv_inj_on_Units by simp
lemma (in group) inv_mult_group:
"[| x \<in> carrier G; y \<in> carrier G |] ==> inv (x \<otimes> y) = inv y \<otimes> inv x"
proof -
assume G: "x \<in> carrier G" "y \<in> carrier G"
then have "inv (x \<otimes> y) \<otimes> (x \<otimes> y) = (inv y \<otimes> inv x) \<otimes> (x \<otimes> y)"
by (simp add: m_assoc) (simp add: m_assoc [symmetric])
with G show ?thesis by (simp del: l_inv Units_l_inv)
qed
lemma (in group) inv_comm:
"[| x \<otimes> y = \<one>; x \<in> carrier G; y \<in> carrier G |] ==> y \<otimes> x = \<one>"
by (rule Units_inv_comm) auto
lemma (in group) inv_equality:
"[|y \<otimes> x = \<one>; x \<in> carrier G; y \<in> carrier G|] ==> inv x = y"
using inv_unique r_inv by blast
lemma (in group) inv_solve_left:
"\<lbrakk> a \<in> carrier G; b \<in> carrier G; c \<in> carrier G \<rbrakk> \<Longrightarrow> a = inv b \<otimes> c \<longleftrightarrow> c = b \<otimes> a"
by (metis inv_equality l_inv_ex l_one m_assoc r_inv)
lemma (in group) inv_solve_left':
"\<lbrakk> a \<in> carrier G; b \<in> carrier G; c \<in> carrier G \<rbrakk> \<Longrightarrow> inv b \<otimes> c = a \<longleftrightarrow> c = b \<otimes> a"
by (metis inv_equality l_inv_ex l_one m_assoc r_inv)
lemma (in group) inv_solve_right:
"\<lbrakk> a \<in> carrier G; b \<in> carrier G; c \<in> carrier G \<rbrakk> \<Longrightarrow> a = b \<otimes> inv c \<longleftrightarrow> b = a \<otimes> c"
by (metis inv_equality l_inv_ex l_one m_assoc r_inv)
lemma (in group) inv_solve_right':
"\<lbrakk>a \<in> carrier G; b \<in> carrier G; c \<in> carrier G\<rbrakk> \<Longrightarrow> b \<otimes> inv c = a \<longleftrightarrow> b = a \<otimes> c"
by (auto simp: m_assoc)
subsection \<open>Power\<close>
consts
pow :: "[('a, 'm) monoid_scheme, 'a, 'b::semiring_1] => 'a" (infixr "[^]\<index>" 75)
overloading nat_pow == "pow :: [_, 'a, nat] => 'a"
begin
definition "nat_pow G a n = rec_nat \<one>\<^bsub>G\<^esub> (%u b. b \<otimes>\<^bsub>G\<^esub> a) n"
end
lemma (in monoid) nat_pow_closed [intro, simp]:
"x \<in> carrier G ==> x [^] (n::nat) \<in> carrier G"
by (induct n) (simp_all add: nat_pow_def)
lemma (in monoid) nat_pow_0 [simp]:
"x [^] (0::nat) = \<one>"
by (simp add: nat_pow_def)
lemma (in monoid) nat_pow_Suc [simp]:
"x [^] (Suc n) = x [^] n \<otimes> x"
by (simp add: nat_pow_def)
lemma (in monoid) nat_pow_one [simp]:
"\<one> [^] (n::nat) = \<one>"
by (induct n) simp_all
lemma (in monoid) nat_pow_mult:
"x \<in> carrier G ==> x [^] (n::nat) \<otimes> x [^] m = x [^] (n + m)"
by (induct m) (simp_all add: m_assoc [THEN sym])
lemma (in monoid) nat_pow_comm:
"x \<in> carrier G \<Longrightarrow> (x [^] (n::nat)) \<otimes> (x [^] (m :: nat)) = (x [^] m) \<otimes> (x [^] n)"
using nat_pow_mult[of x n m] nat_pow_mult[of x m n] by (simp add: add.commute)
lemma (in monoid) nat_pow_Suc2:
"x \<in> carrier G \<Longrightarrow> x [^] (Suc n) = x \<otimes> (x [^] n)"
using nat_pow_mult[of x 1 n] Suc_eq_plus1[of n]
by (metis One_nat_def Suc_eq_plus1_left l_one nat.rec(1) nat_pow_Suc nat_pow_def)
lemma (in monoid) nat_pow_pow:
"x \<in> carrier G ==> (x [^] n) [^] m = x [^] (n * m::nat)"
by (induct m) (simp, simp add: nat_pow_mult add.commute)
lemma (in monoid) nat_pow_consistent:
"x [^] (n :: nat) = x [^]\<^bsub>(G \<lparr> carrier := H \<rparr>)\<^esub> n"
unfolding nat_pow_def by simp
lemma nat_pow_0 [simp]: "x [^]\<^bsub>G\<^esub> (0::nat) = \<one>\<^bsub>G\<^esub>"
by (simp add: nat_pow_def)
lemma nat_pow_Suc [simp]: "x [^]\<^bsub>G\<^esub> (Suc n) = (x [^]\<^bsub>G\<^esub> n)\<otimes>\<^bsub>G\<^esub> x"
by (simp add: nat_pow_def)
lemma (in group) nat_pow_inv:
assumes "x \<in> carrier G" shows "(inv x) [^] (i :: nat) = inv (x [^] i)"
proof (induction i)
case 0 thus ?case by simp
next
case (Suc i)
have "(inv x) [^] Suc i = ((inv x) [^] i) \<otimes> inv x"
by simp
also have " ... = (inv (x [^] i)) \<otimes> inv x"
by (simp add: Suc.IH Suc.prems)
also have " ... = inv (x \<otimes> (x [^] i))"
by (simp add: assms inv_mult_group)
also have " ... = inv (x [^] (Suc i))"
using assms nat_pow_Suc2 by auto
finally show ?case .
qed
overloading int_pow == "pow :: [_, 'a, int] => 'a"
begin
definition "int_pow G a z =
(let p = rec_nat \<one>\<^bsub>G\<^esub> (%u b. b \<otimes>\<^bsub>G\<^esub> a)
in if z < 0 then inv\<^bsub>G\<^esub> (p (nat (-z))) else p (nat z))"
end
lemma int_pow_int: "x [^]\<^bsub>G\<^esub> (int n) = x [^]\<^bsub>G\<^esub> n"
by(simp add: int_pow_def nat_pow_def)
lemma pow_nat:
assumes "i\<ge>0"
shows "x [^]\<^bsub>G\<^esub> nat i = x [^]\<^bsub>G\<^esub> i"
proof (cases i rule: int_cases)
case (nonneg n)
then show ?thesis
by (simp add: int_pow_int)
next
case (neg n)
then show ?thesis
using assms by linarith
qed
lemma int_pow_0 [simp]: "x [^]\<^bsub>G\<^esub> (0::int) = \<one>\<^bsub>G\<^esub>"
by (simp add: int_pow_def)
lemma int_pow_def2: "a [^]\<^bsub>G\<^esub> z =
(if z < 0 then inv\<^bsub>G\<^esub> (a [^]\<^bsub>G\<^esub> (nat (-z))) else a [^]\<^bsub>G\<^esub> (nat z))"
by (simp add: int_pow_def nat_pow_def)
lemma (in group) int_pow_one [simp]:
"\<one> [^] (z::int) = \<one>"
by (simp add: int_pow_def2)
lemma (in group) int_pow_closed [intro, simp]:
"x \<in> carrier G ==> x [^] (i::int) \<in> carrier G"
by (simp add: int_pow_def2)
lemma (in group) int_pow_1 [simp]:
"x \<in> carrier G \<Longrightarrow> x [^] (1::int) = x"
by (simp add: int_pow_def2)
lemma (in group) int_pow_neg:
"x \<in> carrier G \<Longrightarrow> x [^] (-i::int) = inv (x [^] i)"
by (simp add: int_pow_def2)
lemma (in group) int_pow_neg_int: "x \<in> carrier G \<Longrightarrow> x [^] -(int n) = inv (x [^] n)"
by (simp add: int_pow_neg int_pow_int)
lemma (in group) int_pow_mult:
assumes "x \<in> carrier G" shows "x [^] (i + j::int) = x [^] i \<otimes> x [^] j"
proof -
have [simp]: "-i - j = -j - i" by simp
show ?thesis
by (auto simp: assms int_pow_def2 inv_solve_left inv_solve_right nat_add_distrib [symmetric] nat_pow_mult)
qed
lemma (in group) int_pow_inv:
"x \<in> carrier G \<Longrightarrow> (inv x) [^] (i :: int) = inv (x [^] i)"
by (metis int_pow_def2 nat_pow_inv)
lemma (in group) int_pow_pow:
assumes "x \<in> carrier G"
shows "(x [^] (n :: int)) [^] (m :: int) = x [^] (n * m :: int)"
proof (cases)
assume n_ge: "n \<ge> 0" thus ?thesis
proof (cases)
assume m_ge: "m \<ge> 0" thus ?thesis
using n_ge nat_pow_pow[OF assms, of "nat n" "nat m"] int_pow_def2 [where G=G]
by (simp add: mult_less_0_iff nat_mult_distrib)
next
assume m_lt: "\<not> m \<ge> 0"
with n_ge show ?thesis
apply (simp add: int_pow_def2 mult_less_0_iff)
by (metis assms mult_minus_right n_ge nat_mult_distrib nat_pow_pow)
qed
next
assume n_lt: "\<not> n \<ge> 0" thus ?thesis
proof (cases)
assume m_ge: "m \<ge> 0"
have "inv x [^] (nat m * nat (- n)) = inv x [^] nat (- (m * n))"
by (metis (full_types) m_ge mult_minus_right nat_mult_distrib)
with m_ge n_lt show ?thesis
by (simp add: int_pow_def2 mult_less_0_iff assms mult.commute nat_pow_inv nat_pow_pow)
next
assume m_lt: "\<not> m \<ge> 0" thus ?thesis
using n_lt by (auto simp: int_pow_def2 mult_less_0_iff assms nat_mult_distrib_neg nat_pow_inv nat_pow_pow)
qed
qed
lemma (in group) int_pow_diff:
"x \<in> carrier G \<Longrightarrow> x [^] (n - m :: int) = x [^] n \<otimes> inv (x [^] m)"
by(simp only: diff_conv_add_uminus int_pow_mult int_pow_neg)
lemma (in group) inj_on_multc: "c \<in> carrier G \<Longrightarrow> inj_on (\<lambda>x. x \<otimes> c) (carrier G)"
by(simp add: inj_on_def)
lemma (in group) inj_on_cmult: "c \<in> carrier G \<Longrightarrow> inj_on (\<lambda>x. c \<otimes> x) (carrier G)"
by(simp add: inj_on_def)
lemma (in monoid) group_commutes_pow:
fixes n::nat
shows "\<lbrakk>x \<otimes> y = y \<otimes> x; x \<in> carrier G; y \<in> carrier G\<rbrakk> \<Longrightarrow> x [^] n \<otimes> y = y \<otimes> x [^] n"
apply (induction n, auto)
by (metis m_assoc nat_pow_closed)
lemma (in monoid) pow_mult_distrib:
assumes eq: "x \<otimes> y = y \<otimes> x" and xy: "x \<in> carrier G" "y \<in> carrier G"
shows "(x \<otimes> y) [^] (n::nat) = x [^] n \<otimes> y [^] n"
proof (induct n)
case (Suc n)
have "x \<otimes> (y [^] n \<otimes> y) = y [^] n \<otimes> x \<otimes> y"
by (simp add: eq group_commutes_pow m_assoc xy)
then show ?case
using assms Suc.hyps m_assoc by auto
qed auto
lemma (in group) int_pow_mult_distrib:
assumes eq: "x \<otimes> y = y \<otimes> x" and xy: "x \<in> carrier G" "y \<in> carrier G"
shows "(x \<otimes> y) [^] (i::int) = x [^] i \<otimes> y [^] i"
proof (cases i rule: int_cases)
case (nonneg n)
then show ?thesis
by (metis eq int_pow_int pow_mult_distrib xy)
next
case (neg n)
then show ?thesis
unfolding neg
apply (simp add: xy int_pow_neg_int del: of_nat_Suc)
by (metis eq inv_mult_group local.nat_pow_Suc nat_pow_closed pow_mult_distrib xy)
qed
lemma (in group) pow_eq_div2:
fixes m n :: nat
assumes x_car: "x \<in> carrier G"
assumes pow_eq: "x [^] m = x [^] n"
shows "x [^] (m - n) = \<one>"
proof (cases "m < n")
case False
have "\<one> \<otimes> x [^] m = x [^] m" by (simp add: x_car)
also have "\<dots> = x [^] (m - n) \<otimes> x [^] n"
using False by (simp add: nat_pow_mult x_car)
also have "\<dots> = x [^] (m - n) \<otimes> x [^] m"
by (simp add: pow_eq)
finally show ?thesis
by (metis nat_pow_closed one_closed right_cancel x_car)
qed simp
subsection \<open>Submonoids\<close>
locale submonoid = \<^marker>\<open>contributor \<open>Martin Baillon\<close>\<close>
fixes H and G (structure)
assumes subset: "H \<subseteq> carrier G"
and m_closed [intro, simp]: "\<lbrakk>x \<in> H; y \<in> H\<rbrakk> \<Longrightarrow> x \<otimes> y \<in> H"
and one_closed [simp]: "\<one> \<in> H"
lemma (in submonoid) is_submonoid: \<^marker>\<open>contributor \<open>Martin Baillon\<close>\<close>
"submonoid H G" by (rule submonoid_axioms)
lemma (in submonoid) mem_carrier [simp]: \<^marker>\<open>contributor \<open>Martin Baillon\<close>\<close>
"x \<in> H \<Longrightarrow> x \<in> carrier G"
using subset by blast
lemma (in submonoid) submonoid_is_monoid [intro]: \<^marker>\<open>contributor \<open>Martin Baillon\<close>\<close>
assumes "monoid G"
shows "monoid (G\<lparr>carrier := H\<rparr>)"
proof -
interpret monoid G by fact
show ?thesis
by (simp add: monoid_def m_assoc)
qed
lemma submonoid_nonempty: \<^marker>\<open>contributor \<open>Martin Baillon\<close>\<close>
"~ submonoid {} G"
by (blast dest: submonoid.one_closed)
lemma (in submonoid) finite_monoid_imp_card_positive: \<^marker>\<open>contributor \<open>Martin Baillon\<close>\<close>
"finite (carrier G) ==> 0 < card H"
proof (rule classical)
assume "finite (carrier G)" and a: "~ 0 < card H"
then have "finite H" by (blast intro: finite_subset [OF subset])
with is_submonoid a have "submonoid {} G" by simp
with submonoid_nonempty show ?thesis by contradiction
qed
lemma (in monoid) monoid_incl_imp_submonoid : \<^marker>\<open>contributor \<open>Martin Baillon\<close>\<close>
assumes "H \<subseteq> carrier G"
and "monoid (G\<lparr>carrier := H\<rparr>)"
shows "submonoid H G"
proof (intro submonoid.intro[OF assms(1)])
have ab_eq : "\<And> a b. a \<in> H \<Longrightarrow> b \<in> H \<Longrightarrow> a \<otimes>\<^bsub>G\<lparr>carrier := H\<rparr>\<^esub> b = a \<otimes> b" using assms by simp
have "\<And>a b. a \<in> H \<Longrightarrow> b \<in> H \<Longrightarrow> a \<otimes> b \<in> carrier (G\<lparr>carrier := H\<rparr>) "
using assms ab_eq unfolding group_def using monoid.m_closed by fastforce
thus "\<And>a b. a \<in> H \<Longrightarrow> b \<in> H \<Longrightarrow> a \<otimes> b \<in> H" by simp
show "\<one> \<in> H " using monoid.one_closed[OF assms(2)] assms by simp
qed
lemma (in monoid) inv_unique': \<^marker>\<open>contributor \<open>Martin Baillon\<close>\<close>
assumes "x \<in> carrier G" "y \<in> carrier G"
shows "\<lbrakk> x \<otimes> y = \<one>; y \<otimes> x = \<one> \<rbrakk> \<Longrightarrow> y = inv x"
proof -
assume "x \<otimes> y = \<one>" and l_inv: "y \<otimes> x = \<one>"
hence unit: "x \<in> Units G"
using assms unfolding Units_def by auto
show "y = inv x"
using inv_unique[OF l_inv Units_r_inv[OF unit] assms Units_inv_closed[OF unit]] .
qed
lemma (in monoid) m_inv_monoid_consistent: \<^marker>\<open>contributor \<open>Paulo Emílio de Vilhena\<close>\<close>
assumes "x \<in> Units (G \<lparr> carrier := H \<rparr>)" and "submonoid H G"
shows "inv\<^bsub>(G \<lparr> carrier := H \<rparr>)\<^esub> x = inv x"
proof -
have monoid: "monoid (G \<lparr> carrier := H \<rparr>)"
using submonoid.submonoid_is_monoid[OF assms(2) monoid_axioms] .
obtain y where y: "y \<in> H" "x \<otimes> y = \<one>" "y \<otimes> x = \<one>"
using assms(1) unfolding Units_def by auto
have x: "x \<in> H" and in_carrier: "x \<in> carrier G" "y \<in> carrier G"
using y(1) submonoid.subset[OF assms(2)] assms(1) unfolding Units_def by auto
show ?thesis
using monoid.inv_unique'[OF monoid, of x y] x y
using inv_unique'[OF in_carrier y(2-3)] by auto
qed
subsection \<open>Subgroups\<close>
locale subgroup =
fixes H and G (structure)
assumes subset: "H \<subseteq> carrier G"
and m_closed [intro, simp]: "\<lbrakk>x \<in> H; y \<in> H\<rbrakk> \<Longrightarrow> x \<otimes> y \<in> H"
and one_closed [simp]: "\<one> \<in> H"
and m_inv_closed [intro,simp]: "x \<in> H \<Longrightarrow> inv x \<in> H"
lemma (in subgroup) is_subgroup:
"subgroup H G" by (rule subgroup_axioms)
declare (in subgroup) group.intro [intro]
lemma (in subgroup) mem_carrier [simp]:
"x \<in> H \<Longrightarrow> x \<in> carrier G"
using subset by blast
lemma (in subgroup) subgroup_is_group [intro]:
assumes "group G"
shows "group (G\<lparr>carrier := H\<rparr>)"
proof -
interpret group G by fact
have "Group.monoid (G\<lparr>carrier := H\<rparr>)"
by (simp add: monoid_axioms submonoid.intro submonoid.submonoid_is_monoid subset)
then show ?thesis
by (rule monoid.group_l_invI) (auto intro: l_inv mem_carrier)
qed
lemma subgroup_is_submonoid:
assumes "subgroup H G" shows "submonoid H G"
using assms by (auto intro: submonoid.intro simp add: subgroup_def)
lemma (in group) subgroup_Units:
assumes "subgroup H G" shows "H \<subseteq> Units (G \<lparr> carrier := H \<rparr>)"
using group.Units[OF subgroup.subgroup_is_group[OF assms group_axioms]] by simp
lemma (in group) m_inv_consistent [simp]:
assumes "subgroup H G" "x \<in> H"
shows "inv\<^bsub>(G \<lparr> carrier := H \<rparr>)\<^esub> x = inv x"
using assms m_inv_monoid_consistent[OF _ subgroup_is_submonoid] subgroup_Units[of H] by auto
lemma (in group) int_pow_consistent: \<^marker>\<open>contributor \<open>Paulo Emílio de Vilhena\<close>\<close>
assumes "subgroup H G" "x \<in> H"
shows "x [^] (n :: int) = x [^]\<^bsub>(G \<lparr> carrier := H \<rparr>)\<^esub> n"
proof (cases)
assume ge: "n \<ge> 0"
hence "x [^] n = x [^] (nat n)"
using int_pow_def2 [of G] by auto
also have " ... = x [^]\<^bsub>(G \<lparr> carrier := H \<rparr>)\<^esub> (nat n)"
using nat_pow_consistent by simp
also have " ... = x [^]\<^bsub>(G \<lparr> carrier := H \<rparr>)\<^esub> n"
by (metis ge int_nat_eq int_pow_int)
finally show ?thesis .
next
assume "\<not> n \<ge> 0" hence lt: "n < 0" by simp
hence "x [^] n = inv (x [^] (nat (- n)))"
using int_pow_def2 [of G] by auto
also have " ... = (inv x) [^] (nat (- n))"
by (metis assms nat_pow_inv subgroup.mem_carrier)
also have " ... = (inv\<^bsub>(G \<lparr> carrier := H \<rparr>)\<^esub> x) [^]\<^bsub>(G \<lparr> carrier := H \<rparr>)\<^esub> (nat (- n))"
using m_inv_consistent[OF assms] nat_pow_consistent by auto
also have " ... = inv\<^bsub>(G \<lparr> carrier := H \<rparr>)\<^esub> (x [^]\<^bsub>(G \<lparr> carrier := H \<rparr>)\<^esub> (nat (- n)))"
using group.nat_pow_inv[OF subgroup.subgroup_is_group[OF assms(1) is_group]] assms(2) by auto
also have " ... = x [^]\<^bsub>(G \<lparr> carrier := H \<rparr>)\<^esub> n"
by (simp add: int_pow_def2 lt)
finally show ?thesis .
qed
text \<open>
Since \<^term>\<open>H\<close> is nonempty, it contains some element \<^term>\<open>x\<close>. Since
it is closed under inverse, it contains \<open>inv x\<close>. Since
it is closed under product, it contains \<open>x \<otimes> inv x = \<one>\<close>.
\<close>
lemma (in group) one_in_subset:
"[| H \<subseteq> carrier G; H \<noteq> {}; \<forall>a \<in> H. inv a \<in> H; \<forall>a\<in>H. \<forall>b\<in>H. a \<otimes> b \<in> H |]
==> \<one> \<in> H"
by force
text \<open>A characterization of subgroups: closed, non-empty subset.\<close>
lemma (in group) subgroupI:
assumes subset: "H \<subseteq> carrier G" and non_empty: "H \<noteq> {}"
and inv: "!!a. a \<in> H \<Longrightarrow> inv a \<in> H"
and mult: "!!a b. \<lbrakk>a \<in> H; b \<in> H\<rbrakk> \<Longrightarrow> a \<otimes> b \<in> H"
shows "subgroup H G"
proof (simp add: subgroup_def assms)
show "\<one> \<in> H" by (rule one_in_subset) (auto simp only: assms)
qed
lemma (in group) subgroupE:
assumes "subgroup H G"
shows "H \<subseteq> carrier G"
and "H \<noteq> {}"
and "\<And>a. a \<in> H \<Longrightarrow> inv a \<in> H"
and "\<And>a b. \<lbrakk> a \<in> H; b \<in> H \<rbrakk> \<Longrightarrow> a \<otimes> b \<in> H"
using assms unfolding subgroup_def[of H G] by auto
declare monoid.one_closed [iff] group.inv_closed [simp]
monoid.l_one [simp] monoid.r_one [simp] group.inv_inv [simp]
lemma subgroup_nonempty:
"\<not> subgroup {} G"
by (blast dest: subgroup.one_closed)
lemma (in subgroup) finite_imp_card_positive: "finite (carrier G) \<Longrightarrow> 0 < card H"
using subset one_closed card_gt_0_iff finite_subset by blast
lemma (in subgroup) subgroup_is_submonoid : \<^marker>\<open>contributor \<open>Martin Baillon\<close>\<close>
"submonoid H G"
by (simp add: submonoid.intro subset)
lemma (in group) submonoid_subgroupI : \<^marker>\<open>contributor \<open>Martin Baillon\<close>\<close>
assumes "submonoid H G"
and "\<And>a. a \<in> H \<Longrightarrow> inv a \<in> H"
shows "subgroup H G"
by (metis assms subgroup_def submonoid_def)
lemma (in group) group_incl_imp_subgroup: \<^marker>\<open>contributor \<open>Martin Baillon\<close>\<close>
assumes "H \<subseteq> carrier G"
and "group (G\<lparr>carrier := H\<rparr>)"
shows "subgroup H G"
proof (intro submonoid_subgroupI[OF monoid_incl_imp_submonoid[OF assms(1)]])
show "monoid (G\<lparr>carrier := H\<rparr>)" using group_def assms by blast
have ab_eq : "\<And> a b. a \<in> H \<Longrightarrow> b \<in> H \<Longrightarrow> a \<otimes>\<^bsub>G\<lparr>carrier := H\<rparr>\<^esub> b = a \<otimes> b" using assms by simp
fix a assume aH : "a \<in> H"
have " inv\<^bsub>G\<lparr>carrier := H\<rparr>\<^esub> a \<in> carrier G"
using assms aH group.inv_closed[OF assms(2)] by auto
moreover have "\<one>\<^bsub>G\<lparr>carrier := H\<rparr>\<^esub> = \<one>" using assms monoid.one_closed ab_eq one_def by simp
hence "a \<otimes>\<^bsub>G\<lparr>carrier := H\<rparr>\<^esub> inv\<^bsub>G\<lparr>carrier := H\<rparr>\<^esub> a= \<one>"
using assms ab_eq aH group.r_inv[OF assms(2)] by simp
hence "a \<otimes> inv\<^bsub>G\<lparr>carrier := H\<rparr>\<^esub> a= \<one>"
using aH assms group.inv_closed[OF assms(2)] ab_eq by simp
ultimately have "inv\<^bsub>G\<lparr>carrier := H\<rparr>\<^esub> a = inv a"
by (metis aH assms(1) contra_subsetD group.inv_inv is_group local.inv_equality)
moreover have "inv\<^bsub>G\<lparr>carrier := H\<rparr>\<^esub> a \<in> H"
using aH group.inv_closed[OF assms(2)] by auto
ultimately show "inv a \<in> H" by auto
qed
subsection \<open>Direct Products\<close>
definition
DirProd :: "_ \<Rightarrow> _ \<Rightarrow> ('a \<times> 'b) monoid" (infixr "\<times>\<times>" 80) where
"G \<times>\<times> H =
\<lparr>carrier = carrier G \<times> carrier H,
mult = (\<lambda>(g, h) (g', h'). (g \<otimes>\<^bsub>G\<^esub> g', h \<otimes>\<^bsub>H\<^esub> h')),
one = (\<one>\<^bsub>G\<^esub>, \<one>\<^bsub>H\<^esub>)\<rparr>"
lemma DirProd_monoid:
assumes "monoid G" and "monoid H"
shows "monoid (G \<times>\<times> H)"
proof -
interpret G: monoid G by fact
interpret H: monoid H by fact
from assms
show ?thesis by (unfold monoid_def DirProd_def, auto)
qed
text\<open>Does not use the previous result because it's easier just to use auto.\<close>
lemma DirProd_group:
assumes "group G" and "group H"
shows "group (G \<times>\<times> H)"
proof -
interpret G: group G by fact
interpret H: group H by fact
show ?thesis by (rule groupI)
(auto intro: G.m_assoc H.m_assoc G.l_inv H.l_inv
simp add: DirProd_def)
qed
lemma carrier_DirProd [simp]: "carrier (G \<times>\<times> H) = carrier G \<times> carrier H"
by (simp add: DirProd_def)
lemma one_DirProd [simp]: "\<one>\<^bsub>G \<times>\<times> H\<^esub> = (\<one>\<^bsub>G\<^esub>, \<one>\<^bsub>H\<^esub>)"
by (simp add: DirProd_def)
lemma mult_DirProd [simp]: "(g, h) \<otimes>\<^bsub>(G \<times>\<times> H)\<^esub> (g', h') = (g \<otimes>\<^bsub>G\<^esub> g', h \<otimes>\<^bsub>H\<^esub> h')"
by (simp add: DirProd_def)
lemma mult_DirProd': "x \<otimes>\<^bsub>(G \<times>\<times> H)\<^esub> y = (fst x \<otimes>\<^bsub>G\<^esub> fst y, snd x \<otimes>\<^bsub>H\<^esub> snd y)"
by (subst mult_DirProd [symmetric]) simp
lemma DirProd_assoc: "(G \<times>\<times> H \<times>\<times> I) = (G \<times>\<times> (H \<times>\<times> I))"
by auto
lemma inv_DirProd [simp]:
assumes "group G" and "group H"
assumes g: "g \<in> carrier G"
and h: "h \<in> carrier H"
shows "m_inv (G \<times>\<times> H) (g, h) = (inv\<^bsub>G\<^esub> g, inv\<^bsub>H\<^esub> h)"
proof -
interpret G: group G by fact
interpret H: group H by fact
interpret Prod: group "G \<times>\<times> H"
by (auto intro: DirProd_group group.intro group.axioms assms)
show ?thesis by (simp add: Prod.inv_equality g h)
qed
lemma DirProd_subgroups :
assumes "group G"
and "subgroup H G"
and "group K"
and "subgroup I K"
shows "subgroup (H \<times> I) (G \<times>\<times> K)"
proof (intro group.group_incl_imp_subgroup[OF DirProd_group[OF assms(1)assms(3)]])
have "H \<subseteq> carrier G" "I \<subseteq> carrier K" using subgroup.subset assms by blast+
thus "(H \<times> I) \<subseteq> carrier (G \<times>\<times> K)" unfolding DirProd_def by auto
have "Group.group ((G\<lparr>carrier := H\<rparr>) \<times>\<times> (K\<lparr>carrier := I\<rparr>))"
using DirProd_group[OF subgroup.subgroup_is_group[OF assms(2)assms(1)]
subgroup.subgroup_is_group[OF assms(4)assms(3)]].
moreover have "((G\<lparr>carrier := H\<rparr>) \<times>\<times> (K\<lparr>carrier := I\<rparr>)) = ((G \<times>\<times> K)\<lparr>carrier := H \<times> I\<rparr>)"
unfolding DirProd_def using assms by simp
ultimately show "Group.group ((G \<times>\<times> K)\<lparr>carrier := H \<times> I\<rparr>)" by simp
qed
subsection \<open>Homomorphisms (mono and epi) and Isomorphisms\<close>
definition
hom :: "_ => _ => ('a => 'b) set" where
"hom G H =
{h. h \<in> carrier G \<rightarrow> carrier H \<and>
(\<forall>x \<in> carrier G. \<forall>y \<in> carrier G. h (x \<otimes>\<^bsub>G\<^esub> y) = h x \<otimes>\<^bsub>H\<^esub> h y)}"
lemma homI:
"\<lbrakk>\<And>x. x \<in> carrier G \<Longrightarrow> h x \<in> carrier H;
\<And>x y. \<lbrakk>x \<in> carrier G; y \<in> carrier G\<rbrakk> \<Longrightarrow> h (x \<otimes>\<^bsub>G\<^esub> y) = h x \<otimes>\<^bsub>H\<^esub> h y\<rbrakk> \<Longrightarrow> h \<in> hom G H"
by (auto simp: hom_def)
lemma hom_carrier: "h \<in> hom G H \<Longrightarrow> h ` carrier G \<subseteq> carrier H"
by (auto simp: hom_def)
lemma hom_in_carrier: "\<lbrakk>h \<in> hom G H; x \<in> carrier G\<rbrakk> \<Longrightarrow> h x \<in> carrier H"
by (auto simp: hom_def)
lemma hom_compose:
"\<lbrakk> f \<in> hom G H; g \<in> hom H I \<rbrakk> \<Longrightarrow> g \<circ> f \<in> hom G I"
unfolding hom_def by (auto simp add: Pi_iff)
lemma (in group) hom_restrict:
assumes "h \<in> hom G H" and "\<And>g. g \<in> carrier G \<Longrightarrow> h g = t g" shows "t \<in> hom G H"
using assms unfolding hom_def by (auto simp add: Pi_iff)
lemma (in group) hom_compose:
"[|h \<in> hom G H; i \<in> hom H I|] ==> compose (carrier G) i h \<in> hom G I"
by (fastforce simp add: hom_def compose_def)
lemma (in group) restrict_hom_iff [simp]:
"(\<lambda>x. if x \<in> carrier G then f x else g x) \<in> hom G H \<longleftrightarrow> f \<in> hom G H"
by (simp add: hom_def Pi_iff)
definition iso :: "_ => _ => ('a => 'b) set"
where "iso G H = {h. h \<in> hom G H \<and> bij_betw h (carrier G) (carrier H)}"
definition is_iso :: "_ \<Rightarrow> _ \<Rightarrow> bool" (infixr "\<cong>" 60)
where "G \<cong> H = (iso G H \<noteq> {})"
definition mon where "mon G H = {f \<in> hom G H. inj_on f (carrier G)}"
definition epi where "epi G H = {f \<in> hom G H. f ` (carrier G) = carrier H}"
lemma isoI:
"\<lbrakk>h \<in> hom G H; bij_betw h (carrier G) (carrier H)\<rbrakk> \<Longrightarrow> h \<in> iso G H"
by (auto simp: iso_def)
lemma is_isoI: "h \<in> iso G H \<Longrightarrow> G \<cong> H"
using is_iso_def by auto
lemma epi_iff_subset:
"f \<in> epi G G' \<longleftrightarrow> f \<in> hom G G' \<and> carrier G' \<subseteq> f ` carrier G"
by (auto simp: epi_def hom_def)
lemma iso_iff_mon_epi: "f \<in> iso G H \<longleftrightarrow> f \<in> mon G H \<and> f \<in> epi G H"
by (auto simp: iso_def mon_def epi_def bij_betw_def)
lemma iso_set_refl: "(\<lambda>x. x) \<in> iso G G"
by (simp add: iso_def hom_def inj_on_def bij_betw_def Pi_def)
lemma id_iso: "id \<in> iso G G"
by (simp add: iso_def hom_def inj_on_def bij_betw_def Pi_def)
corollary iso_refl [simp]: "G \<cong> G"
using iso_set_refl unfolding is_iso_def by auto
lemma iso_iff:
"h \<in> iso G H \<longleftrightarrow> h \<in> hom G H \<and> h ` (carrier G) = carrier H \<and> inj_on h (carrier G)"
by (auto simp: iso_def hom_def bij_betw_def)
lemma iso_imp_homomorphism:
"h \<in> iso G H \<Longrightarrow> h \<in> hom G H"
by (simp add: iso_iff)
lemma trivial_hom:
"group H \<Longrightarrow> (\<lambda>x. one H) \<in> hom G H"
by (auto simp: hom_def Group.group_def)
lemma (in group) hom_eq:
assumes "f \<in> hom G H" "\<And>x. x \<in> carrier G \<Longrightarrow> f' x = f x"
shows "f' \<in> hom G H"
using assms by (auto simp: hom_def)
lemma (in group) iso_eq:
assumes "f \<in> iso G H" "\<And>x. x \<in> carrier G \<Longrightarrow> f' x = f x"
shows "f' \<in> iso G H"
using assms by (fastforce simp: iso_def inj_on_def bij_betw_def hom_eq image_iff)
lemma (in group) iso_set_sym:
assumes "h \<in> iso G H"
shows "inv_into (carrier G) h \<in> iso H G"
proof -
have h: "h \<in> hom G H" "bij_betw h (carrier G) (carrier H)"
using assms by (auto simp add: iso_def bij_betw_inv_into)
then have HG: "bij_betw (inv_into (carrier G) h) (carrier H) (carrier G)"
by (simp add: bij_betw_inv_into)
have "inv_into (carrier G) h \<in> hom H G"
unfolding hom_def
proof safe
show *: "\<And>x. x \<in> carrier H \<Longrightarrow> inv_into (carrier G) h x \<in> carrier G"
by (meson HG bij_betwE)
show "inv_into (carrier G) h (x \<otimes>\<^bsub>H\<^esub> y) = inv_into (carrier G) h x \<otimes> inv_into (carrier G) h y"
if "x \<in> carrier H" "y \<in> carrier H" for x y
proof (rule inv_into_f_eq)
show "inj_on h (carrier G)"
using bij_betw_def h(2) by blast
show "inv_into (carrier G) h x \<otimes> inv_into (carrier G) h y \<in> carrier G"
by (simp add: * that)
show "h (inv_into (carrier G) h x \<otimes> inv_into (carrier G) h y) = x \<otimes>\<^bsub>H\<^esub> y"
using h bij_betw_inv_into_right [of h] unfolding hom_def by (simp add: "*" that)
qed
qed
then show ?thesis
by (simp add: Group.iso_def bij_betw_inv_into h)
qed
corollary (in group) iso_sym: "G \<cong> H \<Longrightarrow> H \<cong> G"
using iso_set_sym unfolding is_iso_def by auto
lemma iso_set_trans:
"\<lbrakk>h \<in> Group.iso G H; i \<in> Group.iso H I\<rbrakk> \<Longrightarrow> i \<circ> h \<in> Group.iso G I"
by (force simp: iso_def hom_compose intro: bij_betw_trans)
corollary iso_trans [trans]: "\<lbrakk>G \<cong> H ; H \<cong> I\<rbrakk> \<Longrightarrow> G \<cong> I"
using iso_set_trans unfolding is_iso_def by blast
lemma iso_same_card: "G \<cong> H \<Longrightarrow> card (carrier G) = card (carrier H)"
using bij_betw_same_card unfolding is_iso_def iso_def by auto
lemma iso_finite: "G \<cong> H \<Longrightarrow> finite(carrier G) \<longleftrightarrow> finite(carrier H)"
by (auto simp: is_iso_def iso_def bij_betw_finite)
lemma mon_compose:
"\<lbrakk>f \<in> mon G H; g \<in> mon H K\<rbrakk> \<Longrightarrow> (g \<circ> f) \<in> mon G K"
by (auto simp: mon_def intro: hom_compose comp_inj_on inj_on_subset [OF _ hom_carrier])
lemma mon_compose_rev:
"\<lbrakk>f \<in> hom G H; g \<in> hom H K; (g \<circ> f) \<in> mon G K\<rbrakk> \<Longrightarrow> f \<in> mon G H"
using inj_on_imageI2 by (auto simp: mon_def)
lemma epi_compose:
"\<lbrakk>f \<in> epi G H; g \<in> epi H K\<rbrakk> \<Longrightarrow> (g \<circ> f) \<in> epi G K"
using hom_compose by (force simp: epi_def hom_compose simp flip: image_image)
lemma epi_compose_rev:
"\<lbrakk>f \<in> hom G H; g \<in> hom H K; (g \<circ> f) \<in> epi G K\<rbrakk> \<Longrightarrow> g \<in> epi H K"
by (fastforce simp: epi_def hom_def Pi_iff image_def set_eq_iff)
lemma iso_compose_rev:
"\<lbrakk>f \<in> hom G H; g \<in> hom H K; (g \<circ> f) \<in> iso G K\<rbrakk> \<Longrightarrow> f \<in> mon G H \<and> g \<in> epi H K"
unfolding iso_iff_mon_epi using mon_compose_rev epi_compose_rev by blast
lemma epi_iso_compose_rev:
assumes "f \<in> epi G H" "g \<in> hom H K" "(g \<circ> f) \<in> iso G K"
shows "f \<in> iso G H \<and> g \<in> iso H K"
proof
show "f \<in> iso G H"
by (metis (no_types, lifting) assms epi_def iso_compose_rev iso_iff_mon_epi mem_Collect_eq)
then have "f \<in> hom G H \<and> bij_betw f (carrier G) (carrier H)"
using Group.iso_def \<open>f \<in> Group.iso G H\<close> by blast
then have "bij_betw g (carrier H) (carrier K)"
using Group.iso_def assms(3) bij_betw_comp_iff by blast
then show "g \<in> iso H K"
using Group.iso_def assms(2) by blast
qed
lemma mon_left_invertible:
"\<lbrakk>f \<in> hom G H; \<And>x. x \<in> carrier G \<Longrightarrow> g(f x) = x\<rbrakk> \<Longrightarrow> f \<in> mon G H"
by (simp add: mon_def inj_on_def) metis
lemma epi_right_invertible:
"\<lbrakk>g \<in> hom H G; f \<in> carrier G \<rightarrow> carrier H; \<And>x. x \<in> carrier G \<Longrightarrow> g(f x) = x\<rbrakk> \<Longrightarrow> g \<in> epi H G"
by (force simp: Pi_iff epi_iff_subset image_subset_iff_funcset subset_iff)
lemma (in monoid) hom_imp_img_monoid: \<^marker>\<open>contributor \<open>Paulo Emílio de Vilhena\<close>\<close>
assumes "h \<in> hom G H"
shows "monoid (H \<lparr> carrier := h ` (carrier G), one := h \<one>\<^bsub>G\<^esub> \<rparr>)" (is "monoid ?h_img")
proof (rule monoidI)
show "\<one>\<^bsub>?h_img\<^esub> \<in> carrier ?h_img"
by auto
next
fix x y z assume "x \<in> carrier ?h_img" "y \<in> carrier ?h_img" "z \<in> carrier ?h_img"
then obtain g1 g2 g3
where g1: "g1 \<in> carrier G" "x = h g1"
and g2: "g2 \<in> carrier G" "y = h g2"
and g3: "g3 \<in> carrier G" "z = h g3"
using image_iff[where ?f = h and ?A = "carrier G"] by auto
have aux_lemma:
"\<And>a b. \<lbrakk> a \<in> carrier G; b \<in> carrier G \<rbrakk> \<Longrightarrow> h a \<otimes>\<^bsub>(?h_img)\<^esub> h b = h (a \<otimes> b)"
using assms unfolding hom_def by auto
show "x \<otimes>\<^bsub>(?h_img)\<^esub> \<one>\<^bsub>(?h_img)\<^esub> = x"
using aux_lemma[OF g1(1) one_closed] g1(2) r_one[OF g1(1)] by simp
show "\<one>\<^bsub>(?h_img)\<^esub> \<otimes>\<^bsub>(?h_img)\<^esub> x = x"
using aux_lemma[OF one_closed g1(1)] g1(2) l_one[OF g1(1)] by simp
have "x \<otimes>\<^bsub>(?h_img)\<^esub> y = h (g1 \<otimes> g2)"
using aux_lemma g1 g2 by auto
thus "x \<otimes>\<^bsub>(?h_img)\<^esub> y \<in> carrier ?h_img"
using g1(1) g2(1) by simp
have "(x \<otimes>\<^bsub>(?h_img)\<^esub> y) \<otimes>\<^bsub>(?h_img)\<^esub> z = h ((g1 \<otimes> g2) \<otimes> g3)"
using aux_lemma g1 g2 g3 by auto
also have " ... = h (g1 \<otimes> (g2 \<otimes> g3))"
using m_assoc[OF g1(1) g2(1) g3(1)] by simp
also have " ... = x \<otimes>\<^bsub>(?h_img)\<^esub> (y \<otimes>\<^bsub>(?h_img)\<^esub> z)"
using aux_lemma g1 g2 g3 by auto
finally show "(x \<otimes>\<^bsub>(?h_img)\<^esub> y) \<otimes>\<^bsub>(?h_img)\<^esub> z = x \<otimes>\<^bsub>(?h_img)\<^esub> (y \<otimes>\<^bsub>(?h_img)\<^esub> z)" .
qed
lemma (in group) hom_imp_img_group: \<^marker>\<open>contributor \<open>Paulo Emílio de Vilhena\<close>\<close>
assumes "h \<in> hom G H"
shows "group (H \<lparr> carrier := h ` (carrier G), one := h \<one>\<^bsub>G\<^esub> \<rparr>)" (is "group ?h_img")
proof -
interpret monoid ?h_img
using hom_imp_img_monoid[OF assms] .
show ?thesis
proof (unfold_locales)
show "carrier ?h_img \<subseteq> Units ?h_img"
proof (auto simp add: Units_def)
have aux_lemma:
"\<And>g1 g2. \<lbrakk> g1 \<in> carrier G; g2 \<in> carrier G \<rbrakk> \<Longrightarrow> h g1 \<otimes>\<^bsub>H\<^esub> h g2 = h (g1 \<otimes> g2)"
using assms unfolding hom_def by auto
fix g1 assume g1: "g1 \<in> carrier G"
thus "\<exists>g2 \<in> carrier G. (h g2) \<otimes>\<^bsub>H\<^esub> (h g1) = h \<one> \<and> (h g1) \<otimes>\<^bsub>H\<^esub> (h g2) = h \<one>"
using aux_lemma[OF g1 inv_closed[OF g1]]
aux_lemma[OF inv_closed[OF g1] g1]
inv_closed by auto
qed
qed
qed
lemma (in group) iso_imp_group: \<^marker>\<open>contributor \<open>Paulo Emílio de Vilhena\<close>\<close>
assumes "G \<cong> H" and "monoid H"
shows "group H"
proof -
obtain \<phi> where phi: "\<phi> \<in> iso G H" "inv_into (carrier G) \<phi> \<in> iso H G"
using iso_set_sym assms unfolding is_iso_def by blast
define \<psi> where psi_def: "\<psi> = inv_into (carrier G) \<phi>"
have surj: "\<phi> ` (carrier G) = (carrier H)" "\<psi> ` (carrier H) = (carrier G)"
and inj: "inj_on \<phi> (carrier G)" "inj_on \<psi> (carrier H)"
and phi_hom: "\<And>g1 g2. \<lbrakk> g1 \<in> carrier G; g2 \<in> carrier G \<rbrakk> \<Longrightarrow> \<phi> (g1 \<otimes> g2) = (\<phi> g1) \<otimes>\<^bsub>H\<^esub> (\<phi> g2)"
and psi_hom: "\<And>h1 h2. \<lbrakk> h1 \<in> carrier H; h2 \<in> carrier H \<rbrakk> \<Longrightarrow> \<psi> (h1 \<otimes>\<^bsub>H\<^esub> h2) = (\<psi> h1) \<otimes> (\<psi> h2)"
using phi psi_def unfolding iso_def bij_betw_def hom_def by auto
have phi_one: "\<phi> \<one> = \<one>\<^bsub>H\<^esub>"
proof -
have "(\<phi> \<one>) \<otimes>\<^bsub>H\<^esub> \<one>\<^bsub>H\<^esub> = (\<phi> \<one>) \<otimes>\<^bsub>H\<^esub> (\<phi> \<one>)"
by (metis assms(2) image_eqI monoid.r_one one_closed phi_hom r_one surj(1))
thus ?thesis
by (metis (no_types, opaque_lifting) Units_eq Units_one_closed assms(2) f_inv_into_f imageI
monoid.l_one monoid.one_closed phi_hom psi_def r_one surj)
qed
have "carrier H \<subseteq> Units H"
proof
fix h assume h: "h \<in> carrier H"
let ?inv_h = "\<phi> (inv (\<psi> h))"
have "h \<otimes>\<^bsub>H\<^esub> ?inv_h = \<phi> (\<psi> h) \<otimes>\<^bsub>H\<^esub> ?inv_h"
by (simp add: f_inv_into_f h psi_def surj(1))
also have " ... = \<phi> ((\<psi> h) \<otimes> inv (\<psi> h))"
by (metis h imageI inv_closed phi_hom surj(2))
also have " ... = \<phi> \<one>"
by (simp add: h inv_into_into psi_def surj(1))
finally have 1: "h \<otimes>\<^bsub>H\<^esub> ?inv_h = \<one>\<^bsub>H\<^esub>"
using phi_one by simp
have "?inv_h \<otimes>\<^bsub>H\<^esub> h = ?inv_h \<otimes>\<^bsub>H\<^esub> \<phi> (\<psi> h)"
by (simp add: f_inv_into_f h psi_def surj(1))
also have " ... = \<phi> (inv (\<psi> h) \<otimes> (\<psi> h))"
by (metis h imageI inv_closed phi_hom surj(2))
also have " ... = \<phi> \<one>"
by (simp add: h inv_into_into psi_def surj(1))
finally have 2: "?inv_h \<otimes>\<^bsub>H\<^esub> h = \<one>\<^bsub>H\<^esub>"
using phi_one by simp
thus "h \<in> Units H" unfolding Units_def using 1 2 h surj by fastforce
qed
thus ?thesis unfolding group_def group_axioms_def using assms(2) by simp
qed
corollary (in group) iso_imp_img_group: \<^marker>\<open>contributor \<open>Paulo Emílio de Vilhena\<close>\<close>
assumes "h \<in> iso G H"
shows "group (H \<lparr> one := h \<one> \<rparr>)"
proof -
let ?h_img = "H \<lparr> carrier := h ` (carrier G), one := h \<one> \<rparr>"
have "h \<in> iso G ?h_img"
using assms unfolding iso_def hom_def bij_betw_def by auto
hence "G \<cong> ?h_img"
unfolding is_iso_def by auto
hence "group ?h_img"
using iso_imp_group[of ?h_img] hom_imp_img_monoid[of h H] assms unfolding iso_def by simp
moreover have "carrier H = carrier ?h_img"
using assms unfolding iso_def bij_betw_def by simp
hence "H \<lparr> one := h \<one> \<rparr> = ?h_img"
by simp
ultimately show ?thesis by simp
qed
subsubsection \<open>HOL Light's concept of an isomorphism pair\<close>
definition group_isomorphisms
where
"group_isomorphisms G H f g \<equiv>
f \<in> hom G H \<and> g \<in> hom H G \<and>
(\<forall>x \<in> carrier G. g(f x) = x) \<and>
(\<forall>y \<in> carrier H. f(g y) = y)"
lemma group_isomorphisms_sym: "group_isomorphisms G H f g \<Longrightarrow> group_isomorphisms H G g f"
by (auto simp: group_isomorphisms_def)
lemma group_isomorphisms_imp_iso: "group_isomorphisms G H f g \<Longrightarrow> f \<in> iso G H"
by (auto simp: iso_def inj_on_def image_def group_isomorphisms_def hom_def bij_betw_def Pi_iff, metis+)
lemma (in group) iso_iff_group_isomorphisms:
"f \<in> iso G H \<longleftrightarrow> (\<exists>g. group_isomorphisms G H f g)"
proof safe
show "\<exists>g. group_isomorphisms G H f g" if "f \<in> Group.iso G H"
unfolding group_isomorphisms_def
proof (intro exI conjI)
let ?g = "inv_into (carrier G) f"
show "\<forall>x\<in>carrier G. ?g (f x) = x"
by (metis (no_types, lifting) Group.iso_def bij_betw_inv_into_left mem_Collect_eq that)
show "\<forall>y\<in>carrier H. f (?g y) = y"
by (metis (no_types, lifting) Group.iso_def bij_betw_inv_into_right mem_Collect_eq that)
qed (use Group.iso_def iso_set_sym that in \<open>blast+\<close>)
next
fix g
assume "group_isomorphisms G H f g"
then show "f \<in> Group.iso G H"
by (auto simp: iso_def group_isomorphisms_def hom_in_carrier intro: bij_betw_byWitness)
qed
subsubsection \<open>Involving direct products\<close>
lemma DirProd_commute_iso_set:
shows "(\<lambda>(x,y). (y,x)) \<in> iso (G \<times>\<times> H) (H \<times>\<times> G)"
by (auto simp add: iso_def hom_def inj_on_def bij_betw_def)
corollary DirProd_commute_iso :
"(G \<times>\<times> H) \<cong> (H \<times>\<times> G)"
using DirProd_commute_iso_set unfolding is_iso_def by blast
lemma DirProd_assoc_iso_set:
shows "(\<lambda>(x,y,z). (x,(y,z))) \<in> iso (G \<times>\<times> H \<times>\<times> I) (G \<times>\<times> (H \<times>\<times> I))"
by (auto simp add: iso_def hom_def inj_on_def bij_betw_def)
lemma (in group) DirProd_iso_set_trans:
assumes "g \<in> iso G G2"
and "h \<in> iso H I"
shows "(\<lambda>(x,y). (g x, h y)) \<in> iso (G \<times>\<times> H) (G2 \<times>\<times> I)"
proof-
have "(\<lambda>(x,y). (g x, h y)) \<in> hom (G \<times>\<times> H) (G2 \<times>\<times> I)"
using assms unfolding iso_def hom_def by auto
moreover have " inj_on (\<lambda>(x,y). (g x, h y)) (carrier (G \<times>\<times> H))"
using assms unfolding iso_def DirProd_def bij_betw_def inj_on_def by auto
moreover have "(\<lambda>(x, y). (g x, h y)) ` carrier (G \<times>\<times> H) = carrier (G2 \<times>\<times> I)"
using assms unfolding iso_def bij_betw_def image_def DirProd_def by fastforce
ultimately show "(\<lambda>(x,y). (g x, h y)) \<in> iso (G \<times>\<times> H) (G2 \<times>\<times> I)"
unfolding iso_def bij_betw_def by auto
qed
corollary (in group) DirProd_iso_trans :
assumes "G \<cong> G2" and "H \<cong> I"
shows "G \<times>\<times> H \<cong> G2 \<times>\<times> I"
using DirProd_iso_set_trans assms unfolding is_iso_def by blast
lemma hom_pairwise: "f \<in> hom G (DirProd H K) \<longleftrightarrow> (fst \<circ> f) \<in> hom G H \<and> (snd \<circ> f) \<in> hom G K"
apply (auto simp: hom_def mult_DirProd' dest: Pi_mem)
apply (metis Product_Type.mem_Times_iff comp_eq_dest_lhs funcset_mem)
by (metis mult_DirProd prod.collapse)
lemma hom_paired:
"(\<lambda>x. (f x,g x)) \<in> hom G (DirProd H K) \<longleftrightarrow> f \<in> hom G H \<and> g \<in> hom G K"
by (simp add: hom_pairwise o_def)
lemma hom_paired2:
assumes "group G" "group H"
shows "(\<lambda>(x,y). (f x,g y)) \<in> hom (DirProd G H) (DirProd G' H') \<longleftrightarrow> f \<in> hom G G' \<and> g \<in> hom H H'"
using assms
by (fastforce simp: hom_def Pi_def dest!: group.is_monoid)
lemma iso_paired2:
assumes "group G" "group H"
shows "(\<lambda>(x,y). (f x,g y)) \<in> iso (DirProd G H) (DirProd G' H') \<longleftrightarrow> f \<in> iso G G' \<and> g \<in> iso H H'"
using assms
by (fastforce simp add: iso_def inj_on_def bij_betw_def hom_paired2 image_paired_Times
times_eq_iff group_def monoid.carrier_not_empty)
lemma hom_of_fst:
assumes "group H"
shows "(f \<circ> fst) \<in> hom (DirProd G H) K \<longleftrightarrow> f \<in> hom G K"
proof -
interpret group H
by (rule assms)
show ?thesis
using one_closed by (auto simp: hom_def Pi_def)
qed
lemma hom_of_snd:
assumes "group G"
shows "(f \<circ> snd) \<in> hom (DirProd G H) K \<longleftrightarrow> f \<in> hom H K"
proof -
interpret group G
by (rule assms)
show ?thesis
using one_closed by (auto simp: hom_def Pi_def)
qed
subsection\<open>The locale for a homomorphism between two groups\<close>
text\<open>Basis for homomorphism proofs: we assume two groups \<^term>\<open>G\<close> and
\<^term>\<open>H\<close>, with a homomorphism \<^term>\<open>h\<close> between them\<close>
locale group_hom = G?: group G + H?: group H for G (structure) and H (structure) +
fixes h
assumes homh [simp]: "h \<in> hom G H"
declare group_hom.homh [simp]
lemma (in group_hom) hom_mult [simp]:
"[| x \<in> carrier G; y \<in> carrier G |] ==> h (x \<otimes>\<^bsub>G\<^esub> y) = h x \<otimes>\<^bsub>H\<^esub> h y"
proof -
assume "x \<in> carrier G" "y \<in> carrier G"
with homh [unfolded hom_def] show ?thesis by simp
qed
lemma (in group_hom) hom_closed [simp]:
"x \<in> carrier G ==> h x \<in> carrier H"
proof -
assume "x \<in> carrier G"
with homh [unfolded hom_def] show ?thesis by auto
qed
lemma (in group_hom) one_closed: "h \<one> \<in> carrier H"
by simp
lemma (in group_hom) hom_one [simp]: "h \<one> = \<one>\<^bsub>H\<^esub>"
proof -
have "h \<one> \<otimes>\<^bsub>H\<^esub> \<one>\<^bsub>H\<^esub> = h \<one> \<otimes>\<^bsub>H\<^esub> h \<one>"
by (simp add: hom_mult [symmetric] del: hom_mult)
then show ?thesis
by (metis H.Units_eq H.Units_l_cancel H.one_closed local.one_closed)
qed
lemma hom_one:
assumes "h \<in> hom G H" "group G" "group H"
shows "h (one G) = one H"
apply (rule group_hom.hom_one)
by (simp add: assms group_hom_axioms_def group_hom_def)
lemma hom_mult:
"\<lbrakk>h \<in> hom G H; x \<in> carrier G; y \<in> carrier G\<rbrakk> \<Longrightarrow> h (x \<otimes>\<^bsub>G\<^esub> y) = h x \<otimes>\<^bsub>H\<^esub> h y"
by (auto simp: hom_def)
lemma (in group_hom) inv_closed [simp]:
"x \<in> carrier G ==> h (inv x) \<in> carrier H"
by simp
lemma (in group_hom) hom_inv [simp]:
assumes "x \<in> carrier G" shows "h (inv x) = inv\<^bsub>H\<^esub> (h x)"
proof -
have "h x \<otimes>\<^bsub>H\<^esub> h (inv x) = h x \<otimes>\<^bsub>H\<^esub> inv\<^bsub>H\<^esub> (h x)"
using assms by (simp flip: hom_mult)
with assms show ?thesis by (simp del: H.r_inv H.Units_r_inv)
qed
lemma (in group) int_pow_is_hom: \<^marker>\<open>contributor \<open>Joachim Breitner\<close>\<close>
"x \<in> carrier G \<Longrightarrow> (([^]) x) \<in> hom \<lparr> carrier = UNIV, mult = (+), one = 0::int \<rparr> G "
unfolding hom_def by (simp add: int_pow_mult)
lemma (in group_hom) img_is_subgroup: "subgroup (h ` (carrier G)) H" \<^marker>\<open>contributor \<open>Paulo Emílio de Vilhena\<close>\<close>
apply (rule subgroupI)
apply (auto simp add: image_subsetI)
apply (metis G.inv_closed hom_inv image_iff)
by (metis G.monoid_axioms hom_mult image_eqI monoid.m_closed)
lemma (in group_hom) subgroup_img_is_subgroup: \<^marker>\<open>contributor \<open>Paulo Emílio de Vilhena\<close>\<close>
assumes "subgroup I G"
shows "subgroup (h ` I) H"
proof -
have "h \<in> hom (G \<lparr> carrier := I \<rparr>) H"
using G.subgroupE[OF assms] subgroup.mem_carrier[OF assms] homh
unfolding hom_def by auto
hence "group_hom (G \<lparr> carrier := I \<rparr>) H h"
using subgroup.subgroup_is_group[OF assms G.is_group] is_group
unfolding group_hom_def group_hom_axioms_def by simp
thus ?thesis
using group_hom.img_is_subgroup[of "G \<lparr> carrier := I \<rparr>" H h] by simp
qed
lemma (in group_hom) induced_group_hom: \<^marker>\<open>contributor \<open>Paulo Emílio de Vilhena\<close>\<close>
assumes "subgroup I G"
shows "group_hom (G \<lparr> carrier := I \<rparr>) (H \<lparr> carrier := h ` I \<rparr>) h"
proof -
have "h \<in> hom (G \<lparr> carrier := I \<rparr>) (H \<lparr> carrier := h ` I \<rparr>)"
using homh subgroup.mem_carrier[OF assms] unfolding hom_def by auto
thus ?thesis
unfolding group_hom_def group_hom_axioms_def
using subgroup.subgroup_is_group[OF assms G.is_group]
subgroup.subgroup_is_group[OF subgroup_img_is_subgroup[OF assms] is_group] by simp
qed
lemma (in group) canonical_inj_is_hom: \<^marker>\<open>contributor \<open>Paulo Emílio de Vilhena\<close>\<close>
assumes "subgroup H G"
shows "group_hom (G \<lparr> carrier := H \<rparr>) G id"
unfolding group_hom_def group_hom_axioms_def hom_def
using subgroup.subgroup_is_group[OF assms is_group]
is_group subgroup.subset[OF assms] by auto
lemma (in group_hom) hom_nat_pow: \<^marker>\<open>contributor \<open>Paulo Emílio de Vilhena\<close>\<close>
"x \<in> carrier G \<Longrightarrow> h (x [^] (n :: nat)) = (h x) [^]\<^bsub>H\<^esub> n"
by (induction n) auto
lemma (in group_hom) hom_int_pow: \<^marker>\<open>contributor \<open>Paulo Emílio de Vilhena\<close>\<close>
"x \<in> carrier G \<Longrightarrow> h (x [^] (n :: int)) = (h x) [^]\<^bsub>H\<^esub> n"
using hom_nat_pow by (simp add: int_pow_def2)
lemma hom_nat_pow:
"\<lbrakk>h \<in> hom G H; x \<in> carrier G; group G; group H\<rbrakk> \<Longrightarrow> h (x [^]\<^bsub>G\<^esub> (n :: nat)) = (h x) [^]\<^bsub>H\<^esub> n"
by (simp add: group_hom.hom_nat_pow group_hom_axioms_def group_hom_def)
lemma hom_int_pow:
"\<lbrakk>h \<in> hom G H; x \<in> carrier G; group G; group H\<rbrakk> \<Longrightarrow> h (x [^]\<^bsub>G\<^esub> (n :: int)) = (h x) [^]\<^bsub>H\<^esub> n"
by (simp add: group_hom.hom_int_pow group_hom_axioms.intro group_hom_def)
subsection \<open>Commutative Structures\<close>
text \<open>
Naming convention: multiplicative structures that are commutative
are called \emph{commutative}, additive structures are called
\emph{Abelian}.
\<close>
locale comm_monoid = monoid +
assumes m_comm: "\<lbrakk>x \<in> carrier G; y \<in> carrier G\<rbrakk> \<Longrightarrow> x \<otimes> y = y \<otimes> x"
lemma (in comm_monoid) m_lcomm:
"\<lbrakk>x \<in> carrier G; y \<in> carrier G; z \<in> carrier G\<rbrakk> \<Longrightarrow>
x \<otimes> (y \<otimes> z) = y \<otimes> (x \<otimes> z)"
proof -
assume xyz: "x \<in> carrier G" "y \<in> carrier G" "z \<in> carrier G"
from xyz have "x \<otimes> (y \<otimes> z) = (x \<otimes> y) \<otimes> z" by (simp add: m_assoc)
also from xyz have "... = (y \<otimes> x) \<otimes> z" by (simp add: m_comm)
also from xyz have "... = y \<otimes> (x \<otimes> z)" by (simp add: m_assoc)
finally show ?thesis .
qed
lemmas (in comm_monoid) m_ac = m_assoc m_comm m_lcomm
lemma comm_monoidI:
fixes G (structure)
assumes m_closed:
"!!x y. [| x \<in> carrier G; y \<in> carrier G |] ==> x \<otimes> y \<in> carrier G"
and one_closed: "\<one> \<in> carrier G"
and m_assoc:
"!!x y z. [| x \<in> carrier G; y \<in> carrier G; z \<in> carrier G |] ==>
(x \<otimes> y) \<otimes> z = x \<otimes> (y \<otimes> z)"
and l_one: "!!x. x \<in> carrier G ==> \<one> \<otimes> x = x"
and m_comm:
"!!x y. [| x \<in> carrier G; y \<in> carrier G |] ==> x \<otimes> y = y \<otimes> x"
shows "comm_monoid G"
using l_one
by (auto intro!: comm_monoid.intro comm_monoid_axioms.intro monoid.intro
intro: assms simp: m_closed one_closed m_comm)
lemma (in monoid) monoid_comm_monoidI:
assumes m_comm:
"!!x y. [| x \<in> carrier G; y \<in> carrier G |] ==> x \<otimes> y = y \<otimes> x"
shows "comm_monoid G"
by (rule comm_monoidI) (auto intro: m_assoc m_comm)
lemma (in comm_monoid) submonoid_is_comm_monoid :
assumes "submonoid H G"
shows "comm_monoid (G\<lparr>carrier := H\<rparr>)"
proof (intro monoid.monoid_comm_monoidI)
show "monoid (G\<lparr>carrier := H\<rparr>)"
using submonoid.submonoid_is_monoid assms comm_monoid_axioms comm_monoid_def by blast
show "\<And>x y. x \<in> carrier (G\<lparr>carrier := H\<rparr>) \<Longrightarrow> y \<in> carrier (G\<lparr>carrier := H\<rparr>)
\<Longrightarrow> x \<otimes>\<^bsub>G\<lparr>carrier := H\<rparr>\<^esub> y = y \<otimes>\<^bsub>G\<lparr>carrier := H\<rparr>\<^esub> x"
by simp (meson assms m_comm submonoid.mem_carrier)
qed
locale comm_group = comm_monoid + group
lemma (in group) group_comm_groupI:
assumes m_comm: "!!x y. [| x \<in> carrier G; y \<in> carrier G |] ==> x \<otimes> y = y \<otimes> x"
shows "comm_group G"
by standard (simp_all add: m_comm)
lemma comm_groupI:
fixes G (structure)
assumes m_closed:
"!!x y. [| x \<in> carrier G; y \<in> carrier G |] ==> x \<otimes> y \<in> carrier G"
and one_closed: "\<one> \<in> carrier G"
and m_assoc:
"!!x y z. [| x \<in> carrier G; y \<in> carrier G; z \<in> carrier G |] ==>
(x \<otimes> y) \<otimes> z = x \<otimes> (y \<otimes> z)"
and m_comm:
"!!x y. [| x \<in> carrier G; y \<in> carrier G |] ==> x \<otimes> y = y \<otimes> x"
and l_one: "!!x. x \<in> carrier G ==> \<one> \<otimes> x = x"
and l_inv_ex: "!!x. x \<in> carrier G ==> \<exists>y \<in> carrier G. y \<otimes> x = \<one>"
shows "comm_group G"
by (fast intro: group.group_comm_groupI groupI assms)
lemma comm_groupE:
fixes G (structure)
assumes "comm_group G"
shows "\<And>x y. \<lbrakk> x \<in> carrier G; y \<in> carrier G \<rbrakk> \<Longrightarrow> x \<otimes> y \<in> carrier G"
and "\<one> \<in> carrier G"
and "\<And>x y z. \<lbrakk> x \<in> carrier G; y \<in> carrier G; z \<in> carrier G \<rbrakk> \<Longrightarrow> (x \<otimes> y) \<otimes> z = x \<otimes> (y \<otimes> z)"
and "\<And>x y. \<lbrakk> x \<in> carrier G; y \<in> carrier G \<rbrakk> \<Longrightarrow> x \<otimes> y = y \<otimes> x"
and "\<And>x. x \<in> carrier G \<Longrightarrow> \<one> \<otimes> x = x"
and "\<And>x. x \<in> carrier G \<Longrightarrow> \<exists>y \<in> carrier G. y \<otimes> x = \<one>"
apply (simp_all add: group.axioms assms comm_group.axioms comm_monoid.m_comm comm_monoid.m_ac(1))
by (simp_all add: Group.group.axioms(1) assms comm_group.axioms(2) monoid.m_closed group.r_inv_ex)
lemma (in comm_group) inv_mult:
"[| x \<in> carrier G; y \<in> carrier G |] ==> inv (x \<otimes> y) = inv x \<otimes> inv y"
by (simp add: m_ac inv_mult_group)
lemma (in comm_monoid) nat_pow_distrib:
fixes n::nat
assumes "x \<in> carrier G" "y \<in> carrier G"
shows "(x \<otimes> y) [^] n = x [^] n \<otimes> y [^] n"
by (simp add: assms pow_mult_distrib m_comm)
lemma (in comm_group) int_pow_distrib:
assumes "x \<in> carrier G" "y \<in> carrier G"
shows "(x \<otimes> y) [^] (i::int) = x [^] i \<otimes> y [^] i"
by (simp add: assms int_pow_mult_distrib m_comm)
lemma (in comm_monoid) hom_imp_img_comm_monoid: \<^marker>\<open>contributor \<open>Paulo Emílio de Vilhena\<close>\<close>
assumes "h \<in> hom G H"
shows "comm_monoid (H \<lparr> carrier := h ` (carrier G), one := h \<one>\<^bsub>G\<^esub> \<rparr>)" (is "comm_monoid ?h_img")
proof (rule monoid.monoid_comm_monoidI)
show "monoid ?h_img"
using hom_imp_img_monoid[OF assms] .
next
fix x y assume "x \<in> carrier ?h_img" "y \<in> carrier ?h_img"
then obtain g1 g2
where g1: "g1 \<in> carrier G" "x = h g1"
and g2: "g2 \<in> carrier G" "y = h g2"
by auto
have "x \<otimes>\<^bsub>(?h_img)\<^esub> y = h (g1 \<otimes> g2)"
using g1 g2 assms unfolding hom_def by auto
also have " ... = h (g2 \<otimes> g1)"
using m_comm[OF g1(1) g2(1)] by simp
also have " ... = y \<otimes>\<^bsub>(?h_img)\<^esub> x"
using g1 g2 assms unfolding hom_def by auto
finally show "x \<otimes>\<^bsub>(?h_img)\<^esub> y = y \<otimes>\<^bsub>(?h_img)\<^esub> x" .
qed
lemma (in comm_group) hom_group_mult:
assumes "f \<in> hom H G" "g \<in> hom H G"
shows "(\<lambda>x. f x \<otimes>\<^bsub>G\<^esub> g x) \<in> hom H G"
using assms by (auto simp: hom_def Pi_def m_ac)
lemma (in comm_group) hom_imp_img_comm_group: \<^marker>\<open>contributor \<open>Paulo Emílio de Vilhena\<close>\<close>
assumes "h \<in> hom G H"
shows "comm_group (H \<lparr> carrier := h ` (carrier G), one := h \<one>\<^bsub>G\<^esub> \<rparr>)"
unfolding comm_group_def
using hom_imp_img_group[OF assms] hom_imp_img_comm_monoid[OF assms] by simp
lemma (in comm_group) iso_imp_img_comm_group: \<^marker>\<open>contributor \<open>Paulo Emílio de Vilhena\<close>\<close>
assumes "h \<in> iso G H"
shows "comm_group (H \<lparr> one := h \<one>\<^bsub>G\<^esub> \<rparr>)"
proof -
let ?h_img = "H \<lparr> carrier := h ` (carrier G), one := h \<one> \<rparr>"
have "comm_group ?h_img"
using hom_imp_img_comm_group[of h H] assms unfolding iso_def by auto
moreover have "carrier H = carrier ?h_img"
using assms unfolding iso_def bij_betw_def by simp
hence "H \<lparr> one := h \<one> \<rparr> = ?h_img"
by simp
ultimately show ?thesis by simp
qed
lemma (in comm_group) iso_imp_comm_group: \<^marker>\<open>contributor \<open>Paulo Emílio de Vilhena\<close>\<close>
assumes "G \<cong> H" "monoid H"
shows "comm_group H"
proof -
obtain h where h: "h \<in> iso G H"
using assms(1) unfolding is_iso_def by auto
hence comm_gr: "comm_group (H \<lparr> one := h \<one> \<rparr>)"
using iso_imp_img_comm_group[of h H] by simp
hence "\<And>x. x \<in> carrier H \<Longrightarrow> h \<one> \<otimes>\<^bsub>H\<^esub> x = x"
using monoid.l_one[of "H \<lparr> one := h \<one> \<rparr>"] unfolding comm_group_def comm_monoid_def by simp
moreover have "h \<one> \<in> carrier H"
using h one_closed unfolding iso_def hom_def by auto
ultimately have "h \<one> = \<one>\<^bsub>H\<^esub>"
using monoid.one_unique[OF assms(2), of "h \<one>"] by simp
hence "H = H \<lparr> one := h \<one> \<rparr>"
by simp
thus ?thesis
using comm_gr by simp
qed
(*A subgroup of a subgroup is a subgroup of the group*)
lemma (in group) incl_subgroup:
assumes "subgroup J G"
and "subgroup I (G\<lparr>carrier:=J\<rparr>)"
shows "subgroup I G" unfolding subgroup_def
proof
have H1: "I \<subseteq> carrier (G\<lparr>carrier:=J\<rparr>)" using assms(2) subgroup.subset by blast
also have H2: "...\<subseteq>J" by simp
also have "...\<subseteq>(carrier G)" by (simp add: assms(1) subgroup.subset)
finally have H: "I \<subseteq> carrier G" by simp
have "(\<And>x y. \<lbrakk>x \<in> I ; y \<in> I\<rbrakk> \<Longrightarrow> x \<otimes> y \<in> I)" using assms(2) by (auto simp add: subgroup_def)
thus "I \<subseteq> carrier G \<and> (\<forall>x y. x \<in> I \<longrightarrow> y \<in> I \<longrightarrow> x \<otimes> y \<in> I)" using H by blast
have K: "\<one> \<in> I" using assms(2) by (auto simp add: subgroup_def)
have "(\<And>x. x \<in> I \<Longrightarrow> inv x \<in> I)" using assms subgroup.m_inv_closed H
by (metis H1 H2 m_inv_consistent subsetCE)
thus "\<one> \<in> I \<and> (\<forall>x. x \<in> I \<longrightarrow> inv x \<in> I)" using K by blast
qed
(*A subgroup included in another subgroup is a subgroup of the subgroup*)
lemma (in group) subgroup_incl:
assumes "subgroup I G" and "subgroup J G" and "I \<subseteq> J"
shows "subgroup I (G \<lparr> carrier := J \<rparr>)"
using group.group_incl_imp_subgroup[of "G \<lparr> carrier := J \<rparr>" I]
assms(1-2)[THEN subgroup.subgroup_is_group[OF _ group_axioms]] assms(3) by auto
subsection \<open>The Lattice of Subgroups of a Group\<close>
text_raw \<open>\label{sec:subgroup-lattice}\<close>
theorem (in group) subgroups_partial_order:
"partial_order \<lparr>carrier = {H. subgroup H G}, eq = (=), le = (\<subseteq>)\<rparr>"
by standard simp_all
lemma (in group) subgroup_self:
"subgroup (carrier G) G"
by (rule subgroupI) auto
lemma (in group) subgroup_imp_group:
"subgroup H G ==> group (G\<lparr>carrier := H\<rparr>)"
by (erule subgroup.subgroup_is_group) (rule group_axioms)
lemma (in group) subgroup_mult_equality:
"\<lbrakk> subgroup H G; h1 \<in> H; h2 \<in> H \<rbrakk> \<Longrightarrow> h1 \<otimes>\<^bsub>G \<lparr> carrier := H \<rparr>\<^esub> h2 = h1 \<otimes> h2"
unfolding subgroup_def by simp
theorem (in group) subgroups_Inter:
assumes subgr: "(\<And>H. H \<in> A \<Longrightarrow> subgroup H G)"
and not_empty: "A \<noteq> {}"
shows "subgroup (\<Inter>A) G"
proof (rule subgroupI)
from subgr [THEN subgroup.subset] and not_empty
show "\<Inter>A \<subseteq> carrier G" by blast
next
from subgr [THEN subgroup.one_closed]
show "\<Inter>A \<noteq> {}" by blast
next
fix x assume "x \<in> \<Inter>A"
with subgr [THEN subgroup.m_inv_closed]
show "inv x \<in> \<Inter>A" by blast
next
fix x y assume "x \<in> \<Inter>A" "y \<in> \<Inter>A"
with subgr [THEN subgroup.m_closed]
show "x \<otimes> y \<in> \<Inter>A" by blast
qed
lemma (in group) subgroups_Inter_pair :
assumes "subgroup I G"
and "subgroup J G"
shows "subgroup (I\<inter>J) G" using subgroups_Inter[ where ?A = "{I,J}"] assms by auto
theorem (in group) subgroups_complete_lattice:
"complete_lattice \<lparr>carrier = {H. subgroup H G}, eq = (=), le = (\<subseteq>)\<rparr>"
(is "complete_lattice ?L")
proof (rule partial_order.complete_lattice_criterion1)
show "partial_order ?L" by (rule subgroups_partial_order)
next
have "greatest ?L (carrier G) (carrier ?L)"
by (unfold greatest_def) (simp add: subgroup.subset subgroup_self)
then show "\<exists>G. greatest ?L G (carrier ?L)" ..
next
fix A
assume L: "A \<subseteq> carrier ?L" and non_empty: "A \<noteq> {}"
then have Int_subgroup: "subgroup (\<Inter>A) G"
by (fastforce intro: subgroups_Inter)
have "greatest ?L (\<Inter>A) (Lower ?L A)" (is "greatest _ ?Int _")
proof (rule greatest_LowerI)
fix H
assume H: "H \<in> A"
with L have subgroupH: "subgroup H G" by auto
from subgroupH have groupH: "group (G \<lparr>carrier := H\<rparr>)" (is "group ?H")
by (rule subgroup_imp_group)
from groupH have monoidH: "monoid ?H"
by (rule group.is_monoid)
from H have Int_subset: "?Int \<subseteq> H" by fastforce
then show "le ?L ?Int H" by simp
next
fix H
assume H: "H \<in> Lower ?L A"
with L Int_subgroup show "le ?L H ?Int"
by (fastforce simp: Lower_def intro: Inter_greatest)
next
show "A \<subseteq> carrier ?L" by (rule L)
next
show "?Int \<in> carrier ?L" by simp (rule Int_subgroup)
qed
then show "\<exists>I. greatest ?L I (Lower ?L A)" ..
qed
subsection\<open>The units in any monoid give rise to a group\<close>
text \<open>Thanks to Jeremy Avigad. The file Residues.thy provides some infrastructure to use
facts about the unit group within the ring locale.
\<close>
definition units_of :: "('a, 'b) monoid_scheme \<Rightarrow> 'a monoid"
where "units_of G =
\<lparr>carrier = Units G, Group.monoid.mult = Group.monoid.mult G, one = one G\<rparr>"
lemma (in monoid) units_group: "group (units_of G)"
proof -
have "\<And>x y z. \<lbrakk>x \<in> Units G; y \<in> Units G; z \<in> Units G\<rbrakk> \<Longrightarrow> x \<otimes> y \<otimes> z = x \<otimes> (y \<otimes> z)"
by (simp add: Units_closed m_assoc)
moreover have "\<And>x. x \<in> Units G \<Longrightarrow> \<exists>y\<in>Units G. y \<otimes> x = \<one>"
using Units_l_inv by blast
ultimately show ?thesis
unfolding units_of_def
by (force intro!: groupI)
qed
lemma (in comm_monoid) units_comm_group: "comm_group (units_of G)"
proof -
have "\<And>x y. \<lbrakk>x \<in> carrier (units_of G); y \<in> carrier (units_of G)\<rbrakk>
\<Longrightarrow> x \<otimes>\<^bsub>units_of G\<^esub> y = y \<otimes>\<^bsub>units_of G\<^esub> x"
by (simp add: Units_closed m_comm units_of_def)
then show ?thesis
by (rule group.group_comm_groupI [OF units_group]) auto
qed
lemma units_of_carrier: "carrier (units_of G) = Units G"
by (auto simp: units_of_def)
lemma units_of_mult: "mult (units_of G) = mult G"
by (auto simp: units_of_def)
lemma units_of_one: "one (units_of G) = one G"
by (auto simp: units_of_def)
lemma (in monoid) units_of_inv:
assumes "x \<in> Units G"
shows "m_inv (units_of G) x = m_inv G x"
by (simp add: assms group.inv_equality units_group units_of_carrier units_of_mult units_of_one)
lemma units_of_units [simp] : "Units (units_of G) = Units G"
unfolding units_of_def Units_def by force
lemma (in group) surj_const_mult: "a \<in> carrier G \<Longrightarrow> (\<lambda>x. a \<otimes> x) ` carrier G = carrier G"
apply (auto simp add: image_def)
by (metis inv_closed inv_solve_left m_closed)
lemma (in group) l_cancel_one [simp]: "x \<in> carrier G \<Longrightarrow> a \<in> carrier G \<Longrightarrow> x \<otimes> a = x \<longleftrightarrow> a = one G"
by (metis Units_eq Units_l_cancel monoid.r_one monoid_axioms one_closed)
lemma (in group) r_cancel_one [simp]: "x \<in> carrier G \<Longrightarrow> a \<in> carrier G \<Longrightarrow> a \<otimes> x = x \<longleftrightarrow> a = one G"
by (metis monoid.l_one monoid_axioms one_closed right_cancel)
lemma (in group) l_cancel_one' [simp]: "x \<in> carrier G \<Longrightarrow> a \<in> carrier G \<Longrightarrow> x = x \<otimes> a \<longleftrightarrow> a = one G"
using l_cancel_one by fastforce
lemma (in group) r_cancel_one' [simp]: "x \<in> carrier G \<Longrightarrow> a \<in> carrier G \<Longrightarrow> x = a \<otimes> x \<longleftrightarrow> a = one G"
using r_cancel_one by fastforce
declare pow_nat [simp] (*causes looping if added above, especially with int_pow_def2*)
end
|
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module HVX.BlackBoxTests.HuberTestSpec where
import Test.Hspec
import Numeric.LinearAlgebra
import Numeric.LinearAlgebra.Util (zeros)
import HVX
import HVX.Internal.TestUtil
-- Problem definition.
n = 4
a = EConst $ (n><n)
([0.5377 , 0.3188 , 3.5784 , 0.7254
, 1.8339 , -1.3077 , 2.7694 , -0.0631
, -2.2588 , -0.4336 , -1.3499 , 0.7147
, 0.8622 , 0.3426 , 3.0349 , -0.2050 ] :: [Double])
b = EConst $
(n><1) ([ -1.0689 , -0.8095 , -2.9443 , -1.4384 ] :: [Double])
c = EConst $ (n><n)
([ -0.1241 , 0.6715 , 0.4889 , 0.2939
, 1.4897 , -1.2075 , 1.0347 , -0.7873
, 1.4090 , 0.7172 , 0.7269 , 0.8884
, 1.4172 , 1.6302 , -0.3034 , -1.1471 ] :: [Double])
d = EConst $ (n><1)
([ 0.3252 , -0.7549 , 1.3703 , -1.7115 ] :: [Double])
x = EVar "x"
y = EVar "y"
constZeroVector = EConst $ zeros n 1
subgradAns = subgradMinimize
(hmax $ huber 3 (a *~ x +~ b) +~ berhu 1 (c *~ y +~ d))
[x +~ y <=~ constZeroVector]
(decNonSumStep 1.0) 100000
[("x", zeros n 1), ("y", zeros n 1)]
ellipsoidAns = ellipsoidMinimize
(hmax $ huber 3 (a *~ x +~ b) +~ berhu 1 (c *~ y +~ d))
[x +~ y <=~ constZeroVector]
[("x", n), ("y", n)]
1e-16 1e10
(subgradVars, subgradOptval) = subgradAns
(ellipsoidVars, ellipsoidOptval, ellipsoidUBound) = ellipsoidAns
-- CVX's results.
cvxOptval = 0.404882
--cvxOptx = (n><1) [-1.6137 ,-1.1202 ,0.7986 ,-0.7487 ]
--cvxOpty = (n><1) [0.2428 ,-0.0191 ,-0.7986 ,-1.0079 ]
-- Verify that HVX matches CVX.
spec :: Spec
spec =
describe "Verify that HVX matches CVX for huber/berhu" $ do
it "Verify that HVX subgrad matches CVX for huber/berhu" $
subgradOptval `shouldSatisfy` fpequalsApprox cvxOptval
it "Verify that HVX ellipsoid matches CVX for huber/berhu" $
ellipsoidOptval `shouldSatisfy` fpequalsApprox cvxOptval
main :: IO ()
main = hspec spec
|
#pragma once
#include "Library.h"
#include "Tile.h"
#include "TileContentLoadResult.h"
#include "TileContentLoader.h"
#include "TileRefine.h"
#include <gsl/span>
#include <spdlog/fwd.h>
#include <cstddef>
#include <memory>
#include <vector>
namespace Cesium3DTilesSelection {
class Tileset;
/**
* @brief Creates a {@link TileContentLoadResult} from 3D Tiles external
* `tileset.json` data.
*/
class CESIUM3DTILESSELECTION_API ExternalTilesetContent final
: public TileContentLoader {
public:
/**
* @copydoc TileContentLoader::load
*
* The result will only contain the `childTiles` and the `pNewTileContext`.
* Other fields will be empty or have default values.
*/
CesiumAsync::Future<std::unique_ptr<TileContentLoadResult>>
load(const TileContentLoadInput& input) override;
private:
/**
* @brief Create the {@link TileContentLoadResult} from the given input data.
*
* @param pLogger The logger that receives details of loading errors and
* warnings.
* @param tileRefine The {@link TileRefine}
* @param url The source URL
* @param data The raw input data
* @return The {@link TileContentLoadResult}
*/
static std::unique_ptr<TileContentLoadResult> load(
const std::shared_ptr<spdlog::logger>& pLogger,
const glm::dmat4& tileTransform,
TileRefine tileRefine,
const std::string& url,
const gsl::span<const std::byte>& data);
};
} // namespace Cesium3DTilesSelection
|
[STATEMENT]
lemma less_sets_UN2: "less_sets A (\<Union> \<B>) \<longleftrightarrow> (\<forall>B\<in>\<B>. A \<lless> B)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (A \<lless> \<Union> \<B>) = (\<forall>B\<in>\<B>. A \<lless> B)
[PROOF STEP]
by (auto simp: less_sets_def) |
#==============================================================================#
# mime.jl
#
# Simple MIME Multipart encoder.
#
# e.g.
#
# mime_multipart([
# ("foo.txt", "text/plain", "foo"),
# ("bar.txt", "text/plain", "bar")
# ])
#
# returns...
#
# "MIME-Version: 1.0
# Content-Type: multipart/mixed; boundary=\"=PRZLn8Nm1I82df0Dtj4ZvJi=\"
#
# --=PRZLn8Nm1I82df0Dtj4ZvJi=
# Content-Disposition: attachment; filename=foo.txt
# Content-Type: text/plain
# Content-Transfer-Encoding: binary
#
# foo
# --=PRZLn8Nm1I82df0Dtj4ZvJi=
# Content-Disposition: attachment; filename=bar.txt
# Content-Type: text/plain
# Content-Transfer-Encoding: binary
#
# bar
# --=PRZLn8Nm1I82df0Dtj4ZvJi=
#
#
# Copyright Sam O'Connor 2015 - All rights reserved
#==============================================================================#
mime_multipart(parts::Array) = mime_multipart("", parts::Array)
function mime_multipart(header::AbstractString, parts::Array)
boundary = "=PRZLn8Nm1I82df0Dtj4ZvJi="
mime =
"""
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="$boundary"
$header
"""
for (filename, content_type, content) in parts
mime *= "--$boundary\n"
if filename != ""
mime *= "Content-Type: $content_type;\n name=$filename\n"
mime *= "Content-Disposition: attachment;\n filename=$filename\n"
else
mime *= "Content-Type: $content_type\n"
end
if isa(content, AbstractString)
mime *= "Content-Transfer-Encoding: binary\n"
else
mime *= "Content-Transfer-Encoding: base64\n"
b64 = base64encode(content)
b64 = [b64[i:min(length(b64),i+75)] for i in 1:76:length(b64)]
content = join(b64, "\n")
end
mime *= "\n$content\n"
end
mime *= "--$boundary--\n"
return mime
end
#==============================================================================#
# End of file
#==============================================================================#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.