text
stringlengths 0
3.34M
|
---|
Require Import Essentials.Notations.
Require Import Essentials.Types.
Require Import Essentials.Facts_Tactics.
Require Import Category.Main.
Require Import Functor.Main.
Require Import Coq_Cats.Type_Cat.Type_Cat Coq_Cats.Type_Cat.Morphisms.
Require Import NatTrans.NatTrans
NatTrans.Operations
NatTrans.Func_Cat
NatTrans.Morphisms
NatTrans.NatIso.
Require Import Basic_Cons.Terminal.
Require Import PreSheaf.PreSheaf PreSheaf.Terminal.
Require Import Archetypal.Discr.Discr.
(** In this section we show that all components of a monic
morphism of presheaves are monic.
We do this by showing that given a monic morphism of presheaves
N : F ≫–> G we can convert any function from f : A → (F c) to
a morphism of presheaves (PSh(f) : Psh(A) –≻ F) such that this
morphism at c gives exactly f.
*)
Section PreSheaf_Monic_components_Monic.
Context
{C : Category}
{F : PreSheaf C}
.
Section PMCM_PreSheaf_representing_d.
Context (c : C) (d : Type).
Local Hint Extern 1 => progress cbn.
Program Definition PMCM_PreSheaf_representing_d : PreSheaf C
:=
{|
FO := fun c' => ((Hom C c' c) * d)%type;
FA := fun o o' u x => (compose C u (fst x), snd x)
|}
.
End PMCM_PreSheaf_representing_d.
Context
{G : PreSheaf C}
(N : @Monic (PShCat C) F G)
(c : C)
.
Section PreSheaf_Monic_components_Monic_is_Monic.
Context
(d : Type)
(g h : d → (F _o)%object c)
(H : (fun x => Trans (mono_morphism N) c (g x))
= (fun x => Trans (mono_morphism N) c (h x)))
.
(* Local Hint Extern 1 => progress cbn.*)
Local Hint Extern 1 =>
match goal with
[|- context [(F _a)%morphism (?A ∘ ?B)%morphism] ] =>
cbn_rewrite (F_compose F A B)
end.
Program Definition PMCM_PreSheaf_morph_of_function
(f : d → (F _o)%object c)
: (PMCM_PreSheaf_representing_d c d –≻ F)%nattrans
:=
{|
Trans := fun o x => (F _a (fst x))%morphism (f (snd x))
|}
.
Theorem PMCM_N_co_equalizes :
((mono_morphism N) ∘ (PMCM_PreSheaf_morph_of_function g))%nattrans
= ((mono_morphism N) ∘ (PMCM_PreSheaf_morph_of_function h))%nattrans.
Proof.
apply NatTrans_eq_simplify.
extensionality x.
extensionality y.
destruct y as [y1 y2].
cbn in *.
set (W := equal_f (Trans_com (mono_morphism N) y1)).
cbn in W.
do 2 rewrite W.
rewrite (equal_f H).
trivial.
Qed.
Theorem PreSheaf_Monic_components_is_Monic : g = h.
Proof.
extensionality m.
assert (W :=
f_equal
(fun w : (PMCM_PreSheaf_representing_d c d –≻ F)%nattrans =>
Trans w c (id, m))
(mono_morphism_monomorphic N _ _ _ PMCM_N_co_equalizes)
).
cbn in W.
rewrite (F_id F) in W.
trivial.
Qed.
End PreSheaf_Monic_components_Monic_is_Monic.
Definition PreSheaf_Monic_components_Monic_Monic :
Monic (F _o c)%object (G _o c)%object
:=
{|
mono_morphism := Trans (mono_morphism N) c;
mono_morphism_monomorphic :=
PreSheaf_Monic_components_is_Monic
|}.
End PreSheaf_Monic_components_Monic.
(** In this section we show that all components of an epic
morphism of presheaves are epic.
We do this by showing that given an epic morphism of presheaves
N : F –≫ G we can convert any function from f : (G c) → A to
a morphism of presheaves (PSh(f) : G –≻ Psh(A)) such that this
morphism at c gives exactly f.
*)
Section PreSheaf_Epic_components_Epic.
Context
{C : Category}
{F G : PreSheaf C}
(N : @Epic (PShCat C) F G)
(c : C)
.
Section PreSheaf_Epic_components_is_Epic.
Context
(d : Type)
(g h : (G _o)%object c → d)
(H : (fun x => g (Trans (mono_morphism N) c x)) =
(fun x => h (Trans (mono_morphism N) c x)))
.
Local Hint Extern 1 => progress cbn.
Local Hint Extern 1 => rewrite assoc.
Program Definition PECE_PreSheaf_representing_d : PreSheaf C
:=
{|
FO := fun c' => (((Hom C c c') → d))%object%morphism%type;
FA := fun o o' u x y => (x (compose C y u))
|}
.
Local Hint Extern 1 =>
match goal with
[|- context [(G _a)%morphism (?A ∘ ?B)%morphism] ] =>
cbn_rewrite (F_compose G A B)
end.
Program Definition PECE_PreSheaf_morph_of_function
(f : (G _o)%object c → d)
: (G –≻ PECE_PreSheaf_representing_d)%nattrans
:=
{|
Trans := fun o x y => f ((G _a y)%morphism x)
|}
.
Theorem PECE_N_co_equalizes :
((PECE_PreSheaf_morph_of_function g) ∘ (mono_morphism N))%nattrans =
((PECE_PreSheaf_morph_of_function h) ∘ (mono_morphism N))%nattrans.
Proof.
apply NatTrans_eq_simplify.
extensionality x.
extensionality y.
extensionality z.
cbn in *.
set (W := equal_f (Trans_com (mono_morphism N) z)).
cbn in W.
rewrite <- W.
rewrite (equal_f H).
trivial.
Qed.
Theorem PreSheaf_Epic_components_is_Epic : g = h.
Proof.
extensionality m.
assert (W :=
f_equal
(fun w : (G –≻ PECE_PreSheaf_representing_d)%nattrans =>
Trans w c m id)
(mono_morphism_monomorphic N _ _ _ PECE_N_co_equalizes)
).
cbn in W.
rewrite (F_id G) in W.
trivial.
Qed.
End PreSheaf_Epic_components_is_Epic.
Program Definition PreSheaf_Epic_components_Epic :
Epic (F _o c)%object (G _o c)%object
:=
{|
mono_morphism := Trans (mono_morphism N) c;
mono_morphism_monomorphic :=
PreSheaf_Epic_components_is_Epic
|}.
End PreSheaf_Epic_components_Epic.
Local Hint Extern 1 => match goal with
[|- context [(?F _a id)%morphism]] => rewrite (F_id F)
end.
Local Hint Extern 1 =>
match goal with
[|- context [(?F _a (?f ∘ ?g))%morphism]] =>
cbn_rewrite (F_compose F f g)
end.
Local Hint Extern 1 =>
match goal with
[|- context [Trans ?f _ ((?F _a)%morphism ?h _)]] =>
cbn_rewrite (equal_f (Trans_com f h))
end.
Local Hint Extern 1 => progress cbn in *.
(** In this section we show that a monic presheaf morphism can be split
into to presheaf morphisms one iso and one monic.
This result is inherited from that in Type_Cat and is proven similarly.
*)
Section Monic_PreSheaf_Iso_Monic_Factorization.
Context
{C : Category}
{F G : PreSheaf C}
(N : @Monic (PShCat C) F G)
.
Lemma sigT_sig_proof_irrelevance
{T : Type}
{P : T → Type}
{Q : ∀ x, (P x) → Prop}
(A B : sigT (fun y => sig (Q y)))
(H : projT1 A = projT1 B)
(H' :
(
proj1_sig
(
match H in _ = u return
{x : P u | Q u x}
with
eq_refl => projT2 A
end
)
)
=
(proj1_sig (projT2 B)))
:
A = B
.
Proof.
destruct A as [Ax [Ay HA]].
destruct B as [Bx [By HB]].
cbn in *.
transitivity
(
existT
(fun y : T => {x : P y | Q y x})
Bx
match H in _ = u return
{x : P u | Q u x}
with
eq_refl => (exist (Q Ax) Ay HA)
end
).
{
destruct H; trivial.
}
{
match goal with
[|- existT _ ?A ?B = existT _ ?A ?B'] =>
cutrewrite (B = B');trivial
end.
apply sig_proof_irrelevance; trivial.
}
Qed.
Local Hint Extern 1 =>
match goal with
[x : {_ : _ & {_ : _ | _}} |- _] =>
let H :=
fresh "H"
in
let x1 :=
fresh x "1"
in
let x2 :=
fresh x "2"
in
destruct x as [x1 [x2 H]]
end.
Local Hint Extern 1 =>
match goal with
[x : Monic_Image_of |- _] =>
let H :=
fresh "H"
in
let x1 :=
fresh x "1"
in
let x2 :=
fresh x "2"
in
destruct x as [x1 [x2 H]]
end.
Local Hint Extern 1 =>
match goal with
[|- ?A = ?B] =>
assert (H : (projT1 A) = (projT1 B));
[|
apply (sigT_sig_proof_irrelevance _ _ H);
destruct H
]
end.
Program Definition Monic_PreSheaf_Image_of : PreSheaf C
:=
{|
FO := fun x => @Monic_Image_of _ _ (Trans (mono_morphism N) x);
FA := fun c c' h x =>
existT _ (G _a h (projT1 x))%morphism
(exist _ (F _a h (proj1_sig (projT2 x)))%morphism _)
|}
.
Program Definition Monic_PreSheaf_Morph_From_Monic_PreSheaf_Image_of_forward :
(Monic_PreSheaf_Image_of –≻ G)%nattrans
:=
{|
Trans := fun x => @Monic_From_Image_forward _ _ (Trans (mono_morphism N) x)
|}.
Program Definition Monic_PreSheaf_From_Monic_PreSheaf_Image_of_back :
(Monic_PreSheaf_Image_of –≻ F)%nattrans
:=
{|
Trans := fun x => @Monic_From_Image_back _ _ (Trans (mono_morphism N) x)
|}.
Program Definition Monic_PreSheaf_To_Monic_PreSheaf_Image_of :
(F –≻ Monic_PreSheaf_Image_of)%nattrans
:=
{|
Trans := fun x => @Monic_To_Image _ _ (Trans (mono_morphism N) x)
|}.
Definition Monic_PreSheaf_Iso_Monic_Factor_Monic :
@Monic (PShCat C) Monic_PreSheaf_Image_of G.
Proof.
eapply (@is_Monic_Monic
(PShCat C)
_
_
Monic_PreSheaf_Morph_From_Monic_PreSheaf_Image_of_forward
)
.
apply is_Monic_components_is_Monic.
intros c.
set (W := fun A B f H => mono_morphism_monomorphic
(@Monic_Iso_Monic_Factor_Monic A B f H)).
unfold is_Monic in *.
cbn in *.
apply W.
apply PreSheaf_Monic_components_is_Monic.
Defined.
Program Definition Monic_PreSheaf_Iso_Monic_Factor_Monic_Iso :
@Isomorphism (PShCat C) F Monic_PreSheaf_Image_of
:=
{|
iso_morphism := Monic_PreSheaf_To_Monic_PreSheaf_Image_of;
inverse_morphism := Monic_PreSheaf_From_Monic_PreSheaf_Image_of_back
|}
.
Next Obligation.
Proof.
apply NatTrans_eq_simplify.
extensionality x.
extensionality y.
cbn in *.
apply (equal_f Monic_To_Image_form_split_epic).
Qed.
Theorem split_Epic_Monic_Factorization :
(mono_morphism N) =
(
(mono_morphism Monic_PreSheaf_Iso_Monic_Factor_Monic)
∘
(iso_morphism Monic_PreSheaf_Iso_Monic_Factor_Monic_Iso)
)%nattrans.
Proof.
apply NatTrans_eq_simplify; trivial.
Qed.
End Monic_PreSheaf_Iso_Monic_Factorization.
(** In this section we show that a presheaf morphism can be split
into to presheaf morphisms one epic and one monic.
This result is inherited from that in Type_Cat and is proven similarly.
The only difference is that in Type_Cat the epimorphism is split epic
while in presheaves, the morphisms back are not guaranteed to form a
natural transformation.
*)
Section PreSheaf_Epic_Monic_Factorization.
Context
{C : Category}
{F G : PreSheaf C}
(N : (F –≻ G)%nattrans)
.
Local Hint Extern 1 =>
match goal with
[x : {_ : _ | ∃ _, _} |- _] =>
let H :=
fresh "H"
in
let x1 :=
fresh x "1"
in
let x2 :=
fresh x "2"
in
destruct x as [x1 [x2 H]]
end.
Local Hint Extern 1 =>
match goal with
[x : Image_of _ |- _] =>
let H :=
fresh "H"
in
let x1 :=
fresh x "1"
in
let x2 :=
fresh x "2"
in
destruct x as [x1 [x2 H]]
end.
Local Obligation Tactic := basic_simpl; auto 10.
Program Definition PreSheaf_Image_of : PreSheaf C
:=
{|
FO := fun x => @Image_of _ _ (Trans N x);
FA := fun c c' h x => exist _ (G _a h (proj1_sig x))%morphism _
|}
.
Next Obligation.
Proof.
destruct x as [x [y []]].
exists (F _a h y)%morphism; auto.
Qed.
Program Definition PreSheaf_From_Image_Forward :
(PreSheaf_Image_of –≻ G)%nattrans
:=
{|
Trans := fun x => @From_Image_forward _ _ (Trans N x)
|}.
Definition PreSheaf_Epic_Monic_Factor_Monic :
@Monic (PShCat C) PreSheaf_Image_of G.
Proof.
eapply (@is_Monic_Monic
(PShCat C)
_
_
PreSheaf_From_Image_Forward
)
.
apply is_Monic_components_is_Monic.
intros c.
set (W := fun A B f => mono_morphism_monomorphic
(@Epic_Monic_Factor_Monic A B f)).
unfold is_Monic in *; cbn in *.
apply W.
Defined.
Local Hint Extern 1 => apply sig_proof_irrelevance.
Program Definition PreSheaf_To_Image :
(F –≻ PreSheaf_Image_of)%nattrans
:=
{|
Trans := fun x => To_Image (Trans N x)
|}.
Definition PreSheaf_Epic_Monic_Factor_Epic :
@Epic (PShCat C) F PreSheaf_Image_of.
Proof.
eapply (@is_Monic_Monic
((PShCat C) ^op)
_
_
PreSheaf_To_Image
)
.
apply is_Epic_components_is_Epic.
set (W := fun A B f => mono_morphism_monomorphic
(is_split_Monic_Monic
(@Epic_Monic_Factor_split_Epic A B f))).
unfold is_Epic, is_Monic in *; cbn in *.
intros c.
apply W.
Defined.
End PreSheaf_Epic_Monic_Factorization. |
Formal statement is: lemma multiplicity_characterization'_int [rule_format]: "finite {p. p \<ge> 0 \<and> 0 < f (p::int)} \<Longrightarrow> (\<forall>p. 0 < f p \<longrightarrow> prime p) \<Longrightarrow> prime p \<Longrightarrow> multiplicity p (\<Prod>p | p \<ge> 0 \<and> 0 < f p. p ^ f p) = f p" Informal statement is: If $f$ is a function from the positive integers to the positive integers such that the set of positive integers $p$ such that $f(p) > 0$ is finite and $f(p) > 0$ implies that $p$ is prime, then the multiplicity of $p$ in the product of the $p$-th powers of the primes $p$ such that $f(p) > 0$ is $f(p)$. |
Sugar Mummy – A beautiful lady in London is interested in a man for a long-term relationship. This 57 years old lady in London, England, Uk is single but has 3 grown up kids and granddaughters.
She is interested in a man of at least 47 years old of either White or Mixed race-ethnicity. She does not smoke but doesn’t care if you do, though she agrees to drink socially.
This lady who is a graduate with a Bachelors degree is only willing to relocate within London, so she is only interested in people around London or those who intend to move to London someday. |
/-
Copyright (c) 2020 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Yury Kudryashov
! This file was ported from Lean 3 source module topology.uniform_space.compact
! leanprover-community/mathlib commit ee05e9ce1322178f0c12004eb93c00d2c8c00ed2
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Topology.UniformSpace.UniformConvergence
import Mathbin.Topology.UniformSpace.Equicontinuity
import Mathbin.Topology.Separation
import Mathbin.Topology.Support
/-!
# Compact separated uniform spaces
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
## Main statements
* `compact_space_uniformity`: On a compact uniform space, the topology determines the
uniform structure, entourages are exactly the neighborhoods of the diagonal.
* `uniform_space_of_compact_t2`: every compact T2 topological structure is induced by a uniform
structure. This uniform structure is described in the previous item.
* **Heine-Cantor** theorem: continuous functions on compact uniform spaces with values in uniform
spaces are automatically uniformly continuous. There are several variations, the main one is
`compact_space.uniform_continuous_of_continuous`.
## Implementation notes
The construction `uniform_space_of_compact_t2` is not declared as an instance, as it would badly
loop.
## tags
uniform space, uniform continuity, compact space
-/
open Classical uniformity Topology Filter
open Filter UniformSpace Set
variable {α β γ : Type _} [UniformSpace α] [UniformSpace β]
/-!
### Uniformity on compact spaces
-/
/- warning: nhds_set_diagonal_eq_uniformity -> nhdsSet_diagonal_eq_uniformity is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} [_inst_1 : UniformSpace.{u1} α] [_inst_3 : CompactSpace.{u1} α (UniformSpace.toTopologicalSpace.{u1} α _inst_1)], Eq.{succ u1} (Filter.{u1} (Prod.{u1, u1} α α)) (nhdsSet.{u1} (Prod.{u1, u1} α α) (Prod.topologicalSpace.{u1, u1} α α (UniformSpace.toTopologicalSpace.{u1} α _inst_1) (UniformSpace.toTopologicalSpace.{u1} α _inst_1)) (Set.diagonal.{u1} α)) (uniformity.{u1} α _inst_1)
but is expected to have type
forall {α : Type.{u1}} [_inst_1 : UniformSpace.{u1} α] [_inst_3 : CompactSpace.{u1} α (UniformSpace.toTopologicalSpace.{u1} α _inst_1)], Eq.{succ u1} (Filter.{u1} (Prod.{u1, u1} α α)) (nhdsSet.{u1} (Prod.{u1, u1} α α) (instTopologicalSpaceProd.{u1, u1} α α (UniformSpace.toTopologicalSpace.{u1} α _inst_1) (UniformSpace.toTopologicalSpace.{u1} α _inst_1)) (Set.diagonal.{u1} α)) (uniformity.{u1} α _inst_1)
Case conversion may be inaccurate. Consider using '#align nhds_set_diagonal_eq_uniformity nhdsSet_diagonal_eq_uniformityₓ'. -/
/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/
/-- On a compact uniform space, the topology determines the uniform structure, entourages are
exactly the neighborhoods of the diagonal. -/
theorem nhdsSet_diagonal_eq_uniformity [CompactSpace α] : 𝓝ˢ (diagonal α) = 𝓤 α :=
by
refine' nhds_set_diagonal_le_uniformity.antisymm _
have :
(𝓤 (α × α)).HasBasis (fun U => U ∈ 𝓤 α) fun U =>
(fun p : (α × α) × α × α => ((p.1.1, p.2.1), p.1.2, p.2.2)) ⁻¹' U ×ˢ U :=
by
rw [uniformity_prod_eq_comap_prod]
exact (𝓤 α).basis_sets.prod_self.comap _
refine' (is_compact_diagonal.nhds_set_basis_uniformity this).ge_iff.2 fun U hU => _
exact mem_of_superset hU fun ⟨x, y⟩ hxy => mem_Union₂.2 ⟨(x, x), rfl, refl_mem_uniformity hU, hxy⟩
#align nhds_set_diagonal_eq_uniformity nhdsSet_diagonal_eq_uniformity
/- warning: compact_space_uniformity -> compactSpace_uniformity is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} [_inst_1 : UniformSpace.{u1} α] [_inst_3 : CompactSpace.{u1} α (UniformSpace.toTopologicalSpace.{u1} α _inst_1)], Eq.{succ u1} (Filter.{u1} (Prod.{u1, u1} α α)) (uniformity.{u1} α _inst_1) (supᵢ.{u1, succ u1} (Filter.{u1} (Prod.{u1, u1} α α)) (ConditionallyCompleteLattice.toHasSup.{u1} (Filter.{u1} (Prod.{u1, u1} α α)) (CompleteLattice.toConditionallyCompleteLattice.{u1} (Filter.{u1} (Prod.{u1, u1} α α)) (Filter.completeLattice.{u1} (Prod.{u1, u1} α α)))) α (fun (x : α) => nhds.{u1} (Prod.{u1, u1} α α) (Prod.topologicalSpace.{u1, u1} α α (UniformSpace.toTopologicalSpace.{u1} α _inst_1) (UniformSpace.toTopologicalSpace.{u1} α _inst_1)) (Prod.mk.{u1, u1} α α x x)))
but is expected to have type
forall {α : Type.{u1}} [_inst_1 : UniformSpace.{u1} α] [_inst_3 : CompactSpace.{u1} α (UniformSpace.toTopologicalSpace.{u1} α _inst_1)], Eq.{succ u1} (Filter.{u1} (Prod.{u1, u1} α α)) (uniformity.{u1} α _inst_1) (supᵢ.{u1, succ u1} (Filter.{u1} (Prod.{u1, u1} α α)) (ConditionallyCompleteLattice.toSupSet.{u1} (Filter.{u1} (Prod.{u1, u1} α α)) (CompleteLattice.toConditionallyCompleteLattice.{u1} (Filter.{u1} (Prod.{u1, u1} α α)) (Filter.instCompleteLatticeFilter.{u1} (Prod.{u1, u1} α α)))) α (fun (x : α) => nhds.{u1} (Prod.{u1, u1} α α) (instTopologicalSpaceProd.{u1, u1} α α (UniformSpace.toTopologicalSpace.{u1} α _inst_1) (UniformSpace.toTopologicalSpace.{u1} α _inst_1)) (Prod.mk.{u1, u1} α α x x)))
Case conversion may be inaccurate. Consider using '#align compact_space_uniformity compactSpace_uniformityₓ'. -/
/-- On a compact uniform space, the topology determines the uniform structure, entourages are
exactly the neighborhoods of the diagonal. -/
theorem compactSpace_uniformity [CompactSpace α] : 𝓤 α = ⨆ x, 𝓝 (x, x) :=
nhdsSet_diagonal_eq_uniformity.symm.trans (nhdsSet_diagonal _)
#align compact_space_uniformity compactSpace_uniformity
#print unique_uniformity_of_compact /-
theorem unique_uniformity_of_compact [t : TopologicalSpace γ] [CompactSpace γ]
{u u' : UniformSpace γ} (h : u.toTopologicalSpace = t) (h' : u'.toTopologicalSpace = t) :
u = u' := by
apply uniformSpace_eq
change uniformity _ = uniformity _
have : @CompactSpace γ u.to_topological_space := by rwa [h]
have : @CompactSpace γ u'.to_topological_space := by rwa [h']
rw [compactSpace_uniformity, compactSpace_uniformity, h, h']
#align unique_uniformity_of_compact unique_uniformity_of_compact
-/
/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/
/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/
/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/
/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/
/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/
/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (y «expr ≠ » x) -/
#print uniformSpaceOfCompactT2 /-
/-- The unique uniform structure inducing a given compact topological structure. -/
def uniformSpaceOfCompactT2 [TopologicalSpace γ] [CompactSpace γ] [T2Space γ] : UniformSpace γ
where
uniformity := 𝓝ˢ (diagonal γ)
refl := principal_le_nhdsSet
symm := continuous_swap.tendsto_nhdsSet fun x => Eq.symm
comp :=
by
/-
This is the difficult part of the proof. We need to prove that, for each neighborhood `W`
of the diagonal `Δ`, there exists a smaller neighborhood `V` such that `V ○ V ⊆ W`.
-/
set 𝓝Δ := 𝓝ˢ (diagonal γ)
-- The filter of neighborhoods of Δ
set F := 𝓝Δ.lift' fun s : Set (γ × γ) => s ○ s
-- Compositions of neighborhoods of Δ
-- If this weren't true, then there would be V ∈ 𝓝Δ such that F ⊓ 𝓟 Vᶜ ≠ ⊥
rw [le_iff_forall_inf_principal_compl]
intro V V_in
by_contra H
haveI : ne_bot (F ⊓ 𝓟 (Vᶜ)) := ⟨H⟩
-- Hence compactness would give us a cluster point (x, y) for F ⊓ 𝓟 Vᶜ
obtain ⟨⟨x, y⟩, hxy⟩ : ∃ p : γ × γ, ClusterPt p (F ⊓ 𝓟 (Vᶜ)) := cluster_point_of_compact _
-- In particular (x, y) is a cluster point of 𝓟 Vᶜ, hence is not in the interior of V,
-- and a fortiori not in Δ, so x ≠ y
have clV : ClusterPt (x, y) (𝓟 <| Vᶜ) := hxy.of_inf_right
have : (x, y) ∉ interior V :=
by
have : (x, y) ∈ closure (Vᶜ) := by rwa [mem_closure_iff_clusterPt]
rwa [closure_compl] at this
have diag_subset : diagonal γ ⊆ interior V := subset_interior_iff_mem_nhdsSet.2 V_in
have x_ne_y : x ≠ y := mt (@diag_subset (x, y)) this
-- Since γ is compact and Hausdorff, it is normal, hence T₃.
haveI : NormalSpace γ := normalOfCompactT2
-- So there are closed neighboords V₁ and V₂ of x and y contained in disjoint open neighborhoods
-- U₁ and U₂.
obtain
⟨U₁, U₁_in, V₁, V₁_in, U₂, U₂_in₂, V₂, V₂_in, V₁_cl, V₂_cl, U₁_op, U₂_op, VU₁, VU₂, hU₁₂⟩ :=
disjoint_nested_nhds x_ne_y
-- We set U₃ := (V₁ ∪ V₂)ᶜ so that W := U₁ ×ˢ U₁ ∪ U₂ ×ˢ U₂ ∪ U₃ ×ˢ U₃ is an open
-- neighborhood of Δ.
let U₃ := (V₁ ∪ V₂)ᶜ
have U₃_op : IsOpen U₃ := (V₁_cl.union V₂_cl).isOpen_compl
let W := U₁ ×ˢ U₁ ∪ U₂ ×ˢ U₂ ∪ U₃ ×ˢ U₃
have W_in : W ∈ 𝓝Δ := by
rw [mem_nhdsSet_iff_forall]
rintro ⟨z, z'⟩ (rfl : z = z')
refine' IsOpen.mem_nhds _ _
· apply_rules [IsOpen.union, IsOpen.prod]
· simp only [mem_union, mem_prod, and_self_iff]
exact (em _).imp_left fun h => union_subset_union VU₁ VU₂ h
-- So W ○ W ∈ F by definition of F
have : W ○ W ∈ F := by simpa only using mem_lift' W_in
-- And V₁ ×ˢ V₂ ∈ 𝓝 (x, y)
have hV₁₂ : V₁ ×ˢ V₂ ∈ 𝓝 (x, y) := prod_mem_nhds V₁_in V₂_in
-- But (x, y) is also a cluster point of F so (V₁ ×ˢ V₂) ∩ (W ○ W) ≠ ∅
-- However the construction of W implies (V₁ ×ˢ V₂) ∩ (W ○ W) = ∅.
-- Indeed assume for contradiction there is some (u, v) in the intersection.
obtain ⟨⟨u, v⟩, ⟨u_in, v_in⟩, w, huw, hwv⟩ := cluster_pt_iff.mp hxy.of_inf_left hV₁₂ this
-- So u ∈ V₁, v ∈ V₂, and there exists some w such that (u, w) ∈ W and (w ,v) ∈ W.
-- Because u is in V₁ which is disjoint from U₂ and U₃, (u, w) ∈ W forces (u, w) ∈ U₁ ×ˢ U₁.
have uw_in : (u, w) ∈ U₁ ×ˢ U₁ :=
(huw.resolve_right fun h => h.1 <| Or.inl u_in).resolve_right fun h =>
hU₁₂.le_bot ⟨VU₁ u_in, h.1⟩
-- Similarly, because v ∈ V₂, (w ,v) ∈ W forces (w, v) ∈ U₂ ×ˢ U₂.
have wv_in : (w, v) ∈ U₂ ×ˢ U₂ :=
(hwv.resolve_right fun h => h.2 <| Or.inr v_in).resolve_left fun h =>
hU₁₂.le_bot ⟨h.2, VU₂ v_in⟩
-- Hence w ∈ U₁ ∩ U₂ which is empty.
-- So we have a contradiction
exact hU₁₂.le_bot ⟨uw_in.2, wv_in.1⟩
isOpen_uniformity :=
by
-- Here we need to prove the topology induced by the constructed uniformity is the
-- topology we started with.
suffices ∀ x : γ, Filter.comap (Prod.mk x) (𝓝ˢ (diagonal γ)) = 𝓝 x
by
intro s
simp_rw [isOpen_fold, isOpen_iff_mem_nhds, ← mem_comap_prod_mk, this]
intro x
simp_rw [nhdsSet_diagonal, comap_supr, nhds_prod_eq, comap_prod, (· ∘ ·), comap_id']
rw [supᵢ_split_single _ x, comap_const_of_mem fun V => mem_of_mem_nhds]
suffices ∀ (y) (_ : y ≠ x), comap (fun y : γ => x) (𝓝 y) ⊓ 𝓝 y ≤ 𝓝 x by simpa
intro y hxy
simp [comap_const_of_not_mem (compl_singleton_mem_nhds hxy) (Classical.not_not.2 rfl)]
#align uniform_space_of_compact_t2 uniformSpaceOfCompactT2
-/
/-!
### Heine-Cantor theorem
-/
/- warning: compact_space.uniform_continuous_of_continuous -> CompactSpace.uniformContinuous_of_continuous is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : UniformSpace.{u1} α] [_inst_2 : UniformSpace.{u2} β] [_inst_3 : CompactSpace.{u1} α (UniformSpace.toTopologicalSpace.{u1} α _inst_1)] {f : α -> β}, (Continuous.{u1, u2} α β (UniformSpace.toTopologicalSpace.{u1} α _inst_1) (UniformSpace.toTopologicalSpace.{u2} β _inst_2) f) -> (UniformContinuous.{u1, u2} α β _inst_1 _inst_2 f)
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} [_inst_1 : UniformSpace.{u2} α] [_inst_2 : UniformSpace.{u1} β] [_inst_3 : CompactSpace.{u2} α (UniformSpace.toTopologicalSpace.{u2} α _inst_1)] {f : α -> β}, (Continuous.{u2, u1} α β (UniformSpace.toTopologicalSpace.{u2} α _inst_1) (UniformSpace.toTopologicalSpace.{u1} β _inst_2) f) -> (UniformContinuous.{u2, u1} α β _inst_1 _inst_2 f)
Case conversion may be inaccurate. Consider using '#align compact_space.uniform_continuous_of_continuous CompactSpace.uniformContinuous_of_continuousₓ'. -/
/-- Heine-Cantor: a continuous function on a compact uniform space is uniformly
continuous. -/
theorem CompactSpace.uniformContinuous_of_continuous [CompactSpace α] {f : α → β}
(h : Continuous f) : UniformContinuous f :=
have : Tendsto (Prod.map f f) (𝓝ˢ (diagonal α)) (𝓝ˢ (diagonal β)) :=
(h.Prod_map h).tendsto_nhdsSet mapsTo_prod_map_diagonal
(this.mono_left nhdsSet_diagonal_eq_uniformity.ge).mono_right nhdsSet_diagonal_le_uniformity
#align compact_space.uniform_continuous_of_continuous CompactSpace.uniformContinuous_of_continuous
/- warning: is_compact.uniform_continuous_on_of_continuous -> IsCompact.uniformContinuousOn_of_continuous is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : UniformSpace.{u1} α] [_inst_2 : UniformSpace.{u2} β] {s : Set.{u1} α} {f : α -> β}, (IsCompact.{u1} α (UniformSpace.toTopologicalSpace.{u1} α _inst_1) s) -> (ContinuousOn.{u1, u2} α β (UniformSpace.toTopologicalSpace.{u1} α _inst_1) (UniformSpace.toTopologicalSpace.{u2} β _inst_2) f s) -> (UniformContinuousOn.{u1, u2} α β _inst_1 _inst_2 f s)
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} [_inst_1 : UniformSpace.{u2} α] [_inst_2 : UniformSpace.{u1} β] {s : Set.{u2} α} {f : α -> β}, (IsCompact.{u2} α (UniformSpace.toTopologicalSpace.{u2} α _inst_1) s) -> (ContinuousOn.{u2, u1} α β (UniformSpace.toTopologicalSpace.{u2} α _inst_1) (UniformSpace.toTopologicalSpace.{u1} β _inst_2) f s) -> (UniformContinuousOn.{u2, u1} α β _inst_1 _inst_2 f s)
Case conversion may be inaccurate. Consider using '#align is_compact.uniform_continuous_on_of_continuous IsCompact.uniformContinuousOn_of_continuousₓ'. -/
/-- Heine-Cantor: a continuous function on a compact set of a uniform space is uniformly
continuous. -/
theorem IsCompact.uniformContinuousOn_of_continuous {s : Set α} {f : α → β} (hs : IsCompact s)
(hf : ContinuousOn f s) : UniformContinuousOn f s :=
by
rw [uniformContinuousOn_iff_restrict]
rw [isCompact_iff_compactSpace] at hs
rw [continuousOn_iff_continuous_restrict] at hf
skip
exact CompactSpace.uniformContinuous_of_continuous hf
#align is_compact.uniform_continuous_on_of_continuous IsCompact.uniformContinuousOn_of_continuous
#print IsCompact.uniformContinuousAt_of_continuousAt /-
/-- If `s` is compact and `f` is continuous at all points of `s`, then `f` is
"uniformly continuous at the set `s`", i.e. `f x` is close to `f y` whenever `x ∈ s` and `y` is
close to `x` (even if `y` is not itself in `s`, so this is a stronger assertion than
`uniform_continuous_on s`). -/
theorem IsCompact.uniformContinuousAt_of_continuousAt {r : Set (β × β)} {s : Set α}
(hs : IsCompact s) (f : α → β) (hf : ∀ a ∈ s, ContinuousAt f a) (hr : r ∈ 𝓤 β) :
{ x : α × α | x.1 ∈ s → (f x.1, f x.2) ∈ r } ∈ 𝓤 α :=
by
obtain ⟨t, ht, htsymm, htr⟩ := comp_symm_mem_uniformity_sets hr
choose U hU T hT hb using fun a ha =>
exists_mem_nhds_ball_subset_of_mem_nhds ((hf a ha).preimage_mem_nhds <| mem_nhds_left _ ht)
obtain ⟨fs, hsU⟩ := hs.elim_nhds_subcover' U hU
apply mem_of_superset ((bInter_finset_mem fs).2 fun a _ => hT a a.2)
rintro ⟨a₁, a₂⟩ h h₁
obtain ⟨a, ha, haU⟩ := Set.mem_unionᵢ₂.1 (hsU h₁)
apply htr
refine' ⟨f a, htsymm.mk_mem_comm.1 (hb _ _ _ haU _), hb _ _ _ haU _⟩
exacts[mem_ball_self _ (hT a a.2), mem_Inter₂.1 h a ha]
#align is_compact.uniform_continuous_at_of_continuous_at IsCompact.uniformContinuousAt_of_continuousAt
-/
/- warning: continuous.uniform_continuous_of_tendsto_cocompact -> Continuous.uniformContinuous_of_tendsto_cocompact is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} [_inst_1 : UniformSpace.{u1} α] [_inst_2 : UniformSpace.{u2} β] {f : α -> β} {x : β}, (Continuous.{u1, u2} α β (UniformSpace.toTopologicalSpace.{u1} α _inst_1) (UniformSpace.toTopologicalSpace.{u2} β _inst_2) f) -> (Filter.Tendsto.{u1, u2} α β f (Filter.cocompact.{u1} α (UniformSpace.toTopologicalSpace.{u1} α _inst_1)) (nhds.{u2} β (UniformSpace.toTopologicalSpace.{u2} β _inst_2) x)) -> (UniformContinuous.{u1, u2} α β _inst_1 _inst_2 f)
but is expected to have type
forall {α : Type.{u2}} {β : Type.{u1}} [_inst_1 : UniformSpace.{u2} α] [_inst_2 : UniformSpace.{u1} β] {f : α -> β} {x : β}, (Continuous.{u2, u1} α β (UniformSpace.toTopologicalSpace.{u2} α _inst_1) (UniformSpace.toTopologicalSpace.{u1} β _inst_2) f) -> (Filter.Tendsto.{u2, u1} α β f (Filter.cocompact.{u2} α (UniformSpace.toTopologicalSpace.{u2} α _inst_1)) (nhds.{u1} β (UniformSpace.toTopologicalSpace.{u1} β _inst_2) x)) -> (UniformContinuous.{u2, u1} α β _inst_1 _inst_2 f)
Case conversion may be inaccurate. Consider using '#align continuous.uniform_continuous_of_tendsto_cocompact Continuous.uniformContinuous_of_tendsto_cocompactₓ'. -/
theorem Continuous.uniformContinuous_of_tendsto_cocompact {f : α → β} {x : β}
(h_cont : Continuous f) (hx : Tendsto f (cocompact α) (𝓝 x)) : UniformContinuous f :=
uniformContinuous_def.2 fun r hr =>
by
obtain ⟨t, ht, htsymm, htr⟩ := comp_symm_mem_uniformity_sets hr
obtain ⟨s, hs, hst⟩ := mem_cocompact.1 (hx <| mem_nhds_left _ ht)
apply
mem_of_superset
(symmetrize_mem_uniformity <|
(hs.uniform_continuous_at_of_continuous_at f fun _ _ => h_cont.continuous_at) <|
symmetrize_mem_uniformity hr)
rintro ⟨b₁, b₂⟩ h
by_cases h₁ : b₁ ∈ s; · exact (h.1 h₁).1
by_cases h₂ : b₂ ∈ s; · exact (h.2 h₂).2
apply htr
exact ⟨x, htsymm.mk_mem_comm.1 (hst h₁), hst h₂⟩
#align continuous.uniform_continuous_of_tendsto_cocompact Continuous.uniformContinuous_of_tendsto_cocompact
#print HasCompactMulSupport.is_one_at_infty /-
/-- If `f` has compact multiplicative support, then `f` tends to 1 at infinity. -/
@[to_additive "If `f` has compact support, then `f` tends to zero at infinity."]
theorem HasCompactMulSupport.is_one_at_infty {f : α → γ} [TopologicalSpace γ] [One γ]
(h : HasCompactMulSupport f) : Tendsto f (cocompact α) (𝓝 1) :=
by
-- porting note: move to src/topology/support.lean once the port is over
intro N hN
rw [mem_map, mem_cocompact']
refine' ⟨mulTSupport f, h.is_compact, _⟩
rw [compl_subset_comm]
intro v hv
rw [mem_preimage, image_eq_one_of_nmem_mulTSupport hv]
exact mem_of_mem_nhds hN
#align has_compact_mul_support.is_one_at_infty HasCompactMulSupport.is_one_at_infty
#align has_compact_support.is_zero_at_infty HasCompactSupport.is_zero_at_infty
-/
#print HasCompactMulSupport.uniformContinuous_of_continuous /-
@[to_additive]
theorem HasCompactMulSupport.uniformContinuous_of_continuous {f : α → β} [One β]
(h1 : HasCompactMulSupport f) (h2 : Continuous f) : UniformContinuous f :=
h2.uniformContinuous_of_tendsto_cocompact h1.is_one_at_infty
#align has_compact_mul_support.uniform_continuous_of_continuous HasCompactMulSupport.uniformContinuous_of_continuous
#align has_compact_support.uniform_continuous_of_continuous HasCompactSupport.uniformContinuous_of_continuous
-/
/- warning: continuous_on.tendsto_uniformly -> ContinuousOn.tendstoUniformly is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} [_inst_1 : UniformSpace.{u1} α] [_inst_2 : UniformSpace.{u2} β] [_inst_3 : LocallyCompactSpace.{u1} α (UniformSpace.toTopologicalSpace.{u1} α _inst_1)] [_inst_4 : CompactSpace.{u2} β (UniformSpace.toTopologicalSpace.{u2} β _inst_2)] [_inst_5 : UniformSpace.{u3} γ] {f : α -> β -> γ} {x : α} {U : Set.{u1} α}, (Membership.Mem.{u1, u1} (Set.{u1} α) (Filter.{u1} α) (Filter.hasMem.{u1} α) U (nhds.{u1} α (UniformSpace.toTopologicalSpace.{u1} α _inst_1) x)) -> (ContinuousOn.{max u1 u2, u3} (Prod.{u1, u2} α β) γ (Prod.topologicalSpace.{u1, u2} α β (UniformSpace.toTopologicalSpace.{u1} α _inst_1) (UniformSpace.toTopologicalSpace.{u2} β _inst_2)) (UniformSpace.toTopologicalSpace.{u3} γ _inst_5) (Function.HasUncurry.uncurry.{max u1 u2 u3, max u1 u2, u3} (α -> β -> γ) (Prod.{u1, u2} α β) γ (Function.hasUncurryInduction.{u1, max u2 u3, u2, u3} α (β -> γ) β γ (Function.hasUncurryBase.{u2, u3} β γ)) f) (Set.prod.{u1, u2} α β U (Set.univ.{u2} β))) -> (TendstoUniformly.{u2, u3, u1} β γ α _inst_5 f (f x) (nhds.{u1} α (UniformSpace.toTopologicalSpace.{u1} α _inst_1) x))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} [_inst_1 : UniformSpace.{u3} α] [_inst_2 : UniformSpace.{u2} β] [_inst_3 : LocallyCompactSpace.{u3} α (UniformSpace.toTopologicalSpace.{u3} α _inst_1)] [_inst_4 : CompactSpace.{u2} β (UniformSpace.toTopologicalSpace.{u2} β _inst_2)] [_inst_5 : UniformSpace.{u1} γ] {f : α -> β -> γ} {x : α} {U : Set.{u3} α}, (Membership.mem.{u3, u3} (Set.{u3} α) (Filter.{u3} α) (instMembershipSetFilter.{u3} α) U (nhds.{u3} α (UniformSpace.toTopologicalSpace.{u3} α _inst_1) x)) -> (ContinuousOn.{max u3 u2, u1} (Prod.{u3, u2} α β) γ (instTopologicalSpaceProd.{u3, u2} α β (UniformSpace.toTopologicalSpace.{u3} α _inst_1) (UniformSpace.toTopologicalSpace.{u2} β _inst_2)) (UniformSpace.toTopologicalSpace.{u1} γ _inst_5) (Function.HasUncurry.uncurry.{max (max u3 u2) u1, max u3 u2, u1} (α -> β -> γ) (Prod.{u3, u2} α β) γ (Function.hasUncurryInduction.{u3, max u2 u1, u2, u1} α (β -> γ) β γ (Function.hasUncurryBase.{u2, u1} β γ)) f) (Set.prod.{u3, u2} α β U (Set.univ.{u2} β))) -> (TendstoUniformly.{u2, u1, u3} β γ α _inst_5 f (f x) (nhds.{u3} α (UniformSpace.toTopologicalSpace.{u3} α _inst_1) x))
Case conversion may be inaccurate. Consider using '#align continuous_on.tendsto_uniformly ContinuousOn.tendstoUniformlyₓ'. -/
/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/
/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/
/-- A family of functions `α → β → γ` tends uniformly to its value at `x` if `α` is locally compact,
`β` is compact and `f` is continuous on `U × (univ : set β)` for some neighborhood `U` of `x`. -/
theorem ContinuousOn.tendstoUniformly [LocallyCompactSpace α] [CompactSpace β] [UniformSpace γ]
{f : α → β → γ} {x : α} {U : Set α} (hxU : U ∈ 𝓝 x) (h : ContinuousOn (↿f) (U ×ˢ univ)) :
TendstoUniformly f (f x) (𝓝 x) :=
by
rcases LocallyCompactSpace.local_compact_nhds _ _ hxU with ⟨K, hxK, hKU, hK⟩
have : UniformContinuousOn (↿f) (K ×ˢ univ) :=
IsCompact.uniformContinuousOn_of_continuous (hK.prod isCompact_univ)
(h.mono <| prod_mono hKU subset.rfl)
exact this.tendsto_uniformly hxK
#align continuous_on.tendsto_uniformly ContinuousOn.tendstoUniformly
/- warning: continuous.tendsto_uniformly -> Continuous.tendstoUniformly is a dubious translation:
lean 3 declaration is
forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} [_inst_1 : UniformSpace.{u1} α] [_inst_2 : UniformSpace.{u2} β] [_inst_3 : LocallyCompactSpace.{u1} α (UniformSpace.toTopologicalSpace.{u1} α _inst_1)] [_inst_4 : CompactSpace.{u2} β (UniformSpace.toTopologicalSpace.{u2} β _inst_2)] [_inst_5 : UniformSpace.{u3} γ] (f : α -> β -> γ), (Continuous.{max u1 u2, u3} (Prod.{u1, u2} α β) γ (Prod.topologicalSpace.{u1, u2} α β (UniformSpace.toTopologicalSpace.{u1} α _inst_1) (UniformSpace.toTopologicalSpace.{u2} β _inst_2)) (UniformSpace.toTopologicalSpace.{u3} γ _inst_5) (Function.HasUncurry.uncurry.{max u1 u2 u3, max u1 u2, u3} (α -> β -> γ) (Prod.{u1, u2} α β) γ (Function.hasUncurryInduction.{u1, max u2 u3, u2, u3} α (β -> γ) β γ (Function.hasUncurryBase.{u2, u3} β γ)) f)) -> (forall (x : α), TendstoUniformly.{u2, u3, u1} β γ α _inst_5 f (f x) (nhds.{u1} α (UniformSpace.toTopologicalSpace.{u1} α _inst_1) x))
but is expected to have type
forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} [_inst_1 : UniformSpace.{u3} α] [_inst_2 : UniformSpace.{u2} β] [_inst_3 : LocallyCompactSpace.{u3} α (UniformSpace.toTopologicalSpace.{u3} α _inst_1)] [_inst_4 : CompactSpace.{u2} β (UniformSpace.toTopologicalSpace.{u2} β _inst_2)] [_inst_5 : UniformSpace.{u1} γ] (f : α -> β -> γ), (Continuous.{max u3 u2, u1} (Prod.{u3, u2} α β) γ (instTopologicalSpaceProd.{u3, u2} α β (UniformSpace.toTopologicalSpace.{u3} α _inst_1) (UniformSpace.toTopologicalSpace.{u2} β _inst_2)) (UniformSpace.toTopologicalSpace.{u1} γ _inst_5) (Function.HasUncurry.uncurry.{max (max u3 u2) u1, max u3 u2, u1} (α -> β -> γ) (Prod.{u3, u2} α β) γ (Function.hasUncurryInduction.{u3, max u2 u1, u2, u1} α (β -> γ) β γ (Function.hasUncurryBase.{u2, u1} β γ)) f)) -> (forall (x : α), TendstoUniformly.{u2, u1, u3} β γ α _inst_5 f (f x) (nhds.{u3} α (UniformSpace.toTopologicalSpace.{u3} α _inst_1) x))
Case conversion may be inaccurate. Consider using '#align continuous.tendsto_uniformly Continuous.tendstoUniformlyₓ'. -/
/-- A continuous family of functions `α → β → γ` tends uniformly to its value at `x` if `α` is
locally compact and `β` is compact. -/
theorem Continuous.tendstoUniformly [LocallyCompactSpace α] [CompactSpace β] [UniformSpace γ]
(f : α → β → γ) (h : Continuous ↿f) (x : α) : TendstoUniformly f (f x) (𝓝 x) :=
h.ContinuousOn.TendstoUniformly univ_mem
#align continuous.tendsto_uniformly Continuous.tendstoUniformly
section UniformConvergence
#print CompactSpace.uniformEquicontinuous_of_equicontinuous /-
/-- An equicontinuous family of functions defined on a compact uniform space is automatically
uniformly equicontinuous. -/
theorem CompactSpace.uniformEquicontinuous_of_equicontinuous {ι : Type _} {F : ι → β → α}
[CompactSpace β] (h : Equicontinuous F) : UniformEquicontinuous F :=
by
rw [equicontinuous_iff_continuous] at h
rw [uniformEquicontinuous_iff_uniformContinuous]
exact CompactSpace.uniformContinuous_of_continuous h
#align compact_space.uniform_equicontinuous_of_equicontinuous CompactSpace.uniformEquicontinuous_of_equicontinuous
-/
end UniformConvergence
|
You are always encouraged to call our Office if you have questions. We can be reached 24 hours a day. When you call our Office after hours the voicemail message will indicate the emergency after hours number to call 802-999-7318.
There are many ways to think smart and prevent claims. However if a claim occurs it is our Agency’s goal for you to experience fast, fair claims service from the companies we represent. Please contact our Office if you need our assistance during your claims process.
If you have an incident and are unsure about coverage, please call our Office to speak with your agent and they will assist you.
Some of our companies are Direct Reporting Companies which means they require you the policy holder to contact them directly to report a claim. All have a toll free phone number, you can now also submit claims through some company websites. We also have some companies that are Agent Reporting Companies and those companies require that you call our Office providing us with the detail we submit the claim to the company for you. Please refer to our Report Claim button to the right to find your company and see what their process is. |
theorem ex {c d : Char} : c = d → c.val = d.val
| rfl => rfl
|
#include <gsl/gsl_sf_erf.h>
#include <gsl/gsl_vector.h>
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
//#include <gsl/gsl_ran_gaussian.h>
int main (int argc, char *argv[]){
double a = gsl_sf_erf(1);
printf("The random number we get is %f.", a);
exit(0);
} |
% std_editset() - modify a STUDY set structure.
%
% Usage:
% >> [STUDY, ALLEEG] = std_editset(STUDY, ALLEEG, key1, val1, ...);
% Inputs:
% STUDY - EEGLAB STUDY set
% ALLEEG - vector of the EEG datasets included in the STUDY structure
%
% Optional inputs:
% 'commands' - {cell_array} change STUDY (see command description and
% example below.
% 'name' - [string] specify a (mnemonic) name for the STUDY structure.
% {default: ''}
% 'task' - [string] attach a description of the experimental task(s)
% performed by the STUDY subjects {default: ''}.
% 'filename' - [string] filename for the STUDY set.
% 'filepath' - [string] file path (directory/folder) in which the STUDY file
% will be saved.
% 'addchannellabels' - ['on'|'off'] add channel labels ('1', '2', '3', ...)
% to all datasets of a STUDY to ensure that all STUDY functions
% will work {default: 'off'}
% 'notes' - [string] notes about the experiment, the datasets, the STUDY,
% or anything else to store with the STUDY itself {default: ''}.
% 'updatedat' - ['on'|'off'] update 'subject' 'session' 'condition' and/or
% 'group' fields of STUDY dataset(s).
% 'savedat' - ['on'|'off'] re-save datasets
% 'inbrain' - ['on'|'off'] select components for clustering from all STUDY
% datasets with equivalent dipoles located inside the brain volume.
% Dipoles are selected based on their residual variance and their
% location {default: 'off'}
%
% Each of the 'commands' (above) is a cell array composed of any of the following:
% 'index' - [integer] modify dataset index.
% 'remove' - [integer] remove dataset index.
% 'subject' - [string] subject code.
% 'condition' - [string] dataset condition.
% 'session ' - [integer] dataset session number.
% 'group' - [string] dataset group.
% 'load' - [filename] load dataset from specified filename
% 'dipselect' - [float<1] select components for clustering from all STUDY
% datasets with dipole model residual var. below this value.
% 'inbrain' - ['on'|'off'] same as above. This option may also be
% placed in the command list (preceeding the 'dipselect'
% option).
%
% Outputs:
% STUDY - a new STUDY set containing some or all of the datasets in ALLEEG,
% plus additional information from the optional inputs above.
% ALLEEG - a vector of EEG datasets included in the STUDY structure
%
% See also: pop_createstudy(), std_loadalleeg(), pop_clust(), pop_preclust(),
% eeg_preclust(), eeg_createdata()
%
% Authors: Arnaud Delorme, Hilit Serby, SCCN/INC/UCSD, October , 2004-
% Copyright (C) Arnaud Delorme & Scott Makeig, SCCN/INC/UCSD, October 11, 2004, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [STUDY, ALLEEG] = std_editset(STUDY, ALLEEG, varargin)
if (nargin < 3)
help std_editset;
return;
end;
% decode input parameters
% -----------------------
g = finputcheck(varargin, { 'updatedat' 'string' { 'on' 'off' } 'off';
'name' 'string' { } '';
'task' 'string' { } '';
'notes' 'string' { } '';
'filename' 'string' { } '';
'filepath' 'string' { } '';
'resave' 'string' { 'on' 'off' 'info' } 'off';
'savedat' 'string' { 'on' 'off' } 'off';
'addchannellabels' 'string' { 'on' 'off' } 'off';
'rmclust' 'string' { 'on' 'off' } 'on';
'inbrain' 'string' { 'on' 'off' } 'off';
'commands' 'cell' {} {} }, 'std_editset');
if isstr(g), error(g); end;
if ~isempty(g.name), STUDY.name = g.name; end
if ~isempty(g.task), STUDY.task = g.task; end
if ~isempty(g.notes), STUDY.notes = g.notes; end
% make one cell array with commands
% ---------------------------------
allcoms = {};
if ~isempty(g.commands)
if iscell(g.commands{1})
for k = 1:length(g.commands)
% put index field first
indindex = strmatch('index', lower(g.commands{k}(1:2:end)));
if ~isempty(indindex)
tmpcom = { 'index' g.commands{k}{2*(indindex-1)+1+1} g.commands{k}{:} };
else tmpcom = g.commands{k};
end;
allcoms = { allcoms{:} tmpcom{:} };
end;
else
allcoms = g.commands;
end;
end;
g.commands = allcoms;
% add 'dipselect' command if 'inbrain' option is selected
% ---------------------------------
dipselectExists = false;
for k = 1:2:length(g.commands)
if strcmp(g.commands{k},'dipselect')
dipselectExists = true;
end;
end;
if strcmp(g.inbrain,'on') && ~dipselectExists
g.commands{length(g.commands)+1} = 'dipselect';
g.commands{length(g.commands)+1} = 0.15;
end;
% copy values
% -----------
if ~isfield(STUDY, 'datasetinfo')
for realindex = 1:length(ALLEEG)
if ~isempty(ALLEEG(realindex).data)
[tmppath tmpfile tmpext] = fileparts( fullfile(ALLEEG(realindex).filepath, ALLEEG(realindex).filename) );
STUDY.datasetinfo(realindex).filepath = tmppath;
STUDY.datasetinfo(realindex).filename = [ tmpfile tmpext ];
STUDY.datasetinfo(realindex).subject = ALLEEG(realindex).subject;
STUDY.datasetinfo(realindex).session = ALLEEG(realindex).session;
STUDY.datasetinfo(realindex).condition = ALLEEG(realindex).condition;
STUDY.datasetinfo(realindex).group = ALLEEG(realindex).group;
end;
end;
end;
% execute commands
% ----------------
currentind = 1;
rmlist = [];
for k = 1:2:length(g.commands)
switch g.commands{k}
case 'index'
currentind = g.commands{k+1};
case 'subject'
STUDY.datasetinfo(currentind).subject = g.commands{k+1};
case 'comps'
STUDY.datasetinfo(currentind).comps = g.commands{k+1};
case 'condition'
STUDY.datasetinfo(currentind).condition = g.commands{k+1};
case 'group'
STUDY.datasetinfo(currentind).group = g.commands{k+1};
case 'session'
STUDY.datasetinfo(currentind).session = g.commands{k+1};
case 'session'
STUDY.datasetinfo(currentind).session = g.commands{k+1};
case 'remove'
ALLEEG(end+2) = ALLEEG(end);
ALLEEG(g.commands{k+1}) = ALLEEG(end-1); % empty dataset
ALLEEG(end-1:end) = [];
STUDY.datasetinfo(end+2) = STUDY.datasetinfo(end);
STUDY.datasetinfo(g.commands{k+1}) = STUDY.datasetinfo(end-1);
STUDY.datasetinfo(end-1:end) = [];
if isfield(STUDY.datasetinfo, 'index')
STUDY.datasetinfo = rmfield(STUDY.datasetinfo, 'index');
end;
STUDY.datasetinfo(1).index = [];
STUDY.changrp = [];
case 'return', return;
case 'inbrain'
g.inbrain = g.commands{k+1};
case 'dipselect'
STUDY = std_checkset(STUDY, ALLEEG);
rv = g.commands{k+1};
clusters = std_findsameica(ALLEEG);
for cc = 1:length(clusters)
idat = 0;
for tmpi = 1:length(clusters{cc})
if isfield(ALLEEG(clusters{cc}(tmpi)).dipfit, 'model')
idat = clusters{cc}(tmpi);
end;
end;
indleft = [];
if rv ~= 1
if idat ~= 0
if strcmp(g.inbrain,'on')
fprintf('Selecting dipoles with less than %%%2.1f residual variance and removing dipoles outside brain volume in dataset ''%s''\n', ...
100*rv, ALLEEG(idat).setname);
indleft = eeg_dipselect(ALLEEG(idat), rv*100,'inbrain');
else
fprintf('Selecting dipoles with less than %%%2.1f residual variance in dataset ''%s''\n', ...
100*rv, ALLEEG(idat).setname);
indleft = eeg_dipselect(ALLEEG(idat), rv*100,'rv');
end;
else
fprintf('No dipole information found in ''%s'' dataset, using all components\n', ALLEEG.setname)
end
end;
for tmpi = 1:length(clusters{cc})
STUDY.datasetinfo(clusters{cc}(tmpi)).comps = indleft;
end;
end;
STUDY.cluster = [];
STUDY = std_checkset(STUDY, ALLEEG); % recreate parent dataset
case 'load'
TMPEEG = std_loadalleeg( { g.commands{k+1} } );
ALLEEG = eeg_store(ALLEEG, eeg_checkset(TMPEEG), currentind);
ALLEEG(currentind).saved = 'yes';
% update datasetinfo structure
% ----------------------------
[tmppath tmpfile tmpext] = fileparts( fullfile(ALLEEG(currentind).filepath, ...
ALLEEG(currentind).filename) );
STUDY.datasetinfo(currentind).filepath = tmppath;
STUDY.datasetinfo(currentind).filename = [ tmpfile tmpext ];
STUDY.datasetinfo(currentind).subject = ALLEEG(currentind).subject;
STUDY.datasetinfo(currentind).session = ALLEEG(currentind).session;
STUDY.datasetinfo(currentind).condition = ALLEEG(currentind).condition;
STUDY.datasetinfo(currentind).group = ALLEEG(currentind).group;
STUDY.datasetinfo(currentind).index = currentind;
otherwise, error(sprintf('Unknown command %s', g.commands{k}));
end
end
% add channel labels automatically
% -------------------------------
if strcmpi(g.addchannellabels, 'on')
disp('Generating channel labels for all datasets...');
for currentind = 1:length(ALLEEG)
for ind = 1:ALLEEG(currentind).nbchan
ALLEEG(currentind).chanlocs(ind).labels = int2str(ind);
end;
end;
ALLEEG(currentind).saved = 'no';
g.savedat = 'on';
end;
% update ALLEEG structure?
% ------------------------
if strcmpi(g.updatedat, 'on')
for currentind = 1:length(ALLEEG)
if ~strcmpi(ALLEEG(currentind).subject, STUDY.datasetinfo(currentind).subject)
ALLEEG(currentind).subject = STUDY.datasetinfo(currentind).subject;
ALLEEG(currentind).saved = 'no';
end;
if ~strcmpi(ALLEEG(currentind).condition, STUDY.datasetinfo(currentind).condition)
ALLEEG(currentind).condition = STUDY.datasetinfo(currentind).condition;
ALLEEG(currentind).saved = 'no';
end;
if ~isequal(ALLEEG(currentind).session, STUDY.datasetinfo(currentind).session)
ALLEEG(currentind).session = STUDY.datasetinfo(currentind).session;
ALLEEG(currentind).saved = 'no';
end;
if ~strcmpi(char(ALLEEG(currentind).group), char(STUDY.datasetinfo(currentind).group))
ALLEEG(currentind).group = STUDY.datasetinfo(currentind).group;
ALLEEG(currentind).saved = 'no';
end;
end;
end;
% remove empty datasets (cannot be done above because some empty datasets
% might not have been removed)
% ---------------------
[ ALLEEG STUDY.datasetinfo ] = removeempty(ALLEEG, STUDY.datasetinfo);
% save datasets if necessary
% --------------------------
if strcmpi(g.savedat, 'on')
for index = 1:length(ALLEEG)
if isempty(ALLEEG(index).filename)
fprintf('Cannot resave ALLEEG(%d) because the dataset has no filename\n', index);
else
TMP = pop_saveset(ALLEEG(index), 'savemode', 'resave');
ALLEEG = eeg_store(ALLEEG, TMP, index);
ALLEEG(index).saved = 'yes';
end;
end;
end;
% remove cluster information if necessary
% ---------------------------------------
if strcmpi(g.rmclust, 'on')
STUDY.cluster = [];
end;
% save study if necessary
% -----------------------
STUDY.changrp = [];
[STUDY ALLEEG] = std_checkset(STUDY, ALLEEG);
if ~isempty(g.filename),
[STUDY.filepath STUDY.filename ext] = fileparts(fullfile( g.filepath, g.filename ));
STUDY.filename = [ STUDY.filename ext ];
g.resave = 'on';
end
if strcmpi(g.resave, 'on')
STUDY = pop_savestudy(STUDY, ALLEEG, 'savemode', 'resave');
end;
% ---------------------
% remove empty elements
% ---------------------
function [ALLEEG, datasetinfo] = removeempty(ALLEEG, datasetinfo);
rmindex = [];
for index = 1:length(datasetinfo)
if isempty(datasetinfo(index).subject) & isempty(ALLEEG(index).nbchan)
rmindex = [ rmindex index ];
end;
end;
datasetinfo(rmindex) = [];
ALLEEG(rmindex) = [];
for index = 1:length(datasetinfo)
datasetinfo(index).index = index;
end;
% remove empty ALLEEG structures
% ------------------------------
while length(ALLEEG) > length(datasetinfo)
ALLEEG(end) = [];
end;
|
lemma tendsto_prod [tendsto_intros]: fixes f :: "'a \<Rightarrow> 'b \<Rightarrow> 'c::{real_normed_algebra,comm_ring_1}" shows "(\<And>i. i \<in> S \<Longrightarrow> (f i \<longlongrightarrow> L i) F) \<Longrightarrow> ((\<lambda>x. \<Prod>i\<in>S. f i x) \<longlongrightarrow> (\<Prod>i\<in>S. L i)) F" |
//==============================================================================
// Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 & onward LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_DISPATCH_DETAILS_IGNORE_UNUSED_HPP_INCLUDED
#define BOOST_DISPATCH_DETAILS_IGNORE_UNUSED_HPP_INCLUDED
#include <boost/dispatch/attributes.hpp>
/*!
* \file
* \brief Defined and implements the \ref boost::dispatch::ignore_unused utility function
*/
namespace boost { namespace dispatch
{
//============================================================================
/*!
* \ingroup sdk
* In some SFINAE-based code, some functions parameters may be declared
* but not used in a given implementation. Calling this function on such
* parameters prevent compilers to generate spurious warnings.
*
* \par Example Usage:
*
* \include ignore_unused.cpp
*/
//============================================================================
template<class T>
BOOST_DISPATCH_FORCE_INLINE void ignore_unused( T const& ) {}
} }
#endif
|
/**
*
* @file testing_zgetmi.c
*
* PLASMA testings module
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* This program tests the implementation of the inplace format
* conversion based on the GKK algorithm by Gustavson, Karlsson,
* Kagstrom.
*
* @version 2.6.0
* @author Mathieu Faverge
* @date 2010-11-15
*
* @precisions normal z -> c d s
*
* Purpose :
* Test the in place matrix transposition with the 6 different
* formats of input.
**/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <lapacke.h>
#include <plasma.h>
#include "testing_zmain.h"
static int check_solution(int m, int n, int mb, int nb,
PLASMA_Complex64_t *A, PLASMA_Complex64_t *B,
int (*mapA)(int, int, int, int, int, int)) {
int i, j;
for( j=0; j<n; j++) {
for (i=0; i<m; i++) {
if (A[ mapA(m, n, mb, nb, i, j) ] != B[ mapA(n, m, mb, nb, j, i) ] ) {
return -1;
}
}
}
return 0;
}
int testing_zgetmi(int argc, char **argv){
PLASMA_Complex64_t *A, *B;
int m, n, mb, nb;
int i, ret, size;
/* Check for number of arguments*/
if (argc != 4){
USAGE("GETMI", "M N MB NB ntdbypb with \n",
" - M : the number of rows of the matrix \n"
" - N : the number of columns of the matrix \n"
" - MB : the number of rows of each block \n"
" - NB : the number of columns of each block \n");
return -1;
}
m = atoi(argv[0]);
n = atoi(argv[1]);
mb = atoi(argv[2]);
nb = atoi(argv[3]);
size = m*n*sizeof(PLASMA_Complex64_t);
A = (PLASMA_Complex64_t *)malloc(size);
B = (PLASMA_Complex64_t *)malloc(size);
LAPACKE_zlarnv_work(1, ISEED, m*n, A);
for(i=0; i<6; i++) {
memcpy(B, A, size);
printf(" - TESTING ZGETMI (%4s) ...", formatstr[i]);
ret = PLASMA_zgetmi( m, n, A, format[i], mb, nb );
if (ret != PLASMA_SUCCESS) {
printf("Failed\n");
continue;
}
if ( check_solution(m, n, mb, nb, B, A,
(int (*)(int, int, int, int, int, int))formatmap[i]) == 0 )
printf("............ PASSED !\n");
else
printf("... FAILED !\n");
}
free( A ); free( B );
return 0;
}
|
> data <- read.csv("input_1.csv", header = TRUE)
> table(data$landmark)
N Y
14076 1009
> prop.table(table(data$landmark))
N Y
0.93311236 0.06688764
> library(sampling)
> n <- round(9/10*nrow(data)/3)
> train <- strata(data, stratanames = ("landmark"),
+ size = c(14076*9/10, 1009*9/10),, method="srswor")
> traindata <- data[train$ID_unit,]
> testdata <- data[-train$ID_unit,]
> table(traindata$landmark)
N Y
12668 908
> prop.table(table(traindata$landmark))
N Y
0.93311727 0.06688273
> #train <- sample(nrow(data), 9/10*15085)
> #traindata <- data[train,]
> #testdata <- data[-train,]
> library(DMwR)
> smotedata <- SMOTE(landmark ~ ., traindata, perc.over = 150,perc.under = 195)
> table(smotedata$landmark)
N Y
1770 1816
> prop.table(table(smotedata$landmark))
N Y
0.4935862 0.5064138
> library(randomForest)
> set.seed(100)
> rf_ntree <- randomForest(landmark~., data = smotedata, ntree = 600, importance = TRUE)
> pred <- predict(object = rf_ntree,newdata = testdata)
> roc.curve(testdata$landmark, pred)
Area under the curve (AUC): 0.814
> table(testdata$landmark,pred)
pred
N Y
N 1135 273
Y 18 83
> importance(rf_ntree,type = 1, scale = TRUE)
MeanDecreaseAccuracy
lon 35.10535
lat 52.59334
feature.level 98.61635
highest.road.level 20.19906
road.density 37.83646
GDP.level 25.74159
same.features.in.500.buffer 39.83412
different.features.in.500.buffer 43.51922
traffic.stations.nearby.in.Baidu.Map 39.44221
crowd.density 38.65292
Bing.search.results 52.74905
Weibo.search.results 65.89811
Baidu.Map.poi 12.66796
building 30.59576
category_2 41.32356
category_1 21.23061
> importance(rf_ntree,type = 2, scale = TRUE)
MeanDecreaseGini
lon 82.81873
lat 129.49799
feature.level 395.20606
highest.road.level 38.64444
road.density 90.92090
GDP.level 36.87733
same.features.in.500.buffer 82.17458
different.features.in.500.buffer 90.66348
traffic.stations.nearby.in.Baidu.Map 81.52226
crowd.density 99.47272
Bing.search.results 184.04190
Weibo.search.results 205.79951
Baidu.Map.poi 14.14856
building 84.80672
category_2 141.21173
category_1 34.13857
> varImpPlot(rf_ntree)
> write.csv(traindata,"traindata.csv")
> write.csv(testdata,"testdata.csv")
> pred <- predict(object = rf_ntree,newdata = testdata)
> roc.curve(testdata$landmark, pred)
Area under the curve (AUC): 0.814
> table(testdata$landmark,pred)
pred
N Y
N 1134 274
Y 18 83
> |
{-# OPTIONS --without-K --rewriting #-}
open import HoTT
open import cw.CW
open import homotopy.DisjointlyPointedSet
open import groups.Int
open import cohomology.Theory
open import cohomology.ChainComplex
module cw.cohomology.ReconstructedCochainsIsoCellularCochains {i : ULevel}
(OT : OrdinaryTheory i) where
open OrdinaryTheory OT
open import cw.cohomology.WedgeOfCells OT
open import cw.cohomology.cellular.ChainComplex as CCC
open import cw.cohomology.reconstructed.cochain.Complex OT as RCC
open import cw.cohomology.reconstructed.TipAndAugment OT
private
rcc-iso-ccc-nth : ∀ {n} (⊙skel : ⊙Skeleton n) {m} (m≤n : m ≤ n)
→ ⊙has-cells-with-choice 0 ⊙skel i
→ AbGroup.grp (RCC.cochain-template ⊙skel (inl m≤n))
≃ᴳ hom-group (AbGroup.grp (CCC.chain-template (⊙Skeleton.skel ⊙skel) (inl m≤n))) (C2-abgroup 0)
rcc-iso-ccc-nth ⊙skel {m = O} (inl idp) ac
= FreeAbGroup-extend-iso (C2-abgroup 0)
∘eᴳ C2×CX₀-diag-β ⊙skel ac
rcc-iso-ccc-nth ⊙skel {m = S m} (inl idp) ac
= FreeAbGroup-extend-iso (C2-abgroup 0)
∘eᴳ CXₙ/Xₙ₋₁-diag-β ⊙skel ac
rcc-iso-ccc-nth ⊙skel {m = O} (inr ltS) ac =
rcc-iso-ccc-nth (⊙cw-init ⊙skel) (inl idp) (⊙init-has-cells-with-choice ⊙skel ac)
rcc-iso-ccc-nth ⊙skel {m = S m} (inr ltS) ac =
rcc-iso-ccc-nth (⊙cw-init ⊙skel) (inl idp) (⊙init-has-cells-with-choice ⊙skel ac)
rcc-iso-ccc-nth ⊙skel {m = O} (inr (ltSR lt)) ac =
rcc-iso-ccc-nth (⊙cw-init ⊙skel) (inr lt) (⊙init-has-cells-with-choice ⊙skel ac)
rcc-iso-ccc-nth ⊙skel {m = S m} (inr (ltSR lt)) ac =
rcc-iso-ccc-nth (⊙cw-init ⊙skel) (inr lt) (⊙init-has-cells-with-choice ⊙skel ac)
rcc-iso-ccc-above : ∀ {n} (⊙skel : ⊙Skeleton n) {m} (m≰n : ¬ (m ≤ n))
→ AbGroup.grp (RCC.cochain-template ⊙skel (inr m≰n))
≃ᴳ hom-group (AbGroup.grp (CCC.chain-template (⊙Skeleton.skel ⊙skel) (inr m≰n))) (C2-abgroup 0)
rcc-iso-ccc-above ⊙skel _
= pre∘ᴳ-iso (C2-abgroup 0) lower-iso
∘eᴳ trivial-iso-Unit (hom₁-Unit-is-trivial (C2-abgroup 0)) ⁻¹ᴳ
∘eᴳ lower-iso
rcc-iso-ccc-template : ∀ {n} (⊙skel : ⊙Skeleton n) {m : ℕ} (m≤n? : Dec (m ≤ n))
→ ⊙has-cells-with-choice 0 ⊙skel i
→ AbGroup.grp (RCC.cochain-template ⊙skel m≤n?)
≃ᴳ hom-group (AbGroup.grp (CCC.chain-template (⊙Skeleton.skel ⊙skel) m≤n?)) (C2-abgroup 0)
rcc-iso-ccc-template ⊙skel {m} (inl m≤n) ac = rcc-iso-ccc-nth ⊙skel m≤n ac
rcc-iso-ccc-template ⊙skel {m} (inr m≰n) _ = rcc-iso-ccc-above ⊙skel m≰n
rcc-iso-ccc : ∀ {n} (⊙skel : ⊙Skeleton n) (m : ℕ)
→ ⊙has-cells-with-choice 0 ⊙skel i
→ AbGroup.grp (RCC.cochain-template ⊙skel (≤-dec m n))
≃ᴳ hom-group (AbGroup.grp (CCC.chain-template (⊙Skeleton.skel ⊙skel) (≤-dec m n))) (C2-abgroup 0)
rcc-iso-ccc {n} ⊙skel m = rcc-iso-ccc-template ⊙skel (≤-dec m n)
rhead-iso-chead : C2 0 ≃ᴳ hom-group (Lift-group {j = i} ℤ-group) (C2-abgroup 0)
rhead-iso-chead
= pre∘ᴳ-iso (C2-abgroup 0) (lower-iso {j = i})
∘eᴳ ℤ→ᴳ-iso-idf (C2-abgroup 0) ⁻¹ᴳ
|
function generalscript(path, lambdas, sigmas, tasks)
addpath(path);
kernelFID=fopen('all.kernel');
A=fread(kernelFID, 'float');
K=reshape(A,[sqrt(length(A)),sqrt(length(A))]);
perclassattributes = dlmread('all-perclass.attributes');
S = dlmread('all-perimage.attributes');
load experimentIndices
A=unique(perclassattributes, 'rows');
if length(dir('attrClasses*'))>0
load attrClasses
A=attrClasses;
end
% keyboard
attributesInput=A(trainClassesIndices,:);
attributesOutput=A(testClassesIndices,:);
nAttrs=size(A,2);
% allClass = dlmread('all.classid')+1;
% keyboard
nTrainingClasses=length(trainClassesIndices);
nTrainingInstances=length(trainInstancesIndices);
hist=[];
S=S(trainInstancesIndices,:);
Stest=attributesOutput;
% Stest(Stest==0)=-1;
% for i=1:size(Stest,1)
% Stest(i,:)=Stest(i,:)-mean(Stest(i,:));
% Stest(i,:)=Stest(i,:)/norm(Stest(i,:));
% end
for t=1:length(tasks)
nNewTasks=tasks(t);
disp('Getting labels...');
% Y=zeros(nTrainingInstances,nTrainingClasses+nNewTasks);%-1;%-ones(nTrainingInstances,nTrainingClasses);%/(nTrainingClasses-1);
% for i=1:nTrainingInstances
% Y(i,trainInstancesLabels(i))=1;
% end
disp('Precalculating statistics...');
KTrain=K(trainInstancesIndices, trainInstancesIndices);
KK=KTrain'*KTrain;
% S=[attributesInput; rand(nNewTasks, nAttrs)];
% S=[attributesInput; sign(rand(nNewTasks, nAttrs)-0.5)];
% S(S==0)=-1;
% for i=1:size(S,1)
% S(i,:)=S(i,:)-mean(S(i,:));
% S(i,:)=S(i,:)/norm(S(i,:));
% end
KYS=KTrain*S;
SS=S'*S;
% keyboard
for s=1:length(sigmas)
sigma=sigmas(s);
KYS_invSS=KYS/(SS+sigma*eye(size(S,2)));
disp('Learning...');
% step=10^-8;
% for t=1:500
% % keyboard
% W = W - step * (XX*W*SS -XYS + lambda*W);
% end
for lambdaIndex=1:length(lambdas)
lambda=lambdas(lambdaIndex);
Alpha=(KK+lambda*KTrain)\KYS_invSS;
disp('Predicting...');
KTest=K(testInstancesIndices,trainInstancesIndices);
pred=Stest*Alpha'*KTest';
[scores, classPred]=max(pred',[],2);
disp('Evaluating...');
gt=testInstancesLabels;
r=mean(gt==classPred')
% confusionmat(gt, classPred')
hist=[hist; [lambda, sigma, nNewTasks, r]];
% break;
save('hist4', 'hist');
end
end
end
end
|
section\<open>Temporal Properties\<close>
text\<open>This theory presents some examples of temporal properties over the simple drinks machine.\<close>
theory Drinks_Machine_LTL
imports "Drinks_Machine" "Extended_Finite_State_Machines-devel.EFSM_LTL"
begin
declare One_nat_def [simp del]
lemma P_ltl_step_0:
assumes invalid: "P (None, [], <>)"
assumes select: "l = STR ''select'' \<longrightarrow> P (Some 1, [], <1 $:= Some (hd i), 2 $:= Some (Num 0)>)"
shows "P (ltl_step drinks (Some 0) <> (l, i))"
proof-
have length_i: "\<exists>d. (l, i) = (STR ''select'', [d]) \<Longrightarrow> length i = 1"
by (induct i, auto)
have length_i_2: "\<forall>d. i \<noteq> [d] \<Longrightarrow> length i \<noteq> 1"
by (induct i, auto)
show ?thesis
apply (case_tac "\<exists>d. (l, i) = (STR ''select'', [d])")
apply (simp add: possible_steps_0 length_i select_def apply_updates_def)
using select apply auto[1]
by (simp add: possible_steps_0_invalid length_i_2 invalid)
qed
lemma P_ltl_step_1:
assumes invalid: "P (None, [], r)"
assumes coin: "l = STR ''coin'' \<longrightarrow> P (Some 1, [value_plus (r $ 2) (Some (hd i))], r(2 $:= value_plus (r $ 2) (Some (i ! 0))))"
assumes vend_fail: "value_gt (Some (Num 100)) (r $ 2) = trilean.true \<longrightarrow> P (Some 1, [],r)"
assumes vend: "\<not>? value_gt (Some (Num 100)) (r $ 2) = trilean.true \<longrightarrow> P (Some 2, [r$1], r)"
shows "P (ltl_step drinks (Some 1) r (l, i))"
proof-
have length_i: "\<And>s. \<exists>d. (l, i) = (s, [d]) \<Longrightarrow> length i = 1"
by (induct i, auto)
have length_i_2: "\<forall>d. i \<noteq> [d] \<Longrightarrow> length i \<noteq> 1"
by (induct i, auto)
show ?thesis
apply (case_tac "\<exists>d. (l, i) = (STR ''coin'', [d])")
apply (simp add: possible_steps_1_coin length_i coin_def apply_outputs_def apply_updates_def)
using coin apply auto[1]
apply (case_tac "(l, i) = (STR ''vend'', [])")
apply (case_tac "\<exists>n. r $ 2 = Some (Num n)")
apply clarsimp
subgoal for n
apply (case_tac "n \<ge> 100")
apply (simp add: drinks_vend_sufficient vend_def apply_updates_def apply_outputs_def)
apply (metis finfun_upd_triv possible_steps_2_vend vend vend_ge_100)
apply (simp add: drinks_vend_insufficient vend_fail_def apply_updates_def apply_outputs_def)
apply (metis MaybeBoolInt.simps(1) finfun_upd_triv not_less value_gt_def vend_fail)
done
apply (simp add: drinks_vend_invalid invalid)
by (simp add: drinks_no_possible_steps_1 length_i_2 invalid)
qed
lemma LTL_r2_not_always_gt_100: "not (alw (check_exp (Gt (V (Rg 2)) (L (Num 100))))) (watch drinks i)"
using value_gt_def by auto
lemma drinks_step_2_none: "ltl_step drinks (Some 2) r e = (None, [], r)"
by (simp add: drinks_end ltl_step_none_2)
lemma one_before_two_2:
"alw (\<lambda>x. statename (shd (stl x)) = Some 2 \<longrightarrow> statename (shd x) = Some 1) (make_full_observation drinks (Some 2) r [r $ 1] x2a)"
proof(coinduction)
case alw
then show ?case
apply (simp add: drinks_step_2_none)
by (metis (mono_tags, lifting) alw_mono nxt.simps once_none_nxt_always_none option.distinct(1))
qed
lemma one_before_two_aux:
assumes "\<exists> p r i. j = nxt (make_full_observation drinks (Some 1) r p) i"
shows "alw (\<lambda>x. nxt (state_eq (Some 2)) x \<longrightarrow> state_eq (Some 1) x) j"
using assms apply(coinduct)
apply simp
apply clarify
apply standard
apply simp
apply simp
subgoal for r i
apply (case_tac "shd (stl i)")
apply (simp del: ltl_step.simps)
apply (rule P_ltl_step_1)
apply (rule disjI2)
apply (rule alw_mono[of "nxt (state_eq None)"])
apply (simp add: once_none_nxt_always_none)
apply simp
apply auto[1]
apply auto[1]
apply simp
by (simp add: one_before_two_2)
done
lemma LTL_nxt_2_means_vend:
"alw (nxt (state_eq (Some 2)) impl (state_eq (Some 1))) (watch drinks i)"
proof(coinduction)
case alw
then show ?case
apply (case_tac "shd i")
apply (simp del: ltl_step.simps)
apply (rule P_ltl_step_0)
apply simp
apply (rule disjI2)
apply (rule alw_mono[of "nxt (state_eq None)"])
apply (simp add: once_none_nxt_always_none)
using one_before_two_aux by auto
qed
lemma costsMoney_aux:
assumes "\<exists>p r i. j = (nxt (make_full_observation drinks (Some 1) r p) i)"
shows "alw (\<lambda>xs. nxt (state_eq (Some 2)) xs \<longrightarrow> check_exp (Ge (V (Rg 2)) (L (Num 100))) xs) j"
using assms apply coinduct
apply clarsimp
subgoal for r i
apply (case_tac "shd (stl i)")
apply (simp del: ltl_step.simps)
apply (rule P_ltl_step_1)
apply simp
apply (rule disjI2)
apply (rule alw_mono[of "nxt (state_eq None)"])
apply (simp add: once_none_nxt_always_none)
apply simp
apply auto[1]
apply auto[1]
apply simp
apply standard
apply (rule disjI2)
apply (rule alw_mono[of "nxt (state_eq None)"])
apply (metis (no_types, lifting) drinks_step_2_none fst_conv make_full_observation.sel(2) nxt.simps nxt_alw once_none_always_none_aux)
by simp
done
(* costsMoney: THEOREM drinks |- G(X(cfstate=State_2) => gval(value_ge(r_2, Some(NUM(100))))); *)
lemma LTL_costsMoney:
"(alw (nxt (state_eq (Some 2)) impl (check_exp (Ge (V (Rg 2)) (L (Num 100)))))) (watch drinks i)"
proof(coinduction)
case alw
then show ?case
apply (cases "shd i")
subgoal for l ip
apply (case_tac "l = STR ''select'' \<and> length ip = 1")
defer
apply (simp add: possible_steps_0_invalid)
apply (rule disjI2)
apply (rule alw_mono[of "nxt (state_eq None)"])
apply (simp add: once_none_nxt_always_none)
apply (simp add: )
apply (simp add: possible_steps_0 select_def)
apply (rule disjI2)
apply (simp only: nxt.simps[symmetric])
using costsMoney_aux by auto
done
qed
lemma LTL_costsMoney_aux:
"(alw (not (check_exp (Ge (V (Rg 2)) (L (Num 100)))) impl (not (nxt (state_eq (Some 2)))))) (watch drinks i)"
by (metis (no_types, lifting) LTL_costsMoney alw_mono)
lemma implode_select: "String.implode ''select'' = STR ''select''"
by (metis Literal.rep_eq String.implode_explode_eq zero_literal.rep_eq)
lemma implode_coin: "String.implode ''coin'' = STR ''coin''"
by (metis Literal.rep_eq String.implode_explode_eq zero_literal.rep_eq)
lemma implode_vend: "String.implode ''vend'' = STR ''vend''"
by (metis Literal.rep_eq String.implode_explode_eq zero_literal.rep_eq)
lemmas implode_labels = implode_select implode_coin implode_vend
lemma LTL_neverReachS2:"(((((action_eq (''select'', [Str ''coke''])))
aand
(nxt ((action_eq (''coin'', [Num 100])))))
aand
(nxt (nxt((label_eq ''vend'' aand (input_eq []))))))
impl
(nxt (nxt (nxt (state_eq (Some 2))))))
(watch drinks i)"
apply (simp add: implode_labels)
apply (cases i)
apply clarify
apply simp
apply (simp add: possible_steps_0 select_def)
apply (case_tac "shd x2", clarify)
apply (simp add: possible_steps_1_coin coin_def value_plus_def finfun_update_twist apply_updates_def)
apply (case_tac "shd (stl x2)", clarify)
by (simp add: drinks_vend_sufficient )
lemma ltl_step_not_select:
"\<nexists>i. e = (STR ''select'', [i]) \<Longrightarrow>
ltl_step drinks (Some 0) r e = (None, [], r)"
apply (cases e, clarify)
subgoal for a b
apply (rule ltl_step_none)
apply (simp add: possible_steps_empty drinks_def can_take_transition_def can_take_def select_def)
by (cases e, case_tac b, auto)
done
lemma ltl_step_select:
"ltl_step drinks (Some 0) <> (STR ''select'', [i]) = (Some 1, [], <1 $:= Some i, 2 $:= Some (Num 0)>)"
apply (rule ltl_step_some[of _ _ _ _ _ _ select])
apply (simp add: possible_steps_0)
apply (simp add: select_def)
by (simp add: select_def finfun_update_twist apply_updates_def)
lemma ltl_step_not_coin_or_vend:
"\<nexists>i. e = (STR ''coin'', [i]) \<Longrightarrow>
e \<noteq> (STR ''vend'', []) \<Longrightarrow>
ltl_step drinks (Some 1) r e = (None, [], r)"
apply (cases e)
subgoal for a b
apply (simp del: ltl_step.simps)
apply (rule ltl_step_none)
apply (simp add: possible_steps_empty drinks_def can_take_transition_def can_take_def transitions)
by (case_tac e, case_tac b, auto)
done
lemma ltl_step_coin:
"\<exists>p r'. ltl_step drinks (Some 1) r (STR ''coin'', [i]) = (Some 1, p, r')"
by (simp add: possible_steps_1_coin)
lemma alw_tl:
"alw \<phi> (make_full_observation e (Some 0) <> [] xs) \<Longrightarrow>
alw \<phi>
(make_full_observation e (fst (ltl_step e (Some 0) <> (shd xs))) (snd (snd (ltl_step e (Some 0) <> (shd xs))))
(fst (snd (ltl_step e (Some 0) <> (shd xs)))) (stl xs))"
by auto
lemma stop_at_none:
"alw (\<lambda>xs. output (shd (stl xs)) = [Some (EFSM.Str drink)] \<longrightarrow> check_exp (Ge (V (Rg 2)) (L (Num 100))) xs)
(make_full_observation drinks None r p t)"
apply (rule alw_mono[of "nxt (output_eq [])"])
apply (simp add: no_output_none_nxt)
by simp
lemma drink_costs_money_aux:
assumes "\<exists>p r t. j = make_full_observation drinks (Some 1) r p t"
shows "alw (\<lambda>xs. output (shd (stl xs)) = [Some (EFSM.Str drink)] \<longrightarrow> check_exp (Ge (V (Rg 2)) (L (Num 100))) xs) j"
using assms apply coinduct
apply clarsimp
apply (case_tac "shd t")
apply (simp del: ltl_step.simps)
apply (rule P_ltl_step_1)
apply simp
apply (rule disjI2)
apply (rule alw_mono[of "nxt (output_eq [])"])
apply (simp add: no_output_none_nxt)
apply simp
apply (simp add: Str_def value_plus_never_string)
apply auto[1]
apply auto[1]
apply simp
apply standard
apply (rule disjI2)
apply (rule alw_mono[of "nxt (output_eq [])"])
apply (simp add: drinks_step_2_none no_output_none_if_empty nxt_alw)
by simp
lemma LTL_drinks_cost_money:
"alw (nxt (output_eq [Some (Str drink)]) impl (check_exp (Ge (V (Rg 2)) (L (Num 100))))) (watch drinks t)"
proof(coinduction)
case alw
then show ?case
apply (case_tac "shd t")
apply (simp del: ltl_step.simps)
apply (rule P_ltl_step_0)
apply simp
apply (rule disjI2)
apply (rule alw_mono[of "nxt (output_eq [])"])
apply (simp add: no_output_none_nxt)
apply simp
apply simp
using drink_costs_money_aux
apply simp
by blast
qed
lemma steps_1_invalid:
"\<nexists>i. (a, b) = (STR ''coin'', [i]) \<Longrightarrow>
\<nexists>i. (a, b) = (STR ''vend'', []) \<Longrightarrow>
possible_steps drinks 1 r a b = {||}"
apply (simp add: possible_steps_empty drinks_def transitions can_take_transition_def can_take_def)
by (induct b, auto)
lemma output_vend_aux:
assumes "\<exists>p r t. j = make_full_observation drinks (Some 1) r p t"
shows "alw (\<lambda>xs. label_eq ''vend'' xs \<and> output (shd (stl xs)) = [Some d] \<longrightarrow> check_exp (Ge (V (Rg 2)) (L (Num 100))) xs) j"
using assms apply coinduct
apply clarsimp
subgoal for r t
apply (case_tac "shd t")
apply (simp add: implode_vend del: ltl_step.simps)
apply (rule P_ltl_step_1)
apply simp
apply (rule disjI2)
apply (rule alw_mono[of "nxt (output_eq [])"])
apply (simp add: no_output_none_nxt)
apply simp
apply auto[1]
apply auto[1]
apply simp
apply standard
apply (rule disjI2)
apply (rule alw_mono[of "nxt (output_eq [])"])
apply (simp add: drinks_step_2_none no_output_none_if_empty nxt_alw)
by simp
done
text_raw\<open>\snip{outputVend}{1}{2}{%\<close>
lemma LTL_output_vend:
"alw (((label_eq ''vend'') aand (nxt (output_eq [Some d]))) impl
(check_exp (Ge (V (Rg 2)) (L (Num 100))))) (watch drinks t)"
text_raw\<open>}%endsnip\<close>
proof(coinduction)
case alw
then show ?case
apply (simp add: implode_vend)
apply (case_tac "shd t")
apply (simp del: ltl_step.simps)
apply (rule P_ltl_step_0)
apply simp
apply (rule disjI2)
apply (rule alw_mono[of "nxt (output_eq [])"])
apply (simp add: no_output_none_nxt)
apply simp
apply simp
subgoal for a b
using output_vend_aux[of "(make_full_observation drinks (Some 1)
<1 $:= Some (hd b), 2 $:= Some (Num 0)> [] (stl t))" d]
using implode_vend by auto
done
qed
text_raw\<open>\snip{outputVendUnfolded}{1}{2}{%\<close>
lemma LTL_output_vend_unfolded:
"alw (\<lambda>xs. (label (shd xs) = STR ''vend'' \<and>
nxt (\<lambda>s. output (shd s) = [Some d]) xs) \<longrightarrow>
\<not>? value_gt (Some (Num 100)) (datastate (shd xs) $ 2) = trilean.true)
(watch drinks t)"
text_raw\<open>}%endsnip\<close>
apply (insert LTL_output_vend[of d t])
by (simp add: implode_vend)
end
|
import SciLean.Operators
namespace SciLean
variable {X Y Z W : Type} [Vec X] [Vec Y] [Vec Z] [Vec W]
structure HArray (Ts : List Type) where
data : Array (Sigma (λ T : Type => T))
h_len : Ts.length = data.size
typed : ∀ i : Fin Ts.length, (data.get (h_len ▸ i)).1 = Ts.get i
namespace HArray
variable {n} {Ts : List Type}
def get (u : HArray Ts) (i : Fin Ts.length) : Ts.get i
:= u.typed i ▸ (u.data.get (u.h_len ▸ i)).2
def getOp (self : HArray Ts) (idx : Fin Ts.length) : Ts.get idx
:= self.typed idx ▸ (self.data.get (self.h_len ▸ idx)).2
def set (u : HArray Ts) (i : Fin Ts.length) (x : Ts.get i) : HArray Ts
:= ⟨u.data.set (u.h_len ▸ i) (⟨_, x⟩), sorry, sorry⟩
end HArray
class HCurryType (n : Nat) (F : Type) where
Xs : List Type
Y : Type
attribute [reducible] HCurryType.Xs HCurryType.Y
@[reducible]
instance : HCurryType 0 Y where
Xs := []
Y := Y
@[reducible]
instance {X Y : Type} [t : HCurryType n Y] : HCurryType (n + 1) (X → Y) where
Xs := X::t.Xs
Y := t.Y
class HCurry (i : Nat) (Xs' Xs : List Type) (Y : Type) where
index_valid : Xs'.length + i = Xs.length
types_valid : ∀ j, i + j < Xs.length → Xs'.get ⟨j, sorry⟩ = Xs.get ⟨i + j, sorry⟩
F : Type
uncurry : F → (HArray Xs → Y)
attribute [reducible] HCurry.F HCurry.uncurry
@[reducible]
instance (Xs : List Type) (Y : Type) : HCurry n [] Xs Y where
index_valid := sorry
types_valid := sorry
F := Y
uncurry := λ y xs => y
@[reducible]
instance [c : HCurry (i+1) (Xs') Xs Y] : HCurry (i) (X'::Xs') Xs Y where
index_valid := sorry
types_valid := sorry
F := X' → c.F
uncurry := λ f xs =>
let h : (Xs.get ⟨i,sorry⟩ = X') := sorry
let xi : X' := (h ▸ xs[⟨i,sorry⟩])
c.uncurry (f xi) xs
def huncurry (n : Nat) {F : Type} [HCurryType n F]
[ci : HCurry 0 (HCurryType.Xs n F) (HCurryType.Xs n F) (HCurryType.Y n F)]
(f : F) :=
let h : F = ci.F := sorry
ci.uncurry (h ▸ f)
example : huncurry 3 (λ (i j k : Nat) => i + j)
=
λ xs => xs[#0] + xs[#1] :=
by rfl
example : huncurry 2 (λ (i j k : Nat) => i + j)
=
λ xs k => xs[#0] + xs[#1] :=
by rfl
|
/-
Copyright (c) 2022 Devon Tuma. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Devon Tuma
-/
import computational_monads.simulation_semantics.constructions.logging.caching_oracle
import computational_monads.simulation_semantics.constructions.uniform_oracle
import computational_monads.simulation_semantics.mask_state
/-!
# Random Oralces
This file defines a traditional cryptographic `random_oracle`,
an oracle that responds uniformly to new queries, and with the same value for repeat queries.
The definition is a composition of a `uniform_oracle` and a `caching_oracle`.
-/
open oracle_comp oracle_spec
variables {α β γ : Type} {spec spec' spec'' : oracle_spec} {S S' : Type}
/-- Oracle that responds uniformly at random to any new queries,
but returns the same result to subsequent oracle queries.
Masking is used to hide the irrelevent state of the `uniform_oracle` -/
noncomputable def random_oracle (spec : oracle_spec) :
sim_oracle spec uniform_selecting (query_log spec) :=
((uniform_oracle spec) ∘ₛ (caching_oracle spec)).mask_state (equiv.prod_punit (query_log spec))
namespace random_oracle
variables (log : query_log spec) (log' : query_log spec')
/-- The support of apply is things where the log doesn't change on things previously queried,
and the log has the new query if it was previously queried -/
lemma support_apply (i : spec.ι) (t : spec.domain i) (log : query_log spec) :
((random_oracle spec) i (t, log)).support =
λ ⟨u, log'⟩, if log.lookup i t = u then log' = log else log' = log.log_query i t u :=
begin
sorry
end
lemma support_simulate (oa : oracle_comp spec α) :
(simulate (random_oracle spec) oa (query_log.init spec)).support =
{x | sorry} :=
begin
sorry
end
section distribution_semantics
end distribution_semantics
end random_oracle |
section \<open>Sepref-Definition Command\<close>
theory Sepref_Definition
imports Sepref_Rules "Lib/Pf_Mono_Prover" "Lib/Term_Synth" Refine_Automation
keywords "sepref_definition" :: thy_goal
and "sepref_thm" :: thy_goal
begin
subsection \<open>Setup of Extraction-Tools\<close>
declare [[cd_patterns "hn_refine _ ?f _ _ _"]]
lemma heap_fixp_codegen:
assumes DEF: "f \<equiv> heap.fixp_fun cB"
assumes M: "(\<And>x. mono_Heap (\<lambda>f. cB f x))"
shows "f x = cB f x"
unfolding DEF
apply (rule fun_cong[of _ _ x])
apply (rule heap.mono_body_fixp)
apply fact
done
ML \<open>
structure Sepref_Extraction = struct
val heap_extraction: Refine_Automation.extraction = {
pattern = Logic.varify_global @{term "heap.fixp_fun x"},
gen_thm = @{thm heap_fixp_codegen},
gen_tac = (fn ctxt =>
Pf_Mono_Prover.mono_tac ctxt
)
}
val setup = I
(*#> Refine_Automation.add_extraction "trivial" triv_extraction*)
#> Refine_Automation.add_extraction "heap" heap_extraction
end
\<close>
setup Sepref_Extraction.setup
subsection \<open>Synthesis setup for sepref-definition goals\<close>
(* TODO: The UNSPEC are an ad-hoc hack to specify the synthesis goal *)
consts UNSPEC::'a
abbreviation hfunspec
:: "('a \<Rightarrow> 'b \<Rightarrow> assn) \<Rightarrow> ('a \<Rightarrow> 'b \<Rightarrow> assn)\<times>('a \<Rightarrow> 'b \<Rightarrow> assn)"
("(_\<^sup>?)" [1000] 999)
where "R\<^sup>? \<equiv> hf_pres R UNSPEC"
definition SYNTH :: "('a \<Rightarrow> 'r nrest) \<Rightarrow> (('ai \<Rightarrow>'ri Heap) \<times> ('a \<Rightarrow> 'r nrest)) set \<Rightarrow> bool"
where "SYNTH f R \<equiv> True"
definition [simp]: "CP_UNCURRY _ _ \<equiv> True"
definition [simp]: "INTRO_KD _ _ \<equiv> True"
definition [simp]: "SPEC_RES_ASSN _ _ \<equiv> True"
lemma [synth_rules]: "\<lbrakk>INTRO_KD R1 R1'; INTRO_KD R2 R2'\<rbrakk> \<Longrightarrow> INTRO_KD (R1*\<^sub>aR2) (R1'*\<^sub>aR2')" by simp
lemma [synth_rules]: "INTRO_KD (R\<^sup>?) (hf_pres R k)" by simp
lemma [synth_rules]: "INTRO_KD (R\<^sup>k) (R\<^sup>k)" by simp
lemma [synth_rules]: "INTRO_KD (R\<^sup>d) (R\<^sup>d)" by simp
lemma [synth_rules]: "SPEC_RES_ASSN R R" by simp
lemma [synth_rules]: "SPEC_RES_ASSN UNSPEC R" by simp
lemma synth_hnrI:
"\<lbrakk>CP_UNCURRY fi f; INTRO_KD R R'; SPEC_RES_ASSN S S'\<rbrakk> \<Longrightarrow> SYNTH_TERM (SYNTH f ([P]\<^sub>a R\<rightarrow>S)) ((fi,SDUMMY)\<in>SDUMMY,(fi,f)\<in>([P]\<^sub>a R'\<rightarrow>S'))"
by (simp add: SYNTH_def)
term starts_with
ML \<open>
structure Sepref_Definition = struct
fun make_hnr_goal t ctxt = let
val ctxt = Variable.declare_term t ctxt
val (pat,goal) = case Term_Synth.synth_term @{thms synth_hnrI} ctxt t of
@{mpat "(?pat,?goal)"} => (pat,goal) | t => raise TERM("Synthesized term does not match",[t])
val pat = Thm.cterm_of ctxt pat |> Refine_Automation.prepare_cd_pattern ctxt
val goal = HOLogic.mk_Trueprop goal
in
((pat,goal),ctxt)
end
val cfg_prep_code = Attrib.setup_config_bool @{binding sepref_definition_prep_code} (K true)
local
open Refine_Util
val flags = parse_bool_config' "prep_code" cfg_prep_code
val parse_flags = parse_paren_list' flags
in
val sd_parser = parse_flags -- Parse.binding -- Parse.opt_attribs --| @{keyword "is"}
-- Parse.term --| @{keyword "::"} -- Parse.term
end
fun mk_synth_term ctxt t_raw r_raw = let
val t = Syntax.parse_term ctxt t_raw
val r = Syntax.parse_term ctxt r_raw
val t = Const (@{const_name SYNTH},dummyT)$t$r
in
Syntax.check_term ctxt t
end
fun sd_cmd ((((flags,name),attribs),t_raw),r_raw) lthy = let
local
val ctxt = Refine_Util.apply_configs flags lthy
in
val flag_prep_code = Config.get ctxt cfg_prep_code
end
val t = mk_synth_term lthy t_raw r_raw
val ((pat,goal),ctxt) = make_hnr_goal t lthy
fun
after_qed [[thm]] ctxt = let
val thm = singleton (Variable.export ctxt lthy) thm
val (_,lthy)
= Local_Theory.note
((Refine_Automation.mk_qualified (Binding.name_of name) "refine_raw",[]),[thm])
lthy;
val ((dthm,rthm),lthy) = Refine_Automation.define_concrete_fun NONE name attribs [] thm [pat] lthy
val lthy = lthy
|> flag_prep_code ? Refine_Automation.extract_recursion_eqs
[Sepref_Extraction.heap_extraction] (Binding.name_of name) dthm
val _ = Thm.pretty_thm lthy dthm |> Pretty.string_of |> writeln
val _ = Thm.pretty_thm lthy rthm |> Pretty.string_of |> writeln
in
lthy
end
| after_qed thmss _ = raise THM ("After-qed: Wrong thmss structure",~1,flat thmss)
in
Proof.theorem NONE after_qed [[ (goal,[]) ]] ctxt
end
val _ = Outer_Syntax.local_theory_to_proof @{command_keyword "sepref_definition"}
"Synthesis of imperative program"
(sd_parser >> sd_cmd)
val st_parser = Parse.binding --| @{keyword "is"} -- Parse.term --| @{keyword "::"} -- Parse.term
fun st_cmd ((name,t_raw),r_raw) lthy = let
val t = mk_synth_term lthy t_raw r_raw
val ((_,goal),ctxt) = make_hnr_goal t lthy
fun
after_qed [[thm]] ctxt = let
val thm = singleton (Variable.export ctxt lthy) thm
val _ = Thm.pretty_thm lthy thm |> Pretty.string_of |> tracing
val (_,lthy)
= Local_Theory.note
((Refine_Automation.mk_qualified (Binding.name_of name) "refine_raw",[]),[thm])
lthy;
in
lthy
end
| after_qed thmss _ = raise THM ("After-qed: Wrong thmss structure",~1,flat thmss)
in
Proof.theorem NONE after_qed [[ (goal,[]) ]] ctxt
end
val _ = Outer_Syntax.local_theory_to_proof @{command_keyword "sepref_thm"}
"Synthesis of imperative program: Only generate raw refinement theorem"
(st_parser >> st_cmd)
end
\<close>
end
|
module Main
-- import Effects
-- import Effect.StdIO
-- import Prelude.Monad
-- import Sanity.Hello
-- Convenient for Idris build script
-- forces compiling of all modules
import Part1.Sec1_4_5
import Part1.Sec2_2_2_the
import Util.MiniParser
import Part2.Sec3_2_3_gen
import Part2.Sec4_2_2_gen
import Part2.Sec5_3_3_dpair
import Part2.Sec6_1_1_tyfunc
import Part2.Sec6_2_1_adder
import Part2.Sec6_2_2_printf
import Part2.Sec6_3_datastore
import Part2.Sec6_3b_datastore
import Part2.Sec8_1_eqproof
import Part2.Sec8_2_5_vappd
import Part2.Sec8_2z_reverse
import Part2.Sec8_3_deceq
import Part2.Sec9_1_elem
import Part2.Sec9_2_hangman
import Part2.Sez10_1_views
import Part2.Sez10_2a_snoc
import Part2.Sez10_2b
import Part2.Sez10_2e
import Part2.Sez10_3_hiding
import Part3.Sec14a_DoorJam
import Part3.Sec14b_ATM
import Part3.Sec15a_ProcessLib
import Part3.Sec15b_ProcessList
import Play.FunctorLaws
import Play.RankN
main : IO ()
main = sec6_3b
--do
-- run sayHello
-- putStrLn (valToString True 20)
|
"""
The ``mlflow.statsmodels`` module provides an API for logging and loading statsmodels models.
This module exports statsmodels models with the following flavors:
statsmodels (native) format
This is the main flavor that can be loaded back into statsmodels, which relies on pickle
internally to serialize a model.
:py:mod:`mlflow.pyfunc`
Produced for use by generic pyfunc-based deployment tools and batch inference.
.. _statsmodels.base.model.Results:
https://www.statsmodels.org/stable/_modules/statsmodels/base/model.html#Results
"""
import os
import yaml
import logging
import mlflow
from mlflow import pyfunc
from mlflow.models import Model
from mlflow.models.model import MLMODEL_FILE_NAME
from mlflow.models.signature import ModelSignature
from mlflow.models.utils import ModelInputExample, _save_example
from mlflow.tracking.artifact_utils import _download_artifact_from_uri
from mlflow.utils.environment import (
_mlflow_conda_env,
_validate_env_arguments,
_process_pip_requirements,
_process_conda_env,
_CONDA_ENV_FILE_NAME,
_REQUIREMENTS_FILE_NAME,
_CONSTRAINTS_FILE_NAME,
)
from mlflow.utils.requirements_utils import _get_pinned_requirement
from mlflow.utils.file_utils import write_to
from mlflow.utils.docstring_utils import format_docstring, LOG_MODEL_PARAM_DOCS
from mlflow.utils.model_utils import _get_flavor_configuration
from mlflow.exceptions import MlflowException
from mlflow.utils.annotations import experimental
from mlflow.utils.autologging_utils import (
log_fn_args_as_params,
autologging_integration,
safe_patch,
get_autologging_config,
)
from mlflow.utils.validation import _is_numeric
import itertools
import inspect
from mlflow.tracking._model_registry import DEFAULT_AWAIT_MAX_SLEEP_SECONDS
FLAVOR_NAME = "statsmodels"
STATSMODELS_DATA_SUBPATH = "model.statsmodels"
_logger = logging.getLogger(__name__)
def get_default_pip_requirements():
"""
:return: A list of default pip requirements for MLflow Models produced by this flavor.
Calls to :func:`save_model()` and :func:`log_model()` produce a pip environment
that, at minimum, contains these requirements.
"""
return [_get_pinned_requirement("statsmodels")]
def get_default_conda_env():
"""
:return: The default Conda environment for MLflow Models produced by calls to
:func:`save_model()` and :func:`log_model()`.
"""
return _mlflow_conda_env(additional_pip_deps=get_default_pip_requirements())
_model_size_threshold_for_emitting_warning = 100 * 1024 * 1024 # 100 MB
_save_model_called_from_autolog = False
@format_docstring(LOG_MODEL_PARAM_DOCS.format(package_name=FLAVOR_NAME))
def save_model(
statsmodels_model,
path,
conda_env=None,
mlflow_model=None,
remove_data: bool = False,
signature: ModelSignature = None,
input_example: ModelInputExample = None,
pip_requirements=None,
extra_pip_requirements=None,
):
"""
Save a statsmodels model to a path on the local file system.
:param statsmodels_model: statsmodels model (an instance of `statsmodels.base.model.Results`_)
to be saved.
:param path: Local path where the model is to be saved.
:param conda_env: {{ conda_env }}
:param mlflow_model: :py:mod:`mlflow.models.Model` this flavor is being added to.
:param remove_data: bool. If False (default), then the instance is pickled without changes.
If True, then all arrays with length nobs are set to None before
pickling. See the remove_data method.
In some cases not all arrays will be set to None.
:param signature: :py:class:`ModelSignature <mlflow.models.ModelSignature>`
describes model input and output :py:class:`Schema <mlflow.types.Schema>`.
The model signature can be :py:func:`inferred <mlflow.models.infer_signature>`
from datasets with valid model input (e.g. the training dataset with target
column omitted) and valid model output (e.g. model predictions generated on
the training dataset), for example:
.. code-block:: python
from mlflow.models.signature import infer_signature
train = df.drop_column("target_label")
predictions = ... # compute model predictions
signature = infer_signature(train, predictions)
:param input_example: Input example provides one or several instances of valid
model input. The example can be used as a hint of what data to feed the
model. The given example will be converted to a Pandas DataFrame and then
serialized to json using the Pandas split-oriented format. Bytes are
base64-encoded.
:param pip_requirements: {{ pip_requirements }}
:param extra_pip_requirements: {{ extra_pip_requirements }}
"""
import statsmodels
_validate_env_arguments(conda_env, pip_requirements, extra_pip_requirements)
path = os.path.abspath(path)
if os.path.exists(path):
raise MlflowException("Path '{}' already exists".format(path))
model_data_path = os.path.join(path, STATSMODELS_DATA_SUBPATH)
os.makedirs(path)
if mlflow_model is None:
mlflow_model = Model()
if signature is not None:
mlflow_model.signature = signature
if input_example is not None:
_save_example(mlflow_model, input_example, path)
# Save a statsmodels model
statsmodels_model.save(model_data_path, remove_data)
if _save_model_called_from_autolog and not remove_data:
saved_model_size = os.path.getsize(model_data_path)
if saved_model_size >= _model_size_threshold_for_emitting_warning:
_logger.warning(
"The fitted model is larger than "
f"{_model_size_threshold_for_emitting_warning // (1024 * 1024)} MB, "
f"saving it as artifacts is time consuming.\n"
"To reduce model size, use `mlflow.statsmodels.autolog(log_models=False)` and "
"manually log model by "
'`mlflow.statsmodels.log_model(model, remove_data=True, artifact_path="model")`'
)
pyfunc.add_to_model(
mlflow_model,
loader_module="mlflow.statsmodels",
data=STATSMODELS_DATA_SUBPATH,
env=_CONDA_ENV_FILE_NAME,
)
mlflow_model.add_flavor(
FLAVOR_NAME, statsmodels_version=statsmodels.__version__, data=STATSMODELS_DATA_SUBPATH
)
mlflow_model.save(os.path.join(path, MLMODEL_FILE_NAME))
if conda_env is None:
if pip_requirements is None:
default_reqs = get_default_pip_requirements()
# To ensure `_load_pyfunc` can successfully load the model during the dependency
# inference, `mlflow_model.save` must be called beforehand to save an MLmodel file.
inferred_reqs = mlflow.models.infer_pip_requirements(
path, FLAVOR_NAME, fallback=default_reqs,
)
default_reqs = sorted(set(inferred_reqs).union(default_reqs))
else:
default_reqs = None
conda_env, pip_requirements, pip_constraints = _process_pip_requirements(
default_reqs, pip_requirements, extra_pip_requirements,
)
else:
conda_env, pip_requirements, pip_constraints = _process_conda_env(conda_env)
with open(os.path.join(path, _CONDA_ENV_FILE_NAME), "w") as f:
yaml.safe_dump(conda_env, stream=f, default_flow_style=False)
# Save `constraints.txt` if necessary
if pip_constraints:
write_to(os.path.join(path, _CONSTRAINTS_FILE_NAME), "\n".join(pip_constraints))
# Save `requirements.txt`
write_to(os.path.join(path, _REQUIREMENTS_FILE_NAME), "\n".join(pip_requirements))
@format_docstring(LOG_MODEL_PARAM_DOCS.format(package_name=FLAVOR_NAME))
def log_model(
statsmodels_model,
artifact_path,
conda_env=None,
registered_model_name=None,
remove_data: bool = False,
signature: ModelSignature = None,
input_example: ModelInputExample = None,
await_registration_for=DEFAULT_AWAIT_MAX_SLEEP_SECONDS,
pip_requirements=None,
extra_pip_requirements=None,
**kwargs,
):
"""
Log a statsmodels model as an MLflow artifact for the current run.
:param statsmodels_model: statsmodels model (an instance of `statsmodels.base.model.Results`_)
to be saved.
:param artifact_path: Run-relative artifact path.
:param conda_env: {{ conda_env }}
:param registered_model_name: If given, create a model version under
``registered_model_name``, also creating a registered model if one
with the given name does not exist.
:param remove_data: bool. If False (default), then the instance is pickled without changes.
If True, then all arrays with length nobs are set to None before
pickling. See the remove_data method.
In some cases not all arrays will be set to None.
:param signature: :py:class:`ModelSignature <mlflow.models.ModelSignature>`
describes model input and output :py:class:`Schema <mlflow.types.Schema>`.
The model signature can be :py:func:`inferred <mlflow.models.infer_signature>`
from datasets with valid model input (e.g. the training dataset with target
column omitted) and valid model output (e.g. model predictions generated on
the training dataset), for example:
.. code-block:: python
from mlflow.models.signature import infer_signature
train = df.drop_column("target_label")
predictions = ... # compute model predictions
signature = infer_signature(train, predictions)
:param input_example: Input example provides one or several instances of valid
model input. The example can be used as a hint of what data to feed the
model. The given example will be converted to a Pandas DataFrame and then
serialized to json using the Pandas split-oriented format. Bytes are
base64-encoded.
:param await_registration_for: Number of seconds to wait for the model version to finish
being created and is in ``READY`` status. By default, the function
waits for five minutes. Specify 0 or None to skip waiting.
:param pip_requirements: {{ pip_requirements }}
:param extra_pip_requirements: {{ extra_pip_requirements }}
"""
Model.log(
artifact_path=artifact_path,
flavor=mlflow.statsmodels,
registered_model_name=registered_model_name,
statsmodels_model=statsmodels_model,
conda_env=conda_env,
signature=signature,
input_example=input_example,
await_registration_for=await_registration_for,
remove_data=remove_data,
pip_requirements=pip_requirements,
extra_pip_requirements=extra_pip_requirements,
**kwargs,
)
def _load_model(path):
import statsmodels.iolib.api as smio
return smio.load_pickle(path)
def _load_pyfunc(path):
"""
Load PyFunc implementation. Called by ``pyfunc.load_pyfunc``.
:param path: Local filesystem path to the MLflow Model with the ``statsmodels`` flavor.
"""
return _StatsmodelsModelWrapper(_load_model(path))
def load_model(model_uri):
"""
Load a statsmodels model from a local file or a run.
:param model_uri: The location, in URI format, of the MLflow model. For example:
- ``/Users/me/path/to/local/model``
- ``relative/path/to/local/model``
- ``s3://my_bucket/path/to/model``
- ``runs:/<mlflow_run_id>/run-relative/path/to/model``
For more information about supported URI schemes, see
`Referencing Artifacts <https://www.mlflow.org/docs/latest/tracking.html#
artifact-locations>`_.
:return: A statsmodels model (an instance of `statsmodels.base.model.Results`_).
"""
local_model_path = _download_artifact_from_uri(artifact_uri=model_uri)
flavor_conf = _get_flavor_configuration(model_path=local_model_path, flavor_name=FLAVOR_NAME)
statsmodels_model_file_path = os.path.join(
local_model_path, flavor_conf.get("data", STATSMODELS_DATA_SUBPATH)
)
return _load_model(path=statsmodels_model_file_path)
class _StatsmodelsModelWrapper:
def __init__(self, statsmodels_model):
self.statsmodels_model = statsmodels_model
def predict(self, dataframe):
from statsmodels.tsa.base.tsa_model import TimeSeriesModel
model = self.statsmodels_model.model
if isinstance(model, TimeSeriesModel):
# Assume the inference dataframe has columns "start" and "end", and just one row
# TODO: move this to a specific mlflow.statsmodels.tsa flavor? Time series models
# often expect slightly different arguments to make predictions
if dataframe.shape[0] != 1 or not (
"start" in dataframe.columns and "end" in dataframe.columns
):
raise MlflowException(
"prediction dataframes for a TimeSeriesModel must have exactly one row"
+ " and include columns called start and end"
)
start_date = dataframe["start"][0]
end_date = dataframe["end"][0]
return self.statsmodels_model.predict(start=start_date, end=end_date)
else:
return self.statsmodels_model.predict(dataframe)
class AutologHelpers:
# Autologging should be done only in the fit function called by the user, but not
# inside other internal fit functions
should_autolog = True
# Currently we only autolog basic metrics
_autolog_metric_allowlist = [
"aic",
"bic",
"centered_tss",
"condition_number",
"df_model",
"df_resid",
"ess",
"f_pvalue",
"fvalue",
"llf",
"mse_model",
"mse_resid",
"mse_total",
"rsquared",
"rsquared_adj",
"scale",
"ssr",
"uncentered_tss",
]
def _get_autolog_metrics(fitted_model):
result_metrics = {}
failed_evaluating_metrics = set()
for metric in _autolog_metric_allowlist:
try:
if hasattr(fitted_model, metric):
metric_value = getattr(fitted_model, metric)
if _is_numeric(metric_value):
result_metrics[metric] = metric_value
except Exception:
failed_evaluating_metrics.add(metric)
if len(failed_evaluating_metrics) > 0:
_logger.warning(
f"Failed to autolog metrics: {', '.join(sorted(failed_evaluating_metrics))}."
)
return result_metrics
@experimental
@autologging_integration(FLAVOR_NAME)
def autolog(
log_models=True,
disable=False,
exclusive=False,
disable_for_unsupported_versions=False,
silent=False,
): # pylint: disable=unused-argument
"""
Enables (or disables) and configures automatic logging from statsmodels to MLflow.
Logs the following:
- allowlisted metrics returned by method `fit` of any subclass of
statsmodels.base.model.Model, the allowlisted metrics including: {autolog_metric_allowlist}
- trained model.
- an html artifact which shows the model summary.
:param log_models: If ``True``, trained models are logged as MLflow model artifacts.
If ``False``, trained models are not logged.
Input examples and model signatures, which are attributes of MLflow models,
are also omitted when ``log_models`` is ``False``.
:param disable: If ``True``, disables the statsmodels autologging integration. If ``False``,
enables the statsmodels autologging integration.
:param exclusive: If ``True``, autologged content is not logged to user-created fluent runs.
If ``False``, autologged content is logged to the active fluent run,
which may be user-created.
:param disable_for_unsupported_versions: If ``True``, disable autologging for versions of
statsmodels that have not been tested against this version of the MLflow
client or are incompatible.
:param silent: If ``True``, suppress all event logs and warnings from MLflow during statsmodels
autologging. If ``False``, show all events and warnings during statsmodels
autologging.
"""
import statsmodels
# Autologging depends on the exploration of the models class tree within the
# `statsmodels.base.models` module. In order to load / access this module, the
# `statsmodels.api` module must be imported
import statsmodels.api # pylint: disable=unused-import
def find_subclasses(klass):
"""
Recursively return a (non-nested) list of the class object and all its subclasses
:param klass: the class whose class subtree we want to retrieve
:return: a list of classes that includes the argument in the first position
"""
subclasses = klass.__subclasses__()
if subclasses:
subclass_lists = [find_subclasses(c) for c in subclasses]
chain = itertools.chain.from_iterable(subclass_lists)
result = [klass] + list(chain)
return result
else:
return [klass]
def overrides(klass, function_name):
"""
Returns True when the class passed as first argument overrides the function_name
Based on https://stackoverflow.com/a/62303206/5726057
:param klass: the class we are inspecting
:param function_name: a string with the name of the method we want to check overriding
:return:
"""
try:
superclass = inspect.getmro(klass)[1]
overriden = getattr(klass, function_name) is not getattr(superclass, function_name)
return overriden
except (IndexError, AttributeError):
return False
def patch_class_tree(klass):
"""
Patches all subclasses that override any auto-loggable method via monkey patching using
the gorilla package, taking the argument as the tree root in the class hierarchy. Every
auto-loggable method found in any of the subclasses is replaced by the patched version.
:param klass: root in the class hierarchy to be analyzed and patched recursively
"""
# TODO: add more autologgable methods here (e.g. fit_regularized, from_formula, etc)
# See https://www.statsmodels.org/dev/api.html
autolog_supported_func = {"fit": wrapper_fit}
glob_subclasses = set(find_subclasses(klass))
# Create a patch for every method that needs to be patched, i.e. those
# which actually override an autologgable method
patches_list = [
# Link the patched function with the original via a local variable in the closure
# to allow invoking superclass methods in the context of the subclass, and not
# losing the trace of the true original method
(clazz, method_name, wrapper_func)
for clazz in glob_subclasses
for (method_name, wrapper_func) in autolog_supported_func.items()
if overrides(clazz, method_name)
]
for clazz, method_name, patch_impl in patches_list:
safe_patch(FLAVOR_NAME, clazz, method_name, patch_impl, manage_run=True)
def wrapper_fit(original, self, *args, **kwargs):
should_autolog = False
if AutologHelpers.should_autolog:
AutologHelpers.should_autolog = False
should_autolog = True
try:
if should_autolog:
# This may generate warnings due to collisions in already-logged param names
log_fn_args_as_params(original, args, kwargs)
# training model
model = original(self, *args, **kwargs)
if should_autolog:
# Log the model
if get_autologging_config(FLAVOR_NAME, "log_models", True):
global _save_model_called_from_autolog
_save_model_called_from_autolog = True
try:
log_model(model, artifact_path="model")
finally:
_save_model_called_from_autolog = False
# Log the most common metrics
if isinstance(model, statsmodels.base.wrapper.ResultsWrapper):
metrics_dict = _get_autolog_metrics(model)
mlflow.log_metrics(metrics_dict)
model_summary = model.summary().as_text()
mlflow.log_text(model_summary, "model_summary.txt")
return model
finally:
# Clean the shared flag for future calls in case it had been set here ...
if should_autolog:
AutologHelpers.should_autolog = True
patch_class_tree(statsmodels.base.model.Model)
autolog.__doc__ = autolog.__doc__.format(
autolog_metric_allowlist=", ".join(_autolog_metric_allowlist)
)
|
Formal statement is: lemma winding_number_homotopic_loops_null_eq: assumes "path p" and \<zeta>: "\<zeta> \<notin> path_image p" shows "winding_number p \<zeta> = 0 \<longleftrightarrow> (\<exists>a. homotopic_loops (-{\<zeta>}) p (\<lambda>t. a))" (is "?lhs = ?rhs") Informal statement is: If $p$ is a path and $\zeta$ is not in the image of $p$, then the winding number of $p$ around $\zeta$ is zero if and only if $p$ is homotopic to a constant path. |
(* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% *)
(* Module with Certified Checking
of Single-Pass Module.
Last Update: Wed, 24 May 2017
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% *)
Add LoadPath "../..".
Require Import ConceptParams.AuxTactics.LibTactics.
Require Import ConceptParams.AuxTactics.BasicTactics.
Require Import ConceptParams.SetMapLib.List2Set.
Require Import ConceptParams.SetMapLib.ListPair2FMap.
Require Import ConceptParams.GenericModuleLib.SharedDataDefs.
Require Import Coq.Lists.List.
Import ListNotations.
Require Import Coq.Bool.Bool.
Require Import Coq.Structures.Orders.
Require Import Coq.Structures.Equalities.
(* ***************************************************************** *)
(** * Single-Pass Module *)
(** Single-Pass Module is well-defined if
all names are different
and all members are well-defined with following elements
refering to the previously defined ones via local context. *)
(* ***************************************************************** *)
(* ***************************************************************** *)
(* ################################################################# *)
(** ** Shared Parameters of all building blocks *)
(* ################################################################# *)
Module Type SinglePassModuleBase.
Include ModuleBase.
Declare Module MD : DataLC.
Import MD.
(** Initial local context *)
Parameter ctxl_init : ctxloc.
(** Update local context *)
Parameter upd_ctxloc : ctxloc -> ctx -> id -> t -> ctxloc.
End SinglePassModuleBase.
(* ################################################################# *)
(** ** Propositional Part *)
(* ################################################################# *)
Module SinglePassModuleDefs (Import MMB : SinglePassModuleBase)
(Import TOkD : DataLCOkDef MMB.MD).
Module HelperD.
Export MD.
Definition dt := t.
(** We can use generic implementation of single-pass module
checking from the SharedDataDefs.
For this we need several aux functions. *)
Definition update_prop (ok : Prop) (c : ctx)
(cl : ctxloc) (decl : id * dt) : Prop
:= (* check curr member in the local context *)
TOkD.is_ok c cl (snd decl)
(* and preserve previous members' part *)
/\ ok.
Definition update_ctxloc (cl : ctxloc) (c : ctx)
(decl : id * dt) : ctxloc
:= match decl with (nm, d) => upd_ctxloc cl c nm d end.
(** We can use generic implementation of module-welldefinedness *)
Module MSP := SinglePassModule_ProcessMembers.
Module MGM := GenericModule_ModuleOk MId.
(** Aux function checking that all members are ok. *)
Definition members_ok (c : ctx) (decls : list (id * dt)) : Prop :=
MSP.members_ok ctx ctxloc (id * dt)
update_prop update_ctxloc c ctxl_init decls.
End HelperD.
Import HelperD.
(** Single-Pass Module given as the AST [decls]
** is well-defined in the context [c]. *)
Definition module_ok (c : ctx) (decls : list (id * dt)) : Prop :=
MGM.module_ok dt ctx members_ok c decls.
Ltac unfold_def G :=
unfold module_ok, MGM.module_ok in G.
End SinglePassModuleDefs.
(* ################################################################# *)
(** ** Computable Part (static checker of the interpreter) *)
(* ################################################################# *)
Module SinglePassModuleInterp (Import MMB : SinglePassModuleBase)
(Import TOkI : DataLCOkInterp MMB.MD).
Module HelperI.
Export MD.
Definition dt := t.
Definition check_member (c : ctx) (cl : ctxloc) (decl : id * dt) : bool
:= TOkI.is_ok_b c cl (snd decl).
Definition update_ctxloc (cl : ctxloc) (c : ctx)
(decl : id * dt) : ctxloc
:= match decl with (nm, d) => upd_ctxloc cl c nm d end.
Module MSP := SinglePassModule_ProcessMembers.
Module MGM := GenericModule_ModuleOk MId.
(** Aux function checking that all members are ok. *)
Definition members_ok_b (c : ctx) (decls : list (id * dt)) : bool :=
MSP.members_ok_b ctx ctxloc (id * dt)
check_member update_ctxloc c ctxl_init decls.
End HelperI.
Import HelperI.
(** Checks that a module given as the AST [decls]
** is well-defined in the context [c]. *)
Definition module_ok_b (c : ctx) (decls : list (id * dt)) : bool :=
MGM.module_ok_b dt ctx members_ok_b c decls.
End SinglePassModuleInterp.
(* ################################################################# *)
(** ** Proofs of Correctness *)
(* ################################################################# *)
Module SinglePassModuleProps
(Import MMB : SinglePassModuleBase)
(Import TOkD : DataLCOkDef MMB.MD)
(Import TOkI : DataLCOkInterp MMB.MD)
(Import TOkP : DataLCOkProp MMB.MD TOkD TOkI)
.
Module Import MMD := SinglePassModuleDefs MMB TOkD.
Module Import MMI := SinglePassModuleInterp MMB TOkI.
Import MMD.HelperD. Import MMI.HelperI.
(* ----------------------------------------------------------------- *)
(** *** Helper Props *)
(* ----------------------------------------------------------------- *)
Module Helper.
Import MMD.HelperD.
Lemma check_member__sound :
forall (c : ctx) (cl : ctxloc) (decl : id * dt) (P : Prop),
P ->
check_member c cl decl = true ->
update_prop P c cl decl.
Proof.
intros c cl decl P HP H.
unfold check_member in H. unfold update_prop.
apply TOkP.is_ok_b__sound in H. tauto.
Qed.
Lemma check_member__complete :
forall (c : ctx) (cl : ctxloc) (decl : id * dt) (P : Prop),
P ->
update_prop P c cl decl ->
check_member c cl decl = true.
Proof.
intros c cl decl P HP H.
unfold check_member. unfold update_prop in H.
apply TOkP.is_ok_b__complete. tauto.
Qed.
Lemma update_prop__spec :
forall (c : ctx) (cl : ctxloc) (decl : id * dt) (P : Prop),
update_prop P c cl decl -> P.
Proof.
intros c cl decl P H.
unfold update_prop in H. tauto.
Qed.
(* ----------------------------------------------------------------- *)
Module MSP := SinglePassModule_ProcessMembers.
Module MGM := GenericModule_ModuleOk MId.
Lemma members_ok_b__sound :
forall (c : ctx) (decls : list (id * dt)),
members_ok_b c decls = true ->
members_ok c decls.
Proof.
intros c ds H.
unfold members_ok_b in H.
unfold members_ok.
apply MSP.members_ok_b__sound with (update_prop := update_prop) in H.
assumption.
exact check_member__sound.
Qed.
Lemma members_ok_b__complete :
forall (c : ctx) (decls : list (id * dt)),
members_ok c decls ->
members_ok_b c decls = true.
Proof.
intros c ds H.
unfold members_ok in H.
unfold members_ok_b.
apply MSP.members_ok_b__complete with (check_member := check_member) in H.
assumption.
exact check_member__complete.
exact update_prop__spec.
Qed.
End Helper.
(* ================================================================= *)
(** *** Properties *)
(* ================================================================= *)
Theorem module_ok_b__sound : forall (c : ctx) (decls : list (id * dt)),
module_ok_b c decls = true ->
module_ok c decls.
Proof.
apply Helper.MGM.module_ok_b__sound.
apply Helper.members_ok_b__sound.
Qed.
Theorem module_ok_b__complete : forall (c : ctx) (decls : list (id * dt)),
module_ok c decls ->
module_ok_b c decls = true.
Proof.
apply Helper.MGM.module_ok_b__complete.
apply Helper.members_ok_b__complete.
Qed.
End SinglePassModuleProps.
|
The niche image carved on the south wall is an ensemble of divinities assembled around the central figures of Shiva and Parvati shown getting married ( Kalyanasundara icon ) . Parvati is seen standing to Shiva 's right , the ordained place for a Hindu bride at the wedding . The carvings are substantially damaged ; only one of Shiva 's four hands is fully seen and the right leg is missing . Shiva has a headdress with a shining disc attached to it . His garments are well @-@ draped , and well @-@ tied at the waist . The sacred thread is seen across his chest . Parvati is carved as a perfect figure with coiffured hair dress , well adorned with jewellery and is draped tightly to display depressions below the waist only . She is seen with a coy expression and is led by her father who has his right hand on her shoulder . Even though both her hands are damaged , it is inferred that her left hand clasped Shiva 's right hand as a mark of holy alliance . Brahma is sitting as the officiating priest for the marriage . Vishnu is witness to the marriage . Mena , the mother of Parvati , is seen standing next to Vishnu . The moon @-@ god Chandra , seen with a wig and a crescent , is standing behind Parvati holding a circular pot with nectar for the marriage ceremony . Just above the main images , a galaxy of divinities , bearded sages , apsaras ( nymphs ) , Vidyadharas , <unk> , Gandharvas , Bhringi , and other male and female attendants are seen as witness to the marriage ceremony showering flowers on the divine couple .
|
module Eq.Theory where
open import Prelude
open import T
open import DynTheory
open import SubstTheory
open import Contexts
open import Eq.Defs
open import Eq.KleeneTheory
open import Eq.ObsTheory
open import Eq.LogicalTheory
-- Theory about the interactions between the relationships between the equivs
-- Now that we have shown that logical equivalence is a consistent congruence,
-- it follows that it is contained in observational equivalence.
obs-contains-logical : ∀{Γ} {A} → OLogicalEq Γ A ⊆ ObservEq Γ A
obs-contains-logical = obs-is-coarsest OLogicalEq log-is-con-congruence
obs-contains-clogical : ∀{A} → (LogicalEq A) ⊆ (ObservEq [] A)
obs-contains-clogical leq = obs-contains-logical (closed-logical-imp-open leq)
-- Show that observational equivalence implies logical for closed terms.
obs-implies-closed-logical : ∀{A} {e e' : TCExp A} →
[] ⊢ e ≅ e' :: A →
e ~ e' :: A
obs-implies-closed-logical {nat} oeq = ObservEq.observe oeq ∘
obs-implies-closed-logical {A ⇒ B} {e} {e'} oeq = body
where body : (e₁ e₁' : TExp [] A) → LogicalEq A e₁ e₁' → LogicalEq B (e $ e₁) (e' $ e₁')
body e₁ e₁' leq with obs-contains-clogical leq
... | oeq' with obs-trans (obs-congruence oeq' (e e$ ∘)) (obs-congruence oeq (∘ $e e₁'))
... | oeq'' = obs-implies-closed-logical oeq''
obs-contains-logical-subst : ∀{Γ} → SubstRel LogicalEq Γ ⊆ SubstRel (ObservEq []) Γ
obs-contains-logical-subst η x = obs-contains-clogical (η x)
-- Since observational implies logical for closed terms and
-- respects substitution of observational equivalent terms,
-- logical equivalence contains observational.
logical-contains-obs : ∀{Γ} {A} → ObservEq Γ A ⊆ OLogicalEq Γ A
logical-contains-obs {Γ} {A} {e} {e'} oeq {γ} {γ'} η
with substs-respect-obs oeq (obs-contains-logical-subst η)
... | coeq = obs-implies-closed-logical coeq
-- This is sort of silly. We need these lemmas to prove that logical
-- equivalence contains definitional.
nat-val-weakening : ∀{Γ} {n : TNat} → TVal n →
Σ[ e :: TExp Γ nat ] (∀{γ : TSubst Γ []} → n ≡ ssubst γ e)
nat-val-weakening val-zero = zero , (λ {γ} → Refl)
nat-val-weakening {Γ} {suc n} (val-suc v) with nat-val-weakening {Γ} v
... | e , subst-thing = (suc e) , (λ {γ} → resp suc subst-thing)
nat-logical-equiv-val : ∀{Γ} (γ : TSubst Γ []) (e : TExp Γ nat) →
Σ[ n :: TExp Γ nat ] ((ssubst γ n ~ ssubst γ e :: nat) × TVal (ssubst γ n))
nat-logical-equiv-val {Γ} γ e with kleene-refl {ssubst γ e}
... | kleeneq n val E1 E2 with nat-val-weakening {Γ} val
... | n' , is-val = n' , ((kleeneq n val (ID.coe1 (λ x → x ~>* n) is-val eval-refl) E1) ,
ID.coe1 TVal is-val val)
-- Logical equivalence contains definitional equivalence.
logical-contains-def : ∀{Γ} {A} → DefEq Γ A ⊆ OLogicalEq Γ A
logical-contains-def {y = e} def-refl η = ological-refl e η
logical-contains-def {x = e} {y = e'} (def-sym defeq) η =
ological-sym {_} {_} {e'} {e} (logical-contains-def defeq) η
logical-contains-def {x = e} {y = e''} (def-trans {e' = e'} defeq1 defeq2) η
with logical-contains-def defeq1 | logical-contains-def defeq2
... | leq1 | leq2 = ological-trans {_} {_} {e} {e'} {e''} leq1 leq2 η
logical-contains-def (def-cong defeq C) η = ological-is-congruence (logical-contains-def defeq) C η
logical-contains-def {Γ} {A} (def-beta {e = e} {e' = e'}) {γ} {γ'} η
with step-beta {e = (ssubst (liftγ γ) e)} {e' = ssubst γ e'}
... | step with ological-refl e (extendLogicalEQΓ η (ological-refl e' η))
... | leq with subeq (compose-subst-noob γ' e') e ≡≡ subcomp γ' (singγ e') e
... | subeq-r with subcomp (singγ (ssubst γ e')) (liftγ γ) e
... | subeq-l with ID.coe2 (LogicalEq A) subeq-l subeq-r leq
... | leq' = logical-converse-evaluation-1 leq' (eval-step step)
logical-contains-def {Γ} {A} (def-rec-z {e0 = e0} {es = es}) {γ} {γ'} η with ological-refl e0 η
... | leq = logical-converse-evaluation-1 leq (eval-step step-rec-z)
-- This is super nasty. It has some code duplication when handling the congruence stuff.
-- And it also needs to deal with a bunch of nasty substitution crap.
-- The main source of nonstupid complication is that the step rule requires
-- n to be a value, and definitional equivalence does not.
logical-contains-def {Γ} {A} (def-rec-s {e = en} {e0 = e0} {es = es}) {γ} {γ'} η
with nat-logical-equiv-val γ en
... | n , num-leq , is-val with ological-refl (rec en e0 es) η
... | full-leq with ological-is-congruence {e = ssubst γ n} {e' = ssubst γ en}
(closed-logical-imp-open num-leq) (rec1 ∘ (ssubst γ e0) (ssubst (liftγ γ) es))
(emptyLogicalEqΓ {γ = emptyγ} {γ' = emptyγ})
... | eq-with-γn-and-nasty-subst with ID.coe2 (LogicalEq A) (subid _) (subid _) eq-with-γn-and-nasty-subst
... | eq-with-γn with logical-trans eq-with-γn full-leq
... | leq-subrec with ological-refl (rec (suc en) e0 es) (logicalγ-refl {x = γ})
... | full-leq-s with ological-is-congruence {e = ssubst γ n} {e' = ssubst γ en}
(closed-logical-imp-open num-leq) (rec1 (suc ∘) (ssubst γ e0) (ssubst (liftγ γ) es))
(emptyLogicalEqΓ {γ = emptyγ} {γ' = emptyγ})
... | eq-with-sγn-and-nasty-subst with ID.coe2 (LogicalEq A) (subid _) (subid _) eq-with-sγn-and-nasty-subst
... | eq-with-sγn with logical-trans eq-with-sγn full-leq-s
... | leq-subrec-2 with ological-refl es (extendLogicalEQΓ η leq-subrec)
... | leq-unrolled with subeq (compose-subst-noob γ' (rec en e0 es)) es ≡≡
subcomp γ' (singγ (rec en e0 es)) es
... | subeq-l with subcomp (singγ (ssubst γ (rec n e0 es))) (liftγ γ) es
... | subeq-r with ID.coe2 (LogicalEq A) subeq-r subeq-l leq-unrolled
... | leq with step-rec-s {e = ssubst γ n} {e₀ = ssubst γ e0} {es = ssubst (liftγ γ) es} is-val
... | step with logical-converse-evaluation-1 leq (eval-step step)
... | leq-stepped = logical-trans (logical-sym leq-subrec-2) leq-stepped
-- Obvious corollary that observational equivalence contains definitional.
obs-contains-def : ∀{Γ} {A} → DefEq Γ A ⊆ ObservEq Γ A
obs-contains-def = obs-contains-logical o logical-contains-def
-- Proving this mostly out of spite, because one formulation
-- of my theory needed this for observational equivalence,
-- and there wasn't a good way to prove it other than appealing
-- to observational equivalence coinciding with logical, which
-- was what we were trying to prove.
weakened-equiv-log : ∀{Γ} {A} {e e' : TCExp A} →
e ~ e' :: A →
Γ ⊢ weaken-closed e ~ weaken-closed e' :: A
weakened-equiv-log {Γ} {A} {e} {e'} leq {γ} {γ'} η with subren γ closed-wkγ e | subren γ' closed-wkγ e'
... | eq1 | eq2 with closed-subst (γ o closed-wkγ) e | closed-subst (γ' o closed-wkγ) e'
... | eq1' | eq2' = ID.coe2 (LogicalEq A) (symm eq1' ≡≡ symm eq1) (symm eq2' ≡≡ symm eq2) leq
weakened-equiv-obs : ∀{Γ} {A} {e e' : TCExp A} →
[] ⊢ e ≅ e' :: A →
Γ ⊢ weaken-closed e ≅ weaken-closed e' :: A
weakened-equiv-obs {Γ} {A} {e} {e'} oeq = obs-contains-logical (weakened-equiv-log {Γ} {A} {e} {e'} (obs-implies-closed-logical oeq))
-- Some more stuff about renaming.
wkren1 : ∀{Γ A} → TRen Γ (A :: Γ)
wkren1 = (λ x → S x)
weaken1 : ∀{Γ A B} → TExp Γ B → TExp (A :: Γ) B
weaken1 e = ren wkren1 e
weakening-ignores : ∀{Γ A} (e₁ : TCExp A) (γ : TSubst Γ []) →
Sub≡ (λ x₁ → ssubst (singγ e₁) (ren wkren1 (γ x₁))) γ
weakening-ignores e₁ γ x = subren (singγ e₁) wkren1 (γ x) ≡≡ subid (γ x)
-- Functional extensionality
function-ext-log : ∀{Γ A B} {e e' : TExp Γ (A ⇒ B)} →
(A :: Γ) ⊢ weaken1 e $ var Z ~ weaken1 e' $ var Z :: B →
Γ ⊢ e ~ e' :: A ⇒ B
function-ext-log {Γ} {A} {B} {e} {e'} leq {γ} {γ'} η e₁ e₁' leq'
with leq (extendLogicalEQΓ η leq')
... | leq'' with subren (subComp (singγ e₁) (liftγ γ)) wkren1 e |
subren (subComp (singγ e₁') (liftγ γ')) wkren1 e'
... | eq1' | eq2' with eq1' ≡≡ subeq (weakening-ignores e₁ γ) e |
eq2' ≡≡ subeq (weakening-ignores e₁' γ') e'
... | eq1 | eq2 = ID.coe2 (LogicalEq B) (resp (λ x → x $ e₁) eq1) (resp (λ x → x $ e₁') eq2) leq''
function-ext-obs : ∀{Γ A B} {e e' : TExp Γ (A ⇒ B)} →
(A :: Γ) ⊢ weaken1 e $ var Z ≅ weaken1 e' $ var Z :: B →
Γ ⊢ e ≅ e' :: A ⇒ B
function-ext-obs {e = e} {e' = e'} oeq = obs-contains-logical
(function-ext-log {e = e} {e' = e'} (logical-contains-obs oeq))
-- Eta, essentially
-- The important part of the proof is the def-beta and the function-ext-obs,
-- but most of the actual work is fucking around with substitutions.
function-eta-obs : ∀{Γ A B} (e : TExp Γ (A ⇒ B)) →
Γ ⊢ e ≅ (Λ (weaken1 e $ var Z)) :: A ⇒ B
function-eta-obs {Γ} {A} {B} e with
obs-sym (obs-contains-def (def-beta {e = ren (wk wkren1) (ren wkren1 e) $ var Z} {e' = var Z}))
... | beta-eq with (subren (singγ (var Z)) (wk wkren1) (weaken1 e)) ≡≡
(subren (λ x → singγ (var Z) (wk wkren1 x)) wkren1 e) ≡≡
symm (subren emptyγ wkren1 e) ≡≡
subid (weaken1 e)
... | eq2 with resp (λ x → x $ var Z) eq2
... | eq with ID.coe2 (ObservEq (A :: Γ) B) eq refl beta-eq
... | oeq = function-ext-obs oeq
obs-equiv-nat-val : (e : TNat) → Σ[ n :: TNat ] (TVal n × ([] ⊢ e ≅ n :: nat))
obs-equiv-nat-val e with ological-equiv-nat-val e
obs-equiv-nat-val e | n , val , eq = n , val , obs-contains-logical eq
-- OK, maybe we are trying this with numerals again. Argh.
t-numeral : ∀{Γ} → Nat → TExp Γ nat
t-numeral Z = zero
t-numeral (S n) = suc (t-numeral n)
numeral-val : ∀{Γ} → (n : Nat) → TVal {Γ} (t-numeral n)
numeral-val Z = val-zero
numeral-val (S n) = val-suc (numeral-val n)
val-numeral : ∀{Γ} {e : TExp Γ nat} → TVal e → Σ[ n :: Nat ] (e ≡ t-numeral n)
val-numeral val-zero = Z , Refl
val-numeral (val-suc v) with val-numeral v
... | n , eq = (S n) , (resp suc eq)
numeral-subst-dontcare : ∀{Γ Γ'} (n : Nat) (γ : TSubst Γ Γ') → ssubst γ (t-numeral n) ≡ t-numeral n
numeral-subst-dontcare Z γ = Refl
numeral-subst-dontcare (S n) γ = resp suc (numeral-subst-dontcare n γ)
--
obs-equiv-numeral : (e : TNat) → Σ[ n :: Nat ] ([] ⊢ e ≅ t-numeral n :: nat)
obs-equiv-numeral e with obs-equiv-nat-val e
obs-equiv-numeral e | en , val , oeq with val-numeral val
... | n , eq = n , (ID.coe1 (ObservEq [] nat e) eq oeq)
dropSubstRel : ∀(R : CRel) {Γ A} {γ γ' : TSubst (A :: Γ) []} →
SubstRel R (A :: Γ) γ γ' →
SubstRel R Γ (dropγ γ) (dropγ γ')
dropSubstRel R η n = η (S n)
dropLogicalEqΓ = dropSubstRel LogicalEq
-- Allow induction over nats, essentially
function-induction-log : ∀{Γ A} {e e' : TExp (nat :: Γ) A} →
((n : Nat) → Γ ⊢ ssubst (singγ (t-numeral n)) e ~
ssubst (singγ (t-numeral n)) e' :: A) →
(nat :: Γ) ⊢ e ~ e' :: A
function-induction-log {Γ} {A} {e} {e'} f {γ} {γ'} η
with η Z | obs-equiv-numeral (γ Z)
... | n-eq | n , oeq-n with f n (dropLogicalEqΓ η)
... | butt with subcomp (dropγ γ) (singγ (t-numeral n)) e | subcomp (dropγ γ') (singγ (t-numeral n)) e'
... | lol1 | lol2 with subeq (compose-subst-noob (dropγ γ) (t-numeral n)) e |
subeq (compose-subst-noob (dropγ γ') (t-numeral n)) e'
... | lol1' | lol2' with ID.coe2 (LogicalEq A) (symm lol1 ≡≡ symm lol1') (symm lol2 ≡≡ symm lol2') butt
... | wtf with ID.coe2
(λ x y → LogicalEq A
(ssubst (extendγ (dropγ γ) x) e)
(ssubst (extendγ (dropγ γ') y) e'))
(numeral-subst-dontcare n (dropγ γ)) (numeral-subst-dontcare n (dropγ γ')) wtf
... | wtf' with ological-refl e (extendLogicalEQΓ (dropLogicalEqΓ (logicalγ-refl {x = γ})) (obs-consistent oeq-n))
... | leq-e with ID.coe2 (LogicalEq A) (symm (subeq (drop-fix γ) e)) Refl leq-e
... | leq-e' with ological-refl e' (extendLogicalEQΓ (dropLogicalEqΓ (logicalγ-refl {x = γ'}))
(kleene-trans (kleene-sym n-eq) (obs-consistent oeq-n)))
... | leq-e2 with ID.coe2 (LogicalEq A) (symm (subeq (drop-fix γ') e')) Refl leq-e2
... | leq-e2' = logical-trans leq-e' (logical-trans wtf' (logical-sym leq-e2'))
function-induction-obs : ∀{Γ A} {e e' : TExp (nat :: Γ) A} →
((n : Nat) → Γ ⊢ ssubst (singγ (t-numeral n)) e ≅
ssubst (singγ (t-numeral n)) e' :: A) →
(nat :: Γ) ⊢ e ≅ e' :: A
function-induction-obs {Γ} {A} {e} {e'} f =
obs-contains-logical
(function-induction-log {Γ} {A} {e} {e'}
(λ n → logical-contains-obs (f n)))
|
namespace Reynold_operator
namespace Group.tools
open equiv
def to_equiv {G : Type u}[group G](g : G) : perm G := { to_fun := λ s, g*s,
inv_fun := λ s, g⁻¹ *s,
left_inv := begin dsimp, intros x,rw ← mul_assoc, rw inv_mul_self, rw one_mul, end,
right_inv := begin dsimp, intros x,rw ← mul_assoc, rw mul_inv_self, rw one_mul, end}
end Group.tools
open morphism
variables {G : Type u} [group G] [fintype G]{R : Type v}[comm_ring R] {M : Type w} [add_comm_group M] [module R M]
{M' : Type w'} [add_comm_group M'] [module R M']
{f : G → (M →ₗ[R] M)}
notation `Sum` := finset.sum finset.univ
constants (a: R)[hyp : a * ((fintype.card G) : R) = 1]
lemma Reynold_invariant (g : G) (h1 : G → M→ₗ[R]M') : Sum h1 = Sum ( λ z, h1(Group.tools.to_equiv g z)) :=
Sum_permutation h1 (Group.tools.to_equiv g)
def Reynold {G : Type u} [group G][fintype G](f : G → (M →ₗ[R] M')) : M→ₗ[R]M' := Sum f
notation `ℳ ` := Reynold
variables (h1 h2 : M→ₗ[R] M')
#check a • h1+h2
lemma Reynold.add (h1 h2 : G → M→ₗ[R] M') : ℳ (h1 + h2) = ℳ h1 + ℳ h2 :=
begin
sorry, end
lemma Reynold.mul (a : R )(h1 : G → M→ₗ[R] M') : ℳ ( a • h1 )= a • ℳ h1 :=
begin
sorry,
end
def mul_left (g : G) (h1 : G → M→ₗ[R]M') : G → M→ₗ[R]M' := λ s, h1 (s* g)
open technical
lemma Reynold_permutation (g : G) (h1 : G → M→ₗ[R]M') : ℳ ( λ z, h1(Group.tools.to_equiv g z)) = ℳ h1 :=
begin
unfold Reynold, erw ← Sum_permutation,
end
/--
Let `ρ and π` two representation on `M` and `M'`. Let `f : M →ₗ[R] M'` a `linear_map`.
Let `ℒ f := Σ_{g ∈ G} π g⁻¹ ∘ f ∘ ρ g`, then `ℒ f` is a morphism `ρ ⟶ π`.
Proof : `∀ t ∈ G, ρ t ∘ ℒ f ∘ π t⁻¹ := ∑ ρ t g⁻¹ ∘ f ∘ π g t = ∑ t'⁻¹ ∘ f ∘ π t'`
-/
def ℒ (ρ : group_representation G R M) (ρ' : group_representation G R M') (f : M→ₗ[R]M') := Sum (λ g : G, (ρ' g⁻¹ : M' →ₗ[R] M') * f * (ρ g : M →ₗ[R]M ))
#check @ℒ
open equiv function fintype finset
theorem pre_morphism (ρ : group_representation G R M) (ρ' : group_representation G R M') (f : M→ₗ[R]M')
(s : G) : ρ' s ∘ (ℒ ρ ρ' f)
= ℒ ρ ρ' f ∘ ρ s := begin
ext, rw function.comp_apply,dunfold ℒ at ⊢,dsimp, sorry,
end
#check ℳ
end Reynold_operator
namespace TEST
variables {G : Type u} [group G][fintype G] {R : Type v}[comm_ring R] {M : Type w} [add_comm_group M] [module R M]
{M' : Type w'} [add_comm_group M'] [module R M']
(φ : G → (M →ₗ[R]M'))
(f : M' →ₗ[R]M')
lemma hello : f * (finset.sum finset.univ φ) = finset.sum finset.univ (λ g, f * (φ g)) := begin
ext,simp,
end |
[GOAL]
F : Type u_1
Γ : outParam (Subgroup SL(2, ℤ))
k : outParam ℤ
f g : SlashInvariantForm Γ k
h : f.toFun = g.toFun
⊢ f = g
[PROOFSTEP]
cases f
[GOAL]
case mk
F : Type u_1
Γ : outParam (Subgroup SL(2, ℤ))
k : outParam ℤ
g : SlashInvariantForm Γ k
toFun✝ : ℍ → ℂ
slash_action_eq'✝ : ∀ (γ : { x // x ∈ Γ }), toFun✝ ∣[k] γ = toFun✝
h : { toFun := toFun✝, slash_action_eq' := slash_action_eq'✝ }.toFun = g.toFun
⊢ { toFun := toFun✝, slash_action_eq' := slash_action_eq'✝ } = g
[PROOFSTEP]
cases g
[GOAL]
case mk.mk
F : Type u_1
Γ : outParam (Subgroup SL(2, ℤ))
k : outParam ℤ
toFun✝¹ : ℍ → ℂ
slash_action_eq'✝¹ : ∀ (γ : { x // x ∈ Γ }), toFun✝¹ ∣[k] γ = toFun✝¹
toFun✝ : ℍ → ℂ
slash_action_eq'✝ : ∀ (γ : { x // x ∈ Γ }), toFun✝ ∣[k] γ = toFun✝
h :
{ toFun := toFun✝¹, slash_action_eq' := slash_action_eq'✝¹ }.toFun =
{ toFun := toFun✝, slash_action_eq' := slash_action_eq'✝ }.toFun
⊢ { toFun := toFun✝¹, slash_action_eq' := slash_action_eq'✝¹ } =
{ toFun := toFun✝, slash_action_eq' := slash_action_eq'✝ }
[PROOFSTEP]
congr
[GOAL]
F : Type u_1
Γ✝ : outParam (Subgroup SL(2, ℤ))
k✝ : outParam ℤ
k : ℤ
Γ : Subgroup SL(2, ℤ)
inst✝ : SlashInvariantFormClass F Γ k
f : F
γ : { x // x ∈ Γ }
z : ℍ
⊢ ↑f (γ • z) = (↑(↑↑↑γ 1 0) * ↑z + ↑(↑↑↑γ 1 1)) ^ k * ↑f z
[PROOFSTEP]
rw [← ModularForm.slash_action_eq'_iff, slash_action_eqn]
[GOAL]
F : Type u_1
Γ : outParam (Subgroup SL(2, ℤ))
k : outParam ℤ
f g : SlashInvariantForm Γ k
γ : { x // x ∈ Γ }
⊢ (↑f + ↑g) ∣[k] γ = ↑f + ↑g
[PROOFSTEP]
rw [SlashAction.add_slash, slash_action_eqn, slash_action_eqn]
[GOAL]
F : Type u_1
Γ : outParam (Subgroup SL(2, ℤ))
k : outParam ℤ
α : Type u_2
inst✝¹ : SMul α ℂ
inst✝ : IsScalarTower α ℂ ℂ
c : α
f : SlashInvariantForm Γ k
γ : { x // x ∈ Γ }
⊢ (c • ↑f) ∣[k] γ = c • ↑f
[PROOFSTEP]
rw [SlashAction.smul_slash_of_tower, slash_action_eqn]
[GOAL]
F : Type u_1
Γ : outParam (Subgroup SL(2, ℤ))
k : outParam ℤ
f : SlashInvariantForm Γ k
γ : { x // x ∈ Γ }
⊢ (-↑f) ∣[k] γ = -↑f
[PROOFSTEP]
rw [SlashAction.neg_slash, slash_action_eqn]
[GOAL]
F : Type u_1
Γ✝ : outParam (Subgroup SL(2, ℤ))
k : outParam ℤ
k₁ k₂ : ℤ
Γ : Subgroup SL(2, ℤ)
f : SlashInvariantForm Γ k₁
g : SlashInvariantForm Γ k₂
A : { x // x ∈ Γ }
⊢ (↑f * ↑g) ∣[k₁ + k₂] A = ↑f * ↑g
[PROOFSTEP]
simp_rw [ModularForm.mul_slash_subgroup, SlashInvariantFormClass.slash_action_eq]
|
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2020.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/UniqueIdGenerator.h>
#include <boost/date_time/posix_time/posix_time_types.hpp> //no i/o just types
namespace OpenMS
{
UInt64 UniqueIdGenerator::seed_ = 0;
UniqueIdGenerator* UniqueIdGenerator::instance_ = nullptr;
boost::mt19937_64* UniqueIdGenerator::rng_ = nullptr;
boost::uniform_int<UInt64>* UniqueIdGenerator::dist_ = nullptr;
UInt64 UniqueIdGenerator::getUniqueId()
{
UniqueIdGenerator& instance = getInstance_();
#ifdef _OPENMP
UInt64 val;
#pragma omp critical (OPENMS_UniqueIdGenerator_getUniqueId)
{
val = (*instance.dist_)(*instance.rng_);
}
// note: OpenMP can only work on a structured block, return needs to be outside that block
return val;
#else
return (*instance.dist_)(*instance.rng_);
#endif
}
UInt64 UniqueIdGenerator::getSeed()
{
return getInstance_().seed_;
}
void UniqueIdGenerator::setSeed(UInt64 seed)
{
// modifies static members
#ifdef _OPENMP
#pragma omp critical (OPENMS_UniqueIdGenerator_setSeed)
#endif
{
UniqueIdGenerator& instance = getInstance_();
instance.seed_ = seed;
instance.rng_->seed( instance.seed_ );
instance.dist_->reset();
}
}
UniqueIdGenerator::UniqueIdGenerator()
{
}
UniqueIdGenerator & UniqueIdGenerator::getInstance_()
{
// modifies static members
#ifdef _OPENMP
#pragma omp critical (OPENMS_UniqueIdGenerator_getInstance_)
#endif
{
if (!instance_)
{
instance_ = new UniqueIdGenerator();
instance_->init_();
}
}
return *instance_;
}
void UniqueIdGenerator::init_()
{
// modifies static members
#ifdef _OPENMP
#pragma omp critical (OPENMS_UniqueIdGenerator_init_)
#endif
{
// find a seed:
// get something with high resolution (around microseconds) -- its hard to do better on Windows --
// which has absolute system time (there is higher resolution available for the time since program startup, but
// we do not want this here since this seed usually gets initialized at the same program uptime).
// Reason for high-res: in pipelines, instances of TOPP tools can get initialized almost simultaneously (i.e., resolution in seconds is not enough),
// leading to identical random numbers (e.g. feature-IDs) in two or more distinct files.
// C++11 note: C++ build-in alternative once C++11 can be presumed: 'std::chrono::high_resolution_clock'
boost::posix_time::ptime t(boost::posix_time::microsec_clock::local_time() );
seed_ = t.time_of_day().ticks(); // independent of implementation; as opposed to nanoseconds(), which need not be available on every platform
rng_ = new boost::mt19937_64 (seed_);
dist_ = new boost::uniform_int<UInt64> (0, std::numeric_limits<UInt64>::max());
}
}
UniqueIdGenerator::~UniqueIdGenerator()
{
delete rng_;
delete dist_;
}
}
|
A set $S$ is bounded if and only if there exists a real number $a$ such that for all $x \in S$, we have $|x| \leq a$. |
Scroll down possibility with nice effect.
We recommend this version for each website related with beauty, ex. beauty parlor, surgery clinic or cosmetic shop. |
# global.R
# Code here is in scope to both ui.R and server.R
#Load required library
library(leaflet)
# Get dataset from CSV
inputstn <- read.csv("/srv/shiny-server/data/inputdata.txt", header=TRUE)
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <float.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include "common.h"
#include "graph.h"
#include "utils.h"
void graph_init(graph *g, int vertices)
{
g->num_v = vertices;
g->num_e = (int*)malloc(vertices * sizeof(int));
g->capacity = (int*)malloc(vertices * sizeof(int));
g->adj_list = (int**)malloc(vertices * sizeof(int*));
g->w_list = (double**)malloc(vertices * sizeof(double*));
int i = 0;
for (; i < vertices; ++i)
{
g->num_e[i] = 0;
g->capacity[i] = GRAPH_INIT_CAPACITY;
g->adj_list[i] = (int*)malloc(GRAPH_INIT_CAPACITY * sizeof(int));
g->w_list[i] = (double*)malloc(GRAPH_INIT_CAPACITY * sizeof(double));
}
}
ORIGIN_INLINE int graph_edges(const graph *g)
{
const int num_v = g->num_v;
int sum = 0;
int v = 0;
for (; v < num_v; ++v)
{
sum += g->num_e[v];
}
return sum;
}
ORIGIN_INLINE int graph_proper_edges(const graph *g)
{
const int num_v = g->num_v;
int sum = 0;
int v = 0;
for (; v < num_v; ++v)
{
int e = 0;
for (; e < g->num_e[v]; ++e)
{
if (g->adj_list[v][e] != v)
{
++sum;
}
}
}
return sum;
}
ORIGIN_INLINE int graph_loops(const graph *g)
{
const int num_v = g->num_v;
int sum = 0;
int v = 0;
for (; v < num_v; ++v)
{
int e = 0;
for (; e < g->num_e[v]; ++e)
{
if (g->adj_list[v][e] == v)
{
++sum;
}
}
}
return sum;
}
ORIGIN_INLINE int graph_outdegree(const graph *g, int u)
{
return g->num_e[u];
}
ORIGIN_INLINE int graph_indegree(const graph *g, int u)
{
const int num_v = g->num_v;
int sum = 0;
int v = 0;
for (; v < num_v; ++v)
{
int e = 0;
for (; e < g->num_e[v]; ++e)
{
if (g->adj_list[v][e] == u)
{
++sum;
}
}
}
return sum;
}
ORIGIN_INLINE int graph_is_balanced(const graph *g)
{
const int num_v = g->num_v;
int u = 0;
for (; u < num_v; ++u)
{
if (graph_indegree(g, u) != graph_outdegree(g, u))
{
return FALSE;
}
}
return TRUE;
}
ORIGIN_INLINE void graph_add_edge(graph *g, int u, int v, double weight)
{
if (g->num_e[u] == g->capacity[u])
{
graph_grow_lists(g, u);
}
g->adj_list[u][g->num_e[u]] = v;
g->w_list[u][g->num_e[u]] = weight;
g->num_e[u]++;
}
void graph_add_sym_edges(graph *g, int u, int v, double weight)
{
graph_add_edge(g, u, v, weight);
graph_add_edge(g, v, u, weight);
}
int graph_rmv_edge(graph *g, int u, int v)
{
const int num_e = g->num_e[u];
int e = 0;
for (; e < num_e; ++e)
{
if (g->adj_list[u][e] == v)
{
g->num_e[u]--;
int f = e;
for (; f < num_e - 1; ++f)
{
g->adj_list[u][f] = g->adj_list[u][f+1];
g->w_list[u][f] = g->w_list[u][f+1];
}
return TRUE;
}
}
return FALSE;
}
int graph_rmv_sym_edges(graph *g, int u, int v)
{
return (graph_rmv_edge(g, u, v) && graph_rmv_edge(g, v, u));
}
int graph_has_edge(graph *g, int u, int v)
{
const int num_e = g->num_e[u];
int e = 0;
for (; e < num_e; ++e)
{
if (g->adj_list[u][e] == v)
{
return TRUE;
}
}
return FALSE;
}
int graph_strongly_connected(const graph *g)
{
const int num_v = g->num_v;
int *group = (int*)malloc(num_v * sizeof(int));
int u = 0;
for (; u < num_v; ++u)
{
int v = 0;
for (; v < num_v; ++v)
{
group[v] = FALSE;
}
group[u] = TRUE;
graph_test_cc(g, group, u); // Call recursive function
for (v = 0; v < num_v; ++v)
{
if (group[v] == FALSE)
{
free(group);
return FALSE;
}
}
}
free(group);
return TRUE;
}
void graph_svg(const graph *g, double *x, double *y, double size, double offset, FILE *out)
{
fprintf(out, "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">");
const int num_v = g->num_v;
for (int i = 0; i < num_v; ++i)
{
const int num_e = g->num_e[i];
for (int j = 0; j < num_e; ++j)
{
const int e = g->adj_list[i][j];
fprintf(out, " <line x1=\"%f\" y1=\"%f\" x2=\"%f\" y2=\"%f\" style=\"stroke:rgb(0,0,0);stroke-width:2\"/>\n", offset + x[i] * size, offset + y[i] * size, offset + x[e] * size, offset + y[e] * size);
}
}
for (int i = 0; i < num_v; ++i)
{
fprintf(out, " <circle id=\"%d\" cx=\"%f\" cy=\"%f\" r=\"8\" fill=\"rgb(0,0,0)\"/>\n", i, offset + x[i] * size, offset + y[i] * size);
}
fprintf(out, "</svg>");
}
void graph_svg_abun(const graph *g, double *x, double *y, double size, double offset, double *abun, int color, FILE *out)
{
fprintf(out, "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">");
const int num_v = g->num_v;
for (int i = 0; i < num_v; ++i)
{
const int num_e = g->num_e[i];
for (int j = 0; j < num_e; ++j)
{
const int e = g->adj_list[i][j];
fprintf(out, " <line x1=\"%f\" y1=\"%f\" x2=\"%f\" y2=\"%f\" style=\"stroke:rgb(0,0,0);stroke-width:2\"/>\n", offset + x[i] * size, offset + y[i] * size, offset + x[e] * size, offset + y[e] * size);
}
}
int clr[3] = {0, 0, 0};
for (int i = 0; i < num_v; ++i)
{
clr[color] = (int)(abun[i] * 255);
fprintf(out, " <circle id=\"%d\" cx=\"%f\" cy=\"%f\" r=\"8\" stroke=\"black\" stroke-width=\"1\" fill=\"rgb(%d,%d,%d)\"/>\n", i, offset + x[i] * size, offset + y[i] * size, clr[0], clr[1], clr[2]);
}
fprintf(out, "</svg>");
}
void graph_graphml(const graph *g, FILE *out, unsigned int id)
{
const int num_v = g->num_v;
fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
fprintf(out, "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\"");
fprintf(out, " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
fprintf(out, " xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\">\n");
fprintf(out, " <graph id=\"%u\" edgedefault=\"directed\">\n", id);
for (int i = 0; i < num_v; ++i)
{
fprintf(out, " <node id=\"v%d\"/>\n", i);
}
for (int i = 0; i < num_v; ++i)
{
for (int e = 0; e < g->num_e[i]; ++e)
{
fprintf(out, " <edge source=\"v%d\" target=\"v%d\"/>\n", i, g->adj_list[i][e]);
}
}
fprintf(out, " </graph>\n");
fprintf(out, "</graphml>\n");
}
void graph_print(const graph *g, FILE *out)
{
for (int i = 0; i < g->num_v; ++i)
{
fprintf(out, "%5d -> ", i);
for (int e = 0; e < g->num_e[i]; ++e)
{
fprintf(out, "%d ", g->adj_list[i][e]);
}
fprintf(out, "\n");
}
}
void graph_free(graph *g)
{
const int num_v = g->num_v;
for (int i = 0; i < num_v; ++i)
{
free(g->adj_list[i]);
free(g->w_list[i]);
}
free(g->adj_list);
g->adj_list = NULL;
free(g->w_list);
g->w_list = NULL;
free(g->num_e);
g->num_e = NULL;
free(g->capacity);
g->capacity = NULL;
}
void graph_get_rgg(graph *g, int vertices, double r, double *x, double *y, gsl_rng *rng)
{
graph_init(g, vertices);
for (int i = 0; i < vertices; ++i)
{
x[i] = gsl_rng_uniform(rng);
y[i] = gsl_rng_uniform(rng);
}
double d;
for (int i = 0; i < vertices; ++i)
{
for (int j = 0; j < vertices; ++j)
{
const double a = x[i] - x[j];
const double b = y[i] - y[j];
d = hypot(a, b);
if (d < r)
{
graph_add_edge(g, i, j, r - d);
}
}
}
}
void graph_get_crgg(graph *g, int vertices, double r, double *x, double *y, gsl_rng *rng)
{
graph_init(g, vertices);
graph_get_rgg(g, vertices, r, x, y, rng);
while (graph_strongly_connected(g) == FALSE)
{
graph_free(g);
graph_get_rgg(g, vertices, r, x, y, rng);
}
}
void graph_get_rec_rgg(graph *g, int vertices, double width, double r, double *x, double *y, gsl_rng *rng)
{
graph_init(g, vertices);
const double length = 1.0 / width; // A = l * w so l = 1 / w
for (int i = 0; i < vertices; ++i)
{
x[i] = gsl_rng_uniform(rng) * length;
y[i] = gsl_rng_uniform(rng) * width;
}
double d;
for (int i = 0; i < vertices; ++i)
{
for (int j = 0; j < vertices; ++j)
{
const double a = x[i] - x[j];
const double b = y[i] - y[j];
d = hypot(a, b);
if (d < r)
{
graph_add_edge(g, i, j, r - d);
}
}
}
}
void graph_get_rec_crgg(graph *g, int vertices, double width, double r, double *x, double *y, gsl_rng *rng)
{
graph_init(g, vertices);
graph_get_rec_rgg(g, vertices, width, r, x, y, rng);
while (graph_strongly_connected(g) == FALSE)
{
graph_free(g);
graph_get_rec_rgg(g, vertices, width, r, x, y, rng);
}
}
void graph_get_complete(graph *g, int vertices)
{
graph_init(g, vertices);
for (int i = 0; i < vertices; ++i)
{
for (int j = 0; j < vertices; ++j)
{
graph_add_edge(g, i, j, 1.0);
}
}
}
void graph_get_circle(graph *g, int vertices)
{
graph_init(g, vertices);
graph_add_edge(g, vertices - 1, vertices - 1, 1.0);
graph_add_sym_edges(g, 0, vertices - 1, 1.0);
for (int u = 0; u < vertices - 1; ++u)
{
graph_add_edge(g, u, u, 1.0);
graph_add_sym_edges(g, u, u + 1, 1.0);
}
}
void graph_get_star(graph *g, int vertices)
{
graph_init(g, vertices);
for (int u = 0; u < vertices; ++u)
{
graph_add_edge(g, u, u, 1.0);
graph_add_sym_edges(g, u, 0, 1.0);
}
}
///////////////////////////////////////////////////////////////
// 'Private' functions
void graph_test_cc(const graph *g, int *group, int u)
{
const int num_e = g->num_e[u];
int e = 0;
for (; e < num_e; ++e)
{
const int head = g->adj_list[u][e];
if (head != u && group[head] == FALSE)
{
group[head] = TRUE;
graph_test_cc(g, group, head);
}
}
}
// Grow the edge list of some vertex v.
void graph_grow_lists(graph *g, int u)
{
g->capacity[u] <<= 1;
int *tmp_adj = (int*)malloc(g->capacity[u] * sizeof(int));
double *tmp_w = (double*)malloc(g->capacity[u] * sizeof(double));
const int num_e = g->num_e[u];
int e = 0;
for (; e < num_e; ++e)
{
tmp_adj[e] = g->adj_list[u][e];
tmp_w[e] = g->w_list[u][e];
}
int *swap_adj = g->adj_list[u];
double *swap_w = g->w_list[u];
g->adj_list[u] = tmp_adj;
g->w_list[u] = tmp_w;
free(swap_adj);
free(swap_w);
}
|
Composed by Dmitri Shostakovich (1906-1975). Op. 102. Piano duet book (requires 2 copies for performance) for piano duet (2 pianos, 4 hands). With solo part and piano reduction. F Major. Published by International Music Co.
Composed by Dmitri Shostakovich (1906-1975). Set of performance parts (includes separate pull-out violin part) for violin and piano. With solo part and piano reduction. A Minor. 76 pages. Published by Sikorski.
Unlocking the Masters Series. By Dmitri Shostakovich. AMADEUS. Softcover with CD. Size 6x9 inches. 217 pages. Published by Amadeus Press.
Two Pianos, Four Hands. By Dmitri Shostakovich. (Piano). Piano Large Works (Arranged for piano). Book only. Size 9.25x12.5 inches. 64 pages. Published by Sikorski.
Study Score. By Dmitri Shostakovich. (score). Study Score. Size 4.2x7.5 inches. 104 pages. Published by Boosey & Hawkes.
Set of performance parts. By Dmitri Shostakovich. Arranged by Mstislav Rostropovich. (Cello). String Solo. Size 9.25x12.25 inches. 68 pages. Published by Sikorski.
Composed by Dmitri Shostakovich (1906-1975). This edition: softcover. Study score. 104 pages. Sikorski #SIK6621. Published by Sikorski (HS.50499484).
Study Score. By Dmitri Shostakovich. (score). Study Score. Size 6x8.2 inches. 72 pages. Published by Sikorski.
By Dmitri Shostakovich. (Score). Study Score. Book only. Size 6x8.25 inches. 72 pages. Published by Hal Leonard.
Study Score. By Dmitri Shostakovich. (score). Study Score. Size 5.25x7.5 inches. 112 pages. Published by Boosey & Hawkes.
Set of performance parts. By Dmitri Shostakovich. Arranged by David Oistrakh. (Violin). String Solo. Size 8.25x11.75 inches. 64 pages. Published by Sikorski.
By Dmitri Shostakovich. Cello and piano. Published by International Music Co.
Study Score. Composed by Dmitri Shostakovich (1906-1975). Study Score. Score. 128 pages. Sikorski #SIK2241. Published by Sikorski (HS.50481440).
Two Pianos, Four Hands. By Dmitri Shostakovich. (Piano). Piano Large Works (Arranged for piano). Book only. Size 9x12.3 inches. 52 pages. Published by Sikorski.
Full Score. By Dmitri Shostakovich. (score). Study Score. Size 6x8.2 inches. 120 pages. Published by Sikorski. |
If $h$ is bilinear, then $h(x + y, z) = h(x, z) + h(y, z)$. |
(* -*- coding:utf-8 -*- *)
(************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
(* v * INRIA, CNRS and contributors - Copyright 1999-2018 *)
(* <O___,, * (see CREDITS file for the list of authors) *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
Require Export Utf8_core.
(* Arithmetic *)
Notation "x ≤ y" := (le x y) (at level 70, no associativity).
Notation "x ≥ y" := (ge x y) (at level 70, no associativity).
(* test *)
(*
Check ∀ x z, True -> (∃ y v, x + v ≥ y + z) ∨ x ≤ 0.
*)
(* Integer Arithmetic *)
(* TODO: this should come after ZArith
Notation "x ≤ y" := (Z.le x y) (at level 70, no associativity).
*)
|
# <center>Block 1: Linear programming</center>
# <center>Python Notebook</center>
### <center>Alfred Galichon (NYU)</center>
## <center>`math+econ+code' masterclass on matching models, optimal transport and applications</center>
<center>© 2018-2019 by Alfred Galichon. Support from NSF grant DMS-1716489 is acknowledged. James Nesbit contributed.</center>
## Linear programming: duality
### Learning objectives
* Linear programming duality
* Economic interpretation of the dual
* Numerical computation
### References
* [OTME], App. B
* Stigler (1945), The cost of subsistence. *Journal of Farm Economics*.
* Dantzig (1990), The diet problem. *Interface*.
* Complements:
* Gale (1960), *The theory of linear economic models*.
* Vohra (2011), *Mechanism Design: A Linear Programming Approach*.
### The diet problem
During World War II, engineers in US Army were wondering how to feed their personnel at minimal cost, leading to what is now called the **optimal diet problem**.
* Nutritionists have identified a number of vital nutrients (calories, protein, calcium, iron, etc.) that matter for a person's health, and have determined the minimum daily intake of each nutrient
* For each basic food (pasta, butter, bread, etc), nutritionists have characterized the intake in each of the various nutrients
* Each food has a unit cost, and the problem is to find the optimal diet = combination of foods that meet the minimal intake in each of the nutrients and achieves minimal cost
The problem was taken on by G. Stigler, who published a paper about it in 1945, giving a first heuristic solution, exhibiting a diet that costs $\$39.93$ per year in $1939$ dollars. Later (in $1947$) it was one of the first
application of G.B. Dantzig's method (the simplex algorithm), which provided the exact solution ($\$39.67$). It then took $120$ man-day to perform this operation. However today the computer will perform it for us in a
fraction of second.
However, don't try this diet at home! Dantzig did so and almost died from it...
## Motivation
### A look at the Data
Our dataset was directly taken from Stigler's article. It is a .csv file called `StiglerData1939.txt':
```python
import gurobipy as grb
import scipy.sparse as sp
import pandas as pd
import numpy as np
import os
filename = 'data_mec_optim/lp_stigler-diet/StiglerData1939.txt'
thepath = os.path.join(os.getcwd(),'..')
thedata = pd.read_csv(os.path.join(thepath ,filename), sep='\t')
thedata = thedata.dropna(how = 'all')
thedata
```
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Commodity</th>
<th>Unit</th>
<th>Price Aug.15 1939(cents)</th>
<th>Edible Weight per $1.00 (grams)</th>
<th>Calories (1000)</th>
<th>Protein(grams)</th>
<th>Calcium(grams)</th>
<th>Iron(mg.)</th>
<th>Vitamin A(1000 I.U)</th>
<th>Thiamine(mg.)</th>
<th>Riboflavin(mg.)</th>
<th>Niacin(mg.)</th>
<th>Asorbic Acid (mg.)</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>1. Wheat Flour (Enriched)</td>
<td>10 lb.</td>
<td>36.0</td>
<td>12600.0</td>
<td>44.7</td>
<td>1411.0</td>
<td>2.0</td>
<td>365.0</td>
<td>NaN</td>
<td>55.4</td>
<td>33.3</td>
<td>441.0</td>
<td>NaN</td>
</tr>
<tr>
<th>1</th>
<td>2. Macaroni</td>
<td>1 lb.</td>
<td>14.1</td>
<td>3217.0</td>
<td>11.6</td>
<td>418.0</td>
<td>0.7</td>
<td>54.0</td>
<td>NaN</td>
<td>3.2</td>
<td>1.9</td>
<td>68.0</td>
<td>NaN</td>
</tr>
<tr>
<th>2</th>
<td>3. Wheat Cereal (Enriched)</td>
<td>28 oz.</td>
<td>24.2</td>
<td>3280.0</td>
<td>11.8</td>
<td>377.0</td>
<td>14.4</td>
<td>175.0</td>
<td>NaN</td>
<td>14.4</td>
<td>8.8</td>
<td>114.0</td>
<td>NaN</td>
</tr>
<tr>
<th>3</th>
<td>4. Corn Flakes</td>
<td>8 oz.</td>
<td>7.1</td>
<td>3194.0</td>
<td>11.4</td>
<td>252.0</td>
<td>0.1</td>
<td>56.0</td>
<td>NaN</td>
<td>13.5</td>
<td>2.3</td>
<td>68.0</td>
<td>NaN</td>
</tr>
<tr>
<th>4</th>
<td>5. Corn Meal</td>
<td>1 lb.</td>
<td>4.6</td>
<td>9861.0</td>
<td>36.0</td>
<td>897.0</td>
<td>1.7</td>
<td>99.0</td>
<td>30.9</td>
<td>17.4</td>
<td>7.9</td>
<td>106.0</td>
<td>NaN</td>
</tr>
<tr>
<th>...</th>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr>
<th>73</th>
<td>74. Sugar</td>
<td>10 lb.</td>
<td>51.2</td>
<td>8773.0</td>
<td>34.9</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
</tr>
<tr>
<th>74</th>
<td>75. Corn Sirup</td>
<td>24 oz.</td>
<td>13.7</td>
<td>4966.0</td>
<td>14.7</td>
<td>NaN</td>
<td>0.5</td>
<td>74.0</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>5.0</td>
<td>NaN</td>
</tr>
<tr>
<th>75</th>
<td>76. Molasses</td>
<td>18 oz.</td>
<td>13.6</td>
<td>3752.0</td>
<td>9.0</td>
<td>NaN</td>
<td>10.3</td>
<td>244.0</td>
<td>NaN</td>
<td>1.9</td>
<td>7.5</td>
<td>146.0</td>
<td>NaN</td>
</tr>
<tr>
<th>76</th>
<td>77. Strawberry Preserves</td>
<td>1 lb.</td>
<td>20.5</td>
<td>2213.0</td>
<td>6.4</td>
<td>11.0</td>
<td>0.4</td>
<td>7.0</td>
<td>0.2</td>
<td>0.2</td>
<td>0.4</td>
<td>3.0</td>
<td>NaN</td>
</tr>
<tr>
<th>77</th>
<td>Daily allowance</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>3.0</td>
<td>70.0</td>
<td>0.8</td>
<td>12.0</td>
<td>5.0</td>
<td>1.8</td>
<td>2.7</td>
<td>18.0</td>
<td>75.0</td>
</tr>
</tbody>
</table>
<p>78 rows × 13 columns</p>
</div>
Our dataset has the nutritional content of $77$ commodities, and in the final row, the daily minimum requirement of each of these nutrients.
### The Diet problem
Problem setup:
* Assume there are nutrients $i\in\left\{ 1,...,m\right\} $ (calories, protein, calcium, iron, etc.) that matter for a person's health, in such way that the minimum daily intake of nutrient $i$ should be $d_{i}$.
* Nutrients do not come as standalone elements, but are combined into various foods. Each unit of food $j\in\left\{ 1,...,n\right\}$ yields a quantity $N_{ij}$ of nutrient $i\in\left\{1,...,m\right\}$. The dollar cost of food $j$ is $c_{j}$.
The problem is to find the diet that achieves the minimal intake of each nutrient at a cheapest price. If $q\in\mathbb{R}^{n}$ is a vector such that $q_{j}\geq0$ is the quantity of food $i$ purchased, the quantity of nutrient $i$ ingested is $\sum_{j=1}^{n}N_{ij}q_{j}$, and the cost of the diet is $\sum_{j=1}^{n}q_{j}c_{j}$. The optimal diet is therefore given by
\begin{align*}
\min_{q\geq0} & ~c^{\top}q\\
s.t.~ & Nq\geq d.\nonumber
\end{align*}
Before we tackle this problem, let's look into the linear programming problem in standard form.
## A Crash Course on Linear Programming
### Linear programming in standard form
Let $c\in\mathbb{R}^{n}$, $d\in\mathbb{R}^{m}$, $A$ be a $m\times n$ matrix, and consider the following problem
\begin{align}
V_{P} = \max_{x\in\mathbb{R}_{+}^{n}} & \, c^{\top} x \\
s.t.~Ax & \leq d
\end{align}
This problem is a *linear programming problem*, as the objective function, namely $x\rightarrow c^{\top}x$ is linear, and as the constraint, namely $x\in\mathbb{R}_{+}^{n}$ and $Ax=d$ are also linear (or more accurately, affine). This problem is called the *primal program*, for reasons to be explained soon. The set of $x$'s that satisfy the constraint are called *feasible solutions*; the set of solutions of the primal problem are called *optimal solutions*.
### Remarks
* The previous diet problem can be reformulate into this problem - why?
* A problem does not necessarly have a feasible solution (e.g. if $A=0$ and $d\neq0$), in which case (by convention) $V_{P}=-\infty$.
* The whole space may be solution (e.g. if $A=0$ and $d=0$), in which case $V_{P}=+\infty$.
### Duality
There is a powerful tool called duality which provides much insight into the analysis of the primal problem. The idea is to rewrite the problem as
\begin{align*}
V_{P}=\max_{x\in\mathbb{R}_{+}^{n}}\left\{ c^{\top}x+L_{P}\left(
d-Ax\right) \right\}
\end{align*}
where $L_{P}\left(z\right)$ is a penalty function whose value is zero if the constraint is met, that is if $z=0$, and $-\infty$ if it is not, namely if $z\neq0$. The simplest choice of such penalty function is given by $L_{P}\left( z\right) =\min_{y\in\mathbb{R}^{m}}\left\{ z^{\top}y\right\}$. One has
\begin{align*}
V_{P}=\max_{x\in\mathbb{R}_{+}^{n}}\min_{y\in\mathbb{R}^{m}}\left\{c^{\top}x+\left( d-Ax\right) ^{\top}y\right\} .
\end{align*}
However, the minimax inequality $\max_{x}\min_{y}\leq\min_{y}\max_{x}$ always holds, thus
\begin{align*}
V_{P} & \leq\min_{y\in\mathbb{R}^{m}}\max_{x\in\mathbb{R}_{+}^{n}}\left\{
c^{\top}x+\left( d-Ax\right) ^{\top}y\right\} =\min_{y\in\mathbb{R}^{m}
}\max_{x\in\mathbb{R}_{+}^{n}}\left\{ x^{\top}\left( c-A^{\top}y\right)
+d^{\top}y\right\} \\
& \leq\min_{y\in\mathbb{R}^{m}}\left\{ d^{\top}y+L_{D}\left( c-A^{\top
}y\right) \right\} =:V_{D}
\end{align*}
where $L_{D}\left(z\right) = \max_{x\in\mathbb{R}_{+}^{n}}\left\{x^{\top}z\right\}$ is equal to $0$ if $z\in\mathbb{R}_{-}^{n}$, and to $+\infty$ if not. Therefore, the value $V_{D}$ is expressed by the *dual program*
\begin{align}
V_{D}=\min_{y\in\mathbb{R}^{m}} & \, d^{\top}y, \\
s.t.~A^{\top}y & \geq c
\end{align}
and the weak duality inequality $V_{P}\leq V_{D}$ holds. It turns out that as
soon as either the primal or dual program has an optimal solution, then both
programs have an optimal solution and the values of the two programs coincide,
so the weak duality becomes an equality $V_{P}=V_{D}$ called strong duality.
Further, if $x^{\ast}\in\mathbb{R}_{+}^{n}$ is an optimal primal solution, and
$y^{\ast}\in\mathbb{R}^{m}$ is an optimal dual solution, then complementary
slackness holds, that is $x_{i}^{\ast}>0$ implies $\left( A^{\top}y^{\ast
}\right) _{i}=c_{i}$.
### Duality theorem
We summarize these results into the following statement.
---
**Theorem.** In the setting described above:
1. The weak duality inequality holds:
\begin{align}
V_{P}\leq V_{D}.
\end{align}
2. As soon as the primal or the dual program have an optimal solution, then both programs have an optimal solution, and strong duality holds:
\begin{align}
V_{P}=V_{D}.
\end{align}
3. If $x^{\ast}\in\mathbb{R}_{+}^{n}$ is an optimal primal solution, and $y^{\ast}\in\mathbb{R}^{m}$ is an optimal dual solution, then complementary slackness holds:
\begin{align}
x_{i}^{\ast}>0\text{ implies }\left( A^{\top}y^{\ast}\right) _{i}=c_{i}.
\end{align}
---
## The diet problem (revisited)
Recall the optimal diet problem
\begin{align*}
\min_{q\geq0} & \, c^{\top}q\\
s.t.~ & Nq\geq d.
\end{align*}
which has minimax formulation $\min_{q\geq0}\max_{\pi\geq0}c^{\top}q+d^{\top}\pi-q^{\top}N^{\top}\pi$, so the dual is
\begin{align*}
\max_{\pi\geq0} & \, d^{\top}\pi\\
s.t.~ & N^{\top}\pi\leq c
\end{align*}
Interpretation: imagine that there is a new firm called Nutrient Shoppe, who sells raw nutrients. Let $\pi_{i}$ be the price of nutrient $i$. The cost of the diet is $d^{\top}\pi$. Consumer purchase raw nutrients and can generate
"synthetic foods". The cost of the synthetic version of food $j$ is $\sum_{i=1}^{m}N_{ij}\pi_{i}=\left(N^{\intercal}\pi\right)_{j}$. The constraint thus means that each "synthetic food" is more affordable than
its natural counterpart.
The duality means that it is possible to price the nutrients so that the
synthetic foods are cheaper than the natural ones, in such a way that the
price of the synthetic diet equals the price of the natural diet.
Complementary slackness yields:
* $q_{j}>0$ implies $\left( N^{\intercal}\pi\right) _{j}=c_{j}$; that
is, if natural food $j$ is actually purchased, then the prices of its
synthetic and natural versions coincide
* $\pi_{i}>0$ implies $\left( Nq\right) _{i}=d_{i}$; that is, if
nutrient $i$ has a positive price, then the natural diet has the
"just right" amount.
### Solving the diet problem
To solve the primal problem we need to construct the objects $c$, $N$ and $d$. $c$ is simply a vector of ones, the size of the number of commodities. $N$ is a matrix of amount of nutrients in each commodity. $d$ is the required daily allowance of each nutrient.
```python
commodity = (thedata['Commodity'].values)[:-1]
intake = thedata.iloc[:-1, 4:].fillna(0).transpose().values
allowance = thedata.iloc[-1, 4:].fillna(0).transpose()
```
Set up the model:Set up the model: prior to version 9.0, Gurobi in Python was different from R, in the sense that we could not input a matrix of constraints: note that Gurobi in Python is different from R, in the sense that we cannot a matrix of constraints
```python
m = grb.Model('optimalDiet')
meal = m.addVars(commodity, name='meal')
m.setObjective(meal.sum(), grb.GRB.MINIMIZE)
m.addConstrs((grb.quicksum(meal[k] * intake[i, j] for j, k in enumerate(commodity)) >= allowance[i]
for i in range(intake.shape[0])), name='c')
```
Using license file C:\Users\jmcgn\gurobi.lic
Academic license - for non-commercial use only
{0: <gurobi.Constr *Awaiting Model Update*>,
1: <gurobi.Constr *Awaiting Model Update*>,
2: <gurobi.Constr *Awaiting Model Update*>,
3: <gurobi.Constr *Awaiting Model Update*>,
4: <gurobi.Constr *Awaiting Model Update*>,
5: <gurobi.Constr *Awaiting Model Update*>,
6: <gurobi.Constr *Awaiting Model Update*>,
7: <gurobi.Constr *Awaiting Model Update*>,
8: <gurobi.Constr *Awaiting Model Update*>}
```python
m.optimize()
if m.status == grb.GRB.Status.OPTIMAL:
total = 0
solution = m.getAttr('x', meal)
pi = m.getAttr('pi')
```
Gurobi Optimizer version 9.0.0 build v9.0.0rc2 (win64)
Optimize a model with 9 rows, 77 columns and 570 nonzeros
Model fingerprint: 0x7ae6b743
Coefficient statistics:
Matrix range [1e-01, 5e+03]
Objective range [1e+00, 1e+00]
Bounds range [0e+00, 0e+00]
RHS range [8e-01, 8e+01]
Presolve removed 0 rows and 47 columns
Presolve time: 0.01s
Presolved: 9 rows, 30 columns, 240 nonzeros
Iteration Objective Primal Inf. Dual Inf. Time
0 0.0000000e+00 1.384688e+01 0.000000e+00 0s
5 1.0866228e-01 0.000000e+00 0.000000e+00 0s
Solved in 5 iterations and 0.01 seconds
Optimal objective 1.086622782e-01
```python
print('***Optimal solution***')
for food in commodity:
if solution[food] > 0:
print(food, solution[food] * 365)
total += solution[food] * 365
print('Total cost (optimal) =', total)
```
***Optimal solution***
1. Wheat Flour (Enriched) 10.774457511918214
30. Liver (Beef) 0.6907834111074215
46. Cabbage 4.0932688648428766
52. Spinach 1.8277960703546998
69. Navy Beans Dried 22.27542568724304
Total cost (optimal) = 39.66173154546625
Since version 9.0, Gurobi now allows passing a matrix of constraints from Python:
```python
m2 = grb.Model('optimalDietMatrix')
x = m2.addMVar(shape=commodity.shape, name="x")
m2.setObjective(x.sum(), grb.GRB.MINIMIZE)
m2.addConstr(sp.csr_matrix(intake) @ x >= np.array(allowance), name="c")
m2.optimize()
```
Gurobi Optimizer version 9.0.0 build v9.0.0rc2 (win64)
Optimize a model with 9 rows, 77 columns and 570 nonzeros
Model fingerprint: 0x7ae6b743
Coefficient statistics:
Matrix range [1e-01, 5e+03]
Objective range [1e+00, 1e+00]
Bounds range [0e+00, 0e+00]
RHS range [8e-01, 8e+01]
Presolve removed 0 rows and 47 columns
Presolve time: 0.01s
Presolved: 9 rows, 30 columns, 240 nonzeros
Iteration Objective Primal Inf. Dual Inf. Time
0 0.0000000e+00 1.384688e+01 0.000000e+00 0s
5 1.0866228e-01 0.000000e+00 0.000000e+00 0s
Solved in 5 iterations and 0.02 seconds
Optimal objective 1.086622782e-01
As promised, we achieve the minimum cost bundle at $\$39.67$ per year in $1939$ dollars. If we compare this to Stigler's solutions which was
|Food| Annual Quantities| Annual Cost|
| ---------- | ------------------ | ------------ |
| Wheat Flour | 370 lb.| \$13.33 |
| Evaporated Milk | 57 cans | \$3.84 |
|Cabbage| 111 lb. |\$4.11|
|Spinach| 23 lb. |\$1.85|
|Dried Navy Beans| 285 lb. | \$16.80|
|Total Annual Cost| | \$39.93 |
|
Require Import Bool.
Require Import ZArith.
Require Import BinPos.
Require Import Axioms.
Require Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun.
Set Implicit Arguments.
Require Import compcert_imports. Import CompcertCommon.
Require Import Clight.
Require Import Clight_coop.
Require Import Clight_eff.
Require Import VST.concurrency.sepcomp. Import SepComp.
Require Import VST.concurrency.arguments.
Require Import VST.concurrency.jstep.
Require Import VST.concurrency.pred_lemmas.
Require Import VST.concurrency.rc_semantics.
Require Import VST.sepcomp.simulations. Import SM_simulation.
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
(** * Reach-Closed Clight *)
(** This file proves that safe Clight programs are also reach-closed. *)
Module SAFE_CLIGHT_RC. Section SafeClightRC.
Variable hf : I64Helpers.helper_functions.
Notation clsem := (CL_eff_sem1 hf).
Notation rcsem := (RC.effsem clsem).
Variable juicy_mem : Type. (* will be instantiated later to the actual [juicy_mem] *)
Variable transf : FSem.t mem juicy_mem.
Section Z.
Variable Z : Type.
Variable espec : external_specification juicy_mem external_function Z.
Variable espec_def :
forall ef x tys args z m,
ext_spec_pre espec ef x tys args z m ->
vals_def args.
Variable espec_exit :
forall v z m,
ext_spec_exit espec (Some v) z m ->
~~is_vundef v.
Variable ge : Genv.t fundef Ctypes.type.
Definition cl_state_inv (c : RC.state CL_core) (m : mem) e te :=
[/\ forall x b (ty : Ctypes.type),
PTree.get x e = Some (b,ty) ->
RC.roots ge c b
& forall x v,
PTree.get x te = Some v ->
{subset getBlocks [:: v] <= RC.roots ge c}
].
Fixpoint cl_cont_inv (c : RC.state CL_core) (k : cont) (m : mem) :=
match k with
| Kstop => True
| Kseq s k' => cl_cont_inv c k' m
| Kloop1 s1 s2 k' => cl_cont_inv c k' m
| Kloop2 s1 s2 k' => cl_cont_inv c k' m
| Kswitch k' => cl_cont_inv c k' m
| Kcall oid f e te k' => [/\ cl_state_inv c m e te & cl_cont_inv c k' m]
end.
Definition cl_core_inv (c : RC.state CL_core) (m : mem) :=
match RC.core c with
| CL_State f s k e te =>
[/\ cl_state_inv c m e te
, {subset RC.reach_set ge c m <= RC.roots ge c}
& cl_cont_inv c k m]
| CL_Callstate f args k =>
[/\ {subset getBlocks args <= RC.reach_set ge c m}
, {subset RC.reach_set ge c m <= RC.roots ge c}
& cl_cont_inv c k m]
| CL_Returnstate v k =>
[/\ {subset getBlocks [:: v] <= RC.reach_set ge c m}
& cl_cont_inv c k m]
end.
Lemma getBlocksP l b : reflect (exists ofs, List.In (Vptr b ofs) l) (b \in getBlocks l).
Proof.
case e: (b \in getBlocks l).
+ by apply: ReflectT; move: e; rewrite /in_mem /= /is_true /= getBlocks_char.
+ apply: ReflectF=> [][]ofs C.
rewrite /in_mem /= /is_true /= in e; move: C e; elim: l=> //= a l IH; case.
by move=> ->; rewrite /getBlocks /= /eq_block; case: (Coqlib.peq b b).
move=> Hin Hget; apply: IH=> //.
by move: Hget; rewrite getBlocksD; case: a=> // ? ?; rewrite orb_false_iff; case.
Qed.
Lemma sem_cast_getBlocks v v' ty ty' :
Cop.sem_cast v ty ty' = Some v' ->
{subset getBlocks [:: v'] <= getBlocks [:: v]}.
Proof.
rewrite /Cop.sem_cast.
case: (Cop.classify_cast ty ty')=> //; try solve
[ case: v=> // ?; [by case; move=> ->|by move=> ?; case; move=> ->]
| by move=> ? ?; case: v=> //; move=> ?; case=> <-
| by move=> ?; case: v=> //; move=> ?; case=> <-
| by move=> ? ?; case: v=> // ?; case: (Cop.cast_float_int _ _)=> // ?; case=> <-
| by move=> ? ?; case: v=> // ?; case: (Cop.cast_float_int _ _)=> // ?; case=> <-
| by case: v=> // ?; case=> <-
| by move=> ?; case: v=> // ?; case: (Cop.cast_float_long _ _)=> // ?; case=> <-
| by case: v=> // ?; [by case=> // <-|by move=> ?; case=> // <-]
| by move=> ? ? ? ?; case: v=> // ? ?; case: (_ && _)=> //; case=> <-
| by case=> <-].
Qed.
Lemma REACH_mono' U V (H: {subset U <= V}) m : {subset REACH m U <= REACH m V}.
Proof.
move=> b; rewrite /in_mem /= /is_true /=.
by apply: REACH_mono; apply: H.
Qed.
Lemma REACH_loadv chunk m b i b1 ofs1
(LDV: Mem.loadv chunk m (Vptr b i) = Some (Vptr b1 ofs1)) L :
b \in L -> b1 \in REACH m L.
Proof.
move=> H; eapply (REACH_cons _ _ b1 b (Integers.Int.unsigned i) ofs1);
first by apply: REACH_nil.
move: LDV; rewrite /Mem.loadv; case/Mem.load_valid_access=> H2 H3; apply: H2.
split; [omega|case: chunk H3=> /= *; omega].
move: LDV; move/Mem.load_result=> H2; move: (sym_eq H2)=> {H2}H2.
by case: (decode_val_pointer_inv _ _ _ _ H2)=> -> /=; case=> ->.
Qed.
Lemma loadv_reach_set ch (c : RC.state CL_core) m b ofs v :
Mem.loadv ch m (Vptr b ofs) = Some v ->
b \in RC.roots ge c ->
{subset getBlocks [:: v] <= RC.reach_set ge c m}.
Proof.
case: v=> // b' i'; move/REACH_loadv=> H H2 b'' Hget.
move: Hget; case/getBlocksP=> ?; case; case=> ? ?; subst.
by apply: H.
Qed.
Lemma eval_expr_reach' c m e te a v :
cl_state_inv c m e te ->
{subset RC.reach_set ge c m <= RC.roots ge c} ->
eval_expr ge e te m a v ->
{subset getBlocks [:: v] <= RC.roots ge c}.
Proof.
set (P := fun (a0 : expr) v0 =>
{subset getBlocks [:: v0] <= RC.roots ge c}).
set (P0 := fun (a0 : expr) b0 i0 =>
{subset getBlocks [:: Vptr b0 i0] <= RC.roots ge c}).
case=> H H2 Hclosed H3.
case: (eval_expr_lvalue_ind ge e te m P P0)=> //.
{ by move=> id ty v0 H5 b H6; apply: (H2 id v0 H5). }
{ move=> op a0 ty v1 v0 H4 H5 H6 b H7; elim: op H6=> /=.
+ rewrite /Cop.sem_notbool.
case: (Cop.classify_bool (typeof a0))=> //.
case: v1 H4 H5=> // i H8 H9; case=> Heq; subst v0.
move: H7; case/getBlocksP=> x; case=> //.
by rewrite /Val.of_bool; case: (Integers.Int.eq _ _).
case: v1 H4 H5=> // f H8 H9; case=> Heq; subst v0.
move: H7; case/getBlocksP=> x; case=> //.
by rewrite /Val.of_bool; case: (Floats.Float.cmp _ _ _).
case: v1 H4 H5=> // i H8 H9.
case=> Heq; subst v0.
move: H7; case/getBlocksP=> x; case=> //.
by rewrite /Val.of_bool; case: (Integers.Int.eq _ _).
move=> _; case=> Heq; subst v0.
move: H7; case/getBlocksP=> x; case=> //.
case: v1 H4 H5=> // i H8 H9; case=> Heq; subst v0.
move: H7; case/getBlocksP=> x; case=> //.
by rewrite /Val.of_bool; case: (Integers.Int64.eq _ _).
+ rewrite /Cop.sem_notint.
case: (Cop.classify_notint (typeof a0))=> // _.
case: v1 H4 H5=> // i H8 H9; case=> Heq; subst v0.
by move: H7; case/getBlocksP=> x; case.
case: v1 H4 H5=> // f H8 H9; case=> Heq; subst v0.
by move: H7; case/getBlocksP=> x; case.
+ rewrite /Cop.sem_neg.
case Hcl: (Cop.classify_neg (typeof a0))=> // [sgn||].
case Hv1: v1 H4 H5=> // [v0']; subst.
move=> H8 H9; case=> Heq; subst v0.
by move: H7; case/getBlocksP=> x; case.
case: v1 H4 H5=> // f H8 H9; case=> Heq; subst v0.
by move: H7; case/getBlocksP=> x; case.
case: v1 H4 H5=> // f H8 H9; case=> Heq; subst v0.
by move: H7; case/getBlocksP=> x; case. }
{ move=> op a1 a2 ty v1 v2 v0 H4 H5 H6 H7 H8 b H9; elim: op H6 H8=> /=.
{ rewrite /Cop.sem_add.
case: (Cop.classify_add _ _)=> //.
move=> ? ? Heval; case: v1 H4 H5=> // b0 i H4 H5; case: v2 H7 Heval=> // i0 ? ?.
case=> Heq; subst v0; move: H9; case/getBlocksP=> ?; case=> //; case=> ? ?; subst b0.
by apply: H5; apply/getBlocksP; exists i; constructor.
move=> ? ? Heval; case: v1 H4 H5=> // i H4 H5; case: v2 H7 Heval=> // ? ? H7 Heval.
case=> Heq; subst v0; apply: H7; case: (getBlocksP _ _ H9)=> ?; case; case=> Heq' _; subst.
by apply/getBlocksP; eexists; eauto; econstructor; eauto.
move=> ? ? Heval; case: v1 H4 H5=> // ? ? H4 H5; case: v2 H7 Heval=> // ? ? ?; case=> ?; subst.
apply: H5; case: (getBlocksP _ _ H9)=> ?; case; case=> <- _.
by apply/getBlocksP; eexists; eauto; econstructor; eauto.
move=> ? ? Heval; case: v1 H4 H5=> // i H4 H5; case: v2 H7 Heval=> // ? ? H7 Heval.
case=> Heq; subst v0; apply: H7; case: (getBlocksP _ _ H9)=> ?; case; case=> Heq' _; subst.
by apply/getBlocksP; eexists; eauto; econstructor; eauto.
move=> Heval; rewrite /Cop.sem_binarith.
case: (Cop.sem_cast _ _ _)=> // a'.
case: (Cop.sem_cast _ _ _)=> // a''.
case: (Cop.classify_binarith _ _)=> //.
move=> ?; case: a'=> // i; case: a''=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> ?; case: a'=> // i; case: a''=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: a'=> // i; case: a''=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //. }
{ move=> Heval; rewrite /Cop.sem_sub.
case: (Cop.classify_sub _ _)=> //.
move=> ty'.
case: v1 H4 H5=> // ? ? Heval' Hp ?; case: v2 H7 Heval=> // i Hp' Heval''; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case; case=> <- _.
by apply: Hp; apply/getBlocksP; eexists; econstructor; eauto.
move=> ty'.
case: v1 H4 H5=> // ? ? Heval' Hp; case: v2 H7 Heval=> // ? ? Hp' Heval''.
case: (eq_block _ _)=> // ?; subst.
case: (Integers.Int.eq _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> ty'.
move=> ?; case: v1 H4 H5=> // ? ? Heval' Hp; case: v2 H7 Heval=> // ? Hp' Heval''.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //; case=> ? _; subst.
by apply: Hp; apply/getBlocksP; eexists; econstructor; eauto.
rewrite /Cop.sem_binarith.
case: (Cop.sem_cast _ _ _)=> // a'.
case: (Cop.sem_cast _ _ _)=> // a''.
case: (Cop.classify_binarith _ _)=> //.
move=> ?; case: a'=> // i; case: a''=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> ?; case: a'=> // i; case: a''=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: a'=> // i; case: a''=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //. }
{ move=> Heval; rewrite /Cop.sem_mul.
rewrite /Cop.sem_binarith.
case: (Cop.sem_cast _ _ _)=> // a'.
case: (Cop.sem_cast _ _ _)=> // a''.
case: (Cop.classify_binarith _ _)=> //.
move=> ?; case: a'=> // i; case: a''=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> ?; case: a'=> // i; case: a''=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: a'=> // i; case: a''=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //. }
{ move=> Heval; rewrite /Cop.sem_div.
rewrite /Cop.sem_binarith.
case: (Cop.sem_cast _ _ _)=> // a'.
case: (Cop.sem_cast _ _ _)=> // a''.
case: (Cop.classify_binarith _ _)=> //.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //.
case: (_ || _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: (Integers.Int.eq _ _)=> //; case=> // ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //.
case: (_ || _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: (Integers.Int64.eq _ _)=> //; case=> // ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: a'=> // i; case: a''=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //. }
{ move=> Heval; rewrite /Cop.sem_mod.
rewrite /Cop.sem_binarith.
case: (Cop.sem_cast _ _ _)=> // a'.
case: (Cop.sem_cast _ _ _)=> // a''.
case: (Cop.classify_binarith _ _)=> //.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //.
case: (_ || _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: (Integers.Int.eq _ _)=> //; case=> // ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //.
case: (_ || _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: (Integers.Int64.eq _ _)=> //; case=> // ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: a'=> // i; case: a''=> // ?; case=> ?; subst. }
{ move: H9; case/getBlocksP=> ?; case=> //.
move=> ? Heval; subst; rewrite /Cop.sem_and.
rewrite /Cop.sem_binarith.
case: (Cop.sem_cast _ _ _)=> // a'.
case: (Cop.sem_cast _ _ _)=> // a''.
case: (Cop.classify_binarith _ _)=> //.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //.
case: a'=> // i; case: a''=> // ?; case: s=> //. }
{ move=> Heval; subst; rewrite /Cop.sem_or.
rewrite /Cop.sem_binarith.
case: (Cop.sem_cast _ _ _)=> // a'.
case: (Cop.sem_cast _ _ _)=> // a''.
case: (Cop.classify_binarith _ _)=> //.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move: H9; case/getBlocksP=> ?; case=> //.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move: H9; case/getBlocksP=> ?; case=> //.
case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst. }
{ move: H9; case/getBlocksP=> ?; case=> //.
move=> Heval; subst; rewrite /Cop.sem_xor.
rewrite /Cop.sem_binarith.
case: (Cop.sem_cast _ _ _)=> // a'.
case: (Cop.sem_cast _ _ _)=> // a''.
case: (Cop.classify_binarith _ _)=> //.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst.
move=> Heval; case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst. }
{ move=> Heval; subst; rewrite /Cop.sem_shl.
rewrite /Cop.sem_shift.
case: (Cop.classify_shift _ _)=> //.
move=> s; case: v1 H4 H5=> // i Heval' Hp.
case: v2 H7 Heval=> // i' Heval'' Hp'.
case: (Integers.Int.ltu _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> s; case: v1 H4 H5=> // i Heval' Hp.
case: v2 H7 Heval=> // i' Heval'' Hp'.
case: (Integers.Int64.ltu _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> s; case: v1 H4 H5=> // i Heval' Hp.
case: v2 H7 Heval=> // i' Heval'' Hp'.
case: (Integers.Int64.ltu _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> s; case: v1 H4 H5=> // i Heval' Hp.
case: v2 H7 Heval=> // i' Heval'' Hp'.
case: (Integers.Int.ltu _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //. }
{ move=> Heval; subst; rewrite /Cop.sem_shr.
rewrite /Cop.sem_shift.
case: (Cop.classify_shift _ _)=> //.
move=> s; case: v1 H4 H5=> // i Heval' Hp.
case: v2 H7 Heval=> // i' Heval'' Hp'.
case: (Integers.Int.ltu _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> s; case: v1 H4 H5=> // i Heval' Hp.
case: v2 H7 Heval=> // i' Heval'' Hp'.
case: (Integers.Int64.ltu _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> s; case: v1 H4 H5=> // i Heval' Hp.
case: v2 H7 Heval=> // i' Heval'' Hp'.
case: (Integers.Int64.ltu _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> s; case: v1 H4 H5=> // i Heval' Hp.
case: v2 H7 Heval=> // i' Heval'' Hp'.
case: (Integers.Int.ltu _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //. }
{ move=> Heval; rewrite/Cop.sem_cmp.
case: (Cop.classify_cmp _ _)=> //.
rewrite /Val.cmpu_bool.
case: v1 H4 H5=> // ? Heval' Hp.
case: v2 H7 Heval=> // ? Hp' Heval''.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
move=> Heval'''; case: (Integers.Int.eq _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> Hp'; case: v2 H7 Heval=> // ? ? ? /=.
case: (Integers.Int.eq _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> Heval'''; case: (eq_block _ _)=> // ?; subst.
case: (_ && _)=> //; case=> ?; subst.
move: H9; rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
case: (_ && _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: v2 H7 Heval=> // ? ? ?; rewrite /Val.cmpu_bool.
case: v1 H4 H5=> // ? ? ?.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> // ?; subst.
move=> ? /=; case: (Integers.Int.eq _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: v1 H4 H5=> // ? ? ?.
rewrite /Val.cmpu_bool.
case: v2 H7 Heval=> // ? ? ?.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> // ?; subst.
case: (Integers.Int.eq _ _)=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Cop.sem_binarith.
case: (Cop.sem_cast _ _ _)=> // a'.
case: (Cop.sem_cast _ _ _)=> // a''.
case: (Cop.classify_binarith _ _)=> //.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> // ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> // ?; subst.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int64.eq _ _)=> // ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int64.eq _ _)=> // ?; subst.
case: a'=> // i; case: a''=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
case: (Floats.Float.cmp _ _)=> //.
case: (Floats.Float.cmp _ _)=> //. }
{ move=> Heval; rewrite/Cop.sem_cmp.
case: (Cop.classify_cmp _ _)=> //.
rewrite /Val.cmpu_bool.
case: v1 H4 H5=> // ? Heval' Hp.
case: v2 H7 Heval=> // ? Hp' Heval''.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
move=> Heval'''; case: (Integers.Int.eq _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> Hp'; case: v2 H7 Heval=> // ? ? ? /=.
case: (Integers.Int.eq _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> Heval'''; case: (eq_block _ _)=> // ?; subst.
case: (_ && _)=> //; case=> ?; subst.
move: H9; rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
case: (_ && _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: v2 H7 Heval=> // ? ? ?; rewrite /Val.cmpu_bool.
case: v1 H4 H5=> // ? ? ?.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> // ?; subst.
move=> ? /=; case: (Integers.Int.eq _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: v1 H4 H5=> // ? ? ?.
rewrite /Val.cmpu_bool.
case: v2 H7 Heval=> // ? ? ?.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> // ?; subst.
case: (Integers.Int.eq _ _)=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Cop.sem_binarith.
case: (Cop.sem_cast _ _ _)=> // a'.
case: (Cop.sem_cast _ _ _)=> // a''.
case: (Cop.classify_binarith _ _)=> //.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> // ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> // ?; subst.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int64.eq _ _)=> // ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int64.eq _ _)=> // ?; subst.
case: a'=> // i; case: a''=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
case: (Floats.Float.cmp _ _)=> //.
case: (Floats.Float.cmp _ _)=> //. }
{ move=> Heval; rewrite/Cop.sem_cmp.
case: (Cop.classify_cmp _ _)=> //.
rewrite /Val.cmpu_bool.
case: v1 H4 H5=> // ? Heval' Hp.
case: v2 H7 Heval=> // ? Hp' Heval''.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
case: (Integers.Int.ltu _ _)=> //.
case: (Integers.Int.ltu _ _)=> //.
move=> Heval'''; case: (Integers.Int.eq _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> Hp'; case: v2 H7 Heval=> // ? ? ? /=.
case: (Integers.Int.eq _ _)=> //; case=> ?; subst.
move=> Heval'''; case: (eq_block _ _)=> // ?; subst.
move=> Hp'; case: (_ && _)=> //; case=> H9; subst.
move: H9; rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
case: (Integers.Int.ltu _ _)=> //.
case: (Integers.Int.ltu _ _)=> //.
case: (_ && _)=> //; case=> ?; subst.
case: v2 H7 Heval=> // ? ? ?; rewrite /Val.cmpu_bool.
case: v1 H4 H5=> // ? ? ?.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: (Integers.Int.ltu _ _)=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> // ?; subst.
case: v1 H4 H5=> // ? ? ?.
rewrite /Val.cmpu_bool.
case: v2 H7 Heval=> // ? ? ?.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: (Integers.Int.ltu _ _)=> //.
case: (Integers.Int.eq _ _)=> // ?; case=> ?; subst.
rewrite /Cop.sem_binarith.
case: (Cop.sem_cast _ _ _)=> // a'.
case: (Cop.sem_cast _ _ _)=> // a''.
case: (Cop.classify_binarith _ _)=> //.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: (Integers.Int.lt _ _)=> //.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.ltu _ _)=> // ?; subst.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int64.lt _ _)=> // ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int64.ltu _ _)=> // ?; subst.
case: a'=> // i; case: a''=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
case: (Floats.Float.cmp _ _)=> //.
case: (Floats.Float.cmp _ _)=> //. }
{ move=> Heval; rewrite/Cop.sem_cmp.
case: (Cop.classify_cmp _ _)=> //.
rewrite /Val.cmpu_bool.
case: v1 H4 H5=> // ? Heval' Hp.
case: v2 H7 Heval=> // ? Hp' Heval''.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
case: (Integers.Int.ltu _ _)=> //.
case: (Integers.Int.ltu _ _)=> //.
move=> Heval'''; case: (Integers.Int.eq _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> Hp'; case: v2 H7 Heval=> // ? ? ? /=.
case: (Integers.Int.eq _ _)=> //; case=> ?; subst.
move=> Heval'''; case: (eq_block _ _)=> // ?; subst.
move=> Hp'; case: (_ && _)=> //; case=> H9; subst.
move: H9; rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
case: (Integers.Int.ltu _ _)=> //.
case: (Integers.Int.ltu _ _)=> //.
case: (_ && _)=> //; case=> ?; subst.
case: v2 H7 Heval=> // ? ? ?; rewrite /Val.cmpu_bool.
case: v1 H4 H5=> // ? ? ?.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: (Integers.Int.ltu _ _)=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> // ?; subst.
case: v1 H4 H5=> // ? ? ?.
rewrite /Val.cmpu_bool.
case: v2 H7 Heval=> // ? ? ?.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: (Integers.Int.ltu _ _)=> //.
case: (Integers.Int.eq _ _)=> // ?; case=> ?; subst.
rewrite /Cop.sem_binarith.
case: (Cop.sem_cast _ _ _)=> // a'.
case: (Cop.sem_cast _ _ _)=> // a''.
case: (Cop.classify_binarith _ _)=> //.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: (Integers.Int.lt _ _)=> //.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.ltu _ _)=> // ?; subst.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int64.lt _ _)=> // ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int64.ltu _ _)=> // ?; subst.
case: a'=> // i; case: a''=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
case: (Floats.Float.cmp _ _)=> //.
case: (Floats.Float.cmp _ _)=> //. }
{ move=> Heval; rewrite/Cop.sem_cmp.
case: (Cop.classify_cmp _ _)=> //.
rewrite /Val.cmpu_bool.
case: v1 H4 H5=> // ? Heval' Hp.
case: v2 H7 Heval=> // ? Hp' Heval''.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
case: (Integers.Int.ltu _ _)=> //.
case: (Integers.Int.ltu _ _)=> //.
move=> Heval'''; case: (Integers.Int.eq _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> Hp'; case: v2 H7 Heval=> // ? ? ? /=.
case: (Integers.Int.eq _ _)=> //; case=> ?; subst.
move=> Heval'''; case: (eq_block _ _)=> // ?; subst.
move=> Hp'; case: (_ && _)=> //; case=> H9; subst.
move: H9; rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
case: (Integers.Int.ltu _ _)=> //.
case: (Integers.Int.ltu _ _)=> //.
case: (_ && _)=> //; case=> ?; subst.
case: v2 H7 Heval=> // ? ? ?; rewrite /Val.cmpu_bool.
case: v1 H4 H5=> // ? ? ?.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: (Integers.Int.ltu _ _)=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> // ?; subst.
case: v1 H4 H5=> // ? ? ?.
rewrite /Val.cmpu_bool.
case: v2 H7 Heval=> // ? ? ?.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: (Integers.Int.ltu _ _)=> //.
case: (Integers.Int.eq _ _)=> // ?; case=> ?; subst.
rewrite /Cop.sem_binarith.
case: (Cop.sem_cast _ _ _)=> // a'.
case: (Cop.sem_cast _ _ _)=> // a''.
case: (Cop.classify_binarith _ _)=> //.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: (Integers.Int.lt _ _)=> //.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.ltu _ _)=> // ?; subst.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int64.lt _ _)=> // ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int64.ltu _ _)=> // ?; subst.
case: a'=> // i; case: a''=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
case: (Floats.Float.cmp _ _)=> //.
case: (Floats.Float.cmp _ _)=> //. }
{ move=> Heval; rewrite/Cop.sem_cmp.
case: (Cop.classify_cmp _ _)=> //.
rewrite /Val.cmpu_bool.
case: v1 H4 H5=> // ? Heval' Hp.
case: v2 H7 Heval=> // ? Hp' Heval''.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
case: (Integers.Int.ltu _ _)=> //.
case: (Integers.Int.ltu _ _)=> //.
move=> Heval'''; case: (Integers.Int.eq _ _)=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
move=> Hp'; case: v2 H7 Heval=> // ? ? ? /=.
case: (Integers.Int.eq _ _)=> //; case=> ?; subst.
move=> Heval'''; case: (eq_block _ _)=> // ?; subst.
move=> Hp'; case: (_ && _)=> //; case=> H9; subst.
move: H9; rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
case: (Integers.Int.ltu _ _)=> //.
case: (Integers.Int.ltu _ _)=> //.
case: (_ && _)=> //; case=> ?; subst.
case: v2 H7 Heval=> // ? ? ?; rewrite /Val.cmpu_bool.
case: v1 H4 H5=> // ? ? ?.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: (Integers.Int.ltu _ _)=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> // ?; subst.
case: v1 H4 H5=> // ? ? ?.
rewrite /Val.cmpu_bool.
case: v2 H7 Heval=> // ? ? ?.
case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: (Integers.Int.ltu _ _)=> //.
case: (Integers.Int.eq _ _)=> // ?; case=> ?; subst.
rewrite /Cop.sem_binarith.
case: (Cop.sem_cast _ _ _)=> // a'.
case: (Cop.sem_cast _ _ _)=> // a''.
case: (Cop.classify_binarith _ _)=> //.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
case: (Integers.Int.lt _ _)=> //.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.ltu _ _)=> // ?; subst.
move=> s; case: a'=> // i; case: a''=> // ?; case: s=> //; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int64.lt _ _)=> // ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int64.ltu _ _)=> // ?; subst.
case: a'=> // i; case: a''=> // ?; case=> ?; subst.
move: H9; case/getBlocksP=> ?; case=> //.
rewrite /Val.of_bool; case: (Integers.Int.eq _ _)=> //.
case: (Floats.Float.cmp _ _)=> //.
case: (Floats.Float.cmp _ _)=> //. }
}
{ move=> a0 ty v1 v0 H4 H5 H6 b H7; apply: H5.
by apply: (sem_cast_getBlocks H6 H7). }
{ move=> a0 loc ofs v0 H4 H5 H6 b H7.
case: {v0} H6 H7.
+ move=> ch v1 H8 H9 H10.
have H11: {subset getBlocks [:: v1] <= RC.reach_set ge c m}.
{ have H12: loc \in getBlocks [:: Vptr loc ofs].
{ by apply/getBlocksP; exists ofs; constructor. }
move: {H12}(H5 _ H12)=> H12 b' Hget.
by apply: (loadv_reach_set H9)=> //; apply: REACH_nil. }
by apply: Hclosed; apply: H11; apply: H10.
+ move=> H6; case/getBlocksP=> ofs'; case=> //; case=> <- _.
by apply: H5; apply/getBlocksP; exists ofs; constructor.
+ move=> H6; case/getBlocksP=> ofs'; case=> //; case=> <- _.
by apply: H5; apply/getBlocksP; exists ofs; constructor.
}
{ move=> id l ty H4 b; case/getBlocksP=> ofs; case=> //; case=> <- _.
by apply: (H _ _ _ H4). }
{ move=> id l ty H4 H5 H6 b; case/getBlocksP=> ofs; case=> //; case=> <- _.
by apply/orP; left; apply: (find_symbol_isGlobal _ _ _ H5). }
{ by move=> H4 H5 b H7; apply: (H4 _ _ H3). }
Qed.
Lemma eval_lvalue_reach c m e te a b ofs :
cl_state_inv c m e te ->
{subset RC.reach_set ge c m <= RC.roots ge c} ->
eval_lvalue ge e te m a b ofs ->
{subset getBlocks [:: Vptr b ofs] <= RC.roots ge c}.
Proof.
move=> H Hclosed H2 b'; case/getBlocksP=> ofs'; case=> //; case=> <- _; case: H2=> //.
{ case: H=> H ? ? ? ? ?; apply: H. eassumption. }
{ move=> id l ty H5 H6 H7.
apply/orP; left.
by apply: (find_symbol_isGlobal _ _ _ H6). }
{ move=> a0 ty l ofs0; move/(eval_expr_reach' H).
move/(_ Hclosed l)=> X; apply: X; apply/getBlocksP.
by exists ofs0; constructor. }
{ move=> a0 i ty l ofs0 id fList att delta; move/(eval_expr_reach' H).
move/(_ Hclosed l)=> H2 ? ?; apply: H2; apply/getBlocksP.
by exists ofs0; constructor. }
{ move=> a0 i ty l ofs0 id fList att; move/(eval_expr_reach' H).
move/(_ Hclosed l)=> H2 ?; apply: H2; apply/getBlocksP.
by exists ofs0; constructor. }
Qed.
Lemma eval_exprlist_reach' c m e te aa tys vv :
cl_state_inv c m e te ->
{subset RC.reach_set ge c m <= RC.roots ge c} ->
eval_exprlist ge e te m aa tys vv ->
{subset getBlocks vv <= RC.roots ge c}.
Proof.
move=> H Hclosed; elim=> // a bl ty tyl v1 v2 vl H2 H3 H4 H5.
move=> b; case/getBlocksP=> ofs; case.
+ move=> Heq; subst v2.
apply: (eval_expr_reach' H Hclosed H2).
apply: (sem_cast_getBlocks H3).
by apply/getBlocksP; exists ofs; constructor.
+ move=> H6; apply: H5; clear -H6.
elim: vl H6=> // a vl' H7; case.
by move=> Heq; subst a; apply/getBlocksP; exists ofs; constructor.
by move=> H8; apply/getBlocksP; exists ofs; right.
Qed.
Lemma freelist_effect_reach' (c : RC.state CL_core) m L b ofs :
(forall b z1 z2, List.In (b,z1,z2) L -> b \in RC.roots ge c) ->
FreelistEffect m L b ofs ->
RC.reach_set ge c m b.
Proof.
elim: L c m b ofs=> //; case; case=> a q r l' IH c m b ofs /= H; case/orP.
by apply: IH=> // x y z H2; apply: (H x y z); right.
rewrite /FreeEffect.
case Hval: (valid_block_dec _ _)=> //.
case: (eq_block _ _)=> // Heq; subst.
by case/andP; case/andP=> _ _ _; apply: REACH_nil; apply: (H a q r)=> //; left.
Qed.
Lemma freelist_effect_reach b ofs f k e te locs m :
let: c := {|
RC.core := CL_State f (Sreturn None) k e te;
RC.locs := locs |} in
FreelistEffect m (blocks_of_env e) b ofs ->
cl_state_inv c m e te ->
{subset RC.reach_set ge c m <= RC.roots ge c} ->
RC.reach_set ge c m b.
Proof.
move=> Hfree Hs Hsub.
apply: (freelist_effect_reach' (L:=blocks_of_env e)(b:=b)(ofs:=ofs))=> //.
move=> b' z1 z2; rewrite /blocks_of_env /PTree.elements List.in_map_iff.
case=> [[x [y z]]] []; subst; case=> ? ? ?; subst.
move=> Hl; case: (PTree.xelements_complete e _ _ _ _ Hl)=> //.
by rewrite -PTree.get_xget_h; case: Hs=> He Hte; move/(He _).
Qed.
Lemma builtin_effects_reach (c : RC.state CL_core) ef vargs m b ofs :
BuiltinEffects.BuiltinEffect ge ef vargs m b ofs ->
REACH m (getBlocks vargs) b.
Proof.
rewrite /BuiltinEffects.BuiltinEffect; case: ef=> //.
{ rewrite /BuiltinEffects.free_Effect.
elim: vargs m b ofs=> // a l IH m b ofs; case: a=> // b' i.
case: l IH=> // _.
case Hload: (Mem.load _ _ _ _)=> // [v].
case: v Hload=> // i' Hload; case/andP; case/andP; case/andP=> X Y W U.
move: X; rewrite /eq_block; case: (Coqlib.peq b b')=> // Heq _; subst b'.
by apply: REACH_nil; apply/getBlocksP; exists i; constructor. }
{ move=> sz z; rewrite /BuiltinEffects.memcpy_Effect.
elim: vargs m b ofs=> // a l IH m b ofs; case: a=> // b' i.
case: l IH=> // v l IH; case: v IH=> // b'' i'' IH.
case: l IH=> // IH.
case/andP; case/andP; case/andP; case: (eq_block b b')=> // Heq; subst b'.
by move=> _ _ _ _; apply: REACH_nil; apply/getBlocksP; exists i; constructor. }
Qed.
Lemma eval_expr_reach c m a v :
cl_core_inv c m ->
match RC.core c with
| CL_State f s k e te =>
eval_expr ge e te m a v ->
{subset getBlocks [:: v] <= RC.roots ge c}
| _ => True
end.
Proof.
rewrite /cl_core_inv; case: (RC.core c)=> //.
by move=> f s k e te []H U V W; move: H U W; apply: eval_expr_reach'.
Qed.
Lemma external_call_reach l (ef : external_function) vargs m t v m'
(Hgbl: {subset isGlobalBlock ge <= l}) :
~BuiltinEffects.observableEF hf ef ->
external_call ef ge vargs m t v m' ->
{subset getBlocks vargs <= REACH m l} ->
{subset getBlocks [:: v] <= [predU REACH m l & freshloc m m']}.
Proof.
rewrite /BuiltinEffects.observableEF; case: ef=> //.
{ move=> nm sg H.
have Hh: (I64Helpers.is_I64_helper hf nm sg).
{ by case: (I64Helpers.is_I64_helper_dec hf nm sg). }
move {H}; move: Hh=> /= H H2; inversion H2; subst; move {H2}.
case: H args res H0 H1=> /=.
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd). }
{ move=> nm sg H.
have Hh: (I64Helpers.is_I64_helper hf nm sg).
{ by case: (I64Helpers.is_I64_helper_dec hf nm sg). }
move {H}; move: Hh=> /= H H2; inversion H2; subst; move {H2}.
case: H args res H0 H1=> /=.
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd).
+ rewrite /proj_sig_res /= => ? ? ?; case=> //.
move=> ? ? ? Hfnd _ b'; move/getBlocksP; case=> ?; case=> //; case=> <- _.
apply/orP; left; apply: REACH_nil.
by apply: Hgbl; apply: (find_symbol_isGlobal _ _ _ Hfnd). }
{ move=> _ /=; case=> n m0 m0' b m'' Ha Hs.
move: (freshloc_alloc _ _ _ _ _ Ha)=> Ha'.
move: (store_freshloc _ _ _ _ _ _ Hs)=> Hs'.
have Hf: freshloc m0 m'' = fun b' => Coqlib.proj_sumbool (eq_block b' b).
{ extensionality b'.
move: Ha' Hs'; rewrite -(freshloc_trans m0 m0' m'' b').
by move=> -> ->; rewrite orbC.
by apply: (alloc_forward _ _ _ _ _ Ha).
by apply: (store_forward _ _ _ _ _ _ Hs). }
rewrite Hf.
move=> Hsub b'; move/getBlocksP; case=> ofs; case=> //; case=> <- _.
rewrite in_predU; apply/orP; right; rewrite /in_mem /=.
by case: (eq_block b b). }
{ move=> _ /=; case=> b lo sz m0 m0' Hl H2 Hf Hsub.
rewrite (freshloc_free _ _ _ _ _ Hf).
by move=> b'; move/getBlocksP; case=> ofs; case. }
{ by move=> sz al _; case. }
Qed.
Lemma cont_inv_call_cont c k m :
cl_cont_inv c k m ->
cl_cont_inv c (call_cont k) m.
Proof. by elim: k. Qed.
Scheme statement_ind := Induction for statement Sort Prop
with labeled_statements_ind := Induction for labeled_statements Sort Prop.
Lemma cont_inv_find_label' c lbl s k s' k' m :
cl_cont_inv c k m ->
find_label lbl s k = Some (s', k') ->
cl_cont_inv c k' m.
Proof.
set (P := fun s : statement =>
forall k m,
cl_cont_inv c k m ->
find_label lbl s k = Some (s', k') ->
cl_cont_inv c k' m).
set (P0 := fix F (ls : labeled_statements) :=
match ls with
| LSdefault s => P s
| LScase i s ls => P s /\ F ls
end).
apply: (@statement_ind P P0)=> //.
+ move=> s0 Hp0 s1 Hp1 k0 m0 Inv /=.
case Hf: (find_label lbl s0 (Kseq s1 k0))=> [[x y]|].
by case=> ? ?; subst; apply: (Hp0 _ _ _ Hf).
by apply/Hp1.
+ move=> e s0 Hp0 s1 Hp1 k'' s'' Inv /=.
case Hf: (find_label lbl s0 k'')=> [[x y]|].
by case=> ? ?; subst; apply: (Hp0 _ _ _ Hf).
by apply/Hp1.
+ move=> s0 Hp0 s1 Hp1 k'' s'' Inv /=.
case Hf: (find_label lbl s0 (Kloop1 s0 s1 k''))=> [[x y]|].
by case=> ? ?; subst; apply: (Hp0 _ _ _ Hf).
by apply/Hp1.
+ move=> e l Hp k'' m'' Inv; elim: l Hp k'' m'' Inv=> /=.
by move=> s0 Hp0 k'' m'' Inv /=; apply/(Hp0 _ m'').
move=> i s0 l IH []H H2 k'' m'' Inv.
case Hf: (find_label _ _ _)=> // [[? ?]|].
by case=> ? ?; subst; apply: (H _ _ _ Hf).
by apply: IH.
+ move=> l s0 H k'' m'' Inv /=.
case Hid: (ident_eq lbl l)=> // [v|].
by case=> ? ?; subst s0 k''.
by move=> Hf; apply: (H _ _ Inv).
Qed.
Lemma cont_inv_find_label c lbl s k s' k' m :
cl_cont_inv c k m ->
find_label lbl s (call_cont k) = Some (s', k') ->
cl_cont_inv c k' m.
Proof.
by move=> H H2; apply: (cont_inv_find_label' (cont_inv_call_cont H) H2).
Qed.
Lemma state_inv_freshlocs c0 c' m m' locs e te :
let: c := {|RC.core := c0;
RC.locs := locs |} in
cl_state_inv c m e te ->
cl_state_inv {|
RC.core := c';
RC.locs := REACH m' (fun b : block =>
freshloc m m' b ||
RC.reach_set ge c m b)|} m' e te.
Proof.
+ rewrite /cl_state_inv; case=> He Hte; split.
move=> x b ty H; apply/orP; right.
by apply: REACH_nil; apply/orP; right; apply: REACH_nil; apply: (He _ _ _ H).
move=> x v H b H2; apply/orP; right; apply: REACH_nil.
by apply/orP; right; apply: REACH_nil; apply: (Hte _ _ H _ H2).
Qed.
Lemma cont_inv_freshlocs c0 c' k m m' locs :
let: c := {|RC.core := c0;
RC.locs := locs |} in
cl_cont_inv c k m ->
cl_cont_inv
{|RC.core := c';
RC.locs := REACH m' (fun b : block =>
freshloc m m' b ||
RC.reach_set ge c m b)|} k m'.
Proof.
elim: k=> //= _ _ e te k' H []H2 H3; split=> //.
+ by apply: state_inv_freshlocs.
+ by apply: H.
Qed.
Lemma cont_inv_mem c k m m' :
cl_cont_inv c k m ->
cl_cont_inv c k m'.
Proof.
elim: k m m'=> //= _ _ e te k IH m m' []H H2; split=> //.
by apply: (IH _ _ H2).
Qed.
Lemma cont_inv_ext1 c c' locs k m :
cl_cont_inv {| RC.core := c; RC.locs := locs |} k m ->
cl_cont_inv {| RC.core := c'; RC.locs := locs |} k m.
Proof.
elim: k=> // ? ? ? ? ? IH /= [] ? ?; split=> //.
by apply: IH.
Qed.
Lemma cont_inv_retv c k v m :
cl_cont_inv c k m ->
cl_cont_inv
{|
RC.core := CL_Returnstate v k;
RC.locs := [predU getBlocks [:: v] & RC.locs c] |} k m.
Proof.
elim: k=> //=.
by move=> s k IH H; move: (IH H); apply: cont_inv_ext1.
by move=> s s' k IH H; move: (IH H); apply: cont_inv_ext1.
by move=> s s' k IH H; move: (IH H); apply: cont_inv_ext1.
by move=> k IH H; move: (IH H); apply: cont_inv_ext1.
move=> oid f e te k IH []H H2; split=> //.
case: H=> He Hte; split.
move=> x b ty H; case: (orP (He _ _ _ H))=> X; apply/orP; first by left.
by right; apply/orP; right.
move=> x v0 H b Hget; case: (orP (Hte _ _ H _ Hget))=> X; apply/orP.
by left.
by right; apply/orP; right.
by move: (IH H2); apply: cont_inv_ext1.
Qed.
Lemma core_inv_freshlocs locs m m' f s k s' e te :
let: c := {| RC.core := CL_State f s k e te; RC.locs := locs |} in
let: locs' := REACH m' (fun b : block => freshloc m m' b || RC.reach_set ge c m b) in
cl_core_inv c m ->
cl_core_inv {| RC.core := CL_State f s' k e te; RC.locs := locs' |} m'.
Proof.
rewrite /cl_core_inv /cl_state_inv /RC.roots /=.
case=> [][]He Hte Hsub; split=> //=.
split.
{ move=> x b ty H7.
move: (He _ _ _ H7); case/orP; first by move=> ->.
move=> X; apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply: REACH_nil; apply/orP; right. }
{ move=> x v0 H7; move: (Hte _ _ H7)=> H8 b H9; move: (H8 b H9).
rewrite /RC.reach_set /RC.roots /= => H10.
by apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil. }
{ move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by apply: REACH_is_closed. }
{ by move: p; apply cont_inv_freshlocs. }
Qed.
Lemma create_undef_temps_undef l x v :
(create_undef_temps l) ! x = Some v -> v = Vundef.
Proof.
elim: l=> //=; first by rewrite PTree.gempty.
case=> a ? l IH; case: (ident_eq a x).
{ by move=> ?; subst a; rewrite PTree.gss; case. }
{ by move=> Hneq; rewrite PTree.gso=> // ?; subst. }
Qed.
(*TODO: move elsewhere*)
Lemma alloc_variables_valid0 vars E m e m1 b :
alloc_variables E m vars e m1 ->
Mem.valid_block m b ->
Mem.valid_block m1 b.
Proof.
elim: vars E m m1.
by move=> E m m1; inversion 1; subst.
case=> b' t' l IH E m m1; inversion 1; subst=> H2.
apply: (IH (PTree.set b' (b1,t') E) m2)=> //.
by apply: (Mem.valid_block_alloc _ _ _ _ _ H7).
Qed.
Lemma bind_parameters_valid0 vars E m vs m1 b :
bind_parameters E m vars vs m1 ->
Mem.valid_block m b ->
Mem.valid_block m1 b.
Proof.
elim: vars vs E m m1.
by move=> vs E m m1; inversion 1; subst.
case=> b' t' l IH E m m1; inversion 1; subst=> H2.
move: H; inversion 1; subst.
apply: (IH vl m m3)=> //.
by move: (assign_loc_forward _ _ _ _ _ _ H7); case/(_ _ H2).
Qed.
Lemma alloc_variables_freshblocks: forall vars E m e m1
(AL: alloc_variables E m vars e m1)
id b t (Hid: e!id = Some (b,t)),
E!id = Some (b,t) \/ (~Mem.valid_block m b /\ Mem.valid_block m1 b).
Proof. intros vars.
induction vars; simpl; intros; inversion AL; subst; simpl in *.
left; trivial.
destruct (IHvars _ _ _ _ H6 _ _ _ Hid); clear IHvars.
rewrite PTree.gsspec in H.
destruct (Coqlib.peq id id0); subst.
inversion H; subst. right.
split.
eapply Mem.fresh_block_alloc; eassumption.
apply Mem.valid_new_block in H3.
eapply alloc_variables_valid0; eauto.
left; trivial.
right.
destruct H.
split; auto.
intros N; elim H; clear H.
eapply Mem.valid_block_alloc; eassumption.
Qed.
(*end move*)
Lemma function_entry1_state_inv (c0 : RC.state CL_core) c1 f vargs m e te m' locs :
let: c := {| RC.core := c0;
RC.locs := locs |} in
let: c' := {| RC.core := c1;
RC.locs := REACH m' (fun b : block =>
freshloc m m' b ||
RC.reach_set ge c m b)|} in
{subset getBlocks vargs <= RC.reach_set ge c m} ->
function_entry1 f vargs m e te m' ->
cl_state_inv c' m' e te.
Proof.
move=> Hsub; case=> m1 Hno Halloc Hbind ->; split.
{ move=> x b ty He; rewrite /RC.roots /=; apply/orP; right.
case: (alloc_variables_freshblocks Halloc He).
by rewrite PTree.gempty.
move=> Hvalid; apply: REACH_nil; apply/orP; left; apply/andP; split.
case: Hvalid=> _; move/bind_parameters_valid0; move/(_ _ _ _ _ Hbind).
by case: (valid_block_dec m' b).
by case: Hvalid=> Hvalid ?; move: Hvalid; case: (valid_block_dec m b). }
{ move=> x v Hundef b; case/getBlocksP=> ofs; case=> // ?; subst v.
by move: (create_undef_temps_undef Hundef); discriminate. }
Qed.
Notation E := (@FSem.E _ _ transf).
Notation F := (@FSem.F _ _ transf _ _).
Lemma rc_step c m c' m' :
cl_core_inv c (E m) ->
corestep (F clsem) ge (RC.core c) m c' m' ->
let: c'' := RC.mk c' (REACH (E m') (fun b => freshloc (E m) (E m') b
|| RC.reach_set ge c (E m) b))
in [/\ corestep (F rcsem) ge c m c'' m' & cl_core_inv c'' (E m')].
Proof.
move=> Inv step.
rewrite FSem.step in step; case: step=> step Hprop.
move: step Inv.
remember (FSem.E mem juicy_mem transf m') as jm'.
remember (FSem.E mem juicy_mem transf m) as jm.
move=> step.
move: step Heqjm Heqjm'.
case: c=> /= core locs; case.
{ move=> f a1 a2 k e le m0 loc ofs v2 v m0' H H2 H3 H4 Hmeq Hmeq' Inv.
set (c'' := Clight_coop.CL_State f Clight.Sskip k e le).
set (c := {|
RC.core := CL_State f (Sassign a1 a2) k e le;
RC.locs := locs |}).
set (locs'' := REACH m0' (fun b : block =>
freshloc m0 m0' b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //=.
exists (assign_loc_Effect (Clight.typeof a1) loc ofs); split.
by rewrite -Hmeq -Hmeq' /=; econstructor; eauto.
split=> //.
{ move=> b ofs'; rewrite /assign_loc_Effect.
case Hac: (Ctypes.access_mode _)=> // [ch|].
+ case/andP; case/andP=> Heq _ _.
have Heq': loc = b by rewrite /eq_block in Heq; case: (Coqlib.peq loc b) Heq.
subst loc; move {Heq}; rewrite /cl_core_inv /= in Inv.
case: Inv=> Inv Inv2 Inv3; apply: REACH_nil.
by apply: (eval_lvalue_reach Inv Inv2 H); apply/getBlocksP; exists ofs; constructor.
+ case/andP; case/andP=> Heq _ _.
have Heq': loc = b by rewrite /eq_block in Heq; case: (Coqlib.peq b loc) Heq.
subst loc; move {Heq}; rewrite /cl_core_inv /= in Inv.
case: Inv=> Inv Inv2 Inv3; apply: REACH_nil.
by apply: (eval_lvalue_reach Inv Inv2 H); apply/getBlocksP; exists ofs; constructor. }
{ by rewrite -Hmeq -Hmeq'. }
{ by apply: core_inv_freshlocs. } }
{ move=> f id a k e te m0 v H Hmeq Hmeq' Inv.
set (c'' := CL_State f Sskip k e (PTree.set id v te)).
set (c := {|
RC.core := CL_State f (Sset id a) k e te;
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //=.
exists EmptyEffect; split;
first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
by rewrite -Hmeq -Hmeq' /=; econstructor; eauto.
(*reestablish invariant*)
move: (Inv); rewrite /cl_core_inv /cl_state_inv /RC.roots /=.
case; case=> He Hte Hsub Hk; split=> //=.
split.
{ rewrite /locs''=> x b ty H7.
move: (He _ _ _ H7); case/orP; first by move=> ->.
move=> X; apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply: REACH_nil; apply/orP; right. }
{ move=> x v0 H7 b H8; case Heq: (ident_eq x id).
+ subst x; rewrite PTree.gss in H7; case: H7=> Heq'; subst v0.
move: (eval_expr_reach _ _ Inv H); move/(_ b H8).
rewrite /locs'' /RC.reach_set /RC.roots /= => H10.
by apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil.
+ rewrite PTree.gso in H7=> //; move: (Hte _ _ H7); move/(_ b H8).
rewrite /locs'' /RC.reach_set /RC.roots /= => H10.
by apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil. }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
rewrite Hmeq'.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by rewrite Hmeq'; apply: REACH_is_closed. }
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f optid a a1 k e te m0 tyargs tyres vf vargs fd H H2 H3 H4 H5 Hmeq Hmeq' Inv.
set (c'' := CL_Callstate fd vargs (Kcall optid f e te k)).
set (c := {|
RC.core := CL_State f (Scall optid a a1) k e te;
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split;
first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
by rewrite -Hmeq -Hmeq' /=; econstructor; eauto.
(*reestablish invariant*)
case: Inv=> Inv Hsub Hk.
move: (Inv); rewrite /cl_core_inv /cl_state_inv /RC.roots /=.
case=> He Hte //; split.
move=> b H7; move: (eval_exprlist_reach' Inv Hsub H3).
move/(_ b H7); rewrite /locs'' /RC.reach_set /RC.roots /= => H10.
by apply: REACH_nil; apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil.
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
rewrite Hmeq'.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by rewrite Hmeq'; apply: REACH_is_closed. }
split; last by move: Hk; apply: cont_inv_freshlocs.
by move: Inv; apply: state_inv_freshlocs. }
{ (*builtins*)
move=> f optid ef tyargs a1 k e te m0 vargs t vres m0' H2 H3 H4 Hmeq Hmeq' Inv.
set (c'' := CL_State f Sskip k e (set_opttemp optid vres te)).
set (c := {|
RC.core := CL_State f (Sbuiltin optid ef tyargs a1) k e te;
RC.locs := locs |}).
set (locs'' := REACH m0' (fun b : block =>
freshloc m0 m0' b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists (BuiltinEffects.BuiltinEffect ge ef vargs m0); split;
first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //.
move=> b ofs; move/(builtin_effects_reach c)=> Hreach.
case: Inv=> Hs Hsub Hk; move: (eval_exprlist_reach' Hs Hsub H2)=> H7.
by move: Hreach; rewrite Hmeq; apply: REACH_mono'.
by rewrite -Hmeq -Hmeq'.
(*reestablish invariant*)
case: Inv=> Inv Hsub Hk.
move: (Inv); rewrite /cl_core_inv /cl_state_inv /RC.roots /=.
case=> He Hte; split=> //=.
split.
{ rewrite /locs''=> x b ty H7.
move: (He _ _ _ H7); case/orP; first by move=> ->.
move=> X; apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply: REACH_nil; apply/orP; right. }
{ rewrite /c'' /locs'' /c /set_opttemp /=; move {locs'' c c''}.
move {Hk}; case: optid Inv Hte Hsub.
{ move=> a Inv Hte Hsub x v.
move: (eval_exprlist_reach' Inv Hsub H2)=> H7.
have X: {subset getBlocks vargs
<= RC.reach_set ge
{|
RC.core := CL_State f (Sbuiltin (Some a) ef tyargs a1) k e te;
RC.locs := locs |} m0}.
{ by move=> b Hget; move: (H7 _ Hget)=> H7'; apply: REACH_nil. }
have Y: {subset isGlobalBlock ge
<= RC.roots ge
{|
RC.core := CL_State f (Sbuiltin (Some a) ef tyargs a1) k e te;
RC.locs := locs |}}.
{ by move=> b isGbl; apply/orP; left. }
move: (external_call_reach Y H4 H3 X)=> H8.
case: (ident_eq a x)=> Heq H9.
+ subst x; rewrite PTree.gss in H9; case: H9=> Heq'; subst vres.
move=> b H9; move: (H8 _ H9); rewrite in_predU; case/orP=> H10.
by apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply/orP; right; apply: REACH_nil; apply/orP; left.
+ rewrite PTree.gso in H9.
move=> b H10; move: (Hte _ _ H9); move/(_ b H10); case/orP=> H.
by apply/orP; left.
apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil.
by apply/orP; right.
by move=> C; apply: Heq; rewrite C. }
{ move=> Inv Hte Hsub x v H7 b H8; move: (Hte _ _ H7); move/(_ b H8); case/orP=> H.
by apply/orP; left.
apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil.
by apply/orP; right. } }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
rewrite Hmeq'.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by rewrite Hmeq'; apply: REACH_is_closed. }
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f s1 s2 k e te m0 Hmeq Hmeq' Inv.
set (c'' := CL_State f s1 (Kseq s2 k) e te).
set (c := {|
RC.core := CL_State f (Ssequence s1 s2) k e te;
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split;
first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //.
by rewrite -Hmeq -Hmeq'.
case: Inv=> Inv Hsub Hk.
move: (Inv); rewrite /cl_core_inv /cl_state_inv /RC.roots /=.
case=> He Hte; split=> //=.
split.
{ rewrite /locs''=> x b ty H7.
move: (He _ _ _ H7); case/orP; first by move=> ->.
move=> X; apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply: REACH_nil; apply/orP; right. }
{ move=> x v0 H7; move: (Hte _ _ H7)=> H8 b H9; move: (H8 b H9).
rewrite /locs'' /RC.reach_set /RC.roots /= => H10.
by apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil. }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
rewrite Hmeq'.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by rewrite Hmeq'; apply: REACH_is_closed. }
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f s k e te m0 Hmeq Hmeq' Inv.
set (c'' := CL_State f s k e te).
set (c := {|
RC.core := CL_State f Sskip (Kseq s k) e te;
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split;
first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //.
by rewrite -Hmeq -Hmeq'.
case: Inv=> Inv Hsub Hk.
move: (Inv); rewrite /cl_core_inv /cl_state_inv /RC.roots /=.
case=> He Hte; split=> //=.
split.
{ rewrite /locs''=> x b ty H7.
move: (He _ _ _ H7); case/orP; first by move=> ->.
move=> X; apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply: REACH_nil; apply/orP; right. }
{ move=> x v0 H7; move: (Hte _ _ H7)=> H8 b H9; move: (H8 b H9).
rewrite /locs'' /RC.reach_set /RC.roots /= => H10.
by apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil. }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
rewrite Hmeq'.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by apply: REACH_is_closed. }
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f s k e te m0 Hmeq Hmeq' Inv.
set (c'' := CL_State f Scontinue k e te).
set (c := {|
RC.core := CL_State f Scontinue (Kseq s k) e te;
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split;
first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //.
by rewrite -Hmeq -Hmeq'.
case: Inv=> Inv Hsub Hk.
move: (Inv); rewrite /cl_core_inv /cl_state_inv /RC.roots /=.
case=> He Hte; split=> //=.
split.
{ rewrite /locs''=> x b ty H7.
move: (He _ _ _ H7); case/orP; first by move=> ->.
move=> X; apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply: REACH_nil; apply/orP; right. }
{ move=> x v0 H7; move: (Hte _ _ H7)=> H8 b H9; move: (H8 b H9).
rewrite /locs'' /RC.reach_set /RC.roots /= => H10.
by apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil. }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by apply: REACH_is_closed. }
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f s k e te m0 Hmeq Hmeq' Inv.
set (c'' := CL_State f Sbreak k e te).
set (c := {|
RC.core := c'';
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split;
first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //; first by rewrite -Hmeq -Hmeq'.
case: Inv=> Inv Hsub Hk.
move: (Inv); rewrite /cl_core_inv /cl_state_inv /RC.roots /=.
case=> He Hte; split=> //=.
split.
{ rewrite /locs''=> x b ty H7.
move: (He _ _ _ H7); case/orP; first by move=> ->.
move=> X; apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply: REACH_nil; apply/orP; right. }
{ move=> x v0 H7; move: (Hte _ _ H7)=> H8 b H9; move: (H8 b H9).
rewrite /locs'' /RC.reach_set /RC.roots /= => H10.
by apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil. }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by apply: REACH_is_closed. }
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f a s1 s2 k e te m0 v1 b Heval H2 Hmeq Hmeq' Inv.
set (c'' := CL_State f (if b then s1 else s2) k e te).
set (c := {|
RC.core := c'';
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split;
first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //; first by rewrite -Hmeq -Hmeq'.
by apply: (core_inv_freshlocs _ _ Inv). }
{ move=> f s1 s2 k e te m0 Hmeq Hmeq' Inv.
set (c'' := CL_State f s1 (Kloop1 s1 s2 k) e te).
set (c := {|
RC.core := c'';
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split;
first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //; first by rewrite -Hmeq -Hmeq'.
case: Inv=> Inv Hsub Hk; split.
move: (Inv); rewrite /cl_core_inv /cl_state_inv /RC.roots.
case=> He Hte; split=> //=.
{ rewrite /locs''=> x b' ty H7; move: (He _ _ _ H7); case/orP; first by move=> ->.
move=> /= H8; apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply: REACH_nil; apply/orP; right. }
{ rewrite /c'' /locs'' /c /= => x v H7 b' H8; move {locs'' c}.
apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil.
by apply: (Hte _ _ H7 _ H8). }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by apply: REACH_is_closed. }
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f s1 s2 k e te m0 x H Hmeq Hmeq' Inv.
set (c'' := CL_State f s2 (Kloop2 s1 s2 k) e te).
set (c := {|
RC.core := c'';
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split;
first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //; first by rewrite -Hmeq -Hmeq'.
case: Inv=> Inv Hsub Hk; split.
move: (Inv); rewrite /cl_core_inv /cl_state_inv /RC.roots.
case=> He Hte; split=> //=.
{ rewrite /locs''=> x' b' ty H7; move: (He _ _ _ H7); case/orP; first by move=> ->.
move=> /= H8; apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply: REACH_nil; apply/orP; right. }
{ rewrite /c'' /locs'' /c /= => x' v H7 b' H8; move {locs'' c}.
apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil.
by apply: (Hte _ _ H7 _ H8). }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by apply: REACH_is_closed. }
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f s1 s2 k e te m0 Hmeq Hmeq' Inv.
set (c'' := CL_State f Sskip k e te).
set (c := {|
RC.core := c'';
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split;
first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //; first by rewrite -Hmeq -Hmeq'.
case: Inv=> Inv Hsub Hk; split.
move: (Inv); rewrite /cl_core_inv /cl_state_inv /RC.roots.
case=> He Hte; split=> //=.
{ rewrite /locs''=> x' b' ty H7; move: (He _ _ _ H7); case/orP; first by move=> ->.
move=> /= H8; apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply: REACH_nil; apply/orP; right. }
{ rewrite /c'' /locs'' /c /= => x' v H7 b' H8; move {locs'' c}.
apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil.
by apply: (Hte _ _ H7 _ H8). }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by apply: REACH_is_closed. }
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f s1 s2 k e te m0 Hmeq Hmeq' Inv.
set (c'' := CL_State f (Sloop s1 s2) k e te).
set (c := {|
RC.core := c'';
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split; first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //; first by rewrite -Hmeq -Hmeq'.
case: Inv=> Inv Hsub Hk; split.
move: (Inv); rewrite /cl_core_inv /cl_state_inv /RC.roots.
case=> He Hte; split=> //=.
{ rewrite /locs''=> x' b' ty H7; move: (He _ _ _ H7); case/orP; first by move=> ->.
move=> /= H8; apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply: REACH_nil; apply/orP; right. }
{ rewrite /c'' /locs'' /c /= => x' v H7 b' H8; move {locs'' c}.
apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil.
by apply: (Hte _ _ H7 _ H8). }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by apply: REACH_is_closed. }
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f s1 s2 k e te m0 Hmeq Hmeq' Inv.
set (c'' := CL_State f Sskip k e te).
set (c := {|
RC.core := c'';
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split; first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //; first by rewrite -Hmeq -Hmeq'.
case: Inv=> Inv Hsub Hk; split.
move: (Inv); rewrite /cl_core_inv /cl_state_inv /RC.roots.
case=> He Hte; split=> //=.
{ rewrite /locs''=> x' b' ty H7; move: (He _ _ _ H7); case/orP; first by move=> ->.
move=> /= H8; apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply: REACH_nil; apply/orP; right. }
{ rewrite /c'' /locs'' /c /= => x' v H7 b' H8; move {locs'' c}.
apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil.
by apply: (Hte _ _ H7 _ H8). }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by apply: REACH_is_closed. }
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f k e te m0 m0' Hfree Hmeq Hmeq' Inv.
set (c'' := CL_Returnstate Vundef (call_cont k)).
set (c := {|
RC.core := c'';
RC.locs := locs |}).
set (locs'' := REACH m0' (fun b : block =>
freshloc m0 m0' b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists (FreelistEffect m0 (blocks_of_env e)); split;
first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //.
case: Inv=> Inv Hsub Hk.
by move=> b ofs Hfree'; rewrite -Hmeq; apply: (freelist_effect_reach Hfree' Inv).
by rewrite -Hmeq -Hmeq'.
move: Inv; case=> Hs Hsub Hk; split.
by move=> ?; move/getBlocksP; case=> ?; case.
apply: cont_inv_call_cont.
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f a k e te m0 v v' m0' Heval Hcast Hfree Hmeq Hmeq' Inv.
set (c'' := CL_Returnstate v' (call_cont k)).
set (c := {|
RC.core := c'';
RC.locs := locs |}).
set (locs'' := REACH m0' (fun b : block =>
freshloc m0 m0' b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists (FreelistEffect m0 (blocks_of_env e)); split;
first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //.
case: Inv=> Inv Hsub Hk.
move=> b ofs Hfree'.
rewrite -Hmeq. apply (freelist_effect_reach(k:=k)(f:=f) Hfree' Inv). assumption.
by rewrite -Hmeq -Hmeq'.
move: Inv; case=> Hs Hsub Hk; split.
move=> b Hget; move: (sem_cast_getBlocks Hcast Hget)=> Hget'.
move: (eval_expr_reach' Hs Hsub Heval Hget'); case/orP=> H; apply: REACH_nil; apply/orP.
by left.
by right; apply: REACH_nil; apply/orP; right; apply: REACH_nil; apply/orP; right.
apply: cont_inv_call_cont.
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f k e te m0 m0' Hcall Hfree Hmeq Hmeq' Inv.
set (c'' := CL_Returnstate Vundef k).
set (c := {|
RC.core := c'';
RC.locs := locs |}).
set (locs'' := REACH m0' (fun b : block =>
freshloc m0 m0' b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists (FreelistEffect m0 (blocks_of_env e)); split;
first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //.
case: Inv=> Inv Hsub Hk.
by move=> b ofs Hfree'; rewrite -Hmeq; apply: (freelist_effect_reach(k:=k)(f:=f) Hfree' Inv).
by rewrite -Hmeq -Hmeq'.
split; first by move=> ?; move/getBlocksP; case=> ?; case.
move: Inv; case=> Hs Hsub Hk; apply cont_inv_freshlocs.
by move: Hk; apply: cont_inv_ext1. }
{ move=> f s1 s2 k e te m0 n0 Heval Hmeq Hmeq' Inv.
set (c'' := CL_State f (seq_of_labeled_statement (select_switch n0 s2))
(Kswitch k) e te).
set (c := {|
RC.core := c'';
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split; first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //.
by rewrite -Hmeq -Hmeq'.
case: Inv=> Inv Hsub Hk; split.
move: (Inv); rewrite /cl_core_inv /cl_state_inv /RC.roots.
case=> He Hte; split=> //=.
{ rewrite /locs''=> x' b' ty H7; move: (He _ _ _ H7); case/orP; first by move=> ->.
move=> /= H8; apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply: REACH_nil; apply/orP; right. }
{ rewrite /c'' /locs'' /c /= => x' v H7 b' H8; move {locs'' c}.
apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil.
by apply: (Hte _ _ H7 _ H8). }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by apply: REACH_is_closed. }
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f x k e te m0 Hx Hmeq Hmeq' Inv.
set (c'' := CL_State f Sskip k e te).
set (c := {|
RC.core := c'';
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split; first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //.
by rewrite -Hmeq -Hmeq'.
case: Inv=> Inv Hsub Hk; split.
move: (Inv); rewrite /cl_core_inv /cl_state_inv /RC.roots.
case=> He Hte; split=> //=.
{ rewrite /locs''=> x' b' ty H7; move: (He _ _ _ H7); case/orP; first by move=> ->.
move=> /= H8; apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply: REACH_nil; apply/orP; right. }
{ rewrite /c'' /locs'' /c /= => x' v H7 b' H8; move {locs'' c}.
apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil.
by apply: (Hte _ _ H7 _ H8). }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by apply: REACH_is_closed. }
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f k e te m0 Hmeq Hmeq' Inv.
set (c'' := CL_State f Scontinue k e te).
set (c := {|
RC.core := c'';
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split; first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //.
by rewrite -Hmeq -Hmeq'.
case: Inv=> Inv Hsub Hk; split.
move: (Inv); rewrite /cl_core_inv /cl_state_inv /RC.roots.
case=> He Hte; split=> //=.
{ rewrite /locs''=> x' b' ty H7; move: (He _ _ _ H7); case/orP; first by move=> ->.
move=> /= H8; apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply: REACH_nil; apply/orP; right. }
{ rewrite /c'' /locs'' /c /= => x' v H7 b' H8; move {locs'' c}.
apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil.
by apply: (Hte _ _ H7 _ H8). }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by apply: REACH_is_closed. }
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f lbl s k e te m0 Hmeq Hmeq' Inv.
set (c'' := CL_State f s k e te).
set (c := {|
RC.core := c'';
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split; first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //.
by rewrite -Hmeq -Hmeq'.
case: Inv=> Inv Hsub Hk; split.
move: (Inv); rewrite /cl_core_inv /cl_state_inv /RC.roots.
case=> He Hte; split=> //=.
{ rewrite /locs''=> x' b' ty H7; move: (He _ _ _ H7); case/orP; first by move=> ->.
move=> /= H8; apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply: REACH_nil; apply/orP; right. }
{ rewrite /c'' /locs'' /c /= => x' v H7 b' H8; move {locs'' c}.
apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil.
by apply: (Hte _ _ H7 _ H8). }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by apply: REACH_is_closed. }
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f lbl k e te m0 s' k' Hfnd Hmeq Hmeq' Inv.
set (c'' := CL_State f s' k' e te).
set (c := {|
RC.core := c'';
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split; first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //.
by rewrite -Hmeq -Hmeq'.
case: Inv=> Inv Hsub Hk; split.
move: (Inv); rewrite /cl_core_inv /cl_state_inv /RC.roots.
case=> He Hte; split=> //=.
{ rewrite /locs''=> x' b' ty H7; move: (He _ _ _ H7); case/orP; first by move=> ->.
move=> /= H8; apply/orP; right; apply: REACH_nil; apply/orP; right.
by apply: REACH_nil; apply/orP; right. }
{ rewrite /c'' /locs'' /c /= => x' v H7 b' H8; move {locs'' c}.
apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil.
by apply: (Hte _ _ H7 _ H8). }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by apply: REACH_is_closed. }
move: Hfnd; apply: cont_inv_find_label.
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> f vargs k m0 e te m0' Hentry Hmeq Hmeq' Inv.
set (c'' := CL_State f (fn_body f) k e te).
set (c := {|
RC.core := c'';
RC.locs := locs |}).
set (locs'' := REACH m0' (fun b : block =>
freshloc m0 m0' b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split; first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //.
by rewrite -Hmeq -Hmeq'.
case: Inv=> Inv Hsub Hk; split.
split.
{ move=> x b ty H.
set (c''' := {| RC.core := c''; RC.locs := locs'' |}).
case: (@function_entry1_state_inv c''' (CL_Callstate (Internal f) vargs k)
_ _ _ _ _ _ _ Inv Hentry)=> /=.
by move=> He Hte; apply: (He _ _ _ H). }
{ move=> x v H.
set (c''' := {| RC.core := c''; RC.locs := locs'' |}).
case: (@function_entry1_state_inv c''' (CL_Callstate (Internal f) vargs k)
_ _ _ _ _ _ _ Inv Hentry)=> /=.
by move=> He Hte; apply: (Hte _ _ H). }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by apply: REACH_is_closed. }
by move: Hk; apply: cont_inv_freshlocs. }
{ move=> v optid f e te k m0 Hmeq Hmeq' Inv.
set (c'' := CL_State f Sskip k e (set_opttemp optid v te)).
set (c := {|
RC.core := c'';
RC.locs := locs |}).
set (locs'' := REACH m0 (fun b : block =>
freshloc m0 m0 b || RC.reach_set ge c m0 b)).
split.
rewrite FSem.step; split=> //.
exists EmptyEffect; split; first by rewrite -Hmeq -Hmeq'; econstructor; eauto.
split=> //.
by rewrite -Hmeq -Hmeq'.
case: Inv=> Hsub Inv.
rewrite /cl_core_inv /= in Inv; case: Inv; case=> He Hte Hk; split.
split.
{ move=> x b ty H; apply/orP; right; rewrite /locs'' /=.
by apply: REACH_nil; move: H; move/He=> X; apply/orP; right; apply: REACH_nil. }
{ move=> x v0; rewrite /set_opttemp /locs'' /c /c''; move {locs'' c'' c}.
case: optid Hsub Hk He Hte=> a.
case: (ident_eq a x).
+ move=> Heq Hsub Hk He Hte; subst x; rewrite PTree.gss.
case=> ?; subst v0=> b Hget; apply/orP; right.
by apply: REACH_nil; apply/orP; right; apply: (Hsub _ Hget).
+ move=> Hneq Hsub Hk He Hte; rewrite PTree.gso=> H.
move=> b Hget; apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil.
by apply: (Hte _ _ H _ Hget).
by subst x.
move=> Inv He Hte H b Hget.
apply/orP; right; apply: REACH_nil; apply/orP; right; apply: REACH_nil.
by apply: (Hte _ _ H _ Hget). }
{ rewrite /locs''; move=> b X; apply/orP; right.
rewrite /in_mem /= /is_true /= in X; apply REACH_split in X; case: X.
by apply: REACH_mono'=> ? ?; apply/orP; right; apply: REACH_nil; apply/orP; left.
by apply: REACH_is_closed. }
by move: Hk; apply: cont_inv_freshlocs. }
Qed.
Lemma rc_aftext c m ef sg vs c' m' ov :
cl_core_inv c m ->
at_external (F clsem) (RC.core c) = Some (ef,sg,vs) ->
after_external (F rcsem) ov c = Some c' ->
cl_core_inv c' m'.
Proof.
move=> Inv; rewrite /= FSem.atext FSem.aftext /= /RC.at_external /RC.after_external /= => H.
have Hhlt: Clight_coop.CL_halted (RC.core c) = None.
{ move: H; case: (CL_at_external_halted_excl hf (RC.core c))=> // ->.
discriminate. }
case Haft: (CL_after_external _ _)=> // [c''].
case Hov: ov=> [v|]; case=> <-.
{ move: Inv; rewrite /cl_core_inv /=.
move: Haft; rewrite /CL_after_external Hov.
case: (RC.core c)=> // fd vs' k.
case: fd=> // ef' tys ty; case=> <-; case=> H0 H2 H3 /=.
split.
+ by move=> b Hget; apply: REACH_nil; apply/orP; right; apply/orP; left.
+ move: (@cont_inv_mem c k m m' H3); clear.
by apply: cont_inv_retv. }
{ move: Inv; rewrite /cl_core_inv.
move: Haft; rewrite /CL_after_external Hov.
case: (RC.core c)=> // fd args' k.
case: fd=> // ef' tys ty; case=> <- /=; case=> H0 H2 H3.
move: (@cont_inv_mem c k m m' H3).
split.
+ by move=> b; move/getBlocksP; case=> ?; case.
+ by apply: cont_inv_retv. }
Qed.
Lemma rc_safe z c m n :
cl_core_inv c (E m) ->
safeN (F clsem) espec ge n z (RC.core c) m ->
safeN (F rcsem) espec ge n z c m.
Proof.
move=> Inv H; move: z c m Inv H; elim: n=> // n IH z c m Inv H.
rewrite /= !FSem.atext /= /RC.at_external /RC.halted; move: H=> /=.
rewrite !FSem.atext /=.
case Hatext: (Clight_coop.CL_at_external _ _)=> // [[[ef sig] args]|].
rewrite !FSem.halted /= /RC.halted /=.
have Hhlt: Clight_coop.CL_halted (RC.core c) = None.
{ case: (CL_at_external_halted_excl hf (RC.core c))=> //.
rewrite Hatext; discriminate. }
rewrite Hhlt; case=> x []Hpre Hpost.
have Hdef: vals_def args.
{ by eapply espec_def; eauto. }
rewrite Hdef; exists x; split=> // ret' m' z' Hpost'.
case: (Hpost _ _ _ Hpost')=> c' []Haft HsafeN; move {Hpost Hpost'}.
rewrite FSem.aftext /= /RC.after_external /=; case: ret' Haft.
{ move=> v Haft; exists (RC.mk c' [predU getBlocks [::v] & RC.locs c]).
rewrite FSem.aftext /= in Haft; rewrite Haft; split=> //; apply: IH=> //.
move: Inv; rewrite /cl_core_inv /=.
move: Haft; rewrite /CL_after_external; case: (RC.core c)=> // fd vs k.
case: fd=> // ef' tys ty; case=> <-; case=> H H2 H3 /=.
split.
+ by move=> b Hget; apply: REACH_nil; apply/orP; right; apply/orP; left.
+ move: (@cont_inv_mem c k (FSem.E _ _ transf m) (FSem.E _ _ transf m') H3); clear.
by apply: cont_inv_retv. }
{ rewrite FSem.aftext /=.
move=> Heq; rewrite Heq; exists (RC.mk c' (RC.locs c)); split=> //.
apply: IH=> //.
rewrite /CL_after_external in Heq.
move: Inv Heq; rewrite /cl_core_inv.
case: (RC.core c)=> // fd args' k []H H2 H3.
case: fd=> // ef' tys ty; case=> <- /=.
move: (@cont_inv_mem c k (FSem.E _ _ transf m) (FSem.E _ _ transf m') H3).
split.
+ by move=> b; move/getBlocksP; case=> ?; case.
+ by apply: cont_inv_retv. }
rewrite !FSem.halted /= /RC.halted /=.
case Hhlt: (Clight_coop.CL_halted (RC.core c))=> [v|].
{ move=> Hexit.
have Hdef: ~~is_vundef v by (eapply espec_exit; eauto).
by rewrite Hdef. }
case=> c' []m' []step Hsafe.
case: (rc_step Inv step)=> Hstep Hinv.
by eexists; exists m'; split; eauto.
Qed.
Lemma rc_init_safe z v vs c m :
initial_core clsem ge v vs = Some c ->
(forall n, safeN (FSem.F _ _ transf _ _ clsem) espec ge n z c m) ->
let c' := {| RC.core := c; RC.locs := getBlocks vs |} in
[/\ initial_core rcsem ge v vs = Some c'
& forall n, safeN (FSem.F _ _ transf _ _ rcsem) espec ge n z c' m].
Proof.
rewrite /= /RC.initial_core /= => Heq; rewrite Heq=> Hsafe; split=> // n.
move: Heq (Hsafe n.+1); rewrite /= /CL_initial_core; case: v=> // b ofs.
rewrite FSem.atext FSem.halted /=.
case: (Integers.Int.eq_dec _ _)=> // Heq; subst ofs.
case Hg: (Genv.find_funct_ptr _ _)=> // [fd].
case Hfd: fd=> // [f].
case Hty: (type_of_fundef _)=> // [tys ty].
case Hval: (_ && _)=> //.
case=> <- /=; case=> c' []m'; rewrite FSem.step; case; case=> Hstep Hprop Hsafe'.
case: n Hsafe'=> // n Hsafe' /=.
rewrite !FSem.atext /= !FSem.halted /= /RC.corestep /RC.effstep /=.
set c'' := {| RC.core := c'
; RC.locs := REACH (FSem.E _ _ transf m')
(fun b0 : block =>
freshloc (FSem.E _ _ transf m) (FSem.E _ _ transf m') b0
|| RC.reach_set ge
{|
RC.core := CL_Callstate (Internal f) vs Kstop;
RC.locs := getBlocks vs |} (FSem.E _ _ transf m) b0) |}.
exists c'', m'; split.
+ rewrite FSem.step; split=> //; exists EmptyEffect.
rewrite /RC.effstep /=; split=> //.
inversion Hstep; subst; constructor=> //.
apply: rc_safe; rewrite /c'' /=; rewrite /cl_core_inv /=.
inversion Hstep; subst=> /=; split=> //.
eapply (function_entry1_state_inv (c0 := c'')); eauto.
by move=> b' Hget; apply: REACH_nil; apply/orP; right.
rewrite /c'' /= => b' Hin; apply/orP; right.
move: Hin; rewrite /RC.reach_set /RC.roots /=.
move/REACH_split; case.
apply: REACH_mono'=> b''.
by move=> Hglob; apply/orP; right; apply: REACH_nil; apply/orP; left.
by move/REACH_is_closed.
by apply: safe_downward1.
Qed.
End Z. End SafeClightRC. End SAFE_CLIGHT_RC.
Import SAFE_CLIGHT_RC.
Program Definition id_transf (T : Type) : FSem.t T T :=
FSem.mk T T (fun G C sem => sem) id (fun _ _ => True) _ _ _ _ _.
Next Obligation.
apply: prop_ext.
split=> //.
case=> //.
Qed.
Section Clight_RC.
Variable hf : I64Helpers.helper_functions.
Notation clsem := (CL_eff_sem1 hf).
Variable ge : Genv.t fundef Ctypes.type.
Definition I c m B :=
(exists v vs, B = getBlocks vs /\ initial_core clsem ge v vs = Some c)
\/ cl_core_inv ge (RC.mk c B) m.
Lemma init_I v vs c m :
initial_core clsem ge v vs = Some c ->
I c m (getBlocks vs).
Proof.
by left; exists v, vs.
Qed.
Let rcsem := RC.effsem clsem.
Lemma step_I c m c' m' B :
I c m B ->
corestep clsem ge c m c' m' ->
let B' := REACH m' (fun b => freshloc m m' b || RC.reach_set ge (RC.mk c B) m b) in
let c'' := RC.mk c' B' in corestep rcsem ge (RC.mk c B) m c'' m' /\ I c' m' B'.
Proof.
move=> H Hstep.
case: H=> [[v [vs H]]|H].
{ move: H; rewrite /CL_initial_core.
case=> Hget.
case: v=> // b ofs /=.
case Heq: (Integers.Int.eq_dec _ _)=> // [pf].
case Hgenv: (Genv.find_funct_ptr _ _)=> // [fd].
case Hfd: fd=> // [f].
case Hty: (type_of_fundef _)=> // [targs tret].
case Hcst: (_ && _)=> //.
case=> Hceq; split; subst c.
inversion Hstep; subst.
exists EmptyEffect; split=> //.
constructor=> //.
right.
inversion Hstep; subst; split=> //.
set c'' := {|
RC.core := CL_State f (fn_body f) Kstop e le;
RC.locs := REACH m'
(fun b0 : block =>
freshloc m m' b0
|| RC.reach_set ge
{|
RC.core := CL_Callstate (Internal f) vs Kstop;
RC.locs := getBlocks vs |} m b0) |}.
eapply function_entry1_state_inv with (c0 := c''); eauto.
by move=> b' Hget; apply: REACH_nil; apply/orP; right.
rewrite /= => b' Hin; apply/orP; right.
move: Hin; rewrite /RC.reach_set /RC.roots /=.
move/REACH_split; case.
apply: REACH_mono'=> b''.
by move=> Hglob; apply/orP; right; apply: REACH_nil; apply/orP; left.
by move/REACH_is_closed. }
{ case: (@rc_step hf mem (id_transf mem) _ _ _ _ _ H Hstep)=> H2 H3.
split=> //.
by right. }
Qed.
Lemma atext_I c m B ef sg vs :
I c B m ->
at_external clsem c = Some (ef,sg,vs) ->
vals_def vs = true.
Proof.
rewrite /= /CL_at_external; case: c=> //; case=> // ????? _.
by case Hand: (_ && _)=> //; case: (andP Hand)=> ??; case=> _ _ <-.
Qed.
Lemma aftext_I c m B ef sg vs ov c' m' :
I c m B ->
at_external clsem c = Some (ef,sg,vs) ->
after_external clsem ov c = Some c' ->
I c' m' (fun b => match ov with None => B b
| Some v => getBlocks (v::nil) b || B b
end).
Proof.
case.
{ case=> v' []vs' []Hget; rewrite /=.
case: c=> // fd args k /=.
rewrite /CL_initial_core.
case: v'=> // b ofs.
case: (Integers.Int.eq_dec _ _)=> // Heq; subst ofs.
case Hg: (Genv.find_funct_ptr _ _)=> // [fd'].
case Hfd': fd'=> // [f].
case Hty: (type_of_fundef _)=> // [tys ty].
case Hval: (_ && _)=> //.
case=> <- /= *; subst; congruence. }
move=> ?? Haft.
right.
eapply rc_aftext; eauto.
erewrite FSem.atext; eauto.
erewrite FSem.aftext; eauto.
simpl.
rewrite /RC.after_external Haft.
case: ov Haft=> //.
Grab Existential Variables.
refine ov.
refine (id_transf mem).
Qed.
Lemma halted_I c m B v :
I c m B ->
halted clsem c = Some v ->
vals_def (v :: nil) = true.
Proof.
rewrite /= /CL_halted => _; case: c=> // ?; case=> //.
by case Hvd: (vals_def _)=> //; case=> <-.
Qed.
Definition Clight_RC : RCSem.t clsem ge :=
@RCSem.Build_t _ _ _ clsem ge I init_I step_I atext_I aftext_I halted_I.
End Clight_RC.
|
In 2009, B4BC established the B4BC Survivorship Fund which provides grants to regional or local non-profits that support breast cancer patients and survivors through programs that provide assistance for cancer and supportive care needs, improve quality of life and/or focus on cancer wellness education.
Grant awards are made on an annual basis, as funding permits. Please contact us to learn more. |
\section{Introduction}
The next generation multi-phase flow models within the
CFD model FLUIDITY are outlined here.
FLUIDITY is a next generation fully unstructured mesh multi-phase model. Its next generation will include the ability to dynamically change its resolution (adapte the mesh) in response to the physics demands as well as user guidance. It already has some of the most advanced numerical methods in computational physics. Here the long term strategy is outlined in order to help ensure long term alignment of joint work
|
[STATEMENT]
lemma mset_set_insert_eq:
assumes "finite E"
shows "mset_set (E \<union> { x }) \<subseteq># mset_set E + {# x #}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. mset_set (E \<union> {x}) \<subseteq># mset_set E + {#x#}
[PROOF STEP]
proof (rule ccontr)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<not> mset_set (E \<union> {x}) \<subseteq># mset_set E + {#x#} \<Longrightarrow> False
[PROOF STEP]
assume "\<not> ?thesis"
[PROOF STATE]
proof (state)
this:
\<not> mset_set (E \<union> {x}) \<subseteq># mset_set E + {#x#}
goal (1 subgoal):
1. \<not> mset_set (E \<union> {x}) \<subseteq># mset_set E + {#x#} \<Longrightarrow> False
[PROOF STEP]
from this
[PROOF STATE]
proof (chain)
picking this:
\<not> mset_set (E \<union> {x}) \<subseteq># mset_set E + {#x#}
[PROOF STEP]
obtain y where "(count (mset_set (E \<union> { x })) y)
> (count (mset_set E + {# x #}) y)"
[PROOF STATE]
proof (prove)
using this:
\<not> mset_set (E \<union> {x}) \<subseteq># mset_set E + {#x#}
goal (1 subgoal):
1. (\<And>y. count (mset_set E + {#x#}) y < count (mset_set (E \<union> {x})) y \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (meson leI subseteq_mset_def)
[PROOF STATE]
proof (state)
this:
count (mset_set E + {#x#}) y < count (mset_set (E \<union> {x})) y
goal (1 subgoal):
1. \<not> mset_set (E \<union> {x}) \<subseteq># mset_set E + {#x#} \<Longrightarrow> False
[PROOF STEP]
from assms(1)
[PROOF STATE]
proof (chain)
picking this:
finite E
[PROOF STEP]
have "finite (E \<union> { x })"
[PROOF STATE]
proof (prove)
using this:
finite E
goal (1 subgoal):
1. finite (E \<union> {x})
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
finite (E \<union> {x})
goal (1 subgoal):
1. \<not> mset_set (E \<union> {x}) \<subseteq># mset_set E + {#x#} \<Longrightarrow> False
[PROOF STEP]
have "(count (mset_set E + {# x #}) y) = (count (mset_set E) y) + (count {# x #} y)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. count (mset_set E + {#x#}) y = count (mset_set E) y + count {#x#} y
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
count (mset_set E + {#x#}) y = count (mset_set E) y + count {#x#} y
goal (1 subgoal):
1. \<not> mset_set (E \<union> {x}) \<subseteq># mset_set E + {#x#} \<Longrightarrow> False
[PROOF STEP]
have "x \<noteq> y"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. x \<noteq> y
[PROOF STEP]
proof
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. x = y \<Longrightarrow> False
[PROOF STEP]
assume "x = y"
[PROOF STATE]
proof (state)
this:
x = y
goal (1 subgoal):
1. x = y \<Longrightarrow> False
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
x = y
[PROOF STEP]
have "y \<in> E \<union> { x }"
[PROOF STATE]
proof (prove)
using this:
x = y
goal (1 subgoal):
1. y \<in> E \<union> {x}
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
y \<in> E \<union> {x}
goal (1 subgoal):
1. x = y \<Longrightarrow> False
[PROOF STEP]
from \<open>finite (E \<union> { x })\<close> this
[PROOF STATE]
proof (chain)
picking this:
finite (E \<union> {x})
y \<in> E \<union> {x}
[PROOF STEP]
have "(count (mset_set (E \<union> { x })) y) = 1"
[PROOF STATE]
proof (prove)
using this:
finite (E \<union> {x})
y \<in> E \<union> {x}
goal (1 subgoal):
1. count (mset_set (E \<union> {x})) y = 1
[PROOF STEP]
using count_mset_set(1)
[PROOF STATE]
proof (prove)
using this:
finite (E \<union> {x})
y \<in> E \<union> {x}
\<lbrakk>finite ?A; ?x \<in> ?A\<rbrakk> \<Longrightarrow> count (mset_set ?A) ?x = 1
goal (1 subgoal):
1. count (mset_set (E \<union> {x})) y = 1
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
count (mset_set (E \<union> {x})) y = 1
goal (1 subgoal):
1. x = y \<Longrightarrow> False
[PROOF STEP]
from this and \<open>(count (mset_set (E \<union> { x })) y) > (count (mset_set E + {# x #}) y)\<close>
[PROOF STATE]
proof (chain)
picking this:
count (mset_set (E \<union> {x})) y = 1
count (mset_set E + {#x#}) y < count (mset_set (E \<union> {x})) y
[PROOF STEP]
have
"(count (mset_set E + {# x #}) y) = 0"
[PROOF STATE]
proof (prove)
using this:
count (mset_set (E \<union> {x})) y = 1
count (mset_set E + {#x#}) y < count (mset_set (E \<union> {x})) y
goal (1 subgoal):
1. count (mset_set E + {#x#}) y = 0
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
count (mset_set E + {#x#}) y = 0
goal (1 subgoal):
1. x = y \<Longrightarrow> False
[PROOF STEP]
from \<open>(count (mset_set E + {# x #}) y) = 0\<close>
[PROOF STATE]
proof (chain)
picking this:
count (mset_set E + {#x#}) y = 0
[PROOF STEP]
have "count {# x #} y = 0"
[PROOF STATE]
proof (prove)
using this:
count (mset_set E + {#x#}) y = 0
goal (1 subgoal):
1. count {#x#} y = 0
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
count {#x#} y = 0
goal (1 subgoal):
1. x = y \<Longrightarrow> False
[PROOF STEP]
from \<open>x = y\<close>
[PROOF STATE]
proof (chain)
picking this:
x = y
[PROOF STEP]
have "count {# x #} y = 1"
[PROOF STATE]
proof (prove)
using this:
x = y
goal (1 subgoal):
1. count {#x#} y = 1
[PROOF STEP]
using count_mset_set
[PROOF STATE]
proof (prove)
using this:
x = y
\<lbrakk>finite ?A; ?x \<in> ?A\<rbrakk> \<Longrightarrow> count (mset_set ?A) ?x = 1
infinite ?A \<Longrightarrow> count (mset_set ?A) ?x = 0
?x \<notin> ?A \<Longrightarrow> count (mset_set ?A) ?x = 0
goal (1 subgoal):
1. count {#x#} y = 1
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
count {#x#} y = 1
goal (1 subgoal):
1. x = y \<Longrightarrow> False
[PROOF STEP]
from this and \<open>count {# x #} y = 0\<close>
[PROOF STATE]
proof (chain)
picking this:
count {#x#} y = 1
count {#x#} y = 0
[PROOF STEP]
show False
[PROOF STATE]
proof (prove)
using this:
count {#x#} y = 1
count {#x#} y = 0
goal (1 subgoal):
1. False
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
False
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
x \<noteq> y
goal (1 subgoal):
1. \<not> mset_set (E \<union> {x}) \<subseteq># mset_set E + {#x#} \<Longrightarrow> False
[PROOF STEP]
have "y \<notin> E"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. y \<notin> E
[PROOF STEP]
proof
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. y \<in> E \<Longrightarrow> False
[PROOF STEP]
assume "y \<in> E"
[PROOF STATE]
proof (state)
this:
y \<in> E
goal (1 subgoal):
1. y \<in> E \<Longrightarrow> False
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
y \<in> E
[PROOF STEP]
have "y \<in> E \<union> { x }"
[PROOF STATE]
proof (prove)
using this:
y \<in> E
goal (1 subgoal):
1. y \<in> E \<union> {x}
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
y \<in> E \<union> {x}
goal (1 subgoal):
1. y \<in> E \<Longrightarrow> False
[PROOF STEP]
from \<open>finite (E \<union> { x })\<close> this
[PROOF STATE]
proof (chain)
picking this:
finite (E \<union> {x})
y \<in> E \<union> {x}
[PROOF STEP]
have "(count (mset_set (E \<union> { x })) y) = 1"
[PROOF STATE]
proof (prove)
using this:
finite (E \<union> {x})
y \<in> E \<union> {x}
goal (1 subgoal):
1. count (mset_set (E \<union> {x})) y = 1
[PROOF STEP]
using count_mset_set(1)
[PROOF STATE]
proof (prove)
using this:
finite (E \<union> {x})
y \<in> E \<union> {x}
\<lbrakk>finite ?A; ?x \<in> ?A\<rbrakk> \<Longrightarrow> count (mset_set ?A) ?x = 1
goal (1 subgoal):
1. count (mset_set (E \<union> {x})) y = 1
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
count (mset_set (E \<union> {x})) y = 1
goal (1 subgoal):
1. y \<in> E \<Longrightarrow> False
[PROOF STEP]
from this and \<open>(count (mset_set (E \<union> { x })) y) > (count (mset_set E + {# x #}) y)\<close>
[PROOF STATE]
proof (chain)
picking this:
count (mset_set (E \<union> {x})) y = 1
count (mset_set E + {#x#}) y < count (mset_set (E \<union> {x})) y
[PROOF STEP]
have
"(count (mset_set E + {# x #}) y) = 0"
[PROOF STATE]
proof (prove)
using this:
count (mset_set (E \<union> {x})) y = 1
count (mset_set E + {#x#}) y < count (mset_set (E \<union> {x})) y
goal (1 subgoal):
1. count (mset_set E + {#x#}) y = 0
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
count (mset_set E + {#x#}) y = 0
goal (1 subgoal):
1. y \<in> E \<Longrightarrow> False
[PROOF STEP]
from \<open>(count (mset_set E + {# x #}) y) = 0\<close>
[PROOF STATE]
proof (chain)
picking this:
count (mset_set E + {#x#}) y = 0
[PROOF STEP]
have "count (mset_set E) y = 0"
[PROOF STATE]
proof (prove)
using this:
count (mset_set E + {#x#}) y = 0
goal (1 subgoal):
1. count (mset_set E) y = 0
[PROOF STEP]
by (simp split: if_splits)
[PROOF STATE]
proof (state)
this:
count (mset_set E) y = 0
goal (1 subgoal):
1. y \<in> E \<Longrightarrow> False
[PROOF STEP]
from \<open>y \<in> E\<close> \<open>finite E\<close>
[PROOF STATE]
proof (chain)
picking this:
y \<in> E
finite E
[PROOF STEP]
have "count (mset_set E) y = 1"
[PROOF STATE]
proof (prove)
using this:
y \<in> E
finite E
goal (1 subgoal):
1. count (mset_set E) y = 1
[PROOF STEP]
using count_mset_set(1)
[PROOF STATE]
proof (prove)
using this:
y \<in> E
finite E
\<lbrakk>finite ?A; ?x \<in> ?A\<rbrakk> \<Longrightarrow> count (mset_set ?A) ?x = 1
goal (1 subgoal):
1. count (mset_set E) y = 1
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
count (mset_set E) y = 1
goal (1 subgoal):
1. y \<in> E \<Longrightarrow> False
[PROOF STEP]
from this and \<open>count (mset_set E) y = 0\<close>
[PROOF STATE]
proof (chain)
picking this:
count (mset_set E) y = 1
count (mset_set E) y = 0
[PROOF STEP]
show False
[PROOF STATE]
proof (prove)
using this:
count (mset_set E) y = 1
count (mset_set E) y = 0
goal (1 subgoal):
1. False
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
False
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
y \<notin> E
goal (1 subgoal):
1. \<not> mset_set (E \<union> {x}) \<subseteq># mset_set E + {#x#} \<Longrightarrow> False
[PROOF STEP]
from this and \<open>x \<noteq> y\<close>
[PROOF STATE]
proof (chain)
picking this:
y \<notin> E
x \<noteq> y
[PROOF STEP]
have "y \<notin> E \<union> { x }"
[PROOF STATE]
proof (prove)
using this:
y \<notin> E
x \<noteq> y
goal (1 subgoal):
1. y \<notin> E \<union> {x}
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
y \<notin> E \<union> {x}
goal (1 subgoal):
1. \<not> mset_set (E \<union> {x}) \<subseteq># mset_set E + {#x#} \<Longrightarrow> False
[PROOF STEP]
from this
[PROOF STATE]
proof (chain)
picking this:
y \<notin> E \<union> {x}
[PROOF STEP]
have "(count (mset_set (E \<union> { x })) y) = 0"
[PROOF STATE]
proof (prove)
using this:
y \<notin> E \<union> {x}
goal (1 subgoal):
1. count (mset_set (E \<union> {x})) y = 0
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
count (mset_set (E \<union> {x})) y = 0
goal (1 subgoal):
1. \<not> mset_set (E \<union> {x}) \<subseteq># mset_set E + {#x#} \<Longrightarrow> False
[PROOF STEP]
from this and \<open>(count (mset_set (E \<union> { x })) y)
> (count (mset_set E + {# x #}) y)\<close>
[PROOF STATE]
proof (chain)
picking this:
count (mset_set (E \<union> {x})) y = 0
count (mset_set E + {#x#}) y < count (mset_set (E \<union> {x})) y
[PROOF STEP]
show False
[PROOF STATE]
proof (prove)
using this:
count (mset_set (E \<union> {x})) y = 0
count (mset_set E + {#x#}) y < count (mset_set (E \<union> {x})) y
goal (1 subgoal):
1. False
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
False
goal:
No subgoals!
[PROOF STEP]
qed |
(* Title: HOL/UNITY/Detects.thy
Author: Tanja Vos, Cambridge University Computer Laboratory
Copyright 2000 University of Cambridge
Detects definition (Section 3.8 of Chandy & Misra) using LeadsTo
*)
section\<open>The Detects Relation\<close>
theory Detects imports FP SubstAx begin
definition Detects :: "['a set, 'a set] => 'a program set" (infixl "Detects" 60)
where "A Detects B = (Always (-A \<union> B)) \<inter> (B LeadsTo A)"
definition Equality :: "['a set, 'a set] => 'a set" (infixl "<==>" 60)
where "A <==> B = (-A \<union> B) \<inter> (A \<union> -B)"
(* Corollary from Sectiom 3.6.4 *)
lemma Always_at_FP:
"[|F \<in> A LeadsTo B; all_total F|] ==> F \<in> Always (-((FP F) \<inter> A \<inter> -B))"
supply [[simproc del: boolean_algebra_cancel_inf]] inf_compl_bot_right[simp del]
apply (rule LeadsTo_empty)
apply (subgoal_tac "F \<in> (FP F \<inter> A \<inter> - B) LeadsTo (B \<inter> (FP F \<inter> -B))")
apply (subgoal_tac [2] " (FP F \<inter> A \<inter> - B) = (A \<inter> (FP F \<inter> -B))")
apply (subgoal_tac "(B \<inter> (FP F \<inter> -B)) = {}")
apply auto
apply (blast intro: PSP_Stable stable_imp_Stable stable_FP_Int)
done
lemma Detects_Trans:
"[| F \<in> A Detects B; F \<in> B Detects C |] ==> F \<in> A Detects C"
apply (unfold Detects_def Int_def)
apply (simp (no_asm))
apply safe
apply (rule_tac [2] LeadsTo_Trans, auto)
apply (subgoal_tac "F \<in> Always ((-A \<union> B) \<inter> (-B \<union> C))")
apply (blast intro: Always_weaken)
apply (simp add: Always_Int_distrib)
done
lemma Detects_refl: "F \<in> A Detects A"
apply (unfold Detects_def)
apply (simp (no_asm) add: Un_commute Compl_partition subset_imp_LeadsTo)
done
lemma Detects_eq_Un: "(A<==>B) = (A \<inter> B) \<union> (-A \<inter> -B)"
by (unfold Equality_def, blast)
(*Not quite antisymmetry: sets A and B agree in all reachable states *)
lemma Detects_antisym:
"[| F \<in> A Detects B; F \<in> B Detects A|] ==> F \<in> Always (A <==> B)"
apply (unfold Detects_def Equality_def)
apply (simp add: Always_Int_I Un_commute)
done
(* Theorem from Section 3.8 *)
lemma Detects_Always:
"[|F \<in> A Detects B; all_total F|] ==> F \<in> Always (-(FP F) \<union> (A <==> B))"
apply (unfold Detects_def Equality_def)
apply (simp add: Un_Int_distrib Always_Int_distrib)
apply (blast dest: Always_at_FP intro: Always_weaken)
done
(* Theorem from exercise 11.1 Section 11.3.1 *)
lemma Detects_Imp_LeadstoEQ:
"F \<in> A Detects B ==> F \<in> UNIV LeadsTo (A <==> B)"
apply (unfold Detects_def Equality_def)
apply (rule_tac B = B in LeadsTo_Diff)
apply (blast intro: Always_LeadsToI subset_imp_LeadsTo)
apply (blast intro: Always_LeadsTo_weaken)
done
end
|
<a href="https://colab.research.google.com/github/paulc00/ML-Intro/blob/master/notebooks/2_Logistic_Regression.ipynb" target="_parent"></a>
# Logistic Regression
We'll perform a logistic regression to try and classify breast tumors as benign or malignant based on features identified from biopsies.
## Technical setup
First we load packages we'll be using
```
# Import numpy for linear algebra operations
import numpy as np
# Import pandas for data manipulation
import pandas as pd
# Import the functions we'll need from scikit-learn
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report
from sklearn.feature_selection import RFE
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
```
## Import the Data
```
breast_cancer_dataset = load_breast_cancer()
```
## Investigate the Data
We'll perform some EDA here. First we take a look at the data structure that's been passed in. We'll print the contents of the dataset object.
```
print(dir(breast_cancer_dataset))
```
['DESCR', 'data', 'feature_names', 'filename', 'target', 'target_names']
We note that there is a DESCR attribute in the data structure so we can try printing that out. It gives us lots of useful information about our data.
```
print(breast_cancer_dataset.DESCR)
```
.. _breast_cancer_dataset:
Breast cancer wisconsin (diagnostic) dataset
--------------------------------------------
**Data Set Characteristics:**
:Number of Instances: 569
:Number of Attributes: 30 numeric, predictive attributes and the class
:Attribute Information:
- radius (mean of distances from center to points on the perimeter)
- texture (standard deviation of gray-scale values)
- perimeter
- area
- smoothness (local variation in radius lengths)
- compactness (perimeter^2 / area - 1.0)
- concavity (severity of concave portions of the contour)
- concave points (number of concave portions of the contour)
- symmetry
- fractal dimension ("coastline approximation" - 1)
The mean, standard error, and "worst" or largest (mean of the three
largest values) of these features were computed for each image,
resulting in 30 features. For instance, field 3 is Mean Radius, field
13 is Radius SE, field 23 is Worst Radius.
- class:
- WDBC-Malignant
- WDBC-Benign
:Summary Statistics:
===================================== ====== ======
Min Max
===================================== ====== ======
radius (mean): 6.981 28.11
texture (mean): 9.71 39.28
perimeter (mean): 43.79 188.5
area (mean): 143.5 2501.0
smoothness (mean): 0.053 0.163
compactness (mean): 0.019 0.345
concavity (mean): 0.0 0.427
concave points (mean): 0.0 0.201
symmetry (mean): 0.106 0.304
fractal dimension (mean): 0.05 0.097
radius (standard error): 0.112 2.873
texture (standard error): 0.36 4.885
perimeter (standard error): 0.757 21.98
area (standard error): 6.802 542.2
smoothness (standard error): 0.002 0.031
compactness (standard error): 0.002 0.135
concavity (standard error): 0.0 0.396
concave points (standard error): 0.0 0.053
symmetry (standard error): 0.008 0.079
fractal dimension (standard error): 0.001 0.03
radius (worst): 7.93 36.04
texture (worst): 12.02 49.54
perimeter (worst): 50.41 251.2
area (worst): 185.2 4254.0
smoothness (worst): 0.071 0.223
compactness (worst): 0.027 1.058
concavity (worst): 0.0 1.252
concave points (worst): 0.0 0.291
symmetry (worst): 0.156 0.664
fractal dimension (worst): 0.055 0.208
===================================== ====== ======
:Missing Attribute Values: None
:Class Distribution: 212 - Malignant, 357 - Benign
:Creator: Dr. William H. Wolberg, W. Nick Street, Olvi L. Mangasarian
:Donor: Nick Street
:Date: November, 1995
This is a copy of UCI ML Breast Cancer Wisconsin (Diagnostic) datasets.
https://goo.gl/U2Uwz2
Features are computed from a digitized image of a fine needle
aspirate (FNA) of a breast mass. They describe
characteristics of the cell nuclei present in the image.
Separating plane described above was obtained using
Multisurface Method-Tree (MSM-T) [K. P. Bennett, "Decision Tree
Construction Via Linear Programming." Proceedings of the 4th
Midwest Artificial Intelligence and Cognitive Science Society,
pp. 97-101, 1992], a classification method which uses linear
programming to construct a decision tree. Relevant features
were selected using an exhaustive search in the space of 1-4
features and 1-3 separating planes.
The actual linear program used to obtain the separating plane
in the 3-dimensional space is that described in:
[K. P. Bennett and O. L. Mangasarian: "Robust Linear
Programming Discrimination of Two Linearly Inseparable Sets",
Optimization Methods and Software 1, 1992, 23-34].
This database is also available through the UW CS ftp server:
ftp ftp.cs.wisc.edu
cd math-prog/cpo-dataset/machine-learn/WDBC/
.. topic:: References
- W.N. Street, W.H. Wolberg and O.L. Mangasarian. Nuclear feature extraction
for breast tumor diagnosis. IS&T/SPIE 1993 International Symposium on
Electronic Imaging: Science and Technology, volume 1905, pages 861-870,
San Jose, CA, 1993.
- O.L. Mangasarian, W.N. Street and W.H. Wolberg. Breast cancer diagnosis and
prognosis via linear programming. Operations Research, 43(4), pages 570-577,
July-August 1995.
- W.H. Wolberg, W.N. Street, and O.L. Mangasarian. Machine learning techniques
to diagnose breast cancer from fine-needle aspirates. Cancer Letters 77 (1994)
163-171.
Now we know a little bit about our data we can copy it over to pandas to check correlations between attributes, including the target variable.
```
breast_cancer_df = pd.DataFrame(breast_cancer_dataset.data, columns=breast_cancer_dataset.feature_names)
breast_cancer_df['benign'] = breast_cancer_dataset.target
plt.figure(figsize=(22,18))
# Calculate the correlation matrix which will be correlations between each of the attributes
correlation_matrix = breast_cancer_df.corr().round(2)
# Produce a heatmap showing the correlation matrix
sns.heatmap(data=correlation_matrix, annot=True, cmap=sns.color_palette("coolwarm", 7))
```
## Prepare the Data
We'll use information from the correlations between our features and our target, `benign`, to eliminate irrelevant features from our dataset.
```
# correlation_matrix['benign'], get the last row of the correlation matrix
# .iloc[:-1], removing the last column, 'benign'
# .where(lambda x : x < -0.7), for each value, return the value if
# it's less than -0.7 otherwise return NaN
# .notnull(), return False if NaN, True otherwise
corr_support = correlation_matrix['benign']\
.iloc[:-1]\
.where(lambda x : x < -0.73)\
.notnull()
# corr_support = [ True, False, ...]
# Display the feature selection/elimination from RFE
print('Selected features:')
for feature_name, selected in zip(breast_cancer_dataset.feature_names, corr_support):
print(f"\t\t {'+' if selected else '-'} {feature_name}")
```
Selected features:
- mean radius
- mean texture
+ mean perimeter
- mean area
- mean smoothness
- mean compactness
- mean concavity
+ mean concave points
- mean symmetry
- mean fractal dimension
- radius error
- texture error
- perimeter error
- area error
- smoothness error
- compactness error
- concavity error
- concave points error
- symmetry error
- fractal dimension error
+ worst radius
- worst texture
+ worst perimeter
- worst area
- worst smoothness
- worst compactness
- worst concavity
+ worst concave points
- worst symmetry
- worst fractal dimension
```
g = sns.PairGrid(breast_cancer_df, vars=breast_cancer_dataset.feature_names[corr_support],
hue='benign', palette='coolwarm_r')
g.map(plt.scatter, alpha=0.8)
g.add_legend();
for i, j in zip(*np.triu_indices_from(g.axes, 0)):
g.axes[i, j].set_visible(False)
```
Once we've identified the best features for our model we can create a dataset with the reduced feature list.
```
# Define X, our features
X = pd.DataFrame(breast_cancer_dataset.data[:, corr_support], columns=breast_cancer_dataset.feature_names[corr_support])
# Define y, our lables
y = breast_cancer_dataset.target
```
We split the dataset into a training set and a test set
```
# Split our data into training and testing sets using random sampling with 20% of the data as test data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state=5) # random_state will cause the same random sequence to be generated every time
```
```
# Create our model: unpenalized logistic regression
logreg = LogisticRegression(solver='lbfgs', penalty='none', max_iter=500, random_state=1)
```
## Train the Data
Fit our logistic regression model to our data
```
# Train the model
logreg.fit(X_train, y_train)
```
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
intercept_scaling=1, l1_ratio=None, max_iter=500,
multi_class='warn', n_jobs=None, penalty='none',
random_state=1, solver='lbfgs', tol=0.0001, verbose=0,
warm_start=False)
## Evaluate the Performance of the Model
We'll look at the predictive accuracy on our training set and then on the test set. Remember, we're looking to maximize accuracy on our test data.
We'll also look at the classifiation report from scikit-learn.
The classification report gives us
$$Precision = \frac{True\ Positives}{True\ Positives + False\ Positives}$$
and
$$Recall = \frac{True\ Positives}{True\ Positives + False\ Negatives}$$
and
$$F_1\ Score = 2 \times \frac{Precision \times Recall}{Precision + Recall}$$
**Precision** talks about how precise/accurate your model is out of those predicted positive, how many of the labeled positives were actually positive.
**Recall** calculates how many of the actual positives were properly labeled as positive.
*F1 Score* is a measure of accuracy using precision and recall. It takes the occurance of both false positives and false negatives into account.
A **confusion matrix** shows counts of true negatives, true positives, false negatives and false positives.
In the following example the data is almost all negatives. Accuracy is 99% but if the false positive represents something very costly like a highly infectious disease or maybe fraud in a business then accuracy useful on its own.
For this example we calculate F1 as follows:
$$
\begin{align}
Precision & = \frac{1}{1} = 1\\
Recall & = \frac{1}{2} = 0.5\\
F_1 & = 2 \times \frac{1 \times 0.5}{ 1 + 0.5} = 2 \times \frac{0.5}{1.5} = 0.66666'
\end{align}
$$
**Support** provides a count of occurences of the true classes. Continuing our example:
$$
Support = \begin{cases}
998, & \text{if }class \text{ is Negative}\\
2, & \text{if }class \text{ is Positive}
\end{cases}
$$
```
# Make predictions using training data
y_train_predict = logreg.predict(X_train)
train_accuracy = accuracy_score(y_train, y_train_predict)
# Display the training accuracy
print(f'\n\nTraining accuracy = {train_accuracy*100:.3f}%\n')
# Make predictions using test data
y_test_predict = logreg.predict(X_test)
test_accuracy = accuracy_score(y_test, y_test_predict)
# Display the test accuracy
print(f'Test accuracy = {test_accuracy*100:.3f}%\n\n')
# Show the classification report
print(classification_report(y_test, y_test_predict, target_names=breast_cancer_dataset.target_names))
# Calculate and show the misclassification rate
print(f'This model will mis-classify about 1 in {1/(1 - test_accuracy):.2f}.')
```
Training accuracy = 95.824%
Test accuracy = 96.491%
precision recall f1-score support
malignant 0.98 0.94 0.96 48
benign 0.96 0.98 0.97 66
accuracy 0.96 114
macro avg 0.97 0.96 0.96 114
weighted avg 0.97 0.96 0.96 114
This model will mis-classify about 1 in 28.50.
Support is fairly balanced. The f1-score is half way between the precision and recall for both classes and it aligns well with our accuracy so the classification report doesn't give us much additional information in this case but it's very useful to know on cases where our data isn't as well balanced or in cases where the type of incorrect predictions is critical to decisions.
96.49% accuracy might sound pretty good but that means that about 1 in 28.5 of these predictions will be incorrect which is OK but probably not accurate enough for a patient or a provider who has to make a critical, high-risk medical decision based on this information. Every fraction of a percentage point we can gain as we approach 100% provides greater and greater gains.
# Exercise
The correlation matrix heatmap gave us some useful pointers but there's a few issues. It's comparing individual attributes so it doesn't take into account combined effects of features together. There's only two classes in our target so it's difficult to say when a correlation is meaningful.
We'll pivot into a different approach for preparing our data here. It's a technique called l2 regularization. It works by weakening the effect of already weak features. This
OK, let's run that process against our breast cancer data:
```
# This is a logistic regression classifier but it's using an 'l2' penalty
# This is also known as 'ridge regression'. l2 penalty is actually default
# but we're being explicit here for clarity
logreg = LogisticRegression(solver='liblinear', penalty='l2', random_state=1)
```
Fill in the code beneath each of the comment sections below
We're not using corr_support this time so just remove the square brackets and anything contained in them, for instance
```
breast_cancer_dataset.data[:, corr_support]
```
above needs to be replaced with just
```
breast_cancer_dataset.data
```
```
# Define your features, X
# X = ...
```
The following three lines of code will be the same as we used in the example above. Blank lines or comment lines which start with a `#` are not counted as code lines.
```
# Define your labels, y
# y = ...
# Split X and y into training and test datasets
# X_train, X_test, y_train, y_test =
# Train (Fit) your model
# logreg. ...
```
OK, we should have now built our test and training sets and we've trained our model by passing our training features and training labels to the `logreg.fit()` method.
Here's a quick check of the *training data* accuracy (which won't tell us if we're overfitting):
```
# Make predictions using training data
y_train_predict = logreg.predict(X_train)
# Use accuracy_score to get the training score from the test labels and the predictions
train_accuracy = accuracy_score(y_train, y_train_predict)
# Display the training accuracy
print(f'Training accuracy = {train_accuracy*100:.3f}%')
```
In order to check the accuracy under something close to real world conditions we want to predict against our test data, which our model hasn't seen during the training. We can then compare the predictions with the actual test labels to check the accuracy and print it out
```
# Make predictions using test data
# y_test_predict = ...
# test_accuracy = ...
# For the next three lines of code, the comments show how the line starts
# Display the test accuracy
# print(f'Test accuracy = {...
# Display the classification report for test labels vs predictions
# print(classification_report(...
# Calculate and show the mis-classification rate
# print(f'This model will mis-classify about 1 in {...
```
|
Formal statement is: lemma convex_onI [intro?]: assumes "\<And>t x y. t > 0 \<Longrightarrow> t < 1 \<Longrightarrow> x \<in> A \<Longrightarrow> y \<in> A \<Longrightarrow> f ((1 - t) *\<^sub>R x + t *\<^sub>R y) \<le> (1 - t) * f x + t * f y" shows "convex_on A f" Informal statement is: If $f$ satisfies the convexity inequality for all $t \in (0,1)$, then $f$ is convex on $A$. |
(** Yooooosh! Avec un peu de retard, voici mon petit tutoriel sur SSReflect.
* Je t'y partage un peu de tout ce que j'ai appris, en esperant que ce ne soit pas trop confus et assez ordone
* Donc commencons sans plus attendre ^^ *)
Require Export ssreflect.
Require Import ssrnat.
Require Import ssrbool.
Require Import ssrfun.
Require Import seq.
Require Import Permutation.
Require Import eqtype.
(*TODO: Reecrire les bibliotheques dans le bon ordre*)
(****** La gestion de la stack *****)
(** Comme je t'expliquais, SSReflect permet de manipuler la stack de facon tres fluide. Prenons par exemple: *)
Lemma Test_move_stack A B C: (A -> B -> C) -> (A -> B) -> A -> C.
move => Habc Hab Ha.
(** On voit la notre premier symbole chelou. => permet de poper de la stack de preuve un objet*)
move : Habc.
(** Et voici notre second. : lui push un objet sur la stack. Bien entendu on peut les combiner: *)
move : Hab => Hba.
(** A ton avis que c'est il passe? Vi, on a renomme Hab en Hba. En gros, l'ordre a retenir pour l'instant c'est que : arrive avant la tactique et => apres. Ca veut notamment dire qu'on ne peut pas ecrire cela:
* move => Hba : Ha.
* Car l'ordre ne serait pas respecte. Cette question d'ordre assure une certaine coherence en SSReflect ainsi que des lignes de codes relativement courtes.*)
apply.
(** Voila une seconde tactique. Apply prend l'hypothese du haut de la pile et essaie de l'appliquer au but. Presque toute les tactiques de SSR ne prennent pas d'argument et fonctionne plutot sur l'hyppothese en debut de pile *)
apply: Ha.
apply: Hba.
apply: Ha.
Qed.
(*Bien sur, on aurait pu combiner le tout et donner une version de la preuve plus fluide:*)
Lemma Test2 A B C: (A -> B -> C) -> (A -> B) -> A -> C.
move => Habc Hab Ha.
apply: (Habc Ha (Hab Ha)).
Qed.
(*En fait, plutot que apply, on aurait plus utiliser exact. Exact est ce qu'on appelle un terminateur. Ce sont certaines tactiques comme done et by qui finissent la preuve. C'est une bonne pratique d'utiliser ceux ci en fin de preuve*)
(*Lemma Test_final A B C: (A
apply: Habc.
apply: Ha.
pply: Hab.
apply: Ha.
Qed.*)
(* Tu t'en doutes, cette façon de proceder est assez fastidieuse. En fait, ce genre de tactique peut bient *)
Section ABR.
Variable T: eqType.
Hypotheses (R: rel T).
(* (R_trans: transitive R)
(R_total: total R)
(R_antisym: antisymmetric R).*)
Inductive Arbre : Type :=
|Leaf
|Node of T & Arbre & Arbre.
Inductive in_Arbre (a: T) (arb: Arbre) : Prop:=
|in_now l r of arb = Node a l r
|in_left b l r of arb = Node b l r & in_Arbre a l
|in_right b l r of arb = Node b l r & in_Arbre a r.
Implicit Arguments in_now [a arb].
Implicit Arguments in_right [a arb].
Fixpoint naive_in_b (a: T) (arb : Arbre) := match arb with
|Leaf => false
|Node b l r => (b == a) || naive_in_b a l || naive_in_b a r
end.
Lemma naive_in_bP arb a: reflect (in_Arbre a arb) (naive_in_b a arb).
elim: arb;
first by apply: ReflectF; case.
move => s l HreflectL r HreflectR.
rewrite /naive_in_b -/naive_in_b.
case eqas: (s == a).
by move /eqP : eqas <-; apply: ReflectT; apply (in_now l r).
case inl : (naive_in_b a l) => /=.
by apply: ReflectT; apply: (in_left s l r) => //; apply /HreflectL : inl.
case inr : (naive_in_b a r) => /=.
by apply: ReflectT; apply: (in_right s l r) => //; apply /HreflectR : inr.
apply: ReflectF.
case.
by move /eqP: eqas; move => eqas _ _ [] //.
by move /HreflectL: inl; move => inl _ _ _ [_ <- _] //.
by move /HreflectR: inr; move => inr _ _ _ [_ _ <-] //.
Qed.
Inductive ABR (arb: Arbre) :Prop :=
|ABR_intro s l r of arb = Node s l r & ABR l & ABR r &
(forall a, in_Arbre a l -> R a s) &
(forall b, in_Arbre b r -> ~~(R b s)).
Definition singleton a := Node a Leaf Leaf.
Inductive insert_at_leaf a arb res : Prop :=
|insert_leaf of arb = Leaf & res = singleton a
Inductive in_Arbre (a: T) (arb: Arbre) : Prop:=
|in_now l r of arb = Node a l r
|in_left b l r of arb = Node b l r & in_Arbre a l
|in_right b l r of arb = Node b l r & in_Arbre a r.
Implicit Arguments in_now [a arb].
Implicit Arguments in_right [a arb].
Fixpoint naive_in_b (a: T) (arb : Arbre) := match arb with
|Leaf => false
|Node b l r => (b == a) || naive_in_b a l || naive_in_b a r
end.
Lemma naive_in_bP arb a: reflect (in_Arbre a arb) (naive_in_b a arb).
elim: arb;
first by apply: ReflectF; case.
move => s l HreflectL r HreflectR.
rewrite /naive_in_b -/naive_in_b.
case eqas: (s == a).
by move /eqP : eqas <-; apply: ReflectT; apply (in_now l r).
case inl : (naive_in_b a l) => /=.
by apply: ReflectT; apply: (in_left s l r) => //; apply /HreflectL : inl.
case inr : (naive_in_b a r) => /=.
by apply: ReflectT; apply: (in_right s l r) => //; apply /HreflectR : inr.
apply: ReflectF.
case.
by move /eqP: eqas; move => eqas _ _ [] //.
by move /HreflectL: inl; move => inl _ _ _ [_ <- _] //.
by move /HreflectR: inr; move => inr _ _ _ [_ _ <-] //.
Qed.
Inductive ABR (arb: Arbre) :Prop :=
|ABR_intro s l r of arb = Node s l r & ABR l & ABR r &
(forall a, in_Arbre a l -> R a s) &
(forall b, in_Arbre b r -> ~~(R b s)).
Definition singleton a := Node a Leaf Leaf.
Inductive insert_at_leaf a arb res : Prop :=
|insert_leaf of arb = Leaf & res = singleton a
|insert_left b r of arb = Node b Leaf r & res = Node b (singleton a) r
|insert_right b l of arb = Node b l Leaf & res = Node b l (singleton a).
Implicit Arguments insert_leaf [a arb res].
Implicit Arguments insert_left [a arb res].
Implicit Arguments insert_right [a arb res].
Lemma ABR_left a l r : ABR (Node a l r) -> ABR l.
by move => [] _ _ _ [] <- <- <-.
Qed.
Lemma ABR_right a l r: ABR (Node a l r) -> ABR r.
by move => [] _ _ _ [] <- <- <-.
Qed.
Program Fixpoint insert a arb (h: ABR arb): {res | insert_at_leaf a arb res /\ ABR res}
:= match arb with
|Leaf => Node a Leaf Leaf
|Node b l r => if (R a b) then Node b (insert a l (ABR_left b l r h)) r else Node b l (insert a r (ABR_right b l r h))
end.
Proof.
Next Obligation.
split.
by apply: insert_leaf.
exists a Leaf Leaf => //.
by move => ? [].
by move => ? [].
Qed.
Next Obligation.
split.
case: (R a b).
case: i0 => [-> ->| |].
by apply: (insert_left b r).
move => ? ? -> ->.
by apply: (insert_
done.
Inductive in_ABR a (arb: Arbre): Prop :=
|in_ABR_now l r of arb = Node a l r
|in_ABR_left b l r of arb = Node b l r & R a b & in_ABR a l
|in_ABR_right b l r of arb = Node b l r & ~~(R a b) & in_ABR a r.
Implicit Arguments in_ABR_now [a arb].
Implicit Arguments in_ABR_left [a arb].
Implicit Arguments in_ABR_right [a arb].
Lemma in_ABR_in_equiv (arb: Arbre) a : ABR arb -> (in_ABR a arb <-> in_Arbre a arb).
move => HARB.
split.
- elim.
by move => _ l r ->; apply: (in_now l r).
by move => _ b l r -> _ _; apply: (in_left b l r).
by move => _ b l r -> _ _; apply: (in_right b l r).
- move => Hin.
elim: Hin HARB.
by move => _ l r -> _; apply (in_ABR_now l r).
move => _ b l r -> HinArbre HinABR.
move => [] // _ _ _ [] <- <- <- HABRl _ Hinf _.
apply: (in_ABR_left b l r) => //.
by apply: Hinf => //.
by apply: HinABR.
move => _ b l r -> HinArbre HinABR.
move => [] // _ _ _ [] <- <- <- _ HABRr _ Hsup.
apply: (in_ABR_right b l r) => //.
by apply: Hsup => //.
by apply: HinABR.
Qed.
Fixpoint in_b_abr a arb := match arb with
|Leaf => false
|Node b l r => (b == a) || (if R a b then in_b_abr a l else in_b_abr a r)
end.
Lemma in_b_abr_P a arb : reflect (in_ABR a arb) (in_b_abr a arb).
elim: arb.
by apply: ReflectF; case.
move => s l HrefL r HrefR.
rewrite /in_b_abr -/in_b_abr.
case eqas: (s == a).
by move /eqP : eqas <-; apply: ReflectT; apply (in_ABR_now l r).
case Ras: (R a s).
case inl: (in_b_abr a l).
apply: ReflectT.
apply: (in_ABR_left s l r) => //; apply /HrefL : inl.
apply: ReflectF.
case.
|xor_gt of n > m : xor_le_gt n m false true.
Lemma xor_P n m: xor_le_gt n m (n <= m) (n > m).
Proof.
rewrite ltnNge.
case X : (n <= m).
+ constructor => //.
+ constructor by rewrite ltnNge X.
Qed.
Lemma not_le_gt n m: (n <= m) -> (n > m) -> False.
by case: xor_P.
move => Hnm Hmn.
move : (conj Hnm Hmn).
move /andP.
by case: xor_P.
Qed.
Section Perm.
Variable T: eqType.
Fixpoint Occurence a (l: seq T) := if l is b::l' then ((a == b) + Occurence a l') else O.
Lemma Occurence_cons a l : Occurence a (a :: l) = (Occurence a l) .+1.
Proof. by rewrite /Occurence eq_refl. Qed.
Lemma Occurence_ignore b l a: (a == b) = false -> Occurence a (b :: l) = Occurence a l.
Proof. by move => /= ->. Qed.
Definition Permutation_Occ l l' := nosimpl (forall a, Occurence a l = Occurence a l').
Lemma PO_sym l l' : Permutation_Occ l l' -> Permutation_Occ l' l.
Proof. by move => PO z. Qed.
Lemma PO_cons a l l': Permutation_Occ (a::l) (a::l') -> Permutation_Occ l l'.
Proof.
move => PO z.
move /(_ z) : PO.
rewrite !/Occurence.
case (z == a); [by move => [] | done].
Qed.
Lemma PO_nil l : Permutation_Occ nil l -> l = nil.
Proof.
case: l.
done.
move => a ? /(_ a) /=.
by rewrite eq_refl.
Qed.
Lemma PO_singleton a l : Permutation_Occ [::a] l -> l = [::a].
Proof.
case: l => [/PO_sym /PO_nil | b l].
done.
case X : (b == a).
by move /eqP : X => -> /PO_cons /PO_nil ->.
move / (_ b).
rewrite Occurence_cons Occurence_ignore => //.
Qed.
Fixpoint insert_at (a: T) n s := match n, s with
|S m, b::s' => b :: (insert_at a m s')
|_, _ => a::s
end.
Lemma insert_nil a n : insert_at a n [::] = [:: a].
Proof. by case : n. Qed.
Lemma insert_zero a l : insert_at a 0 l = a :: l.
Proof. done. Qed.
Lemma insert_cons a n b l : insert_at a n.+1 (b::l) = b::(insert_at a n l).
Proof. done. Qed.
Lemma Occurence_insert_cons a l n: (Occurence a (insert_at a n l)) = (Occurence a l) .+1.
Proof.
elim: n a l => [| n Hrec] a l.
by rewrite Occurence_cons.
case: l => [| b l] /=.
by rewrite eq_refl.
by rewrite Hrec.
Qed.
Lemma Occurence_insert_ignore a l n z: (z == a) = false -> (Occurence z (insert_at a n l)) = Occurence z l.
elim: n a l z => [|n Hrec] a l z.
by move => /= ->.
case: l => [/= -> | b l Hneq /=].
done.
by rewrite Hrec.
Qed.
Lemma Permutation_insert_swap n a l: Permutation (insert_at a n l) (insert_at a n.+1l).
Proof.
elim: n a l => [| m Hrec] a l.
case: l => *.
by rewrite !insert_nil; exact: Permutation_refl.
exact: perm_swap.
case: l => [|b l].
by rewrite !insert_nil; exact: Permutation_refl.
rewrite !insert_cons.
apply: perm_skip.
apply: Hrec.
Qed.
Lemma Permutation_insert_double n m a l : Permutation (insert_at a n l) (insert_at a m l).
Proof.
wlog : n m /(n <= m).
by case: (leqP n m) => [| /ltnW] X /(_ _ _ X) => //; exact: Permutation_sym.
move => /leP Hle.
elim: Hle a l => [|m' Hle Hrec] a l.
exact: Permutation_refl.
apply: (Permutation_trans (Hrec _ _)).
exact: Permutation_insert_swap.
Qed.
Lemma Permutation_insert_head a n l l': Permutation l l' -> Permutation (a::l) (insert_at a n l').
Proof.
elim: n l l' a => [| m Hrec] l l' a PO.
exact : perm_skip.
case: l' PO => [/Permutation_sym /Permutation_nil -> | b l' PO].
by rewrite insert_nil; exact: Permutation_refl.
apply: (Permutation_trans (Hrec _ (b :: l') _ _)) => //.
exact: Permutation_insert_double.
Qed.
Lemma PO_insert_inv a n l l' : Permutation_Occ (a::l) (insert_at a n l') -> Permutation_Occ l l'.
Proof.
move => PO z.
case X: (z == a); last first.
by rewrite -(Occurence_ignore a _ _ X) -(Occurence_insert_ignore a l' n) => //.
move : X => /eqP ->.
apply /eq_add_S.
rewrite -(Occurence_insert_cons a l' n) -Occurence_cons.
exact: PO.
Qed.
CoInductive insert_spec a : seq T -> Type :=
insert_spec_intro l n: insert_spec a (insert_at a n l).
Lemma extract_insert a: forall l, 0 < Occurence a l -> insert_spec a l.
Proof.
elim => [| b l Hrec] Hocc.
done.
case X: (a == b).
by move : X => /eqP ->; rewrite -insert_zero; split.
move: Hrec => [|l' n].
by rewrite -(Occurence_ignore b).
rewrite -insert_cons.
by split.
Qed.
Inductive insert_permutation: seq T -> seq T -> Type :=
|Perm_nil : insert_permutation nil nil
|Perm_add a n l l' of insert_permutation l l' : insert_permutation (a::l) (insert_at a n l').
Lemma Extract_perm: forall l l', Permutation_Occ l l' -> insert_permutation l l'.
Proof.
elim => [_ /PO_nil -> | a l Hrec l' PO].
exact: Perm_nil.
move:(extract_insert a l') (PO) => [|tl' n POtl'].
by move : PO => /(_ a) /= <-; rewrite eq_refl.
apply: Perm_add.
apply: Hrec.
exact: (PO_insert_inv a n).
Qed.
Lemma Instanciate_perm l l' : insert_permutation l l' -> Permutation l l'.
elim => *.
by exact: perm_nil.
by exact: Permutation_insert_head.
Qed.
Lemma Permutation_Occ_Permutation l l': Permutation_Occ l l' -> Permutation l l'.
Proof.
move => /(Extract_perm).
exact: Instanciate_perm.
Qed.
Lemma Permutation_Permutation_Occ l l': Permutation l l' -> Permutation_Occ l l'.
Proof.
elim => [| x l_ l_' _ PO /=| x y l_| l_ l_' l_'' _ eq1 _ eq2] z /=.
done.
by move : PO => /(_ z) ->.
by ring.
by move : eq1 eq2 => /(_ z) eq1 /(_ z) eq2; transitivity (Occurence z l_').
Qed.
Lemma Permutation_equiv l l' : Permutation l l' <-> Permutation_Occ l l'.
split.
exact: Permutation_Permutation_Occ.
exact: Permutation_Occ_Permutation.
Qed.
|
data ErlList : List Type -> Type where
Nil : ErlList []
(::) : x -> ErlList xs -> ErlList (x :: xs)
data ErlType : Type -> Type where
ETInteger : ErlType Integer
ETString : ErlType String
data ErlTypes : List Type -> Type where
ETErlTypesNil : ErlTypes []
ETErlTypesCons : (ErlType x, ErlTypes xs) => ErlTypes (x :: xs)
erlCall : ErlList xs -> {auto prf : ErlTypes xs} -> ()
erlCall args = ()
foo : ()
foo = erlCall [1,2,3, "foo", "bar", "baz", 4,5,6]
|
function [model, globalOpt] = svargplvmReOptimiseModel(model, initVardistIters, itNo, newExperimentNo, varargin)
% SVARGPLVMREOPTIMISEMODEL Optimise an already optimised svargplvm model for more iterations
%
% SEEALSO : svargplvmOptimiseModel
%
% COPYRIGHT : Andreas C. Damianou, 2011
% VARGPLVM
globalOptOrig = model.globalOpt;
globalOpt = globalOptOrig;
if nargin < 4
newExperimentNo = globalOpt.experimentNo;
end
globalOpt.experimentNo = newExperimentNo;
globalOpt.initVardistIters = initVardistIters;
globalOpt.itNo = itNo;
model.globalOpt = globalOpt;
model = svargplvmOptimiseModel(model, varargin{:});
globalOptOrig.initVardistIters = [globalOptOrig.initVardistIters initVardistIters];
globalOptOrig.itNo = [globalOptOrig.itNo itNo];
globalOpt = globalOptOrig;
model.globalOpt = globalOpt;
|
module Naperian
-- Naperian Functors, based on https://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/aplicative.pdf
import Data.Vect
import Data.Fin
interface Functor f => Naperian (f : Type -> Type) where
Log : {f : Type} -> Type
lookup' : f a -> (Log -> a)
positions : f Log
tabulate : (Log -> a) -> f a
positions = tabulate id
Naperian (Vect n) where
Log {n} = Fin n
lookup' [] FZ impossible
lookup' [] (FS _) impossible
lookup' (x :: xs) FZ = x
lookup' (x :: xs) (FS y) = lookup' xs y
tabulate h = map h positions
where
positions = positions' (replicate _ ())
where
positions' : Vect n () -> Vect n (Fin n)
positions' [] = []
positions' (() :: xs) = FZ :: map FS (positions' xs)
transpose' : (Naperian f, Naperian g) => f (g a) -> g (f a)
transpose' source = (map tabulate . tabulate . flip . lookup' . map lookup') source
example : Vect 2 (Vect 3 Integer)
example = [[1, 2, 3], [4, 5, 6]]
transposedExample : Vect 3 (Vect 2 Integer)
transposedExample = transpose' example
|
[STATEMENT]
lemma Re_zeta_ge_1:
assumes "x > 1"
shows "Re (zeta (of_real x)) \<ge> 1"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. 1 \<le> Re (zeta (complex_of_real x))
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. 1 \<le> Re (zeta (complex_of_real x))
[PROOF STEP]
have *: "(\<lambda>n. real (Suc n) powr -x) sums Re (zeta (complex_of_real x))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<lambda>n. real (Suc n) powr - x) sums Re (zeta (complex_of_real x))
[PROOF STEP]
using sums_Re[OF sums_zeta[of "of_real x"]] assms
[PROOF STATE]
proof (prove)
using this:
1 < Re (complex_of_real x) \<Longrightarrow> (\<lambda>n. Re (of_nat (Suc n) powr - complex_of_real x)) sums Re (zeta (complex_of_real x))
1 < x
goal (1 subgoal):
1. (\<lambda>n. real (Suc n) powr - x) sums Re (zeta (complex_of_real x))
[PROOF STEP]
by (simp add: powr_Reals_eq)
[PROOF STATE]
proof (state)
this:
(\<lambda>n. real (Suc n) powr - x) sums Re (zeta (complex_of_real x))
goal (1 subgoal):
1. 1 \<le> Re (zeta (complex_of_real x))
[PROOF STEP]
show "Re (zeta (of_real x)) \<ge> 1"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. 1 \<le> Re (zeta (complex_of_real x))
[PROOF STEP]
proof (rule sums_le[OF _ _ *])
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>n. ?f n \<le> real (Suc n) powr - x
2. ?f sums 1
[PROOF STEP]
show "(\<lambda>n. if n = 0 then 1 else 0) sums 1"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<lambda>n. if n = 0 then 1::'a else (0::'a)) sums (1::'a)
[PROOF STEP]
by (rule sums_single)
[PROOF STATE]
proof (state)
this:
(\<lambda>n. if n = 0 then 1::?'a1 else (0::?'a1)) sums (1::?'a1)
goal (1 subgoal):
1. \<And>n. (if n = 0 then 1 else 0) \<le> real (Suc n) powr - x
[PROOF STEP]
qed auto
[PROOF STATE]
proof (state)
this:
1 \<le> Re (zeta (complex_of_real x))
goal:
No subgoals!
[PROOF STEP]
qed |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP #-}
{- |
Module : Physics.Learn.QuantumMat
Copyright : (c) Scott N. Walck 2016-2018
License : BSD3 (see LICENSE)
Maintainer : Scott N. Walck <[email protected]>
Stability : experimental
This module contains state vectors and matrices
for quantum mechanics.
-}
-- Using only Complex Double here, no cyclotomic
module Physics.Learn.QuantumMat
(
-- * Complex numbers
C
-- * State Vectors
, xp
, xm
, yp
, ym
, zp
, zm
, np
, nm
, dim
, scaleV
, inner
, norm
, normalize
, probVector
, gramSchmidt
, conjV
, fromList
, toList
-- * Matrices (operators)
, sx
, sy
, sz
, scaleM
, (<>)
, (#>)
, (<#)
, conjugateTranspose
, fromLists
, toLists
, size
, matrixFunction
-- * Density matrices
, couter
, dm
, trace
, normalizeDM
, oneQubitMixed
-- * Quantum Dynamics
, timeEvMat
, timeEv
, timeEvMatSpec
-- * Composition
, Kronecker(..)
-- * Measurement
, possibleOutcomes
, outcomesProjectors
, outcomesProbabilities
-- * Vector and Matrix
, Vector
, Matrix
)
where
import Numeric.LinearAlgebra
( C
, Vector
, Matrix
, Herm
, iC -- square root of negative one
, (><) -- matrix definition
, ident
, scale
, norm_2
, inv
, (<\>)
, sym
, eigenvaluesSH
, eigSH
, cmap
, takeDiag
, conj
, dot
, tr
)
-- , (<>) -- matrix product (not * !!!!)
-- , (#>) -- matrix-vector product
-- , fromList -- vector definition
import qualified Numeric.LinearAlgebra as H
-- because H.outer does not conjugate
import Data.Complex
( Complex(..)
, magnitude
, realPart
)
#if MIN_VERSION_base(4,11,0)
import Prelude hiding ((<>))
#endif
-- | The state resulting from a measurement of
-- spin angular momentum in the x direction
-- on a spin-1/2 particle
-- when the result of the measurement is hbar/2.
xp :: Vector C
xp = normalize $ fromList [1, 1]
-- | The state resulting from a measurement of
-- spin angular momentum in the x direction
-- on a spin-1/2 particle
-- when the result of the measurement is -hbar/2.
xm :: Vector C
xm = normalize $ fromList [1, -1]
-- | The state resulting from a measurement of
-- spin angular momentum in the y direction
-- on a spin-1/2 particle
-- when the result of the measurement is hbar/2.
yp :: Vector C
yp = normalize $ fromList [1, iC]
-- | The state resulting from a measurement of
-- spin angular momentum in the y direction
-- on a spin-1/2 particle
-- when the result of the measurement is -hbar/2.
ym :: Vector C
ym = normalize $ fromList [1, -iC]
-- | The state resulting from a measurement of
-- spin angular momentum in the z direction
-- on a spin-1/2 particle
-- when the result of the measurement is hbar/2.
zp :: Vector C
zp = normalize $ fromList [1, 0]
-- | The state resulting from a measurement of
-- spin angular momentum in the z direction
-- on a spin-1/2 particle
-- when the result of the measurement is -hbar/2.
zm :: Vector C
zm = normalize $ fromList [0, 1]
-- | The state resulting from a measurement of
-- spin angular momentum in the direction
-- specified by spherical angles theta (polar angle)
-- and phi (azimuthal angle)
-- on a spin-1/2 particle
-- when the result of the measurement is hbar/2.
np :: Double -> Double -> Vector C
np theta phi = fromList [ cos (theta/2) :+ 0
, exp(0 :+ phi) * (sin (theta/2) :+ 0) ]
-- | The state resulting from a measurement of
-- spin angular momentum in the direction
-- specified by spherical angles theta (polar angle)
-- and phi (azimuthal angle)
-- on a spin-1/2 particle
-- when the result of the measurement is -hbar/2.
nm :: Double -> Double -> Vector C
nm theta phi = fromList [ sin (theta/2) :+ 0
, -exp(0 :+ phi) * (cos (theta/2) :+ 0) ]
-- | Dimension of a vector.
dim :: Vector C -> Int
dim = H.size
-- | Scale a complex vector by a complex number.
scaleV :: C -> Vector C -> Vector C
scaleV = scale
-- | Complex inner product. First vector gets conjugated.
inner :: Vector C -> Vector C -> C
inner = dot
-- | Length of a complex vector.
norm :: Vector C -> Double
norm = norm_2
-- | Return a normalized version of a given state vector.
normalize :: Vector C -> Vector C
normalize v = scale (1 / norm_2 v :+ 0) v
-- | Return a vector of probabilities for a given state vector.
probVector :: Vector C -- ^ state vector
-> Vector Double -- ^ vector of probabilities
probVector = cmap (\c -> magnitude c**2)
-- | Conjugate the entries of a vector.
conjV :: Vector C -> Vector C
conjV = conj
-- | Construct a vector from a list of complex numbers.
fromList :: [C] -> Vector C
fromList = H.fromList
-- | Produce a list of complex numbers from a vector.
toList :: Vector C -> [C]
toList = H.toList
--------------
-- Matrices --
--------------
-- | The Pauli X matrix.
sx :: Matrix C
sx = (2><2) [ 0, 1
, 1, 0 ]
-- | The Pauli Y matrix.
sy :: Matrix C
sy = (2><2) [ 0, -iC
, iC, 0 ]
-- | The Pauli Z matrix.
sz :: Matrix C
sz = (2><2) [ 1, 0
, 0, -1 ]
-- | Scale a complex matrix by a complex number.
scaleM :: C -> Matrix C -> Matrix C
scaleM = scale
-- | Matrix product.
(<>) :: Matrix C -> Matrix C -> Matrix C
(<>) = (H.<>)
-- | Matrix-vector product.
(#>) :: Matrix C -> Vector C -> Vector C
(#>) = (H.#>)
-- | Vector-matrix product
(<#) :: Vector C -> Matrix C -> Vector C
(<#) = (H.<#)
-- | Conjugate transpose of a matrix.
conjugateTranspose :: Matrix C -> Matrix C
conjugateTranspose = tr
-- | Construct a matrix from a list of lists of complex numbers.
fromLists :: [[C]] -> Matrix C
fromLists = H.fromLists
-- | Produce a list of lists of complex numbers from a matrix.
toLists :: Matrix C -> [[C]]
toLists = H.toLists
-- | Size of a matrix.
size :: Matrix C -> (Int,Int)
size = H.size
-- | Apply a function to a matrix.
-- Assumes the matrix is a normal matrix (a matrix
-- with an orthonormal basis of eigenvectors).
matrixFunction :: (C -> C) -> Matrix C -> Matrix C
matrixFunction f m
= let (valv,vecm) = H.eig m
fvalv = fromList [f val | val <- toList valv]
in vecm <> H.diag fvalv <> tr vecm
----------------------
-- Density Matrices --
----------------------
-- | Complex outer product
couter :: Vector C -> Vector C -> Matrix C
couter v w = v `H.outer` conj w
-- | Build a pure-state density matrix from a state vector.
dm :: Vector C -> Matrix C
dm cvec = cvec `couter` cvec
-- | Trace of a matrix.
trace :: Matrix C -> C
trace = sum . toList . takeDiag
-- | Normalize a density matrix so that it has trace one.
normalizeDM :: Matrix C -> Matrix C
normalizeDM rho = scale (1 / trace rho) rho
-- | The one-qubit totally mixed state.
oneQubitMixed :: Matrix C
oneQubitMixed = normalizeDM $ ident 2
----------------------
-- Quantum Dynamics --
----------------------
-- | Given a time step and a Hamiltonian matrix,
-- produce a unitary time evolution matrix.
-- Unless you really need the time evolution matrix,
-- it is better to use 'timeEv', which gives the
-- same numerical results without doing an explicit
-- matrix inversion. The function assumes hbar = 1.
timeEvMat :: Double -> Matrix C -> Matrix C
timeEvMat dt h
= let ah = scale (0 :+ dt / 2) h
(l,m) = size h
n = if l == m then m else error "timeEv needs square Hamiltonian"
identity = ident n
in inv (identity + ah) <> (identity - ah)
-- | Given a time step and a Hamiltonian matrix,
-- advance the state vector using the Schrodinger equation.
-- This method should be faster than using 'timeEvMat'
-- since it solves a linear system rather than calculating
-- an inverse matrix. The function assumes hbar = 1.
timeEv :: Double -> Matrix C -> Vector C -> Vector C
timeEv dt h v
= let ah = scale (0 :+ dt / 2) h
(l,m) = size h
n = if l == m then m else error "timeEv needs square Hamiltonian"
identity = ident n
in (identity + ah) <\> ((identity - ah) #> v)
-- | Given a Hamiltonian matrix, return a function from time
-- to evolution matrix. Uses spectral decomposition.
-- Assumes hbar = 1.
timeEvMatSpec :: Matrix C -> Double -> Matrix C
timeEvMatSpec m t = matrixFunction (\h -> exp(-iC * h * (t :+ 0))) m
-----------------
-- Composition --
-----------------
class Kronecker a where
kron :: a -> a -> a
instance H.Product t => Kronecker (Vector t) where
kron v1 v2 = H.fromList [c1 * c2 | c1 <- H.toList v1, c2 <- H.toList v2]
instance H.Product t => Kronecker (Matrix t) where
kron = H.kronecker
-----------------
-- Measurement --
-----------------
-- | The possible outcomes of a measurement
-- of an observable.
-- These are the eigenvalues of the matrix
-- of the observable.
possibleOutcomes :: Matrix C -> [Double]
possibleOutcomes observable
= H.toList $ eigenvaluesSH (sym observable)
-- From a Hermitian matrix, a list of pairs of eigenvalues and eigenvectors.
valsVecs :: Herm C -> [(Double,Vector C)]
valsVecs h = let (valv,m) = eigSH h
vals = H.toList valv
vecs = map (conjV . fromList) $ toLists (conjugateTranspose m)
in zip vals vecs
-- From a Hermitian matrix, a list of pairs of eigenvalues and projectors.
valsPs :: Herm C -> [(Double,Matrix C)]
valsPs h = [(val,couter vec vec) | (val,vec) <- valsVecs h]
combineFst :: (Eq a, Num b) => [(a,b)] -> [(a,b)]
combineFst [] = []
combineFst [p] = [p]
combineFst ((x1,m1):(x2,m2):ps)
= if x1 == x2
then combineFst ((x1,m1+m2):ps)
else (x1,m1):combineFst ((x2,m2):ps)
-- | Given an obervable, return a list of pairs
-- of possible outcomes and projectors
-- for each outcome.
outcomesProjectors :: Matrix C -> [(Double,Matrix C)]
outcomesProjectors m = combineFst (valsPs (sym m))
-- | Given an observable and a state vector, return a list of pairs
-- of possible outcomes and probabilites
-- for each outcome.
outcomesProbabilities :: Matrix C -> Vector C -> [(Double,Double)]
outcomesProbabilities m v
= [(a,realPart (inner v (p #> v))) | (a,p) <- outcomesProjectors m]
------------------
-- Gram-Schmidt --
------------------
-- | Form an orthonormal list of complex vectors
-- from a linearly independent list of complex vectors.
gramSchmidt :: [Vector C] -> [Vector C]
gramSchmidt [] = []
gramSchmidt (v:vs) = let nvs = gramSchmidt vs
nv = normalize (v - sum [scale (inner w v) w | w <- nvs])
in nv:nvs
-- To Do
-- Generate higher spin operators and state vectors
-- eigenvectors
-- projection operators
|
import data.int.basic tactic.pure_maths -- hide
/-
# Propositional logic
## Level 1: And elimination
Let $p$ and $q$ be propositions (mathematical statements). The formal statement $p \land q$
(read '$p$ conjunction $q$')
corresponds to the informal statement '$p$ and $q$'.
Suppose you are given a hypothesis `h : p ∧ q`. Then
1. [left and elimination] `h.left` is a proof of `p` and
2. [right and elimination] `h.right` is a proof of `q`.
Here, `h.left` is an abbreviation for `and.elim_left h`. Likewise for `h.right`.
**Theorem**: Let $x$ be an integer. Supose $h : (x > 0) \land (x ^ 2 = 16)$. Then $x ^ 2 = 16$.
**Proof**: The result follows from right and elimination on $h$. ∎
The Lean proof is below.
**Notation**: the symbol `∧` in Lean is typed `\and`.
-/
/- Axiom : and.elim_left (h : p ∧ q) :
p
-/
/- Axiom : and.elim_right (h : p ∧ q) :
q
-/
example (x : ℤ) (h : (x > 0) ∧ (x * x = 16)) : x * x = 16 :=
begin
from h.right,
end
/-
Alternatively, the `cases` tactic will decompose the `∧` into both the left and right sides.
Below `cases h with h₁ h₂` decomposes `h` into `h₁ : x > 0` and `h₂ : x * x = 16`.
-/
example (x : ℤ) (h : (x > 0) ∧ (x * x = 16)) : x * x = 16 :=
begin
cases h with h₁ h₂,
show x * x = 16, from h₂,
end
/-
Frequently, we consider the conjunction of several statements.
We can, for instance, derive $q$ given the assumption $p \land (q \land r).
-/
example (p q r : Prop) (h : p ∧ (q ∧ r)) : q :=
begin
have h₂ : q ∧ r, from h.right,
show q, from h₂.left,
end
/- Tactic : cases
`cases` is a general-purpose elimination tactic. It it used to 'decompose' a hypothesis into
its constituent parts.
### Examples
* Given `h : ∃ (x : ℤ), x + 5 = y`, typing `cases h with m h₂` replaces `h` with `m : ℤ` and
`h₂ : m + 5 = y`.
* Given `h : p ∧ q`, typing `cases h with hp hq` replaces `h` with `hp : p` and `hq : q`.
* Given `h : p ∨ q`, typing `cases h with hp hq` replaces the current goal with two goals
(1) in which `h` is replaced with `hp : p` and (2) in which `h` is replaced with `hq : q`.
* Given `x : ℕ`, typing `cases x with k` replaces the goal with two new goals: (1) a goal in which
every occurence of `x` is replaced with `0` and (2) a goal with a new variable `k : ℕ` and in
which every occurrence of `x` is replaced with `succ k`.
* Given `h : ∃ (x : X), P(x)`, typing `cases h with y h₂` introduces a new variable `y : X`
and replaces `h` with `h₂ : P(y)`.
-/
namespace exlean -- hide
/-
## Tasks
1. Replace `sorry` below with a Lean proof using `have` together with left and right and elimination.
Adapt the proof of the example above.
2. Write another Lean proof using `cases`.
3. On a piece of paper, state and give a handwritten proof of this result.
-/
/- Theorem : no-side-bar
Let $p$, $q$, and $r$ be propositions. Assuming $h : (r \land (p \land q)) \land r$,
we have $q$.
-/
theorem decomposing_and (p q r : Prop) (h : (r ∧ (p ∧ q)) ∧ r) :
q :=
begin
have h₂ : r ∧ (p ∧ q), from h.left,
have h₃ : p ∧ q, from h₂.right,
show q, from h₃.right,
end
end exlean -- hide |
firstTrue : (f : ℕ → Bool) → ∃ (λ n → f n ≡ true) → ℕ
firstTrue f prf = mp-ℕ
firstTrue-true : firstTrue f prf ≡ n → f n ≡ true
firstTrue-true = ?
firstTrue-false : firstTrue f prf ≡ n → ∀ m → m < n → f m ≡ false
firstTrue-false = ?
|
C Copyright(C) 1999-2020 National Technology & Engineering Solutions
C of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
C NTESS, the U.S. Government retains certain rights in this software.
C
C See packages/seacas/LICENSE for details
C************************************************************************
subroutine wrprop(ndbi, ndbo, flag, nump, nval, names, values,
* namlen)
C************************************************************************
C This subroutine with read properties from an input file and
C write properties to an output text file
C ndbi - IN - file id to read from
C ndbo - IN - file id to write to
C flag - IN - flag indicating what type of properties to read/write
C nump - IN - number of properties
C nval - IN - number of values
C names - IN - names of the properties
C values - IN - values of the properties
integer ndbi, ndbo, flag, nump, nval
character*(namlen) names(*)
integer values(*)
if (nump .eq. 0) return
call exgpn (ndbi, flag, names, ierr)
do 100 i = 1, nump
call exgpa (ndbi, flag, names(i), values, ierr)
write (ndbo,1000) '! Property Name: '
write (ndbo,1000) names(i)
write (ndbo,1000) '! Property Value(s): '
write (ndbo,1010) (values(j), j = 1, nval)
100 continue
1000 format (A)
1010 format (7(I10, 1X))
return
end
|
Hello there! Do you know if they make any plugins to help with SEO? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good success. If you know of any please share. Appreciate it! |
#ifndef __GSL_BLOCK_H__
#define __GSL_BLOCK_H__
#include <gsl/gsl_block_complex_long_double.h>
#include <gsl/gsl_block_complex_double.h>
#include <gsl/gsl_block_complex_float.h>
#include <gsl/gsl_block_long_double.h>
#include <gsl/gsl_block_double.h>
#include <gsl/gsl_block_float.h>
#include <gsl/gsl_block_ulong.h>
#include <gsl/gsl_block_long.h>
#include <gsl/gsl_block_uint.h>
#include <gsl/gsl_block_int.h>
#include <gsl/gsl_block_ushort.h>
#include <gsl/gsl_block_short.h>
#include <gsl/gsl_block_uchar.h>
#include <gsl/gsl_block_char.h>
#endif /* __GSL_BLOCK_H__ */
|
# Binomial Distribution - Waiting Time
> This document is written in *R*.
>
> ***GitHub***: https://github.com/czs108
## Background
> Suppose in a certain call centre, phone calls arrive at an *average* rate of **6** per *minute*. This means that the probability of a call arriving in any given *second* must be **0.1**.
>
> Simulate this process using a *Binomial Distribution* with a sample size of **60**. Each member of the sample represents a *second*.
>
> If a phone call arrives during a particular second then the corresponding member will be **1**. If no phone call arrives during a particular second, then the corresponding member will be **0**.
## Question A
> Use the function `sample` to generate a sample of **60** *seconds*.
```R
res <- sample(x=c(1, 0), size=60, replace=TRUE, prob=c(0.1, 0.9))
for (i in c(1:6)) {
end <- i * 10
idx <- c((end - 9):end)
print(res[idx])
}
```
[1] 0 1 0 0 0 0 0 0 0 0
[1] 0 0 0 1 0 0 0 0 0 0
[1] 0 0 0 0 0 0 0 0 0 0
[1] 0 0 0 1 0 0 0 0 0 0
[1] 0 0 0 1 0 0 0 0 0 0
[1] 0 0 0 0 0 0 0 0 0 0
## Question B
> In order to simulate a distribution, we need to generate a large number of samples.
>
> You can do this using a `for` loop. At each iteration you should record the value of $X$, the number phone calls arriving in the sample.
```R
trials <- 10000
phones <- c(rep(0, trials))
for (i in c(1:trials)) {
res <- sample(x=c(1, 0), size=60, replace=TRUE, prob=c(0.1, 0.9))
phones[i] <- sum(res)
}
barplot(phones, ylab="Number of phone calls in a minute")
```
## Question C
> Use the `table` function to compute the distribution over the different values of $X$.
>
> Plot the distribution using the `plot` function.
```R
probs <- prop.table(table(phones))
probs
```
phones
0 1 2 3 4 5 6 7 8 9 10
0.0011 0.0109 0.0382 0.0866 0.1370 0.1673 0.1679 0.1452 0.1047 0.0695 0.0354
11 12 13 14 15 16 17 18
0.0203 0.0090 0.0043 0.0018 0.0005 0.0001 0.0001 0.0001
```R
plot(probs, xlab="Number of phone calls in a minute", ylab="Probability")
```
## Question D
> Compute the true distribution using the formula for the *Binomial Distribution*.
>
> Plot the true distribution using the `points` function.
```R
p <- 0.1
phones <- c(0:60)
probs.true <- choose(n=60, k=phones) * (p ^ phones) * (1 - p) ^ (60 - phones)
probs.true
```
<ol class=list-inline>
<li>0.00179701029991443</li>
<li>0.0119800686660962</li>
<li>0.0392680028499821</li>
<li>0.0843534876036652</li>
<li>0.133559688705803</li>
<li>0.166207612611666</li>
<li>0.169285531363734</li>
<li>0.145101884026058</li>
<li>0.106811109074737</li>
<li>0.068570094714646</li>
<li>0.0388563870049661</li>
<li>0.019624437881296</li>
<li>0.00890368014984726</li>
<li>0.00365279185634759</li>
<li>0.00136254934324077</li>
<li>0.000464276072511669</li>
<li>0.000145086272659897</li>
<li>4.1724156843369e-05</li>
<li>1.10749305201535e-05</li>
<li>2.72015837337103e-06</li>
<li>6.19591629490069e-07</li>
<li>1.31130503595782e-07</li>
<li>2.58287355567449e-08</li>
<li>4.74150701041694e-09</li>
<li>8.12202589747346e-10</li>
<li>1.29952414359575e-10</li>
<li>1.94373269341245e-11</li>
<li>2.71962599078285e-12</li>
<li>3.56141498792993e-13</li>
<li>4.36648580895624e-14</li>
<li>5.01337259546826e-15</li>
<li>5.39072322093362e-16</li>
<li>5.42815879885677e-17</li>
<li>5.11745610666632e-18</li>
<li>4.51540244705852e-19</li>
<li>3.72699884519116e-20</li>
<li>2.87577071388206e-21</li>
<li>2.07262754153662e-22</li>
<li>1.39387232325562e-23</li>
<li>8.73652168422329e-25</li>
<li>5.09630431579692e-26</li>
<li>2.76222456140754e-27</li>
<li>1.38841975308845e-28</li>
<li>6.45776629343464e-30</li>
<li>2.7722734087977e-31</li>
<li>1.09521912446329e-32</li>
<li>3.96818523356264e-34</li>
<li>1.31334735862593e-35</li>
<li>3.95220269956878e-37</li>
<li>1.07542930600511e-38</li>
<li>2.62882719245694e-40</li>
<li>5.72729235829398e-42</li>
<li>1.101402376595e-43</li>
<li>1.84721572594549e-45</li>
<li>2.66059878222601e-47</li>
<li>3.22496822088001e-49</li>
<li>3.19937323500001e-51</li>
<li>2.49463800000001e-53</li>
<li>1.4337e-55</li>
<li>5.40000000000002e-58</li>
<li>1e-60</li>
</ol>
Use the `dbinom` function directly.
```R
dbinom(x=c(0:5), prob=p, size=60)
```
<ol class=list-inline>
<li>0.00179701029991443</li>
<li>0.0119800686660962</li>
<li>0.039268002849982</li>
<li>0.0843534876036651</li>
<li>0.133559688705803</li>
<li>0.166207612611666</li>
</ol>
```R
plot(probs, xlab="Number of phone calls in a minute", ylab="Probability")
points(probs.true ~ phones, col="red")
```
## Question E
> Compute the distribution over the possible waiting times for the *1st* call.
It's a *Geometric Distribution*.
```R
seconds <- c(0:60)
probs.time <- (1 - p) ^ seconds * p
probs.time
```
<ol class=list-inline>
<li>0.1</li>
<li>0.09</li>
<li>0.081</li>
<li>0.0729</li>
<li>0.06561</li>
<li>0.059049</li>
<li>0.0531441</li>
<li>0.04782969</li>
<li>0.043046721</li>
<li>0.0387420489</li>
<li>0.03486784401</li>
<li>0.031381059609</li>
<li>0.0282429536481</li>
<li>0.02541865828329</li>
<li>0.022876792454961</li>
<li>0.0205891132094649</li>
<li>0.0185302018885184</li>
<li>0.0166771816996666</li>
<li>0.0150094635296999</li>
<li>0.0135085171767299</li>
<li>0.0121576654590569</li>
<li>0.0109418989131512</li>
<li>0.00984770902183612</li>
<li>0.00886293811965251</li>
<li>0.00797664430768726</li>
<li>0.00717897987691853</li>
<li>0.00646108188922668</li>
<li>0.00581497370030401</li>
<li>0.00523347633027361</li>
<li>0.00471012869724625</li>
<li>0.00423911582752162</li>
<li>0.00381520424476946</li>
<li>0.00343368382029252</li>
<li>0.00309031543826326</li>
<li>0.00278128389443694</li>
<li>0.00250315550499324</li>
<li>0.00225283995449392</li>
<li>0.00202755595904453</li>
<li>0.00182480036314007</li>
<li>0.00164232032682607</li>
<li>0.00147808829414346</li>
<li>0.00133027946472911</li>
<li>0.0011972515182562</li>
<li>0.00107752636643058</li>
<li>0.000969773729787525</li>
<li>0.000872796356808772</li>
<li>0.000785516721127895</li>
<li>0.000706965049015106</li>
<li>0.000636268544113595</li>
<li>0.000572641689702235</li>
<li>0.000515377520732012</li>
<li>0.000463839768658811</li>
<li>0.00041745579179293</li>
<li>0.000375710212613637</li>
<li>0.000338139191352273</li>
<li>0.000304325272217046</li>
<li>0.000273892744995341</li>
<li>0.000246503470495807</li>
<li>0.000221853123446226</li>
<li>0.000199667811101604</li>
<li>0.000179701029991443</li>
</ol>
Use the `dgeom` function directly.
```R
dgeom(x=c(0:5), prob=p)
```
<ol class=list-inline>
<li>0.1</li>
<li>0.09</li>
<li>0.081</li>
<li>0.0729</li>
<li>0.06561</li>
<li>0.059049</li>
</ol>
The `pgeom` function can calculate the *cumulative* probability.
```R
pgeom(q=5, prob=p)
```
0.468559
```R
sum(dgeom(x=c(0:5), prob=p))
```
0.468559
```R
barplot(probs.time, xlab="Waiting times", ylab="Probability")
```
## Question F
> What's the *mean* waiting time for the *1st* call?
\begin{equation}
E\; (Times) = \frac{1}{p} = 10
\end{equation}
```R
mean <- sum(seconds * probs.time)
mean
```
8.88678835110539
|
{-# OPTIONS --rewriting #-}
module Everything where
import Examples
import Properties
import PrettyPrinter
import Interpreter
|
#include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_bessel.h>
int
main (void)
{
double x = 5.0;
gsl_sf_result result;
double expected = -0.17759677131433830434739701;
int status = gsl_sf_bessel_J0_e (x, &result);
printf ("status = %s\n", gsl_strerror(status));
printf ("J0(5.0) = %.18f\n"
" +/- % .18f\n",
result.val, result.err);
printf ("exact = %.18f\n", expected);
return status;
}
|
! { dg-do compile }
subroutine s
type t
1 ! { dg-error "Statement label without statement" }
end type
end subroutine
|
{-# OPTIONS --prop --allow-unsolved-metas #-}
postulate
A : Set
P : A → Prop
a : A
c : P a
Q : Prop
x : Q
x = _ where
b : A
b = a
d : P b
d = c
|
[STATEMENT]
lemma K3_imp_K2:
"\<lbrakk> Says A Tgs
\<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace>
\<in> set evs;
A \<notin> bad; evs \<in> kerbIV \<rbrakk>
\<Longrightarrow> \<exists>Ta. Says Kas A (Crypt (shrK A)
\<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>)
\<in> set evs"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evs; A \<notin> bad; evs \<in> kerbIV\<rbrakk> \<Longrightarrow> \<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evs
[PROOF STEP]
apply (erule rev_mp)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>A \<notin> bad; evs \<in> kerbIV\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evs \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evs)
[PROOF STEP]
apply (erule kerbIV.induct)
[PROOF STATE]
proof (prove)
goal (10 subgoals):
1. A \<notin> bad \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set [] \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set [])
2. \<And>evsf X Ba. \<lbrakk>A \<notin> bad; evsf \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evsf \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evsf); X \<in> synth (analz (knows Spy evsf))\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Spy Ba X # evsf) \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set (Says Spy Ba X # evsf))
3. \<And>evs1 Aa. \<lbrakk>A \<notin> bad; evs1 \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evs1 \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evs1)\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Aa Kas \<lbrace>Agent Aa, Agent Tgs, Number (CT evs1)\<rbrace> # evs1) \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set (Says Aa Kas \<lbrace>Agent Aa, Agent Tgs, Number (CT evs1)\<rbrace> # evs1))
4. \<And>evs2 authKa A' Aa T1. \<lbrakk>A \<notin> bad; evs2 \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evs2 \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evs2); Key authKa \<notin> used evs2; authKa \<in> symKeys; Says A' Kas \<lbrace>Agent Aa, Agent Tgs, Number T1\<rbrace> \<in> set evs2\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Kas Aa (Crypt (shrK Aa) \<lbrace>Key authKa, Agent Tgs, Number (CT evs2), Crypt (shrK Tgs) \<lbrace>Agent Aa, Agent Tgs, Key authKa, Number (CT evs2)\<rbrace>\<rbrace>) # evs2) \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set (Says Kas Aa (Crypt (shrK Aa) \<lbrace>Key authKa, Agent Tgs, Number (CT evs2), Crypt (shrK Tgs) \<lbrace>Agent Aa, Agent Tgs, Key authKa, Number (CT evs2)\<rbrace>\<rbrace>) # evs2))
5. \<And>evs3 Aa T1 Kas' authKa Ta authTicketa Ba. \<lbrakk>A \<notin> bad; evs3 \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evs3 \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evs3); Says Aa Kas \<lbrace>Agent Aa, Agent Tgs, Number T1\<rbrace> \<in> set evs3; Says Kas' Aa (Crypt (shrK Aa) \<lbrace>Key authKa, Agent Tgs, Number Ta, authTicketa\<rbrace>) \<in> set evs3; valid Ta wrt T1\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Aa Tgs \<lbrace>authTicketa, Crypt authKa \<lbrace>Agent Aa, Number (CT evs3)\<rbrace>, Agent Ba\<rbrace> # evs3) \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set (Says Aa Tgs \<lbrace>authTicketa, Crypt authKa \<lbrace>Agent Aa, Number (CT evs3)\<rbrace>, Agent Ba\<rbrace> # evs3))
6. \<And>evs4 servK Ba authKa A' Aa Ta T2a. \<lbrakk>A \<notin> bad; evs4 \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evs4 \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evs4); Key servK \<notin> used evs4; servK \<in> symKeys; Ba \<noteq> Tgs; authKa \<in> symKeys; Says A' Tgs \<lbrace>Crypt (shrK Tgs) \<lbrace>Agent Aa, Agent Tgs, Key authKa, Number Ta\<rbrace>, Crypt authKa \<lbrace>Agent Aa, Number T2a\<rbrace>, Agent Ba\<rbrace> \<in> set evs4; \<not> expiredAK Ta evs4; \<not> expiredA T2a evs4; servKlife + CT evs4 \<le> authKlife + Ta\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Tgs Aa (Crypt authKa \<lbrace>Key servK, Agent Ba, Number (CT evs4), Crypt (shrK Ba) \<lbrace>Agent Aa, Agent Ba, Key servK, Number (CT evs4)\<rbrace>\<rbrace>) # evs4) \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set (Says Tgs Aa (Crypt authKa \<lbrace>Key servK, Agent Ba, Number (CT evs4), Crypt (shrK Ba) \<lbrace>Agent Aa, Agent Ba, Key servK, Number (CT evs4)\<rbrace>\<rbrace>) # evs4))
7. \<And>evs5 authKa servK Aa authTicketa T2a Ba Tgs' Ts servTicket. \<lbrakk>A \<notin> bad; evs5 \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evs5 \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evs5); authKa \<in> symKeys; servK \<in> symKeys; Says Aa Tgs \<lbrace>authTicketa, Crypt authKa \<lbrace>Agent Aa, Number T2a\<rbrace>, Agent Ba\<rbrace> \<in> set evs5; Says Tgs' Aa (Crypt authKa \<lbrace>Key servK, Agent Ba, Number Ts, servTicket\<rbrace>) \<in> set evs5; valid Ts wrt T2a\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Aa Ba \<lbrace>servTicket, Crypt servK \<lbrace>Agent Aa, Number (CT evs5)\<rbrace>\<rbrace> # evs5) \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set (Says Aa Ba \<lbrace>servTicket, Crypt servK \<lbrace>Agent Aa, Number (CT evs5)\<rbrace>\<rbrace> # evs5))
8. \<And>evs6 A' Ba Aa servK Ts T3. \<lbrakk>A \<notin> bad; evs6 \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evs6 \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evs6); Says A' Ba \<lbrace>Crypt (shrK Ba) \<lbrace>Agent Aa, Agent Ba, Key servK, Number Ts\<rbrace>, Crypt servK \<lbrace>Agent Aa, Number T3\<rbrace>\<rbrace> \<in> set evs6; \<not> expiredSK Ts evs6; \<not> expiredA T3 evs6\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Ba Aa (Crypt servK (Number T3)) # evs6) \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set (Says Ba Aa (Crypt servK (Number T3)) # evs6))
9. \<And>evsO1 Aa authKa Ta authTicketa. \<lbrakk>A \<notin> bad; evsO1 \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evsO1 \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evsO1); Aa \<noteq> Spy; Says Kas Aa (Crypt (shrK Aa) \<lbrace>Key authKa, Agent Tgs, Number Ta, authTicketa\<rbrace>) \<in> set evsO1; expiredAK Ta evsO1\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Aa Spy \<lbrace>Agent Aa, Agent Tgs, Number Ta, Key authKa\<rbrace> # evsO1) \<longrightarrow> (\<exists>Taa. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Taa, authTicket\<rbrace>) \<in> set (Says Aa Spy \<lbrace>Agent Aa, Agent Tgs, Number Ta, Key authKa\<rbrace> # evsO1))
10. \<And>evsO2 Aa authKa servK Ba Ts servTicket. \<lbrakk>A \<notin> bad; evsO2 \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evsO2 \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evsO2); Aa \<noteq> Spy; Says Tgs Aa (Crypt authKa \<lbrace>Key servK, Agent Ba, Number Ts, servTicket\<rbrace>) \<in> set evsO2; expiredSK Ts evsO2\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Aa Spy \<lbrace>Agent Aa, Agent Ba, Number Ts, Key servK\<rbrace> # evsO2) \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set (Says Aa Spy \<lbrace>Agent Aa, Agent Ba, Number Ts, Key servK\<rbrace> # evsO2))
[PROOF STEP]
apply (frule_tac [7] K5_msg_in_parts_spies)
[PROOF STATE]
proof (prove)
goal (10 subgoals):
1. A \<notin> bad \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set [] \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set [])
2. \<And>evsf X Ba. \<lbrakk>A \<notin> bad; evsf \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evsf \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evsf); X \<in> synth (analz (knows Spy evsf))\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Spy Ba X # evsf) \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set (Says Spy Ba X # evsf))
3. \<And>evs1 Aa. \<lbrakk>A \<notin> bad; evs1 \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evs1 \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evs1)\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Aa Kas \<lbrace>Agent Aa, Agent Tgs, Number (CT evs1)\<rbrace> # evs1) \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set (Says Aa Kas \<lbrace>Agent Aa, Agent Tgs, Number (CT evs1)\<rbrace> # evs1))
4. \<And>evs2 authKa A' Aa T1. \<lbrakk>A \<notin> bad; evs2 \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evs2 \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evs2); Key authKa \<notin> used evs2; authKa \<in> symKeys; Says A' Kas \<lbrace>Agent Aa, Agent Tgs, Number T1\<rbrace> \<in> set evs2\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Kas Aa (Crypt (shrK Aa) \<lbrace>Key authKa, Agent Tgs, Number (CT evs2), Crypt (shrK Tgs) \<lbrace>Agent Aa, Agent Tgs, Key authKa, Number (CT evs2)\<rbrace>\<rbrace>) # evs2) \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set (Says Kas Aa (Crypt (shrK Aa) \<lbrace>Key authKa, Agent Tgs, Number (CT evs2), Crypt (shrK Tgs) \<lbrace>Agent Aa, Agent Tgs, Key authKa, Number (CT evs2)\<rbrace>\<rbrace>) # evs2))
5. \<And>evs3 Aa T1 Kas' authKa Ta authTicketa Ba. \<lbrakk>A \<notin> bad; evs3 \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evs3 \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evs3); Says Aa Kas \<lbrace>Agent Aa, Agent Tgs, Number T1\<rbrace> \<in> set evs3; Says Kas' Aa (Crypt (shrK Aa) \<lbrace>Key authKa, Agent Tgs, Number Ta, authTicketa\<rbrace>) \<in> set evs3; valid Ta wrt T1\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Aa Tgs \<lbrace>authTicketa, Crypt authKa \<lbrace>Agent Aa, Number (CT evs3)\<rbrace>, Agent Ba\<rbrace> # evs3) \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set (Says Aa Tgs \<lbrace>authTicketa, Crypt authKa \<lbrace>Agent Aa, Number (CT evs3)\<rbrace>, Agent Ba\<rbrace> # evs3))
6. \<And>evs4 servK Ba authKa A' Aa Ta T2a. \<lbrakk>A \<notin> bad; evs4 \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evs4 \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evs4); Key servK \<notin> used evs4; servK \<in> symKeys; Ba \<noteq> Tgs; authKa \<in> symKeys; Says A' Tgs \<lbrace>Crypt (shrK Tgs) \<lbrace>Agent Aa, Agent Tgs, Key authKa, Number Ta\<rbrace>, Crypt authKa \<lbrace>Agent Aa, Number T2a\<rbrace>, Agent Ba\<rbrace> \<in> set evs4; \<not> expiredAK Ta evs4; \<not> expiredA T2a evs4; servKlife + CT evs4 \<le> authKlife + Ta\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Tgs Aa (Crypt authKa \<lbrace>Key servK, Agent Ba, Number (CT evs4), Crypt (shrK Ba) \<lbrace>Agent Aa, Agent Ba, Key servK, Number (CT evs4)\<rbrace>\<rbrace>) # evs4) \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set (Says Tgs Aa (Crypt authKa \<lbrace>Key servK, Agent Ba, Number (CT evs4), Crypt (shrK Ba) \<lbrace>Agent Aa, Agent Ba, Key servK, Number (CT evs4)\<rbrace>\<rbrace>) # evs4))
7. \<And>evs5 authKa servK Aa authTicketa T2a Ba Tgs' Ts servTicket. \<lbrakk>A \<notin> bad; evs5 \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evs5 \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evs5); authKa \<in> symKeys; servK \<in> symKeys; Says Aa Tgs \<lbrace>authTicketa, Crypt authKa \<lbrace>Agent Aa, Number T2a\<rbrace>, Agent Ba\<rbrace> \<in> set evs5; Says Tgs' Aa (Crypt authKa \<lbrace>Key servK, Agent Ba, Number Ts, servTicket\<rbrace>) \<in> set evs5; valid Ts wrt T2a; servTicket \<in> parts (knows Spy evs5)\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Aa Ba \<lbrace>servTicket, Crypt servK \<lbrace>Agent Aa, Number (CT evs5)\<rbrace>\<rbrace> # evs5) \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set (Says Aa Ba \<lbrace>servTicket, Crypt servK \<lbrace>Agent Aa, Number (CT evs5)\<rbrace>\<rbrace> # evs5))
8. \<And>evs6 A' Ba Aa servK Ts T3. \<lbrakk>A \<notin> bad; evs6 \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evs6 \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evs6); Says A' Ba \<lbrace>Crypt (shrK Ba) \<lbrace>Agent Aa, Agent Ba, Key servK, Number Ts\<rbrace>, Crypt servK \<lbrace>Agent Aa, Number T3\<rbrace>\<rbrace> \<in> set evs6; \<not> expiredSK Ts evs6; \<not> expiredA T3 evs6\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Ba Aa (Crypt servK (Number T3)) # evs6) \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set (Says Ba Aa (Crypt servK (Number T3)) # evs6))
9. \<And>evsO1 Aa authKa Ta authTicketa. \<lbrakk>A \<notin> bad; evsO1 \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evsO1 \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evsO1); Aa \<noteq> Spy; Says Kas Aa (Crypt (shrK Aa) \<lbrace>Key authKa, Agent Tgs, Number Ta, authTicketa\<rbrace>) \<in> set evsO1; expiredAK Ta evsO1\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Aa Spy \<lbrace>Agent Aa, Agent Tgs, Number Ta, Key authKa\<rbrace> # evsO1) \<longrightarrow> (\<exists>Taa. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Taa, authTicket\<rbrace>) \<in> set (Says Aa Spy \<lbrace>Agent Aa, Agent Tgs, Number Ta, Key authKa\<rbrace> # evsO1))
10. \<And>evsO2 Aa authKa servK Ba Ts servTicket. \<lbrakk>A \<notin> bad; evsO2 \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evsO2 \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evsO2); Aa \<noteq> Spy; Says Tgs Aa (Crypt authKa \<lbrace>Key servK, Agent Ba, Number Ts, servTicket\<rbrace>) \<in> set evsO2; expiredSK Ts evsO2\<rbrakk> \<Longrightarrow> Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set (Says Aa Spy \<lbrace>Agent Aa, Agent Ba, Number Ts, Key servK\<rbrace> # evsO2) \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set (Says Aa Spy \<lbrace>Agent Aa, Agent Ba, Number Ts, Key servK\<rbrace> # evsO2))
[PROOF STEP]
apply (frule_tac [5] K3_msg_in_parts_spies, simp_all, blast, blast)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>evs3 Aa T1 Kas' authKa Ta authTicketa Ba. \<lbrakk>A \<notin> bad; evs3 \<in> kerbIV; Says A Tgs \<lbrace>authTicket, Crypt authK \<lbrace>Agent A, Number T2\<rbrace>, Agent B\<rbrace> \<in> set evs3 \<longrightarrow> (\<exists>Ta. Says Kas A (Crypt (shrK A) \<lbrace>Key authK, Agent Tgs, Number Ta, authTicket\<rbrace>) \<in> set evs3); Says Aa Kas \<lbrace>Agent Aa, Agent Tgs, Number T1\<rbrace> \<in> set evs3; Says Kas' Aa (Crypt (shrK Aa) \<lbrace>Key authKa, Agent Tgs, Number Ta, authTicketa\<rbrace>) \<in> set evs3; valid Ta wrt T1; authTicketa \<in> parts (knows Spy evs3)\<rbrakk> \<Longrightarrow> A = Aa \<and> authTicket = authTicketa \<and> authK = authKa \<and> A = Aa \<and> T2 = CT evs3 \<and> B = Ba \<longrightarrow> (\<exists>Ta. Says Kas Aa (Crypt (shrK Aa) \<lbrace>Key authKa, Agent Tgs, Number Ta, authTicketa\<rbrace>) \<in> set evs3)
[PROOF STEP]
apply (blast dest: Says_imp_spies [THEN parts.Inj, THEN authK_authentic])
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
From stdpp Require Import gmap.
From stdpp Require Export finite.
From cgraphs.cgraphs Require Export multiset.
Lemma list_lookup_insert_spec {V} (xs : list V) i j v :
(<[ i := v ]> xs) !! j = if (decide (i = j ∧ i < length xs)) then Some v else (xs !! j).
Proof.
case_decide.
- destruct H. subst. apply list_lookup_insert; done.
- destruct (decide (i < length xs)).
+ assert (i ≠ j) by naive_solver. apply list_lookup_insert_ne. done.
+ rewrite list_insert_ge; [done|lia].
Qed.
From iris.bi Require Import bi.
Lemma insert_subseteq_None `{Countable K} {V} (m m' : gmap K V) i v :
m !! i = None ->
<[ i := v ]> m ⊆ m' ->
m ⊆ m' ∧ m' !! i = Some v.
Proof.
rewrite !map_subseteq_spec.
intros H1 H2.
split.
- intros. apply H2.
destruct (decide (i = i0)); simplify_eq.
rewrite lookup_insert_ne //.
- apply H2. rewrite lookup_insert //.
Qed.
Lemma fmap_map_disjoint `{Countable K} {V1 V2} (f : V1 -> V2) (m1 m2 : gmap K V1) :
m1 ##ₘ m2 -> f <$> m1 ##ₘ f <$> m2.
Proof.
intros HH.
intros x. rewrite !lookup_fmap.
specialize (HH x).
destruct (m1 !! x); destruct (m2 !! x); try done.
Qed.
Lemma fmap_singleton_inv `{Countable K} {V1 V2} (f : V1 -> V2) (x : gmap K V1) (k : K) (v : V2) :
f <$> x = {[ k := v ]} -> ∃ v' : V1, x = {[ k := v' ]}.
Proof.
intros HH.
rewrite ->map_eq_iff in HH.
pose proof (HH k) as H'.
rewrite lookup_fmap in H'.
rewrite lookup_singleton in H'.
destruct (x !! k) eqn:E; simpl in *; simplify_eq.
exists v0.
rewrite map_eq_iff.
intros. specialize (HH i).
rewrite lookup_fmap in HH.
destruct (decide (i = k)).
- subst. rewrite lookup_singleton in HH. rewrite lookup_singleton.
destruct (x !! k); simplify_eq. done.
- rewrite lookup_singleton_ne in HH; eauto.
rewrite lookup_singleton_ne; eauto.
destruct (x !! i); simplify_eq. done.
Qed.
Lemma singleton_eq_iff `{Countable K} {V} (k1 k2 : K) (v1 v2 : V) :
({[ k1 := v1 ]} : gmap K V) = {[ k2 := v2 ]} <-> k1 = k2 ∧ v1 = v2.
Proof.
split; last naive_solver.
intros HH.
rewrite ->map_eq_iff in HH.
specialize (HH k1).
rewrite lookup_singleton in HH.
destruct (decide (k1 = k2)); subst.
- rewrite lookup_singleton in HH. simplify_eq; done.
- rewrite lookup_singleton_ne in HH. simplify_eq. done.
Qed.
Lemma dec_exists_list {A} (P : A → Prop) (xs : list A) :
(∀ x, P x → x ∈ xs) → (∀ x, x ∈ xs → Decision (P x)) → Decision (∃ x, P x).
Proof.
intros HPxs Hdec.
induction xs as [|x xs IHxs]. { right. set_solver. }
assert (Decision (P x)) as [] by (apply Hdec; set_solver).
{ left. naive_solver. }
apply IHxs.
- intros x' HPx'. specialize (HPxs x' HPx').
assert (x' = x ∨ x' ∈ xs) as []; set_solver.
- intros ??. apply Hdec. set_solver.
Qed.
Lemma dec_forall_list {A} (P : A → Prop) (xs : list A) :
(∀ x, P x ∨ x ∈ xs) → (∀ x, x ∈ xs → Decision (P x)) → Decision (∀ x, P x).
intros HPxs Hdec.
Proof.
induction xs as [|x xs IHxs]. { left. set_solver. }
assert (Decision (P x)) as [] by (apply Hdec; set_solver);
[|right;naive_solver].
apply IHxs.
- intros x'. destruct (HPxs x').
+ set_solver.
+ assert (x' = x ∨ x' ∈ xs) as []; set_solver.
- intros ??. apply Hdec. set_solver.
Qed.
Lemma lookup_app_lr {A} (l1 l2 : list A) {i : nat} :
(l1 ++ l2) !! i = if decide (i < length l1) then l1 !! i else l2 !! (i - length l1).
Proof.
case_decide.
- apply lookup_app_l. lia.
- apply lookup_app_r. lia.
Qed.
Lemma list_lookup_singleton_spec {A} (a : A) {i : nat} :
[a] !! i = if decide (i = 0) then Some a else None.
Proof.
destruct i; simpl; eauto.
Qed.
Lemma lookup_app_plus {A} (l1 l2 : list A) (i : nat) :
(l1 ++ l2) !! (length l1 + i) = l2 !! i.
Proof.
by induction l1.
Qed.
Lemma pigeon `{Countable A} (s : gset A) (xs : list A) :
(∀ i x, xs !! i = Some x -> x ∈ s) ->
size s < length xs ->
∃ i j a, xs !! i = Some a ∧ xs !! j = Some a ∧ i ≠ j.
Proof.
revert s. induction xs as [|x xs IH]; simpl; [lia|].
intros s Hxs Hsize.
destruct (decide (Exists (x=.) xs)) as [(? & Hx & <-)%Exists_exists|H2].
- apply elem_of_list_lookup in Hx as [j Hj].
exists 0,(S j),x.
eauto with lia.
- apply not_Exists_Forall in H2; [|solve_decision].
rewrite-> Forall_forall in H2. simpl in *.
assert (x ∈ s).
{ specialize (Hxs 0). naive_solver. }
assert (∀ i x, xs !! i = Some x -> x ∈ s).
{ intros i x' Hi. specialize (Hxs (S i)). naive_solver. }
destruct (IH (s ∖ {[x]})) as (i & j & a & ?).
{ intros. apply elem_of_difference.
split;[naive_solver|].
apply not_elem_of_singleton_2. apply not_symmetry.
apply H2. eapply elem_of_list_lookup_2. done. }
* assert (size s = 1 + size (s ∖ {[x]})); try lia.
replace 1 with (size ((singleton x) : gset A)); try apply size_singleton.
replace (size s) with (size ({[x]} ∪ s)); try apply size_union_alt.
f_equiv. apply subseteq_union_1_L.
rewrite <-elem_of_subseteq_singleton. done.
* exists (S i),(S j),a. naive_solver.
Qed.
Lemma lookup_take_Some {A} (xs : list A) (k i : nat) (x : A) :
take k xs !! i = Some x -> xs !! i = Some x.
Proof.
revert k i. induction xs; destruct k, i; naive_solver.
Qed.
Lemma lookup_take_Some_iff {A} (xs : list A) (k i : nat) (x : A) :
take k xs !! i = Some x <-> xs !! i = Some x ∧ i < k.
Proof.
split.
- intros. split.
+ apply lookup_take_Some in H. done.
+ apply lookup_lt_Some in H. rewrite take_length in H. lia.
- intros [].
rewrite lookup_take; done.
Qed.
Fixpoint insert2 {T} (i : nat) (x : T) (xs : list T) : list T :=
match i,xs with
| 0,xs => x :: xs
| S i',y :: xs => y :: insert2 i' x xs
| S i',[] => [x]
end.
Lemma lookup_insert2' {A} i j (x : A) xs :
i ≤ length xs ->
insert2 i x xs !! j =
if decide (j < i) then xs !! j
else if decide (j = i) then Some x
else xs !! (j - 1).
Proof.
intros Hlen. revert xs j Hlen; induction i;
intros xs j Hlen;
destruct xs; simpl; destruct j; simpl in *; eauto with lia.
- f_equiv. lia.
- rewrite IHi; last lia. repeat case_decide; eauto with lia.
destruct j; eauto with lia. simpl. f_equiv. lia.
Qed.
Lemma insert2_length {T} (i : nat) (x : T) (xs : list T) :
length (insert2 i x xs) = length xs + 1.
Proof.
revert i. induction xs; intros; destruct i; simpl in *; auto with lia.
Qed.
Lemma in_insert2 {T} (i : nat) (x a : T) (xs : list T) :
a ∈ insert2 i x xs <-> a = x ∨ a ∈ xs.
Proof.
revert i; induction xs; intros; destruct i; simpl in *; rewrite ->?elem_of_cons, ?IHxs;
rewrite ?elem_of_cons; naive_solver lia.
Qed.
Lemma insert2_NoDup {T} (i : nat) (x : T) (xs : list T) :
x ∉ xs ∧ NoDup xs <-> NoDup (insert2 i x xs).
Proof.
revert i; induction xs; destruct i; simpl; intros;
rewrite ?list.NoDup_cons; eauto with lia.
rewrite <-IHxs, in_insert2, not_elem_of_cons; naive_solver lia.
Qed.
Lemma insert2_out_of_bounds {T} (i : nat) (x : T) (xs : list T) :
i > length xs -> insert2 i x xs = xs ++ [x].
Proof.
revert i; induction xs; destruct i; simpl; intros; try f_equiv; eauto with lia.
Qed.
Lemma insert2_NoDup_2 {T} (i : nat) (x : T) (xs : list T) :
x ∉ xs -> NoDup xs -> NoDup (insert2 i x xs).
Proof.
rewrite <-insert2_NoDup. eauto.
Qed.
Lemma insert2_delete {T} (i : nat) (x : T) (xs : list T) :
i ≤ length xs -> delete i (insert2 i x xs) = xs.
Proof.
revert i; induction xs; destruct i; simpl; try f_equiv; eauto with lia.
intro. f_equiv. rewrite IHxs; eauto with lia.
Qed.
Lemma delete_insert2' {T} (i : nat) (x : T) (xs : list T) :
xs !! i = Some x -> insert2 i x (delete i xs) = xs.
Proof.
revert i; induction xs; destruct i; simpl; intros; try f_equiv; naive_solver.
Qed.
Lemma in_delete {A} x i (xs : list A) :
x ∈ delete i xs -> x ∈ xs.
Proof.
revert i; induction xs; intros; destruct i; simpl in *;
eauto; rewrite elem_of_cons; eauto.
rewrite-> elem_of_cons in H.
destruct H; eauto.
Qed.
Lemma NoDup_delete {A} i (xs : list A) :
NoDup xs -> NoDup (delete i xs).
Proof.
intro. revert i; induction xs; intros; destruct i; simpl in *; eauto.
- eapply NoDup_cons_1_2. done.
- eapply NoDup_cons_2; eauto using NoDup_cons_1_2.
rewrite-> list.NoDup_cons in H. intro.
apply in_delete in H0. naive_solver.
Qed.
Lemma take_nonempty {A} (xs : list A) (k : nat) :
k ≠ 0 -> xs ≠ [] -> take k xs ≠ [].
Proof.
destruct k, xs; simpl; naive_solver.
Qed.
Lemma drop_nonempty {A} (xs : list A) (i : nat) (a : A) :
xs !! i = Some a -> drop i xs ≠ [].
Proof.
revert xs; induction i; destruct xs; simpl; naive_solver.
Qed.
Lemma drop_take_app {A} (xs : list A) n :
xs = take n xs ++ drop n xs.
Proof.
revert n; induction xs; simpl; intros.
- destruct n; simpl; done.
- destruct n; simpl; try done.
f_equiv. eauto.
Qed.
Lemma lookup_reverse {A} i (l : list A) :
i < length l → reverse l !! i = l !! (length l - S i).
Proof.
revert i. induction l as [|y l IH]; intros i ?; simplify_eq/=; [done|].
rewrite reverse_cons. destruct (decide (i = length l)) as [->|].
- by rewrite ->lookup_app_r, reverse_length, Nat.sub_diag
by (by rewrite reverse_length).
- rewrite ->lookup_app_l, IH by (rewrite ?reverse_length; lia).
by replace (length l - i) with (S (length l - S i)) by lia.
Qed.
Lemma lookup_reverse_Some {A} i a (l : list A) :
reverse l !! i = Some a -> l !! (length l - S i) = Some a.
Proof.
destruct (decide (i < length l)).
- rewrite lookup_reverse; done.
- intro. apply lookup_lt_Some in H. rewrite reverse_length in H. lia.
Qed.
Lemma lookup_reverse_Some_iff {A} i a (l : list A) :
reverse l !! i = Some a <-> l !! (length l - S i) = Some a ∧ i < length l.
Proof.
destruct (decide (i < length l)).
- rewrite lookup_reverse;[|done]. naive_solver.
- split.
+ intro. apply lookup_lt_Some in H. rewrite reverse_length in H. lia.
+ naive_solver lia.
Qed.
Lemma lookup_singleton_Some {A} (a b : A) i :
[a] !! i = Some b <-> i = 0 ∧ a = b.
Proof.
destruct i; simpl. naive_solver.
destruct i; simpl; naive_solver.
Qed.
Lemma lookup_delete_lr {A} (xs : list A) (i j : nat) :
delete i xs !! j = if decide (j < i) then xs !! j else xs !! (S j).
Proof.
case_decide.
- rewrite lookup_delete_lt; done.
- rewrite lookup_delete_ge. done. lia.
Qed.
Lemma split_first {A} (xs : list A) a :
xs !! 0 = Some a -> xs = [a] ++ drop 1 xs.
Proof.
intros. destruct xs; simpl in *; simplify_eq. rewrite drop_0. done.
Qed.
Lemma last_lookup {A} (xs : list A) :
last xs = xs !! (length xs - 1).
Proof.
induction xs; simpl. done.
destruct xs; simpl in *. done.
rewrite Nat.sub_0_r in IHxs. done.
Qed.
Lemma split_last {A} (xs : list A) a :
last xs = Some a -> xs = take (length xs - 1) xs ++ [a].
Proof.
rewrite last_lookup.
intro.
assert ([a] = drop (length xs - 1) xs).
{
induction xs; simpl. simplify_eq.
rewrite Nat.sub_0_r.
simpl in *. rewrite Nat.sub_0_r in H.
destruct xs; simpl in *. simplify_eq. done.
rewrite Nat.sub_0_r in IHxs.
eauto.
}
rewrite H0.
rewrite take_drop. done.
Qed.
Lemma last_take {A} i (xs : list A) :
i < length xs -> last (take (S i) xs) = xs !! i.
Proof.
intro.
rewrite last_lookup.
rewrite lookup_take; rewrite take_length.
{ f_equiv. lia. } lia.
Qed.
Lemma last_take_Some {A} i (xs : list A) a :
xs !! i = Some a -> last (take (S i) xs) = Some a.
Proof.
intro.
rewrite last_take; first done.
apply lookup_lt_Some in H. done.
Qed.
Lemma last_drop {A} (xs : list A) i :
i < length xs -> last (drop i xs) = last xs.
Proof.
intros Hlt.
rewrite !last_lookup.
rewrite lookup_drop.
f_equiv. rewrite drop_length. lia.
Qed.
Lemma lookup_update {A} i j (xs : list A) x :
(<[ i := x ]> xs) !! j = if decide (i = j ∧ j < length xs) then Some x else xs !! j.
Proof.
revert i j; induction xs; intros i j; destruct i,j; simpl; eauto.
- case_decide. lia. done.
- rewrite IHxs. clear IHxs. repeat case_decide; eauto with lia.
Qed.
Lemma lookup_union_Some' `{Countable K} {V} (A B : gmap K V) x v :
A ##ₘ B ->
(A ∪ B) !! x = Some v ->
(A !! x = Some v ∧ B !! x = None) ∨ (B !! x = Some v ∧ A !! x = None).
Proof.
intros Hdisj Hl.
apply lookup_union_Some in Hl as []; eauto; [left | right]; split; eauto;
rewrite ->map_disjoint_alt in Hdisj; specialize (Hdisj x);
destruct (A !! x); naive_solver.
Qed.
Section disjoint.
Context `{Countable K}.
Context {V : Type}.
Definition disjoint (xs : list (gmap K V)) :=
forall i j h1 h2,
xs !! i = Some h1 -> xs !! j = Some h2 -> i ≠ j -> h1 ##ₘ h2.
Lemma disjoint_nil : disjoint [].
Proof.
intros j1 j2 h1 h2 Hs1 Hs2 Hneq; simplify_eq.
Qed.
Lemma disjoint_singleton g : disjoint [g].
Proof.
intros [] [] h1 h2 Hs1 Hs2 Hneq; simplify_eq.
Qed.
Lemma disjoint_two g1 g2 : g1 ##ₘ g2 -> disjoint [g1; g2].
Proof.
intros Hdisj j1 j2 h1 h2 Hs1 Hs2 Hneq.
destruct j1; destruct j2; try destruct j1; try destruct j2; try lia; simpl in *;
simplify_eq; eauto.
Qed.
Lemma disjoint_cons g gs :
(∀ g', g' ∈ gs -> g ##ₘ g') -> disjoint gs -> disjoint (g::gs).
Proof.
intros Hdisj1 Hdisj2.
intros j1 j2 h1 h2 Hs1 Hs2 Hneq.
destruct j1; destruct j2; try lia; simpl in *; simplify_eq.
- eauto using elem_of_list_lookup_2.
- symmetry. eauto using elem_of_list_lookup_2.
- unfold disjoint in *. eauto.
Qed.
Lemma disjoint_cons_weaken g gs :
disjoint (g::gs) -> disjoint gs.
Proof.
intros Hdisj.
intros j1 j2 h1 h2 Hs1 Hs2 Hneq.
eapply (Hdisj (S j1) (S j2)); eauto with lia.
Qed.
Lemma disjoint_cons_alt g gs :
disjoint (g::gs) <-> Forall (λ g', g ##ₘ g') gs ∧ disjoint gs.
Proof.
split.
- intros Hdisj. split; last by eapply disjoint_cons_weaken.
rewrite Forall_forall.
intros h Hin.
eapply elem_of_list_lookup in Hin as [? ?].
eapply (Hdisj 0 (S x)); eauto with lia.
- intros [Hfa Hdisj].
rewrite ->Forall_forall in Hfa.
eapply disjoint_cons; eauto.
Qed.
Lemma disjoint_delete gs i:
disjoint gs -> disjoint (delete i gs).
Proof.
intros Hdisj j1 j2 h1 h2 Hs1 Hs2 Hneq.
rewrite lookup_delete_lr in Hs1.
rewrite lookup_delete_lr in Hs2.
repeat case_decide; simpl in *; unfold disjoint in *; eauto with lia.
Qed.
Lemma disjoint_update gs g i :
(∀ j g', gs !! j = Some g' -> i ≠ j -> g ##ₘ g') ->
disjoint gs -> disjoint (<[ i := g ]> gs).
Proof.
destruct (decide (length gs <= i)).
{ rewrite list_insert_ge; eauto with lia. }
intros HH Hdisj j1 j2 h1 h2 Hs1 Hs2 Hneq.
rewrite lookup_update in Hs1.
rewrite lookup_update in Hs2.
repeat case_decide.
- destruct H0,H1. simplify_eq.
- destruct H0. simplify_eq. symmetry. eauto.
- destruct H1. simplify_eq. eauto.
- eauto.
Qed.
Lemma disjoint_weaken gs gs' :
gs' ⊆* gs -> disjoint gs -> disjoint gs'.
Proof.
intros Hsub Hdisj.
intros j1 j2 h1 h2 Hs1 Hs2 Hneq.
eapply Forall2_lookup_l in Hs1; last done.
eapply Forall2_lookup_l in Hs2; last done.
destruct Hs1 as (h1' & Hs1 & Hsub1).
destruct Hs2 as (h2' & Hs2 & Hsub2).
eapply map_disjoint_weaken.
- eapply Hdisj; last done; eauto.
- done.
- done.
Qed.
Lemma sublist_elem_of {A} (x : A) (xs ys : list A) :
sublist xs ys -> x ∈ xs -> x ∈ ys.
Proof.
induction 1; rewrite ?elem_of_cons; naive_solver.
Qed.
Lemma sublist_Forall {A} P (xs ys : list A) :
sublist xs ys -> Forall P ys -> Forall P xs.
Proof.
rewrite !Forall_forall. eauto using sublist_elem_of.
Qed.
Lemma disjoint_sublist gs gs' :
sublist gs' gs -> disjoint gs -> disjoint gs'.
Proof.
intros Hsub Hdisj.
induction Hsub.
- apply disjoint_nil.
- apply disjoint_cons_alt in Hdisj as [].
rewrite ->disjoint_cons_alt. split; eauto.
eapply sublist_Forall; eauto.
- apply IHHsub. eapply disjoint_cons_weaken; eauto.
Qed.
Lemma disjoint_update_sub gs g g' i :
gs !! i = Some g -> g' ⊆ g -> disjoint gs -> disjoint (<[i := g']> gs).
Proof.
intros Hsome Hsub Hdisj.
eapply disjoint_update; last done.
intros j h Hin Hneq.
eapply map_disjoint_weaken_l; last done.
eapply Hdisj; eauto.
Qed.
Lemma disjoint_app_singleton gs g :
(∀ g', g' ∈ gs -> g ##ₘ g') -> disjoint gs -> disjoint (gs ++ [g]).
Proof.
intros HH Hdisj j1 j2 h1 h2 Hs1 Hs2 Hneq.
rewrite lookup_app_lr in Hs1.
rewrite lookup_app_lr in Hs2.
unfold disjoint in *.
case_decide; case_decide;
try apply lookup_singleton_Some in Hs1 as [];
try apply lookup_singleton_Some in Hs2 as []; subst;
eauto using elem_of_list_lookup_2 with lia; symmetry;
eauto using elem_of_list_lookup_2 with lia.
Qed.
Lemma disjoint_insert gs g i :
(∀ g', g' ∈ gs -> g ##ₘ g') -> disjoint gs -> disjoint (insert2 i g gs).
Proof.
destruct (decide (length gs < i)).
{ rewrite insert2_out_of_bounds; eauto with lia.
intros. apply disjoint_app_singleton; eauto. }
intros HH Hdisj j1 j2 h1 h2 Hs1 Hs2 Hneq.
rewrite lookup_insert2' in Hs1; last lia.
rewrite lookup_insert2' in Hs2; last lia.
repeat case_decide; simpl in *; simplify_eq;
unfold disjoint in *;
eauto using elem_of_list_lookup_2 with lia; symmetry;
eauto using elem_of_list_lookup_2 with lia.
Qed.
End disjoint.
Lemma map_disjoint_self_empty `{Countable K} {V} (m : gmap K V) :
m ##ₘ m -> m = ∅.
Proof.
intros HH.
apply map_empty. intro.
specialize (HH i).
destruct (m !! i); eauto; done.
Qed.
Definition fin_list {A} n (f : fin n -> A) : list A := vec_to_list (fun_to_vec f).
Lemma fin_list_lookup {A} n (f : fin n -> A) (i : fin n) :
fin_list n f !! fin_to_nat i = Some (f i).
Proof.
unfold fin_list.
rewrite -vlookup_lookup lookup_fun_to_vec //.
Qed.
Lemma fin_list_length {A} n (f : fin n -> A) :
length (fin_list n f) = n.
Proof.
unfold fin_list.
rewrite vec_to_list_length //.
Qed.
Lemma fin_list_lookup_ne {A} n (f : fin n -> A) (i : nat) :
i >= n -> fin_list n f !! i = None.
Proof.
intros. destruct (fin_list n f !! i) eqn:E; eauto.
exfalso. eapply lookup_lt_Some in E. rewrite fin_list_length in E. lia.
Qed.
Definition fin_gset `{Countable A} n (f : fin n -> A) : gset A
:= list_to_set (fin_list n f).
Lemma elem_of_fin_gset `{Countable A} n (f : fin n -> A) (x : A) :
x ∈ fin_gset n f <-> ∃ i, f i = x.
Proof.
unfold fin_gset.
rewrite elem_of_list_to_set elem_of_list_lookup.
split.
- intros [i Hi].
assert (i < n) as Q.
{ eapply lookup_lt_Some in Hi. rewrite fin_list_length in Hi. done. }
replace i with (fin_to_nat (nat_to_fin Q)) in Hi
by rewrite fin_to_nat_to_fin //.
rewrite fin_list_lookup in Hi. naive_solver.
- intros [i Hi]. exists (fin_to_nat i).
rewrite fin_list_lookup. by f_equal.
Qed.
Definition all_fin n := fin_gset n id.
Lemma all_fin_all n : ∀ i, i ∈ all_fin n.
Proof.
intro. apply elem_of_fin_gset. eauto.
Qed.
Definition big_union `{Countable A} : gset (gset A) -> gset A := set_fold (∪) ∅.
Lemma elem_of_big_union `{Countable A} (s : gset (gset A)) (x : A) :
x ∈ big_union s <-> ∃ a, a ∈ s ∧ x ∈ a.
Proof.
eapply (set_fold_ind_L (λ y s, x ∈ y ↔ (∃ a, a ∈ s ∧ x ∈ a))); first set_solver.
intros. rewrite elem_of_union H1. set_solver.
Qed.
Definition fin_union `{Countable A} n (f : fin n -> gset A) : gset A :=
big_union (fin_gset n f).
Lemma elem_of_fin_union `{Countable A} n (f : fin n -> gset A) (x : A) :
x ∈ fin_union n f <-> ∃ i, x ∈ f i.
Proof.
unfold fin_union.
rewrite elem_of_big_union.
setoid_rewrite elem_of_fin_gset.
naive_solver.
Qed.
Fixpoint list_to_mapi' {A} (xs : list A) (n : nat) : gmap nat A :=
match xs with
| [] => ∅
| x::r => <[ n := x ]> (list_to_mapi' r (S n))
end.
Definition list_to_mapi {A} (xs : list A) := list_to_mapi' xs 0.
Lemma list_to_mapi'_lookup {A} (xs : list A) (i n : nat) :
i >= n -> list_to_mapi' xs n !! i = xs !! (i - n).
Proof.
revert i n. induction xs; simpl; intros.
- rewrite !lookup_empty. by destruct (i - n).
- rewrite lookup_insert_spec lookup_cons.
case_decide; subst.
+ replace (i - i) with 0 by lia. done.
+ destruct (i - n) eqn:E; try lia.
erewrite IHxs; last lia.
f_equal. lia.
Qed.
Lemma list_to_mapi_lookup {A} (xs : list A) (i : nat) :
list_to_mapi xs !! i = xs !! i.
Proof.
unfold list_to_mapi. rewrite list_to_mapi'_lookup; f_equal; lia.
Qed.
Definition fin_gmap {T} n : (fin n -> T) -> gmap nat T := list_to_mapi ∘ fin_list n.
Lemma fin_gmap_lookup {T} n (f : fin n -> T) (i : fin n) :
fin_gmap n f !! (fin_to_nat i) = Some (f i).
Proof.
unfold fin_gmap. simpl.
rewrite list_to_mapi_lookup fin_list_lookup //.
Qed.
Lemma fin_gmap_lookup_ne {T} n (f : fin n -> T) (k : nat) :
k >= n -> fin_gmap n f !! k = None.
Proof.
unfold fin_gmap. simpl. intros.
rewrite list_to_mapi_lookup fin_list_lookup_ne //.
Qed.
Lemma lookup_alter_spec `{Countable K} {V} (f : V -> V) (m : gmap K V) i j :
alter f i m !! j = if decide (i = j) then f <$> m !! i else m !! j.
Proof.
case_decide; subst.
- rewrite lookup_alter //.
- rewrite lookup_alter_ne //.
Qed.
Definition gmap_slice `{Countable K1, Countable K2} {A} (m : gmap (K1 * K2) A) (x : K1) : gmap K2 A :=
default ∅ (gmap_curry m !! x).
Lemma gmap_slice_lookup `{Countable K1, Countable K2} {A}
(m : gmap (K1*K2) A) x y :
gmap_slice m x !! y = m !! (x,y).
Proof.
unfold gmap_slice.
destruct (gmap_curry m !! x) eqn:E; simpl.
- rewrite -lookup_gmap_curry E //.
- rewrite ->lookup_gmap_curry_None in E.
rewrite E lookup_empty //.
Qed.
Lemma gmap_slice_alter `{Countable K1, Countable K2} {A} (f : A -> A)
(m : gmap (K1*K2) A) x y x' :
gmap_slice (alter f (x,y) m) x' =
if decide (x = x')
then alter f y (gmap_slice m x')
else gmap_slice m x'.
Proof.
eapply map_eq. intros.
case_decide; subst;
rewrite !gmap_slice_lookup ?lookup_alter_spec; repeat case_decide;
simplify_eq; eauto; rewrite gmap_slice_lookup //.
Qed.
Lemma gmap_slice_insert `{Countable K1, Countable K2} {A}
(m : gmap (K1*K2) A) x y x' v :
gmap_slice (<[ (x,y) := v ]> m) x' =
if decide (x = x')
then <[ y := v ]> (gmap_slice m x')
else gmap_slice m x'.
Proof.
eapply map_eq. intros.
case_decide; subst; rewrite !gmap_slice_lookup ?lookup_insert_spec;
repeat case_decide; simplify_eq; rewrite // gmap_slice_lookup //.
Qed.
Lemma gmap_slice_delete `{Countable K1, Countable K2} {A}
(m : gmap (K1*K2) A) x y x' :
gmap_slice (delete (x,y) m) x' =
if decide (x = x')
then delete y (gmap_slice m x')
else gmap_slice m x'.
Proof.
eapply map_eq. intros.
case_decide; subst; rewrite !gmap_slice_lookup ?lookup_delete_spec;
repeat case_decide; simplify_eq; rewrite // gmap_slice_lookup //.
Qed.
Lemma gmap_slice_empty `{Countable K1, Countable K2} {A} (x : K1) :
gmap_slice (∅ : gmap (K1*K2) A) x = ∅.
Proof.
eapply map_eq. intros.
rewrite gmap_slice_lookup !lookup_empty //.
Qed.
Lemma gmap_slice_union `{Countable K1, Countable K2} {A} (m1 m2 : gmap (K1*K2) A) (x : K1) :
gmap_slice (m1 ∪ m2) x = gmap_slice m1 x ∪ gmap_slice m2 x.
Proof.
eapply map_eq. intros.
rewrite lookup_union !gmap_slice_lookup lookup_union //.
Qed.
Definition gmap_unslice `{Countable K1, Countable K2} {A} (m : gmap K2 A) (x : K1) : gmap (K1 * K2) A :=
map_kmap (λ y, (x,y)) m.
Lemma gmap_slice_unslice `{Countable K1, Countable K2} {A} (m : gmap K2 A) (x y : K1) :
gmap_slice (gmap_unslice m x) y = if decide (x = y) then m else ∅.
Proof.
eapply map_eq. intros i.
rewrite gmap_slice_lookup.
unfold gmap_unslice.
case_decide.
- subst. rewrite lookup_map_kmap //.
- rewrite lookup_empty lookup_map_kmap_None.
intros; simplify_eq.
Qed.
Lemma imap_fin_list {A B} n (g : nat -> A -> B) (f : fin n -> A) :
imap g (fin_list n f) = fin_list n (λ i, g (fin_to_nat i) (f i)).
Proof.
eapply list_eq. intros.
rewrite list_lookup_imap.
destruct (decide (i < n)) as [H|H].
- rewrite -(fin_to_nat_to_fin _ _ H).
rewrite !fin_list_lookup //.
- rewrite !fin_list_lookup_ne //; lia.
Qed.
Lemma list_to_mapi_imap {A} (xs : list A) :
list_to_mapi xs = list_to_map (imap (λ i a, (i,a)) xs).
Proof.
apply map_eq. intros.
rewrite list_to_mapi_lookup.
destruct (list_to_map (imap (λ (i0 : nat) (a : A), (i0, a)) xs) !! i) eqn:E.
- eapply elem_of_list_to_map_2 in E.
eapply elem_of_lookup_imap_1 in E as (j & y & H1 & H2).
by simplify_eq.
- eapply not_elem_of_list_to_map_2 in E.
rewrite fmap_imap in E.
rewrite ->elem_of_lookup_imap in E.
destruct (xs !! i) eqn:F; eauto.
exfalso. apply E. eauto.
Qed.
Definition fin_multiset {A} n (f : fin n -> A) : multiset A :=
list_to_multiset (fin_list n f).
Lemma fin_multiset_gmap {A:ofe} n (f : fin n -> A) :
fin_multiset n (λ m, (fin_to_nat m, f m)) ≡ map_to_multiset (fin_gmap n f).
Proof.
unfold fin_multiset, fin_gmap, map_to_multiset. simpl.
rewrite list_to_mapi_imap map_to_list_to_map.
- rewrite imap_fin_list //.
- rewrite fmap_imap NoDup_alt. intros ???.
rewrite !list_lookup_imap.
destruct (fin_list n f !! i) eqn:E; last naive_solver.
destruct (fin_list n f !! j) eqn:F; naive_solver.
Qed.
Lemma fin_list_0 {A} (f : fin 0 -> A) : fin_list 0 f = [].
Proof. done. Qed.
Lemma fin_gset_0 `{Countable A} (f : fin 0 -> A) : fin_gset 0 f = ∅.
Proof. done. Qed.
Lemma fin_gmap_0 {A} (f : fin 0 -> A) : fin_gmap 0 f = ∅.
Proof. done. Qed.
Lemma fin_multiset_0 {A : ofe} (f : fin 0 -> A) : fin_multiset 0 f = ε.
Proof. done. Qed.
Lemma fin_union_0 `{Countable A} (f : fin 0 -> gset A) : fin_union 0 f = ∅.
Proof. done. Qed.
Lemma fin_list_S {A} n (f : fin (S n) -> A) :
fin_list (S n) f = f 0%fin :: fin_list n (λ i, f (FS i)).
Proof. done. Qed.
Lemma fin_gset_S `{Countable A} n (f : fin (S n) -> A) :
fin_gset (S n) f = {[ f 0%fin ]} ∪ fin_gset n (λ i, f (FS i)).
Proof. done. Qed.
Lemma fin_gmap_dom {A} n (f : fin n -> A) (k : nat) :
k ∈ dom (fin_gmap n f) <-> k < n.
Proof.
rewrite elem_of_dom.
destruct (decide (k < n)) as [H|H].
- rewrite -(fin_to_nat_to_fin _ _ H).
rewrite fin_gmap_lookup.
erewrite !fin_to_nat_to_fin. naive_solver.
- rewrite fin_gmap_lookup_ne; last lia.
split; intros; try lia.
destruct H0. discriminate.
Qed.
Lemma fin_multiset_S {A : ofe} n (f : fin (S n) -> A) :
fin_multiset (S n) f = {[ f 0%fin ]} ⋅ fin_multiset n (λ i, f (FS i)).
Proof. done. Qed.
Lemma big_union_empty `{Countable A} :
big_union (∅ : gset (gset A)) = ∅.
Proof. done. Qed.
Lemma big_union_singleton `{Countable A} (a : gset A) :
big_union {[ a ]} = a.
Proof.
unfold big_union.
rewrite set_fold_singleton right_id_L //.
Qed.
Lemma big_union_singleton_union `{Countable A} (a : gset A) (b : gset (gset A)) :
big_union ({[ a ]} ∪ b) = a ∪ big_union b.
Proof.
destruct (decide (a ∈ b)) as [Q|Q].
- rewrite subseteq_union_1_L; last rewrite singleton_subseteq_l //.
eapply set_eq. intros.
rewrite elem_of_union.
rewrite !elem_of_big_union.
set_solver.
- unfold big_union.
assert (a ∪ set_fold union ∅ b =
set_fold union (set_fold union ∅ b) ({[ a ]} : gset (gset A))) as ->.
{ rewrite set_fold_singleton //. }
rewrite -set_fold_disj_union; last set_solver.
rewrite comm_L //.
Qed.
Lemma big_union_union `{Countable A} (a b : gset (gset A)) :
big_union (a ∪ b) = big_union a ∪ big_union b.
Proof.
revert b. induction a using set_ind_L; intros.
- rewrite big_union_empty !left_id_L //.
- rewrite -assoc_L !big_union_singleton_union IHa assoc_L //.
Qed.
Lemma fin_union_S `{Countable A} n (f : fin (S n) -> gset A) :
fin_union (S n) f = (f 0%fin) ∪ fin_union n (λ i, f (FS i)).
Proof.
unfold fin_union.
rewrite fin_gset_S big_union_union big_union_singleton //.
Qed.
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright (c) 2016, Perry L Miller IV
% All rights reserved.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Discussion about bullets.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Bullets}
\label{sec:discussion_bullets}
% Start some bullets.
\begin{itemize}
\item All work and no play makes Jack a dull boy.
All work and no play makes Jack a dull boy.
\item All work and no play makes Jack a dull boy.
All work and no play makes Jack a dull boy.
% End the bullets.
\end{itemize}
|
/-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.limits.shapes.finite_products
import Mathlib.category_theory.limits.shapes.binary_products
import Mathlib.category_theory.limits.preserves.shapes.products
import Mathlib.category_theory.limits.preserves.shapes.binary_products
import Mathlib.category_theory.limits.shapes.pullbacks
import Mathlib.category_theory.pempty
import Mathlib.data.equiv.fin
import Mathlib.PostPort
universes v u u'
namespace Mathlib
/-!
# Constructing finite products from binary products and terminal.
If a category has binary products and a terminal object then it has finite products.
If a functor preserves binary products and the terminal object then it preserves finite products.
# TODO
Provide the dual results.
Show the analogous results for functors which reflect or create (co)limits.
-/
namespace category_theory
/--
Given `n+1` objects of `C`, a fan for the last `n` with point `c₁.X` and a binary fan on `c₁.X` and
`f 0`, we can build a fan for all `n+1`.
In `extend_fan_is_limit` we show that if the two given fans are limits, then this fan is also a
limit.
-/
@[simp] theorem extend_fan_X {C : Type u} [category C] {n : ℕ} {f : ulift (fin (n + 1)) → C} (c₁ : limits.fan fun (i : ulift (fin n)) => f (ulift.up (fin.succ (ulift.down i)))) (c₂ : limits.binary_fan (f (ulift.up 0)) (limits.cone.X c₁)) : limits.cone.X (extend_fan c₁ c₂) = limits.cone.X c₂ :=
Eq.refl (limits.cone.X (extend_fan c₁ c₂))
/--
Show that if the two given fans in `extend_fan` are limits, then the constructed fan is also a
limit.
-/
def extend_fan_is_limit {C : Type u} [category C] {n : ℕ} (f : ulift (fin (n + 1)) → C) {c₁ : limits.fan fun (i : ulift (fin n)) => f (ulift.up (fin.succ (ulift.down i)))} {c₂ : limits.binary_fan (f (ulift.up 0)) (limits.cone.X c₁)} (t₁ : limits.is_limit c₁) (t₂ : limits.is_limit c₂) : limits.is_limit (extend_fan c₁ c₂) :=
limits.is_limit.mk
fun (s : limits.cone (discrete.functor f)) =>
subtype.val
(limits.binary_fan.is_limit.lift' t₂ (nat_trans.app (limits.cone.π s) (ulift.up 0))
(limits.is_limit.lift t₁
(limits.cone.mk (limits.cone.X s)
(discrete.nat_trans
fun (i : discrete (ulift (fin n))) =>
nat_trans.app (limits.cone.π s) (ulift.up (fin.succ (ulift.down i)))))))
/--
If `C` has a terminal object and binary products, then it has a product for objects indexed by
`ulift (fin n)`.
This is a helper lemma for `has_finite_products_of_has_binary_and_terminal`, which is more general
than this.
-/
/--
If `C` has a terminal object and binary products, then it has limits of shape
`discrete (ulift (fin n))` for any `n : ℕ`.
This is a helper lemma for `has_finite_products_of_has_binary_and_terminal`, which is more general
than this.
-/
/-- If `C` has a terminal object and binary products, then it has finite products. -/
theorem has_finite_products_of_has_binary_and_terminal {C : Type u} [category C] [limits.has_binary_products C] [limits.has_terminal C] : limits.has_finite_products C := sorry
/--
If `F` preserves the terminal object and binary products, then it preserves products indexed by
`ulift (fin n)` for any `n`.
-/
def preserves_fin_of_preserves_binary_and_terminal {C : Type u} [category C] {D : Type u'} [category D] (F : C ⥤ D) [limits.preserves_limits_of_shape (discrete limits.walking_pair) F] [limits.preserves_limits_of_shape (discrete pempty) F] [limits.has_finite_products C] (n : ℕ) (f : ulift (fin n) → C) : limits.preserves_limit (discrete.functor f) F :=
sorry
/--
If `F` preserves the terminal object and binary products, then it preserves limits of shape
`discrete (ulift (fin n))`.
-/
def preserves_ulift_fin_of_preserves_binary_and_terminal {C : Type u} [category C] {D : Type u'} [category D] (F : C ⥤ D) [limits.preserves_limits_of_shape (discrete limits.walking_pair) F] [limits.preserves_limits_of_shape (discrete pempty) F] [limits.has_finite_products C] (n : ℕ) : limits.preserves_limits_of_shape (discrete (ulift (fin n))) F :=
limits.preserves_limits_of_shape.mk
fun (K : discrete (ulift (fin n)) ⥤ C) =>
let this : discrete.functor (functor.obj K) ≅ K :=
discrete.nat_iso
fun (i : discrete (discrete (ulift (fin n)))) => iso.refl (functor.obj (discrete.functor (functor.obj K)) i);
limits.preserves_limit_of_iso_diagram F this
/-- If `F` preserves the terminal object and binary products then it preserves finite products. -/
def preserves_finite_products_of_preserves_binary_and_terminal {C : Type u} [category C] {D : Type u'} [category D] (F : C ⥤ D) [limits.preserves_limits_of_shape (discrete limits.walking_pair) F] [limits.preserves_limits_of_shape (discrete pempty) F] [limits.has_finite_products C] (J : Type v) [fintype J] : limits.preserves_limits_of_shape (discrete J) F :=
trunc.rec_on_subsingleton (fintype.equiv_fin J)
fun (e : J ≃ fin (fintype.card J)) =>
limits.preserves_limits_of_shape_of_equiv
(equivalence.symm (discrete.equivalence (equiv.trans e (equiv.symm equiv.ulift)))) F
|
C----------------------------------------------------------------------
subroutine ftgpfe(iunit,group,felem,nelem,
& array,flgval,anynul,status)
C Read an array of r*4 values from the primary array.
C Data conversion and scaling will be performed if necessary
C (e.g, if the datatype of the FITS array is not the same
C as the array being read).
C Undefined elements will have the corresponding element of
C FLGVAL set equal to .true.
C ANYNUL is return with a value of .true. if any pixels were undefined.
C iunit i Fortran unit number
C group i number of the data group, if any
C felem i the first pixel to be read (this routine treats
C the primary array a large one dimensional array of
C values, regardless of the actual dimensionality).
C nelem i number of data elements to be read
C array r returned array of values that were read
C flgval l set to .true. if the corresponding element is undefined
C anynul l set to .true. if any returned elements are undefined
C status i returned error stataus
C written by Wm Pence, HEASARC/GSFC, June 1991
integer iunit,group,felem,nelem,status,row
real nulval,array(*)
logical anynul,flgval(*)
integer i
do 10 i=1,nelem
flgval(i)=.false.
10 continue
C the primary array is represented as a binary table:
C each group of the primary array is a row in the table,
C where the first column contains the group parameters
C and the second column contains the image itself
row=max(1,group)
call ftgcle(iunit,2,row,felem,nelem,1,2,nulval,
& array,flgval,anynul,status)
end
|
\section{Background}
\label{s:background}
%
In this section, we review the foundations on which \sys is built.
%
In \autoref{sec:logic}, we review definitions from formal logic; %
in \autoref{sec:rtlc}, we define a $\lambda$-calculus with refinement
types; %
in \autoref{sec:chcs}, we define systems of Constrained Horn Clauses.
% formal logic:
\subsection{Formal logic}
\label{sec:logic}
%
\sys uses logic to express and infer refinement types of programs.
%
All objects defined in this paper are defined over a fixed space of
logical variables $X$.
%
In particular, for theory $\mathcal{T}$, the space of $\mathcal{T}$
formulas over $X$ is denoted $\tformulas{\mathcal{T}}$.
%
For each formula $\varphi \in \tformulas{\mathcal{T}}$, the set of
variables that occur in $\varphi$ (i.e., the \emph{vocabulary} of
$\varphi$) is denoted $\vocab(\varphi)$.
% define models, satisfaction, entailment
For formulas $\varphi_0, \ldots, \varphi_n, \varphi \in
\tformulas{\mathcal{T}}$, the fact that $\varphi_0, \ldots, \varphi_n$
\emph{entail} $\varphi$ is denoted $\varphi_0, \ldots, \varphi_n
\entails \varphi$.
% Define replacement and substitution:
For sequences of variables $Y = [ y_0, \ldots, y_n ]$ and $Z = [ z_0,
\ldots, z_n ]$, the $\mathcal{T}$ formula constraining the equality of
each element in $Y$ with its corresponding element in $Z$, i.e., the
formula $\bigland_{0 \leq i \leq n} y_i = z_i$, is denoted $Y = Z$.
%
The repeated replacement of variables $\varphi[ z_0 / y_0 \ldots z_{n}
/ y_{n} ]$ is denoted $\replace{\varphi}{Y}{Z}$.
%
For each formula $\varphi$ defined over free variables $Y$,
$\replace{\varphi}{Y}{Z}$ is denoted alternatively as $\varphi[ Z ]$.
%
The number of free variables in formula $\varphi$ is denoted
$\degreeof{\varphi}$.
\subsection{A $\lambda$-calculus with refinement types}
\label{sec:rtlc}
\begin{figure*}[t]
\begin{floatrow}[2]
\ffigbox[.48\textwidth] %
{ \caption{The space of program expressions, $\expr$.} %
\label{fig:exprs} }
{ \begin{align*}
% expression is a constant,
e \rightarrow &\ c \\
% or a variable,
| &\ x \\
% or a binary operation,
| &\ e \oplus e \\
% or a constructor application,
| &\ C(e_0, \ldots, e_k) \\
% or case split,
| &\ \cc{match}\ e\ \cc{with}\ %
C_0(\overline{x}_0)\ \cc{->}\ e_0 %
\ldots %
C_k(\overline{x}_k)\ \cc{->}\ e_k \\
% or an abstraction,
| &\ \lambda x.\ e \\
% or an application,
| &\ e\ e \\
% or a fixpoint,
| &\ \fix{ f }{ e }
\end{align*} }
%
\ffigbox[.48\textwidth] %
{\caption{The space of types, $\types$.
%
Metavariable $\tau$ ranges over $\types$, %
$x_i$ and $y_i$ range over individual value variables, %
$\overline{x}$ range over vectors of value variables, and %
$X$ ranges over type variables.} %
\label{fig:types} }
%
{ \begin{align*} %
% a type is a base type,
\tau \rightarrow &\ \setformer{ \nu : \bools }{ \varphi } \\
| &\ \setformer{ \nu : \ints}{ \varphi } \\
% a type variable,
| &\ X \overline{x} \\
% a function type, or
| &\ x : \tau \rightarrow \tau \\
% a recursive type
| &\ \mu X \overline{x}.\ %
C_0(y_0^0 : \tau_0^0, \ldots, %
y_0^{ \arityof{C_0} } : \tau_0^{ \arityof{C_0} }), %
\ldots, \\
&\ C_n(y_n^0 : \tau_n^0, \ldots, %
y_n^{ \arityof{C_n} } : \tau_n^{ \arityof{C_n} })
\end{align*} }
\end{floatrow}
\end{figure*}
% define STLC syntax:
\paragraph{Syntax}
% define spaces:
\autoref{fig:exprs} defines the space of
simply-typed $\lambda$-calculus expressions, $\expr$.
%
For the remainder of this paper, metavariable $e$ ranges over
$\expr$, %
$c$ ranges over constants, %
$\oplus$ ranges over binary operators, $x$ and $f$ range over
program variables, and $C$ ranges over constructor symbols.
%
Each constructor symbol $C$ is mapped to a fixed cardinality, denoted
$|C| \in \nats$.
% define expressions:
An expression is a Boolean or integer constant, %
a variable (drawn from space of variables $\vars$), %
an application of an fixed operator to a pair of expressions, %
an application of a constructor to a sequence of expressions, %
a match expression, %
a $\lambda$-abstraction, %
an application, or %
a fixpoint expression.
%
For each $e \in \expr$, the \emph{free-variables} of $e$ are denoted
$\freevars(e)$.
%
A \emph{refinement-typed $\lambda$-calculus (RTLC)} \emph{program} is
a closed expression---i.e., an expression $e$ such that $\freevars(e)
= \emptyset$.
%
The space of RTLC programs is denoted $\rtlc$.
%
For $P \in \rtlc$, the set of all subexpressions of $P$ is denoted
$\subexps(P)$.
% define semantics:
\paragraph{Semantics}
%
\begin{figure*}
\centering
\begin{gather*}
% evaluate const:
\inference[ CONST ]{ }{ \Gamma \judges c \evalsto c }
% evaluate variable:
\inference[ VAR ]{ }{ \Gamma \judges x \evalsto \Gamma(x) }
% evaluate binary operations:
\inference[ OP ]{ %
\Gamma \judges e_0 \evalsto v_0 & %
\Gamma \judges e_1 \evalsto v_1 } %
{ \Gamma \judges e_0 \oplus e_1 \evalsto v_0 \oplus v_1 } \\ \\
% evaluate constructor application:
\inference[ CONS ]{ %
\Gamma \judges e_0 \evalsto v_0 & \ldots & %
\Gamma \judges e_k \evalsto v_k } %
{ \Gamma \judges C(e_0, \ldots, e_k) \evalsto C(v_0, \ldots, v_k) }
% evaluate if-then-else by then branch
\inference[ $\mathrm{MATCH}_{i}$ ]{ %
\Gamma \judges e \evalsto C_i(v_0, \ldots, v_{ |C_i| }) & %
X_i = x_1, \ldots, x_{|C_i|} \\ %
\Gamma[ x_0 \mapsto v_0, \ldots, x_{|C_i|} \mapsto v_{|C_i|} ]
\judges %
e_i \evalsto v' } %
{ \Gamma \judges \cc{match}\ e\ \cc{with}\ %
C_0(X_0)\ \cc{->}\ e_0 %
\ldots %
C_k(X_k)\ \cc{->}\ e_k \evalsto v' } \\ \\
% evaluate an abstraction:
\inference[ ABS ]{ } %
{ \Gamma \judges \lambda x.\ e \evalsto \lambda x.\ e }
% apply a lambda:
\inference[ APP-ABS ]{ %
\Gamma \judges e_0 \evalsto \lambda x.\ e_0' & %
\Gamma \judges e_1 \evalsto v_1 & %
\upd{\Gamma}{x}{v_1} \judges e_0' \evalsto v }
{ \Gamma \judges e_0\ e_1 \evalsto v } \\ \\
% evaluate a fix:
\inference[ FIX ]{ } %
{ \Gamma \judges \fix{ f }{ e } \evalsto \fix{ f }{ e } }
% apply a fixpoint:
\inference[ APP-FIX ]{ %
\Gamma \judges e_0 \evalsto \fix{ f }{ e_0' } & %
\upd{ \Gamma }{ f }{ \fix{ f }{ e_0' } } \judges %
e_0'\ e_1 \evalsto v }
{ \Gamma \judges e_0\ e_1 \evalsto v }
\end{gather*}
\caption{The natural semantics of $\rtlc$.}
\label{fig:nat-sem}
\end{figure*}
%
A value is a Boolean, an integer, a $\lambda$ abstraction, a fixpoint
abstraction, or a constructor applied to a sequence of values;
%
the space of values is denoted $\values$.
%
The semantics of $\rtlc$ is defined by a natural semantics that
relates expressions to values, given in \autoref{fig:nat-sem}.
%
For $e \in \expr$ and $v \in \values$, the fact that $e$
\emph{evaluates} to $v$ is denoted $e \evalsto v$.
\paragraph{Typing}
%
Each expression has types that describe the spaces of values that it
takes as input and the spaces of values to which it evaluates.
%
The space of types, defined over a space of type variable $\typevars$
is given in \autoref{fig:types}.
%
A type is either a refined Boolean value, %
a refined Integer value, %
a type vector applied to a vector of value variables, %
%
\BH{does this also need to have a refinement?}
%
a function over types, %
%
or a recursive type, defined over a type parameter $X$ abstracted over
a sequence of value variables $\overline{x}$.
%
For each $\tau \in \types$, the free value variables and free type
variables of $\tau$, denoted $\freevaluevars(\tau) \subseteq \vars$
and $\freetypevars(\tau) \subseteq \typevars$, are the value variables
and type variables that occur in $\tau$ that are not bound in a
recursive type definition.
%
$\tau$ is \emph{well-formed} if $\freevars(\tau) = \emptyset$.
%
Note that $\tau$ may contain occurrences of free value variables.
% introduce has-type symbol:
For expression $e \in \expr$ and type $\tau \in \types$, the fact that
$e$ has type $\tau$ is denoted $e \hastype \tau$.
%
The definition of the has-type relation is standard.
% define base types:
A type $\tau$ in which the only formula is that occurs in a component
type of $\tau$ is $\true$ is a \emph{base} type, denoted
$\basetype(\tau)$.
%
Each expression that has a type has a unique base type, which can be
inferred automatically by a conventional type-inference algorithm,
such as Hindley-Milner algorithm.
%
\sys assumes access to an algorithm that, given $e \in \expr$,
computes $\basetype(\tau)$.
%
\BH{extend this to give base type of all free variables of an
expression}
% problem statement
The problem that we address in this paper is, given program $P \in
\rtlc$ and well-formed $\tau \in \types$, to determine if $P \hastype
\tau$.
\paragraph{Symbolic encoding of semantics}
%
The semantics of $\rtlc$ is represented symbolically using \lia
formulas.
%
\BH{hoist defn of disjoint copies of variables for expressions}
%
In particular, for each $e \in \expr$ with subexpressions $e_0,
\ldots, e_n \in \expr$, there is some $\varphi \in \formulas{\vars[e],
\vars[e_0], \ldots, \vars[e_n]}$ such that
\BH{merge updated defn from current draft of equivalence paper}
% define CHC's:
\subsection{Constrained Horn Clauses}
\label{sec:chcs}
\subsubsection{Structure}
% definition of CHC
A Constrained Horn Clause is a body, consisting of a conjunctive set
of uninterpreted relational predicates and a constraint, and a head
relational predicate.
%
Relational predicates are predicate symbols paired with a map from
each symbol to its arity.
%
\begin{defn}
\label{defn:rel-preds}
For each space of symbols $\mathcal{R}$ and function $a: \mathcal{R}
\to \nats$, $(\mathcal{R}, a)$ is a space of \emph{relational
predicates}.
\end{defn}
%
The space of all relational predicates is denoted $\relpreds$.
%
For each space of relational predicates $\mathcal{R} \in \relpreds$,
we denote the predicate symbols and arity of $\mathcal{R}$ as
$\relsof{\mathcal{R}}$ and $\arityof{\mathcal{R}}$, respectively.
%
For relational predicates $\mathcal{R} \in \relpreds$ and symbol $R$,
we denote $R \in \relsof{ \mathcal{R} }$ alternatively as $R \in
\mathcal{R}$.
%
All definitions introduced in this section are given over a fixed,
arbitrary set of relational-predicate symbols $\mathcal{R}$.
% define applications of relational predicates:
An application of a relational predicate is a relational-predicate
symbol $R$ paired with a sequence of variables of length equal to the
arity of $R$.
%
\begin{defn}
\label{defn:pred-apps}
For $R \in \mathcal{R}$ and sequence of variables $Y \in X^{*}$ such
that $|Y| = \arityof{\mathcal{R}}(R)$, $(R, Y)$ is an
\emph{application}.
\end{defn}
%
The space of applications is denoted $\apps{\mathcal{R}}$.
%
For each application $A \in \apps{\mathcal{R}}$, the predicate symbol
and argument sequence of $A$ are denoted $\relof{A}$ and $\argsof{A}$
respectively.
% define CHC:
A Constrained Horn Clause is a body of applications, a constraint, and
a head application.
%
\begin{defn}
\label{defn:chcs-structure}
For $\mathcal{A} \subseteq \apps{\mathcal{R}}$ and %
$\varphi \in \formulas$, $\mathcal{B} = (\mathcal{A}, \varphi)$ is a
\emph{clause body}.
%
For $H \in \apps{\mathcal{R}}$, $(\mathcal{B}, H)$ is a
\emph{Constrained Horn Clause}.
\end{defn}
% define space of bodies:
The space of clause bodies is denoted $\bodies{ \mathcal{R} } =
\pset(\apps{\mathcal{R}}) \times \formulas$.
% define space, projection:
The space of Constrained Horn Clauses is denoted $\chc{\mathcal{R}} =
\bodies{ \mathcal{R} } \times \apps{\mathcal{R}}$.
%
For each clause $\mathcal{C} \in \chc{\mathcal{R}}$, the body and head
of $\mathcal{C}$ are denoted $\bodyof{ \mathcal{C} }$ and $\headof{
\mathcal{C} }$, respectively.
% define siblings:
For each $\mathcal{S} \subseteq \chc{ \mathcal{R} }$, $\mathcal{C} \in
\mathcal{S}$, and all applications $A_0, A_1 \in \appsof{ \bodyof{
\mathcal{C} } }$, $\relof{A_0}$ and $\relof{A_1}$ are
\emph{siblings} in $\mathcal{S}$.
% define system of CHC's
We will present \sys as a solver for CHCs without recursive
definitions of predicates, represented in a normalized form.
% give conditions on normalization:
Let $\mathcal{S} \subseteq \chc{ \mathcal{R} }$ be such that %
\textbf{(1)} each relational predicate occurs in the head of some
clause, %
\textbf{(2)} each $R \in \mathcal{R}$ is applied to the same variables
$\varsof{ \mathcal{S}}(R)$ in each of its occurrences in a clause as a
head, %
\textbf{(3)} all clauses with distinct head relational predicates are
defined over disjoint spaces of variables, %
\textbf{(4)} each relational predicate occurs in each clause body in
at most one application, and %
\textbf{(5)} there is exactly one relational predicate $\queryof{
\mathcal{S} }$ that is the dependency of no relational predicate.
%
Then $\mathcal{S}$ is a \emph{normalized} recursion-free system.
%
For the remainder of this paper, we consider only normalized sets of
CHCs, and denote the space of such sets as $\chcs{\mathcal{R}}$.
\subsubsection{Solutions}
\label{sec:chc-solns}
%
A solution to a CHC system $\mathcal{S}$ is an interpretation of each
relational predicate $R$ of arity $n$ as a formula over $n$ free
variables such that for each clause $\mathcal{C} \in \mathcal{S}$, the
conjunction of interpretations of all relational predicates in the
body of $\mathcal{C}$ and the constraint of $\mathcal{C}$ entail the
interpretation of the head of $\mathcal{C}$.
%
Let a map from each $R \in \relsof{ \mathcal{R} }$ to a formula over
an ordered vector of $\arityof{ \mathcal{R} }(R)$ free variables be an
\emph{interpretation} of $\mathcal{R}$;
%
let the space of interpretations of $\mathcal{R}$ be denoted
$\interps{ \mathcal{R} }$.
%
\begin{defn}
\label{defn:chc-soln}
For $\mathcal{B} \in \bodies{ \mathcal{R} }$ and $H \in \apps{
\mathcal{R} }$, %
let $\sigma \in \interps{ \mathcal{R} }$ be such that for each $R
\in \mathcal{R}$, $\arityof{\mathcal{R}}(R) = \degreeof{\sigma(R)}$
and %
%
\[ \elts{ \sigma(\relof{ A })[ \argsof{ A } ] }_{ A \in \appsof{
\mathcal{B} } }, %
\ctrof{ \mathcal{B} } \entails %
\sigma( \relof{H} )[ \argsof{ H } ]
\]
Then $\sigma$ is a \emph{solution} of $(\mathcal{B}, H)$.
\end{defn}
% define partial solution
For $\mathcal{S} \subseteq \chc{ \mathcal{R} }$, if
% solution respects dependence order:
\textbf{(a)} for each $R \in \domain(\sigma)$ and $R' \in \mathcal{R}$
a dependence of $R$ in $\mathcal{S}$, it holds that $R' \in
\domain(\sigma)$;
%
\textbf{(b)} for each $\mathcal{C} \in \mathcal{S}$ such that
$\relof{ \headof{ \mathcal{C} } } \in \domain(\sigma)$, $\sigma$ is a
solution of $\mathcal{C}$;
%
then $\sigma$ is a \emph{partial solution} of $\mathcal{S}$.
%
If, in addition, $\sigma(\queryof{ \mathcal{S} }) \entails \false$,
then $\sigma$ is a \emph{solution} of $\mathcal{S}$.
%
%%% Local Variables:
%%% mode: latex
%%% TeX-master: "p"
%%% End:
|
lemma Re_prod_Reals: "(\<And>x. x \<in> A \<Longrightarrow> f x \<in> \<real>) \<Longrightarrow> Re (prod f A) = prod (\<lambda>x. Re (f x)) A" |
[STATEMENT]
lemma convex_on_ereal_sum_aux:
assumes "1-a>0"
shows "(1 - ereal a) * (ereal (c / (1 - a)) * b) = (ereal c) * b"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (1 - ereal a) * (ereal (c / (1 - a)) * b) = ereal c * b
[PROOF STEP]
by (metis mult.assoc mult.commute eq_divide_eq ereal_minus(1) assms
one_ereal_def less_le times_ereal.simps(1)) |
{-# OPTIONS --without-K --rewriting #-}
open import PathInduction
open import Pushout
module JamesContractibility {i} (A : Type i) (⋆A : A) where
open import JamesTwoMaps A ⋆A public
-- We do not prove the flattening lemma here, we only prove that the following pushout is contractible
T : Type i
T = Pushout (span JA JA (A × JA) snd (uncurry αJ))
⋆T : T
⋆T = inl εJ
T-contr-inl-ε : inl εJ == ⋆T
T-contr-inl-ε = idp
T-contr-inl-α : (a : A) (x : JA) → inl x == ⋆T → inl (αJ a x) == ⋆T
T-contr-inl-α a x y = push (⋆A , αJ a x) ∙ ! (ap inr (δJ (αJ a x))) ∙ ! (push (a , x)) ∙ y
T-contr-inl-δ : (x : JA) (y : inl x == ⋆T) → Square (ap inl (δJ x)) y (T-contr-inl-α ⋆A x y) idp
T-contr-inl-δ x y = & coh (ap-square inr (& cη (ηJ x))) (natural-square (λ z → push (⋆A , z)) (δJ x) idp (ap-∘ inr (αJ ⋆A) (δJ x))) where
coh : Coh ({A : Type i} {a b : A} {p : a == b} {c : A} {q q' : c == b} (q= : Square q q' idp idp)
{d : A} {r : d == c} {e : A} {s : d == e} {t : d == a} (sq : Square r t q p)
→ Square t s (p ∙ ! q' ∙ ! r ∙ s) idp)
coh = path-induction
cη : Coh ({A : Type i} {a b : A} {p : a == b} {c : A} {q : a == c} {r : b == c} (ηJ : ! p ∙ q == r) → Square p q r idp)
cη = path-induction
T-contr-inl : (x : JA) → inl x == ⋆T
T-contr-inl = JA-elim T-contr-inl-ε T-contr-inl-α (λ x y → ↓-='-from-square idp (ap-cst ⋆T (δJ x)) (square-symmetry (T-contr-inl-δ x y)))
T-contr-inr : (x : JA) → inr x == ⋆T
T-contr-inr x = ap inr (δJ x) ∙ ! (push (⋆A , x)) ∙ T-contr-inl x
T-contr-push : (a : A) (x : JA) → Square (T-contr-inl x) (push (a , x)) idp (T-contr-inr (αJ a x))
T-contr-push a x = & coh where
coh : Coh ({A : Type i} {a b : A} {r : a == b} {c : A} {p : c == b} {d : A} {q : d == c} {e : A} {y : d == e}
→ Square y q idp (p ∙ ! r ∙ (r ∙ ! p ∙ ! q ∙ y)))
coh = path-induction
T-contr : (x : T) → x == ⋆T
T-contr = Pushout-elim T-contr-inl T-contr-inr (λ {(a , x) → ↓-='-from-square (ap-idf (push (a , x))) (ap-cst ⋆T (push (a , x))) (T-contr-push a x)})
|
State Before: K : Type u
V V₁ V₂ V₃ : Type v
V' V'₁ : Type v'
V'' : Type v''
ι : Type w
ι' : Type w'
η : Type u₁'
φ : η → Type ?u.1195191
inst✝⁶ : DivisionRing K
inst✝⁵ : AddCommGroup V
inst✝⁴ : Module K V
inst✝³ : AddCommGroup V₁
inst✝² : Module K V₁
inst✝¹ : AddCommGroup V'
inst✝ : Module K V'
n : ℕ
f : V →ₗ[K] V'
⊢ ↑n ≤ rank f ↔ ∃ s, Finset.card s = n ∧ LinearIndependent K fun x => ↑f ↑x State After: K : Type u
V V₁ V₂ V₃ : Type v
V' V'₁ : Type v'
V'' : Type v''
ι : Type w
ι' : Type w'
η : Type u₁'
φ : η → Type ?u.1195191
inst✝⁶ : DivisionRing K
inst✝⁵ : AddCommGroup V
inst✝⁴ : Module K V
inst✝³ : AddCommGroup V₁
inst✝² : Module K V₁
inst✝¹ : AddCommGroup V'
inst✝ : Module K V'
n : ℕ
f : V →ₗ[K] V'
⊢ (∃ s, (∃ t, ↑t = s ∧ Finset.card t = n) ∧ LinearIndependent K fun x => ↑f ↑x) ↔
∃ s, Finset.card s = n ∧ LinearIndependent K fun x => ↑f ↑x Tactic: simp only [le_rank_iff_exists_linearIndependent, Cardinal.lift_natCast, Cardinal.lift_eq_nat_iff,
Cardinal.mk_set_eq_nat_iff_finset] State Before: K : Type u
V V₁ V₂ V₃ : Type v
V' V'₁ : Type v'
V'' : Type v''
ι : Type w
ι' : Type w'
η : Type u₁'
φ : η → Type ?u.1195191
inst✝⁶ : DivisionRing K
inst✝⁵ : AddCommGroup V
inst✝⁴ : Module K V
inst✝³ : AddCommGroup V₁
inst✝² : Module K V₁
inst✝¹ : AddCommGroup V'
inst✝ : Module K V'
n : ℕ
f : V →ₗ[K] V'
⊢ (∃ s, (∃ t, ↑t = s ∧ Finset.card t = n) ∧ LinearIndependent K fun x => ↑f ↑x) ↔
∃ s, Finset.card s = n ∧ LinearIndependent K fun x => ↑f ↑x State After: case mp
K : Type u
V V₁ V₂ V₃ : Type v
V' V'₁ : Type v'
V'' : Type v''
ι : Type w
ι' : Type w'
η : Type u₁'
φ : η → Type ?u.1195191
inst✝⁶ : DivisionRing K
inst✝⁵ : AddCommGroup V
inst✝⁴ : Module K V
inst✝³ : AddCommGroup V₁
inst✝² : Module K V₁
inst✝¹ : AddCommGroup V'
inst✝ : Module K V'
n : ℕ
f : V →ₗ[K] V'
⊢ (∃ s, (∃ t, ↑t = s ∧ Finset.card t = n) ∧ LinearIndependent K fun x => ↑f ↑x) →
∃ s, Finset.card s = n ∧ LinearIndependent K fun x => ↑f ↑x
case mpr
K : Type u
V V₁ V₂ V₃ : Type v
V' V'₁ : Type v'
V'' : Type v''
ι : Type w
ι' : Type w'
η : Type u₁'
φ : η → Type ?u.1195191
inst✝⁶ : DivisionRing K
inst✝⁵ : AddCommGroup V
inst✝⁴ : Module K V
inst✝³ : AddCommGroup V₁
inst✝² : Module K V₁
inst✝¹ : AddCommGroup V'
inst✝ : Module K V'
n : ℕ
f : V →ₗ[K] V'
⊢ (∃ s, Finset.card s = n ∧ LinearIndependent K fun x => ↑f ↑x) →
∃ s, (∃ t, ↑t = s ∧ Finset.card t = n) ∧ LinearIndependent K fun x => ↑f ↑x Tactic: constructor State Before: case mp
K : Type u
V V₁ V₂ V₃ : Type v
V' V'₁ : Type v'
V'' : Type v''
ι : Type w
ι' : Type w'
η : Type u₁'
φ : η → Type ?u.1195191
inst✝⁶ : DivisionRing K
inst✝⁵ : AddCommGroup V
inst✝⁴ : Module K V
inst✝³ : AddCommGroup V₁
inst✝² : Module K V₁
inst✝¹ : AddCommGroup V'
inst✝ : Module K V'
n : ℕ
f : V →ₗ[K] V'
⊢ (∃ s, (∃ t, ↑t = s ∧ Finset.card t = n) ∧ LinearIndependent K fun x => ↑f ↑x) →
∃ s, Finset.card s = n ∧ LinearIndependent K fun x => ↑f ↑x State After: case mp.intro.intro.intro.intro
K : Type u
V V₁ V₂ V₃ : Type v
V' V'₁ : Type v'
V'' : Type v''
ι : Type w
ι' : Type w'
η : Type u₁'
φ : η → Type ?u.1195191
inst✝⁶ : DivisionRing K
inst✝⁵ : AddCommGroup V
inst✝⁴ : Module K V
inst✝³ : AddCommGroup V₁
inst✝² : Module K V₁
inst✝¹ : AddCommGroup V'
inst✝ : Module K V'
f : V →ₗ[K] V'
t : Finset V
si : LinearIndependent K fun x => ↑f ↑x
⊢ ∃ s, Finset.card s = Finset.card t ∧ LinearIndependent K fun x => ↑f ↑x Tactic: rintro ⟨s, ⟨t, rfl, rfl⟩, si⟩ State Before: case mp.intro.intro.intro.intro
K : Type u
V V₁ V₂ V₃ : Type v
V' V'₁ : Type v'
V'' : Type v''
ι : Type w
ι' : Type w'
η : Type u₁'
φ : η → Type ?u.1195191
inst✝⁶ : DivisionRing K
inst✝⁵ : AddCommGroup V
inst✝⁴ : Module K V
inst✝³ : AddCommGroup V₁
inst✝² : Module K V₁
inst✝¹ : AddCommGroup V'
inst✝ : Module K V'
f : V →ₗ[K] V'
t : Finset V
si : LinearIndependent K fun x => ↑f ↑x
⊢ ∃ s, Finset.card s = Finset.card t ∧ LinearIndependent K fun x => ↑f ↑x State After: no goals Tactic: exact ⟨t, rfl, si⟩ State Before: case mpr
K : Type u
V V₁ V₂ V₃ : Type v
V' V'₁ : Type v'
V'' : Type v''
ι : Type w
ι' : Type w'
η : Type u₁'
φ : η → Type ?u.1195191
inst✝⁶ : DivisionRing K
inst✝⁵ : AddCommGroup V
inst✝⁴ : Module K V
inst✝³ : AddCommGroup V₁
inst✝² : Module K V₁
inst✝¹ : AddCommGroup V'
inst✝ : Module K V'
n : ℕ
f : V →ₗ[K] V'
⊢ (∃ s, Finset.card s = n ∧ LinearIndependent K fun x => ↑f ↑x) →
∃ s, (∃ t, ↑t = s ∧ Finset.card t = n) ∧ LinearIndependent K fun x => ↑f ↑x State After: case mpr.intro.intro
K : Type u
V V₁ V₂ V₃ : Type v
V' V'₁ : Type v'
V'' : Type v''
ι : Type w
ι' : Type w'
η : Type u₁'
φ : η → Type ?u.1195191
inst✝⁶ : DivisionRing K
inst✝⁵ : AddCommGroup V
inst✝⁴ : Module K V
inst✝³ : AddCommGroup V₁
inst✝² : Module K V₁
inst✝¹ : AddCommGroup V'
inst✝ : Module K V'
f : V →ₗ[K] V'
s : Finset V
si : LinearIndependent K fun x => ↑f ↑x
⊢ ∃ s_1, (∃ t, ↑t = s_1 ∧ Finset.card t = Finset.card s) ∧ LinearIndependent K fun x => ↑f ↑x Tactic: rintro ⟨s, rfl, si⟩ State Before: case mpr.intro.intro
K : Type u
V V₁ V₂ V₃ : Type v
V' V'₁ : Type v'
V'' : Type v''
ι : Type w
ι' : Type w'
η : Type u₁'
φ : η → Type ?u.1195191
inst✝⁶ : DivisionRing K
inst✝⁵ : AddCommGroup V
inst✝⁴ : Module K V
inst✝³ : AddCommGroup V₁
inst✝² : Module K V₁
inst✝¹ : AddCommGroup V'
inst✝ : Module K V'
f : V →ₗ[K] V'
s : Finset V
si : LinearIndependent K fun x => ↑f ↑x
⊢ ∃ s_1, (∃ t, ↑t = s_1 ∧ Finset.card t = Finset.card s) ∧ LinearIndependent K fun x => ↑f ↑x State After: no goals Tactic: exact ⟨s, ⟨s, rfl, rfl⟩, si⟩ |
State Before: C : Type u₁
inst✝³ : Category C
J : Type u
inst✝² : Category J
j : J
I : IsTerminal j
F : J ⥤ C
inst✝¹ : HasLimit F
inst✝ : ∀ (i j : J) (f : i ⟶ j), IsIso (F.map f)
⊢ limit.π F j ≫ limit.lift F (coneOfDiagramTerminal I F) = 𝟙 (limit F) State After: case w
C : Type u₁
inst✝³ : Category C
J : Type u
inst✝² : Category J
j : J
I : IsTerminal j
F : J ⥤ C
inst✝¹ : HasLimit F
inst✝ : ∀ (i j : J) (f : i ⟶ j), IsIso (F.map f)
j✝ : J
⊢ (limit.π F j ≫ limit.lift F (coneOfDiagramTerminal I F)) ≫ limit.π F j✝ = 𝟙 (limit F) ≫ limit.π F j✝ Tactic: ext State Before: case w
C : Type u₁
inst✝³ : Category C
J : Type u
inst✝² : Category J
j : J
I : IsTerminal j
F : J ⥤ C
inst✝¹ : HasLimit F
inst✝ : ∀ (i j : J) (f : i ⟶ j), IsIso (F.map f)
j✝ : J
⊢ (limit.π F j ≫ limit.lift F (coneOfDiagramTerminal I F)) ≫ limit.π F j✝ = 𝟙 (limit F) ≫ limit.π F j✝ State After: no goals Tactic: simp State Before: C : Type u₁
inst✝³ : Category C
J : Type u
inst✝² : Category J
j : J
I : IsTerminal j
F : J ⥤ C
inst✝¹ : HasLimit F
inst✝ : ∀ (i j : J) (f : i ⟶ j), IsIso (F.map f)
⊢ limit.lift F (coneOfDiagramTerminal I F) ≫ limit.π F j = 𝟙 (F.obj j) State After: no goals Tactic: simp |
```python
from controleII import digital
from lcapy.discretetime import z, n
from lcapy import s,exp
from control import tf
```
```python
# Questão 1
Xz = (10 * z + 5) / ((z-1) * (z-0.2))
teste = digital(Xz)
display(teste.izt())
print(teste.calcn())
```
```python
# Questão 2
Xz = 1 + 2*z**-1 + 3*z**-2 + 4 *z **-3
teste = digital(Xz)
display(teste.izt())
print(teste.calcn())
```
```python
# Questão 4
Xz = (z**2 + z + 2) / ((z-1)* (z**2 -z + 1))
Q4 = digital(Xz=Xz)
display(Q4.izt())
Q4.calcn()
```
```python
# Questão 5
Xz = (2*z**3 + z) / ((z-2)**2 * (z-1))
Q5 = digital(Xz = Xz)
display(Q5.izt())
```
```python
# Questão 6
Xz1 = 9 / (z * (1-2*z**-1)**2)
Xz2 = z / (z - 2)
Xz3 = 3*z / (z - 1)
Xz = Xz1 + Xz2 + Xz3
teste = digital(Xz)
display(teste.izt())
```
```python
# Questão 7
Xz = (z+2) / (z**2 * (z-2))
Q7 = digital(Xz = Xz)
display(Q7.izt())
```
```python
# Questão 13:
gs = 1 / (s * (s + 1))
gsc = tf([1], [1, 1])
teste = digital(Gs = gs, Gsc = gsc, tau=1)
display(teste.s2t())
display(teste.s2z())
```
```python
# questão 14
gss = 4 / (s * (s+2))
gsc = tf(4, [1, 2])
tau = .1
Q14 = digital(Gs=gss, Gsc=gsc, tau = .1)
display(Q14.s2t())
display(Q14.s2z())
fz, time, mag = Q14.Fz(20)
display(fz, time, mag)
```
```python
# questão 16
gss = 10 / (s + 10*s**2)
gsc = tf([10], [10, 1])
tau = 2
Q16 = digital(Gs=gss, Gsc=gsc, tau = 2)
display(Q16.s2z())
display(Q16.s2t())
fz, time, mag = Q16.Fz(14, fb = 0.05, plot=True)
display(fz, mag)
```
```python
g1s = 2 * (s - 6.93) / (s - 1) * (1 / (s * (s+1)))
gsc = tf(1, [1, 1]) #* 2* tf([1, -6.93], [1, -1])
tau = .1
Q17 = digital(Gs=g1s, Gsc=gsc, tau = tau)
display(Q17.s2z())
fz, time, mag = Q17.Fz(30, plot=True, save=True, title='Resposta ao degrau unitário sem o controlador')
display(fz)
```
```python
Xz = (0.130976*z - 0.26969) / (z**2 - 1.879029*z + 0.7303) * (z / (z-1))
C = N(Xz.partfrac())
C
```
```python
from sympy import solve, var, N
var('u')
a =(u**2 - 2.01*u + 1) * u/(u-1)
solve(u, a)
```
```python
from sympy import var
from sympy import solve
k = var('k')
W = var('W')
t = (2 + W) / (2 - W)
Xz = k/(z-1) - ((1-exp(-1))/(z- exp(-1)))*k
#Xz = Xz.subs(z, t)
F = Xz/(Xz + 1)
G = F.simplify().as_numer_denom()[1]
G.subs(k, 25)
```
|
subsection \<open>Create Consistent\label{sec:create_consistent}\<close>
theory CreateConsistent
imports CreateAlgorithms Consistency
begin
lemma nth_visible_eff:
assumes "nth_visible s n = Inr i"
shows "extended_to_set i \<subseteq> I ` set s"
proof -
have "i \<in> set (ext_ids (filter is_visible s))"
apply (cases "n < length (ext_ids (filter is_visible s))")
using assms by auto
thus ?thesis
apply (simp add: ext_ids_def)
using extended.inject by auto
qed
lemma subset_mono:
assumes "N \<subseteq> M"
shows "I ` insert_messages N \<subseteq> I ` insert_messages M"
proof -
have "insert_messages N \<subseteq> insert_messages M" using assms
by (metis (no_types, lifting) Collect_mono_iff insert_messages_def subsetCE)
thus ?thesis by (simp add: image_mono)
qed
lemma deps_insert:
assumes "\<Union> (deps ` M) \<subseteq> (I ` insert_messages M)"
assumes "deps m \<subseteq> I ` insert_messages M"
shows "\<Union> (deps ` (M \<union> {m})) \<subseteq> (I ` insert_messages (M \<union> {m}))"
proof -
have "deps m \<subseteq> I ` insert_messages (M \<union> {m})" using assms(2) subset_mono
by (metis Un_upper1 order_trans)
thus ?thesis using assms(1) apply (simp)
by (meson rev_subsetD subsetI subset_insertI subset_mono)
qed
lemma wf_add:
fixes m :: "('\<I>,'\<Sigma>) insert_message"
assumes "wfP (depends_on M)"
assumes "\<And>n. n \<in> (M \<union> {m}) \<Longrightarrow> I m \<notin> deps (Insert n)"
assumes "m \<notin> M"
shows "wfP (depends_on (M \<union> {m}))"
proof -
have "\<And>Q. Q \<noteq> {} \<Longrightarrow> (\<exists>z\<in>Q. \<forall>y. (y \<in> M \<union> {m}) \<and> (z \<in> M \<union> {m}) \<and>
I y \<in> deps (Insert z) \<longrightarrow> y \<notin> Q)"
proof -
fix Q :: "('\<I>,'\<Sigma>) insert_message set"
assume b:"Q \<noteq> {}"
show "\<exists>z\<in>Q. \<forall>y. (y \<in> M \<union> {m}) \<and> (z \<in> M \<union> {m}) \<and> I y \<in> deps (Insert z)
\<longrightarrow> y \<notin> Q"
proof (cases "\<exists>x. x \<in> Q - {m}")
case True
hence "\<exists>z\<in> Q - {m}. \<forall>y. (y \<in> M) \<and> (z \<in> M) \<and> I y \<in> deps (Insert z)
\<longrightarrow> y \<notin> Q - {m}"
by (metis depends_on.simps assms(1) wfP_eq_minimal)
then show ?thesis using assms(2) DiffD2 by auto
next
case False
hence "Q = {m}" using b by blast
thus ?thesis using assms(2) by blast
qed
qed
thus ?thesis by (simp add:wfP_eq_minimal, blast)
qed
lemma create_insert_p_s_ordered:
assumes "is_associated_string N s"
assumes "a_conditions (insert_messages N) a"
assumes "Inr (Insert m) = create_insert s n \<sigma> new_id"
shows "a (P m) < a (S m)"
proof -
obtain p q where pq_def:
"create_insert s n \<sigma> new_id = Inr (Insert (InsertMessage p new_id q \<sigma>))"
by (metis (no_types, lifting) One_nat_def add.right_neutral add_Suc_right
create_insert.elims sum.case_eq_if sum.simps(4) assms(3) bind_def)
have "Inr p = nth_visible s n" using pq_def Error_Monad.bindE by fastforce
moreover have "Inr q = nth_visible s (Suc n)"
using pq_def Error_Monad.bindE by fastforce
ultimately have "a p < a q"
using assms by (metis is_associated_string_def nth_visible_inc')
moreover have "m = InsertMessage p new_id q \<sigma>"
using assms(3) pq_def by auto
ultimately show ?thesis by (simp add: pq_def)
qed
lemma create_insert_consistent:
assumes "consistent M"
assumes "is_associated_string N s"
assumes "N \<subseteq> M"
assumes "Inr m = create_insert s n \<sigma> new_id"
assumes "new_id \<notin> I ` insert_messages M"
shows "consistent (M \<union> {m})"
proof -
obtain p q where pq_def:
"create_insert s n \<sigma> new_id = Inr (Insert (InsertMessage p new_id q \<sigma>))"
by (metis (no_types, lifting) One_nat_def add.right_neutral add_Suc_right
create_insert.elims assms(4) sum.case_eq_if sum.simps(4) bind_def)
define m' where "m' = InsertMessage p new_id q \<sigma>"
hence a:"m = Insert m'" using pq_def assms(4) by auto
hence d: "create_insert s n \<sigma> new_id = Inr (Insert m')"
using pq_def assms by simp
have b:"I m' = new_id" using m'_def by (simp add:I_def)
hence "inj_on I (insert_messages M \<union> {m'})" using assms(5) assms(1)
using consistent_def by fastforce
hence "inj_on I (insert_messages (M \<union> {m}))" using assms(4) pq_def m'_def
by (metis Inr_inject insert_insert_message)
moreover
have p:"extended_to_set p \<subseteq> I ` set s" using pq_def nth_visible_eff by fastforce
have q: "extended_to_set q \<subseteq> I ` set s"
using pq_def apply (simp add:bind_def del:nth_visible.simps)
apply (cases "nth_visible s n", simp)
by (cases "nth_visible s (Suc n)", simp, simp add: nth_visible_eff)
have "extended_to_set p \<union> extended_to_set q \<subseteq> I ` set s" using p q by simp
hence "extended_to_set p \<union> extended_to_set q \<subseteq> I ` insert_messages N"
by (metis assms(2) is_associated_string_def to_woot_character_keeps_i_lifted)
hence "extended_to_set p \<union> extended_to_set q \<subseteq> I ` insert_messages M"
using assms(3) subset_mono by blast
hence c:"deps m \<subseteq> I ` insert_messages M" using pq_def assms(4) by auto
hence "\<Union> (deps ` (M \<union> {m})) \<subseteq> (I ` insert_messages (M \<union> {m}))"
by (metis consistent_def assms(1) deps_insert)
moreover have w:
"\<forall>n \<in> insert_messages M \<union> {m'}. deps (Insert n) \<subseteq> I ` insert_messages M"
by (metis a c consistent_def assms(1) Sup_le_iff imageI insert_iff
insert_is_Un insert_messages_def mem_Collect_eq sup.commute)
hence "\<forall>n \<in> insert_messages M \<union> {m'}. I m' \<notin> deps (Insert n)"
using b assms(5) by blast
hence "wfP (depends_on (insert_messages M \<union> {m'}))"
by (metis Un_insert_right insert_absorb wf_add assms(1)
consistent_def sup_bot.right_neutral)
moreover obtain a where a_def: "a_conditions (insert_messages M) a"
using consistent_def assms(1) by blast
define a' where
"a' = (\<lambda>i. if i = \<lbrakk> new_id \<rbrakk> then \<lbrakk>\<Psi> (a (P m'), a(S m')) new_id\<rbrakk> else a i)"
hence "a_conditions (insert_messages (M \<union> {m})) a'"
proof -
have "a' \<turnstile> < a' \<stileturn>" using a'_def a_conditions_def a_def by auto
moreover have
"\<And>m''. m'' \<in> (insert_messages M \<union> {m'}) \<longrightarrow>
a'(P m'') < a'(S m'') \<and>
a' \<lbrakk>I m''\<rbrakk> = \<lbrakk>\<Psi> (a'(P m''), a'(S m'')) (I m'')\<rbrakk>"
proof
fix m''
assume e:" m'' \<in> (insert_messages M \<union> {m'})"
show "a'(P m'') < a'(S m'') \<and> a' \<lbrakk> I m''\<rbrakk> =
\<lbrakk>\<Psi> (a'(P m''), a'(S m'')) (I m'')\<rbrakk>"
proof (cases "m'' \<in> insert_messages M")
case True
moreover have "deps (Insert m'') \<subseteq> I ` insert_messages M"
using e w by blast
hence "P m'' \<noteq> \<lbrakk> new_id \<rbrakk> \<and> S m'' \<noteq> \<lbrakk> new_id \<rbrakk>"
by (meson assms(5) contra_subsetD pred_is_dep succ_is_dep)
moreover have "I m'' \<noteq> new_id"
using assms(5) True by blast
ultimately show ?thesis using a_def True
by (simp add: a_conditions_def a'_def)
next
case False
moreover have "I m'' = new_id" using False b e by blast
moreover have "deps (Insert m'') \<subseteq> I ` insert_messages M"
using False a c e by blast
hence "P m'' \<noteq> \<lbrakk> new_id \<rbrakk> \<and> S m'' \<noteq> \<lbrakk> new_id \<rbrakk>"
by (meson assms(5) contra_subsetD pred_is_dep succ_is_dep)
moreover have "a_conditions (insert_messages N) a"
using a_def a_subset assms is_associated_string_def by blast
hence "a (P m') < a (S m')"
by (metis assms(2) d create_insert_p_s_ordered)
hence "a' (P m'') < a' (S m'')" using calculation a'_def False e by auto
ultimately show ?thesis using e a'_def by auto
qed
qed
ultimately show "?thesis" using a_conditions_def
by (metis a insert_insert_message)
qed
ultimately show "?thesis" using consistent_def a by (metis insert_insert_message)
qed
lemma bind_simp: "(x \<bind> (\<lambda>l. y l) = Inr r) \<Longrightarrow> (y (projr x) = Inr r)"
using isOK_I by force
end |
ZPPSVX Example Program Results
Solution(s)
1 2
1 ( 1.0000,-1.0000) (-1.0000, 2.0000)
2 (-0.0000, 3.0000) ( 3.0000,-4.0000)
3 (-4.0000,-5.0000) (-2.0000, 3.0000)
4 ( 2.0000, 1.0000) ( 4.0000,-5.0000)
Backward errors (machine-dependent)
1.1E-16 7.9E-17
Estimated forward error bounds (machine-dependent)
6.1E-14 7.4E-14
Estimate of reciprocal condition number
6.6E-03
A has not been equilibrated
|
/* Copyright © 2017 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
*/
#include <unity/dml/distributed_graph.hpp>
#include <unity/dml/load_balancing.hpp>
#include <rpc/dc.hpp>
#include <rpc/dc_global.hpp>
#include <parallel/pthread_tools.hpp>
#include <fileio/sanitize_url.hpp>
#include <sframe/sframe.hpp>
#include <sframe/sframe_saving.hpp>
#include <sgraph/sgraph.hpp>
#include <sgraph/sgraph_compute.hpp>
#include <sgraph/sgraph_fast_triple_apply.hpp>
#include <sgraph/hilbert_curve.hpp>
#include <unity/lib/gl_sgraph.hpp>
#include <unity/lib/gl_sarray.hpp>
#include <unity/lib/unity_sgraph.hpp>
#include <unity/lib/unity_sarray.hpp>
#include <boost/filesystem.hpp>
#include <numerics/armadillo.hpp>
#include <numerics/armadillo.hpp>
namespace turi {
namespace distributed_sgraph_compute {
/**************************************************************************/
/* */
/* Helper Functions */
/* */
/**************************************************************************/
/**
* This function creates a local copy of the sgraph which contains only
* a subset of the the edges of the original graph.
*/
sgraph make_local_sgraph(sgraph& global_sgraph,
std::vector<std::pair<size_t, size_t>> edge_coordinates,
std::vector<size_t> vertex_coordinates) {
sgraph ret(global_sgraph.get_num_partitions());
size_t sframe_default_segments = SFRAME_DEFAULT_NUM_SEGMENTS;
SFRAME_DEFAULT_NUM_SEGMENTS = 1;
sframe empty_vertices;
empty_vertices.open_for_write(global_sgraph.get_vertex_fields(),
global_sgraph.get_vertex_field_types());
empty_vertices.close();
sframe empty_edges;
empty_edges.open_for_write(global_sgraph.get_edge_fields(),
global_sgraph.get_edge_field_types());
empty_edges.close();
for (size_t i = 0; i < ret.get_num_partitions(); ++i) {
ret.vertex_partition(i) = empty_vertices;
for (size_t j = 0; j < ret.get_num_partitions(); ++j) {
ret.edge_partition(i, j) = empty_edges;
}
}
for (auto edge_coord: edge_coordinates) {
auto tempname = get_temp_name() + ".frame_idx";
sframe_save_weak_reference(global_sgraph.edge_partition(edge_coord.first, edge_coord.second), tempname);
ret.edge_partition(edge_coord.first, edge_coord.second) = sframe(tempname);
}
for (auto vertex_coord: vertex_coordinates) {
auto tempname = get_temp_name() + ".frame_idx";
sframe_save_weak_reference(global_sgraph.vertex_partition(vertex_coord), tempname);
ret.vertex_partition(vertex_coord) = sframe(tempname);
}
SFRAME_DEFAULT_NUM_SEGMENTS = sframe_default_segments;
return ret;
}
/**************************************************************************/
/* */
/* Distributed Graph */
/* */
/**************************************************************************/
distributed_graph::distributed_graph(std::string path,
distributed_control* dc,
std::vector<std::string> vdata_fields,
std::vector<std::string> edata_fields)
: procid(dc->procid()), numprocs(dc->numprocs()), dc(dc) {
m_global_graph = std::make_shared<sgraph>();
m_local_graph = std::make_shared<sgraph>();
std::shared_ptr<unity_sgraph> ug = std::make_shared<unity_sgraph>();
ug->load_graph(path);
ug = std::static_pointer_cast<unity_sgraph>(ug->select_vertex_fields(vdata_fields, 0)->select_edge_fields(edata_fields, 0, 0));
*m_global_graph = ug->get_graph();
partition_graph();
logstream(LOG_EMPH) << "Constructing local sgraph" << std::endl;
*m_local_graph = make_local_sgraph(*m_global_graph,
edge_coords[procid],
m_my_master_vertex_partitions);
logstream(LOG_EMPH) << "Done constructing local sgraph" << std::endl;
}
size_t distributed_graph::num_partitions() const {
return m_global_graph->get_num_partitions();
}
size_t distributed_graph::num_vertices(size_t partition_id) const {
if( partition_id == (size_t)-1 ) {
return m_global_graph->num_vertices();
} else {
return m_global_graph->vertex_partition(partition_id).num_rows();
}
}
size_t distributed_graph::num_edges(size_t src_partition, size_t dst_partition) const {
if( src_partition == (size_t)-1 || dst_partition == (size_t)-1 ) {
return m_global_graph->num_edges();
} else {
return m_global_graph->edge_partition(src_partition, dst_partition).num_rows();
}
}
void distributed_graph::print_partition_summary() {
std::cout << "[Proc " << procid << "] Vertex partition assignment: \n";
for (size_t i = 0; i < vertex_partition_to_worker.size(); ++i) {
std::cout << "[Proc " << procid << "] Partition " << i << ":";
for (size_t j = 0; j < vertex_partition_to_worker[i].size(); ++j) {
std::cout << vertex_partition_to_worker[i][j] << " ";
}
std::cout << "\n";
}
std::cout << std::endl;;
size_t num_edges_local = 0;
for (auto coord : my_edge_partitions())
num_edges_local += m_global_graph->edge_partition(coord.first, coord.second).num_rows();
size_t num_vertices_local = 0;
for (auto coord : my_master_vertex_partitions())
num_vertices_local += m_global_graph->vertex_partition(coord).num_rows();
std::cout << "[Proc " << procid << "] Number edge partitions: "
<< my_edge_partitions().size() << "\n"
<< "[Proc " << procid << "] Number edges: "
<< num_edges_local << "\n"
<< "[Proc " << procid << "] Number owning vertices: "
<< num_vertices_local << "\n"
<< "[Proc " << procid << "] Number vertex partitions: "
<< my_vertex_partitions().size() << "\n"
<< "[Proc " << procid << "] Master of vertex partitions: \n";
for (auto i : my_master_vertex_partitions()) {
std::cout << i << "\t";
}
std::cout << std::endl;
}
/**
* Graph partitioning
* Assign edge partitions to machines evenly using hilbert curve ordering
* to minimize the span of vertex partitions.
*/
void distributed_graph::partition_graph() {
edge_coords.resize(numprocs);
vertex_coords.resize(numprocs);
// tmp data structures
std::vector<std::set<size_t>> vertex_coords_set(numprocs);
EIGTODO::SparseMatrix<size_t> constraint_matrix(numprocs, num_partitions());
std::set<size_t> my_src_vertex_coords_set, my_dst_vertex_coords_set;
// Fill in edge_coords
size_t num_edge_partitions = num_partitions() * num_partitions();
for (size_t i = 0; i < numprocs; ++i) {
size_t low = (num_edge_partitions * i) / numprocs;
size_t high = (num_edge_partitions * (i + 1)) / numprocs;
for (size_t j = low; j < high; ++j) {
auto coord = hilbert_index_to_coordinate(j, num_edge_partitions);
edge_coords[i].push_back(coord);
vertex_coords_set[i].insert(coord.first);
vertex_coords_set[i].insert(coord.second);
if (i == procid) {
my_src_vertex_coords_set.insert(coord.first);
my_dst_vertex_coords_set.insert(coord.second);
}
}
}
// Fill in vertex_coords, assign masters
for (size_t i = 0; i < numprocs; ++i) {
vertex_coords[i].assign(vertex_coords_set[i].begin(),
vertex_coords_set[i].end());
for (size_t j : vertex_coords[i]) {
constraint_matrix.coeffRef(i, j) = 1;
}
}
std::vector<size_t> master_assignment;
double max_load = 0.0;
std::tie(master_assignment, max_load) = solve_genearlized_load_balancing(constraint_matrix);
logstream(LOG_INFO) << "Max load " << max_load << std::endl;
m_src_vertex_coords.assign(my_src_vertex_coords_set.begin(),
my_src_vertex_coords_set.end());
m_dst_vertex_coords.assign(my_dst_vertex_coords_set.begin(),
my_dst_vertex_coords_set.end());
// Fill in veretx_partition_to_worker
// A reverse lookup table: vertex partition to worker
vertex_partition_to_worker.resize(num_partitions());
for (size_t i = 0; i < vertex_coords.size(); ++i) {
for (auto j: vertex_coords[i]) {
vertex_partition_to_worker[j].push_back(i);
}
}
// First worker in each partition is the master
for (size_t j = 0; j < vertex_partition_to_worker.size(); ++j) {
size_t master = master_assignment[j];
for (size_t i = 0; i < vertex_partition_to_worker[j].size(); ++i) {
if (vertex_partition_to_worker[j][i] == master)
std::swap(vertex_partition_to_worker[j][0], vertex_partition_to_worker[j][i]);
}
}
// Fill in m_my_master_vertex_partitions
for (size_t coord = 0; coord < vertex_partition_to_worker.size(); ++coord) {
// if I am master for this partition
if (vertex_partition_to_worker[coord][0] == procid) {
m_my_master_vertex_partitions.push_back(coord);
}
}
// Done, print some debug information
print_partition_summary();
}
void distributed_graph::add_vertex_field(
const std::vector<std::shared_ptr<sarray<flexible_type>>>& column_data,
const std::string& column_name,
flex_type_enum dtype) {
ASSERT_EQ(column_data.size(), num_partitions());
for (size_t i = 0; i < column_data.size(); ++i) {
auto column = column_data[i];
ASSERT_EQ((int)column->get_type(), (int)dtype);
auto& sf = m_local_graph->vertex_partition(i);
size_t expected_column_size = m_local_graph->vertex_partition(i).size();
if (is_master_of_partition(i)) {
ASSERT_EQ(column->size(), expected_column_size);
sf = sf.add_column(column, column_name);
} else {
// make dummy column
auto sa = std::make_shared<sarray<flexible_type>>();
sa->open_for_write(1);
sa->set_type(dtype);
flexible_type v(dtype);
std::vector<flexible_type> dummy_values(expected_column_size, v);
turi::copy(dummy_values.begin(), dummy_values.end(), *sa);
sa->close();
sf = sf.add_column(sa, column_name);
}
}
}
void distributed_graph::save_as_sgraph(const std::string& path) {
auto dc = distributed_control::get_instance();
size_t procid = dc->procid();
namespace fs = boost::filesystem;
std::string subgraph_prefix("subgraphs");
// Create directory for subgraph
dir_archive dirarc;
if (procid == 0) {
dirarc.open_directory_for_write(path);
fs::path subgraph_dir(path);
subgraph_dir /= subgraph_prefix;
auto fstat = fileio::get_file_status(subgraph_dir.string());
if (fstat == fileio::file_status::MISSING) {
fileio::create_directory(subgraph_dir.string());
} else if(fstat == fileio::file_status::DIRECTORY) {
// do nothing, let it be overwritting
logstream(LOG_WARNING) << "Subgraph directory " << subgraph_dir.string()
<< " already exists. Overwriting." << std::endl;
} else {
// regular file
log_and_throw(std::string("Cannot create directory at regular file ") + subgraph_dir.string());
}
}
dc->barrier();
// Each machine saves its own vertex partition
auto vertex_partition_outname = [=](size_t partition_id) {
std::string vertex_prefix = std::string("vertex-part-") + std::to_string(partition_id);
fs::path outpath(path);
outpath /= subgraph_prefix;
outpath /= vertex_prefix;
return outpath.string() + ".frame_idx";
};
for (auto partition_id: my_master_vertex_partitions()) {
std::string outname = vertex_partition_outname(partition_id);
auto& sf = m_local_graph->vertex_partition(partition_id);
logstream(LOG_INFO) << "Saving partition " << partition_id << std::endl;
sframe_save_weak_reference(sf, outname);
logstream(LOG_INFO) << "Done saving partition " << partition_id << std::endl;
}
// Ignore edge partitions, since no algorithm changes it, yet.
dc->barrier();
// For root machine, lets' collect the pieces
if (procid == 0) {
sgraph ret(*m_global_graph);
for (size_t i = 0; i < num_partitions(); ++i) {
ret.vertex_partition(i) = sframe(vertex_partition_outname(i));
}
// Save reference
dirarc.set_metadata("contents", "graph");
oarchive oarc(dirarc);
unity_sgraph ug(std::make_shared<sgraph>(ret));
ug.save_reference(oarc);
}
}
} // end of distributed_sgraph_compute
} // end of turicreate
|
C$Procedure ATTCMP ( Attribute comparison for DSK segments )
SUBROUTINE ATTCMP ( HAN1, DLADS1, HAN2, DLADS2,
. TIMTOL, MATCH, TMATCH )
C$ Abstract
C
C Given handles and DLA descriptors for a pair of DSK segments,
C indicate whether the segments have matching attributes.
C
C$ Disclaimer
C
C THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE
C CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S.
C GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE
C ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE
C PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS"
C TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY
C WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A
C PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC
C SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE
C SOFTWARE AND RELATED MATERIALS, HOWEVER USED.
C
C IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA
C BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT
C LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND,
C INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS,
C REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE
C REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY.
C
C RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF
C THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY
C CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE
C ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE.
C
C$ Required_Reading
C
C None.
C
C$ Keywords
C
C DSKBRIEF
C
C$ Declarations
IMPLICIT NONE
INCLUDE 'dla.inc'
INCLUDE 'dskdsc.inc'
INTEGER HAN1
INTEGER DLADS1 ( * )
INTEGER HAN2
INTEGER DLADS2 ( * )
DOUBLE PRECISION TIMTOL
LOGICAL MATCH
LOGICAL TMATCH
C$ Brief_I/O
C
C VARIABLE I/O DESCRIPTION
C -------- --- --------------------------------------------------
C HAN1 I Handle of DSK containing first segment.
C DLADS1 I DLA descriptor of first segment.
C HAN2 I Handle of DSK containing second segment.
C DLADS1 I DLA descriptor of second segment.
C TIMTOL I Tolerance to use for time comparisons.
C MATCH O Flag indicating whether segments match.
C TMATCH O Flag indicating whether segments match
C when time bound are considered.
C
C$ Detailed_Input
C
C HAN1,
C DLADS1 are, respectively, the DSK handle and DLA descriptor
C of the first segment to be compared.
C
C HAN2,
C DLADS2 are, respectively, the DSK handle and DLA descriptor
C of the second segment to be compared.
C
C TIMTOL is a tolerance value to be used for time bound
C comparisons. TIMTOL is a non-negative number.
C Units are TDB seconds.
C
C$ Detailed_Output
C
C MATCH is a logical flag that is set to .TRUE. if and only
C if the DSK segments designated by the input handles and
C DLA descriptors have matching attributes, excluding
C time boundaries.
C
C In order for two DSK segments to match, the following
C segment attributes must match:
C
C Body
C Surface
C Frame
C Coordinate system
C
C If the coordinate system is planetodetic, the
C system parameters must match exactly.
C
C Data type
C Data class
C
C TMATCH is a logical flag that is set to .TRUE. if and only if
C the DSK segments designated by the input handles and
C DLA descriptors have matching time boundaries, to
C within the tolerance specified by TIMTOL.
C
C$ Parameters
C
C None.
C
C$ Exceptions
C
C 1) If a DSK data look-up fails, an error will be signaled
C by a routine in the call tree of this routine.
C
C$ Files
C
C None.
C
C$ Particulars
C
C This routine supports grouping of segments for abbreviated
C summaries created by DSKBRIEF.
C
C$ Examples
C
C See usage in DSKBRIEF.
C
C$ Restrictions
C
C 1) For use only within program DSKBRIEF.
C
C$ Literature_References
C
C None.
C
C$ Author_and_Institution
C
C N.J. Bachman (JPL)
C
C$ Version
C
C- DSKBRIEF Version 1.0.0, 15-FEB-2017 (NJB)
C
C Added time bounds check as a match criterion.
C
C 30-AUG-2016 (NJB)
C
C Original version.
C-&
C
C SPICELIB functions
C
DOUBLE PRECISION DSKDS1 ( DSKDSZ )
DOUBLE PRECISION DSKDS2 ( DSKDSZ )
LOGICAL FAILED
LOGICAL RETURN
IF ( RETURN() ) THEN
RETURN
END IF
CALL CHKIN ( 'ATTCMP' )
C
C No match so far.
C
MATCH = .FALSE.
C
C Get DSK descriptors for both segments.
C
CALL DSKGD ( HAN1, DLADS1, DSKDS1 )
CALL DSKGD ( HAN2, DLADS2, DSKDS2 )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ATTCMP' )
RETURN
END IF
C
C The following must match:
C
C Body
C Surface
C Frame
C Coordinate system
C Data type
C Data class
C
MATCH = ( DSKDS1(CTRIDX) .EQ. DSKDS2(CTRIDX) )
. .AND. ( DSKDS1(SRFIDX) .EQ. DSKDS2(SRFIDX) )
. .AND. ( DSKDS1(FRMIDX) .EQ. DSKDS2(FRMIDX) )
. .AND. ( DSKDS1(SYSIDX) .EQ. DSKDS2(SYSIDX) )
. .AND. ( DSKDS1(TYPIDX) .EQ. DSKDS2(TYPIDX) )
. .AND. ( DSKDS1(CLSIDX) .EQ. DSKDS2(CLSIDX) )
C
C If the coordinate system is planetodetic, the system
C parameters must match exactly.
C
IF ( NINT(DSKDS1(SYSIDX)) .EQ. PDTSYS ) THEN
MATCH = ( DSKDS1(PARIDX ) .EQ. DSKDS2(PARIDX ) )
. .AND. ( DSKDS1(PARIDX+1) .EQ. DSKDS2(PARIDX+1) )
END IF
C
C Compare start and stop times.
C
TMATCH = ( ABS(DSKDS1(BTMIDX) - DSKDS2(BTMIDX)) .LE. TIMTOL )
. .AND. ( ABS(DSKDS1(ETMIDX) - DSKDS2(ETMIDX)) .LE. TIMTOL )
CALL CHKOUT ( 'ATTCMP' )
RETURN
END
|
(* This file is part of the Linear Logic formalization in Coq: https://github.com/meta-logic/coq-ll *)
(** ** Soundness
This file proves the soundness of the triadic (focused) system of linear logic *)
(* Add LoadPath "../" . *)
Require Export Permutation.
Require Import Coq.Relations.Relations.
Require Import Coq.Arith.EqNat.
Require Import Coq.Classes.Morphisms.
Require Import Coq.Setoids.Setoid.
Require Export Coq.Sorting.PermutSetoid.
Require Export Coq.Sorting.PermutEq.
Require Import Coq.Program.Equality.
Require Import Coq.Logic.FunctionalExtensionality.
Require Export LL.SequentCalculiBasicTheory.
Set Implicit Arguments.
Module FFSoundness (DT : Eqset_dec_pol).
Module Export Sys := SqBasic DT.
Theorem Soundness : forall (B : list Lexp) n (M : list Lexp) A ,
LexpPos M ->
n |-F- B ; M ; A -> |-- B ; M ++ (Arrow2LL A).
Proof with solveF.
intros B n M A MPos.
generalize dependent B.
generalize dependent M.
generalize dependent A.
induction n using strongind;
intros A M MPos B H1.
+ inversionF H1;subst ...
eapply sig2_copy with (F:= A3°);auto.
(* INDUCTIVE CASES *)
+ inversionF H1.
++ (* tensor *)
apply sig2_tensor with (N:=M0) (M:=N) (F:=F) (G:=G) ...
MReplace (F :: N) ( N ++ (Arrow2LL (DW F) )) .
apply H with n0 ...
MReplace (G :: M0) ( M0 ++ (Arrow2LL (DW G) )) .
apply H with m ...
++ (* oplus *)
apply H in H2 ...
simpl in *.
eapply sig2_plus1 with (F:=F) (M:=M) ...
rewrite union_comm in H2 ...
++ (* oplus2 *)
apply H in H2 ...
simpl in *.
eapply sig2_plus2 with (G:=G) (M:=M) ...
rewrite union_comm in H2.
eauto.
++ (* bang *)
apply H in H2;auto.
simpl. simpl in H2.
eapply sig2_bang with (F:=F);auto.
++ (* Release *)
apply H in H3;auto.
++ (* bottom *)
apply H in H2;auto.
simpl in *.
eapply sig2_bot;eauto.
++ (* par *)
apply H in H2;auto.
simpl in *.
eapply sig2_par ...
MReplace (F :: G :: M ++ M0) (M ++ F :: G :: M0) ...
++ (* with *)
apply H in H2 ...
apply H in H3 ...
simpl in *.
apply sig2_with with (F:=F) (G:=G) (M:=M ++ M0) ...
MReplace ( F :: M ++ M0) ( M ++ F :: M0) ...
MReplace (G :: M ++ M0) ( M ++ G :: M0) ...
++ (* ? *)
apply H in H2 ...
simpl in *.
apply sig2_quest with (F:=F) (M := M ++ M0) ...
rewrite union_comm in H2 ...
++ (* store *)
apply H in H3 ...
simpl in *.
rewrite <- union_assoc in H3 ...
++ (* decide *)
apply H in H4 ...
simpl in *.
rewrite app_nil_r.
rewrite H3.
MReplace (F :: L') ( L' ++ [F]) ...
++ (* decide *)
apply H in H4 ...
simpl in *.
rewrite H3.
eapply sig2_copy with (F:=F) ...
rewrite H3 in H4 ...
MReplace ( (F::M)++[]) (M ++ [F]) ...
++ (* exists *)
apply H in H2;auto.
simpl in *.
rewrite union_comm in H2.
rewrite union_comm ...
eapply sig2_ex ...
eauto.
++ (* forall *)
simpl in *.
eapply sig2_fx ...
intro x.
generalize (H2 x);intro.
apply H in H0 ...
simpl in *.
MReplace (Subst FX x :: M ++ M0) ( M ++ Subst FX x :: M0) ...
Qed.
End FFSoundness.
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoStarIsType #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilyDependencies #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}
{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}
module Numeric.Wavelet.Continuous (
-- * Continuous Wavelet Transform
CWD(..), mapCWD
, CWDLine(..), mapCWDLine
, LNorm(..), CWDOpts(..), defaultCWDO
, cwd
, cwdReal
-- * Wavelets
, AWavelet(..), mapAWavelet
, morlet, morletFunc
, meyer, meyerFunc
, fbsp, fbspFunc
) where
import Data.Complex
import Data.Finite
import Data.Foldable
import Data.Maybe
import Data.Ord
import Data.Proxy
import Data.Type.Equality
import Data.Vector.Generic.Sized (Vector)
import GHC.Generics (Generic)
import GHC.TypeLits.Compare
import GHC.TypeNats
import Math.FFT.Base
import Numeric.Wavelet.Internal.FFT
import qualified Data.Vector.Generic as UVG
import qualified Data.Vector.Generic.Sized as VG
import qualified Data.Vector.Sized as V
newtype CWD v n m a b = CWD { cwdLines :: V.Vector m (CWDLine v n a b) }
deriving (Show, Functor)
data CWDLine v n a b = CWDLine
{ cwdlData :: Vector v n b
, cwdlScale :: Finite (n `Div` 2 + 1) -- ^ Scale factor, in number of ticks.
, cwdlFreq :: a -- ^ The frequency associated with this scale, in inverse tick
, cwdlCoI :: Finite (n `Div` 2 + 1) -- ^ How many items are /outside/ of the Cone of Influence, on each side.
}
deriving (Show, Functor)
mapCWDLine
:: (UVG.Vector v b, UVG.Vector v c)
=> (b -> c)
-> CWDLine v n a b
-> CWDLine v n a c
mapCWDLine f (CWDLine d s q c) = CWDLine (VG.map f d) s q c
mapCWD
:: (UVG.Vector v b, UVG.Vector v c)
=> (b -> c)
-> CWD v n m a b
-> CWD v n m a c
mapCWD f (CWD l) = CWD (mapCWDLine f <$> l)
data LNorm = L1 | L2
deriving (Show, Eq, Ord, Enum, Bounded, Generic)
data CWDOpts n = CWDO
{ cwdoNorm :: LNorm -- ^ wavelet normalization
, cwdoMinScale :: Finite (n `Div` 2 + 1) -- ^ min scale (period)
, cwdoMaxScale :: Finite (n `Div` 2 + 1) -- ^ max scale (period)
}
deriving (Show, Eq, Ord, Generic)
defaultCWDO :: KnownNat n => CWDOpts n
defaultCWDO = CWDO
{ cwdoNorm = L2
, cwdoMinScale = minBound
, cwdoMaxScale = maxBound
}
-- | 'cwd' for complex-valued analytic wavelets.
cwd :: forall v n m a b.
( UVG.Vector v (Complex b)
, KnownNat n
, KnownNat m
, FFTWReal b
, 1 <= n
, RealFloat a
)
=> AWavelet v a (Complex b)
-> CWDOpts n
-> Vector v n (Complex b)
-> CWD v n m a (Complex b)
cwd AW{..} CWDO{..} xs = CWD . VG.generate $ \i ->
let s = scaleOf i
dt = 1/s
in case awVector dt of
VG.SomeSized (wv :: Vector v q (Complex b))
| Just Refl <- isLE (Proxy @1) (Proxy @q)
, Just Refl <- isLE (Proxy @((q-1)`Div`2)) (Proxy @(q-1))
-> let ys :: Vector v (n + q - 1) (Complex b)
ys = (* (realToFrac (normie dt) :+ 0)) `VG.map` convolve xs wv
coi = fromMaybe maxBound . packFinite . round @a @Integer $ sqrt 2 * s
s' = fromMaybe maxBound . packFinite . round @a @Integer $ s
ys' :: Vector v n (Complex b)
ys' = VG.slice @_ @((q - 1)`Div`2) @n @((q-1)-((q-1)`Div`2)) Proxy ys
in CWDLine ys' s' (awFreq / s) coi
_ -> error "Bad scale: wavelet vector is empty?"
where
n = natVal (Proxy @n)
m = natVal (Proxy @m)
normie :: a -> a
normie = case cwdoNorm of
L1 -> sqrt
L2 -> id
minScale = fromIntegral cwdoMinScale `max` 1
maxScale = (fromIntegral cwdoMaxScale `min` (fromIntegral n / (2 * sqrt 2)))
`max` (minScale + 1)
scaleStep = (log maxScale - log minScale) / (fromIntegral m - 1)
scaleOf :: Finite m -> a
scaleOf i = exp $ log minScale + fromIntegral i * scaleStep
-- | 'cwd' for real-valued analytic wavelets.
cwdReal
:: forall v n m a b.
( UVG.Vector v b
, UVG.Vector v (Complex b)
, KnownNat n
, KnownNat m
, FFTWReal b
, 1 <= n
, RealFloat a
)
=> AWavelet v a b
-> CWDOpts n
-> Vector v n b
-> CWD v n m a b
cwdReal aw cwdo = mapCWD realPart
. cwd (mapAWavelet (:+ 0) aw) cwdo
. VG.map (:+ 0)
-- | Analytical Wavelet
data AWavelet v a b = AW
{ awVector :: a -> v b -- ^ generate a vector within awRange with a given dt
, awFreq :: a -- ^ Dominant frequency component
, awRange :: a -- ^ range away from zero outside of which wavelet can be considered negligible
}
deriving Functor
mapAWavelet
:: (UVG.Vector v b, UVG.Vector v c)
=> (b -> c)
-> AWavelet v a b
-> AWavelet v a c
mapAWavelet f (AW v q r) = AW (UVG.map f . v) q r
morlet
:: (UVG.Vector v (Complex a), RealFloat a)
=> a
-> AWavelet v a (Complex a)
morlet σ = AW{..}
where
awRange = 4
(!awFreq, mf) = morletFunc_ σ
awVector = renderFunc awRange mf
morletFunc :: RealFloat a => a -> a -> Complex a
morletFunc = snd . morletFunc_
morletFunc_ :: RealFloat a => a -> (a, a -> Complex a)
morletFunc_ σ = (q, f)
where
f t = (c * exp(-t*t/2) :+ 0) * (exp (0 :+ (σ * t)) - (exp (-σ2/2) :+ 0))
!c = pi ** (-1/4) * (1 + exp (-σ2) - 2 * exp (-3/4*σ2)) ** (-1/2)
!σ2 = σ * σ
!q = converge 20 iter σ / (2 * pi)
iter w = σ / (1 - exp (-σ * w))
meyer
:: (UVG.Vector v a, RealFloat a)
=> AWavelet v a a
meyer = AW{..}
where
awRange = 6
awVector = renderFunc awRange meyerFunc
awFreq = 4 * pi / 3
meyerFunc :: RealFloat a => a -> a
meyerFunc t
| isNaN ψ || isInfinite ψ = 0
| otherwise = ψ
where
t' = t - 0.5
t'3 = t'**3
sinTerm = sin(4*pi/3*t') / pi
ψ1 = (4/3/pi*t'*cos(2*pi/3*t') - sinTerm)
/ (t' - 16/9 * t'3)
ψ2 = (8/3/pi*t'*cos(8*pi/3*t') + sinTerm)
/ (t' - 64/9 * t'3)
ψ = ψ1 + ψ2
fbsp
:: (UVG.Vector v (Complex a), FFTWReal a)
=> Int -- ^ m, >= 1
-> a -- ^ f_b, bandwidth
-> a -- ^ f_c, wavelet center frequency
-> AWavelet v a (Complex a)
fbsp m fb fc = AW{..}
where
awRange = 4/fb
awVector = renderFunc awRange (fbspFunc m fb fc)
awFreq = autoDeriveFreq awRange awVector
autoDeriveFreq
:: (UVG.Vector v (Complex a), FFTWReal a)
=> a
-> (a -> v (Complex a))
-> a
autoDeriveFreq r fv = case fv 0.001 of
VG.SomeSized v ->
let vv = zip [1..] . map magnitude . VG.toList $ fft v
(i,_) = maximumBy (comparing snd) vv
in fromInteger i / (r * 2)
_ -> error "bad vector"
fbspFunc :: RealFloat a => Int -> a -> a -> a -> Complex a
fbspFunc m fb fc t =
((sqrt fb * sinc (fb * t / fromIntegral m))^m :+ 0) * exp (0 :+ (2 * pi * fc * t))
where
sinc x = sin x / x
-- | Render the effective range of a wavelet (based on 'awRange'), centered
-- around zero. Takes a timestep.
renderFunc
:: (UVG.Vector v b, RealFrac a)
=> a -- ^ range about zero
-> (a -> b) -- ^ func
-> a -- ^ dt
-> v b
renderFunc r f dt = UVG.generate (round n) $ \i ->
f (fromIntegral i * dt - r)
where
n = r * 2 / dt
converge
:: (Fractional a, Ord a)
=> Int -- ^ maximum iterations
-> (a -> a) -- ^ function to find the fixed point convergence
-> a -- ^ starting value
-> a
converge n f = go 0
where
go !i !x
| i >= n = 0
| abs (x - y) < 0.00001 = x
| otherwise = go (i + 1) y
where
!y = f x
|
{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
module Test.Grenade.Layers.LeakyRelu where
import Data.Proxy
import GHC.TypeLits
import Grenade.Core
import Grenade.Layers.LeakyRelu
import qualified Numeric.LinearAlgebra as LA
import Numeric.LinearAlgebra.Static (L)
import qualified Numeric.LinearAlgebra.Static as H
import Hedgehog
import qualified Hedgehog.Range as Range
import Test.Hedgehog.Compat
import Test.Hedgehog.Hmatrix
prop_leaky_relu_correct_on_one_element = property $ do
input :: S ('D1 1) <- forAll genOfShape
alpha <- forAll $ genRealNum (Range.constant 0 0.9)
let layer = LeakyRelu alpha :: LeakyRelu
S1D out = snd $ runForwards layer input :: S ('D1 1)
x = (\(S1D a) -> H.extract a LA.! 0) input
H.extract out LA.! 0 === if x >= 0 then x else x * alpha
prop_leaky_relu_correct_on_3D_array = property $ do
height :: Int <- forAll $ choose 2 100
width :: Int <- forAll $ choose 2 100
channels :: Int <- forAll $ choose 2 100
alpha <- forAll $ genRealNum (Range.constant 0 0.9)
case (someNatVal (fromIntegral height), someNatVal (fromIntegral width), someNatVal (fromIntegral channels)) of
(Just (SomeNat (Proxy :: Proxy h)), Just (SomeNat (Proxy :: Proxy w)), Just (SomeNat (Proxy :: Proxy c))) -> do
input :: S ('D3 h w c) <- forAll genOfShape
let layer = LeakyRelu alpha :: LeakyRelu
S3D out = snd $ runForwards layer input :: S ('D3 h w c)
inp' = (\(S3D x) -> H.dmmap (\a -> if a >= 0 then a else a * alpha) x) input :: L (h * c) w
H.extract inp' === H.extract out
tests :: IO Bool
tests = checkParallel $$(discover)
|
function out=diag(in,K)
if isempty(in),out=in;return;end
precision=in(1).precision;
zero=mp(0,precision);
if nargin==1,K=0;end
s=size(in);
switch min(s)
case 1 %a vector, either row or column
N=length(in);
out=zeros(mp(N),mp(N));
SS.type='()';SS.subs={1:(N+1):(N*N)};
out=subsasgn(out,SS,in);
otherwise %a matrix
out=zero*[];
for ii=1:size(in,1)
if (ii+K)<=size(in,2)
%Force column vector
out(ii,1)=in(ii,(ii+K));
end
end
end
|
/-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
-/
import data.int.basic
import data.nat.pow
import data.nat.size
/-!
# Bitwise operations on integers
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
## Recursors
* `int.bit_cases_on`: Parity disjunction. Something is true/defined on `ℤ` if it's true/defined for
even and for odd values.
-/
namespace int
/-! ### bitwise ops -/
@[simp] lemma bodd_zero : bodd 0 = ff := rfl
@[simp] lemma bodd_one : bodd 1 = tt := rfl
lemma bodd_two : bodd 2 = ff := rfl
@[simp, norm_cast] lemma bodd_coe (n : ℕ) : int.bodd n = nat.bodd n := rfl
@[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd :=
by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros;
simp; cases i.bodd; simp
@[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd :=
by cases n; simp; refl
@[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n :=
by cases n; simp [has_neg.neg, int.coe_nat_eq, int.neg, bodd, -of_nat_eq_coe]
@[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) :=
by cases m with m m; cases n with n n; unfold has_add.add;
simp [int.add, -of_nat_eq_coe, bool.bxor_comm]
@[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n :=
by cases m with m m; cases n with n n;
simp [← int.mul_def, int.mul, -of_nat_eq_coe, bool.bxor_comm]
theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n
| (n : ℕ) :=
by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ),
by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2
| -[1+ n] := begin
refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2),
dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul],
{ change -[1+ 2 * nat.div2 n] = _, rw zero_add },
{ rw [zero_add, add_comm], refl }
end
theorem div2_val : ∀ n, div2 n = n / 2
| (n : ℕ) := congr_arg of_nat n.div2_val
| -[1+ n] := congr_arg neg_succ_of_nat n.div2_val
lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm
lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _)
lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 :=
by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val }
lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n :=
(bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _
/-- Defines a function from `ℤ` conditionally, if it is defined for odd and even integers separately
using `bit`. -/
def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n :=
by rw [← bit_decomp n]; apply h
@[simp] lemma bit_zero : bit ff 0 = 0 := rfl
@[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n :=
by rw [bit_val, nat.bit_val]; cases b; refl
@[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] :=
by rw [bit_val, nat.bit_val]; cases b; refl
@[simp] lemma bodd_bit (b n) : bodd (bit b n) = b :=
by rw bit_val; simp; cases b; cases bodd n; refl
@[simp] lemma bodd_bit0 (n : ℤ) : bodd (bit0 n) = ff := bodd_bit ff n
@[simp] lemma bodd_bit1 (n : ℤ) : bodd (bit1 n) = tt := bodd_bit tt n
lemma bit0_ne_bit1 (m n : ℤ) : bit0 m ≠ bit1 n :=
mt (congr_arg bodd) $ by simp
lemma bit1_ne_bit0 (m n : ℤ) : bit1 m ≠ bit0 n :=
(bit0_ne_bit1 _ _).symm
lemma bit1_ne_zero (m : ℤ) : bit1 m ≠ 0 :=
by simpa only [bit0_zero] using bit1_ne_bit0 m 0
@[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b
| (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero
| -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero];
clear test_bit_zero; cases b; refl
@[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m
| (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ
| -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ]
private meta def bitwise_tac : tactic unit := `[
funext m,
funext n,
cases m with m m; cases n with n n; try {refl},
all_goals
{ apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat,
try {dsimp [nat.land, nat.ldiff, nat.lor]},
try {rw [
show nat.bitwise (λ a b, a && bnot b) n m =
nat.bitwise (λ a b, b && bnot a) m n, from
congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]},
apply congr_arg (λ f, nat.bitwise f m n),
funext a,
funext b,
cases a; cases b; refl },
all_goals {unfold nat.land nat.ldiff nat.lor}
]
theorem bitwise_or : bitwise bor = lor := by bitwise_tac
theorem bitwise_and : bitwise band = land := by bitwise_tac
theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac
theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac
@[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) :
bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) :=
begin
cases m with m m; cases n with n n;
repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ };
unfold bitwise nat_bitwise bnot;
[ induction h : f ff ff,
induction h : f ff tt,
induction h : f tt ff,
induction h : f tt tt ],
all_goals
{ unfold cond, rw nat.bitwise_bit,
repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } },
all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl }
end
@[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) :=
by rw [← bitwise_or, bitwise_bit]
@[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) :=
by rw [← bitwise_and, bitwise_bit]
@[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) :=
by rw [← bitwise_diff, bitwise_bit]
@[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) :=
by rw [← bitwise_xor, bitwise_bit]
@[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n)
| (n : ℕ) := by simp [lnot]
| -[1+ n] := by simp [lnot]
@[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) :
test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) :=
begin
induction k with k IH generalizing m n;
apply bit_cases_on m; intros a m';
apply bit_cases_on n; intros b n';
rw bitwise_bit,
{ simp [test_bit_zero] },
{ simp [test_bit_succ, IH] }
end
@[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k :=
by rw [← bitwise_or, test_bit_bitwise]
@[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k :=
by rw [← bitwise_and, test_bit_bitwise]
@[simp]
lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) :=
by rw [← bitwise_diff, test_bit_bitwise]
@[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) :=
by rw [← bitwise_xor, test_bit_bitwise]
@[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k)
| (n : ℕ) k := by simp [lnot, test_bit]
| -[1+ n] k := by simp [lnot, test_bit]
@[simp]
@[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl
@[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl
@[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl
@[simp]
lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl
lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k
| (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat,
← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add]
| -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ,
← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add]
/-! ### bitwise ops -/
local attribute [simp] int.zero_div
lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k
| (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _)
| -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _)
| (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ
(λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k)
(λ i n, congr_arg coe $
by rw [← nat.shiftl_sub, add_tsub_cancel_left]; apply nat.le_add_right)
(λ i n, congr_arg coe $
by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, tsub_self]; refl)
| -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ
(λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k])
(λ i n, congr_arg neg_succ_of_nat $
by rw [← nat.shiftl'_sub, add_tsub_cancel_left]; apply nat.le_add_right)
(λ i n, congr_arg neg_succ_of_nat $
by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, tsub_self]; refl)
lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k :=
shiftl_add _ _ _
lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n)
| (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _)
| -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _)
lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n)
| (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _)
| -[1+ m] n := begin
rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl,
exact coe_nat_lt_coe_nat_of_lt (pow_pos dec_trivial _)
end
lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) :=
congr_arg coe (nat.one_shiftl _)
@[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0
| (n : ℕ) := congr_arg coe (nat.zero_shiftl _)
| -[1+ n] := congr_arg coe (nat.zero_shiftr _)
@[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _
end int
|
State Before: P : PFunctor
α β : Type u
p : Obj P (W P)
⊢ dest (mk p) = p State After: case mk
P : PFunctor
α β : Type u
fst✝ : P.A
snd✝ : B P fst✝ → W P
⊢ dest (mk { fst := fst✝, snd := snd✝ }) = { fst := fst✝, snd := snd✝ } Tactic: cases p State Before: case mk
P : PFunctor
α β : Type u
fst✝ : P.A
snd✝ : B P fst✝ → W P
⊢ dest (mk { fst := fst✝, snd := snd✝ }) = { fst := fst✝, snd := snd✝ } State After: no goals Tactic: rfl |
program main
implicit none
include 'omp_lib.h'
integer lower, upper, stride
integer i, j
lower = 9
upper = 0
stride = -3
!$omp parallel do private (j)
do i = lower, upper, stride
j = omp_get_thread_num();
print *, "Iteration ", i, " by thread:", j
enddo
end
|
# Constrained Optimization
```python
import numpy as np
from scipy.linalg import cholesky, solve_triangular, cho_solve, cho_factor
from scipy.linalg import solve
from scipy.optimize import minimize
```
### Lagrange multipliers and constrained optimization
Recall why Lagrange multipliers are useful for constrained optimization - a stationary point must be where the constraint surface $g$ touches a level set of the function $f$ (since the value of $f$ does not change on a level set). At that point, $f$ and $g$ are parallel, and hence their gradients are also parallel (since the gradient is normal to the level set). So we want to solve
$$\nabla f = -\lambda \nabla g$$
or equivalently,
$$\nabla f + \lambda \nabla g = 0$$
## Example 1
Maximize $f (x, y, z) = xy + yz$ subject to the constraints $x + 2y = 6$ and $x − 3z = 0$.
We set up the equations
$$
F (x, y, z, λ, μ) = xy + yz − λ(x + 2y − 6) − μ(x − 3z)
$$
Now set partial derivatives to zero and solve the following set of equations
\begin{align}
y - \lambda - \mu &= 0 \\
x + z - 2\lambda &= 0 \\
y +3\mu &= 0 \\
x + 2y - 6 &= 0 \\
x - 3z &= 0
\end{align}
which is a linear equation in $x, y, z, \lambda, \mu$
$$
\begin{pmatrix}
0 & 1 & 0 & -1 & -1 \\
1 & 0 & 1 & -2 & 0 \\
0 & 1 & 0 & 0 & 3 \\
1 & 2 & 0 & 0 & 0 \\
1 & 0 & -3 & 0 & 0 \\
\end{pmatrix}\pmatrix{x \\ y \\ z \\ \lambda \\ \mu} = \pmatrix{0 \\ 0 \\ 0 \\ 6 \\ 0}
$$
```python
A = np.array([
[0, 1, 0, -1, -1],
[1, 0, 1, -2, 0],
[0, 1, 0, 0, 3],
[1, 2, 0, 0, 0],
[1, 0,-3, 0, 0]])
b = np.array([0,0,0,6,0])
sol = solve(A, b)
```
```python
sol
```
array([ 3. , 1.5, 1. , 2. , -0.5])
```python
def f(x, y, z):
return x*y + y*z
```
```python
f(*sol[:3])
```
6.0
### Using `scipy.optimize`
We first need to set this as a minimization problem.
```python
def f(x):
return -(x[0]*x[1] + x[1]*x[2])
```
```python
cons = ({'type': 'eq',
'fun' : lambda x: np.array([x[0] + 2*x[1] - 6, x[0] - 3*x[2]])})
```
```python
x0 = np.array([2,2,0.67])
res = minimize(f, x0, constraints=cons)
```
array([2.99999979, 1.50000011, 0.99999993])
```python
res.fun
```
-5.999999999999969
```python
res.x
```
array([2.99999979, 1.50000011, 0.99999993])
## Example 2
Find the minimum of the following quadratic function on $\mathbb{R}^2$
$$f(x) = x^TAx +b^Tx +c$$
where
$$A = \left(\begin{matrix}13&5\\5&7\end{matrix}\right), b = \left(\begin{matrix}1\\1\end{matrix}\right) \textrm {and } c = 2$$
Under the constraints:
$$g(x) = 2x_1-5x_2=2 \;\;\;\;\;\; \textrm{ and } \;\;\;\;\;\; h(x) = x_1+x_2=1$$
1. Use a matrix decomposition method to find the minimum of the *unconstrained* problem without using `scipy.optimize` (Use library functions - no need to code your own). Note: for full credit you should exploit matrix structure.
2. Find the solution using constrained optimization with the `scipy.optimize` package.
2. Use Lagrange multipliers and solving the resulting set of equations directly without using `scipy.optimize`.
### Solve unconstrained problem
To find the minimum, we differentiate $f(x)$ with respect to $x^T$ and set it equal to $0$. We thus need to solve
$$
2Ax + b = 0
$$
or
$$
Ax = -\frac{b}{2}
$$
We see that $A$ is a symmetric positive definite real matrix. Hence we use Cholesky factorization.
Steps
$$
L = \text{cholesky}(A) \\
\text{solve } Ly = b \\
\text{solve } L^Tx = y
$$
```python
A = np.array([
[13,5],
[5,7]
])
b = np.array([1,1]).reshape(-1,1)
c = 2
```
```python
L = cholesky(A, lower=True)
y = solve_triangular(L, -b/2, lower=True)
x = solve_triangular(L.T, y, lower=False)
```
```python
x
```
array([[-0.01515152],
[-0.06060606]])
#### Short cut
```python
cho_solve(cho_factor(A), -b/2)
```
array([[-0.01515152],
[-0.06060606]])
### Solve constrained problem using `scipy.optimize`
```python
f = lambda x, A, b, c: x.T @ A @ x + b.T @ x + c
```
```python
from scipy.optimize import minimize
```
```python
cons = ({'type': 'eq', 'fun': lambda x: 2*x[0] - 5*x[1] - 2},
{'type': 'eq', 'fun': lambda x: x[0] + x[1] - 1})
res = minimize(f, [0,0], constraints=cons, args=(A, b, c))
res.x
```
array([1.00000000e+00, 3.41607086e-16])
### Solve constrained problem using Lagrange multipliers
We set up the equations
$$
F(x_1, x_2, \lambda, \mu) = f + \lambda g + \mu h
$$
Sometimes this is written as
$$
F(x_1, x_2, \lambda, \mu) = f - \lambda g - \mu h
$$
All this means is a final sign change in the estimated values of $\lambda$ and $\mu$.
We show the original equations for convenience
$$f(x) = x^TAx +b^Tx +c$$
where
$$A = \left(\begin{matrix}13&5\\5&7\end{matrix}\right), b = \left(\begin{matrix}1\\1\end{matrix}\right) \textrm {and } c = 2$$
Under the constraints:
$$g(x) = 2x_1-5x_2=2 \;\;\;\;\;\; \textrm{ and } \;\;\;\;\;\; h(x) = x_1+x_2=1$$
To make the calculations explicit, we rewrite $F$ as
$$
F = 13x_1^2 + 10xy_1x_2+ 7x_2^2 + x_1 + x_2 +2 + \lambda(2x_1 - 5x_2 -2) + \mu(x_1 + x_2 -1)
$$
Taking partial derivatives, we get
$$
\begin{align}
\frac{\delta F}{\delta x_1} &=& 26 x_1 + 10 x_2 + 1 + 2\lambda + \mu &= 0 \\
\frac{\delta F}{\delta x_2} &=& 10 x_1 + 14 x_2 + 1 - 5\lambda + \mu &= 0 \\
\frac{\delta F}{\delta \lambda} &=& 2 x_1 - 5 x_2 -2 &= 0 \\
\frac{\delta F}{\delta \mu} &=& x_1 + x_2 - 1 &= 0
\end{align}
$$
Plugging in the numbers and expressing in matrix form, we get
$$
\begin{bmatrix}
26 & 10 & 2 & 1 \\
10 & 14 & -5 & 1 \\
2 & -5 & 0 & 0 \\
1 & 1 & 0 & 0
\end{bmatrix} \begin{bmatrix}
x_1 \\
x_2 \\
\lambda \\
\mu
\end{bmatrix} = \begin{bmatrix}
-1 \\
-1 \\
2 \\
1
\end{bmatrix}
$$
With a bit of practice, you can probably just write the matrix directly by inspection.
```python
A = np.array([
[26, 10, 2, 1],
[10, 14, -5, 1],
[2, -5, 0, 0],
[1, 1, 0, 0]
])
b = np.array([-1, -1, 2, 1]).reshape(-1,1)
```
```python
solve(A, b)
```
array([[ 1.00000000e+00],
[-4.37360585e-17],
[-2.28571429e+00],
[-2.24285714e+01]])
```python
```
|
theory prop_11
imports Main
"$HIPSTER_HOME/IsaHipster"
begin
datatype 'a list = Nil2 | Cons2 "'a" "'a list"
fun append :: "'a list => 'a list => 'a list" where
"append (Nil2) y = y"
| "append (Cons2 z xs) y = Cons2 z (append xs y)"
fun rev :: "'a list => 'a list" where
"rev (Nil2) = Nil2"
| "rev (Cons2 y xs) = append (rev xs) (Cons2 y (Nil2))"
(*hipster append rev*)
lemma lemma_a [thy_expl]: "append x2 Nil2 = x2"
by (hipster_induct_schemes append.simps rev.simps)
lemma lemma_aa [thy_expl]: "append (append x1 y1) z1 = append x1 (append y1 z1)"
by (hipster_induct_schemes append.simps rev.simps)
lemma lemma_ab [thy_expl]: "append (rev x4) (rev y4) = rev (append y4 x4)"
by (hipster_induct_schemes append.simps rev.simps)
lemma lemma_ac [thy_expl]: "rev (rev x3) = x3"
by (hipster_induct_schemes append.simps rev.simps)
theorem revAppend :
"(rev (append (rev x) (rev y))) = (append y x)"
by (hipster_induct_schemes append.simps rev.simps)
(*
lemma lemma_a [thy_expl]: "append x2 Nil2 = x2"
by (hipster_induct_schemes append.simps rev.simps)
lemma lemma_aa [thy_expl]: "append (append x2 y2) z2 =
append x2 (append y2 z2)"
by (hipster_induct_schemes append.simps rev.simps)
lemma lemma_ab [thy_expl]: "append (rev x5) (rev y5) =
rev (append y5 x5)"
by (hipster_induct_schemes append.simps rev.simps)
lemma lemma_ac [thy_expl]: "rev (rev x5) = x5"
by (hipster_induct_schemes append.simps rev.simps)
*)
theorem x0 :
"(rev (append (rev x) (rev y))) = (append y x)"
by hipster_induct_schemes
(*by (tactic {* Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1 *})*)
end
|
open import Relation.Binary.Core
module PLRTree.Insert {A : Set}
(_≤_ : A → A → Set)
(tot≤ : Total _≤_) where
open import Data.Sum
open import PLRTree {A}
insert : A → PLRTree → PLRTree
insert x leaf = node perfect x leaf leaf
insert x (node perfect y l r)
with tot≤ x y | l | r
... | inj₁ x≤y | leaf | leaf = node right x (node perfect y leaf leaf) leaf
... | inj₁ x≤y | _ | _ = node left x (insert y l) r
... | inj₂ y≤x | leaf | leaf = node right y (node perfect x leaf leaf) leaf
... | inj₂ y≤x | _ | _ = node left y (insert x l) r
insert x (node left y l r)
with tot≤ x y
... | inj₁ x≤y
with insert y l
... | node perfect y' l' r' = node right x (node perfect y' l' r') r
... | t = node left x t r
insert x (node left y l r) | inj₂ y≤x
with insert x l
... | node perfect y' l' r' = node right y (node perfect y' l' r') r
... | t = node left y t r
insert x (node right y l r)
with tot≤ x y
... | inj₁ x≤y
with insert y r
... | node perfect y' l' r' = node perfect x l (node perfect y' l' r')
... | t = node right x l t
insert x (node right y l r) | inj₂ y≤x
with insert x r
... | node perfect y' l' r' = node perfect y l (node perfect y' l' r')
... | t = node right y l t
|
x <- c("abc", "abd", "abe", "bcf")
grepl(pattern="^a", x) # string begin with "a"
grepl(pattern="[ce]", x) # strings contain either "c" or "e"
grepl(pattern="[ce]$", x) # strings end in "c" or "e"
grepl(pattern="^a[ce]", x) # strings end in "c" or "e"
x <- c("/*", "*/", "* ", "** ", "*+ ", "*R ")
grepl(pattern="^\\*", x) # strings begin with an asterisk, "*"
# all but the first
grepl(pattern="^\\* ", x) # strings begin with an asterisk-space, "* "
# only the third one
grepl(pattern="^\\*[*] ", x) # strings begin with double asterisk, "**"
# only the fourth one
grepl(pattern="^\\*[\\*] ", x) # strings begin with double asterisk, "**"
# only the fourth one
grepl(pattern="^\\*[\\*+] ", x) # strings begin with double asterisk or asterisk-plus, "**" or "*+"
# fourth and fifth
grepl(pattern="^\\*[*+R] ", x) # any of **, *+, *R
# fourth, fifth, and sixth
grepl(pattern="^/[*]", x) # strings begin with a slash-asterisk, "/*"
# first only
grepl(pattern="^.*[*]/ *$", x) # strings end with a asterisk-slash, "*/"
# second only
x <- c(";", "anything;", "; ", ";\\n ", "\\;")
grepl(pattern=";", x)
# all
grepl(pattern=";$", x)
# first, second, fifth
grepl(pattern=";[[:blank:]]*$", x)
# all but fourth
grepl(pattern="^.*[\\];[[:blank:]]*$", x)
# only fifth
grepl(pattern="^.*[^\\]*;[[:blank:]]*$", x)
# all but the fourth |
################################################################################
# The contents of this file are Teradata Public Content
# and have been released to the Public Domain.
# Licensed under BSD; see "license.txt" file for more information.
# Copyright (c) 2021 by Teradata
################################################################################
#
# R And Python Analytics with SCRIPT Table Operator
# Orange Book supplementary material
# Alexander Kolovos - August 2021 - v.2.1
#
# Example 1: Scoring (R version)
# File : ex1rFit.r
#
# Note: Present script is meant to be run on a client machine
#
# Fit a Ranfom Forests model to a given dataset. Export model information
# to an R model object to score data in a target SQL Engine database.
# Use case:
# Predict the propensity of a financial services customer base
# to open a credit card account.
#
# The present file creates the R model object for prediction, and saves it
# into "ex1rMod.rds". This task is assumed to take place on a client machine
# where the present script and the data file with the fitting data reside.
# Execute this script in advance of using the scoring script "ex1rSco.r"
# in the database.
#
# Requires the randomForest add-on package.
#
# Required input:
# - model fitting data from the file "ex1dataFit.csv"
#
# Output:
# - R model file "ex1rMod.rds". To be imported in the database together
# with the scoring R script.
#
################################################################################
# Load dependency package
library(randomForest)
# Import the fitting data from CSV file
cv <- c("numeric", "numeric", "numeric", "numeric", "numeric", "numeric",
"numeric", "numeric", "numeric", "numeric", "numeric", "numeric",
"numeric", "numeric", "numeric", "numeric", "numeric", "numeric",
"numeric", "numeric", "numeric", "numeric", "numeric", "numeric",
"numeric", "numeric", "numeric", "numeric")
trainDataDF <- try( read.table("ex1dataFit.csv", sep=",", flush=TRUE,
header=TRUE, quote="", na.strings="", colClasses=cv) )
# Change the class of the dependent variable to a factor to indicate to
# randomForest that we want to built a classification tree.
trainDataDF$cc_acct_ind = as.factor(trainDataDF$cc_acct_ind)
# For the classifier, specify the following parameters:
# ntree=10, mtry=3, and nodesize=1
RFmodel <- randomForest(formula = (cc_acct_ind ~
tot_income + tot_age + tot_cust_years +
tot_children + female_ind + single_ind +
married_ind + separated_ind +
ca_resident_ind + ny_resident_ind +
tx_resident_ind + il_resident_ind +
az_resident_ind + oh_resident_ind +
ck_acct_ind + sv_acct_ind + ck_avg_bal +
sv_avg_bal + ck_avg_tran_amt +
sv_avg_tran_amt + q1_trans_cnt +
q2_trans_cnt + q3_trans_cnt + q4_trans_cnt),
data = trainDataDF,
ntree = 10,
nodesize = 1,
mtry = 3)
RFmodel
# Export the Random Forest model into a file
saveRDS(RFmodel, "ex1rMod.rds")
|
# -*- coding: utf-8 -*-
from numpy import roll
def shift_wind_mat(wind_mat, Nshift):
"""Shift the Winding Matrix of Nshift number of Slot
Parameters
----------
wind_mat : numpy.ndarray
A Winding Matrix (Nlay_r, Nlay_theta, Zs,
qs) (created by comp_connection_mat)
Nshift : int
Number of Slot to shift (Integer 0 < Nshift < Zs)
Returns
-------
shift_wind_mat: numpy.ndarray
The shifted matrix along the Slot
"""
assert len(wind_mat.shape) == 4, "wind_mat has a wrong shape (dim 4)"
assert Nshift % 1 == 0, "Nshift must be an integer"
return roll(wind_mat, shift=Nshift, axis=2)
|
{-# OPTIONS --without-K --safe #-}
module Categories.Object.Subobject.Properties where
open import Level
open import Data.Product
open import Data.Unit
open import Function using (_$_)
open import Relation.Binary using (_=[_]⇒_)
open import Relation.Binary.Bundles
open import Relation.Binary.OrderMorphism
open import Categories.Category
open import Categories.Functor
open import Categories.Functor.Presheaf
open import Categories.Category.Slice
open import Categories.Object.Subobject
open import Categories.Diagram.Pullback renaming (glue to glue-pullback)
open import Categories.Diagram.Pullback.Properties
open import Categories.Category.Instance.Posets
open import Categories.Category.Instance.Setoids
open import Categories.Adjoint.Instance.PosetCore
import Categories.Morphism as Mor
import Categories.Morphism.Reasoning as MR
open import Categories.Morphism.Notation
module _ {o ℓ e} {𝒞 : Category o ℓ e} (has-pullbacks : ∀ {A B X} → (f : 𝒞 [ A , X ]) → (g : 𝒞 [ B , X ]) → Pullback 𝒞 f g) where
private
module 𝒞 = Category 𝒞
open 𝒞.HomReasoning
open 𝒞.Equiv
open Mor 𝒞
open MR 𝒞
open _↣_
-- The Subobject functor, into the category of posets
Subₚ : Presheaf 𝒞 (Posets (o ⊔ ℓ ⊔ e) (ℓ ⊔ e) (ℓ ⊔ e))
Subₚ = record
{ F₀ = Subobjects 𝒞
; F₁ = λ f → record
{ fun = morphism f
; monotone = λ {(α , m) (β , n)} h → monotone f {(α , m)} {β , n} h
}
; identity = λ {A} {(α , m)} →
let pid = has-pullbacks 𝒞.id (mor m)
in record
{ from = record
{ h = Pullback.p₂ pid
; △ = ⟺ (Pullback.commute pid) ○ 𝒞.identityˡ
}
; to = record
{ h = Pullback.universal pid id-comm-sym
; △ = Pullback.p₁∘universal≈h₁ pid
}
; iso = record
{ isoˡ = pullback-identity 𝒞 pid
; isoʳ = Pullback.p₂∘universal≈h₂ pid
}
}
; homomorphism = λ {X} {Y} {Z} {f} {g} {(α , m)} →
let pfg = has-pullbacks (𝒞 [ f ∘ g ]) (mor m)
pf = has-pullbacks f (mor m)
pg = has-pullbacks g (Pullback.p₁ pf)
iso = up-to-iso 𝒞 pfg (glue-pullback 𝒞 pf pg)
module iso = _≅_ iso
in record
{ from = record
{ h = iso.from
; △ = Pullback.p₁∘universal≈h₁ pg
}
; to = record
{ h = iso.to
; △ = Pullback.p₁∘universal≈h₁ pfg
}
; iso = record
{ isoˡ = iso.isoˡ
; isoʳ = iso.isoʳ
}
}
; F-resp-≈ = λ {A B f g} eq {(α , m)} →
let pf = has-pullbacks f (mor m)
pg = has-pullbacks g (mor m)
iso = up-to-iso 𝒞 pf (pullback-resp-≈ 𝒞 pg (sym eq) refl)
module iso = _≅_ iso
in record
{ from = record
{ h = iso.from
; △ = Pullback.p₁∘universal≈h₁ pg
}
; to = record
{ h = iso.to
; △ = Pullback.p₁∘universal≈h₁ pf
}
; iso = record
{ isoˡ = iso.isoˡ
; isoʳ = iso.isoʳ
}
}
}
where
morphism : ∀ {A B} → (f : 𝒞 [ B , A ]) → Σ[ α ∈ 𝒞.Obj ] (α ↣ A) → Σ[ β ∈ 𝒞.Obj ] (β ↣ B)
morphism f (α , m) =
let pb = has-pullbacks f (mor m)
in Pullback.P pb , record
{ mor = Pullback.p₁ pb
; mono = Pullback-resp-Mono 𝒞 pb (mono m)
}
monotone : ∀ {A B} (f : 𝒞 [ B , A ]) → Poset._≤_ (Subobjects 𝒞 A) =[ morphism f ]⇒ Poset._≤_ (Subobjects 𝒞 B)
monotone f {(α , m)} {(β , n)} h =
let pm = has-pullbacks f (mor m)
pn = has-pullbacks f (mor n)
in record
{ h = Pullback.universal pn $ begin
𝒞 [ f ∘ Pullback.p₁ pm ] ≈⟨ Pullback.commute pm ⟩
𝒞 [ mor m ∘ Pullback.p₂ pm ] ≈⟨ pushˡ (⟺ (Slice⇒.△ h)) ⟩
𝒞 [ mor n ∘ 𝒞 [ Slice⇒.h h ∘ Pullback.p₂ pm ] ] ∎
; △ = Pullback.p₁∘universal≈h₁ pn
}
-- The subobject functor as a presheaf on Setoids.
-- This is just Subₚ composed with the 'Core'
Sub : Presheaf 𝒞 (Setoids (o ⊔ ℓ ⊔ e) (ℓ ⊔ e))
Sub = Core ∘F Subₚ
|
---
title: Logic
subtitle: An Idris port of Coq.Init.Logic
title-meta: "Logic: An Idris port of Coq.Init.Logic"
author:
- |
\affaddr{Eric Bailey}\
\affaddr{https://github.com/yurrriq}\
\email{[email protected]}
author-meta: Eric Bailey
abstract: Here I present an Idris port of the [`Coq.Init.Logic`](https://coq.inria.fr/library/Coq.Init.Logic.html) module from the Coq standard library.
keywords:
- logic
- coq
- idris
pandoc-minted:
language: idris
---
> ||| An Idris port of Coq.Init.Logic
> module Logic
>
> import Data.Bifunctor
>
> %access export
= Propositional connectives
== Unit
`()` is the always true proposition ($\top$).
```idris
%elim data Unit = MkUnit
```
== Void
`Void` is the always false proposition ($\bot$).
```idris
%elim data Void : Type where
```
== Negation
`Not a`, written `~a`, is the negation of `a`.
> syntax "~" [x] = (Not x)
```idris
Not : Type -> Type
Not a = a -> Void
```
== Conjunction
`And a b`, written `(a, b)`, is the conjunction of `a` and `b`.
`Conj p q` is a proof of `(a, b)` as soon as `p` is a proof of `a` and `q` a proof of `b`.
`proj1` and `proj2` are first and second projections of a conjunction.
> syntax "(" [a] "," [b] ")" = (And a b)
>
> ||| The conjunction of `a` and `b`.
> data And : Type -> Type -> Type where
> Conj : a -> b -> (a, b)
>
> implementation Bifunctor And where
> bimap f g (Conj a b) = Conj (f a) (g b)
>
> ||| First projection of a conjunction.
> proj1 : (a, b) -> a
> proj1 (Conj a _) = a
>
> ||| Second projection of a conjunction.
> proj2 : (a, b) -> b
> proj2 (Conj _ b) = b
== Disjunction
`Either a b` is the disjunction of `a` and `b`.
```idris
data Either : Type -> Type -> Type where
Left : a -> Either a b
Right : b -> Either a b
```
== Biconditional
[Proof Wiki](https://proofwiki.org/wiki/Definition:Biconditional)
<!-- $\varphi \vdash \psi$\ -->
<!-- $\underline{\psi \vdash \varphi}$\ -->
<!-- $\varphi \iff \psi$ -->
`iff a b`, written `a <-> b`, expresses the equivalence of `a` and `b`.
> infixl 9 <->
>
> ||| The biconditional is a *binary connective* that can be voiced:
> ||| *p* **if and only if** *q*.
> public export
> (<->) : Type -> Type -> Type
> (<->) a b = (a -> b, b -> a)
=== Biconditional is Reflexive
[Proof Wiki](https://proofwiki.org/wiki/Biconditional_is_Reflexive)
$\vdash \varphi \iff \varphi$
> ||| The biconditional operator is reflexive.
> iffRefl : a <-> a
> iffRefl = Conj id id
=== Biconditional is Transitive
[Proof Wiki](https://proofwiki.org/wiki/Biconditional_is_Transitive)
<!-- \[ -->
<!-- \begin{prooftree} -->
<!-- \Hypo{ \varphi \iff \psi } -->
<!-- \Hypo{ \psi \iff \chi } -->
<!-- \Infer2 { \vdash \varphi \iff \chi } -->
<!-- \end{prooftree} -->
<!-- \] -->
> ||| The biconditional operator is transitive.
> iffTrans : (a <-> b) -> (b <-> c) -> (a <-> c)
> iffTrans (Conj ab ba) (Conj bc cb) =
> Conj (bc . ab) (ba . cb)
=== Biconditional is Commutative
[Proof Wiki](https://proofwiki.org/wiki/Biconditional_is_Commutative)
$\varphi \iff \psi \dashv\vdash \psi \iff \varphi$
or
$\vdash (\varphi \iff \psi) \iff (\psi \iff \varphi)$
> ||| The biconditional operator is commutative.
> iffSym : (a <-> b) -> (b <-> a)
> iffSym (Conj ab ba) = Conj ba ab
=== andIffCompatLeft
$\psi \iff \chi \dashv\vdash (\varphi \land \psi) \iff (\varphi \land \chi)$
> andIffCompatLeft : (b <-> c) -> ((a, b) <-> (a, c))
> andIffCompatLeft = bimap second second
=== andIffCompatRight
$\psi \iff \chi \dashv\vdash (\psi \land \varphi) \iff (\chi \land \varphi)$
> andIffCompatRight : (b <-> c) -> ((b, a) <-> (c, a))
> andIffCompatRight = bimap first first
=== orIffCompatLeft
$\psi \iff \chi \vdash (\varphi \lor \psi) \iff (\varphi \lor \chi)$
> orIffCompatLeft : (b <-> c) ->
> (Either a b <-> Either a c)
> orIffCompatLeft = bimap second second
=== orIffCompatRight
$\psi \iff \chi \vdash (\psi \lor \varphi) \iff (\chi \lor \varphi)$
> orIffCompatRight : (b <-> c) ->
> (Either b a <-> Either c a)
> orIffCompatRight = bimap first first
=== negVoid
$\neg \varphi \dashv\vdash \varphi \iff \bot$
or
$\vdash \neg \varphi \iff (\varphi \iff \bot)$
> negVoid : (~a) <-> (a <-> Void)
> negVoid = Conj (flip Conj void) proj1
=== andCancelLeft
<!-- $\psi \implies \varphi$\ -->
<!-- $\underline{\chi \implies \varphi}$\ -->
<!-- $((\varphi \land \psi) \iff (\varphi \land \chi)) \iff (\psi \iff \chi)$ -->
> andCancelLeft : (b -> a) ->
> (c -> a) ->
> (((a, b) <-> (a, c)) <-> (b <-> c))
> andCancelLeft ba ca = Conj (bimap f g) andIffCompatLeft
> where
> f h b = proj2 . h $ Conj (ba b) b
> g h c = proj2 . h $ Conj (ca c) c
=== andCancelRight
> andCancelRight : (b -> a) ->
> (c -> a) ->
> (((b, a) <-> (c, a)) <-> (b <-> c))
> andCancelRight ba ca = Conj (bimap f g) andIffCompatRight
> where
> f h b = proj1 . h $ Conj b (ba b)
> g h c = proj1 . h $ Conj c (ca c)
=== Conjunction is Commutative
[Proof Wiki](https://proofwiki.org/wiki/Rule_of_Commutation/Conjunction)
==== Formulation 1
$\varphi \land \psi \dashv\vdash \psi \land \varphi$
==== Formulation 2
$\vdash (\varphi \land \psi) \iff (\psi \land \varphi)$
==== Source
> ||| Conjunction is commutative.
> andComm : (a, b) <-> (b, a)
> andComm = Conj swap swap
> where
> swap : (p, q) -> (q, p)
> swap (Conj p q) = Conj q p
=== Conjunction is Associative
[Proof Wiki](https://proofwiki.org/wiki/Rule_of_Association/Conjunction)
==== Formulation 1
$(\varphi \land \psi) \land \chi \dashv\vdash \varphi \land (\psi \land \chi)$
==== Formulation 2
$\vdash ((\varphi \land \psi) \land \chi) \iff (\varphi \land (\psi \land \chi))$
==== Source
> ||| Conjunction is associative.
> andAssoc : ((a, b), c) <-> (a, (b, c))
> andAssoc = Conj f g
> where
> f abc@(Conj (Conj a b) c) = Conj a (first proj2 abc)
> g abc@(Conj a (Conj b c)) = Conj (second proj1 abc) c
=== orCancelLeft
$(\psi \implies \neg \varphi) \implies (\chi \implies \neg \varphi) \implies (((\varphi \lor \psi) \iff (\varphi \lor \chi)) \iff (\psi \iff \chi))$
> orCancelLeft : (b -> ~a) ->
> (c -> ~a) ->
> ((Either a b <-> Either a c) <-> (b <-> c))
> orCancelLeft bNotA cNotA = Conj (bimap f g) orIffCompatLeft
> where
> f ef b = go (bNotA b) (ef (Right b))
> g eg c = go (cNotA c) (eg (Right c))
> go : (~a) -> Either a b -> b
> go lf = either (void . lf) id
=== orCancelRight
<!-- $\psi \vdash \neg \varphi$\ -->
<!-- $\underline{\chi \vdash \neg \varphi}$\ -->
<!-- $((\psi \lor \varphi) \iff (\chi \lor \varphi)) \iff (\psi \iff \chi)$ -->
> orCancelRight : (b -> ~a) ->
> (c -> ~a) ->
> ((Either b a <-> Either c a) <-> (b <-> c))
> orCancelRight bNotA cNotA = Conj (bimap f g) orIffCompatRight
> where
> f ef b = go (bNotA b) (ef (Left b))
> g eg c = go (cNotA c) (eg (Left c))
> go : (~p) -> Either q p -> q
> go rf = either id (void . rf)
=== Disjunction is Commutative
[Proof Wiki](https://proofwiki.org/wiki/Rule_of_Commutation/Disjunction)
$(\varphi \lor \psi) \iff (\psi \lor \varphi)$
> ||| Disjunction is commutative.
> orComm : Either a b <-> Either b a
> orComm = Conj mirror mirror
=== Disjunction is Associative
[Proof Wiki](https://proofwiki.org/wiki/Rule_of_Association/Disjunction)
$(\varphi \lor \psi) \lor \chi \vdash \varphi \lor (\psi \lor \chi)$
> ||| Disjunction is associative on the left.
> orAssocLeft : Either (Either a b) c -> Either a (Either b c)
> orAssocLeft = either (second Left) (pure . pure)
$\varphi \lor (\psi \lor \chi) \vdash (\varphi \lor \psi) \lor \chi$
> ||| Disjunction is associative on the right.
> orAssocRight : Either a (Either b c) -> Either (Either a b) c
> orAssocRight = either (Left . Left) (first Right)
==== Formulation 1
$(\varphi \lor \psi) \lor \chi \dashv\vdash \varphi \lor (\psi \lor \chi)$
==== Formulation 2
$\vdash ((\varphi \lor \psi) \lor \chi) \iff (\varphi \lor (\psi \lor \chi))$
==== Source
> ||| Disjunction is associative.
> orAssoc : Either (Either a b) c <-> Either a (Either b c)
> orAssoc = Conj orAssocLeft orAssocRight
=== iffAnd
$\varphi \iff \psi \vdash (\varphi \implies \psi) \land (\psi \implies \varphi)$
> iffAnd : (a <-> b) -> (a -> b, b -> a)
> iffAnd = id
=== iffAndTo
$\varphi \iff \psi \dashv\vdash (\varphi \implies \psi) \land (\psi \implies \varphi)$
or
$\vdash (\varphi \iff \psi) \iff ((\varphi \implies \psi) \land (\psi \implies \varphi))$
> iffToAnd : (a <-> b) <-> (a -> b, b -> a)
> iffToAnd = Conj id id
|
This article on engagement ring statistics was last updated on December 18, 2018. This article will hopefully help couple’s make more informed decisions when purchasing their engagement ring.
Here are some of the statistics that we compiled based on our research. See below for sources and techniques of how we gathered our data.
From the 10,000’s of couples who we surveyed in 2018, 24.4% of them said that they have allocated a High Budget towards their engagement ring. 54.8% of those surveyed said that they have allocated a Medium Budget towards their engagement ring. Only 21.8% of the people asked said that they allocated a low budget towards their engagement ring.
Of course, this data only represents a relative figure that can only be understood based on each couple’s personal budget. This statistic, however, belays the importance that couples in 2018 are placing on their engagement rings.
Part of our questionnaire asks the couple’s to gauge their lifestyle. The options were between modest, average, upper class, and luxury. This graph represents their answers and also give insight into the self-projection of where people think that they are holding when in the search for an engagement ring. The overwhelming majority of couples felt that their lifestyle was average.
Like some of the earlier graphs, this statistical chart gives relative data instead of numerical data. The amount of debt isn’t a set amount but rather a relative amount as defined by the survey-takers expectations and opinion.
Only 28.4% of the couple’s surveyed had no debt. The remaining 71.6% of people looking for engagement ring already had existing debt.
This data chart is interesting. It shows the popularity of the keyword “engagement ring” over the years. It starts from 2004 and runs until 2018. The popularity of the keyword has stayed more-or-less in the same place. There was a rise between 2009 – 2012. The keyword has slowly been decreasing since 2012.
Important Note: It could be that the searches have gotten smarter and more people are typing more complicated searches into google instead of the simple catch-all “engagement ring”. Couples are probably typing something like “3-carat vintage engagement rings” into Google instead.
Estate Diamond Jewelry has been in business since 1981 and has a large network of buyers. Because we focus on ethical jewelry and vintage engagement rings, our niche is limited and our personal data doesn’t reflect the market as a whole. It is for that reason that we discarded our own data and began collecting data from a fresh angle.
In 2016, we created an online engagement ring budget calculator that has so far quizzed 10,000’s of potential engagement ring buyers. The form helps couples discover an appropriate budget when shopping for their engagement ring. After discounting the outlying and erroneous data, we have managed to discover fantastic data that sheds a lot of light on the engagement ring.
In 2017, we created another form called the engagement ring finder. This form helps couples find their dream ring. They input what type of ring they are looking for and we search for them. We always encourage our potential customers to buy vintage, but the results aren’t limited to the niche.
Some of our data is also collected from other jewelry stores and websites.
We used Google Trends to determine our search-based statistics. |
Require Export SfLib.
Module AExp.
Inductive aexp : Type :=
| ANum : nat -> aexp
| APlus : aexp -> aexp -> aexp
| AMinus : aexp -> aexp -> aexp
| AMult : aexp -> aexp -> aexp.
Inductive bexp : Type :=
| BTrue : bexp
| BFalse : bexp
| BEq : aexp -> aexp -> bexp
| BLe : aexp -> aexp -> bexp
| BNot : bexp -> bexp
| BAnd : bexp -> bexp -> bexp.
Fixpoint aeval (a : aexp) : nat :=
match a with
| ANum n => n
| APlus a1 a2 => (aeval a1) + (aeval a2)
| AMinus a1 a2 => (aeval a1) - (aeval a2)
| AMult a1 a2 => (aeval a1) * (aeval a2)
end.
Example test_aeval1:
aeval (APlus (ANum 2) (ANum 2)) = 4.
Proof. reflexivity. Qed.
Fixpoint beval (b : bexp) : bool :=
match b with
| BTrue => true
| BFalse => false
| BEq a1 a2 => beq_nat (aeval a1) (aeval a2)
| BLe a1 a2 => ble_nat (aeval a1) (aeval a2)
| BNot b1 => negb (beval b1)
| BAnd b1 b2 => andb (beval b1) (beval b2)
end.
Fixpoint optimize_0plus (a:aexp) : aexp :=
match a with
| ANum n => ANum n
| APlus (ANum 0) e2 => optimize_0plus e2
| APlus e1 e2 => APlus (optimize_0plus e1) (optimize_0plus e2)
| AMinus e1 e2 => AMinus (optimize_0plus e1) (optimize_0plus e2)
| AMult e1 e2 => AMult (optimize_0plus e1) (optimize_0plus e2)
end.
Example test_optimize_0plus:
optimize_0plus (APlus (ANum 2)
(APlus (ANum 0)
(APlus (ANum 0) (ANum 1))))
= APlus (ANum 2) (ANum 1).
Proof. reflexivity. Qed.
Theorem optimize_0plus_sound :
forall a,
aeval (optimize_0plus a) = aeval a.
Proof.
intros a.
induction a.
Case "ANum". reflexivity.
Case "APlus".
destruct a1.
SCase "a1 = ANum n".
destruct n.
SSCase "n = 0". simpl. apply IHa2.
SSCase "n <> 0". simpl. rewrite IHa2. reflexivity.
SCase "a1 = APlus a1_1 a1_2".
simpl. simpl in IHa1. rewrite IHa1.
rewrite IHa2. reflexivity.
SCase "a1 = AMinus a1_1 a1_2".
simpl. simpl in IHa1. rewrite IHa1.
rewrite IHa2. reflexivity.
SCase "a1 = AMult a1_1 a2_2".
simpl. simpl in IHa1. rewrite IHa1.
rewrite IHa2. reflexivity.
Case "AMinus".
simpl. rewrite IHa1. rewrite IHa2. reflexivity.
Case "AMult".
simpl. rewrite IHa1. rewrite IHa2. reflexivity.
Qed.
Theorem optimize_0plus_sound' :
forall a,
aeval (optimize_0plus a) = aeval a.
Proof.
intros a.
induction a;
try (simpl; rewrite IHa1; rewrite IHa2; reflexivity);
try reflexivity.
Case "APlus".
destruct a1;
try (simpl; simpl in IHa1; rewrite IHa1; rewrite IHa2; reflexivity).
SCase "a1 = ANum n".
destruct n;
simpl; rewrite IHa2; reflexivity.
Qed.
Tactic Notation "aexp_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "ANum" | Case_aux c "APlus"
| Case_aux c "AMinus" | Case_aux c "AMult" ].
Theorem optimize_0plus_sound'' :
forall a,
aeval (optimize_0plus a) = aeval a.
Proof.
intros a.
aexp_cases (induction a) Case;
try (simpl; rewrite IHa1; rewrite IHa2; reflexivity);
try reflexivity.
Case "APlus".
aexp_cases (destruct a1) SCase;
try (simpl; simpl in IHa1; rewrite IHa1; rewrite IHa2; reflexivity).
SCase "ANum".
destruct n;
simpl; rewrite IHa2; reflexivity.
Qed.
Fixpoint optimize_0plus_b (b : bexp) : bexp :=
match b with
| BTrue => BTrue
| BFalse => BFalse
| BEq a1 a2 => BEq (optimize_0plus a1) (optimize_0plus a2)
| BLe a1 a2 => BLe (optimize_0plus a1) (optimize_0plus a2)
| BNot b1 => BNot (optimize_0plus_b b1)
| BAnd b1 b2 => BAnd (optimize_0plus_b b1) (optimize_0plus_b b2)
end.
Tactic Notation "bexp_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "BTrue" | Case_aux c "BFalse"
| Case_aux c "BEq" | Case_aux c "BLe"
| Case_aux c "BNot" | Case_aux c "BAnd" ].
Theorem optimize_0plus_b_sound :
forall b,
beval (optimize_0plus_b b) = beval b.
Proof.
intros b.
bexp_cases (induction b) Case;
try reflexivity;
try (simpl; repeat (rewrite optimize_0plus_sound); reflexivity);
try (simpl; rewrite IHb; reflexivity);
try (simpl; rewrite IHb1; rewrite IHb2; reflexivity).
Qed.
|
lemma fmeasurableI: "A \<in> sets M \<Longrightarrow> emeasure M A < \<infinity> \<Longrightarrow> A \<in> fmeasurable M" |
import pandas as pd
import numpy as np
import re
import time
import bs4 as bs4
import requests as rq
import io
import sys
queries = ["pydata","NLP","machine+learning","docker","scrapy","mongodb","markov","active+learning","jenkins","tensorflow","kubernetes"]
url = "https://www.youtube.com/results?search_query={query}&sp=CAI%253D&p={page}"
for query in queries:
for page in range(1,15):
urll = url.format(query=query, page=page)
print(urll)
response = rq.get(urll)
with io.open("C:/Users/joaor/Documents/Projetos/data/raspadinha/pages/{}_{}.html".format(query,page), "w",encoding="utf-8") as output:
output.write(response.text)
time.sleep(0.1)
|
###############################################################################
## ##
## ##
###############################################################################
###############################################################################
## Load required packages ##
library(shiny)
library(ggplot2)
library(RMySQL)
library(DT)
library(colourpicker)
## To be added soon
#library(colourpicker)
## ##
###############################################################################
###############################################################################
## ##
dfkey <- read.delim("connect/db.txt", header = T, sep="\t", stringsAsFactors = F)
geneDefault = as.character(dfkey$default)
host <- as.character(dfkey$url)
user <- as.character(dfkey$id)
DBpd <- as.character(dfkey$id2)
dbname <- as.character(dfkey$db)
coordinateTbName <- as.character(dfkey$coordTb)
exprTbName <- as.character(dfkey$exprTb)
geneID_TbName <- as.character(dfkey$geneTb)
## ##
###############################################################################
###############################################################################
## ##
oldw <- getOption("warn")
options(warn = -1)
dbDB <- dbConnect(MySQL(), user = user, password = DBpd, host = host, dbname=dbname)
query <- paste0("SELECT DISTINCT * FROM ", coordinateTbName)
dfCoordSel <- dbGetQuery(dbDB, query)
dbDisconnect(dbDB)
dfCoordSel[["all"]] <- "all"
## ##
###############################################################################
###############################################################################
## ##
conditionVec <- unique(sort(dfCoordSel$sampleName))
Nsamples <- length(conditionVec)
allOptions <- names(dfCoordSel)
rmNameVec <-c(
"^DC",
"uniquecellID",
"hmIdent",
"old_ident",
"cellID",
"sample_group",
"DF_pANN",
"clusterColor",
"sampleColor",
"clustIdent",
"G2M_Score",
"DM_Pseudotime",
"^Sub_clusters_ExNeurons$",
"sample_group_colors",
"row_names",
"sampleID"
)
rmVec <- as.vector(NULL, mode = "numeric")
for (i in 1:length(rmNameVec)){
rmVec <- c(
rmVec,
grep(rmNameVec[i], names(dfCoordSel))
)
}
XYsel <- allOptions
if (length(rmVec) > 0){
XYsel <- XYsel[-rmVec]
}
## Reorder
XYsel <- c(
XYsel[grep("UMAP_", XYsel)],
XYsel[grep("tSNE_", XYsel)],
XYsel[grep("sampleName", XYsel)],
XYsel[grep("clusterName", XYsel)],
XYsel[grep("ClusterTame", XYsel)],
XYsel[grep("ClusterTest", XYsel)],
XYsel[grep("PC_", XYsel)],
XYsel[grep("DM_Pseudotime", XYsel)],
XYsel[grep("meta_", XYsel)],
#XYsel[grep("DF_Classification", XYsel)],
XYsel[grep("nCount", XYsel)],
XYsel[grep("nFeatures", XYsel)],
XYsel[grep("nCount", XYsel)],
XYsel[grep("percent", XYsel)],
XYsel[grep("nCount", XYsel)],
XYsel[grep("nCount", XYsel)]
)
## Get color selection ##
allColorOptions <- c(
#"Log10 Expresson" = "lg10Expr",
#"DM Pseudotime" = "DM_Pseudotime",
"Sample" = "sampleName",
"Cluster" = "clusterName",
"Subcluster" = "subClusterName",
# "WT vs. IDH" = "WT_IDH",
"Gender" = "Gender",
# "Norm vs Hyp" = "Norm_Hyp",
# "Con Prad AZ" = "Con_Prad_AZ",
"Cells From Tumor" = "CellFromTumor",
"Patient" = "Patient",
"Region" = "Region",
"Article Cell Type" = "Article_Cell_Type",
"Doublet Classification" = "DF_Classification" ,
"nCount_RNA" = "nCount_RNA",
"nFeature_RNA" = "nFeature_RNA",
"percent_mt" = "percent_mt",
"S Phase Score" = "S_Score",
"G2M Score" = "G2M_Score",
"Cell Cycle Phase" = "Phase",
"Uniform" = "all"
)
colAddvec <- c(
XYsel[grep("ClusterTest", XYsel)],
XYsel[grep("meta_", XYsel)]
)
names(colAddvec) <- colAddvec
allColorOptions <- c(
allColorOptions,
colAddvec
)
splitOptions <- c(
"Sample" = "sampleName",
"Cluster" = "clusterName",
"SubCluster" = "subClusterName",
"Patient" = "Patient",
"Gender" = "Gender",
#"Norm vs Hyp" = "Norm_Hyp",
#"Con Prad AZ" = "Con_Prad_AZ",
"Cells From Tumor" = "CellFromTumor",
"Region" = "Region",
"Article Cell Type" = "Article_Cell_Type",
#"Doublet Classification" = "DF_Classification" ,
"None" = "all",
"WT vs. IDH" = "WT_IDH",
"Gender" = "Gender",
"Doublet Classification" = "DF_Classification" ,
"Cell Cycle Phase" = "Phase"
)
splitAddvec <- c(
#XYsel[grep("ClusterTest", XYsel)],
XYsel[grep("meta_", XYsel)]
)
names(splitAddvec) <- gsub("meta_", "",splitAddvec)
splitOptions <- c(
splitAddvec,
splitOptions
)
splitOptions <- splitOptions[splitOptions %in% names(dfCoordSel)]
allColorOptions <- allColorOptions[allColorOptions %in% names(dfCoordSel)]
allColorOptions <-
c(
"Log10 Expression" = "lg10Expr",
allColorOptions
)
## ##
###############################################################################
###############################################################################
## ##
oldw <- getOption("wafrn")
options(warn = -1)
dbDB <- dbConnect(MySQL(), user = user, password = DBpd, host = host, dbname=dbname)
query <- paste0("SELECT DISTINCT gene FROM ", geneID_TbName)
allGenes <- as.vector(dbGetQuery(dbDB, query)[,"gene"])
dbDisconnect(dbDB)
## ##
###############################################################################
###############################################################################
## ##
shinyUI(fluidPage(
navbarPage(
"bioLOGIC SC",
tabPanel("FeatureView"),
tags$head(
tags$style(type = 'text/css',
HTML('.navbar { background-color: #42972050;}
.navbar-default .navbar-brand{color: white;}
.tab-panel{ background-color: red; color: white}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:focus,
.navbar-default .navbar-nav > .active > a:hover {
color: #555;
background-color: #42972050;
}')
),
tags$script(HTML("var header = $('.navbar > .container-fluid');
header.append('<div style=\"float:left\"><ahref=\"URL\"><img src=\"assets/images/logo.ico\" alt=\"alt\" style=\"float:right;width:33px;height:41px;padding-top:10px;\"> </a>`</div>');
console.log(header)")
),
tags$link(rel="shortcut icon", href="assets/images/logo.ico")
)
),
#titlePanel("FeatureView"),
sidebarLayout(
sidebarPanel(
tags$style(".well {background-color:#42972050;}"),
helpText("To create a Violin-style plot, select, for example, as x-axis: seurat clusters, as y-axis: log10Expr and as colorBy: seurat clusters. \n\n To view averaged expression values for signature gene categories, start typing cat_ in the search box to see category suggestions. "),
selectizeInput("gene",
label = "Gene or Category Selection",
choices = NULL, #c(as.vector(sort(unique(allGenes)))),
selected = geneDefault,
options = list(maxOptions = 50)) ,
selectInput("x_axis",
label = "Choose an X-axis",
choices =unique(c("Log10 Expression" = "lg10Expr", allColorOptions, XYsel)),
selected = "UMAP_1"),
selectInput("y_axis",
label = "Choose an Y-axis",
choices =unique(c("Log10 Expression" = "lg10Expr", XYsel)),
selected = "UMAP_2"),
selectInput("splitByColumn",
label = "Split Plots By",
choices = splitOptions,
selected = splitOptions[1]),
selectInput("colorBy",
label = "Color Plots By",
choices = allColorOptions,
selected = names(allColorOptions)[1]),
## To be added soon
#colourInput("dotcolor", "Choose dot colorscale", "darkblue"),
colourInput("dotcolor", "Select colour", "darkblue"),
colourInput("lowColor", "Select colour", "#D3D3D3"),
selectInput("background",
label = "Select Background",
choices =c("Grey" = "grey", "White" = "white","Minimal" = "minimal", "Plain" = "plain"),
selected = "white"),
radioButtons("dotsize", label = "Choose a Dotsize", choices = c("0.1","0.5","1","2"), selected = "1",
inline = FALSE, width = NULL, choiceNames = c("0.1","0.5","1","2"),
choiceValues = c("0.1","0.5","1","2")),
# selectInput("dotsize",
# label = "Choose an Dotsize",
# choices =c("0.1","0.5","1","2"),
# selected = "1"),
#downloadButton('downloadPlot', "Download Plot"),
#downloadButton("downloadData", "Download Data"),
# checkboxGroupInput("selected_sample",
# label = "Select Column",
# choices = seq_along(mtcars))
),
mainPanel(
fluidRow(
column(12,
uiOutput("multi_plot_ui")
)
),
fluidRow(
column(12,
textOutput("dev_text")
)
)
)
)
))
## ##
###############################################################################
|
[GOAL]
c : Cardinal.{u_1}
co : ℵ₀ ≤ c
⊢ Ordinal.IsLimit (ord c)
[PROOFSTEP]
refine' ⟨fun h => aleph0_ne_zero _, fun a => lt_imp_lt_of_le_imp_le fun h => _⟩
[GOAL]
case refine'_1
c : Cardinal.{u_1}
co : ℵ₀ ≤ c
h : ord c = 0
⊢ ℵ₀ = 0
[PROOFSTEP]
rw [← Ordinal.le_zero, ord_le] at h
[GOAL]
case refine'_1
c : Cardinal.{u_1}
co : ℵ₀ ≤ c
h : c ≤ card 0
⊢ ℵ₀ = 0
[PROOFSTEP]
simpa only [card_zero, nonpos_iff_eq_zero] using co.trans h
[GOAL]
case refine'_2
c : Cardinal.{u_1}
co : ℵ₀ ≤ c
a : Ordinal.{u_1}
h : ord c ≤ succ a
⊢ ord c ≤ a
[PROOFSTEP]
rw [ord_le] at h ⊢
[GOAL]
case refine'_2
c : Cardinal.{u_1}
co : ℵ₀ ≤ c
a : Ordinal.{u_1}
h : c ≤ card (succ a)
⊢ c ≤ card a
[PROOFSTEP]
rwa [← @add_one_of_aleph0_le (card a), ← card_succ]
[GOAL]
case refine'_2
c : Cardinal.{u_1}
co : ℵ₀ ≤ c
a : Ordinal.{u_1}
h : c ≤ card (succ a)
⊢ ℵ₀ ≤ card a
[PROOFSTEP]
rw [← ord_le, ← le_succ_of_isLimit, ord_le]
[GOAL]
case refine'_2
c : Cardinal.{u_1}
co : ℵ₀ ≤ c
a : Ordinal.{u_1}
h : c ≤ card (succ a)
⊢ ℵ₀ ≤ card (succ a)
[PROOFSTEP]
exact co.trans h
[GOAL]
case refine'_2.h
c : Cardinal.{u_1}
co : ℵ₀ ≤ c
a : Ordinal.{u_1}
h : c ≤ card (succ a)
⊢ Ordinal.IsLimit (ord ℵ₀)
[PROOFSTEP]
rw [ord_aleph0]
[GOAL]
case refine'_2.h
c : Cardinal.{u_1}
co : ℵ₀ ≤ c
a : Ordinal.{u_1}
h : c ≤ card (succ a)
⊢ Ordinal.IsLimit ω
[PROOFSTEP]
exact omega_isLimit
[GOAL]
a b : Cardinal.{u_1}
⊢ alephIdx a ≤ alephIdx b ↔ a ≤ b
[PROOFSTEP]
rw [← not_lt, ← not_lt, alephIdx_lt]
[GOAL]
x✝ : ∃ b, ∀ (x : Ordinal.{u}), x < b ↔ ∃ y, ↑initialSeg y = x
o : Ordinal.{u}
e : ∀ (x : Ordinal.{u}), x < o ↔ ∃ y, ↑initialSeg y = x
⊢ False
[PROOFSTEP]
have : ∀ c, alephIdx c < o := fun c => (e _).2 ⟨_, rfl⟩
[GOAL]
x✝ : ∃ b, ∀ (x : Ordinal.{u}), x < b ↔ ∃ y, ↑initialSeg y = x
o : Ordinal.{u}
e : ∀ (x : Ordinal.{u}), x < o ↔ ∃ y, ↑initialSeg y = x
this : ∀ (c : Cardinal.{u}), alephIdx c < o
⊢ False
[PROOFSTEP]
refine' Ordinal.inductionOn o _ this
[GOAL]
x✝ : ∃ b, ∀ (x : Ordinal.{u}), x < b ↔ ∃ y, ↑initialSeg y = x
o : Ordinal.{u}
e : ∀ (x : Ordinal.{u}), x < o ↔ ∃ y, ↑initialSeg y = x
this : ∀ (c : Cardinal.{u}), alephIdx c < o
⊢ ∀ (α : Type u) (r : α → α → Prop) [inst : IsWellOrder α r], (∀ (c : Cardinal.{u}), alephIdx c < type r) → False
[PROOFSTEP]
intro α r _ h
[GOAL]
x✝ : ∃ b, ∀ (x : Ordinal.{u}), x < b ↔ ∃ y, ↑initialSeg y = x
o : Ordinal.{u}
e : ∀ (x : Ordinal.{u}), x < o ↔ ∃ y, ↑initialSeg y = x
this : ∀ (c : Cardinal.{u}), alephIdx c < o
α : Type u
r : α → α → Prop
inst✝ : IsWellOrder α r
h : ∀ (c : Cardinal.{u}), alephIdx c < type r
⊢ False
[PROOFSTEP]
let s := ⨆ a, invFun alephIdx (Ordinal.typein r a)
[GOAL]
x✝ : ∃ b, ∀ (x : Ordinal.{u}), x < b ↔ ∃ y, ↑initialSeg y = x
o : Ordinal.{u}
e : ∀ (x : Ordinal.{u}), x < o ↔ ∃ y, ↑initialSeg y = x
this : ∀ (c : Cardinal.{u}), alephIdx c < o
α : Type u
r : α → α → Prop
inst✝ : IsWellOrder α r
h : ∀ (c : Cardinal.{u}), alephIdx c < type r
s : Cardinal.{u} := ⨆ (a : α), Function.invFun alephIdx (typein r a)
⊢ False
[PROOFSTEP]
apply (lt_succ s).not_le
[GOAL]
x✝ : ∃ b, ∀ (x : Ordinal.{u}), x < b ↔ ∃ y, ↑initialSeg y = x
o : Ordinal.{u}
e : ∀ (x : Ordinal.{u}), x < o ↔ ∃ y, ↑initialSeg y = x
this : ∀ (c : Cardinal.{u}), alephIdx c < o
α : Type u
r : α → α → Prop
inst✝ : IsWellOrder α r
h : ∀ (c : Cardinal.{u}), alephIdx c < type r
s : Cardinal.{u} := ⨆ (a : α), Function.invFun alephIdx (typein r a)
⊢ succ s ≤ s
[PROOFSTEP]
have I : Injective.{u + 2, u + 2} alephIdx := alephIdx.initialSeg.toEmbedding.injective
[GOAL]
x✝ : ∃ b, ∀ (x : Ordinal.{u}), x < b ↔ ∃ y, ↑initialSeg y = x
o : Ordinal.{u}
e : ∀ (x : Ordinal.{u}), x < o ↔ ∃ y, ↑initialSeg y = x
this : ∀ (c : Cardinal.{u}), alephIdx c < o
α : Type u
r : α → α → Prop
inst✝ : IsWellOrder α r
h : ∀ (c : Cardinal.{u}), alephIdx c < type r
s : Cardinal.{u} := ⨆ (a : α), Function.invFun alephIdx (typein r a)
I : Injective alephIdx
⊢ succ s ≤ s
[PROOFSTEP]
simpa only [typein_enum, leftInverse_invFun I (succ s)] using
le_ciSup (Cardinal.bddAbove_range.{u, u} fun a : α => invFun alephIdx (Ordinal.typein r a))
(Ordinal.enum r _ (h (succ s)))
[GOAL]
⊢ (type fun x x_1 => x < x_1) = Ordinal.univ
[PROOFSTEP]
rw [Ordinal.univ_id]
[GOAL]
⊢ (type fun x x_1 => x < x_1) = type fun x x_1 => x < x_1
[PROOFSTEP]
exact Quotient.sound ⟨alephIdx.relIso⟩
[GOAL]
⊢ #Cardinal.{u} = univ
[PROOFSTEP]
simpa only [card_type, card_univ] using congr_arg card type_cardinal
[GOAL]
⊢ aleph' 0 = 0
[PROOFSTEP]
rw [← nonpos_iff_eq_zero, ← aleph'_alephIdx 0, aleph'_le]
[GOAL]
⊢ 0 ≤ alephIdx 0
[PROOFSTEP]
apply Ordinal.zero_le
[GOAL]
o : Ordinal.{u_1}
⊢ aleph' (succ o) = succ (aleph' o)
[PROOFSTEP]
apply (succ_le_of_lt <| aleph'_lt.2 <| lt_succ o).antisymm' (Cardinal.alephIdx_le.1 <| _)
[GOAL]
o : Ordinal.{u_1}
⊢ alephIdx (aleph' (succ o)) ≤ alephIdx (succ (aleph' o))
[PROOFSTEP]
rw [alephIdx_aleph', succ_le_iff, ← aleph'_lt, aleph'_alephIdx]
[GOAL]
o : Ordinal.{u_1}
⊢ aleph' o < succ (aleph' o)
[PROOFSTEP]
apply lt_succ
[GOAL]
n : ℕ
⊢ aleph' (succ ↑n) = ↑(Nat.succ n)
[PROOFSTEP]
rw [aleph'_succ, aleph'_nat n, nat_succ]
[GOAL]
o : Ordinal.{u_1}
l : Ordinal.IsLimit o
c : Cardinal.{u_1}
h : ∀ (o' : Ordinal.{u_1}), o' < o → aleph' o' ≤ c
⊢ aleph' o ≤ c
[PROOFSTEP]
rw [← aleph'_alephIdx c, aleph'_le, limit_le l]
[GOAL]
o : Ordinal.{u_1}
l : Ordinal.IsLimit o
c : Cardinal.{u_1}
h : ∀ (o' : Ordinal.{u_1}), o' < o → aleph' o' ≤ c
⊢ ∀ (x : Ordinal.{u_1}), x < o → x ≤ alephIdx c
[PROOFSTEP]
intro x h'
[GOAL]
o : Ordinal.{u_1}
l : Ordinal.IsLimit o
c : Cardinal.{u_1}
h : ∀ (o' : Ordinal.{u_1}), o' < o → aleph' o' ≤ c
x : Ordinal.{u_1}
h' : x < o
⊢ x ≤ alephIdx c
[PROOFSTEP]
rw [← aleph'_le, aleph'_alephIdx]
[GOAL]
o : Ordinal.{u_1}
l : Ordinal.IsLimit o
c : Cardinal.{u_1}
h : ∀ (o' : Ordinal.{u_1}), o' < o → aleph' o' ≤ c
x : Ordinal.{u_1}
h' : x < o
⊢ aleph' x ≤ c
[PROOFSTEP]
exact h _ h'
[GOAL]
o : Ordinal.{u_1}
ho : Ordinal.IsLimit o
⊢ aleph' o = ⨆ (a : ↑(Iio o)), aleph' ↑a
[PROOFSTEP]
refine' le_antisymm _ (ciSup_le' fun i => aleph'_le.2 (le_of_lt i.2))
[GOAL]
o : Ordinal.{u_1}
ho : Ordinal.IsLimit o
⊢ aleph' o ≤ ⨆ (a : ↑(Iio o)), aleph' ↑a
[PROOFSTEP]
rw [aleph'_le_of_limit ho]
[GOAL]
o : Ordinal.{u_1}
ho : Ordinal.IsLimit o
⊢ ∀ (o' : Ordinal.{u_1}), o' < o → aleph' o' ≤ ⨆ (a : ↑(Iio o)), aleph' ↑a
[PROOFSTEP]
exact fun a ha => le_ciSup (bddAbove_of_small _) (⟨a, ha⟩ : Iio o)
[GOAL]
c : Cardinal.{u_1}
⊢ aleph' ω ≤ c ↔ ℵ₀ ≤ c
[PROOFSTEP]
simp only [aleph'_le_of_limit omega_isLimit, lt_omega, exists_imp, aleph0_le]
[GOAL]
c : Cardinal.{u_1}
⊢ (∀ (o' : Ordinal.{u_1}) (x : ℕ), o' = ↑x → aleph' o' ≤ c) ↔ ∀ (n : ℕ), ↑n ≤ c
[PROOFSTEP]
exact forall_swap.trans (forall_congr' fun n => by simp only [forall_eq, aleph'_nat])
[GOAL]
c : Cardinal.{u_1}
n : ℕ
⊢ (∀ (x : Ordinal.{u_1}), x = ↑n → aleph' x ≤ c) ↔ ↑n ≤ c
[PROOFSTEP]
simp only [forall_eq, aleph'_nat]
[GOAL]
o₁ o₂ : Ordinal.{u_1}
⊢ max (aleph o₁) (aleph o₂) = aleph (max o₁ o₂)
[PROOFSTEP]
cases' le_total (aleph o₁) (aleph o₂) with h h
[GOAL]
case inl
o₁ o₂ : Ordinal.{u_1}
h : aleph o₁ ≤ aleph o₂
⊢ max (aleph o₁) (aleph o₂) = aleph (max o₁ o₂)
[PROOFSTEP]
rw [max_eq_right h, max_eq_right (aleph_le.1 h)]
[GOAL]
case inr
o₁ o₂ : Ordinal.{u_1}
h : aleph o₂ ≤ aleph o₁
⊢ max (aleph o₁) (aleph o₂) = aleph (max o₁ o₂)
[PROOFSTEP]
rw [max_eq_left h, max_eq_left (aleph_le.1 h)]
[GOAL]
o : Ordinal.{u_1}
⊢ aleph (succ o) = succ (aleph o)
[PROOFSTEP]
rw [aleph, add_succ, aleph'_succ, aleph]
[GOAL]
⊢ aleph 0 = ℵ₀
[PROOFSTEP]
rw [aleph, add_zero, aleph'_omega]
[GOAL]
o : Ordinal.{u_1}
ho : Ordinal.IsLimit o
⊢ aleph o = ⨆ (a : ↑(Iio o)), aleph ↑a
[PROOFSTEP]
apply le_antisymm _ (ciSup_le' _)
[GOAL]
o : Ordinal.{u_1}
ho : Ordinal.IsLimit o
⊢ aleph o ≤ ⨆ (i : ↑(Iio o)), aleph ↑i
[PROOFSTEP]
rw [aleph, aleph'_limit (ho.add _)]
[GOAL]
o : Ordinal.{u_1}
ho : Ordinal.IsLimit o
⊢ ⨆ (a : ↑(Iio (ω + o))), aleph' ↑a ≤ ⨆ (i : ↑(Iio o)), aleph ↑i
[PROOFSTEP]
refine' ciSup_mono' (bddAbove_of_small _) _
[GOAL]
o : Ordinal.{u_1}
ho : Ordinal.IsLimit o
⊢ ∀ (i : ↑(Iio (ω + o))), ∃ i', aleph' ↑i ≤ aleph ↑i'
[PROOFSTEP]
rintro ⟨i, hi⟩
[GOAL]
case mk
o : Ordinal.{u_1}
ho : Ordinal.IsLimit o
i : Ordinal.{u_1}
hi : i ∈ Iio (ω + o)
⊢ ∃ i', aleph' ↑{ val := i, property := hi } ≤ aleph ↑i'
[PROOFSTEP]
cases' lt_or_le i ω with h h
[GOAL]
case mk.inl
o : Ordinal.{u_1}
ho : Ordinal.IsLimit o
i : Ordinal.{u_1}
hi : i ∈ Iio (ω + o)
h : i < ω
⊢ ∃ i', aleph' ↑{ val := i, property := hi } ≤ aleph ↑i'
[PROOFSTEP]
rcases lt_omega.1 h with ⟨n, rfl⟩
[GOAL]
case mk.inl.intro
o : Ordinal.{u_1}
ho : Ordinal.IsLimit o
n : ℕ
hi : ↑n ∈ Iio (ω + o)
h : ↑n < ω
⊢ ∃ i', aleph' ↑{ val := ↑n, property := hi } ≤ aleph ↑i'
[PROOFSTEP]
use⟨0, ho.pos⟩
[GOAL]
case h
o : Ordinal.{u_1}
ho : Ordinal.IsLimit o
n : ℕ
hi : ↑n ∈ Iio (ω + o)
h : ↑n < ω
⊢ aleph' ↑{ val := ↑n, property := hi } ≤ aleph ↑{ val := 0, property := (_ : 0 < o) }
[PROOFSTEP]
simpa using (nat_lt_aleph0 n).le
[GOAL]
case mk.inr
o : Ordinal.{u_1}
ho : Ordinal.IsLimit o
i : Ordinal.{u_1}
hi : i ∈ Iio (ω + o)
h : ω ≤ i
⊢ ∃ i', aleph' ↑{ val := i, property := hi } ≤ aleph ↑i'
[PROOFSTEP]
exact ⟨⟨_, (sub_lt_of_le h).2 hi⟩, aleph'_le.2 (le_add_sub _ _)⟩
[GOAL]
o : Ordinal.{u_1}
ho : Ordinal.IsLimit o
⊢ ∀ (i : ↑(Iio o)), aleph ↑i ≤ aleph o
[PROOFSTEP]
exact fun i => aleph_le.2 (le_of_lt i.2)
[GOAL]
o : Ordinal.{u_1}
⊢ ℵ₀ ≤ aleph' o ↔ ω ≤ o
[PROOFSTEP]
rw [← aleph'_omega, aleph'_le]
[GOAL]
o : Ordinal.{u_1}
⊢ ℵ₀ ≤ aleph o
[PROOFSTEP]
rw [aleph, aleph0_le_aleph']
[GOAL]
o : Ordinal.{u_1}
⊢ ω ≤ ω + o
[PROOFSTEP]
apply Ordinal.le_add_right
[GOAL]
o : Ordinal.{u_1}
ho : 0 < o
⊢ 0 < aleph' o
[PROOFSTEP]
rwa [← aleph'_zero, aleph'_lt]
[GOAL]
o : Ordinal.{?u.105251}
⊢ Nonempty (Quotient.out (ord (aleph o))).α
[PROOFSTEP]
rw [out_nonempty_iff_ne_zero, ← ord_zero]
[GOAL]
o : Ordinal.{?u.105266}
⊢ ord (aleph o) ≠ ord 0
[PROOFSTEP]
exact fun h => (ord_injective h).not_gt (aleph_pos o)
[GOAL]
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ c = aleph (alephIdx c - ω)
[PROOFSTEP]
rw [aleph, Ordinal.add_sub_cancel_of_le, aleph'_alephIdx]
[GOAL]
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ ω ≤ alephIdx c
[PROOFSTEP]
rwa [← aleph0_le_aleph', aleph'_alephIdx]
[GOAL]
o : Ordinal.{u_1}
l : Ordinal.IsLimit o
a : Ordinal.{u_1}
⊢ (ord ∘ aleph') o ≤ a ↔ ∀ (b : Ordinal.{u_1}), b < o → (ord ∘ aleph') b ≤ a
[PROOFSTEP]
simp [ord_le, aleph'_le_of_limit l]
[GOAL]
⊢ succ ℵ₀ = aleph 1
[PROOFSTEP]
rw [← aleph_zero, ← aleph_succ, Ordinal.succ_zero]
[GOAL]
⊢ ℵ₀ < aleph 1
[PROOFSTEP]
rw [← succ_aleph0]
[GOAL]
⊢ ℵ₀ < succ ℵ₀
[PROOFSTEP]
apply lt_succ
[GOAL]
α : Type u_1
s : Set α
⊢ Set.Countable s ↔ #↑s < aleph 1
[PROOFSTEP]
rw [← succ_aleph0, lt_succ_iff, le_aleph0_iff_set_countable]
[GOAL]
a : Ordinal.{u_1}
⊢ ord (succ (card a)) ∈ {b | ord (card b) = b}
[PROOFSTEP]
dsimp
[GOAL]
a : Ordinal.{u_1}
⊢ ord (card (ord (succ (card a)))) = ord (succ (card a))
[PROOFSTEP]
rw [card_ord]
[GOAL]
o : Ordinal.{u_1}
ho : ord (card o) = o
⊢ ord (aleph' (↑alephIdx.relIso (card o))) = o
[PROOFSTEP]
simpa using ho
[GOAL]
⊢ ord ∘ aleph' = enumOrd {b | ord (card b) = b}
[PROOFSTEP]
rw [← eq_enumOrd _ ord_card_unbounded, range_eq_iff]
[GOAL]
⊢ StrictMono (ord ∘ aleph') ∧
(∀ (a : Ordinal.{u_1}), (ord ∘ aleph') a ∈ {b | ord (card b) = b}) ∧
∀ (b : Ordinal.{u_1}), b ∈ {b | ord (card b) = b} → ∃ a, (ord ∘ aleph') a = b
[PROOFSTEP]
exact
⟨aleph'_isNormal.strictMono,
⟨fun a => by
dsimp
rw [card_ord], fun b hb => eq_aleph'_of_eq_card_ord hb⟩⟩
[GOAL]
a : Ordinal.{u_1}
⊢ (ord ∘ aleph') a ∈ {b | ord (card b) = b}
[PROOFSTEP]
dsimp
[GOAL]
a : Ordinal.{u_1}
⊢ ord (card (ord (aleph' a))) = ord (aleph' a)
[PROOFSTEP]
rw [card_ord]
[GOAL]
o : Ordinal.{u_1}
ho : ord (card o) = o
ho' : ω ≤ o
⊢ ∃ a, ord (aleph a) = o
[PROOFSTEP]
cases' eq_aleph'_of_eq_card_ord ho with a ha
[GOAL]
case intro
o : Ordinal.{u_1}
ho : ord (card o) = o
ho' : ω ≤ o
a : Ordinal.{u_1}
ha : ord (aleph' a) = o
⊢ ∃ a, ord (aleph a) = o
[PROOFSTEP]
use a - ω
[GOAL]
case h
o : Ordinal.{u_1}
ho : ord (card o) = o
ho' : ω ≤ o
a : Ordinal.{u_1}
ha : ord (aleph' a) = o
⊢ ord (aleph (a - ω)) = o
[PROOFSTEP]
unfold aleph
[GOAL]
case h
o : Ordinal.{u_1}
ho : ord (card o) = o
ho' : ω ≤ o
a : Ordinal.{u_1}
ha : ord (aleph' a) = o
⊢ ord (aleph' (ω + (a - ω))) = o
[PROOFSTEP]
rwa [Ordinal.add_sub_cancel_of_le]
[GOAL]
case h
o : Ordinal.{u_1}
ho : ord (card o) = o
ho' : ω ≤ o
a : Ordinal.{u_1}
ha : ord (aleph' a) = o
⊢ ω ≤ a
[PROOFSTEP]
rwa [← aleph0_le_aleph', ← ord_le_ord, ha, ord_aleph0]
[GOAL]
⊢ ord ∘ aleph = enumOrd {b | ord (card b) = b ∧ ω ≤ b}
[PROOFSTEP]
rw [← eq_enumOrd _ ord_card_unbounded']
[GOAL]
⊢ StrictMono (ord ∘ aleph) ∧ range (ord ∘ aleph) = {b | ord (card b) = b ∧ ω ≤ b}
[PROOFSTEP]
use aleph_isNormal.strictMono
[GOAL]
case right
⊢ range (ord ∘ aleph) = {b | ord (card b) = b ∧ ω ≤ b}
[PROOFSTEP]
rw [range_eq_iff]
[GOAL]
case right
⊢ (∀ (a : Ordinal.{u_1}), (ord ∘ aleph) a ∈ {b | ord (card b) = b ∧ ω ≤ b}) ∧
∀ (b : Ordinal.{u_1}), b ∈ {b | ord (card b) = b ∧ ω ≤ b} → ∃ a, (ord ∘ aleph) a = b
[PROOFSTEP]
refine' ⟨fun a => ⟨_, _⟩, fun b hb => eq_aleph_of_eq_card_ord hb.1 hb.2⟩
[GOAL]
case right.refine'_1
a : Ordinal.{u_1}
⊢ ord (card ((ord ∘ aleph) a)) = (ord ∘ aleph) a
[PROOFSTEP]
rw [Function.comp_apply, card_ord]
[GOAL]
case right.refine'_2
a : Ordinal.{u_1}
⊢ ω ≤ (ord ∘ aleph) a
[PROOFSTEP]
rw [← ord_aleph0, Function.comp_apply, ord_le_ord]
[GOAL]
case right.refine'_2
a : Ordinal.{u_1}
⊢ ℵ₀ ≤ aleph a
[PROOFSTEP]
exact aleph0_le_aleph _
[GOAL]
⊢ StrictMono beth
[PROOFSTEP]
intro a b
[GOAL]
a b : Ordinal.{u_1}
⊢ a < b → beth a < beth b
[PROOFSTEP]
induction' b using Ordinal.induction with b IH generalizing a
[GOAL]
case h
a✝ b : Ordinal.{u_1}
IH : ∀ (k : Ordinal.{u_1}), k < b → ∀ ⦃a : Ordinal.{u_1}⦄, a < k → beth a < beth k
a : Ordinal.{u_1}
⊢ a < b → beth a < beth b
[PROOFSTEP]
intro h
[GOAL]
case h
a✝ b : Ordinal.{u_1}
IH : ∀ (k : Ordinal.{u_1}), k < b → ∀ ⦃a : Ordinal.{u_1}⦄, a < k → beth a < beth k
a : Ordinal.{u_1}
h : a < b
⊢ beth a < beth b
[PROOFSTEP]
rcases zero_or_succ_or_limit b with (rfl | ⟨c, rfl⟩ | hb)
[GOAL]
case h.inl
a✝ a : Ordinal.{u_1}
IH : ∀ (k : Ordinal.{u_1}), k < 0 → ∀ ⦃a : Ordinal.{u_1}⦄, a < k → beth a < beth k
h : a < 0
⊢ beth a < beth 0
[PROOFSTEP]
exact (Ordinal.not_lt_zero a h).elim
[GOAL]
case h.inr.inl.intro
a✝ a c : Ordinal.{u_1}
IH : ∀ (k : Ordinal.{u_1}), k < succ c → ∀ ⦃a : Ordinal.{u_1}⦄, a < k → beth a < beth k
h : a < succ c
⊢ beth a < beth (succ c)
[PROOFSTEP]
rw [lt_succ_iff] at h
[GOAL]
case h.inr.inl.intro
a✝ a c : Ordinal.{u_1}
IH : ∀ (k : Ordinal.{u_1}), k < succ c → ∀ ⦃a : Ordinal.{u_1}⦄, a < k → beth a < beth k
h : a ≤ c
⊢ beth a < beth (succ c)
[PROOFSTEP]
rw [beth_succ]
[GOAL]
case h.inr.inl.intro
a✝ a c : Ordinal.{u_1}
IH : ∀ (k : Ordinal.{u_1}), k < succ c → ∀ ⦃a : Ordinal.{u_1}⦄, a < k → beth a < beth k
h : a ≤ c
⊢ beth a < 2 ^ beth c
[PROOFSTEP]
apply lt_of_le_of_lt _ (cantor _)
[GOAL]
a✝ a c : Ordinal.{u_1}
IH : ∀ (k : Ordinal.{u_1}), k < succ c → ∀ ⦃a : Ordinal.{u_1}⦄, a < k → beth a < beth k
h : a ≤ c
⊢ beth a ≤ beth c
[PROOFSTEP]
rcases eq_or_lt_of_le h with (rfl | h)
[GOAL]
case inl
a✝ a : Ordinal.{u_1}
IH : ∀ (k : Ordinal.{u_1}), k < succ a → ∀ ⦃a : Ordinal.{u_1}⦄, a < k → beth a < beth k
h : a ≤ a
⊢ beth a ≤ beth a
[PROOFSTEP]
rfl
[GOAL]
case inr
a✝ a c : Ordinal.{u_1}
IH : ∀ (k : Ordinal.{u_1}), k < succ c → ∀ ⦃a : Ordinal.{u_1}⦄, a < k → beth a < beth k
h✝ : a ≤ c
h : a < c
⊢ beth a ≤ beth c
[PROOFSTEP]
exact (IH c (lt_succ c) h).le
[GOAL]
case h.inr.inr
a✝ b : Ordinal.{u_1}
IH : ∀ (k : Ordinal.{u_1}), k < b → ∀ ⦃a : Ordinal.{u_1}⦄, a < k → beth a < beth k
a : Ordinal.{u_1}
h : a < b
hb : Ordinal.IsLimit b
⊢ beth a < beth b
[PROOFSTEP]
apply (cantor _).trans_le
[GOAL]
case h.inr.inr
a✝ b : Ordinal.{u_1}
IH : ∀ (k : Ordinal.{u_1}), k < b → ∀ ⦃a : Ordinal.{u_1}⦄, a < k → beth a < beth k
a : Ordinal.{u_1}
h : a < b
hb : Ordinal.IsLimit b
⊢ 2 ^ beth a ≤ beth b
[PROOFSTEP]
rw [beth_limit hb, ← beth_succ]
[GOAL]
case h.inr.inr
a✝ b : Ordinal.{u_1}
IH : ∀ (k : Ordinal.{u_1}), k < b → ∀ ⦃a : Ordinal.{u_1}⦄, a < k → beth a < beth k
a : Ordinal.{u_1}
h : a < b
hb : Ordinal.IsLimit b
⊢ beth (succ a) ≤ ⨆ (a : ↑(Iio b)), beth ↑a
[PROOFSTEP]
exact le_ciSup (bddAbove_of_small _) (⟨_, hb.succ_lt h⟩ : Iio b)
[GOAL]
o : Ordinal.{u_1}
⊢ aleph o ≤ beth o
[PROOFSTEP]
induction o using limitRecOn with
| H₁ => simp
| H₂ o h =>
rw [aleph_succ, beth_succ, succ_le_iff]
exact (cantor _).trans_le (power_le_power_left two_ne_zero h)
| H₃ o ho IH =>
rw [aleph_limit ho, beth_limit ho]
exact ciSup_mono (bddAbove_of_small _) fun x => IH x.1 x.2
[GOAL]
o : Ordinal.{u_1}
⊢ aleph o ≤ beth o
[PROOFSTEP]
induction o using limitRecOn with
| H₁ => simp
| H₂ o h =>
rw [aleph_succ, beth_succ, succ_le_iff]
exact (cantor _).trans_le (power_le_power_left two_ne_zero h)
| H₃ o ho IH =>
rw [aleph_limit ho, beth_limit ho]
exact ciSup_mono (bddAbove_of_small _) fun x => IH x.1 x.2
[GOAL]
case H₁
⊢ aleph 0 ≤ beth 0
[PROOFSTEP]
| H₁ => simp
[GOAL]
case H₁
⊢ aleph 0 ≤ beth 0
[PROOFSTEP]
simp
[GOAL]
case H₂
o : Ordinal.{u_1}
h : aleph o ≤ beth o
⊢ aleph (succ o) ≤ beth (succ o)
[PROOFSTEP]
| H₂ o h =>
rw [aleph_succ, beth_succ, succ_le_iff]
exact (cantor _).trans_le (power_le_power_left two_ne_zero h)
[GOAL]
case H₂
o : Ordinal.{u_1}
h : aleph o ≤ beth o
⊢ aleph (succ o) ≤ beth (succ o)
[PROOFSTEP]
rw [aleph_succ, beth_succ, succ_le_iff]
[GOAL]
case H₂
o : Ordinal.{u_1}
h : aleph o ≤ beth o
⊢ aleph o < 2 ^ beth o
[PROOFSTEP]
exact (cantor _).trans_le (power_le_power_left two_ne_zero h)
[GOAL]
case H₃
o : Ordinal.{u_1}
ho : Ordinal.IsLimit o
IH : ∀ (o' : Ordinal.{u_1}), o' < o → aleph o' ≤ beth o'
⊢ aleph o ≤ beth o
[PROOFSTEP]
| H₃ o ho IH =>
rw [aleph_limit ho, beth_limit ho]
exact ciSup_mono (bddAbove_of_small _) fun x => IH x.1 x.2
[GOAL]
case H₃
o : Ordinal.{u_1}
ho : Ordinal.IsLimit o
IH : ∀ (o' : Ordinal.{u_1}), o' < o → aleph o' ≤ beth o'
⊢ aleph o ≤ beth o
[PROOFSTEP]
rw [aleph_limit ho, beth_limit ho]
[GOAL]
case H₃
o : Ordinal.{u_1}
ho : Ordinal.IsLimit o
IH : ∀ (o' : Ordinal.{u_1}), o' < o → aleph o' ≤ beth o'
⊢ ⨆ (a : ↑(Iio o)), aleph ↑a ≤ ⨆ (a : ↑(Iio o)), beth ↑a
[PROOFSTEP]
exact ciSup_mono (bddAbove_of_small _) fun x => IH x.1 x.2
[GOAL]
o : Ordinal.{u}
ho : Ordinal.IsLimit o
a : Ordinal.{u}
ha : ∀ (b : Ordinal.{u}), b < o → ord (beth b) ≤ a
⊢ ord (beth o) ≤ a
[PROOFSTEP]
rw [beth_limit ho, ord_le]
[GOAL]
o : Ordinal.{u}
ho : Ordinal.IsLimit o
a : Ordinal.{u}
ha : ∀ (b : Ordinal.{u}), b < o → ord (beth b) ≤ a
⊢ ⨆ (a : ↑(Iio o)), beth ↑a ≤ card a
[PROOFSTEP]
exact ciSup_le' fun b => ord_le.1 (ha _ b.2)
[GOAL]
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ c * c = c
[PROOFSTEP]
refine'
le_antisymm _
(by simpa only [mul_one] using mul_le_mul_left' (one_le_aleph0.trans h) c)
-- the only nontrivial part is `c * c ≤ c`. We prove it inductively.
[GOAL]
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ c ≤ c * c
[PROOFSTEP]
simpa only [mul_one] using mul_le_mul_left' (one_le_aleph0.trans h) c
[GOAL]
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ c * c ≤ c
[PROOFSTEP]
refine' Acc.recOn (Cardinal.lt_wf.apply c) (fun c _ => Quotient.inductionOn c fun α IH ol => _) h
[GOAL]
c✝ : Cardinal.{u_1}
h : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
⊢ Quotient.mk isEquivalent α * Quotient.mk isEquivalent α ≤ Quotient.mk isEquivalent α
[PROOFSTEP]
rcases ord_eq α with ⟨r, wo, e⟩
[GOAL]
case intro.intro
c✝ : Cardinal.{u_1}
h : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
⊢ Quotient.mk isEquivalent α * Quotient.mk isEquivalent α ≤ Quotient.mk isEquivalent α
[PROOFSTEP]
skip
[GOAL]
case intro.intro
c✝ : Cardinal.{u_1}
h : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
⊢ Quotient.mk isEquivalent α * Quotient.mk isEquivalent α ≤ Quotient.mk isEquivalent α
[PROOFSTEP]
letI := linearOrderOfSTO r
[GOAL]
case intro.intro
c✝ : Cardinal.{u_1}
h : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this : LinearOrder α := linearOrderOfSTO r
⊢ Quotient.mk isEquivalent α * Quotient.mk isEquivalent α ≤ Quotient.mk isEquivalent α
[PROOFSTEP]
haveI : IsWellOrder α (· < ·) := wo
[GOAL]
case intro.intro
c✝ : Cardinal.{u_1}
h : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝ : LinearOrder α := linearOrderOfSTO r
this : IsWellOrder α fun x x_1 => x < x_1
⊢ Quotient.mk isEquivalent α * Quotient.mk isEquivalent α ≤ Quotient.mk isEquivalent α
[PROOFSTEP]
let g : α × α → α := fun p => max p.1 p.2
[GOAL]
case intro.intro
c✝ : Cardinal.{u_1}
h : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝ : LinearOrder α := linearOrderOfSTO r
this : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
⊢ Quotient.mk isEquivalent α * Quotient.mk isEquivalent α ≤ Quotient.mk isEquivalent α
[PROOFSTEP]
let f : α × α ↪ Ordinal × α × α := ⟨fun p : α × α => (typein (· < ·) (g p), p), fun p q => congr_arg Prod.snd⟩
[GOAL]
case intro.intro
c✝ : Cardinal.{u_1}
h : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝ : LinearOrder α := linearOrderOfSTO r
this : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
⊢ Quotient.mk isEquivalent α * Quotient.mk isEquivalent α ≤ Quotient.mk isEquivalent α
[PROOFSTEP]
let s :=
f ⁻¹'o
Prod.Lex (· < ·)
(Prod.Lex (· < ·) (· < ·))
-- this is a well order on `α × α`.
[GOAL]
case intro.intro
c✝ : Cardinal.{u_1}
h : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝ : LinearOrder α := linearOrderOfSTO r
this : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
⊢ Quotient.mk isEquivalent α * Quotient.mk isEquivalent α ≤ Quotient.mk isEquivalent α
[PROOFSTEP]
haveI : IsWellOrder _ s := (RelEmbedding.preimage _ _).isWellOrder
[GOAL]
case intro.intro
c✝ : Cardinal.{u_1}
h : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝¹ : LinearOrder α := linearOrderOfSTO r
this✝ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this : IsWellOrder (α × α) s
⊢ Quotient.mk isEquivalent α * Quotient.mk isEquivalent α ≤ Quotient.mk isEquivalent α
[PROOFSTEP]
suffices type s ≤ type r by exact card_le_card this
[GOAL]
c✝ : Cardinal.{u_1}
h : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝² : LinearOrder α := linearOrderOfSTO r
this✝¹ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this✝ : IsWellOrder (α × α) s
this : type s ≤ type r
⊢ Quotient.mk isEquivalent α * Quotient.mk isEquivalent α ≤ Quotient.mk isEquivalent α
[PROOFSTEP]
exact card_le_card this
[GOAL]
case intro.intro
c✝ : Cardinal.{u_1}
h : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝¹ : LinearOrder α := linearOrderOfSTO r
this✝ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this : IsWellOrder (α × α) s
⊢ type s ≤ type r
[PROOFSTEP]
refine' le_of_forall_lt fun o h => _
[GOAL]
case intro.intro
c✝ : Cardinal.{u_1}
h✝ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝¹ : LinearOrder α := linearOrderOfSTO r
this✝ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this : IsWellOrder (α × α) s
o : Ordinal.{u_1}
h : o < type s
⊢ o < type r
[PROOFSTEP]
rcases typein_surj s h with ⟨p, rfl⟩
[GOAL]
case intro.intro.intro
c✝ : Cardinal.{u_1}
h✝ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝¹ : LinearOrder α := linearOrderOfSTO r
this✝ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this : IsWellOrder (α × α) s
p : α × α
h : typein s p < type s
⊢ typein s p < type r
[PROOFSTEP]
rw [← e, lt_ord]
[GOAL]
case intro.intro.intro
c✝ : Cardinal.{u_1}
h✝ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝¹ : LinearOrder α := linearOrderOfSTO r
this✝ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this : IsWellOrder (α × α) s
p : α × α
h : typein s p < type s
⊢ card (typein s p) < #α
[PROOFSTEP]
refine' lt_of_le_of_lt (_ : _ ≤ card (succ (typein (· < ·) (g p))) * card (succ (typein (· < ·) (g p)))) _
[GOAL]
case intro.intro.intro.refine'_1
c✝ : Cardinal.{u_1}
h✝ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝¹ : LinearOrder α := linearOrderOfSTO r
this✝ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this : IsWellOrder (α × α) s
p : α × α
h : typein s p < type s
⊢ card (typein s p) ≤
card (succ (typein (fun x x_1 => x < x_1) (g p))) * card (succ (typein (fun x x_1 => x < x_1) (g p)))
[PROOFSTEP]
have : {q | s q p} ⊆ insert (g p) {x | x < g p} ×ˢ insert (g p) {x | x < g p} :=
by
intro q h
simp only [Preimage, ge_iff_le, Embedding.coeFn_mk, Prod.lex_def, typein_lt_typein, typein_inj, mem_setOf_eq] at h
exact max_le_iff.1 (le_iff_lt_or_eq.2 <| h.imp_right And.left)
[GOAL]
c✝ : Cardinal.{u_1}
h✝ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝¹ : LinearOrder α := linearOrderOfSTO r
this✝ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this : IsWellOrder (α × α) s
p : α × α
h : typein s p < type s
⊢ {q | s q p} ⊆ insert (g p) {x | x < g p} ×ˢ insert (g p) {x | x < g p}
[PROOFSTEP]
intro q h
[GOAL]
c✝ : Cardinal.{u_1}
h✝¹ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝¹ : LinearOrder α := linearOrderOfSTO r
this✝ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this : IsWellOrder (α × α) s
p : α × α
h✝ : typein s p < type s
q : α × α
h : q ∈ {q | s q p}
⊢ q ∈ insert (g p) {x | x < g p} ×ˢ insert (g p) {x | x < g p}
[PROOFSTEP]
simp only [Preimage, ge_iff_le, Embedding.coeFn_mk, Prod.lex_def, typein_lt_typein, typein_inj, mem_setOf_eq] at h
[GOAL]
c✝ : Cardinal.{u_1}
h✝¹ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝¹ : LinearOrder α := linearOrderOfSTO r
this✝ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this : IsWellOrder (α × α) s
p : α × α
h✝ : typein s p < type s
q : α × α
h :
max q.fst q.snd < max p.fst p.snd ∨
max q.fst q.snd = max p.fst p.snd ∧ (q.fst < p.fst ∨ q.fst = p.fst ∧ q.snd < p.snd)
⊢ q ∈ insert (g p) {x | x < g p} ×ˢ insert (g p) {x | x < g p}
[PROOFSTEP]
exact max_le_iff.1 (le_iff_lt_or_eq.2 <| h.imp_right And.left)
[GOAL]
case intro.intro.intro.refine'_1
c✝ : Cardinal.{u_1}
h✝ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝² : LinearOrder α := linearOrderOfSTO r
this✝¹ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this✝ : IsWellOrder (α × α) s
p : α × α
h : typein s p < type s
this : {q | s q p} ⊆ insert (g p) {x | x < g p} ×ˢ insert (g p) {x | x < g p}
⊢ card (typein s p) ≤
card (succ (typein (fun x x_1 => x < x_1) (g p))) * card (succ (typein (fun x x_1 => x < x_1) (g p)))
[PROOFSTEP]
suffices H : (insert (g p) {x | r x (g p)} : Set α) ≃ Sum {x | r x (g p)} PUnit
[GOAL]
case intro.intro.intro.refine'_1
c✝ : Cardinal.{u_1}
h✝ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝² : LinearOrder α := linearOrderOfSTO r
this✝¹ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this✝ : IsWellOrder (α × α) s
p : α × α
h : typein s p < type s
this : {q | s q p} ⊆ insert (g p) {x | x < g p} ×ˢ insert (g p) {x | x < g p}
H : ↑(insert (g p) {x | r x (g p)}) ≃ ↑{x | r x (g p)} ⊕ PUnit
⊢ card (typein s p) ≤
card (succ (typein (fun x x_1 => x < x_1) (g p))) * card (succ (typein (fun x x_1 => x < x_1) (g p)))
[PROOFSTEP]
exact ⟨(Set.embeddingOfSubset _ _ this).trans ((Equiv.Set.prod _ _).trans (H.prodCongr H)).toEmbedding⟩
[GOAL]
case H
c✝ : Cardinal.{u_1}
h✝ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝² : LinearOrder α := linearOrderOfSTO r
this✝¹ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this✝ : IsWellOrder (α × α) s
p : α × α
h : typein s p < type s
this : {q | s q p} ⊆ insert (g p) {x | x < g p} ×ˢ insert (g p) {x | x < g p}
⊢ ↑(insert (g p) {x | r x (g p)}) ≃ ↑{x | r x (g p)} ⊕ PUnit
[PROOFSTEP]
refine' (Equiv.Set.insert _).trans ((Equiv.refl _).sumCongr punitEquivPUnit)
[GOAL]
case H
c✝ : Cardinal.{u_1}
h✝ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝² : LinearOrder α := linearOrderOfSTO r
this✝¹ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this✝ : IsWellOrder (α × α) s
p : α × α
h : typein s p < type s
this : {q | s q p} ⊆ insert (g p) {x | x < g p} ×ˢ insert (g p) {x | x < g p}
⊢ ¬g p ∈ {x | r x (g p)}
[PROOFSTEP]
apply @irrefl _ r
[GOAL]
case intro.intro.intro.refine'_2
c✝ : Cardinal.{u_1}
h✝ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝¹ : LinearOrder α := linearOrderOfSTO r
this✝ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this : IsWellOrder (α × α) s
p : α × α
h : typein s p < type s
⊢ card (succ (typein (fun x x_1 => x < x_1) (g p))) * card (succ (typein (fun x x_1 => x < x_1) (g p))) < #α
[PROOFSTEP]
cases' lt_or_le (card (succ (typein (· < ·) (g p)))) ℵ₀ with qo qo
[GOAL]
case intro.intro.intro.refine'_2.inl
c✝ : Cardinal.{u_1}
h✝ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝¹ : LinearOrder α := linearOrderOfSTO r
this✝ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this : IsWellOrder (α × α) s
p : α × α
h : typein s p < type s
qo : card (succ (typein (fun x x_1 => x < x_1) (g p))) < ℵ₀
⊢ card (succ (typein (fun x x_1 => x < x_1) (g p))) * card (succ (typein (fun x x_1 => x < x_1) (g p))) < #α
[PROOFSTEP]
exact (mul_lt_aleph0 qo qo).trans_le ol
[GOAL]
case intro.intro.intro.refine'_2.inr
c✝ : Cardinal.{u_1}
h✝ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝¹ : LinearOrder α := linearOrderOfSTO r
this✝ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this : IsWellOrder (α × α) s
p : α × α
h : typein s p < type s
qo : ℵ₀ ≤ card (succ (typein (fun x x_1 => x < x_1) (g p)))
⊢ card (succ (typein (fun x x_1 => x < x_1) (g p))) * card (succ (typein (fun x x_1 => x < x_1) (g p))) < #α
[PROOFSTEP]
suffices : (succ (typein LT.lt (g p))).card < ⟦α⟧
[GOAL]
case intro.intro.intro.refine'_2.inr
c✝ : Cardinal.{u_1}
h✝ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝² : LinearOrder α := linearOrderOfSTO r
this✝¹ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this✝ : IsWellOrder (α × α) s
p : α × α
h : typein s p < type s
qo : ℵ₀ ≤ card (succ (typein (fun x x_1 => x < x_1) (g p)))
this : card (succ (typein LT.lt (g p))) < Quotient.mk isEquivalent α
⊢ card (succ (typein (fun x x_1 => x < x_1) (g p))) * card (succ (typein (fun x x_1 => x < x_1) (g p))) < #α
[PROOFSTEP]
exact (IH _ this qo).trans_lt this
[GOAL]
case this
c✝ : Cardinal.{u_1}
h✝ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝¹ : LinearOrder α := linearOrderOfSTO r
this✝ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this : IsWellOrder (α × α) s
p : α × α
h : typein s p < type s
qo : ℵ₀ ≤ card (succ (typein (fun x x_1 => x < x_1) (g p)))
⊢ card (succ (typein LT.lt (g p))) < Quotient.mk isEquivalent α
[PROOFSTEP]
rw [← lt_ord]
[GOAL]
case this
c✝ : Cardinal.{u_1}
h✝ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝¹ : LinearOrder α := linearOrderOfSTO r
this✝ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this : IsWellOrder (α × α) s
p : α × α
h : typein s p < type s
qo : ℵ₀ ≤ card (succ (typein (fun x x_1 => x < x_1) (g p)))
⊢ succ (typein LT.lt (g p)) < ord (Quotient.mk isEquivalent α)
[PROOFSTEP]
apply (ord_isLimit ol).2
[GOAL]
case this.a
c✝ : Cardinal.{u_1}
h✝ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝¹ : LinearOrder α := linearOrderOfSTO r
this✝ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this : IsWellOrder (α × α) s
p : α × α
h : typein s p < type s
qo : ℵ₀ ≤ card (succ (typein (fun x x_1 => x < x_1) (g p)))
⊢ typein LT.lt (g p) < ord (Quotient.mk isEquivalent α)
[PROOFSTEP]
rw [mk'_def, e]
[GOAL]
case this.a
c✝ : Cardinal.{u_1}
h✝ : ℵ₀ ≤ c✝
c : Cardinal.{u_1}
x✝ : ∀ (y : Cardinal.{u_1}), y < c → Acc (fun x x_1 => x < x_1) y
α : Type u_1
IH : ∀ (y : Cardinal.{u_1}), y < Quotient.mk isEquivalent α → ℵ₀ ≤ y → y * y ≤ y
ol : ℵ₀ ≤ Quotient.mk isEquivalent α
r : α → α → Prop
wo : IsWellOrder α r
e : ord #α = type r
this✝¹ : LinearOrder α := linearOrderOfSTO r
this✝ : IsWellOrder α fun x x_1 => x < x_1
g : α × α → α := fun p => max p.fst p.snd
f : α × α ↪ Ordinal.{u_1} × α × α :=
{ toFun := fun p => (typein (fun x x_1 => x < x_1) (g p), p),
inj' :=
(_ :
∀ (p q : α × α),
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p =
(fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q →
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) p).snd =
((fun p => (typein (fun x x_1 => x < x_1) (g p), p)) q).snd) }
s : α × α → α × α → Prop :=
↑f ⁻¹'o Prod.Lex (fun x x_1 => x < x_1) (Prod.Lex (fun x x_1 => x < x_1) fun x x_1 => x < x_1)
this : IsWellOrder (α × α) s
p : α × α
h : typein s p < type s
qo : ℵ₀ ≤ card (succ (typein (fun x x_1 => x < x_1) (g p)))
⊢ typein LT.lt (g p) < type r
[PROOFSTEP]
apply typein_lt_type
[GOAL]
a b : Cardinal.{u_1}
ha : ℵ₀ ≤ a
hb : ℵ₀ ≤ b
⊢ a ≤ a * b
[PROOFSTEP]
simpa only [mul_one] using mul_le_mul_left' (one_le_aleph0.trans hb) a
[GOAL]
a b : Cardinal.{u_1}
ha : ℵ₀ ≤ a
hb : ℵ₀ ≤ b
⊢ b ≤ a * b
[PROOFSTEP]
simpa only [one_mul] using mul_le_mul_right' (one_le_aleph0.trans ha) b
[GOAL]
o₁ o₂ : Ordinal.{u_1}
⊢ aleph o₁ * aleph o₂ = aleph (max o₁ o₂)
[PROOFSTEP]
rw [Cardinal.mul_eq_max (aleph0_le_aleph o₁) (aleph0_le_aleph o₂), max_aleph_eq]
[GOAL]
a b c : Cardinal.{u_1}
hc : ℵ₀ ≤ c
h1 : a < c
h2 : b < c
h : ℵ₀ ≤ max a b
⊢ max a b * max a b < c
[PROOFSTEP]
rw [mul_eq_self h]
[GOAL]
a b c : Cardinal.{u_1}
hc : ℵ₀ ≤ c
h1 : a < c
h2 : b < c
h : ℵ₀ ≤ max a b
⊢ max a b < c
[PROOFSTEP]
exact max_lt h1 h2
[GOAL]
a b : Cardinal.{u_1}
h : ℵ₀ ≤ a
⊢ a * b ≤ max a b
[PROOFSTEP]
convert mul_le_mul' (le_max_left a b) (le_max_right a b) using 1
[GOAL]
case h.e'_4
a b : Cardinal.{u_1}
h : ℵ₀ ≤ a
⊢ max a b = max a b * max a b
[PROOFSTEP]
rw [mul_eq_self]
[GOAL]
case h.e'_4
a b : Cardinal.{u_1}
h : ℵ₀ ≤ a
⊢ ℵ₀ ≤ max a b
[PROOFSTEP]
refine' h.trans (le_max_left a b)
[GOAL]
a b : Cardinal.{u_1}
h : ℵ₀ ≤ a
h' : b ≠ 0
⊢ a * b = max a b
[PROOFSTEP]
cases' le_or_lt ℵ₀ b with hb hb
[GOAL]
case inl
a b : Cardinal.{u_1}
h : ℵ₀ ≤ a
h' : b ≠ 0
hb : ℵ₀ ≤ b
⊢ a * b = max a b
[PROOFSTEP]
exact mul_eq_max h hb
[GOAL]
case inr
a b : Cardinal.{u_1}
h : ℵ₀ ≤ a
h' : b ≠ 0
hb : b < ℵ₀
⊢ a * b = max a b
[PROOFSTEP]
refine' (mul_le_max_of_aleph0_le_left h).antisymm _
[GOAL]
case inr
a b : Cardinal.{u_1}
h : ℵ₀ ≤ a
h' : b ≠ 0
hb : b < ℵ₀
⊢ max a b ≤ a * b
[PROOFSTEP]
have : b ≤ a := hb.le.trans h
[GOAL]
case inr
a b : Cardinal.{u_1}
h : ℵ₀ ≤ a
h' : b ≠ 0
hb : b < ℵ₀
this : b ≤ a
⊢ max a b ≤ a * b
[PROOFSTEP]
rw [max_eq_left this]
[GOAL]
case inr
a b : Cardinal.{u_1}
h : ℵ₀ ≤ a
h' : b ≠ 0
hb : b < ℵ₀
this : b ≤ a
⊢ a ≤ a * b
[PROOFSTEP]
convert mul_le_mul_left' (one_le_iff_ne_zero.mpr h') a
[GOAL]
case h.e'_3
a b : Cardinal.{u_1}
h : ℵ₀ ≤ a
h' : b ≠ 0
hb : b < ℵ₀
this : b ≤ a
⊢ a = a * 1
[PROOFSTEP]
rw [mul_one]
[GOAL]
a b : Cardinal.{u_1}
h : ℵ₀ ≤ b
⊢ a * b ≤ max a b
[PROOFSTEP]
simpa only [mul_comm b, max_comm b] using mul_le_max_of_aleph0_le_left h
[GOAL]
a b : Cardinal.{u_1}
h' : a ≠ 0
h : ℵ₀ ≤ b
⊢ a * b = max a b
[PROOFSTEP]
rw [mul_comm, max_comm]
[GOAL]
a b : Cardinal.{u_1}
h' : a ≠ 0
h : ℵ₀ ≤ b
⊢ b * a = max b a
[PROOFSTEP]
exact mul_eq_max_of_aleph0_le_left h h'
[GOAL]
a b : Cardinal.{u_1}
h : ℵ₀ ≤ a * b
⊢ a * b = max a b
[PROOFSTEP]
rcases aleph0_le_mul_iff.mp h with ⟨ha, hb, ha' | hb'⟩
[GOAL]
case intro.intro.inl
a b : Cardinal.{u_1}
h : ℵ₀ ≤ a * b
ha : a ≠ 0
hb : b ≠ 0
ha' : ℵ₀ ≤ a
⊢ a * b = max a b
[PROOFSTEP]
exact mul_eq_max_of_aleph0_le_left ha' hb
[GOAL]
case intro.intro.inr
a b : Cardinal.{u_1}
h : ℵ₀ ≤ a * b
ha : a ≠ 0
hb : b ≠ 0
hb' : ℵ₀ ≤ b
⊢ a * b = max a b
[PROOFSTEP]
exact mul_eq_max_of_aleph0_le_right ha hb'
[GOAL]
a b : Cardinal.{u_1}
⊢ a * b ≤ max (max a b) ℵ₀
[PROOFSTEP]
rcases eq_or_ne a 0 with (rfl | ha0)
[GOAL]
case inl
b : Cardinal.{u_1}
⊢ 0 * b ≤ max (max 0 b) ℵ₀
[PROOFSTEP]
simp
[GOAL]
case inr
a b : Cardinal.{u_1}
ha0 : a ≠ 0
⊢ a * b ≤ max (max a b) ℵ₀
[PROOFSTEP]
rcases eq_or_ne b 0 with (rfl | hb0)
[GOAL]
case inr.inl
a : Cardinal.{u_1}
ha0 : a ≠ 0
⊢ a * 0 ≤ max (max a 0) ℵ₀
[PROOFSTEP]
simp
[GOAL]
case inr.inr
a b : Cardinal.{u_1}
ha0 : a ≠ 0
hb0 : b ≠ 0
⊢ a * b ≤ max (max a b) ℵ₀
[PROOFSTEP]
cases' le_or_lt ℵ₀ a with ha ha
[GOAL]
case inr.inr.inl
a b : Cardinal.{u_1}
ha0 : a ≠ 0
hb0 : b ≠ 0
ha : ℵ₀ ≤ a
⊢ a * b ≤ max (max a b) ℵ₀
[PROOFSTEP]
rw [mul_eq_max_of_aleph0_le_left ha hb0]
[GOAL]
case inr.inr.inl
a b : Cardinal.{u_1}
ha0 : a ≠ 0
hb0 : b ≠ 0
ha : ℵ₀ ≤ a
⊢ max a b ≤ max (max a b) ℵ₀
[PROOFSTEP]
exact le_max_left _ _
[GOAL]
case inr.inr.inr
a b : Cardinal.{u_1}
ha0 : a ≠ 0
hb0 : b ≠ 0
ha : a < ℵ₀
⊢ a * b ≤ max (max a b) ℵ₀
[PROOFSTEP]
cases' le_or_lt ℵ₀ b with hb hb
[GOAL]
case inr.inr.inr.inl
a b : Cardinal.{u_1}
ha0 : a ≠ 0
hb0 : b ≠ 0
ha : a < ℵ₀
hb : ℵ₀ ≤ b
⊢ a * b ≤ max (max a b) ℵ₀
[PROOFSTEP]
rw [mul_comm, mul_eq_max_of_aleph0_le_left hb ha0, max_comm]
[GOAL]
case inr.inr.inr.inl
a b : Cardinal.{u_1}
ha0 : a ≠ 0
hb0 : b ≠ 0
ha : a < ℵ₀
hb : ℵ₀ ≤ b
⊢ max a b ≤ max (max a b) ℵ₀
[PROOFSTEP]
exact le_max_left _ _
[GOAL]
case inr.inr.inr.inr
a b : Cardinal.{u_1}
ha0 : a ≠ 0
hb0 : b ≠ 0
ha : a < ℵ₀
hb : b < ℵ₀
⊢ a * b ≤ max (max a b) ℵ₀
[PROOFSTEP]
exact le_max_of_le_right (mul_lt_aleph0 ha hb).le
[GOAL]
a b : Cardinal.{u_1}
ha : ℵ₀ ≤ a
hb : b ≤ a
hb' : b ≠ 0
⊢ a * b = a
[PROOFSTEP]
rw [mul_eq_max_of_aleph0_le_left ha hb', max_eq_left hb]
[GOAL]
a b : Cardinal.{u_1}
hb : ℵ₀ ≤ b
ha : a ≤ b
ha' : a ≠ 0
⊢ a * b = b
[PROOFSTEP]
rw [mul_comm, mul_eq_left hb ha ha']
[GOAL]
a b : Cardinal.{u_1}
h : b ≠ 0
⊢ a ≤ b * a
[PROOFSTEP]
convert mul_le_mul_right' (one_le_iff_ne_zero.mpr h) a
[GOAL]
case h.e'_3
a b : Cardinal.{u_1}
h : b ≠ 0
⊢ a = 1 * a
[PROOFSTEP]
rw [one_mul]
[GOAL]
a b : Cardinal.{u_1}
h : b ≠ 0
⊢ a ≤ a * b
[PROOFSTEP]
rw [mul_comm]
[GOAL]
a b : Cardinal.{u_1}
h : b ≠ 0
⊢ a ≤ b * a
[PROOFSTEP]
exact le_mul_left h
[GOAL]
a b : Cardinal.{u_1}
⊢ a * b = a ↔ max ℵ₀ b ≤ a ∧ b ≠ 0 ∨ b = 1 ∨ a = 0
[PROOFSTEP]
rw [max_le_iff]
[GOAL]
a b : Cardinal.{u_1}
⊢ a * b = a ↔ (ℵ₀ ≤ a ∧ b ≤ a) ∧ b ≠ 0 ∨ b = 1 ∨ a = 0
[PROOFSTEP]
refine' ⟨fun h => _, _⟩
[GOAL]
case refine'_1
a b : Cardinal.{u_1}
h : a * b = a
⊢ (ℵ₀ ≤ a ∧ b ≤ a) ∧ b ≠ 0 ∨ b = 1 ∨ a = 0
[PROOFSTEP]
cases' le_or_lt ℵ₀ a with ha ha
[GOAL]
case refine'_1.inl
a b : Cardinal.{u_1}
h : a * b = a
ha : ℵ₀ ≤ a
⊢ (ℵ₀ ≤ a ∧ b ≤ a) ∧ b ≠ 0 ∨ b = 1 ∨ a = 0
[PROOFSTEP]
have : a ≠ 0 := by
rintro rfl
exact ha.not_lt aleph0_pos
[GOAL]
a b : Cardinal.{u_1}
h : a * b = a
ha : ℵ₀ ≤ a
⊢ a ≠ 0
[PROOFSTEP]
rintro rfl
[GOAL]
b : Cardinal.{u_1}
h : 0 * b = 0
ha : ℵ₀ ≤ 0
⊢ False
[PROOFSTEP]
exact ha.not_lt aleph0_pos
[GOAL]
case refine'_1.inl
a b : Cardinal.{u_1}
h : a * b = a
ha : ℵ₀ ≤ a
this : a ≠ 0
⊢ (ℵ₀ ≤ a ∧ b ≤ a) ∧ b ≠ 0 ∨ b = 1 ∨ a = 0
[PROOFSTEP]
left
[GOAL]
case refine'_1.inl.h
a b : Cardinal.{u_1}
h : a * b = a
ha : ℵ₀ ≤ a
this : a ≠ 0
⊢ (ℵ₀ ≤ a ∧ b ≤ a) ∧ b ≠ 0
[PROOFSTEP]
rw [and_assoc]
[GOAL]
case refine'_1.inl.h
a b : Cardinal.{u_1}
h : a * b = a
ha : ℵ₀ ≤ a
this : a ≠ 0
⊢ ℵ₀ ≤ a ∧ b ≤ a ∧ b ≠ 0
[PROOFSTEP]
use ha
[GOAL]
case right
a b : Cardinal.{u_1}
h : a * b = a
ha : ℵ₀ ≤ a
this : a ≠ 0
⊢ b ≤ a ∧ b ≠ 0
[PROOFSTEP]
constructor
[GOAL]
case right.left
a b : Cardinal.{u_1}
h : a * b = a
ha : ℵ₀ ≤ a
this : a ≠ 0
⊢ b ≤ a
[PROOFSTEP]
rw [← not_lt]
[GOAL]
case right.left
a b : Cardinal.{u_1}
h : a * b = a
ha : ℵ₀ ≤ a
this : a ≠ 0
⊢ ¬a < b
[PROOFSTEP]
exact fun hb => ne_of_gt (hb.trans_le (le_mul_left this)) h
[GOAL]
case right.right
a b : Cardinal.{u_1}
h : a * b = a
ha : ℵ₀ ≤ a
this : a ≠ 0
⊢ b ≠ 0
[PROOFSTEP]
rintro rfl
[GOAL]
case right.right
a : Cardinal.{u_1}
ha : ℵ₀ ≤ a
this : a ≠ 0
h : a * 0 = a
⊢ False
[PROOFSTEP]
apply this
[GOAL]
case right.right
a : Cardinal.{u_1}
ha : ℵ₀ ≤ a
this : a ≠ 0
h : a * 0 = a
⊢ a = 0
[PROOFSTEP]
rw [mul_zero] at h
[GOAL]
case right.right
a : Cardinal.{u_1}
ha : ℵ₀ ≤ a
this : a ≠ 0
h : 0 = a
⊢ a = 0
[PROOFSTEP]
exact h.symm
[GOAL]
case refine'_1.inr
a b : Cardinal.{u_1}
h : a * b = a
ha : a < ℵ₀
⊢ (ℵ₀ ≤ a ∧ b ≤ a) ∧ b ≠ 0 ∨ b = 1 ∨ a = 0
[PROOFSTEP]
right
[GOAL]
case refine'_1.inr.h
a b : Cardinal.{u_1}
h : a * b = a
ha : a < ℵ₀
⊢ b = 1 ∨ a = 0
[PROOFSTEP]
by_cases h2a : a = 0
[GOAL]
case pos
a b : Cardinal.{u_1}
h : a * b = a
ha : a < ℵ₀
h2a : a = 0
⊢ b = 1 ∨ a = 0
[PROOFSTEP]
exact Or.inr h2a
[GOAL]
case neg
a b : Cardinal.{u_1}
h : a * b = a
ha : a < ℵ₀
h2a : ¬a = 0
⊢ b = 1 ∨ a = 0
[PROOFSTEP]
have hb : b ≠ 0 := by
rintro rfl
apply h2a
rw [mul_zero] at h
exact h.symm
[GOAL]
a b : Cardinal.{u_1}
h : a * b = a
ha : a < ℵ₀
h2a : ¬a = 0
⊢ b ≠ 0
[PROOFSTEP]
rintro rfl
[GOAL]
a : Cardinal.{u_1}
ha : a < ℵ₀
h2a : ¬a = 0
h : a * 0 = a
⊢ False
[PROOFSTEP]
apply h2a
[GOAL]
a : Cardinal.{u_1}
ha : a < ℵ₀
h2a : ¬a = 0
h : a * 0 = a
⊢ a = 0
[PROOFSTEP]
rw [mul_zero] at h
[GOAL]
a : Cardinal.{u_1}
ha : a < ℵ₀
h2a : ¬a = 0
h : 0 = a
⊢ a = 0
[PROOFSTEP]
exact h.symm
[GOAL]
case neg
a b : Cardinal.{u_1}
h : a * b = a
ha : a < ℵ₀
h2a : ¬a = 0
hb : b ≠ 0
⊢ b = 1 ∨ a = 0
[PROOFSTEP]
left
[GOAL]
case neg.h
a b : Cardinal.{u_1}
h : a * b = a
ha : a < ℵ₀
h2a : ¬a = 0
hb : b ≠ 0
⊢ b = 1
[PROOFSTEP]
rw [← h, mul_lt_aleph0_iff, lt_aleph0, lt_aleph0] at ha
[GOAL]
case neg.h
a b : Cardinal.{u_1}
h : a * b = a
ha : a = 0 ∨ b = 0 ∨ (∃ n, a = ↑n) ∧ ∃ n, b = ↑n
h2a : ¬a = 0
hb : b ≠ 0
⊢ b = 1
[PROOFSTEP]
rcases ha with (rfl | rfl | ⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩)
[GOAL]
case neg.h.inl
b : Cardinal.{u_1}
hb : b ≠ 0
h : 0 * b = 0
h2a : ¬0 = 0
⊢ b = 1
case neg.h.inr.inl
a : Cardinal.{u_1}
h2a : ¬a = 0
h : a * 0 = a
hb : 0 ≠ 0
⊢ 0 = 1
case neg.h.inr.inr.intro.intro.intro n : ℕ h2a : ¬↑n = 0 m : ℕ hb : ↑m ≠ 0 h : ↑n * ↑m = ↑n ⊢ ↑m = 1
[PROOFSTEP]
contradiction
[GOAL]
case neg.h.inr.inl
a : Cardinal.{u_1}
h2a : ¬a = 0
h : a * 0 = a
hb : 0 ≠ 0
⊢ 0 = 1
case neg.h.inr.inr.intro.intro.intro n : ℕ h2a : ¬↑n = 0 m : ℕ hb : ↑m ≠ 0 h : ↑n * ↑m = ↑n ⊢ ↑m = 1
[PROOFSTEP]
contradiction
[GOAL]
case neg.h.inr.inr.intro.intro.intro
n : ℕ
h2a : ¬↑n = 0
m : ℕ
hb : ↑m ≠ 0
h : ↑n * ↑m = ↑n
⊢ ↑m = 1
[PROOFSTEP]
rw [← Ne] at h2a
[GOAL]
case neg.h.inr.inr.intro.intro.intro
n : ℕ
h2a : ↑n ≠ 0
m : ℕ
hb : ↑m ≠ 0
h : ↑n * ↑m = ↑n
⊢ ↑m = 1
[PROOFSTEP]
rw [← one_le_iff_ne_zero] at h2a hb
[GOAL]
case neg.h.inr.inr.intro.intro.intro
n : ℕ
h2a : 1 ≤ ↑n
m : ℕ
hb : 1 ≤ ↑m
h : ↑n * ↑m = ↑n
⊢ ↑m = 1
[PROOFSTEP]
norm_cast at h2a hb h ⊢
[GOAL]
case neg.h.inr.inr.intro.intro.intro
n m : ℕ
h2a : 1 ≤ n
hb : 1 ≤ m
h : n * m = n
⊢ m = 1
[PROOFSTEP]
apply le_antisymm _ hb
[GOAL]
n m : ℕ
h2a : 1 ≤ n
hb : 1 ≤ m
h : n * m = n
⊢ m ≤ 1
[PROOFSTEP]
rw [← not_lt]
[GOAL]
n m : ℕ
h2a : 1 ≤ n
hb : 1 ≤ m
h : n * m = n
⊢ ¬1 < m
[PROOFSTEP]
apply fun h2b => ne_of_gt _ h
[GOAL]
n m : ℕ
h2a : 1 ≤ n
hb : 1 ≤ m
h : n * m = n
⊢ 1 < m → n < n * m
[PROOFSTEP]
conv_rhs => left; rw [← mul_one n]
[GOAL]
case h₂
n m : ℕ
h2a : 1 ≤ n
hb : 1 ≤ m
h : n * m = n
| n < n * m
[PROOFSTEP]
left; rw [← mul_one n]
[GOAL]
case h₂
n m : ℕ
h2a : 1 ≤ n
hb : 1 ≤ m
h : n * m = n
| n < n * m
[PROOFSTEP]
left; rw [← mul_one n]
[GOAL]
case h₂
n m : ℕ
h2a : 1 ≤ n
hb : 1 ≤ m
h : n * m = n
| n < n * m
[PROOFSTEP]
left
[GOAL]
case h₂
n m : ℕ
h2a : 1 ≤ n
hb : 1 ≤ m
h : n * m = n
| n
[PROOFSTEP]
rw [← mul_one n]
[GOAL]
n m : ℕ
h2a : 1 ≤ n
hb : 1 ≤ m
h : n * m = n
⊢ 1 < m → n * 1 < n * m
[PROOFSTEP]
rw [mul_lt_mul_left]
[GOAL]
n m : ℕ
h2a : 1 ≤ n
hb : 1 ≤ m
h : n * m = n
⊢ 1 < m → 1 < m
n m : ℕ h2a : 1 ≤ n hb : 1 ≤ m h : n * m = n ⊢ 0 < n
[PROOFSTEP]
exact id
[GOAL]
n m : ℕ
h2a : 1 ≤ n
hb : 1 ≤ m
h : n * m = n
⊢ 0 < n
[PROOFSTEP]
apply Nat.lt_of_succ_le h2a
[GOAL]
case refine'_2
a b : Cardinal.{u_1}
⊢ (ℵ₀ ≤ a ∧ b ≤ a) ∧ b ≠ 0 ∨ b = 1 ∨ a = 0 → a * b = a
[PROOFSTEP]
rintro (⟨⟨ha, hab⟩, hb⟩ | rfl | rfl)
[GOAL]
case refine'_2.inl.intro.intro
a b : Cardinal.{u_1}
hb : b ≠ 0
ha : ℵ₀ ≤ a
hab : b ≤ a
⊢ a * b = a
[PROOFSTEP]
rw [mul_eq_max_of_aleph0_le_left ha hb, max_eq_left hab]
[GOAL]
case refine'_2.inr.inl
a : Cardinal.{u_1}
⊢ a * 1 = a
case refine'_2.inr.inr b : Cardinal.{u_1} ⊢ 0 * b = 0
[PROOFSTEP]
all_goals simp
[GOAL]
case refine'_2.inr.inl
a : Cardinal.{u_1}
⊢ a * 1 = a
[PROOFSTEP]
simp
[GOAL]
case refine'_2.inr.inr
b : Cardinal.{u_1}
⊢ 0 * b = 0
[PROOFSTEP]
simp
[GOAL]
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ c + c ≤ c
[PROOFSTEP]
convert mul_le_mul_right' ((nat_lt_aleph0 2).le.trans h) c using 1
[GOAL]
case h.e'_3
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ c + c = ↑2 * c
[PROOFSTEP]
simp [two_mul, mul_eq_self h]
[GOAL]
case h.e'_4
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ c = c * c
[PROOFSTEP]
simp [two_mul, mul_eq_self h]
[GOAL]
a b : Cardinal.{u_1}
ha : ℵ₀ ≤ b
⊢ a + b = max a b
[PROOFSTEP]
rw [add_comm, max_comm, add_eq_max ha]
[GOAL]
a b : Cardinal.{u_1}
⊢ a + b ≤ max (max a b) ℵ₀
[PROOFSTEP]
cases' le_or_lt ℵ₀ a with ha ha
[GOAL]
case inl
a b : Cardinal.{u_1}
ha : ℵ₀ ≤ a
⊢ a + b ≤ max (max a b) ℵ₀
[PROOFSTEP]
rw [add_eq_max ha]
[GOAL]
case inl
a b : Cardinal.{u_1}
ha : ℵ₀ ≤ a
⊢ max a b ≤ max (max a b) ℵ₀
[PROOFSTEP]
exact le_max_left _ _
[GOAL]
case inr
a b : Cardinal.{u_1}
ha : a < ℵ₀
⊢ a + b ≤ max (max a b) ℵ₀
[PROOFSTEP]
cases' le_or_lt ℵ₀ b with hb hb
[GOAL]
case inr.inl
a b : Cardinal.{u_1}
ha : a < ℵ₀
hb : ℵ₀ ≤ b
⊢ a + b ≤ max (max a b) ℵ₀
[PROOFSTEP]
rw [add_comm, add_eq_max hb, max_comm]
[GOAL]
case inr.inl
a b : Cardinal.{u_1}
ha : a < ℵ₀
hb : ℵ₀ ≤ b
⊢ max a b ≤ max (max a b) ℵ₀
[PROOFSTEP]
exact le_max_left _ _
[GOAL]
case inr.inr
a b : Cardinal.{u_1}
ha : a < ℵ₀
hb : b < ℵ₀
⊢ a + b ≤ max (max a b) ℵ₀
[PROOFSTEP]
exact le_max_of_le_right (add_lt_aleph0 ha hb).le
[GOAL]
a b c : Cardinal.{u_1}
hc : ℵ₀ ≤ c
h1 : a < c
h2 : b < c
h : ℵ₀ ≤ max a b
⊢ max a b + max a b < c
[PROOFSTEP]
rw [add_eq_self h]
[GOAL]
a b c : Cardinal.{u_1}
hc : ℵ₀ ≤ c
h1 : a < c
h2 : b < c
h : ℵ₀ ≤ max a b
⊢ max a b < c
[PROOFSTEP]
exact max_lt h1 h2
[GOAL]
a b c : Cardinal.{u_1}
h : a + b = c
ha : a < c
hc : ℵ₀ ≤ c
⊢ b = c
[PROOFSTEP]
apply le_antisymm
[GOAL]
case a
a b c : Cardinal.{u_1}
h : a + b = c
ha : a < c
hc : ℵ₀ ≤ c
⊢ b ≤ c
[PROOFSTEP]
rw [← h]
[GOAL]
case a
a b c : Cardinal.{u_1}
h : a + b = c
ha : a < c
hc : ℵ₀ ≤ c
⊢ b ≤ a + b
[PROOFSTEP]
apply self_le_add_left
[GOAL]
case a
a b c : Cardinal.{u_1}
h : a + b = c
ha : a < c
hc : ℵ₀ ≤ c
⊢ c ≤ b
[PROOFSTEP]
rw [← not_lt]
[GOAL]
case a
a b c : Cardinal.{u_1}
h : a + b = c
ha : a < c
hc : ℵ₀ ≤ c
⊢ ¬b < c
[PROOFSTEP]
intro hb
[GOAL]
case a
a b c : Cardinal.{u_1}
h : a + b = c
ha : a < c
hc : ℵ₀ ≤ c
hb : b < c
⊢ False
[PROOFSTEP]
have : a + b < c := add_lt_of_lt hc ha hb
[GOAL]
case a
a b c : Cardinal.{u_1}
h : a + b = c
ha : a < c
hc : ℵ₀ ≤ c
hb : b < c
this : a + b < c
⊢ False
[PROOFSTEP]
simp [h, lt_irrefl] at this
[GOAL]
a b : Cardinal.{u_1}
ha : ℵ₀ ≤ a
hb : b ≤ a
⊢ a + b = a
[PROOFSTEP]
rw [add_eq_max ha, max_eq_left hb]
[GOAL]
a b : Cardinal.{u_1}
hb : ℵ₀ ≤ b
ha : a ≤ b
⊢ a + b = b
[PROOFSTEP]
rw [add_comm, add_eq_left hb ha]
[GOAL]
a b : Cardinal.{u_1}
⊢ a + b = a ↔ max ℵ₀ b ≤ a ∨ b = 0
[PROOFSTEP]
rw [max_le_iff]
[GOAL]
a b : Cardinal.{u_1}
⊢ a + b = a ↔ ℵ₀ ≤ a ∧ b ≤ a ∨ b = 0
[PROOFSTEP]
refine' ⟨fun h => _, _⟩
[GOAL]
case refine'_1
a b : Cardinal.{u_1}
h : a + b = a
⊢ ℵ₀ ≤ a ∧ b ≤ a ∨ b = 0
[PROOFSTEP]
cases' le_or_lt ℵ₀ a with ha ha
[GOAL]
case refine'_1.inl
a b : Cardinal.{u_1}
h : a + b = a
ha : ℵ₀ ≤ a
⊢ ℵ₀ ≤ a ∧ b ≤ a ∨ b = 0
[PROOFSTEP]
left
[GOAL]
case refine'_1.inl.h
a b : Cardinal.{u_1}
h : a + b = a
ha : ℵ₀ ≤ a
⊢ ℵ₀ ≤ a ∧ b ≤ a
[PROOFSTEP]
use ha
[GOAL]
case right
a b : Cardinal.{u_1}
h : a + b = a
ha : ℵ₀ ≤ a
⊢ b ≤ a
[PROOFSTEP]
rw [← not_lt]
[GOAL]
case right
a b : Cardinal.{u_1}
h : a + b = a
ha : ℵ₀ ≤ a
⊢ ¬a < b
[PROOFSTEP]
apply fun hb => ne_of_gt _ h
[GOAL]
a b : Cardinal.{u_1}
h : a + b = a
ha : ℵ₀ ≤ a
⊢ a < b → a < a + b
[PROOFSTEP]
intro hb
[GOAL]
a b : Cardinal.{u_1}
h : a + b = a
ha : ℵ₀ ≤ a
hb : a < b
⊢ a < a + b
[PROOFSTEP]
exact hb.trans_le (self_le_add_left b a)
[GOAL]
case refine'_1.inr
a b : Cardinal.{u_1}
h : a + b = a
ha : a < ℵ₀
⊢ ℵ₀ ≤ a ∧ b ≤ a ∨ b = 0
[PROOFSTEP]
right
[GOAL]
case refine'_1.inr.h
a b : Cardinal.{u_1}
h : a + b = a
ha : a < ℵ₀
⊢ b = 0
[PROOFSTEP]
rw [← h, add_lt_aleph0_iff, lt_aleph0, lt_aleph0] at ha
[GOAL]
case refine'_1.inr.h
a b : Cardinal.{u_1}
h : a + b = a
ha : (∃ n, a = ↑n) ∧ ∃ n, b = ↑n
⊢ b = 0
[PROOFSTEP]
rcases ha with ⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩
[GOAL]
case refine'_1.inr.h.intro.intro.intro
n m : ℕ
h : ↑n + ↑m = ↑n
⊢ ↑m = 0
[PROOFSTEP]
norm_cast at h ⊢
[GOAL]
case refine'_1.inr.h.intro.intro.intro
n m : ℕ
h : n + m = n
⊢ m = 0
[PROOFSTEP]
rw [← add_right_inj, h, add_zero]
[GOAL]
case refine'_2
a b : Cardinal.{u_1}
⊢ ℵ₀ ≤ a ∧ b ≤ a ∨ b = 0 → a + b = a
[PROOFSTEP]
rintro (⟨h1, h2⟩ | h3)
[GOAL]
case refine'_2.inl.intro
a b : Cardinal.{u_1}
h1 : ℵ₀ ≤ a
h2 : b ≤ a
⊢ a + b = a
[PROOFSTEP]
rw [add_eq_max h1, max_eq_left h2]
[GOAL]
case refine'_2.inr
a b : Cardinal.{u_1}
h3 : b = 0
⊢ a + b = a
[PROOFSTEP]
rw [h3, add_zero]
[GOAL]
a b : Cardinal.{u_1}
⊢ a + b = b ↔ max ℵ₀ a ≤ b ∨ a = 0
[PROOFSTEP]
rw [add_comm, add_eq_left_iff]
[GOAL]
a b c : Cardinal.{u_1}
h : a + b = a + c
ha : a < ℵ₀
⊢ b = c
[PROOFSTEP]
cases' le_or_lt ℵ₀ b with hb hb
[GOAL]
case inl
a b c : Cardinal.{u_1}
h : a + b = a + c
ha : a < ℵ₀
hb : ℵ₀ ≤ b
⊢ b = c
[PROOFSTEP]
have : a < b := ha.trans_le hb
[GOAL]
case inl
a b c : Cardinal.{u_1}
h : a + b = a + c
ha : a < ℵ₀
hb : ℵ₀ ≤ b
this : a < b
⊢ b = c
[PROOFSTEP]
rw [add_eq_right hb this.le, eq_comm] at h
[GOAL]
case inl
a b c : Cardinal.{u_1}
h : a + c = b
ha : a < ℵ₀
hb : ℵ₀ ≤ b
this : a < b
⊢ b = c
[PROOFSTEP]
rw [eq_of_add_eq_of_aleph0_le h this hb]
[GOAL]
case inr
a b c : Cardinal.{u_1}
h : a + b = a + c
ha : a < ℵ₀
hb : b < ℵ₀
⊢ b = c
[PROOFSTEP]
have hc : c < ℵ₀ := by
rw [← not_le]
intro hc
apply lt_irrefl ℵ₀
apply (hc.trans (self_le_add_left _ a)).trans_lt
rw [← h]
apply add_lt_aleph0 ha hb
[GOAL]
a b c : Cardinal.{u_1}
h : a + b = a + c
ha : a < ℵ₀
hb : b < ℵ₀
⊢ c < ℵ₀
[PROOFSTEP]
rw [← not_le]
[GOAL]
a b c : Cardinal.{u_1}
h : a + b = a + c
ha : a < ℵ₀
hb : b < ℵ₀
⊢ ¬ℵ₀ ≤ c
[PROOFSTEP]
intro hc
[GOAL]
a b c : Cardinal.{u_1}
h : a + b = a + c
ha : a < ℵ₀
hb : b < ℵ₀
hc : ℵ₀ ≤ c
⊢ False
[PROOFSTEP]
apply lt_irrefl ℵ₀
[GOAL]
a b c : Cardinal.{u_1}
h : a + b = a + c
ha : a < ℵ₀
hb : b < ℵ₀
hc : ℵ₀ ≤ c
⊢ ℵ₀ < ℵ₀
[PROOFSTEP]
apply (hc.trans (self_le_add_left _ a)).trans_lt
[GOAL]
a b c : Cardinal.{u_1}
h : a + b = a + c
ha : a < ℵ₀
hb : b < ℵ₀
hc : ℵ₀ ≤ c
⊢ a + c < ℵ₀
[PROOFSTEP]
rw [← h]
[GOAL]
a b c : Cardinal.{u_1}
h : a + b = a + c
ha : a < ℵ₀
hb : b < ℵ₀
hc : ℵ₀ ≤ c
⊢ a + b < ℵ₀
[PROOFSTEP]
apply add_lt_aleph0 ha hb
[GOAL]
case inr
a b c : Cardinal.{u_1}
h : a + b = a + c
ha : a < ℵ₀
hb : b < ℵ₀
hc : c < ℵ₀
⊢ b = c
[PROOFSTEP]
rw [lt_aleph0] at *
[GOAL]
case inr
a b c : Cardinal.{u_1}
h : a + b = a + c
ha : ∃ n, a = ↑n
hb : ∃ n, b = ↑n
hc : ∃ n, c = ↑n
⊢ b = c
[PROOFSTEP]
rcases ha with ⟨n, rfl⟩
[GOAL]
case inr.intro
b c : Cardinal.{u_1}
hb : ∃ n, b = ↑n
hc : ∃ n, c = ↑n
n : ℕ
h : ↑n + b = ↑n + c
⊢ b = c
[PROOFSTEP]
rcases hb with ⟨m, rfl⟩
[GOAL]
case inr.intro.intro
c : Cardinal.{u_1}
hc : ∃ n, c = ↑n
n m : ℕ
h : ↑n + ↑m = ↑n + c
⊢ ↑m = c
[PROOFSTEP]
rcases hc with ⟨k, rfl⟩
[GOAL]
case inr.intro.intro.intro
n m k : ℕ
h : ↑n + ↑m = ↑n + ↑k
⊢ ↑m = ↑k
[PROOFSTEP]
norm_cast at h ⊢
[GOAL]
case inr.intro.intro.intro
n m k : ℕ
h : n + m = n + k
⊢ m = k
[PROOFSTEP]
apply add_left_cancel h
[GOAL]
a b c : Cardinal.{u_1}
h : a + b = c + b
hb : b < ℵ₀
⊢ a = c
[PROOFSTEP]
rw [add_comm a b, add_comm c b] at h
[GOAL]
a b c : Cardinal.{u_1}
h : b + a = b + c
hb : b < ℵ₀
⊢ a = c
[PROOFSTEP]
exact Cardinal.eq_of_add_eq_add_left h hb
[GOAL]
o₁ o₂ : Ordinal.{u_1}
⊢ aleph o₁ + aleph o₂ = aleph (max o₁ o₂)
[PROOFSTEP]
rw [Cardinal.add_eq_max (aleph0_le_aleph o₁), max_aleph_eq]
[GOAL]
c : Cardinal.{u_1}
hc : ℵ₀ ≤ c
a b : Ordinal.{u_1}
ha : a < ord c
hb : b < ord c
⊢ (fun x x_1 => x + x_1) a b < ord c
[PROOFSTEP]
rw [lt_ord, Ordinal.card_add] at *
[GOAL]
c : Cardinal.{u_1}
hc : ℵ₀ ≤ c
a b : Ordinal.{u_1}
ha : card a < c
hb : card b < c
⊢ card a + card b < c
[PROOFSTEP]
exact add_lt_of_lt hc ha hb
[GOAL]
α β γ : Cardinal.{u_1}
γ₀ : γ < ℵ₀
⊢ α + γ ≤ β + γ ↔ α ≤ β
[PROOFSTEP]
refine' ⟨fun h => _, fun h => add_le_add_right h γ⟩
[GOAL]
α β γ : Cardinal.{u_1}
γ₀ : γ < ℵ₀
h : α + γ ≤ β + γ
⊢ α ≤ β
[PROOFSTEP]
contrapose h
[GOAL]
α β γ : Cardinal.{u_1}
γ₀ : γ < ℵ₀
h : ¬α ≤ β
⊢ ¬α + γ ≤ β + γ
[PROOFSTEP]
rw [not_le, lt_iff_le_and_ne, Ne] at h ⊢
[GOAL]
α β γ : Cardinal.{u_1}
γ₀ : γ < ℵ₀
h : β ≤ α ∧ ¬β = α
⊢ β + γ ≤ α + γ ∧ ¬β + γ = α + γ
[PROOFSTEP]
exact ⟨add_le_add_right h.1 γ, mt (add_right_inj_of_lt_aleph0 γ₀).1 h.2⟩
[GOAL]
κ μ : Cardinal.{u}
H1✝ : ℵ₀ ≤ κ
H2 : μ < ℵ₀
n : ℕ
H3 : μ = ↑n
α : Type u
H1 : ℵ₀ ≤ Quotient.mk isEquivalent α
⊢ Quotient.mk isEquivalent α ^ ↑Nat.zero < ℵ₀
[PROOFSTEP]
rw [Nat.cast_zero, power_zero]
[GOAL]
κ μ : Cardinal.{u}
H1✝ : ℵ₀ ≤ κ
H2 : μ < ℵ₀
n : ℕ
H3 : μ = ↑n
α : Type u
H1 : ℵ₀ ≤ Quotient.mk isEquivalent α
⊢ 1 < ℵ₀
[PROOFSTEP]
exact one_lt_aleph0
[GOAL]
κ μ : Cardinal.{u}
H1✝ : ℵ₀ ≤ κ
H2 : μ < ℵ₀
n✝ : ℕ
H3 : μ = ↑n✝
α : Type u
H1 : ℵ₀ ≤ Quotient.mk isEquivalent α
n : ℕ
ih : Quotient.mk isEquivalent α ^ ↑n ≤ Quotient.mk isEquivalent α
⊢ Quotient.mk isEquivalent α ^ ↑(Nat.succ n) ≤ Quotient.mk isEquivalent α * Quotient.mk isEquivalent α
[PROOFSTEP]
rw [Nat.cast_succ, power_add, power_one]
[GOAL]
κ μ : Cardinal.{u}
H1✝ : ℵ₀ ≤ κ
H2 : μ < ℵ₀
n✝ : ℕ
H3 : μ = ↑n✝
α : Type u
H1 : ℵ₀ ≤ Quotient.mk isEquivalent α
n : ℕ
ih : Quotient.mk isEquivalent α ^ ↑n ≤ Quotient.mk isEquivalent α
⊢ Quotient.mk isEquivalent α ^ ↑n * Quotient.mk isEquivalent α ≤ Quotient.mk isEquivalent α * Quotient.mk isEquivalent α
[PROOFSTEP]
exact mul_le_mul_right' ih _
[GOAL]
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ c ^ c = 2 ^ c
[PROOFSTEP]
apply ((power_le_power_right <| (cantor c).le).trans _).antisymm
[GOAL]
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ 2 ^ c ≤ c ^ c
[PROOFSTEP]
exact power_le_power_right ((nat_lt_aleph0 2).le.trans h)
[GOAL]
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ (2 ^ c) ^ c ≤ 2 ^ c
[PROOFSTEP]
rw [← power_mul, mul_eq_self h]
[GOAL]
ι : Type u
inst✝ : Infinite ι
c : ι → Cardinal.{v}
h₁ : ∀ (i : ι), 2 ≤ c i
h₂ : ∀ (i : ι), lift (c i) ≤ lift #ι
⊢ prod c = 2 ^ lift #ι
[PROOFSTEP]
rw [← lift_id'.{u, v} (prod.{u, v} c), lift_prod, ← lift_two_power]
[GOAL]
ι : Type u
inst✝ : Infinite ι
c : ι → Cardinal.{v}
h₁ : ∀ (i : ι), 2 ≤ c i
h₂ : ∀ (i : ι), lift (c i) ≤ lift #ι
⊢ (prod fun i => lift (c i)) = lift (2 ^ #ι)
[PROOFSTEP]
apply le_antisymm
[GOAL]
case a
ι : Type u
inst✝ : Infinite ι
c : ι → Cardinal.{v}
h₁ : ∀ (i : ι), 2 ≤ c i
h₂ : ∀ (i : ι), lift (c i) ≤ lift #ι
⊢ (prod fun i => lift (c i)) ≤ lift (2 ^ #ι)
[PROOFSTEP]
refine' (prod_le_prod _ _ h₂).trans_eq _
[GOAL]
case a
ι : Type u
inst✝ : Infinite ι
c : ι → Cardinal.{v}
h₁ : ∀ (i : ι), 2 ≤ c i
h₂ : ∀ (i : ι), lift (c i) ≤ lift #ι
⊢ (prod fun i => lift #ι) = lift (2 ^ #ι)
[PROOFSTEP]
rw [prod_const, lift_lift, ← lift_power, power_self_eq (aleph0_le_mk ι), lift_umax.{u, v}]
[GOAL]
case a
ι : Type u
inst✝ : Infinite ι
c : ι → Cardinal.{v}
h₁ : ∀ (i : ι), 2 ≤ c i
h₂ : ∀ (i : ι), lift (c i) ≤ lift #ι
⊢ lift (2 ^ #ι) ≤ prod fun i => lift (c i)
[PROOFSTEP]
rw [← prod_const', lift_prod]
[GOAL]
case a
ι : Type u
inst✝ : Infinite ι
c : ι → Cardinal.{v}
h₁ : ∀ (i : ι), 2 ≤ c i
h₂ : ∀ (i : ι), lift (c i) ≤ lift #ι
⊢ (prod fun i => lift 2) ≤ prod fun i => lift (c i)
[PROOFSTEP]
refine' prod_le_prod _ _ fun i => _
[GOAL]
case a
ι : Type u
inst✝ : Infinite ι
c : ι → Cardinal.{v}
h₁ : ∀ (i : ι), 2 ≤ c i
h₂ : ∀ (i : ι), lift (c i) ≤ lift #ι
i : ι
⊢ lift 2 ≤ lift (c i)
[PROOFSTEP]
rw [lift_two, ← lift_two.{u, v}, lift_le]
[GOAL]
case a
ι : Type u
inst✝ : Infinite ι
c : ι → Cardinal.{v}
h₁ : ∀ (i : ι), 2 ≤ c i
h₂ : ∀ (i : ι), lift (c i) ≤ lift #ι
i : ι
⊢ 2 ≤ c i
[PROOFSTEP]
exact h₁ i
[GOAL]
c : Cardinal.{u}
h : ℵ₀ ≤ c
n : ℕ
hn : 2 ≤ n
⊢ 2 ≤ ↑n
[PROOFSTEP]
assumption_mod_cast
[GOAL]
c : Cardinal.{u}
n : ℕ
h1 : ℵ₀ ≤ c
h2 : 1 ≤ n
⊢ 1 ≤ ↑n
[PROOFSTEP]
exact_mod_cast h2
[GOAL]
c : Cardinal.{u}
n : ℕ
⊢ c ^ ↑n ≤ max c ℵ₀
[PROOFSTEP]
cases' le_or_lt ℵ₀ c with hc hc
[GOAL]
case inl
c : Cardinal.{u}
n : ℕ
hc : ℵ₀ ≤ c
⊢ c ^ ↑n ≤ max c ℵ₀
[PROOFSTEP]
exact le_max_of_le_left (power_nat_le hc)
[GOAL]
case inr
c : Cardinal.{u}
n : ℕ
hc : c < ℵ₀
⊢ c ^ ↑n ≤ max c ℵ₀
[PROOFSTEP]
exact le_max_of_le_right (power_lt_aleph0 hc (nat_lt_aleph0 _)).le
[GOAL]
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ c ^< ℵ₀ = c
[PROOFSTEP]
apply le_antisymm
[GOAL]
case a
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ c ^< ℵ₀ ≤ c
[PROOFSTEP]
rw [powerlt_le]
[GOAL]
case a
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ ∀ (x : Cardinal.{u_1}), x < ℵ₀ → c ^ x ≤ c
[PROOFSTEP]
intro c'
[GOAL]
case a
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
c' : Cardinal.{u_1}
⊢ c' < ℵ₀ → c ^ c' ≤ c
[PROOFSTEP]
rw [lt_aleph0]
[GOAL]
case a
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
c' : Cardinal.{u_1}
⊢ (∃ n, c' = ↑n) → c ^ c' ≤ c
[PROOFSTEP]
rintro ⟨n, rfl⟩
[GOAL]
case a.intro
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
n : ℕ
⊢ c ^ ↑n ≤ c
[PROOFSTEP]
apply power_nat_le h
[GOAL]
case a
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ c ≤ c ^< ℵ₀
[PROOFSTEP]
convert le_powerlt c one_lt_aleph0
[GOAL]
case h.e'_3
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ c = c ^ 1
[PROOFSTEP]
rw [power_one]
[GOAL]
c : Cardinal.{u_1}
⊢ c ^< ℵ₀ ≤ max c ℵ₀
[PROOFSTEP]
cases' le_or_lt ℵ₀ c with h h
[GOAL]
case inl
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ c ^< ℵ₀ ≤ max c ℵ₀
[PROOFSTEP]
rw [powerlt_aleph0 h]
[GOAL]
case inl
c : Cardinal.{u_1}
h : ℵ₀ ≤ c
⊢ c ≤ max c ℵ₀
[PROOFSTEP]
apply le_max_left
[GOAL]
case inr
c : Cardinal.{u_1}
h : c < ℵ₀
⊢ c ^< ℵ₀ ≤ max c ℵ₀
[PROOFSTEP]
rw [powerlt_le]
[GOAL]
case inr
c : Cardinal.{u_1}
h : c < ℵ₀
⊢ ∀ (x : Cardinal.{u_1}), x < ℵ₀ → c ^ x ≤ max c ℵ₀
[PROOFSTEP]
exact fun c' hc' => (power_lt_aleph0 h hc').le.trans (le_max_right _ _)
[GOAL]
α : Type u
inst✝ : Infinite α
H1 : ℵ₀ ≤ #α
x✝ : α
⊢ ∀ ⦃a₂ : α⦄, (fun a => [a]) x✝ = (fun a => [a]) a₂ → x✝ = a₂
[PROOFSTEP]
simp
[GOAL]
α : Type u
inst✝ : Infinite α
H1 : ℵ₀ ≤ #α
⊢ (sum fun x => #α) = #α
[PROOFSTEP]
simp [H1]
[GOAL]
α : Type u
inst✝ : Nonempty α
⊢ #(List α) = max #α ℵ₀
[PROOFSTEP]
cases finite_or_infinite α
[GOAL]
case inl
α : Type u
inst✝ : Nonempty α
h✝ : Finite α
⊢ #(List α) = max #α ℵ₀
[PROOFSTEP]
rw [mk_list_eq_aleph0, eq_comm, max_eq_right]
[GOAL]
case inl
α : Type u
inst✝ : Nonempty α
h✝ : Finite α
⊢ #α ≤ ℵ₀
[PROOFSTEP]
exact mk_le_aleph0
[GOAL]
case inr
α : Type u
inst✝ : Nonempty α
h✝ : Infinite α
⊢ #(List α) = max #α ℵ₀
[PROOFSTEP]
rw [mk_list_eq_mk, eq_comm, max_eq_left]
[GOAL]
case inr
α : Type u
inst✝ : Nonempty α
h✝ : Infinite α
⊢ ℵ₀ ≤ #α
[PROOFSTEP]
exact aleph0_le_mk α
[GOAL]
α : Type u
⊢ #(List α) ≤ max ℵ₀ #α
[PROOFSTEP]
cases finite_or_infinite α
[GOAL]
case inl
α : Type u
h✝ : Finite α
⊢ #(List α) ≤ max ℵ₀ #α
[PROOFSTEP]
exact mk_le_aleph0.trans (le_max_left _ _)
[GOAL]
case inr
α : Type u
h✝ : Infinite α
⊢ #(List α) ≤ max ℵ₀ #α
[PROOFSTEP]
rw [mk_list_eq_mk]
[GOAL]
case inr
α : Type u
h✝ : Infinite α
⊢ #α ≤ max ℵ₀ #α
[PROOFSTEP]
apply le_max_right
[GOAL]
α : Type u
β : Type v
inst✝² : Infinite α
inst✝¹ : Zero β
inst✝ : Nontrivial β
⊢ #(α →₀ β) = max (lift #α) (lift #β)
[PROOFSTEP]
apply le_antisymm
[GOAL]
case a
α : Type u
β : Type v
inst✝² : Infinite α
inst✝¹ : Zero β
inst✝ : Nontrivial β
⊢ #(α →₀ β) ≤ max (lift #α) (lift #β)
[PROOFSTEP]
calc
#(α →₀ β) ≤ #(Finset (α × β)) := mk_le_of_injective (Finsupp.graph_injective α β)
_ = #(α × β) := (mk_finset_of_infinite _)
_ = max (lift.{v} #α) (lift.{u} #β) := by rw [mk_prod, mul_eq_max_of_aleph0_le_left] <;> simp
[GOAL]
α : Type u
β : Type v
inst✝² : Infinite α
inst✝¹ : Zero β
inst✝ : Nontrivial β
⊢ #(α × β) = max (lift #α) (lift #β)
[PROOFSTEP]
rw [mk_prod, mul_eq_max_of_aleph0_le_left]
[GOAL]
case h
α : Type u
β : Type v
inst✝² : Infinite α
inst✝¹ : Zero β
inst✝ : Nontrivial β
⊢ ℵ₀ ≤ lift #α
[PROOFSTEP]
simp
[GOAL]
case h'
α : Type u
β : Type v
inst✝² : Infinite α
inst✝¹ : Zero β
inst✝ : Nontrivial β
⊢ lift #β ≠ 0
[PROOFSTEP]
simp
[GOAL]
case a
α : Type u
β : Type v
inst✝² : Infinite α
inst✝¹ : Zero β
inst✝ : Nontrivial β
⊢ max (lift #α) (lift #β) ≤ #(α →₀ β)
[PROOFSTEP]
apply max_le
[GOAL]
case a.h₁
α : Type u
β : Type v
inst✝² : Infinite α
inst✝¹ : Zero β
inst✝ : Nontrivial β
⊢ lift #α ≤ #(α →₀ β)
[PROOFSTEP]
rw [← lift_id #(α →₀ β), ← lift_umax]
[GOAL]
case a.h₂
α : Type u
β : Type v
inst✝² : Infinite α
inst✝¹ : Zero β
inst✝ : Nontrivial β
⊢ lift #β ≤ #(α →₀ β)
[PROOFSTEP]
rw [← lift_id #(α →₀ β), ← lift_umax]
[GOAL]
case a.h₁
α : Type u
β : Type v
inst✝² : Infinite α
inst✝¹ : Zero β
inst✝ : Nontrivial β
⊢ lift #α ≤ lift #(α →₀ β)
[PROOFSTEP]
cases' exists_ne (0 : β) with b hb
[GOAL]
case a.h₁.intro
α : Type u
β : Type v
inst✝² : Infinite α
inst✝¹ : Zero β
inst✝ : Nontrivial β
b : β
hb : b ≠ 0
⊢ lift #α ≤ lift #(α →₀ β)
[PROOFSTEP]
exact lift_mk_le.{v}.2 ⟨⟨_, Finsupp.single_left_injective hb⟩⟩
[GOAL]
case a.h₂
α : Type u
β : Type v
inst✝² : Infinite α
inst✝¹ : Zero β
inst✝ : Nontrivial β
⊢ lift #β ≤ lift #(α →₀ β)
[PROOFSTEP]
inhabit α
[GOAL]
case a.h₂
α : Type u
β : Type v
inst✝² : Infinite α
inst✝¹ : Zero β
inst✝ : Nontrivial β
inhabited_h : Inhabited α
⊢ lift #β ≤ lift #(α →₀ β)
[PROOFSTEP]
exact lift_mk_le.{u}.2 ⟨⟨_, Finsupp.single_injective default⟩⟩
[GOAL]
α β : Type u
inst✝² : Infinite α
inst✝¹ : Zero β
inst✝ : Nontrivial β
⊢ #(α →₀ β) = max #α #β
[PROOFSTEP]
simp
[GOAL]
α : Type u
β : Type v
inst✝² : Nonempty α
inst✝¹ : Zero β
inst✝ : Infinite β
⊢ #(α →₀ β) = max (lift #α) (lift #β)
[PROOFSTEP]
cases fintypeOrInfinite α
[GOAL]
case inl
α : Type u
β : Type v
inst✝² : Nonempty α
inst✝¹ : Zero β
inst✝ : Infinite β
val✝ : Fintype α
⊢ #(α →₀ β) = max (lift #α) (lift #β)
[PROOFSTEP]
rw [mk_finsupp_lift_of_fintype]
[GOAL]
case inl
α : Type u
β : Type v
inst✝² : Nonempty α
inst✝¹ : Zero β
inst✝ : Infinite β
val✝ : Fintype α
⊢ lift #β ^ Fintype.card α = max (lift #α) (lift #β)
[PROOFSTEP]
have : ℵ₀ ≤ (#β).lift := aleph0_le_lift.2 (aleph0_le_mk β)
[GOAL]
case inl
α : Type u
β : Type v
inst✝² : Nonempty α
inst✝¹ : Zero β
inst✝ : Infinite β
val✝ : Fintype α
this : ℵ₀ ≤ lift #β
⊢ lift #β ^ Fintype.card α = max (lift #α) (lift #β)
[PROOFSTEP]
rw [max_eq_right (le_trans _ this), power_nat_eq this]
[GOAL]
case inl
α : Type u
β : Type v
inst✝² : Nonempty α
inst✝¹ : Zero β
inst✝ : Infinite β
val✝ : Fintype α
this : ℵ₀ ≤ lift #β
⊢ 1 ≤ Fintype.card α
α : Type u
β : Type v
inst✝² : Nonempty α
inst✝¹ : Zero β
inst✝ : Infinite β
val✝ : Fintype α
this : ℵ₀ ≤ lift #β
⊢ lift #α ≤ ℵ₀
[PROOFSTEP]
exacts [Fintype.card_pos, lift_le_aleph0.2 (lt_aleph0_of_finite _).le]
[GOAL]
case inr
α : Type u
β : Type v
inst✝² : Nonempty α
inst✝¹ : Zero β
inst✝ : Infinite β
val✝ : Infinite α
⊢ #(α →₀ β) = max (lift #α) (lift #β)
[PROOFSTEP]
apply mk_finsupp_lift_of_infinite
[GOAL]
α β : Type u
inst✝² : Nonempty α
inst✝¹ : Zero β
inst✝ : Infinite β
⊢ #(α →₀ β) = max #α #β
[PROOFSTEP]
simp
[GOAL]
α : Type u
inst✝ : Nonempty α
⊢ #(α →₀ ℕ) = max #α ℵ₀
[PROOFSTEP]
simp
[GOAL]
α : Type u
inst✝ : Infinite α
⊢ #(Multiset α) = #α
[PROOFSTEP]
simp
[GOAL]
α : Type u
inst✝ : IsEmpty α
⊢ #(α →₀ ℕ) = 1
[PROOFSTEP]
simp
[GOAL]
α : Type u
inst✝¹ : Countable α
inst✝ : Nonempty α
⊢ #(α →₀ ℕ) = ℵ₀
[PROOFSTEP]
simp
[GOAL]
α : Type u
inst✝ : Infinite α
c : Cardinal.{u}
⊢ #{ t // #↑t ≤ c } ≤ #α ^ c
[PROOFSTEP]
refine' le_trans _ (by rw [← add_one_eq (aleph0_le_mk α)])
[GOAL]
α : Type u
inst✝ : Infinite α
c : Cardinal.{u}
⊢ ?m.211821 ≤ #α ^ c
[PROOFSTEP]
rw [← add_one_eq (aleph0_le_mk α)]
[GOAL]
α : Type u
inst✝ : Infinite α
c : Cardinal.{u}
⊢ #{ t // #↑t ≤ c } ≤ (#α + 1) ^ c
[PROOFSTEP]
induction' c using Cardinal.inductionOn with β
[GOAL]
case h
α : Type u
inst✝ : Infinite α
β : Type u
⊢ #{ t // #↑t ≤ #β } ≤ (#α + 1) ^ #β
[PROOFSTEP]
fapply mk_le_of_surjective
[GOAL]
case h.f
α : Type u
inst✝ : Infinite α
β : Type u
⊢ (fun α β => β → α) (α ⊕ ULift (Fin 1)) β → { t // #↑t ≤ #β }
[PROOFSTEP]
intro f
[GOAL]
case h.f
α : Type u
inst✝ : Infinite α
β : Type u
f : (fun α β => β → α) (α ⊕ ULift (Fin 1)) β
⊢ { t // #↑t ≤ #β }
[PROOFSTEP]
use Sum.inl ⁻¹' range f
[GOAL]
case property
α : Type u
inst✝ : Infinite α
β : Type u
f : (fun α β => β → α) (α ⊕ ULift (Fin 1)) β
⊢ #↑(Sum.inl ⁻¹' range f) ≤ #β
[PROOFSTEP]
refine' le_trans (mk_preimage_of_injective _ _ fun x y => Sum.inl.inj) _
[GOAL]
case property
α : Type u
inst✝ : Infinite α
β : Type u
f : (fun α β => β → α) (α ⊕ ULift (Fin 1)) β
⊢ #↑(range f) ≤ #β
[PROOFSTEP]
apply mk_range_le
[GOAL]
case h.hf
α : Type u
inst✝ : Infinite α
β : Type u
⊢ Surjective fun f => { val := Sum.inl ⁻¹' range f, property := (_ : #↑(Sum.inl ⁻¹' range f) ≤ #β) }
[PROOFSTEP]
rintro ⟨s, ⟨g⟩⟩
[GOAL]
case h.hf.mk.intro
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
⊢ ∃ a,
(fun f => { val := Sum.inl ⁻¹' range f, property := (_ : #↑(Sum.inl ⁻¹' range f) ≤ #β) }) a =
{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
[PROOFSTEP]
use fun y => if h : ∃ x : s, g x = y then Sum.inl (Classical.choose h).val else Sum.inr (ULift.up 0)
[GOAL]
case h
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
⊢ ((fun f => { val := Sum.inl ⁻¹' range f, property := (_ : #↑(Sum.inl ⁻¹' range f) ≤ #β) }) fun y =>
if h : ∃ x, ↑g x = y then Sum.inl ↑(choose h) else Sum.inr { down := 0 }) =
{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
[PROOFSTEP]
apply Subtype.eq
[GOAL]
case h.a
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
⊢ ↑((fun f => { val := Sum.inl ⁻¹' range f, property := (_ : #↑(Sum.inl ⁻¹' range f) ≤ #β) }) fun y =>
if h : ∃ x, ↑g x = y then Sum.inl ↑(choose h) else Sum.inr { down := 0 }) =
↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
[PROOFSTEP]
ext x
[GOAL]
case h.a.h
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
⊢ x ∈
↑((fun f => { val := Sum.inl ⁻¹' range f, property := (_ : #↑(Sum.inl ⁻¹' range f) ≤ #β) }) fun y =>
if h : ∃ x, ↑g x = y then Sum.inl ↑(choose h) else Sum.inr { down := 0 }) ↔
x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
[PROOFSTEP]
constructor
[GOAL]
case h.a.h.mp
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
⊢ x ∈
↑((fun f => { val := Sum.inl ⁻¹' range f, property := (_ : #↑(Sum.inl ⁻¹' range f) ≤ #β) }) fun y =>
if h : ∃ x, ↑g x = y then Sum.inl ↑(choose h) else Sum.inr { down := 0 }) →
x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
[PROOFSTEP]
rintro ⟨y, h⟩
[GOAL]
case h.a.h.mp.intro
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
y : β
h : (fun y => if h : ∃ x, ↑g x = y then Sum.inl ↑(choose h) else Sum.inr { down := 0 }) y = Sum.inl x
⊢ x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
[PROOFSTEP]
dsimp only at h
[GOAL]
case h.a.h.mp.intro
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
y : β
h : (if h : ∃ x, ↑g x = y then Sum.inl ↑(choose h) else Sum.inr { down := 0 }) = Sum.inl x
⊢ x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
[PROOFSTEP]
by_cases h' : ∃ z : s, g z = y
[GOAL]
case pos
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
y : β
h : (if h : ∃ x, ↑g x = y then Sum.inl ↑(choose h) else Sum.inr { down := 0 }) = Sum.inl x
h' : ∃ z, ↑g z = y
⊢ x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
[PROOFSTEP]
rw [dif_pos h'] at h
[GOAL]
case pos
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
y : β
h' : ∃ z, ↑g z = y
h : Sum.inl ↑(choose h') = Sum.inl x
⊢ x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
[PROOFSTEP]
cases Sum.inl.inj h
[GOAL]
case pos.refl
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
y : β
h' : ∃ z, ↑g z = y
h : Sum.inl ↑(choose h') = Sum.inl ↑(choose h')
⊢ ↑(choose h') ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
[PROOFSTEP]
exact (Classical.choose h').2
[GOAL]
case neg
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
y : β
h : (if h : ∃ x, ↑g x = y then Sum.inl ↑(choose h) else Sum.inr { down := 0 }) = Sum.inl x
h' : ¬∃ z, ↑g z = y
⊢ x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
[PROOFSTEP]
rw [dif_neg h'] at h
[GOAL]
case neg
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
y : β
h : Sum.inr { down := 0 } = Sum.inl x
h' : ¬∃ z, ↑g z = y
⊢ x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
[PROOFSTEP]
cases h
[GOAL]
case h.a.h.mpr
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
⊢ x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) } →
x ∈
↑((fun f => { val := Sum.inl ⁻¹' range f, property := (_ : #↑(Sum.inl ⁻¹' range f) ≤ #β) }) fun y =>
if h : ∃ x, ↑g x = y then Sum.inl ↑(choose h) else Sum.inr { down := 0 })
[PROOFSTEP]
intro h
[GOAL]
case h.a.h.mpr
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
h : x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
⊢ x ∈
↑((fun f => { val := Sum.inl ⁻¹' range f, property := (_ : #↑(Sum.inl ⁻¹' range f) ≤ #β) }) fun y =>
if h : ∃ x, ↑g x = y then Sum.inl ↑(choose h) else Sum.inr { down := 0 })
[PROOFSTEP]
have : ∃ z : s, g z = g ⟨x, h⟩ := ⟨⟨x, h⟩, rfl⟩
[GOAL]
case h.a.h.mpr
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
h : x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
this : ∃ z, ↑g z = ↑g { val := x, property := h }
⊢ x ∈
↑((fun f => { val := Sum.inl ⁻¹' range f, property := (_ : #↑(Sum.inl ⁻¹' range f) ≤ #β) }) fun y =>
if h : ∃ x, ↑g x = y then Sum.inl ↑(choose h) else Sum.inr { down := 0 })
[PROOFSTEP]
use g ⟨x, h⟩
[GOAL]
case h
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
h : x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
this : ∃ z, ↑g z = ↑g { val := x, property := h }
⊢ (fun y => if h : ∃ x, ↑g x = y then Sum.inl ↑(choose h) else Sum.inr { down := 0 }) (↑g { val := x, property := h }) =
Sum.inl x
[PROOFSTEP]
dsimp only
[GOAL]
case h
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
h : x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
this : ∃ z, ↑g z = ↑g { val := x, property := h }
⊢ (if h_1 : ∃ x_1, ↑g x_1 = ↑g { val := x, property := h } then Sum.inl ↑(choose h_1) else Sum.inr { down := 0 }) =
Sum.inl x
[PROOFSTEP]
rw [dif_pos this]
[GOAL]
case h
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
h : x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
this : ∃ z, ↑g z = ↑g { val := x, property := h }
⊢ Sum.inl ↑(choose this) = Sum.inl x
[PROOFSTEP]
congr
[GOAL]
case h.e_val
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
h : x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
this : ∃ z, ↑g z = ↑g { val := x, property := h }
⊢ ↑(choose this) = x
[PROOFSTEP]
suffices : Classical.choose this = ⟨x, h⟩
[GOAL]
case h.e_val
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
h : x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
this✝ : ∃ z, ↑g z = ↑g { val := x, property := h }
this : choose this✝ = { val := x, property := h }
⊢ ↑(choose this✝) = x
case this
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
h : x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
this : ∃ z, ↑g z = ↑g { val := x, property := h }
⊢ choose this = { val := x, property := h }
[PROOFSTEP]
exact congr_arg Subtype.val this
[GOAL]
case this
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
h : x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
this : ∃ z, ↑g z = ↑g { val := x, property := h }
⊢ choose this = { val := x, property := h }
[PROOFSTEP]
apply g.2
[GOAL]
case this.a
α : Type u
inst✝ : Infinite α
β : Type u
s : Set α
g : ↑s ↪ β
x : α
h : x ∈ ↑{ val := s, property := (_ : Nonempty (↑s ↪ β)) }
this : ∃ z, ↑g z = ↑g { val := x, property := h }
⊢ Embedding.toFun g (choose this) = Embedding.toFun g { val := x, property := h }
[PROOFSTEP]
exact Classical.choose_spec this
[GOAL]
α : Type u
c : Cardinal.{u}
⊢ #{ t // #↑t ≤ c } ≤ max #α ℵ₀ ^ c
[PROOFSTEP]
trans #{ t : Set (Sum (ULift.{u} ℕ) α) // #t ≤ c }
[GOAL]
α : Type u
c : Cardinal.{u}
⊢ #{ t // #↑t ≤ c } ≤ #{ t // #↑t ≤ c }
[PROOFSTEP]
refine' ⟨Embedding.subtypeMap _ _⟩
[GOAL]
case refine'_1
α : Type u
c : Cardinal.{u}
⊢ Set α ↪ Set (ULift ℕ ⊕ α)
case refine'_2 α : Type u c : Cardinal.{u} ⊢ ∀ ⦃x : Set α⦄, #↑x ≤ c → #↑(↑?refine'_1 x) ≤ c
[PROOFSTEP]
apply Embedding.image
[GOAL]
case refine'_1.f
α : Type u
c : Cardinal.{u}
⊢ α ↪ ULift ℕ ⊕ α
case refine'_2 α : Type u c : Cardinal.{u} ⊢ ∀ ⦃x : Set α⦄, #↑x ≤ c → #↑(↑(Embedding.image ?refine'_1.f) x) ≤ c
[PROOFSTEP]
use Sum.inr
[GOAL]
case inj'
α : Type u
c : Cardinal.{u}
⊢ Injective Sum.inr
case refine'_2
α : Type u
c : Cardinal.{u}
⊢ ∀ ⦃x : Set α⦄, #↑x ≤ c → #↑(↑(Embedding.image { toFun := Sum.inr, inj' := ?inj' }) x) ≤ c
[PROOFSTEP]
apply Sum.inr.inj
[GOAL]
case refine'_2
α : Type u
c : Cardinal.{u}
⊢ ∀ ⦃x : Set α⦄,
#↑x ≤ c →
#↑(↑(Embedding.image
{ toFun := Sum.inr, inj' := (_ : ∀ {val val_1 : α}, Sum.inr val = Sum.inr val_1 → val = val_1) })
x) ≤
c
[PROOFSTEP]
intro s hs
[GOAL]
case refine'_2
α : Type u
c : Cardinal.{u}
s : Set α
hs : #↑s ≤ c
⊢ #↑(↑(Embedding.image { toFun := Sum.inr, inj' := (_ : ∀ {val val_1 : α}, Sum.inr val = Sum.inr val_1 → val = val_1) })
s) ≤
c
[PROOFSTEP]
exact mk_image_le.trans hs
[GOAL]
α : Type u
c : Cardinal.{u}
⊢ #{ t // #↑t ≤ c } ≤ max #α ℵ₀ ^ c
[PROOFSTEP]
apply (mk_bounded_set_le_of_infinite (Sum (ULift.{u} ℕ) α) c).trans
[GOAL]
α : Type u
c : Cardinal.{u}
⊢ #(ULift ℕ ⊕ α) ^ c ≤ max #α ℵ₀ ^ c
[PROOFSTEP]
rw [max_comm, ← add_eq_max]
[GOAL]
α : Type u
c : Cardinal.{u}
⊢ #(ULift ℕ ⊕ α) ^ c ≤ (ℵ₀ + #α) ^ c
[PROOFSTEP]
rfl
[GOAL]
α : Type u
c : Cardinal.{u}
⊢ ℵ₀ ≤ ℵ₀
[PROOFSTEP]
rfl
[GOAL]
α : Type u
s : Set α
c : Cardinal.{u}
⊢ #{ t // t ⊆ s ∧ #↑t ≤ c } ≤ max #↑s ℵ₀ ^ c
[PROOFSTEP]
refine' le_trans _ (mk_bounded_set_le s c)
[GOAL]
α : Type u
s : Set α
c : Cardinal.{u}
⊢ #{ t // t ⊆ s ∧ #↑t ≤ c } ≤ #{ t // #↑t ≤ c }
[PROOFSTEP]
refine' ⟨Embedding.codRestrict _ _ _⟩
[GOAL]
case refine'_1
α : Type u
s : Set α
c : Cardinal.{u}
⊢ { t // t ⊆ s ∧ #↑t ≤ c } ↪ Set ↑s
case refine'_2
α : Type u
s : Set α
c : Cardinal.{u}
⊢ ∀ (a : { t // t ⊆ s ∧ #↑t ≤ c }),
↑?refine'_1 a ∈ fun t =>
Quot.lift ((fun α β => Nonempty (α ↪ β)) ↑t) (_ : ∀ (a b : Type u), a ≈ b → Nonempty (↑t ↪ a) = Nonempty (↑t ↪ b))
c
[PROOFSTEP]
use fun t => (↑) ⁻¹' t.1
[GOAL]
case inj'
α : Type u
s : Set α
c : Cardinal.{u}
⊢ Injective fun t => Subtype.val ⁻¹' ↑t
[PROOFSTEP]
rintro ⟨t, ht1, ht2⟩ ⟨t', h1t', h2t'⟩ h
[GOAL]
case inj'.mk.intro.mk.intro
α : Type u
s : Set α
c : Cardinal.{u}
t : Set α
ht1 : t ⊆ s
ht2 : #↑t ≤ c
t' : Set α
h1t' : t' ⊆ s
h2t' : #↑t' ≤ c
h :
(fun t => Subtype.val ⁻¹' ↑t) { val := t, property := (_ : t ⊆ s ∧ #↑t ≤ c) } =
(fun t => Subtype.val ⁻¹' ↑t) { val := t', property := (_ : t' ⊆ s ∧ #↑t' ≤ c) }
⊢ { val := t, property := (_ : t ⊆ s ∧ #↑t ≤ c) } = { val := t', property := (_ : t' ⊆ s ∧ #↑t' ≤ c) }
[PROOFSTEP]
apply Subtype.eq
[GOAL]
case inj'.mk.intro.mk.intro.a
α : Type u
s : Set α
c : Cardinal.{u}
t : Set α
ht1 : t ⊆ s
ht2 : #↑t ≤ c
t' : Set α
h1t' : t' ⊆ s
h2t' : #↑t' ≤ c
h :
(fun t => Subtype.val ⁻¹' ↑t) { val := t, property := (_ : t ⊆ s ∧ #↑t ≤ c) } =
(fun t => Subtype.val ⁻¹' ↑t) { val := t', property := (_ : t' ⊆ s ∧ #↑t' ≤ c) }
⊢ ↑{ val := t, property := (_ : t ⊆ s ∧ #↑t ≤ c) } = ↑{ val := t', property := (_ : t' ⊆ s ∧ #↑t' ≤ c) }
[PROOFSTEP]
dsimp only at h ⊢
[GOAL]
case inj'.mk.intro.mk.intro.a
α : Type u
s : Set α
c : Cardinal.{u}
t : Set α
ht1 : t ⊆ s
ht2 : #↑t ≤ c
t' : Set α
h1t' : t' ⊆ s
h2t' : #↑t' ≤ c
h : Subtype.val ⁻¹' t = Subtype.val ⁻¹' t'
⊢ t = t'
[PROOFSTEP]
refine' (preimage_eq_preimage' _ _).1 h
[GOAL]
case inj'.mk.intro.mk.intro.a.refine'_1
α : Type u
s : Set α
c : Cardinal.{u}
t : Set α
ht1 : t ⊆ s
ht2 : #↑t ≤ c
t' : Set α
h1t' : t' ⊆ s
h2t' : #↑t' ≤ c
h : Subtype.val ⁻¹' t = Subtype.val ⁻¹' t'
⊢ t ⊆ range Subtype.val
[PROOFSTEP]
rw [Subtype.range_coe]
[GOAL]
case inj'.mk.intro.mk.intro.a.refine'_2
α : Type u
s : Set α
c : Cardinal.{u}
t : Set α
ht1 : t ⊆ s
ht2 : #↑t ≤ c
t' : Set α
h1t' : t' ⊆ s
h2t' : #↑t' ≤ c
h : Subtype.val ⁻¹' t = Subtype.val ⁻¹' t'
⊢ t' ⊆ range Subtype.val
[PROOFSTEP]
rw [Subtype.range_coe]
[GOAL]
case inj'.mk.intro.mk.intro.a.refine'_1
α : Type u
s : Set α
c : Cardinal.{u}
t : Set α
ht1 : t ⊆ s
ht2 : #↑t ≤ c
t' : Set α
h1t' : t' ⊆ s
h2t' : #↑t' ≤ c
h : Subtype.val ⁻¹' t = Subtype.val ⁻¹' t'
⊢ t ⊆ s
[PROOFSTEP]
assumption
[GOAL]
case inj'.mk.intro.mk.intro.a.refine'_2
α : Type u
s : Set α
c : Cardinal.{u}
t : Set α
ht1 : t ⊆ s
ht2 : #↑t ≤ c
t' : Set α
h1t' : t' ⊆ s
h2t' : #↑t' ≤ c
h : Subtype.val ⁻¹' t = Subtype.val ⁻¹' t'
⊢ t' ⊆ s
[PROOFSTEP]
assumption
[GOAL]
case refine'_2
α : Type u
s : Set α
c : Cardinal.{u}
⊢ ∀ (a : { t // t ⊆ s ∧ #↑t ≤ c }),
↑{ toFun := fun t => Subtype.val ⁻¹' ↑t,
inj' :=
(_ :
∀ ⦃a₁ a₂ : { t // t ⊆ s ∧ #↑t ≤ c }⦄,
(fun t => Subtype.val ⁻¹' ↑t) a₁ = (fun t => Subtype.val ⁻¹' ↑t) a₂ → a₁ = a₂) }
a ∈
fun t =>
Quot.lift ((fun α β => Nonempty (α ↪ β)) ↑t) (_ : ∀ (a b : Type u), a ≈ b → Nonempty (↑t ↪ a) = Nonempty (↑t ↪ b))
c
[PROOFSTEP]
rintro ⟨t, _, h2t⟩
[GOAL]
case refine'_2.mk.intro
α : Type u
s : Set α
c : Cardinal.{u}
t : Set α
left✝ : t ⊆ s
h2t : #↑t ≤ c
⊢ ↑{ toFun := fun t => Subtype.val ⁻¹' ↑t,
inj' :=
(_ :
∀ ⦃a₁ a₂ : { t // t ⊆ s ∧ #↑t ≤ c }⦄,
(fun t => Subtype.val ⁻¹' ↑t) a₁ = (fun t => Subtype.val ⁻¹' ↑t) a₂ → a₁ = a₂) }
{ val := t, property := (_ : t ⊆ s ∧ #↑t ≤ c) } ∈
fun t =>
Quot.lift ((fun α β => Nonempty (α ↪ β)) ↑t) (_ : ∀ (a b : Type u), a ≈ b → Nonempty (↑t ↪ a) = Nonempty (↑t ↪ b)) c
[PROOFSTEP]
exact (mk_preimage_of_injective _ _ Subtype.val_injective).trans h2t
[GOAL]
α : Type u_1
inst✝ : Infinite α
s : Set α
h2 : #↑s < #α
⊢ #↑sᶜ = #α
[PROOFSTEP]
refine' eq_of_add_eq_of_aleph0_le _ h2 (aleph0_le_mk α)
[GOAL]
α : Type u_1
inst✝ : Infinite α
s : Set α
h2 : #↑s < #α
⊢ #↑s + #↑sᶜ = #α
[PROOFSTEP]
exact mk_sum_compl s
[GOAL]
α : Type u_1
inst✝ : Infinite α
s : Finset α
⊢ #↑(↑s)ᶜ = #α
[PROOFSTEP]
apply mk_compl_of_infinite
[GOAL]
case h2
α : Type u_1
inst✝ : Infinite α
s : Finset α
⊢ #↑↑s < #α
[PROOFSTEP]
exact (finset_card_lt_aleph0 s).trans_le (aleph0_le_mk α)
[GOAL]
α : Type u_1
inst✝ : Infinite α
s t : Set α
hs : #↑s < #α
ht : #↑t < #α
⊢ #↑sᶜ = #↑tᶜ
[PROOFSTEP]
rw [mk_compl_of_infinite s hs, mk_compl_of_infinite t ht]
[GOAL]
α : Type u
β : Type v
inst✝ : Finite α
s : Set α
t : Set β
h1 : lift #α = lift #β
h2 : lift #↑s = lift #↑t
⊢ lift #↑sᶜ = lift #↑tᶜ
[PROOFSTEP]
cases nonempty_fintype α
[GOAL]
case intro
α : Type u
β : Type v
inst✝ : Finite α
s : Set α
t : Set β
h1 : lift #α = lift #β
h2 : lift #↑s = lift #↑t
val✝ : Fintype α
⊢ lift #↑sᶜ = lift #↑tᶜ
[PROOFSTEP]
rcases lift_mk_eq.{u, v, w}.1 h1 with ⟨e⟩
[GOAL]
case intro.intro
α : Type u
β : Type v
inst✝ : Finite α
s : Set α
t : Set β
h1 : lift #α = lift #β
h2 : lift #↑s = lift #↑t
val✝ : Fintype α
e : α ≃ β
⊢ lift #↑sᶜ = lift #↑tᶜ
[PROOFSTEP]
letI : Fintype β := Fintype.ofEquiv α e
[GOAL]
case intro.intro
α : Type u
β : Type v
inst✝ : Finite α
s : Set α
t : Set β
h1 : lift #α = lift #β
h2 : lift #↑s = lift #↑t
val✝ : Fintype α
e : α ≃ β
this : Fintype β := Fintype.ofEquiv α e
⊢ lift #↑sᶜ = lift #↑tᶜ
[PROOFSTEP]
replace h1 : Fintype.card α = Fintype.card β := (Fintype.ofEquiv_card _).symm
[GOAL]
case intro.intro
α : Type u
β : Type v
inst✝ : Finite α
s : Set α
t : Set β
h2 : lift #↑s = lift #↑t
val✝ : Fintype α
e : α ≃ β
this : Fintype β := Fintype.ofEquiv α e
h1 : Fintype.card α = Fintype.card β
⊢ lift #↑sᶜ = lift #↑tᶜ
[PROOFSTEP]
classical
lift s to Finset α using s.toFinite
lift t to Finset β using t.toFinite
simp only [Finset.coe_sort_coe, mk_fintype, Fintype.card_coe, lift_natCast, Nat.cast_inj] at h2
simp only [← Finset.coe_compl, Finset.coe_sort_coe, mk_coe_finset, Finset.card_compl, lift_natCast, Nat.cast_inj, h1,
h2]
[GOAL]
case intro.intro
α : Type u
β : Type v
inst✝ : Finite α
s : Set α
t : Set β
h2 : lift #↑s = lift #↑t
val✝ : Fintype α
e : α ≃ β
this : Fintype β := Fintype.ofEquiv α e
h1 : Fintype.card α = Fintype.card β
⊢ lift #↑sᶜ = lift #↑tᶜ
[PROOFSTEP]
lift s to Finset α using s.toFinite
[GOAL]
case intro.intro.intro
α : Type u
β : Type v
inst✝ : Finite α
t : Set β
val✝ : Fintype α
e : α ≃ β
this : Fintype β := Fintype.ofEquiv α e
h1 : Fintype.card α = Fintype.card β
s : Finset α
h2 : lift #↑↑s = lift #↑t
⊢ lift #↑(↑s)ᶜ = lift #↑tᶜ
[PROOFSTEP]
lift t to Finset β using t.toFinite
[GOAL]
case intro.intro.intro.intro
α : Type u
β : Type v
inst✝ : Finite α
val✝ : Fintype α
e : α ≃ β
this : Fintype β := Fintype.ofEquiv α e
h1 : Fintype.card α = Fintype.card β
s : Finset α
t : Finset β
h2 : lift #↑↑s = lift #↑↑t
⊢ lift #↑(↑s)ᶜ = lift #↑(↑t)ᶜ
[PROOFSTEP]
simp only [Finset.coe_sort_coe, mk_fintype, Fintype.card_coe, lift_natCast, Nat.cast_inj] at h2
[GOAL]
case intro.intro.intro.intro
α : Type u
β : Type v
inst✝ : Finite α
val✝ : Fintype α
e : α ≃ β
this : Fintype β := Fintype.ofEquiv α e
h1 : Fintype.card α = Fintype.card β
s : Finset α
t : Finset β
h2 : Finset.card s = Finset.card t
⊢ lift #↑(↑s)ᶜ = lift #↑(↑t)ᶜ
[PROOFSTEP]
simp only [← Finset.coe_compl, Finset.coe_sort_coe, mk_coe_finset, Finset.card_compl, lift_natCast, Nat.cast_inj, h1,
h2]
[GOAL]
α β : Type u
inst✝ : Finite α
s : Set α
t : Set β
h1 : #α = #β
h : #↑s = #↑t
⊢ #↑sᶜ = #↑tᶜ
[PROOFSTEP]
rw [← lift_inj.{u, max u v}]
[GOAL]
α β : Type u
inst✝ : Finite α
s : Set α
t : Set β
h1 : #α = #β
h : #↑s = #↑t
⊢ lift #↑sᶜ = lift #↑tᶜ
[PROOFSTEP]
apply mk_compl_eq_mk_compl_finite_lift.{u, u, max u v}
[GOAL]
case h1
α β : Type u
inst✝ : Finite α
s : Set α
t : Set β
h1 : #α = #β
h : #↑s = #↑t
⊢ lift #α = lift #β
[PROOFSTEP]
rwa [lift_inj]
[GOAL]
case h2
α β : Type u
inst✝ : Finite α
s : Set α
t : Set β
h1 : #α = #β
h : #↑s = #↑t
⊢ lift #↑s = lift #↑t
[PROOFSTEP]
rwa [lift_inj]
[GOAL]
α : Type u_1
β : Type u_2
s : Set α
f : ↑s ↪ β
h : Nonempty (↑sᶜ ≃ ↑(range ↑f)ᶜ)
⊢ ∃ g, ∀ (x : ↑s), ↑g ↑x = ↑f x
[PROOFSTEP]
intros
[GOAL]
α : Type u_1
β : Type u_2
s : Set α
f : ↑s ↪ β
h : Nonempty (↑sᶜ ≃ ↑(range ↑f)ᶜ)
⊢ ∃ g, ∀ (x : ↑s), ↑g ↑x = ↑f x
[PROOFSTEP]
have := h
[GOAL]
α : Type u_1
β : Type u_2
s : Set α
f : ↑s ↪ β
h this : Nonempty (↑sᶜ ≃ ↑(range ↑f)ᶜ)
⊢ ∃ g, ∀ (x : ↑s), ↑g ↑x = ↑f x
[PROOFSTEP]
cases' this with g
[GOAL]
case intro
α : Type u_1
β : Type u_2
s : Set α
f : ↑s ↪ β
h : Nonempty (↑sᶜ ≃ ↑(range ↑f)ᶜ)
g : ↑sᶜ ≃ ↑(range ↑f)ᶜ
⊢ ∃ g, ∀ (x : ↑s), ↑g ↑x = ↑f x
[PROOFSTEP]
let h : α ≃ β :=
(Set.sumCompl (s : Set α)).symm.trans ((sumCongr (Equiv.ofInjective f f.2) g).trans (Set.sumCompl (range f)))
[GOAL]
case intro
α : Type u_1
β : Type u_2
s : Set α
f : ↑s ↪ β
h✝ : Nonempty (↑sᶜ ≃ ↑(range ↑f)ᶜ)
g : ↑sᶜ ≃ ↑(range ↑f)ᶜ
h : α ≃ β :=
(Set.sumCompl s).symm.trans ((sumCongr (ofInjective ↑f (_ : Injective f.toFun)) g).trans (Set.sumCompl (range ↑f)))
⊢ ∃ g, ∀ (x : ↑s), ↑g ↑x = ↑f x
[PROOFSTEP]
refine' ⟨h, _⟩
[GOAL]
case intro
α : Type u_1
β : Type u_2
s : Set α
f : ↑s ↪ β
h✝ : Nonempty (↑sᶜ ≃ ↑(range ↑f)ᶜ)
g : ↑sᶜ ≃ ↑(range ↑f)ᶜ
h : α ≃ β :=
(Set.sumCompl s).symm.trans ((sumCongr (ofInjective ↑f (_ : Injective f.toFun)) g).trans (Set.sumCompl (range ↑f)))
⊢ ∀ (x : ↑s), ↑h ↑x = ↑f x
[PROOFSTEP]
rintro ⟨x, hx⟩
[GOAL]
case intro.mk
α : Type u_1
β : Type u_2
s : Set α
f : ↑s ↪ β
h✝ : Nonempty (↑sᶜ ≃ ↑(range ↑f)ᶜ)
g : ↑sᶜ ≃ ↑(range ↑f)ᶜ
h : α ≃ β :=
(Set.sumCompl s).symm.trans ((sumCongr (ofInjective ↑f (_ : Injective f.toFun)) g).trans (Set.sumCompl (range ↑f)))
x : α
hx : x ∈ s
⊢ ↑h ↑{ val := x, property := hx } = ↑f { val := x, property := hx }
[PROOFSTEP]
simp [Set.sumCompl_symm_apply_of_mem, hx]
[GOAL]
α : Type u
β : Type v
inst✝ : Finite α
s : Set α
f : ↑s ↪ β
h : Nonempty (α ≃ β)
⊢ ∃ g, ∀ (x : ↑s), ↑g ↑x = ↑f x
[PROOFSTEP]
apply extend_function.{v, u} f
[GOAL]
α : Type u
β : Type v
inst✝ : Finite α
s : Set α
f : ↑s ↪ β
h : Nonempty (α ≃ β)
⊢ Nonempty (↑sᶜ ≃ ↑(range ↑f)ᶜ)
[PROOFSTEP]
cases' id h with g
[GOAL]
case intro
α : Type u
β : Type v
inst✝ : Finite α
s : Set α
f : ↑s ↪ β
h : Nonempty (α ≃ β)
g : α ≃ β
⊢ Nonempty (↑sᶜ ≃ ↑(range ↑f)ᶜ)
[PROOFSTEP]
rw [← lift_mk_eq.{u, v, max u v}] at h
[GOAL]
case intro
α : Type u
β : Type v
inst✝ : Finite α
s : Set α
f : ↑s ↪ β
h : lift #α = lift #β
g : α ≃ β
⊢ Nonempty (↑sᶜ ≃ ↑(range ↑f)ᶜ)
[PROOFSTEP]
rw [← lift_mk_eq.{u, v, max u v}, mk_compl_eq_mk_compl_finite_lift.{u, v, max u v} h]
[GOAL]
case intro
α : Type u
β : Type v
inst✝ : Finite α
s : Set α
f : ↑s ↪ β
h : lift #α = lift #β
g : α ≃ β
⊢ lift #↑s = lift #↑(range ↑f)
[PROOFSTEP]
rw [mk_range_eq_lift.{u, v, max u v}]
[GOAL]
case intro
α : Type u
β : Type v
inst✝ : Finite α
s : Set α
f : ↑s ↪ β
h : lift #α = lift #β
g : α ≃ β
⊢ Injective ↑f
[PROOFSTEP]
exact f.2
[GOAL]
α : Type u_1
β : Type u_2
s : Set α
f : ↑s ↪ β
hs : #↑s < #α
h : Nonempty (α ≃ β)
⊢ ∃ g, ∀ (x : ↑s), ↑g ↑x = ↑f x
[PROOFSTEP]
cases fintypeOrInfinite α
[GOAL]
case inl
α : Type u_1
β : Type u_2
s : Set α
f : ↑s ↪ β
hs : #↑s < #α
h : Nonempty (α ≃ β)
val✝ : Fintype α
⊢ ∃ g, ∀ (x : ↑s), ↑g ↑x = ↑f x
[PROOFSTEP]
exact extend_function_finite f h
[GOAL]
case inr
α : Type u_1
β : Type u_2
s : Set α
f : ↑s ↪ β
hs : #↑s < #α
h : Nonempty (α ≃ β)
val✝ : Infinite α
⊢ ∃ g, ∀ (x : ↑s), ↑g ↑x = ↑f x
[PROOFSTEP]
apply extend_function f
[GOAL]
case inr
α : Type u_1
β : Type u_2
s : Set α
f : ↑s ↪ β
hs : #↑s < #α
h : Nonempty (α ≃ β)
val✝ : Infinite α
⊢ Nonempty (↑sᶜ ≃ ↑(range ↑f)ᶜ)
[PROOFSTEP]
cases' id h with g
[GOAL]
case inr.intro
α : Type u_1
β : Type u_2
s : Set α
f : ↑s ↪ β
hs : #↑s < #α
h : Nonempty (α ≃ β)
val✝ : Infinite α
g : α ≃ β
⊢ Nonempty (↑sᶜ ≃ ↑(range ↑f)ᶜ)
[PROOFSTEP]
haveI := Infinite.of_injective _ g.injective
[GOAL]
case inr.intro
α : Type u_1
β : Type u_2
s : Set α
f : ↑s ↪ β
hs : #↑s < #α
h : Nonempty (α ≃ β)
val✝ : Infinite α
g : α ≃ β
this : Infinite β
⊢ Nonempty (↑sᶜ ≃ ↑(range ↑f)ᶜ)
[PROOFSTEP]
rw [← lift_mk_eq'] at h ⊢
[GOAL]
case inr.intro
α : Type u_1
β : Type u_2
s : Set α
f : ↑s ↪ β
hs : #↑s < #α
h : lift #α = lift #β
val✝ : Infinite α
g : α ≃ β
this : Infinite β
⊢ lift #↑sᶜ = lift #↑(range ↑f)ᶜ
[PROOFSTEP]
rwa [mk_compl_of_infinite s hs, mk_compl_of_infinite]
[GOAL]
case inr.intro.h2
α : Type u_1
β : Type u_2
s : Set α
f : ↑s ↪ β
hs : #↑s < #α
h : lift #α = lift #β
val✝ : Infinite α
g : α ≃ β
this : Infinite β
⊢ #↑(range ↑f) < #β
[PROOFSTEP]
rwa [← lift_lt, mk_range_eq_of_injective f.injective, ← h, lift_lt]
|
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import copy
import traceback
import six
import sys
import multiprocessing as mp
if sys.version_info >= (3, 0):
import queue as Queue
else:
import Queue
import numpy as np
from paddle.io import DataLoader
from paddle.io import DistributedBatchSampler
from ppdet.core.workspace import register, serializable, create
from . import transform
from ppdet.utils.logger import setup_logger
logger = setup_logger('reader')
MAIN_PID = os.getpid()
class Compose(object):
def __init__(self, transforms, num_classes=80):
self.transforms = transforms
self.transforms_cls = []
for t in self.transforms:
for k, v in t.items():
op_cls = getattr(transform, k)
self.transforms_cls.append(op_cls(**v))
if hasattr(op_cls, 'num_classes'):
op_cls.num_classes = num_classes
def __call__(self, data):
for f in self.transforms_cls:
try:
data = f(data)
except Exception as e:
stack_info = traceback.format_exc()
logger.warn("fail to map op [{}] with error: {} and stack:\n{}".
format(f, e, str(stack_info)))
raise e
return data
class BatchCompose(Compose):
def __init__(self, transforms, num_classes=80):
super(BatchCompose, self).__init__(transforms, num_classes)
self.output_fields = mp.Manager().list([])
self.lock = mp.Lock()
def __call__(self, data):
for f in self.transforms_cls:
try:
data = f(data)
except Exception as e:
stack_info = traceback.format_exc()
logger.warn("fail to map op [{}] with error: {} and stack:\n{}".
format(f, e, str(stack_info)))
raise e
# accessing ListProxy in main process (no worker subprocess)
# may incur errors in some enviroments, ListProxy back to
# list if no worker process start, while this `__call__`
# will be called in main process
global MAIN_PID
if os.getpid() == MAIN_PID and \
isinstance(self.output_fields, mp.managers.ListProxy):
self.output_fields = []
# parse output fields by first sample
# **this shoule be fixed if paddle.io.DataLoader support**
# For paddle.io.DataLoader not support dict currently,
# we need to parse the key from the first sample,
# BatchCompose.__call__ will be called in each worker
# process, so lock is need here.
if len(self.output_fields) == 0:
self.lock.acquire()
if len(self.output_fields) == 0:
for k, v in data[0].items():
# FIXME(dkp): for more elegent coding
if k not in ['flipped', 'h', 'w']:
self.output_fields.append(k)
self.lock.release()
data = [[data[i][k] for k in self.output_fields]
for i in range(len(data))]
data = list(zip(*data))
batch_data = [np.stack(d, axis=0) for d in data]
return batch_data
class BaseDataLoader(object):
__share__ = ['num_classes']
def __init__(self,
inputs_def=None,
sample_transforms=[],
batch_transforms=[],
batch_size=1,
shuffle=False,
drop_last=False,
drop_empty=True,
num_classes=80,
**kwargs):
# sample transform
self._sample_transforms = Compose(
sample_transforms, num_classes=num_classes)
# batch transfrom
self._batch_transforms = BatchCompose(batch_transforms, num_classes)
self.batch_size = batch_size
self.shuffle = shuffle
self.drop_last = drop_last
self.kwargs = kwargs
def __call__(self,
dataset,
worker_num,
batch_sampler=None,
return_list=False,
use_prefetch=True):
self.dataset = dataset
self.dataset.parse_dataset()
# get data
self.dataset.set_transform(self._sample_transforms)
# set kwargs
self.dataset.set_kwargs(**self.kwargs)
# batch sampler
if batch_sampler is None:
self._batch_sampler = DistributedBatchSampler(
self.dataset,
batch_size=self.batch_size,
shuffle=self.shuffle,
drop_last=self.drop_last)
else:
self._batch_sampler = batch_sampler
self.dataloader = DataLoader(
dataset=self.dataset,
batch_sampler=self._batch_sampler,
collate_fn=self._batch_transforms,
num_workers=worker_num,
return_list=return_list,
use_buffer_reader=use_prefetch,
use_shared_memory=False)
self.loader = iter(self.dataloader)
return self
def __len__(self):
return len(self._batch_sampler)
def __iter__(self):
return self
def __next__(self):
# pack {filed_name: field_data} here
# looking forward to support dictionary
# data structure in paddle.io.DataLoader
try:
data = next(self.loader)
return {
k: v
for k, v in zip(self._batch_transforms.output_fields, data)
}
except StopIteration:
self.loader = iter(self.dataloader)
six.reraise(*sys.exc_info())
def next(self):
# python2 compatibility
return self.__next__()
@register
class TrainReader(BaseDataLoader):
def __init__(self,
inputs_def=None,
sample_transforms=[],
batch_transforms=[],
batch_size=1,
shuffle=True,
drop_last=True,
drop_empty=True,
num_classes=80,
**kwargs):
super(TrainReader, self).__init__(
inputs_def, sample_transforms, batch_transforms, batch_size,
shuffle, drop_last, drop_empty, num_classes, **kwargs)
@register
class EvalReader(BaseDataLoader):
def __init__(self,
inputs_def=None,
sample_transforms=[],
batch_transforms=[],
batch_size=1,
shuffle=False,
drop_last=True,
drop_empty=True,
num_classes=80,
**kwargs):
super(EvalReader, self).__init__(
inputs_def, sample_transforms, batch_transforms, batch_size,
shuffle, drop_last, drop_empty, num_classes, **kwargs)
@register
class TestReader(BaseDataLoader):
def __init__(self,
inputs_def=None,
sample_transforms=[],
batch_transforms=[],
batch_size=1,
shuffle=False,
drop_last=False,
drop_empty=True,
num_classes=80,
**kwargs):
super(TestReader, self).__init__(
inputs_def, sample_transforms, batch_transforms, batch_size,
shuffle, drop_last, drop_empty, num_classes, **kwargs)
|
"""
initial_conditions(model)
Get initial conditions at all degrees of freedom.
"""
initial_conditions(model) =
mapreduce((ρ, p) -> fill(ρ, size(p, 2)), vcat, model.ρ, model.mesh.points)
|
classdef ParamDCLFDCBF < handle
properties
alpha
gamma
P % weight for Lyapunov function
uWeight
sWeight
end
methods
function self = ParamDCLFDCBF(alpha, gamma, P, u_weight, s_weight)
self.alpha = alpha;
self.gamma = gamma;
self.P = P;
self.uWeight = u_weight;
self.sWeight = s_weight;
end
end
end |
Achill Island lies off the coast of County Mayo and is Ireland 's largest island . It is a popular tourist destination for surfing and contains 5 Blue Flag beaches and <unk> one of the worlds highest sea cliffs . Stately homes , built during the 17th , 18th and 19th centuries in Palladian , Neoclassical and neo @-@ Gothic styles , such as , Castle Ward , Castletown House , Bantry House , <unk> Castle are also of interest to tourists . Some have been converted into hotels , such as Ashford Castle , Castle Leslie and <unk> Castle .
|
module Printf
data Format = Number Format
| Str Format
| Lit Char Format -- do we really need String literals?
| Chr Format -- from exercise 2
| Dbl Format
| End
total PrintfType : Format -> Type
PrintfType (Number fmt) = Int -> PrintfType fmt -- NOTE: it would be nice if
-- we could specify
-- Num a => a -> PrintfType fmt
PrintfType (Str fmt) = String -> PrintfType fmt
PrintfType (Lit lit fmt) = PrintfType fmt
PrintfType End = String -- teeechnically it should be IO ().
-- sprintf would have type ... -> String
PrintfType (Chr fmt) = Char -> PrintfType fmt
PrintfType (Dbl fmt) = Double -> PrintfType fmt
printfFmt : (fmt : Format) -> (acc : String) -> PrintfType fmt
printfFmt (Number fmt) acc = \i => printfFmt fmt (acc ++ show i)
printfFmt (Str fmt) acc = \s => printfFmt fmt (acc ++ s)
printfFmt (Lit lit fmt) acc = printfFmt fmt (acc ++ cast lit)
printfFmt End acc = acc
printfFmt (Chr fmt) acc = \c => printfFmt fmt (acc ++ cast c)
printfFmt (Dbl fmt) acc = \d => printfFmt fmt (acc ++ show d)
toFormat : List Char -> Format
toFormat [] = End
toFormat ('%' :: 'd' :: cs) = Number (toFormat cs)
toFormat ('%' :: 's' :: cs) = Str (toFormat cs)
toFormat ('%' :: 'c' :: cs) = Chr (toFormat cs)
toFormat ('%' :: 'f' :: cs) = Dbl (toFormat cs)
toFormat (c :: cs) = Lit c (toFormat cs) -- sorry, I'm lazy
printf : (fmt : String) -> PrintfType (toFormat (unpack fmt))
printf fmt = printfFmt _ ""
printfExample : String
printfExample = printf "%d %d %%%%%%s" 10 2 "foo"
-- NOTEs:
-- Using Lit Char instead of Lit String made things easier when building
-- literals. I'm curious about the efficiency though...
-- There's still a bit of dependency between format (PrintfType) and
-- toFormat. For example there is no guarantee that toFormat
-- will produce a case for all possible Formats.
-- I wonder if there are languages where we can specify that a function
-- must be surjective.
-- Let's go back to Chapter6.idr
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.